Compare commits
2 Commits
f3150f06fa
...
v0.3.7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce4a42eec2 | ||
|
|
ac951c31b1 |
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "ai-translate-client",
|
"name": "ai-translate-client",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.3.6",
|
"version": "0.3.7",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
2
src-tauri/Cargo.lock
generated
2
src-tauri/Cargo.lock
generated
@@ -19,7 +19,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ai-translate-client"
|
name = "ai-translate-client"
|
||||||
version = "0.3.6"
|
version = "0.3.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"reqwest 0.12.28",
|
"reqwest 0.12.28",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "ai-translate-client"
|
name = "ai-translate-client"
|
||||||
version = "0.3.6"
|
version = "0.3.7"
|
||||||
description = "A client using AI models to translate"
|
description = "A client using AI models to translate"
|
||||||
authors = ["Julian"]
|
authors = ["Julian"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ struct OpenAIResponse {
|
|||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct Choice {
|
struct Choice {
|
||||||
message: Option<Message>,
|
// message: Option<Message>,
|
||||||
delta: Option<Delta>,
|
delta: Option<Delta>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,16 +56,17 @@ async fn translate(
|
|||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
if !payload.stream {
|
if !payload.stream {
|
||||||
let data = res.json::<OpenAIResponse>().await.map_err(|e| e.to_string())?;
|
let text = res.text().await.map_err(|e| e.to_string())?;
|
||||||
return Ok(data.choices.get(0).and_then(|c| c.message.as_ref()).map(|m| m.content.clone()).unwrap_or_default());
|
return Ok(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut stream = res.bytes_stream();
|
let mut stream = res.bytes_stream();
|
||||||
let mut full_response = String::new();
|
let mut raw_stream_log = String::new();
|
||||||
|
|
||||||
while let Some(item) = stream.next().await {
|
while let Some(item) = stream.next().await {
|
||||||
let chunk = item.map_err(|e| e.to_string())?;
|
let chunk = item.map_err(|e| e.to_string())?;
|
||||||
let text = String::from_utf8_lossy(&chunk);
|
let text = String::from_utf8_lossy(&chunk);
|
||||||
|
raw_stream_log.push_str(&text);
|
||||||
|
|
||||||
for line in text.lines() {
|
for line in text.lines() {
|
||||||
let line = line.trim();
|
let line = line.trim();
|
||||||
@@ -77,7 +78,6 @@ async fn translate(
|
|||||||
if let Some(choice) = json.choices.get(0) {
|
if let Some(choice) = json.choices.get(0) {
|
||||||
if let Some(delta) = &choice.delta {
|
if let Some(delta) = &choice.delta {
|
||||||
if let Some(content) = &delta.content {
|
if let Some(content) = &delta.content {
|
||||||
full_response.push_str(content);
|
|
||||||
app.emit("translation-chunk", content).map_err(|e| e.to_string())?;
|
app.emit("translation-chunk", content).map_err(|e| e.to_string())?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -87,7 +87,7 @@ async fn translate(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(full_response)
|
Ok(raw_stream_log)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "ai-translate-client",
|
"productName": "ai-translate-client",
|
||||||
"version": "0.3.6",
|
"version": "0.3.7",
|
||||||
"identifier": "top.volan.ai-translate-client",
|
"identifier": "top.volan.ai-translate-client",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "pnpm dev",
|
"beforeDevCommand": "pnpm dev",
|
||||||
|
|||||||
@@ -19,9 +19,20 @@ watch(() => settings.logs, (newVal) => {
|
|||||||
}
|
}
|
||||||
}, { immediate: true });
|
}, { immediate: true });
|
||||||
|
|
||||||
|
const decodeUnicode = (str: string) => {
|
||||||
|
if (!str) return str;
|
||||||
|
try {
|
||||||
|
return str.replace(/\\u([0-9a-fA-F]{4})/g, (_match, grp) => {
|
||||||
|
return String.fromCharCode(parseInt(grp, 16));
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const getLogSummary = (log: any) => {
|
const getLogSummary = (log: any) => {
|
||||||
if (log.type === 'error') return String(log.content);
|
if (log.type === 'error') return String(log.content);
|
||||||
if (typeof log.content === 'string') return log.content;
|
if (typeof log.content === 'string') return decodeUnicode(log.content);
|
||||||
if (log.content && log.content.model) return `Model: ${log.content.model}`;
|
if (log.content && log.content.model) return `Model: ${log.content.model}`;
|
||||||
if (log.content && log.content.score) return `Score: ${log.content.score}`;
|
if (log.content && log.content.score) return `Score: ${log.content.score}`;
|
||||||
return 'JSON Data';
|
return 'JSON Data';
|
||||||
@@ -92,8 +103,18 @@ const getLogSummary = (log: any) => {
|
|||||||
)"
|
)"
|
||||||
>{{ selectedLogItem.type === 'request' ? 'Request' : selectedLogItem.type === 'response' ? 'Response' : 'Error' }}</span>
|
>{{ selectedLogItem.type === 'request' ? 'Request' : selectedLogItem.type === 'response' ? 'Response' : 'Error' }}</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="flex gap-2">
|
||||||
<button
|
<button
|
||||||
@click="copyWithFeedback(typeof selectedLogItem.content === 'object' ? JSON.stringify(selectedLogItem.content, null, 2) : String(selectedLogItem.content), `log-${selectedLogItem.id}`)"
|
v-if="selectedLogItem.curl"
|
||||||
|
@click="copyWithFeedback(decodeUnicode(selectedLogItem.curl), `curl-${selectedLogItem.id}`)"
|
||||||
|
class="flex items-center gap-2 px-3 py-2 text-xs font-medium text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/30 rounded-lg transition-colors border border-blue-100 dark:border-blue-900/50"
|
||||||
|
>
|
||||||
|
<Check v-if="activeCopyId === `curl-${selectedLogItem.id}`" class="w-4 h-4" />
|
||||||
|
<Copy v-else class="w-4 h-4" />
|
||||||
|
复制 cURL
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
@click="copyWithFeedback(decodeUnicode(typeof selectedLogItem.content === 'object' ? JSON.stringify(selectedLogItem.content, null, 2) : String(selectedLogItem.content)), `log-${selectedLogItem.id}`)"
|
||||||
class="flex items-center gap-2 px-3 py-2 text-xs font-medium text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800 rounded-lg transition-colors border border-slate-200 dark:border-slate-700"
|
class="flex items-center gap-2 px-3 py-2 text-xs font-medium text-slate-600 hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800 rounded-lg transition-colors border border-slate-200 dark:border-slate-700"
|
||||||
>
|
>
|
||||||
<Check v-if="activeCopyId === `log-${selectedLogItem.id}`" class="w-4 h-4 text-green-600" />
|
<Check v-if="activeCopyId === `log-${selectedLogItem.id}`" class="w-4 h-4 text-green-600" />
|
||||||
@@ -101,9 +122,18 @@ const getLogSummary = (log: any) => {
|
|||||||
复制内容
|
复制内容
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="flex-1 overflow-auto p-6 bg-slate-50/30 dark:bg-slate-900/50 custom-scrollbar">
|
<div class="flex-1 overflow-auto p-6 bg-slate-50/30 dark:bg-slate-900/50 custom-scrollbar space-y-6">
|
||||||
<pre class="font-mono text-xs leading-relaxed text-slate-700 dark:text-slate-300 whitespace-pre-wrap break-all">{{ typeof selectedLogItem.content === 'object' ? JSON.stringify(selectedLogItem.content, null, 2) : selectedLogItem.content }}</pre>
|
<div v-if="selectedLogItem.curl" class="space-y-2">
|
||||||
|
<h3 class="text-[10px] font-bold text-slate-400 uppercase tracking-widest px-1">cURL 请求命令</h3>
|
||||||
|
<pre class="font-mono text-[11px] leading-relaxed p-4 bg-slate-950 text-blue-400 rounded-xl border border-slate-800 whitespace-pre-wrap break-all shadow-inner">{{ decodeUnicode(selectedLogItem.curl) }}</pre>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-2">
|
||||||
|
<h3 class="text-[10px] font-bold text-slate-400 uppercase tracking-widest px-1">{{ selectedLogItem.type === 'request' ? 'Payload (JSON)' : 'Response Data' }}</h3>
|
||||||
|
<pre class="font-mono text-[11px] leading-relaxed p-4 bg-slate-950 text-slate-300 rounded-xl border border-slate-800 whitespace-pre-wrap break-all shadow-inner">{{ decodeUnicode(typeof selectedLogItem.content === 'object' ? JSON.stringify(selectedLogItem.content, null, 2) : selectedLogItem.content) }}</pre>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
<div v-else class="flex-1 flex flex-col items-center justify-center text-slate-300 dark:text-slate-800 p-10 text-center space-y-4">
|
<div v-else class="flex-1 flex flex-col items-center justify-center text-slate-300 dark:text-slate-800 p-10 text-center space-y-4">
|
||||||
|
|||||||
@@ -105,6 +105,15 @@ const clearSource = () => {
|
|||||||
evaluationResult.value = null;
|
evaluationResult.value = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const generateCurl = (apiBaseUrl: string, apiKey: string, body: any) => {
|
||||||
|
const fullUrl = `${apiBaseUrl.replace(/\/$/, '')}/chat/completions`;
|
||||||
|
const maskedKey = apiKey ? `${apiKey.slice(0, 6)}...${apiKey.slice(-4)}` : 'YOUR_API_KEY';
|
||||||
|
return `curl "${fullUrl}" \\
|
||||||
|
-H "Content-Type: application/json" \\
|
||||||
|
-H "Authorization: Bearer ${maskedKey}" \\
|
||||||
|
-d '${JSON.stringify(body, null, 2)}'`;
|
||||||
|
};
|
||||||
|
|
||||||
const evaluateTranslation = async () => {
|
const evaluateTranslation = async () => {
|
||||||
if (!targetText.value) return;
|
if (!targetText.value) return;
|
||||||
isEvaluating.value = true;
|
isEvaluating.value = true;
|
||||||
@@ -140,14 +149,18 @@ const evaluateTranslation = async () => {
|
|||||||
stream: false
|
stream: false
|
||||||
};
|
};
|
||||||
|
|
||||||
settings.addLog('request', { type: 'evaluation', ...requestBody });
|
settings.addLog('request', { type: 'evaluation', ...requestBody }, generateCurl(apiBaseUrl, apiKey, requestBody));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody });
|
const response = await invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody });
|
||||||
try {
|
try {
|
||||||
const jsonStr = response.replace(/```json\s?|\s?```/g, '').trim();
|
// 解析 API 的原始响应 JSON
|
||||||
|
const fullResponseJson = JSON.parse(response);
|
||||||
|
settings.addLog('response', fullResponseJson);
|
||||||
|
|
||||||
|
const content = fullResponseJson.choices?.[0]?.message?.content || response;
|
||||||
|
const jsonStr = content.replace(/```json\s?|\s?```/g, '').trim();
|
||||||
evaluationResult.value = JSON.parse(jsonStr);
|
evaluationResult.value = JSON.parse(jsonStr);
|
||||||
settings.addLog('response', { type: 'evaluation', content: evaluationResult.value });
|
|
||||||
} catch (parseErr) {
|
} catch (parseErr) {
|
||||||
console.error('Failed to parse evaluation result:', response);
|
console.error('Failed to parse evaluation result:', response);
|
||||||
settings.addLog('error', `Evaluation parsing error: ${response}`);
|
settings.addLog('error', `Evaluation parsing error: ${response}`);
|
||||||
@@ -197,17 +210,23 @@ const refineTranslation = async () => {
|
|||||||
stream: settings.enableStreaming
|
stream: settings.enableStreaming
|
||||||
};
|
};
|
||||||
|
|
||||||
settings.addLog('request', { type: 'refinement', ...requestBody });
|
settings.addLog('request', { type: 'refinement', ...requestBody }, generateCurl(apiBaseUrl, apiKey, requestBody));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody });
|
const response = await invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody });
|
||||||
if (!settings.enableStreaming) targetText.value = response;
|
|
||||||
|
if (settings.enableStreaming) {
|
||||||
|
settings.addLog('response', targetText.value);
|
||||||
|
} else {
|
||||||
|
const fullResponseJson = JSON.parse(response);
|
||||||
|
settings.addLog('response', fullResponseJson);
|
||||||
|
targetText.value = fullResponseJson.choices?.[0]?.message?.content || response;
|
||||||
|
}
|
||||||
|
|
||||||
if (evaluationResult.value?.suggestions) {
|
if (evaluationResult.value?.suggestions) {
|
||||||
appliedSuggestionIds.value.push(...selectedSuggestionIds.value);
|
appliedSuggestionIds.value.push(...selectedSuggestionIds.value);
|
||||||
selectedSuggestionIds.value = [];
|
selectedSuggestionIds.value = [];
|
||||||
}
|
}
|
||||||
settings.addLog('response', 'Refinement completed');
|
|
||||||
|
|
||||||
if (currentHistoryId.value) {
|
if (currentHistoryId.value) {
|
||||||
settings.updateHistoryItem(currentHistoryId.value, {
|
settings.updateHistoryItem(currentHistoryId.value, {
|
||||||
@@ -249,18 +268,27 @@ const translate = async () => {
|
|||||||
stream: settings.enableStreaming
|
stream: settings.enableStreaming
|
||||||
};
|
};
|
||||||
|
|
||||||
settings.addLog('request', requestBody);
|
settings.addLog('request', requestBody, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await invoke<string>('translate', { apiAddress: settings.apiBaseUrl, apiKey: settings.apiKey, payload: requestBody });
|
const response = await invoke<string>('translate', { apiAddress: settings.apiBaseUrl, apiKey: settings.apiKey, payload: requestBody });
|
||||||
if (!settings.enableStreaming) targetText.value = response;
|
|
||||||
settings.addLog('response', 'Translation completed');
|
let finalTargetText = '';
|
||||||
|
if (settings.enableStreaming) {
|
||||||
|
finalTargetText = targetText.value;
|
||||||
|
settings.addLog('response', response);
|
||||||
|
} else {
|
||||||
|
const fullResponseJson = JSON.parse(response);
|
||||||
|
settings.addLog('response', fullResponseJson);
|
||||||
|
finalTargetText = fullResponseJson.choices?.[0]?.message?.content || response;
|
||||||
|
targetText.value = finalTargetText;
|
||||||
|
}
|
||||||
|
|
||||||
currentHistoryId.value = settings.addHistory({
|
currentHistoryId.value = settings.addHistory({
|
||||||
sourceLang: { ...sourceLang.value },
|
sourceLang: { ...sourceLang.value },
|
||||||
targetLang: { ...targetLang.value },
|
targetLang: { ...targetLang.value },
|
||||||
sourceText: sourceText.value,
|
sourceText: sourceText.value,
|
||||||
targetText: settings.enableStreaming ? targetText.value : response,
|
targetText: finalTargetText,
|
||||||
context: context.value,
|
context: context.value,
|
||||||
speakerIdentity: settings.speakerIdentity,
|
speakerIdentity: settings.speakerIdentity,
|
||||||
toneRegister: settings.toneRegister,
|
toneRegister: settings.toneRegister,
|
||||||
|
|||||||
@@ -159,10 +159,10 @@ export const useSettingsStore = defineStore('settings', () => {
|
|||||||
set: (val) => { toneRegisterMap.value[sourceLang.value.code] = val; }
|
set: (val) => { toneRegisterMap.value[sourceLang.value.code] = val; }
|
||||||
});
|
});
|
||||||
|
|
||||||
const logs = ref<{ id: string; timestamp: string; type: 'request' | 'response' | 'error'; content: any }[]>([]);
|
const logs = ref<{ id: string; timestamp: string; type: 'request' | 'response' | 'error'; content: any; curl?: string }[]>([]);
|
||||||
const history = useLocalStorage<HistoryItem[]>('translation-history-v1', []);
|
const history = useLocalStorage<HistoryItem[]>('translation-history-v1', []);
|
||||||
|
|
||||||
const addLog = (type: 'request' | 'response' | 'error', content: any) => {
|
const addLog = (type: 'request' | 'response' | 'error', content: any, curl?: string) => {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
|
const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
|
||||||
|
|
||||||
@@ -170,7 +170,8 @@ export const useSettingsStore = defineStore('settings', () => {
|
|||||||
id: crypto.randomUUID(),
|
id: crypto.randomUUID(),
|
||||||
timestamp,
|
timestamp,
|
||||||
type,
|
type,
|
||||||
content
|
content,
|
||||||
|
curl
|
||||||
});
|
});
|
||||||
if (logs.value.length > 50) logs.value.pop(); // 稍微增加日志保留数量
|
if (logs.value.length > 50) logs.value.pop(); // 稍微增加日志保留数量
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user