Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce4a42eec2 | ||
|
|
ac951c31b1 | ||
|
|
f3150f06fa | ||
|
|
7de7877c64 | ||
|
|
15626ba9e1 | ||
|
|
c719b50285 |
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ai-translate-client",
|
||||
"private": true,
|
||||
"version": "0.3.5",
|
||||
"version": "0.3.7",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
2
src-tauri/Cargo.lock
generated
2
src-tauri/Cargo.lock
generated
@@ -19,7 +19,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ai-translate-client"
|
||||
version = "0.3.5"
|
||||
version = "0.3.7"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"reqwest 0.12.28",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ai-translate-client"
|
||||
version = "0.3.5"
|
||||
version = "0.3.7"
|
||||
description = "A client using AI models to translate"
|
||||
authors = ["Julian"]
|
||||
edition = "2021"
|
||||
|
||||
@@ -23,7 +23,7 @@ struct OpenAIResponse {
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Choice {
|
||||
message: Option<Message>,
|
||||
// message: Option<Message>,
|
||||
delta: Option<Delta>,
|
||||
}
|
||||
|
||||
@@ -56,16 +56,17 @@ async fn translate(
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
if !payload.stream {
|
||||
let data = res.json::<OpenAIResponse>().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());
|
||||
let text = res.text().await.map_err(|e| e.to_string())?;
|
||||
return Ok(text);
|
||||
}
|
||||
|
||||
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 {
|
||||
let chunk = item.map_err(|e| e.to_string())?;
|
||||
let text = String::from_utf8_lossy(&chunk);
|
||||
raw_stream_log.push_str(&text);
|
||||
|
||||
for line in text.lines() {
|
||||
let line = line.trim();
|
||||
@@ -77,7 +78,6 @@ async fn translate(
|
||||
if let Some(choice) = json.choices.get(0) {
|
||||
if let Some(delta) = &choice.delta {
|
||||
if let Some(content) = &delta.content {
|
||||
full_response.push_str(content);
|
||||
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)]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "ai-translate-client",
|
||||
"version": "0.3.5",
|
||||
"version": "0.3.7",
|
||||
"identifier": "top.volan.ai-translate-client",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
@@ -19,9 +19,20 @@ watch(() => settings.logs, (newVal) => {
|
||||
}
|
||||
}, { 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) => {
|
||||
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.score) return `Score: ${log.content.score}`;
|
||||
return 'JSON Data';
|
||||
@@ -92,18 +103,37 @@ const getLogSummary = (log: any) => {
|
||||
)"
|
||||
>{{ selectedLogItem.type === 'request' ? 'Request' : selectedLogItem.type === 'response' ? 'Response' : 'Error' }}</span>
|
||||
</div>
|
||||
<button
|
||||
@click="copyWithFeedback(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"
|
||||
>
|
||||
<Check v-if="activeCopyId === `log-${selectedLogItem.id}`" class="w-4 h-4 text-green-600" />
|
||||
<Copy v-else class="w-4 h-4" />
|
||||
复制内容
|
||||
</button>
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
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"
|
||||
>
|
||||
<Check v-if="activeCopyId === `log-${selectedLogItem.id}`" class="w-4 h-4 text-green-600" />
|
||||
<Copy v-else class="w-4 h-4" />
|
||||
复制内容
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-auto p-6 bg-slate-50/30 dark:bg-slate-900/50 custom-scrollbar">
|
||||
<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 class="flex-1 overflow-auto p-6 bg-slate-50/30 dark:bg-slate-900/50 custom-scrollbar space-y-6">
|
||||
<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>
|
||||
</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">
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, onUnmounted } from 'vue';
|
||||
import { Play, Settings, Type, Save, Check, Plus, Trash2, ChevronDown } from 'lucide-vue-next';
|
||||
import { Play, Settings, Type, Save, Check, Plus, Trash2, ChevronDown, Eye, EyeOff, Pencil } from 'lucide-vue-next';
|
||||
import { useSettingsStore, DEFAULT_TEMPLATE, DEFAULT_EVALUATION_TEMPLATE, DEFAULT_REFINEMENT_TEMPLATE, type ApiProfile } from '../stores/settings';
|
||||
import { cn } from '../lib/utils';
|
||||
|
||||
const settings = useSettingsStore();
|
||||
const settingsCategory = ref<'api' | 'general' | 'prompts'>('api');
|
||||
const showApiKey = ref(false);
|
||||
|
||||
const newProfileName = ref('');
|
||||
const isSavingProfile = ref(false);
|
||||
@@ -34,6 +35,34 @@ const deleteProfile = (id: string) => {
|
||||
settings.profiles = settings.profiles.filter(p => p.id !== id);
|
||||
};
|
||||
|
||||
const editingProfileId = ref<string | null>(null);
|
||||
const editProfileForm = ref<ApiProfile | null>(null);
|
||||
const showEditApiKey = ref(false);
|
||||
|
||||
const startEditProfile = (profile: ApiProfile) => {
|
||||
editingProfileId.value = profile.id;
|
||||
editProfileForm.value = { ...profile };
|
||||
showEditApiKey.value = false;
|
||||
};
|
||||
|
||||
const cancelEditProfile = () => {
|
||||
editingProfileId.value = null;
|
||||
editProfileForm.value = null;
|
||||
};
|
||||
|
||||
const saveEditProfile = () => {
|
||||
if (!editProfileForm.value || !editingProfileId.value) return;
|
||||
if (!editProfileForm.value.name.trim()) return;
|
||||
|
||||
const index = settings.profiles.findIndex(p => p.id === editingProfileId.value);
|
||||
if (index !== -1) {
|
||||
settings.profiles[index] = { ...editProfileForm.value };
|
||||
}
|
||||
|
||||
editingProfileId.value = null;
|
||||
editProfileForm.value = null;
|
||||
};
|
||||
|
||||
const evaluationProfileDropdownOpen = ref(false);
|
||||
const toggleDropdown = (type: string) => {
|
||||
if (type === 'evaluationProfile') evaluationProfileDropdownOpen.value = !evaluationProfileDropdownOpen.value;
|
||||
@@ -161,12 +190,22 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-medium text-slate-700 dark:text-slate-300">API Key</label>
|
||||
<input
|
||||
v-model="settings.apiKey"
|
||||
type="password"
|
||||
class="w-full px-4 py-2.5 border dark:border-slate-700 rounded-xl bg-slate-50/50 dark:bg-slate-950 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-sm text-slate-900 dark:text-slate-100"
|
||||
placeholder="sk-..."
|
||||
/>
|
||||
<div class="relative">
|
||||
<input
|
||||
v-model="settings.apiKey"
|
||||
:type="showApiKey ? 'text' : 'password'"
|
||||
class="w-full pl-4 pr-12 py-2.5 border dark:border-slate-700 rounded-xl bg-slate-50/50 dark:bg-slate-950 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-sm text-slate-900 dark:text-slate-100"
|
||||
placeholder="sk-..."
|
||||
/>
|
||||
<button
|
||||
@click="showApiKey = !showApiKey"
|
||||
type="button"
|
||||
class="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors focus:outline-none"
|
||||
>
|
||||
<Eye v-if="showApiKey" class="w-5 h-5" />
|
||||
<EyeOff v-else class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm font-medium text-slate-700 dark:text-slate-300">Model Name</label>
|
||||
@@ -189,34 +228,72 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
<div
|
||||
v-for="profile in settings.profiles"
|
||||
:key="profile.id"
|
||||
class="p-3 flex items-center justify-between group hover:bg-white dark:hover:bg-slate-800 transition-colors rounded-lg border border-transparent hover:border-slate-200 dark:hover:border-slate-700"
|
||||
>
|
||||
<div class="flex flex-col gap-1 min-w-0">
|
||||
<span class="text-sm font-bold text-slate-700 dark:text-slate-200 truncate">{{ profile.name }}</span>
|
||||
<div class="flex items-center gap-2 text-[10px] text-slate-500 dark:text-slate-400 font-mono bg-slate-100 dark:bg-slate-950 px-2 py-0.5 rounded w-fit">
|
||||
<span class="truncate max-w-32">{{ profile.modelName }}</span>
|
||||
<span class="opacity-30">•</span>
|
||||
<span class="truncate max-w-48">{{ profile.apiBaseUrl }}</span>
|
||||
<!-- 编辑模式 -->
|
||||
<div v-if="editingProfileId === profile.id && editProfileForm" class="p-4 bg-white dark:bg-slate-800/80 rounded-xl border border-blue-200 dark:border-blue-800/50 shadow-sm space-y-3 my-1">
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-[11px] font-medium text-slate-500 uppercase tracking-wider">预设名称</label>
|
||||
<input v-model="editProfileForm.name" type="text" class="w-full px-3 py-2 border dark:border-slate-700 rounded-lg bg-slate-50/50 dark:bg-slate-950 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all text-sm text-slate-900 dark:text-slate-100" placeholder="预设名称" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-[11px] font-medium text-slate-500 uppercase tracking-wider">API Base URL</label>
|
||||
<input v-model="editProfileForm.apiBaseUrl" type="text" class="w-full px-3 py-2 border dark:border-slate-700 rounded-lg bg-slate-50/50 dark:bg-slate-950 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-sm text-slate-900 dark:text-slate-100" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-[11px] font-medium text-slate-500 uppercase tracking-wider">API Key</label>
|
||||
<div class="relative">
|
||||
<input v-model="editProfileForm.apiKey" :type="showEditApiKey ? 'text' : 'password'" class="w-full pl-3 pr-10 py-2 border dark:border-slate-700 rounded-lg bg-slate-50/50 dark:bg-slate-950 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-sm text-slate-900 dark:text-slate-100" />
|
||||
<button @click="showEditApiKey = !showEditApiKey" type="button" class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 dark:hover:text-slate-300 transition-colors focus:outline-none p-1">
|
||||
<Eye v-if="showEditApiKey" class="w-4 h-4" />
|
||||
<EyeOff v-else class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-[11px] font-medium text-slate-500 uppercase tracking-wider">Model Name</label>
|
||||
<input v-model="editProfileForm.modelName" type="text" class="w-full px-3 py-2 border dark:border-slate-700 rounded-lg bg-slate-50/50 dark:bg-slate-950 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all font-mono text-sm text-slate-900 dark:text-slate-100" />
|
||||
</div>
|
||||
<div class="flex items-center justify-end gap-2 pt-2">
|
||||
<button @click="cancelEditProfile" class="px-4 py-2 text-xs font-medium text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200 bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 rounded-lg transition-colors">取消</button>
|
||||
<button @click="saveEditProfile" :disabled="!editProfileForm.name.trim()" class="px-4 py-2 text-xs font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg transition-colors">保存修改</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<button
|
||||
@click="applyProfile(profile)"
|
||||
class="flex items-center gap-1.5 px-3 py-1.5 bg-blue-50 text-blue-600 hover:bg-blue-100 dark:bg-blue-900/30 dark:text-blue-400 dark:hover:bg-blue-900/50 rounded-lg transition-colors text-xs font-medium shadow-sm"
|
||||
>
|
||||
<Play class="w-3 h-3 fill-current" />
|
||||
应用
|
||||
</button>
|
||||
<button
|
||||
@click="deleteProfile(profile.id)"
|
||||
class="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"
|
||||
title="删除"
|
||||
>
|
||||
<Trash2 class="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<!-- 正常显示模式 -->
|
||||
<div v-else class="p-3 flex items-center justify-between group hover:bg-white dark:hover:bg-slate-800 transition-colors rounded-lg border border-transparent hover:border-slate-200 dark:hover:border-slate-700">
|
||||
<div class="flex flex-col gap-1 min-w-0">
|
||||
<span class="text-sm font-bold text-slate-700 dark:text-slate-200 truncate">{{ profile.name }}</span>
|
||||
<div class="flex items-center gap-2 text-[10px] text-slate-500 dark:text-slate-400 font-mono bg-slate-100 dark:bg-slate-950 px-2 py-0.5 rounded w-fit">
|
||||
<span class="truncate max-w-32">{{ profile.modelName }}</span>
|
||||
<span class="opacity-30">•</span>
|
||||
<span class="truncate max-w-48">{{ profile.apiBaseUrl }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<button
|
||||
@click="applyProfile(profile)"
|
||||
class="flex items-center gap-1.5 px-3 py-1.5 bg-blue-50 text-blue-600 hover:bg-blue-100 dark:bg-blue-900/30 dark:text-blue-400 dark:hover:bg-blue-900/50 rounded-lg transition-colors text-xs font-medium shadow-sm"
|
||||
>
|
||||
<Play class="w-3 h-3 fill-current" />
|
||||
应用
|
||||
</button>
|
||||
<button
|
||||
@click="startEditProfile(profile)"
|
||||
class="p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded-lg transition-colors"
|
||||
title="编辑"
|
||||
>
|
||||
<Pencil class="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
@click="deleteProfile(profile.id)"
|
||||
class="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/30 rounded-lg transition-colors"
|
||||
title="删除"
|
||||
>
|
||||
<Trash2 class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div> </div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -361,7 +438,6 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
spellcheck="false"
|
||||
></textarea>
|
||||
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
||||
<p class="text-[10px] font-semibold text-slate-400 uppercase mb-2">可用变量 (Variables)</p>
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<span v-for="tag in ['{SOURCE_CODE}', '{TARGET_CODE}', '{SOURCE_LANG}', '{TARGET_LANG}', '{SPEAKER_IDENTITY}', '{TONE_REGISTER}']" :key="tag" class="px-2 py-0.5 bg-white dark:bg-slate-800 text-[10px] font-mono rounded-md border dark:border-slate-700 text-slate-500 shadow-sm">{{ tag }}</span>
|
||||
</div>
|
||||
@@ -373,7 +449,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
<div class="px-5 py-3 border-b dark:border-slate-800 bg-slate-50 dark:bg-slate-950 flex items-center justify-between">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="w-2 h-2 rounded-full bg-amber-500"></div>
|
||||
<h3 class="text-sm font-bold text-slate-700 dark:text-slate-200">质量审计指令 (JSON 输出)</h3>
|
||||
<h3 class="text-sm font-bold text-slate-700 dark:text-slate-200">质量审计指令</h3>
|
||||
</div>
|
||||
<button @click="settings.evaluationPromptTemplate = DEFAULT_EVALUATION_TEMPLATE" class="text-xs text-blue-600 dark:text-blue-400 hover:underline font-medium">恢复默认</button>
|
||||
</div>
|
||||
@@ -384,7 +460,6 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
spellcheck="false"
|
||||
></textarea>
|
||||
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
||||
<p class="text-[10px] font-semibold text-slate-400 uppercase mb-2">可用变量 (Variables)</p>
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<span v-for="tag in ['{SOURCE_LANG}', '{TARGET_LANG}', '{SPEAKER_IDENTITY}', '{TONE_REGISTER}', '{CONTEXT}']" :key="tag" class="px-2 py-0.5 bg-white dark:bg-slate-800 text-[10px] font-mono rounded-md border dark:border-slate-700 text-slate-500 shadow-sm">{{ tag }}</span>
|
||||
</div>
|
||||
@@ -407,7 +482,6 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
spellcheck="false"
|
||||
></textarea>
|
||||
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
||||
<p class="text-[10px] font-semibold text-slate-400 uppercase mb-2">可用变量 (Variables)</p>
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<span v-for="tag in ['{SOURCE_LANG}', '{TARGET_LANG}', '{SPEAKER_IDENTITY}', '{TONE_REGISTER}', '{CONTEXT}']" :key="tag" class="px-2 py-0.5 bg-white dark:bg-slate-800 text-[10px] font-mono rounded-md border dark:border-slate-700 text-slate-500 shadow-sm">{{ tag }}</span>
|
||||
</div>
|
||||
|
||||
@@ -49,6 +49,7 @@ const sourceText = ref('');
|
||||
const context = ref('');
|
||||
const targetText = ref('');
|
||||
const isTranslating = ref(false);
|
||||
const currentHistoryId = ref<string | null>(null);
|
||||
|
||||
interface Suggestion { id: number; text: string; importance: number; }
|
||||
interface EvaluationResult { score: number; analysis: string; suggestions?: Suggestion[]; }
|
||||
@@ -104,6 +105,15 @@ const clearSource = () => {
|
||||
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 () => {
|
||||
if (!targetText.value) return;
|
||||
isEvaluating.value = true;
|
||||
@@ -139,14 +149,18 @@ const evaluateTranslation = async () => {
|
||||
stream: false
|
||||
};
|
||||
|
||||
settings.addLog('request', { type: 'evaluation', ...requestBody });
|
||||
settings.addLog('request', { type: 'evaluation', ...requestBody }, generateCurl(apiBaseUrl, apiKey, requestBody));
|
||||
|
||||
try {
|
||||
const response = await invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody });
|
||||
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);
|
||||
settings.addLog('response', { type: 'evaluation', content: evaluationResult.value });
|
||||
} catch (parseErr) {
|
||||
console.error('Failed to parse evaluation result:', response);
|
||||
settings.addLog('error', `Evaluation parsing error: ${response}`);
|
||||
@@ -196,17 +210,29 @@ const refineTranslation = async () => {
|
||||
stream: settings.enableStreaming
|
||||
};
|
||||
|
||||
settings.addLog('request', { type: 'refinement', ...requestBody });
|
||||
settings.addLog('request', { type: 'refinement', ...requestBody }, generateCurl(apiBaseUrl, apiKey, requestBody));
|
||||
|
||||
try {
|
||||
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) {
|
||||
appliedSuggestionIds.value.push(...selectedSuggestionIds.value);
|
||||
selectedSuggestionIds.value = [];
|
||||
}
|
||||
settings.addLog('response', 'Refinement completed');
|
||||
|
||||
if (currentHistoryId.value) {
|
||||
settings.updateHistoryItem(currentHistoryId.value, {
|
||||
targetText: targetText.value
|
||||
});
|
||||
}
|
||||
} catch (err: any) {
|
||||
const errorMsg = String(err);
|
||||
settings.addLog('error', errorMsg);
|
||||
@@ -220,6 +246,7 @@ const translate = async () => {
|
||||
if (!sourceText.value.trim() || isTranslating.value) return;
|
||||
|
||||
isTranslating.value = true;
|
||||
currentHistoryId.value = null;
|
||||
targetText.value = '';
|
||||
evaluationResult.value = null;
|
||||
|
||||
@@ -241,18 +268,27 @@ const translate = async () => {
|
||||
stream: settings.enableStreaming
|
||||
};
|
||||
|
||||
settings.addLog('request', requestBody);
|
||||
settings.addLog('request', requestBody, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
|
||||
|
||||
try {
|
||||
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;
|
||||
}
|
||||
|
||||
settings.addHistory({
|
||||
currentHistoryId.value = settings.addHistory({
|
||||
sourceLang: { ...sourceLang.value },
|
||||
targetLang: { ...targetLang.value },
|
||||
sourceText: sourceText.value,
|
||||
targetText: settings.enableStreaming ? targetText.value : response,
|
||||
targetText: finalTargetText,
|
||||
context: context.value,
|
||||
speakerIdentity: settings.speakerIdentity,
|
||||
toneRegister: settings.toneRegister,
|
||||
|
||||
@@ -159,10 +159,10 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
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 addLog = (type: 'request' | 'response' | 'error', content: any) => {
|
||||
const addLog = (type: 'request' | 'response' | 'error', content: any, curl?: string) => {
|
||||
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')}`;
|
||||
|
||||
@@ -170,7 +170,8 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
id: crypto.randomUUID(),
|
||||
timestamp,
|
||||
type,
|
||||
content
|
||||
content,
|
||||
curl
|
||||
});
|
||||
if (logs.value.length > 50) logs.value.pop(); // 稍微增加日志保留数量
|
||||
};
|
||||
@@ -178,10 +179,11 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
const addHistory = (item: Omit<HistoryItem, 'id' | 'timestamp'>) => {
|
||||
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 id = crypto.randomUUID();
|
||||
|
||||
history.value.unshift({
|
||||
...item,
|
||||
id: crypto.randomUUID(),
|
||||
id,
|
||||
timestamp
|
||||
});
|
||||
|
||||
@@ -189,6 +191,15 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
if (history.value.length > 100) {
|
||||
history.value = history.value.slice(0, 100);
|
||||
}
|
||||
|
||||
return id;
|
||||
};
|
||||
|
||||
const updateHistoryItem = (id: string, updates: Partial<HistoryItem>) => {
|
||||
const index = history.value.findIndex(h => h.id === id);
|
||||
if (index !== -1) {
|
||||
history.value[index] = { ...history.value[index], ...updates };
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -210,6 +221,7 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
logs,
|
||||
history,
|
||||
addLog,
|
||||
addHistory
|
||||
addHistory,
|
||||
updateHistoryItem
|
||||
};
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user