Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ac5e7f26c6 | |||
| 53f078154e | |||
| 17b91d6ac8 | |||
| f50a176252 | |||
| 505c7e612c | |||
| bdad27d6ac | |||
| fbd1728aee | |||
|
|
2e7789df63 |
1
src-tauri/.gitignore
vendored
1
src-tauri/.gitignore
vendored
@@ -1,6 +1,7 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
/target*/
|
||||
|
||||
# Generated by Tauri
|
||||
# will have schema files for capabilities auto-completion
|
||||
|
||||
@@ -32,12 +32,19 @@ struct Delta {
|
||||
content: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone)]
|
||||
struct TranslationChunkEvent {
|
||||
request_id: String,
|
||||
chunk: String,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn translate(
|
||||
app: AppHandle,
|
||||
api_address: String,
|
||||
api_key: String,
|
||||
payload: TranslationPayload,
|
||||
request_id: String,
|
||||
) -> Result<String, String> {
|
||||
let client = Client::new();
|
||||
// Ensure URL doesn't have double slashes if api_address ends with /
|
||||
@@ -55,6 +62,12 @@ async fn translate(
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let status = res.status();
|
||||
if !status.is_success() {
|
||||
let error_text = res.text().await.unwrap_or_else(|_| format!("HTTP {}", status));
|
||||
return Err(format!("HTTP {}: {}", status, error_text));
|
||||
}
|
||||
|
||||
if !payload.stream {
|
||||
let text = res.text().await.map_err(|e| e.to_string())?;
|
||||
return Ok(text);
|
||||
@@ -78,7 +91,11 @@ async fn translate(
|
||||
if let Some(choice) = json.choices.get(0) {
|
||||
if let Some(delta) = &choice.delta {
|
||||
if let Some(content) = &delta.content {
|
||||
app.emit("translation-chunk", content).map_err(|e| e.to_string())?;
|
||||
let event = TranslationChunkEvent {
|
||||
request_id: request_id.clone(),
|
||||
chunk: content.clone(),
|
||||
};
|
||||
app.emit("translation-chunk", event).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
17
src/App.vue
17
src/App.vue
@@ -6,8 +6,7 @@ import {
|
||||
FileText,
|
||||
Sun,
|
||||
Moon,
|
||||
Clock,
|
||||
MessageSquare
|
||||
Clock
|
||||
} from 'lucide-vue-next';
|
||||
import { useSettingsStore } from './stores/settings';
|
||||
import pkg from '../package.json';
|
||||
@@ -48,6 +47,20 @@ const view = ref<'translate' | 'conversation' | 'settings' | 'logs' | 'history'>
|
||||
<Languages class="w-6 h-6 text-blue-600 group-hover:scale-110 transition-transform" />
|
||||
<h1 class="font-semibold text-lg tracking-tight">AI 翻译</h1>
|
||||
</div>
|
||||
<nav class="flex items-center gap-1 rounded-full bg-slate-200/60 dark:bg-slate-800/70 p-1">
|
||||
<button
|
||||
@click="view = 'translate'"
|
||||
:class="cn('px-4 py-1.5 rounded-full text-sm font-medium transition-colors', view === 'translate' ? 'bg-white text-slate-900 shadow-sm dark:bg-slate-700 dark:text-slate-100' : 'text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200')"
|
||||
>
|
||||
单轮翻译
|
||||
</button>
|
||||
<button
|
||||
@click="view = 'conversation'"
|
||||
:class="cn('px-4 py-1.5 rounded-full text-sm font-medium transition-colors', view === 'conversation' ? 'bg-white text-slate-900 shadow-sm dark:bg-slate-700 dark:text-slate-100' : 'text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200')"
|
||||
>
|
||||
多轮翻译
|
||||
</button>
|
||||
</nav>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
@click="toggleTheme"
|
||||
|
||||
@@ -7,18 +7,37 @@ import {
|
||||
ShieldCheck, RotateCcw
|
||||
} from 'lucide-vue-next';
|
||||
import {
|
||||
useSettingsStore,
|
||||
useSettingsStore,
|
||||
} from '../stores/settings';
|
||||
import {
|
||||
LANGUAGES,
|
||||
SPEAKER_IDENTITY_OPTIONS,
|
||||
TONE_REGISTER_OPTIONS,
|
||||
type Participant
|
||||
} from '../stores/settings';
|
||||
} from '../domain/translation';
|
||||
import { useConversationStore } from '../stores/conversation';
|
||||
import { useLogsStore } from '../stores/logs';
|
||||
import { cn } from '../lib/utils';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import { useClipboard } from '../composables/useClipboard';
|
||||
import {
|
||||
buildConversationEvaluationUserPrompt,
|
||||
buildConversationRefinementUserPrompt,
|
||||
buildConversationSystemPrompt,
|
||||
buildConversationTranslationUserPrompt,
|
||||
} from '../lib/prompt-builders';
|
||||
import {
|
||||
executeTranslationRequest,
|
||||
extractAssistantContent,
|
||||
resolveModelConfig,
|
||||
tryParseEvaluationResult,
|
||||
type TranslationChunkEvent,
|
||||
type TranslationPayload,
|
||||
} from '../lib/translation-service';
|
||||
|
||||
const settings = useSettingsStore();
|
||||
const conversationStore = useConversationStore();
|
||||
const logsStore = useLogsStore();
|
||||
const { activeCopyId, copyWithFeedback } = useClipboard();
|
||||
|
||||
// UI States
|
||||
@@ -65,7 +84,7 @@ const closeAllModalDropdowns = () => {
|
||||
|
||||
// Current active session
|
||||
const activeSession = computed(() =>
|
||||
settings.chatSessions.find(s => s.id === settings.activeSessionId) || null
|
||||
conversationStore.chatSessions.find(s => s.id === conversationStore.activeSessionId) || null
|
||||
);
|
||||
|
||||
const scrollToBottom = async (smooth = true) => {
|
||||
@@ -79,7 +98,7 @@ const scrollToBottom = async (smooth = true) => {
|
||||
};
|
||||
|
||||
// Watch for session switch
|
||||
watch(() => settings.activeSessionId, async (newVal) => {
|
||||
watch(() => conversationStore.activeSessionId, async (newVal) => {
|
||||
if (newVal) {
|
||||
// 切换会话时,先立即滚动到底部(非平滑),然后再等 DOM 渲染完成后尝试平滑滚动确保到位
|
||||
await scrollToBottom(false);
|
||||
@@ -88,9 +107,9 @@ watch(() => settings.activeSessionId, async (newVal) => {
|
||||
});
|
||||
|
||||
const filteredSessions = computed(() => {
|
||||
if (!searchQuery.value.trim()) return settings.chatSessions;
|
||||
if (!searchQuery.value.trim()) return conversationStore.chatSessions;
|
||||
const q = searchQuery.value.toLowerCase();
|
||||
return settings.chatSessions.filter(s =>
|
||||
return conversationStore.chatSessions.filter(s =>
|
||||
s.title.toLowerCase().includes(q) ||
|
||||
s.partner.name.toLowerCase().includes(q)
|
||||
);
|
||||
@@ -101,6 +120,7 @@ const myInput = ref('');
|
||||
const partnerInput = ref('');
|
||||
const isTranslating = ref(false);
|
||||
const currentStreamingMessageId = ref<string | null>(null);
|
||||
const activeStreamRequestId = ref<string | null>(null);
|
||||
|
||||
// Dropdowns
|
||||
const myToneDropdownOpen = ref(false);
|
||||
@@ -108,17 +128,21 @@ const myToneDropdownOpen = ref(false);
|
||||
// Methods
|
||||
const handleCreateSession = () => {
|
||||
if (!newSessionPartner.value.name.trim()) return;
|
||||
const id = settings.createSession({ ...newSessionMe.value }, { ...newSessionPartner.value });
|
||||
const id = conversationStore.createSession({ ...newSessionMe.value }, { ...newSessionPartner.value });
|
||||
isCreatingSession.value = false;
|
||||
settings.activeSessionId = id;
|
||||
conversationStore.activeSessionId = id;
|
||||
};
|
||||
|
||||
let unlisten: (() => void) | null = null;
|
||||
onMounted(async () => {
|
||||
unlisten = await listen<string>('translation-chunk', (event) => {
|
||||
if (activeSession.value && currentStreamingMessageId.value) {
|
||||
settings.updateChatMessage(activeSession.value.id, currentStreamingMessageId.value, {
|
||||
translated: (activeSession.value.messages.find(m => m.id === currentStreamingMessageId.value)?.translated || '') + event.payload
|
||||
unlisten = await listen<TranslationChunkEvent>('translation-chunk', (event) => {
|
||||
if (
|
||||
activeSession.value &&
|
||||
currentStreamingMessageId.value &&
|
||||
event.payload.request_id === activeStreamRequestId.value
|
||||
) {
|
||||
conversationStore.updateChatMessage(activeSession.value.id, currentStreamingMessageId.value, {
|
||||
translated: (activeSession.value.messages.find(m => m.id === currentStreamingMessageId.value)?.translated || '') + event.payload.chunk
|
||||
});
|
||||
|
||||
// 优化:只有当正在流式输出的消息是最后一条时,才自动滚动到底部
|
||||
@@ -131,12 +155,6 @@ onMounted(async () => {
|
||||
});
|
||||
onUnmounted(() => { if (unlisten) unlisten(); });
|
||||
|
||||
const generateCurl = (baseUrl: string, key: string, body: any) => {
|
||||
const fullUrl = `${baseUrl.replace(/\/$/, '')}/chat/completions`;
|
||||
const maskedKey = key ? `${key.slice(0, 6)}...${key.slice(-4)}` : 'YOUR_API_KEY';
|
||||
return `curl "${fullUrl}" \\\n -H "Content-Type: application/json" \\\n -H "Authorization: Bearer ${maskedKey}" \\\n -d '${JSON.stringify(body, null, 2)}'`;
|
||||
};
|
||||
|
||||
const translateMessage = async (sender: 'me' | 'partner', retranslateId?: string) => {
|
||||
if (!activeSession.value || isTranslating.value) return;
|
||||
|
||||
@@ -148,12 +166,12 @@ const translateMessage = async (sender: 'me' | 'partner', retranslateId?: string
|
||||
if (!msg) return;
|
||||
text = msg.original;
|
||||
messageId = retranslateId;
|
||||
settings.updateChatMessage(activeSession.value.id, messageId, { translated: '', evaluation: undefined });
|
||||
conversationStore.updateChatMessage(activeSession.value.id, messageId, { translated: '', evaluation: undefined });
|
||||
} else {
|
||||
text = sender === 'me' ? myInput.value.trim() : partnerInput.value.trim();
|
||||
if (!text) return;
|
||||
|
||||
const newId = settings.addMessageToSession(activeSession.value.id, sender, text, '');
|
||||
const newId = conversationStore.addMessageToSession(activeSession.value.id, sender, text, '');
|
||||
if (!newId) return;
|
||||
messageId = newId;
|
||||
if (sender === 'me') myInput.value = ''; else partnerInput.value = '';
|
||||
@@ -181,53 +199,51 @@ const translateMessage = async (sender: 'me' | 'partner', retranslateId?: string
|
||||
// 3. Prepare Prompt
|
||||
const fromLang = sender === 'me' ? activeSession.value.me.language : activeSession.value.partner.language;
|
||||
const toLang = sender === 'me' ? activeSession.value.partner.language : activeSession.value.me.language;
|
||||
const myToneLabel = TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.label || '随和';
|
||||
const targetTone = sender === 'me'
|
||||
? TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.value || 'Polite & Conversational'
|
||||
: 'Auto-detect';
|
||||
const senderName = sender === 'me' ? activeSession.value.me.name : activeSession.value.partner.name;
|
||||
|
||||
const systemPrompt = settings.chatSystemPromptTemplate
|
||||
.replace(/{ME_NAME}/g, activeSession.value.me.name)
|
||||
.replace(/{ME_GENDER}/g, activeSession.value.me.gender)
|
||||
.replace(/{ME_LANG}/g, activeSession.value.me.language.englishName)
|
||||
.replace(/{PART_NAME}/g, activeSession.value.partner.name)
|
||||
.replace(/{PART_GENDER}/g, activeSession.value.partner.gender)
|
||||
.replace(/{PART_LANG}/g, activeSession.value.partner.language.englishName)
|
||||
.replace(/{HISTORY_BLOCK}/g, historyBlock || 'None (This is the start of conversation)')
|
||||
.replace(/{FROM_LANG}/g, fromLang.englishName)
|
||||
.replace(/{TO_LANG}/g, toLang.englishName)
|
||||
.replace(/{MY_TONE}/g, myToneLabel);
|
||||
const systemPrompt = buildConversationSystemPrompt(settings.chatSystemPromptTemplate, {
|
||||
me: activeSession.value.me,
|
||||
partner: activeSession.value.partner,
|
||||
historyBlock,
|
||||
senderName,
|
||||
fromLang,
|
||||
toLang,
|
||||
targetTone,
|
||||
}, 'None (This is the start of conversation)');
|
||||
|
||||
const requestBody = {
|
||||
const requestBody: TranslationPayload = {
|
||||
model: settings.modelName,
|
||||
messages: [
|
||||
{ role: "system", content: systemPrompt },
|
||||
{ role: "user", content: text }
|
||||
{ role: "user", content: buildConversationTranslationUserPrompt(text) }
|
||||
],
|
||||
stream: settings.enableStreaming
|
||||
};
|
||||
|
||||
settings.addLog('request', { type: retranslateId ? 'conversation-retranslate' : 'conversation', ...requestBody }, generateCurl(settings.apiBaseUrl, settings.apiKey, requestBody));
|
||||
|
||||
try {
|
||||
const response = await invoke<string>('translate', {
|
||||
apiAddress: settings.apiBaseUrl,
|
||||
apiKey: settings.apiKey,
|
||||
payload: requestBody
|
||||
const response = await executeTranslationRequest({
|
||||
apiAddress: settings.apiBaseUrl,
|
||||
apiKey: settings.apiKey,
|
||||
payload: requestBody,
|
||||
logger: logsStore,
|
||||
logType: retranslateId ? 'conversation-retranslate' : 'conversation',
|
||||
onStreamStart: (requestId) => {
|
||||
activeStreamRequestId.value = requestId;
|
||||
},
|
||||
});
|
||||
|
||||
if (!settings.enableStreaming) {
|
||||
const fullResponseJson = JSON.parse(response);
|
||||
settings.addLog('response', fullResponseJson);
|
||||
const translatedText = fullResponseJson.choices?.[0]?.message?.content || response;
|
||||
settings.updateChatMessage(activeSession.value.id, messageId, { translated: translatedText });
|
||||
} else {
|
||||
settings.addLog('response', response);
|
||||
conversationStore.updateChatMessage(activeSession.value.id, messageId, { translated: extractAssistantContent(response) });
|
||||
}
|
||||
} catch (err: any) {
|
||||
const errorMsg = String(err);
|
||||
settings.addLog('error', errorMsg);
|
||||
settings.updateChatMessage(activeSession.value.id, messageId, { translated: `Error: ${errorMsg}` });
|
||||
conversationStore.updateChatMessage(activeSession.value.id, messageId, { translated: `Error: ${String(err)}` });
|
||||
} finally {
|
||||
isTranslating.value = false;
|
||||
currentStreamingMessageId.value = null;
|
||||
activeStreamRequestId.value = null;
|
||||
|
||||
// 只有新消息才滚动到底部
|
||||
if (!retranslateId) {
|
||||
@@ -238,7 +254,7 @@ const translateMessage = async (sender: 'me' | 'partner', retranslateId?: string
|
||||
|
||||
const deleteMessage = (messageId: string) => {
|
||||
if (!activeSession.value) return;
|
||||
settings.deleteChatMessage(activeSession.value.id, messageId);
|
||||
conversationStore.deleteChatMessage(activeSession.value.id, messageId);
|
||||
};
|
||||
|
||||
const evaluateMessage = async (messageId: string, force = false) => {
|
||||
@@ -254,7 +270,7 @@ const evaluateMessage = async (messageId: string, force = false) => {
|
||||
|
||||
if (!force && (msg.evaluation || msg.isEvaluating)) return;
|
||||
|
||||
settings.updateChatMessage(activeSession.value.id, messageId, { isEvaluating: true, evaluation: undefined });
|
||||
conversationStore.updateChatMessage(activeSession.value.id, messageId, { isEvaluating: true, evaluation: undefined });
|
||||
|
||||
const historyLimit = 10;
|
||||
const recentMessages = activeSession.value.messages.filter(m => m.id !== messageId).slice(-historyLimit);
|
||||
@@ -271,42 +287,29 @@ const evaluateMessage = async (messageId: string, force = false) => {
|
||||
|
||||
// 动态确定目标语气约束
|
||||
const targetTone = msg.sender === 'me'
|
||||
? (TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.label || '随和')
|
||||
: '自动识别 (保留原作者原始语气和情绪)';
|
||||
? (TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.value || 'Polite & Conversational')
|
||||
: 'Auto-detect';
|
||||
|
||||
const systemPrompt = settings.chatEvaluationPromptTemplate
|
||||
.replace(/{ME_NAME}/g, activeSession.value.me.name)
|
||||
.replace(/{ME_GENDER}/g, activeSession.value.me.gender)
|
||||
.replace(/{ME_LANG}/g, activeSession.value.me.language.englishName)
|
||||
.replace(/{PART_NAME}/g, activeSession.value.partner.name)
|
||||
.replace(/{PART_GENDER}/g, activeSession.value.partner.gender)
|
||||
.replace(/{PART_LANG}/g, activeSession.value.partner.language.englishName)
|
||||
.replace(/{HISTORY_BLOCK}/g, historyBlock || 'None')
|
||||
.replace(/{TARGET_TONE}/g, targetTone)
|
||||
.replace(/{SENDER_NAME}/g, senderName)
|
||||
.replace(/{FROM_LANG}/g, fromLang.englishName)
|
||||
.replace(/{TO_LANG}/g, toLang.englishName)
|
||||
.replace(/{ORIGINAL_TEXT}/g, msg.original)
|
||||
.replace(/{CURRENT_TRANSLATION}/g, msg.translated);
|
||||
const systemPrompt = buildConversationSystemPrompt(settings.chatEvaluationPromptTemplate, {
|
||||
me: activeSession.value.me,
|
||||
partner: activeSession.value.partner,
|
||||
historyBlock,
|
||||
senderName,
|
||||
fromLang,
|
||||
toLang,
|
||||
targetTone,
|
||||
}, 'None');
|
||||
|
||||
const userPrompt = `[Source Text]\n${msg.original}\n\n[Current Translation]\n${msg.translated}`;
|
||||
const userPrompt = buildConversationEvaluationUserPrompt(msg.original, msg.translated);
|
||||
|
||||
// 使用审计专用配置
|
||||
let evalApiBaseUrl = settings.apiBaseUrl;
|
||||
let evalApiKey = settings.apiKey;
|
||||
let evalModelName = settings.modelName;
|
||||
const modelConfig = resolveModelConfig({
|
||||
apiBaseUrl: settings.apiBaseUrl,
|
||||
apiKey: settings.apiKey,
|
||||
modelName: settings.modelName,
|
||||
}, settings.profiles, settings.evaluationProfileId);
|
||||
|
||||
if (settings.evaluationProfileId) {
|
||||
const profile = settings.profiles.find(p => p.id === settings.evaluationProfileId);
|
||||
if (profile) {
|
||||
evalApiBaseUrl = profile.apiBaseUrl;
|
||||
evalApiKey = profile.apiKey;
|
||||
evalModelName = profile.modelName;
|
||||
}
|
||||
}
|
||||
|
||||
const requestBody = {
|
||||
model: evalModelName,
|
||||
const requestBody: TranslationPayload = {
|
||||
model: modelConfig.modelName,
|
||||
messages: [
|
||||
{ role: "system", content: systemPrompt },
|
||||
{ role: "user", content: userPrompt }
|
||||
@@ -314,22 +317,18 @@ const evaluateMessage = async (messageId: string, force = false) => {
|
||||
stream: false
|
||||
};
|
||||
|
||||
settings.addLog('request', { type: 'conversation-eval', ...requestBody }, generateCurl(evalApiBaseUrl, evalApiKey, requestBody));
|
||||
|
||||
try {
|
||||
const response = await invoke<string>('translate', {
|
||||
apiAddress: evalApiBaseUrl,
|
||||
apiKey: evalApiKey,
|
||||
payload: requestBody
|
||||
const response = await executeTranslationRequest({
|
||||
apiAddress: modelConfig.apiBaseUrl,
|
||||
apiKey: modelConfig.apiKey,
|
||||
payload: requestBody,
|
||||
logger: logsStore,
|
||||
logType: 'conversation-eval',
|
||||
});
|
||||
const fullResponseJson = JSON.parse(response);
|
||||
settings.addLog('response', fullResponseJson);
|
||||
const evaluationJson = fullResponseJson.choices?.[0]?.message?.content || response;
|
||||
settings.updateChatMessage(activeSession.value.id, messageId, { evaluation: evaluationJson });
|
||||
} catch (err: any) {
|
||||
settings.addLog('error', String(err));
|
||||
conversationStore.updateChatMessage(activeSession.value.id, messageId, { evaluation: extractAssistantContent(response) });
|
||||
} catch {
|
||||
} finally {
|
||||
settings.updateChatMessage(activeSession.value.id, messageId, { isEvaluating: false });
|
||||
conversationStore.updateChatMessage(activeSession.value.id, messageId, { isEvaluating: false });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -344,19 +343,17 @@ const refineMessage = async (messageId: string) => {
|
||||
const msg = activeSession.value.messages.find(m => m.id === messageId);
|
||||
if (!msg || !msg.evaluation || msg.isRefining) return;
|
||||
|
||||
let evalData;
|
||||
try {
|
||||
evalData = parseEvaluation(msg.evaluation);
|
||||
} catch (e) { return; }
|
||||
const parsedEvaluation = tryParseEvaluationResult(msg.evaluation);
|
||||
const evalData = parsedEvaluation.result;
|
||||
|
||||
// 仅使用选中的建议
|
||||
const selectedSuggestions = evalData.suggestions.filter((s: any) => selectedSuggestionIds.value.includes(s.id));
|
||||
if (selectedSuggestions.length === 0) return;
|
||||
|
||||
const suggestionsText = selectedSuggestions.map((s: any) => `- ${s.text}`).join('\n');
|
||||
const currentTranslation = msg.translated;
|
||||
|
||||
isAuditModalOpen.value = false; // 关闭弹窗开始润色
|
||||
settings.updateChatMessage(activeSession.value.id, messageId, { isRefining: true, translated: '' });
|
||||
conversationStore.updateChatMessage(activeSession.value.id, messageId, { isRefining: true, translated: '' });
|
||||
currentStreamingMessageId.value = messageId;
|
||||
|
||||
const historyLimit = 10;
|
||||
@@ -367,75 +364,61 @@ const refineMessage = async (messageId: string) => {
|
||||
return `${senderName}: "${m.original}"`;
|
||||
}).join('\n');
|
||||
|
||||
const myToneLabel = TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.label || '随和';
|
||||
|
||||
// 确定目标语气
|
||||
const targetTone = msg.sender === 'me' ? myToneLabel : '自动识别 (保持原作者原始语气和情绪)';
|
||||
const targetTone = msg.sender === 'me'
|
||||
? TONE_REGISTER_OPTIONS.find(o => o.value === activeSession.value!.me.tone)?.value || 'Polite & Conversational'
|
||||
: 'Auto-detect';
|
||||
|
||||
// 动态确定语言方向
|
||||
const fromLang = msg.sender === 'me' ? activeSession.value.me.language : activeSession.value.partner.language;
|
||||
const toLang = msg.sender === 'me' ? activeSession.value.partner.language : activeSession.value.me.language;
|
||||
const senderName = msg.sender === 'me' ? activeSession.value.me.name : activeSession.value.partner.name;
|
||||
|
||||
const systemPrompt = settings.chatRefinementPromptTemplate
|
||||
.replace(/{ME_NAME}/g, activeSession.value.me.name)
|
||||
.replace(/{ME_GENDER}/g, activeSession.value.me.gender)
|
||||
.replace(/{ME_LANG}/g, activeSession.value.me.language.englishName)
|
||||
.replace(/{PART_NAME}/g, activeSession.value.partner.name)
|
||||
.replace(/{PART_GENDER}/g, activeSession.value.partner.gender)
|
||||
.replace(/{PART_LANG}/g, activeSession.value.partner.language.englishName)
|
||||
.replace(/{HISTORY_BLOCK}/g, historyBlock || 'None')
|
||||
.replace(/{ORIGINAL_TEXT}/g, msg.original)
|
||||
.replace(/{CURRENT_TRANSLATION}/g, msg.translated)
|
||||
.replace(/{SUGGESTIONS}/g, suggestionsText)
|
||||
.replace(/{TARGET_TONE}/g, targetTone)
|
||||
.replace(/{FROM_LANG}/g, fromLang.englishName)
|
||||
.replace(/{TO_LANG}/g, toLang.englishName);
|
||||
const systemPrompt = buildConversationSystemPrompt(settings.chatRefinementPromptTemplate, {
|
||||
me: activeSession.value.me,
|
||||
partner: activeSession.value.partner,
|
||||
historyBlock,
|
||||
senderName,
|
||||
fromLang,
|
||||
toLang,
|
||||
targetTone,
|
||||
}, 'None');
|
||||
|
||||
// 使用审计专用配置
|
||||
let refineApiBaseUrl = settings.apiBaseUrl;
|
||||
let refineApiKey = settings.apiKey;
|
||||
let refineModelName = settings.modelName;
|
||||
const modelConfig = resolveModelConfig({
|
||||
apiBaseUrl: settings.apiBaseUrl,
|
||||
apiKey: settings.apiKey,
|
||||
modelName: settings.modelName,
|
||||
}, settings.profiles, settings.evaluationProfileId);
|
||||
|
||||
if (settings.evaluationProfileId) {
|
||||
const profile = settings.profiles.find(p => p.id === settings.evaluationProfileId);
|
||||
if (profile) {
|
||||
refineApiBaseUrl = profile.apiBaseUrl;
|
||||
refineApiKey = profile.apiKey;
|
||||
refineModelName = profile.modelName;
|
||||
}
|
||||
}
|
||||
|
||||
const requestBody = {
|
||||
model: refineModelName,
|
||||
const requestBody: TranslationPayload = {
|
||||
model: modelConfig.modelName,
|
||||
messages: [
|
||||
{ role: "system", content: systemPrompt },
|
||||
{ role: "user", content: `Please refine the following original text: ${msg.original}` }
|
||||
{ role: "user", content: buildConversationRefinementUserPrompt(msg.original, currentTranslation, selectedSuggestions.map((s: any) => s.text)) }
|
||||
],
|
||||
stream: settings.enableStreaming
|
||||
};
|
||||
|
||||
settings.addLog('request', { type: 'conversation-refine', ...requestBody }, generateCurl(refineApiBaseUrl, refineApiKey, requestBody));
|
||||
|
||||
try {
|
||||
const response = await invoke<string>('translate', {
|
||||
apiAddress: refineApiBaseUrl,
|
||||
apiKey: refineApiKey,
|
||||
payload: requestBody
|
||||
const response = await executeTranslationRequest({
|
||||
apiAddress: modelConfig.apiBaseUrl,
|
||||
apiKey: modelConfig.apiKey,
|
||||
payload: requestBody,
|
||||
logger: logsStore,
|
||||
logType: 'conversation-refine',
|
||||
onStreamStart: (requestId) => {
|
||||
activeStreamRequestId.value = requestId;
|
||||
},
|
||||
});
|
||||
|
||||
if (!settings.enableStreaming) {
|
||||
const fullResponseJson = JSON.parse(response);
|
||||
settings.addLog('response', fullResponseJson);
|
||||
const refinedText = fullResponseJson.choices?.[0]?.message?.content || response;
|
||||
settings.updateChatMessage(activeSession.value.id, messageId, { translated: refinedText });
|
||||
} else {
|
||||
settings.addLog('response', response);
|
||||
conversationStore.updateChatMessage(activeSession.value.id, messageId, { translated: extractAssistantContent(response) });
|
||||
}
|
||||
} catch (err: any) {
|
||||
settings.addLog('error', String(err));
|
||||
} catch {
|
||||
} finally {
|
||||
settings.updateChatMessage(activeSession.value.id, messageId, { isRefining: false, evaluation: undefined });
|
||||
conversationStore.updateChatMessage(activeSession.value.id, messageId, { isRefining: false, evaluation: undefined });
|
||||
currentStreamingMessageId.value = null;
|
||||
activeStreamRequestId.value = null;
|
||||
|
||||
// 只有当润色的是最后一条消息时才滚动到底部
|
||||
const lastMsg = activeSession.value.messages[activeSession.value.messages.length - 1];
|
||||
@@ -445,20 +428,7 @@ const refineMessage = async (messageId: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
const parseEvaluation = (evalStr?: string) => {
|
||||
if (!evalStr) return null;
|
||||
try {
|
||||
// 1. 清洗数据:剔除 Markdown 代码块标记 (如 ```json ... ``` 或 ``` ...)
|
||||
let cleanStr = evalStr.trim();
|
||||
if (cleanStr.startsWith('```')) {
|
||||
cleanStr = cleanStr.replace(/^```[a-zA-Z]*\n?/, '').replace(/\n?```$/, '').trim();
|
||||
}
|
||||
return JSON.parse(cleanStr);
|
||||
} catch (e) {
|
||||
console.error('Failed to parse evaluation JSON:', e, 'Raw string:', evalStr);
|
||||
return { score: 0, analysis: '无法解析审计结果,请查看日志', suggestions: [] };
|
||||
}
|
||||
};
|
||||
const parseEvaluation = (evalStr?: string) => tryParseEvaluationResult(evalStr).result;
|
||||
|
||||
const handleGlobalClick = () => {
|
||||
myToneDropdownOpen.value = false;
|
||||
@@ -504,10 +474,10 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
<div
|
||||
v-for="session in filteredSessions"
|
||||
:key="session.id"
|
||||
@click="settings.activeSessionId = session.id"
|
||||
@click="conversationStore.activeSessionId = session.id"
|
||||
:class="cn(
|
||||
'w-full p-4 rounded-xl text-left transition-all border group relative cursor-pointer',
|
||||
settings.activeSessionId === session.id
|
||||
conversationStore.activeSessionId === session.id
|
||||
? 'bg-blue-50 dark:bg-blue-900/20 border-blue-100 dark:border-blue-900/50 shadow-sm'
|
||||
: 'hover:bg-slate-100 dark:hover:bg-slate-800/50 border-transparent'
|
||||
)"
|
||||
@@ -526,7 +496,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
</p>
|
||||
|
||||
<button
|
||||
@click.stop="settings.deleteSession(session.id)"
|
||||
@click.stop="conversationStore.deleteSession(session.id)"
|
||||
class="absolute right-2 bottom-2 p-1.5 rounded-md text-red-400 opacity-0 group-hover:opacity-100 hover:bg-red-50 dark:hover:bg-red-900/30 transition-all"
|
||||
title="删除会话"
|
||||
>
|
||||
|
||||
@@ -1,27 +1,28 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch } from 'vue';
|
||||
import { Clock, Search, ArrowRightLeft, Trash2, User, Type, Copy, Check, FileText } from 'lucide-vue-next';
|
||||
import { useSettingsStore, SPEAKER_IDENTITY_OPTIONS, TONE_REGISTER_OPTIONS } from '../stores/settings';
|
||||
import { useHistoryStore } from '../stores/history';
|
||||
import { SPEAKER_IDENTITY_OPTIONS, TONE_REGISTER_OPTIONS } from '../domain/translation';
|
||||
import { cn } from '../lib/utils';
|
||||
import { useClipboard } from '../composables/useClipboard';
|
||||
|
||||
const settings = useSettingsStore();
|
||||
const historyStore = useHistoryStore();
|
||||
const { activeCopyId, copyWithFeedback } = useClipboard();
|
||||
|
||||
const searchQuery = ref('');
|
||||
const selectedHistoryId = ref<string | null>(null);
|
||||
|
||||
const filteredHistory = computed(() => {
|
||||
if (!searchQuery.value.trim()) return settings.history;
|
||||
if (!searchQuery.value.trim()) return historyStore.history;
|
||||
const q = searchQuery.value.toLowerCase();
|
||||
return settings.history.filter(h =>
|
||||
return historyStore.history.filter(h =>
|
||||
h.sourceText.toLowerCase().includes(q) ||
|
||||
h.targetText.toLowerCase().includes(q)
|
||||
);
|
||||
});
|
||||
|
||||
const selectedHistoryItem = computed(() =>
|
||||
settings.history.find(h => h.id === selectedHistoryId.value) || null
|
||||
historyStore.history.find(h => h.id === selectedHistoryId.value) || null
|
||||
);
|
||||
|
||||
watch(filteredHistory, (newVal) => {
|
||||
@@ -31,7 +32,7 @@ watch(filteredHistory, (newVal) => {
|
||||
}, { immediate: true });
|
||||
|
||||
const deleteHistoryItem = (id: string) => {
|
||||
settings.history = settings.history.filter(h => h.id !== id);
|
||||
historyStore.deleteHistoryItem(id);
|
||||
if (selectedHistoryId.value === id) {
|
||||
selectedHistoryId.value = filteredHistory.value[0]?.id || null;
|
||||
}
|
||||
@@ -55,7 +56,7 @@ const deleteHistoryItem = (id: string) => {
|
||||
<div class="flex items-center justify-between px-1">
|
||||
<span class="text-[11px] font-bold text-slate-400 uppercase tracking-wider">共 {{ filteredHistory.length }} 条记录</span>
|
||||
<button
|
||||
@click="settings.history = []"
|
||||
@click="historyStore.clearHistory()"
|
||||
class="text-[11px] text-red-500 hover:underline font-medium"
|
||||
>清空全部</button>
|
||||
</div>
|
||||
@@ -194,4 +195,4 @@ const deleteHistoryItem = (id: string) => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch } from 'vue';
|
||||
import { FileText, Check, Copy } from 'lucide-vue-next';
|
||||
import { useSettingsStore } from '../stores/settings';
|
||||
import { useLogsStore } from '../stores/logs';
|
||||
import { cn } from '../lib/utils';
|
||||
import { useClipboard } from '../composables/useClipboard';
|
||||
|
||||
const settings = useSettingsStore();
|
||||
const logsStore = useLogsStore();
|
||||
const { activeCopyId, copyWithFeedback } = useClipboard();
|
||||
|
||||
const selectedLogId = ref<string | null>(null);
|
||||
const selectedLogItem = computed(() =>
|
||||
settings.logs.find(l => l.id === selectedLogId.value) || null
|
||||
logsStore.logs.find(l => l.id === selectedLogId.value) || null
|
||||
);
|
||||
|
||||
watch(() => settings.logs, (newVal) => {
|
||||
watch(() => logsStore.logs, (newVal) => {
|
||||
if (newVal.length > 0 && !selectedLogId.value) {
|
||||
selectedLogId.value = newVal[0].id;
|
||||
}
|
||||
@@ -47,7 +47,7 @@ const getLogSummary = (log: any) => {
|
||||
<div class="flex items-center justify-between">
|
||||
<h2 class="text-sm font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider">系统日志</h2>
|
||||
<button
|
||||
@click="settings.logs = []"
|
||||
@click="logsStore.clearLogs()"
|
||||
class="text-[11px] text-red-500 hover:underline font-medium flex items-center gap-1"
|
||||
>
|
||||
清空全部
|
||||
@@ -56,12 +56,12 @@ const getLogSummary = (log: any) => {
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-y-auto custom-scrollbar p-2 space-y-1">
|
||||
<div v-if="settings.logs.length === 0" class="py-20 text-center space-y-2">
|
||||
<div v-if="logsStore.logs.length === 0" class="py-20 text-center space-y-2">
|
||||
<FileText class="w-10 h-10 text-slate-200 dark:text-slate-800 mx-auto" />
|
||||
<p class="text-sm text-slate-400 italic">暂无日志记录</p>
|
||||
</div>
|
||||
<div
|
||||
v-for="log in settings.logs"
|
||||
v-for="log in logsStore.logs"
|
||||
:key="log.id"
|
||||
@click="selectedLogId = log.id"
|
||||
:class="cn(
|
||||
@@ -144,4 +144,4 @@ const getLogSummary = (log: any) => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
@@ -8,9 +8,9 @@ import {
|
||||
DEFAULT_REFINEMENT_TEMPLATE,
|
||||
CONVERSATION_SYSTEM_PROMPT_TEMPLATE,
|
||||
CONVERSATION_EVALUATION_PROMPT_TEMPLATE,
|
||||
CONVERSATION_REFINEMENT_PROMPT_TEMPLATE,
|
||||
type ApiProfile
|
||||
CONVERSATION_REFINEMENT_PROMPT_TEMPLATE
|
||||
} from '../stores/settings';
|
||||
import type { ApiProfile } from '../domain/translation';
|
||||
import { cn } from '../lib/utils';
|
||||
|
||||
const settings = useSettingsStore();
|
||||
@@ -536,7 +536,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
></textarea>
|
||||
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<span v-for="tag in ['{ME_NAME}', '{ME_GENDER}', '{ME_LANG}', '{PART_NAME}', '{PART_GENDER}', '{PART_LANG}', '{HISTORY_BLOCK}', '{FROM_LANG}', '{TO_LANG}', '{MY_TONE}']" :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>
|
||||
<span v-for="tag in ['{ME_NAME}', '{ME_GENDER}', '{ME_LANG}', '{PART_NAME}', '{PART_GENDER}', '{PART_LANG}', '{HISTORY_BLOCK}', '{SENDER_NAME}', '{FROM_LANG}', '{TO_LANG}', '{TARGET_TONE}']" :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>
|
||||
</div>
|
||||
</div>
|
||||
@@ -558,7 +558,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
></textarea>
|
||||
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<span v-for="tag in ['{ME_NAME}', '{ME_GENDER}', '{ME_LANG}', '{PART_NAME}', '{PART_GENDER}', '{PART_LANG}', '{TARGET_TONE}', '{SENDER_NAME}', '{FROM_LANG}', '{TO_LANG}', '{HISTORY_BLOCK}', '{ORIGINAL_TEXT}', '{CURRENT_TRANSLATION}']" :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>
|
||||
<span v-for="tag in ['{ME_NAME}', '{ME_GENDER}', '{ME_LANG}', '{PART_NAME}', '{PART_GENDER}', '{PART_LANG}', '{HISTORY_BLOCK}', '{SENDER_NAME}', '{FROM_LANG}', '{TO_LANG}', '{TARGET_TONE}']" :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>
|
||||
</div>
|
||||
</div>
|
||||
@@ -580,7 +580,7 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
></textarea>
|
||||
<div class="px-5 py-3 bg-slate-50 dark:bg-slate-950 border-t dark:border-slate-800">
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<span v-for="tag in ['{ME_NAME}', '{ME_GENDER}', '{ME_LANG}', '{PART_NAME}', '{PART_GENDER}', '{PART_LANG}', '{TARGET_TONE}', '{HISTORY_BLOCK}', '{ORIGINAL_TEXT}', '{CURRENT_TRANSLATION}', '{SUGGESTIONS}']" :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>
|
||||
<span v-for="tag in ['{ME_NAME}', '{ME_GENDER}', '{ME_LANG}', '{PART_NAME}', '{PART_GENDER}', '{PART_LANG}', '{HISTORY_BLOCK}', '{SENDER_NAME}', '{FROM_LANG}', '{TO_LANG}', '{TARGET_TONE}']" :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>
|
||||
</div>
|
||||
</div>
|
||||
@@ -590,4 +590,4 @@ onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
@@ -1,14 +1,50 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, onUnmounted } from 'vue';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { ChevronDown, Check, ArrowRightLeft, Trash2, FileText, Plus, Loader2, Send, User, Type, Copy, Save } from 'lucide-vue-next';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import { useSettingsStore, LANGUAGES, SPEAKER_IDENTITY_OPTIONS, TONE_REGISTER_OPTIONS } from '../stores/settings';
|
||||
import { LANGUAGES, SPEAKER_IDENTITY_OPTIONS, TONE_REGISTER_OPTIONS } from '../domain/translation';
|
||||
import { useSettingsStore } from '../stores/settings';
|
||||
import { useHistoryStore } from '../stores/history';
|
||||
import { useLogsStore } from '../stores/logs';
|
||||
import { useTranslationWorkspaceStore } from '../stores/translation-workspace';
|
||||
import { cn } from '../lib/utils';
|
||||
import { useClipboard } from '../composables/useClipboard';
|
||||
import {
|
||||
buildSingleEvaluationSystemPrompt,
|
||||
buildSingleEvaluationUserPrompt,
|
||||
buildSingleRefinementSystemPrompt,
|
||||
buildSingleRefinementUserPrompt,
|
||||
buildSingleTranslationSystemPrompt,
|
||||
buildSingleTranslationUserPrompt,
|
||||
} from '../lib/prompt-builders';
|
||||
import {
|
||||
executeTranslationRequest,
|
||||
extractAssistantContent,
|
||||
resolveModelConfig,
|
||||
tryParseEvaluationResult,
|
||||
type TranslationChunkEvent,
|
||||
type TranslationPayload,
|
||||
} from '../lib/translation-service';
|
||||
|
||||
const settings = useSettingsStore();
|
||||
const historyStore = useHistoryStore();
|
||||
const logsStore = useLogsStore();
|
||||
const workspaceStore = useTranslationWorkspaceStore();
|
||||
const { activeCopyId, copyWithFeedback } = useClipboard();
|
||||
const {
|
||||
sourceText,
|
||||
context,
|
||||
targetText,
|
||||
isTranslating,
|
||||
currentHistoryId,
|
||||
evaluationResult,
|
||||
isEvaluating,
|
||||
isRefining,
|
||||
selectedSuggestionIds,
|
||||
appliedSuggestionIds,
|
||||
activeStreamRequestId,
|
||||
} = storeToRefs(workspaceStore);
|
||||
|
||||
const sourceDropdownOpen = ref(false);
|
||||
const targetDropdownOpen = ref(false);
|
||||
@@ -45,33 +81,11 @@ const handleGlobalClick = (e: MouseEvent) => {
|
||||
onMounted(() => window.addEventListener('click', handleGlobalClick));
|
||||
onUnmounted(() => window.removeEventListener('click', handleGlobalClick));
|
||||
|
||||
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[]; }
|
||||
|
||||
const evaluationResult = ref<EvaluationResult | null>(null);
|
||||
const isEvaluating = ref(false);
|
||||
const isRefining = ref(false);
|
||||
const selectedSuggestionIds = ref<number[]>([]);
|
||||
const appliedSuggestionIds = ref<number[]>([]);
|
||||
|
||||
const toggleSuggestion = (id: number) => {
|
||||
if (!selectedSuggestionIds.value) selectedSuggestionIds.value = [];
|
||||
const index = selectedSuggestionIds.value.indexOf(id);
|
||||
if (index > -1) selectedSuggestionIds.value.splice(index, 1);
|
||||
else selectedSuggestionIds.value.push(id);
|
||||
};
|
||||
|
||||
let unlisten: (() => void) | null = null;
|
||||
onMounted(async () => {
|
||||
unlisten = await listen<string>('translation-chunk', (event) => {
|
||||
if (isTranslating.value || isRefining.value) {
|
||||
targetText.value += event.payload;
|
||||
unlisten = await listen<TranslationChunkEvent>('translation-chunk', (event) => {
|
||||
if ((isTranslating.value || isRefining.value) && event.payload.request_id === activeStreamRequestId.value) {
|
||||
targetText.value += event.payload.chunk;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -100,73 +114,55 @@ const swapLanguages = () => {
|
||||
};
|
||||
|
||||
const clearSource = () => {
|
||||
sourceText.value = '';
|
||||
targetText.value = '';
|
||||
evaluationResult.value = null;
|
||||
workspaceStore.clearWorkspace();
|
||||
};
|
||||
|
||||
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 toggleSuggestion = (id: number) => {
|
||||
workspaceStore.toggleSuggestion(id);
|
||||
};
|
||||
|
||||
const evaluateTranslation = async () => {
|
||||
if (!targetText.value) return;
|
||||
isEvaluating.value = true;
|
||||
evaluationResult.value = null;
|
||||
selectedSuggestionIds.value = [];
|
||||
appliedSuggestionIds.value = [];
|
||||
workspaceStore.resetEvaluationState();
|
||||
|
||||
let apiBaseUrl = settings.apiBaseUrl;
|
||||
let apiKey = settings.apiKey;
|
||||
let modelName = settings.modelName;
|
||||
const modelConfig = resolveModelConfig({
|
||||
apiBaseUrl: settings.apiBaseUrl,
|
||||
apiKey: settings.apiKey,
|
||||
modelName: settings.modelName,
|
||||
}, settings.profiles, settings.evaluationProfileId);
|
||||
|
||||
if (settings.evaluationProfileId) {
|
||||
const profile = settings.profiles.find(p => p.id === settings.evaluationProfileId);
|
||||
if (profile) {
|
||||
apiBaseUrl = profile.apiBaseUrl;
|
||||
apiKey = profile.apiKey;
|
||||
modelName = profile.modelName;
|
||||
}
|
||||
}
|
||||
const evaluationSystemPrompt = buildSingleEvaluationSystemPrompt(settings.evaluationPromptTemplate, {
|
||||
sourceLang: sourceLang.value,
|
||||
targetLang: targetLang.value,
|
||||
speakerIdentity: settings.speakerIdentity,
|
||||
toneRegister: settings.toneRegister,
|
||||
context: context.value,
|
||||
});
|
||||
|
||||
const evaluationSystemPrompt = settings.evaluationPromptTemplate
|
||||
.replace(/{SOURCE_LANG}/g, sourceLang.value.englishName)
|
||||
.replace(/{TARGET_LANG}/g, targetLang.value.englishName)
|
||||
.replace(/{SPEAKER_IDENTITY}/g, settings.speakerIdentity)
|
||||
.replace(/{TONE_REGISTER}/g, settings.toneRegister)
|
||||
.replace(/{CONTEXT}/g, context.value || 'None');
|
||||
const evaluationUserPrompt = buildSingleEvaluationUserPrompt(sourceText.value, targetText.value);
|
||||
|
||||
const evaluationUserPrompt = `[Source Text]\n${sourceText.value}\n\n[Translated Text]\n${targetText.value}`;
|
||||
|
||||
const requestBody = {
|
||||
model: modelName,
|
||||
const requestBody: TranslationPayload = {
|
||||
model: modelConfig.modelName,
|
||||
messages: [ { role: "system", content: evaluationSystemPrompt }, { role: "user", content: evaluationUserPrompt } ],
|
||||
stream: false
|
||||
};
|
||||
|
||||
settings.addLog('request', { type: 'evaluation', ...requestBody }, generateCurl(apiBaseUrl, apiKey, requestBody));
|
||||
|
||||
try {
|
||||
const response = await invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody });
|
||||
try {
|
||||
// 解析 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);
|
||||
} catch (parseErr) {
|
||||
console.error('Failed to parse evaluation result:', response);
|
||||
settings.addLog('error', `Evaluation parsing error: ${response}`);
|
||||
const response = await executeTranslationRequest({
|
||||
apiAddress: modelConfig.apiBaseUrl,
|
||||
apiKey: modelConfig.apiKey,
|
||||
payload: requestBody,
|
||||
logger: logsStore,
|
||||
logType: 'evaluation',
|
||||
});
|
||||
const parsedEvaluation = tryParseEvaluationResult(extractAssistantContent(response));
|
||||
if (!parsedEvaluation.ok) {
|
||||
console.error(parsedEvaluation.error, response);
|
||||
logsStore.addLog('error', `Evaluation parsing error: ${response}`);
|
||||
}
|
||||
} catch (err: any) {
|
||||
settings.addLog('error', `Evaluation error: ${String(err)}`);
|
||||
evaluationResult.value = parsedEvaluation.result;
|
||||
} catch {
|
||||
} finally {
|
||||
isEvaluating.value = false;
|
||||
}
|
||||
@@ -181,47 +177,41 @@ const refineTranslation = async () => {
|
||||
const originalTranslation = targetText.value;
|
||||
targetText.value = '';
|
||||
|
||||
let apiBaseUrl = settings.apiBaseUrl;
|
||||
let apiKey = settings.apiKey;
|
||||
let modelName = settings.modelName;
|
||||
const modelConfig = resolveModelConfig({
|
||||
apiBaseUrl: settings.apiBaseUrl,
|
||||
apiKey: settings.apiKey,
|
||||
modelName: settings.modelName,
|
||||
}, settings.profiles, settings.evaluationProfileId);
|
||||
|
||||
if (settings.evaluationProfileId) {
|
||||
const profile = settings.profiles.find(p => p.id === settings.evaluationProfileId);
|
||||
if (profile) {
|
||||
apiBaseUrl = profile.apiBaseUrl;
|
||||
apiKey = profile.apiKey;
|
||||
modelName = profile.modelName;
|
||||
}
|
||||
}
|
||||
const refinementSystemPrompt = buildSingleRefinementSystemPrompt(settings.refinementPromptTemplate, {
|
||||
sourceLang: sourceLang.value,
|
||||
targetLang: targetLang.value,
|
||||
speakerIdentity: settings.speakerIdentity,
|
||||
toneRegister: settings.toneRegister,
|
||||
context: context.value,
|
||||
});
|
||||
|
||||
const refinementSystemPrompt = settings.refinementPromptTemplate
|
||||
.replace(/{SOURCE_LANG}/g, sourceLang.value.englishName)
|
||||
.replace(/{TARGET_LANG}/g, targetLang.value.englishName)
|
||||
.replace(/{SPEAKER_IDENTITY}/g, settings.speakerIdentity)
|
||||
.replace(/{TONE_REGISTER}/g, settings.toneRegister)
|
||||
.replace(/{CONTEXT}/g, context.value || 'None');
|
||||
const refinementUserPrompt = buildSingleRefinementUserPrompt(sourceText.value, originalTranslation, selectedTexts);
|
||||
|
||||
const formattedSuggestions = selectedTexts.map((text, i) => `${i + 1}. ${text}`).join('\n');
|
||||
const refinementUserPrompt = `[Source Text]\n${sourceText.value}\n\n[Current Translation]\n${originalTranslation}\n\n[User Feedback]\n${formattedSuggestions}`;
|
||||
|
||||
const requestBody = {
|
||||
model: modelName,
|
||||
const requestBody: TranslationPayload = {
|
||||
model: modelConfig.modelName,
|
||||
messages: [ { role: "system", content: refinementSystemPrompt }, { role: "user", content: refinementUserPrompt } ],
|
||||
stream: settings.enableStreaming
|
||||
};
|
||||
|
||||
settings.addLog('request', { type: 'refinement', ...requestBody }, generateCurl(apiBaseUrl, apiKey, requestBody));
|
||||
|
||||
try {
|
||||
const response = await invoke<string>('translate', { apiAddress: apiBaseUrl, apiKey: apiKey, payload: requestBody });
|
||||
const response = await executeTranslationRequest({
|
||||
apiAddress: modelConfig.apiBaseUrl,
|
||||
apiKey: modelConfig.apiKey,
|
||||
payload: requestBody,
|
||||
logger: logsStore,
|
||||
logType: 'refinement',
|
||||
onStreamStart: (requestId) => {
|
||||
activeStreamRequestId.value = requestId;
|
||||
},
|
||||
});
|
||||
|
||||
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 (!settings.enableStreaming) targetText.value = extractAssistantContent(response);
|
||||
|
||||
if (evaluationResult.value?.suggestions) {
|
||||
appliedSuggestionIds.value.push(...selectedSuggestionIds.value);
|
||||
@@ -229,16 +219,15 @@ const refineTranslation = async () => {
|
||||
}
|
||||
|
||||
if (currentHistoryId.value) {
|
||||
settings.updateHistoryItem(currentHistoryId.value, {
|
||||
historyStore.updateHistoryItem(currentHistoryId.value, {
|
||||
targetText: targetText.value
|
||||
});
|
||||
}
|
||||
} catch (err: any) {
|
||||
const errorMsg = String(err);
|
||||
settings.addLog('error', errorMsg);
|
||||
targetText.value = `Error: ${errorMsg}`;
|
||||
targetText.value = `Error: ${String(err)}`;
|
||||
} finally {
|
||||
isRefining.value = false;
|
||||
activeStreamRequestId.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -250,41 +239,41 @@ const translate = async () => {
|
||||
targetText.value = '';
|
||||
evaluationResult.value = null;
|
||||
|
||||
const systemMessage = settings.systemPromptTemplate
|
||||
.replace(/{SOURCE_LANG}/g, sourceLang.value.englishName)
|
||||
.replace(/{SOURCE_CODE}/g, sourceLang.value.code)
|
||||
.replace(/{TARGET_LANG}/g, targetLang.value.englishName)
|
||||
.replace(/{TARGET_CODE}/g, targetLang.value.code)
|
||||
.replace(/{SPEAKER_IDENTITY}/g, settings.speakerIdentity)
|
||||
.replace(/{TONE_REGISTER}/g, settings.toneRegister);
|
||||
const systemMessage = buildSingleTranslationSystemPrompt(settings.systemPromptTemplate, {
|
||||
sourceLang: sourceLang.value,
|
||||
targetLang: targetLang.value,
|
||||
speakerIdentity: settings.speakerIdentity,
|
||||
toneRegister: settings.toneRegister,
|
||||
});
|
||||
|
||||
const userMessage = context.value
|
||||
? `[Context]\n${context.value}\n\n[Text to Translate]\n${sourceText.value}`
|
||||
: `[Text to Translate]\n${sourceText.value}`;
|
||||
const userMessage = buildSingleTranslationUserPrompt(sourceText.value, context.value);
|
||||
|
||||
const requestBody = {
|
||||
const requestBody: TranslationPayload = {
|
||||
model: settings.modelName,
|
||||
messages: [ { role: "system", content: systemMessage }, { role: "user", content: userMessage } ],
|
||||
stream: settings.enableStreaming
|
||||
};
|
||||
|
||||
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 });
|
||||
const response = await executeTranslationRequest({
|
||||
apiAddress: settings.apiBaseUrl,
|
||||
apiKey: settings.apiKey,
|
||||
payload: requestBody,
|
||||
logger: logsStore,
|
||||
onStreamStart: (requestId) => {
|
||||
activeStreamRequestId.value = requestId;
|
||||
},
|
||||
});
|
||||
|
||||
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;
|
||||
finalTargetText = extractAssistantContent(response);
|
||||
targetText.value = finalTargetText;
|
||||
}
|
||||
|
||||
currentHistoryId.value = settings.addHistory({
|
||||
currentHistoryId.value = historyStore.addHistory({
|
||||
sourceLang: { ...sourceLang.value },
|
||||
targetLang: { ...targetLang.value },
|
||||
sourceText: sourceText.value,
|
||||
@@ -295,11 +284,10 @@ const translate = async () => {
|
||||
modelName: settings.modelName
|
||||
});
|
||||
} catch (err: any) {
|
||||
const errorMsg = String(err);
|
||||
settings.addLog('error', errorMsg);
|
||||
targetText.value = `Error: ${errorMsg}`;
|
||||
targetText.value = `Error: ${String(err)}`;
|
||||
} finally {
|
||||
isTranslating.value = false;
|
||||
activeStreamRequestId.value = null;
|
||||
}
|
||||
|
||||
if (settings.enableEvaluation) await evaluateTranslation();
|
||||
@@ -656,4 +644,4 @@ const translate = async () => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
89
src/domain/translation.ts
Normal file
89
src/domain/translation.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
export interface Language {
|
||||
displayName: string;
|
||||
englishName: string;
|
||||
code: string;
|
||||
}
|
||||
|
||||
export const LANGUAGES: Language[] = [
|
||||
{ displayName: '中文(简体)', englishName: 'Simplified Chinese', code: 'zh-Hans' },
|
||||
{ displayName: '中文(繁体)', englishName: 'Traditional Chinese', code: 'zh-Hant' },
|
||||
{ displayName: '英语(美国)', englishName: 'American English', code: 'en-US' },
|
||||
{ displayName: '英语(英国)', englishName: 'British English', code: 'en-GB' },
|
||||
{ displayName: '西班牙语', englishName: 'Spanish', code: 'es' },
|
||||
{ displayName: '葡萄牙语', englishName: 'Portuguese', code: 'pt' },
|
||||
{ displayName: '日语', englishName: 'Japanese', code: 'ja' },
|
||||
{ displayName: '韩语', englishName: 'Korean', code: 'ko' },
|
||||
{ displayName: '法语', englishName: 'French', code: 'fr' },
|
||||
{ displayName: '德语', englishName: 'German', code: 'de' },
|
||||
{ displayName: '意大利语', englishName: 'Italian', code: 'it' },
|
||||
{ displayName: '俄语', englishName: 'Russian', code: 'ru' },
|
||||
{ displayName: '越南语', englishName: 'Vietnamese', code: 'vi' },
|
||||
{ displayName: '泰语', englishName: 'Thai', code: 'th' },
|
||||
{ displayName: '阿拉伯语', englishName: 'Arabic', code: 'ar' },
|
||||
];
|
||||
|
||||
export const SPEAKER_IDENTITY_OPTIONS = [
|
||||
{ label: '男性', value: 'Male' },
|
||||
{ label: '女性', value: 'Female' },
|
||||
{ label: '中性', value: 'Gender-neutral' },
|
||||
] as const;
|
||||
|
||||
export const TONE_REGISTER_OPTIONS = [
|
||||
{ label: '自动识别', value: 'Auto-detect', description: '分析并保持原文的语气、情绪和礼貌程度' },
|
||||
{ label: '正式专业', value: 'Formal & Professional', description: '商务邮件、法律合同、官方报告' },
|
||||
{ label: '礼貌客气', value: 'Polite & Respectful', description: '与长辈、客户或初次见面的人交流' },
|
||||
{ label: '礼貌随和', value: 'Polite & Conversational', description: '得体但不刻板的日常对话' },
|
||||
{ label: '中性标准', value: 'Neutral & Standard', description: '维基百科、说明书、客观的新闻报道' },
|
||||
{ label: '非正式', value: 'Casual & Informal', description: '朋友聊天、社交媒体、非正式简讯' },
|
||||
{ label: '亲切友好', value: 'Warm & Friendly', description: '社区信函、给朋友的建议、温馨提示' },
|
||||
{ label: '严谨权威', value: 'Strict & Authoritative', description: '警示标志、强制规定、上级指令' },
|
||||
{ label: '热情生动', value: 'Enthusiastic & Vivid', description: '广告文案、旅游推荐、博主推文' },
|
||||
] as const;
|
||||
|
||||
export interface ApiProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
apiBaseUrl: string;
|
||||
apiKey: string;
|
||||
modelName: string;
|
||||
}
|
||||
|
||||
export interface HistoryItem {
|
||||
id: string;
|
||||
timestamp: string;
|
||||
sourceLang: Language;
|
||||
targetLang: Language;
|
||||
sourceText: string;
|
||||
targetText: string;
|
||||
context: string;
|
||||
speakerIdentity: string;
|
||||
toneRegister: string;
|
||||
modelName: string;
|
||||
}
|
||||
|
||||
export interface Participant {
|
||||
name: string;
|
||||
gender: string;
|
||||
language: Language;
|
||||
tone: string;
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
id: string;
|
||||
sender: 'me' | 'partner';
|
||||
original: string;
|
||||
translated: string;
|
||||
timestamp: string;
|
||||
evaluation?: string;
|
||||
isEvaluating?: boolean;
|
||||
isRefining?: boolean;
|
||||
}
|
||||
|
||||
export interface ChatSession {
|
||||
id: string;
|
||||
title: string;
|
||||
me: Participant;
|
||||
partner: Participant;
|
||||
messages: ChatMessage[];
|
||||
lastActivity: string;
|
||||
}
|
||||
103
src/lib/prompt-builders.ts
Normal file
103
src/lib/prompt-builders.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import type { Language, Participant } from '../domain/translation';
|
||||
|
||||
interface SingleTranslationPromptContext {
|
||||
sourceLang: Language;
|
||||
targetLang: Language;
|
||||
speakerIdentity: string;
|
||||
toneRegister: string;
|
||||
context: string;
|
||||
}
|
||||
|
||||
interface ConversationPromptContext {
|
||||
me: Participant;
|
||||
partner: Participant;
|
||||
historyBlock: string;
|
||||
senderName: string;
|
||||
fromLang: Language;
|
||||
toLang: Language;
|
||||
targetTone: string;
|
||||
}
|
||||
|
||||
function replaceTokens(template: string, values: Record<string, string>) {
|
||||
return Object.entries(values).reduce(
|
||||
(result, [key, value]) => result.replace(new RegExp(`\\{${key}\\}`, 'g'), value),
|
||||
template,
|
||||
);
|
||||
}
|
||||
|
||||
export function buildSingleTranslationSystemPrompt(
|
||||
template: string,
|
||||
context: Omit<SingleTranslationPromptContext, 'context'>,
|
||||
) {
|
||||
return replaceTokens(template, {
|
||||
SOURCE_LANG: context.sourceLang.englishName,
|
||||
SOURCE_CODE: context.sourceLang.code,
|
||||
TARGET_LANG: context.targetLang.englishName,
|
||||
TARGET_CODE: context.targetLang.code,
|
||||
SPEAKER_IDENTITY: context.speakerIdentity,
|
||||
TONE_REGISTER: context.toneRegister,
|
||||
});
|
||||
}
|
||||
|
||||
export function buildSingleEvaluationSystemPrompt(
|
||||
template: string,
|
||||
context: SingleTranslationPromptContext,
|
||||
) {
|
||||
return replaceTokens(template, {
|
||||
SOURCE_LANG: context.sourceLang.englishName,
|
||||
TARGET_LANG: context.targetLang.englishName,
|
||||
SPEAKER_IDENTITY: context.speakerIdentity,
|
||||
TONE_REGISTER: context.toneRegister,
|
||||
CONTEXT: context.context || 'None',
|
||||
});
|
||||
}
|
||||
|
||||
export function buildSingleRefinementSystemPrompt(
|
||||
template: string,
|
||||
context: SingleTranslationPromptContext,
|
||||
) {
|
||||
return buildSingleEvaluationSystemPrompt(template, context);
|
||||
}
|
||||
|
||||
export function buildSingleTranslationUserPrompt(sourceText: string, context: string) {
|
||||
return context
|
||||
? `[Context]\n${context}\n\n[Text to Translate]\n${sourceText}`
|
||||
: `[Text to Translate]\n${sourceText}`;
|
||||
}
|
||||
|
||||
export function buildSingleEvaluationUserPrompt(sourceText: string, targetText: string) {
|
||||
return `[Source Text]\n${sourceText}\n\n[Translated Text]\n${targetText}`;
|
||||
}
|
||||
|
||||
export function buildSingleRefinementUserPrompt(sourceText: string, currentTranslation: string, suggestions: string[]) {
|
||||
const formattedSuggestions = suggestions.map((text, index) => `${index + 1}. ${text}`).join('\n');
|
||||
return `[Source Text]\n${sourceText}\n\n[Current Translation]\n${currentTranslation}\n\n[User Feedback]\n${formattedSuggestions}`;
|
||||
}
|
||||
|
||||
export function buildConversationSystemPrompt(template: string, context: ConversationPromptContext, emptyHistoryFallback: string) {
|
||||
return replaceTokens(template, {
|
||||
ME_NAME: context.me.name,
|
||||
ME_GENDER: context.me.gender,
|
||||
ME_LANG: context.me.language.englishName,
|
||||
PART_NAME: context.partner.name,
|
||||
PART_GENDER: context.partner.gender,
|
||||
PART_LANG: context.partner.language.englishName,
|
||||
HISTORY_BLOCK: context.historyBlock || emptyHistoryFallback,
|
||||
SENDER_NAME: context.senderName,
|
||||
FROM_LANG: context.fromLang.englishName,
|
||||
TO_LANG: context.toLang.englishName,
|
||||
TARGET_TONE: context.targetTone,
|
||||
});
|
||||
}
|
||||
|
||||
export function buildConversationTranslationUserPrompt(text: string) {
|
||||
return `[Text to Translate]\n${text}`;
|
||||
}
|
||||
|
||||
export function buildConversationEvaluationUserPrompt(sourceText: string, currentTranslation: string) {
|
||||
return `[Source Text]\n${sourceText}\n\n[Current Translation]\n${currentTranslation}`;
|
||||
}
|
||||
|
||||
export function buildConversationRefinementUserPrompt(sourceText: string, currentTranslation: string, suggestions: string[]) {
|
||||
return `[Source Text]\n${sourceText}\n\n[Current Translation]\n${currentTranslation}\n\n[Suggestions]\n${suggestions.map((text) => `- ${text}`).join('\n')}`;
|
||||
}
|
||||
164
src/lib/translation-service.ts
Normal file
164
src/lib/translation-service.ts
Normal file
@@ -0,0 +1,164 @@
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import type { ApiProfile } from '../domain/translation';
|
||||
|
||||
interface Message {
|
||||
role: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface TranslationPayload {
|
||||
model: string;
|
||||
messages: Message[];
|
||||
stream: boolean;
|
||||
}
|
||||
|
||||
export interface TranslationChunkEvent {
|
||||
request_id: string;
|
||||
chunk: string;
|
||||
}
|
||||
|
||||
export interface EvaluationSuggestion {
|
||||
id: number;
|
||||
text: string;
|
||||
importance: number;
|
||||
}
|
||||
|
||||
export interface EvaluationResult {
|
||||
score: number;
|
||||
analysis: string;
|
||||
suggestions: EvaluationSuggestion[];
|
||||
}
|
||||
|
||||
export interface ModelConfig {
|
||||
apiBaseUrl: string;
|
||||
apiKey: string;
|
||||
modelName: string;
|
||||
}
|
||||
|
||||
type LogType = 'request' | 'response' | 'error';
|
||||
|
||||
interface Logger {
|
||||
addLog: (type: LogType, content: any, curl?: string) => void;
|
||||
}
|
||||
|
||||
interface ExecuteTranslationRequestOptions {
|
||||
apiAddress: string;
|
||||
apiKey: string;
|
||||
payload: TranslationPayload;
|
||||
logger: Logger;
|
||||
logType?: string;
|
||||
onStreamStart?: (requestId: string) => void;
|
||||
}
|
||||
|
||||
const FALLBACK_EVALUATION_RESULT: EvaluationResult = {
|
||||
score: 0,
|
||||
analysis: '无法解析审计结果,请查看日志',
|
||||
suggestions: [],
|
||||
};
|
||||
|
||||
export function resolveModelConfig(
|
||||
primary: ModelConfig,
|
||||
profiles: ApiProfile[],
|
||||
profileId: string | null,
|
||||
): ModelConfig {
|
||||
if (!profileId) return primary;
|
||||
|
||||
const profile = profiles.find((item) => item.id === profileId);
|
||||
if (!profile) return primary;
|
||||
|
||||
return {
|
||||
apiBaseUrl: profile.apiBaseUrl,
|
||||
apiKey: profile.apiKey,
|
||||
modelName: profile.modelName,
|
||||
};
|
||||
}
|
||||
|
||||
export function generateCurl(apiBaseUrl: string, apiKey: string, body: TranslationPayload) {
|
||||
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)}'`;
|
||||
}
|
||||
|
||||
export async function executeTranslationRequest({
|
||||
apiAddress,
|
||||
apiKey,
|
||||
payload,
|
||||
logger,
|
||||
logType,
|
||||
onStreamStart,
|
||||
}: ExecuteTranslationRequestOptions) {
|
||||
const requestId = crypto.randomUUID();
|
||||
const requestLog = logType ? { type: logType, ...payload } : payload;
|
||||
|
||||
logger.addLog('request', requestLog, generateCurl(apiAddress, apiKey, payload));
|
||||
|
||||
try {
|
||||
if (payload.stream) onStreamStart?.(requestId);
|
||||
|
||||
const response = await invoke<string>('translate', {
|
||||
apiAddress,
|
||||
apiKey,
|
||||
payload,
|
||||
requestId,
|
||||
});
|
||||
|
||||
logger.addLog('response', payload.stream ? response : safeParseJson(response) ?? response);
|
||||
return response;
|
||||
} catch (error) {
|
||||
logger.addLog('error', String(error));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function safeParseJson(value: string) {
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function extractAssistantContent(response: string) {
|
||||
const parsed = safeParseJson(response);
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
return (parsed as any).choices?.[0]?.message?.content || response;
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
export function tryParseEvaluationResult(raw?: string) {
|
||||
if (!raw) {
|
||||
return {
|
||||
ok: false as const,
|
||||
error: 'Evaluation result is empty',
|
||||
result: FALLBACK_EVALUATION_RESULT,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
let cleanStr = raw.trim();
|
||||
if (cleanStr.startsWith('```')) {
|
||||
cleanStr = cleanStr.replace(/^```[a-zA-Z]*\n?/, '').replace(/\n?```$/, '').trim();
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(cleanStr);
|
||||
return {
|
||||
ok: true as const,
|
||||
result: {
|
||||
score: Number(parsed.score) || 0,
|
||||
analysis: typeof parsed.analysis === 'string' ? parsed.analysis : '',
|
||||
suggestions: Array.isArray(parsed.suggestions) ? parsed.suggestions : [],
|
||||
} satisfies EvaluationResult,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false as const,
|
||||
error: `Failed to parse evaluation JSON: ${String(error)}`,
|
||||
result: FALLBACK_EVALUATION_RESULT,
|
||||
};
|
||||
}
|
||||
}
|
||||
86
src/stores/conversation.ts
Normal file
86
src/stores/conversation.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { useLocalStorage } from '@vueuse/core';
|
||||
import type { ChatMessage, ChatSession, Participant } from '../domain/translation';
|
||||
|
||||
function formatTimestamp() {
|
||||
const now = new Date();
|
||||
return `${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')}`;
|
||||
}
|
||||
|
||||
export const useConversationStore = defineStore('conversation', () => {
|
||||
const chatSessions = useLocalStorage<ChatSession[]>('chat-sessions-v1', []);
|
||||
const activeSessionId = useLocalStorage<string | null>('active-session-id-v1', null);
|
||||
|
||||
const createSession = (me: Participant, partner: Participant) => {
|
||||
const id = crypto.randomUUID();
|
||||
const timestamp = formatTimestamp();
|
||||
|
||||
const newSession: ChatSession = {
|
||||
id,
|
||||
title: `${partner.name} 的对话`,
|
||||
me,
|
||||
partner,
|
||||
messages: [],
|
||||
lastActivity: timestamp,
|
||||
};
|
||||
|
||||
chatSessions.value.unshift(newSession);
|
||||
activeSessionId.value = id;
|
||||
return id;
|
||||
};
|
||||
|
||||
const deleteSession = (id: string) => {
|
||||
chatSessions.value = chatSessions.value.filter((session) => session.id !== id);
|
||||
if (activeSessionId.value === id) {
|
||||
activeSessionId.value = chatSessions.value[0]?.id || null;
|
||||
}
|
||||
};
|
||||
|
||||
const addMessageToSession = (sessionId: string, sender: 'me' | 'partner', original: string, translated = '') => {
|
||||
const session = chatSessions.value.find((item) => item.id === sessionId);
|
||||
if (!session) return null;
|
||||
|
||||
const timestamp = formatTimestamp();
|
||||
const newMessage: ChatMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
sender,
|
||||
original,
|
||||
translated,
|
||||
timestamp,
|
||||
};
|
||||
|
||||
session.messages.push(newMessage);
|
||||
session.lastActivity = timestamp;
|
||||
|
||||
const index = chatSessions.value.findIndex((item) => item.id === sessionId);
|
||||
if (index > 0) {
|
||||
const [current] = chatSessions.value.splice(index, 1);
|
||||
chatSessions.value.unshift(current);
|
||||
}
|
||||
|
||||
return newMessage.id;
|
||||
};
|
||||
|
||||
const updateChatMessage = (sessionId: string, messageId: string, updates: Partial<ChatMessage>) => {
|
||||
const session = chatSessions.value.find((item) => item.id === sessionId);
|
||||
const message = session?.messages.find((item) => item.id === messageId);
|
||||
if (message) Object.assign(message, updates);
|
||||
};
|
||||
|
||||
const deleteChatMessage = (sessionId: string, messageId: string) => {
|
||||
const session = chatSessions.value.find((item) => item.id === sessionId);
|
||||
if (session) {
|
||||
session.messages = session.messages.filter((item) => item.id !== messageId);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
chatSessions,
|
||||
activeSessionId,
|
||||
createSession,
|
||||
deleteSession,
|
||||
addMessageToSession,
|
||||
updateChatMessage,
|
||||
deleteChatMessage,
|
||||
};
|
||||
});
|
||||
51
src/stores/history.ts
Normal file
51
src/stores/history.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { useLocalStorage } from '@vueuse/core';
|
||||
import type { HistoryItem } from '../domain/translation';
|
||||
|
||||
function formatTimestamp() {
|
||||
const now = new Date();
|
||||
return `${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')}`;
|
||||
}
|
||||
|
||||
export const useHistoryStore = defineStore('history', () => {
|
||||
const history = useLocalStorage<HistoryItem[]>('translation-history-v1', []);
|
||||
|
||||
const addHistory = (item: Omit<HistoryItem, 'id' | 'timestamp'>) => {
|
||||
const id = crypto.randomUUID();
|
||||
|
||||
history.value.unshift({
|
||||
...item,
|
||||
id,
|
||||
timestamp: formatTimestamp(),
|
||||
});
|
||||
|
||||
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((item) => item.id === id);
|
||||
if (index !== -1) {
|
||||
history.value[index] = { ...history.value[index], ...updates };
|
||||
}
|
||||
};
|
||||
|
||||
const deleteHistoryItem = (id: string) => {
|
||||
history.value = history.value.filter((item) => item.id !== id);
|
||||
};
|
||||
|
||||
const clearHistory = () => {
|
||||
history.value = [];
|
||||
};
|
||||
|
||||
return {
|
||||
history,
|
||||
addHistory,
|
||||
updateHistoryItem,
|
||||
deleteHistoryItem,
|
||||
clearHistory,
|
||||
};
|
||||
});
|
||||
41
src/stores/logs.ts
Normal file
41
src/stores/logs.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { ref } from 'vue';
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
export interface LogEntry {
|
||||
id: string;
|
||||
timestamp: string;
|
||||
type: 'request' | 'response' | 'error';
|
||||
content: any;
|
||||
curl?: string;
|
||||
}
|
||||
|
||||
function createTimestamp() {
|
||||
const now = new Date();
|
||||
return `${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')}`;
|
||||
}
|
||||
|
||||
export const useLogsStore = defineStore('logs', () => {
|
||||
const logs = ref<LogEntry[]>([]);
|
||||
|
||||
const addLog = (type: LogEntry['type'], content: any, curl?: string) => {
|
||||
logs.value.unshift({
|
||||
id: crypto.randomUUID(),
|
||||
timestamp: createTimestamp(),
|
||||
type,
|
||||
content,
|
||||
curl,
|
||||
});
|
||||
|
||||
if (logs.value.length > 50) logs.value.pop();
|
||||
};
|
||||
|
||||
const clearLogs = () => {
|
||||
logs.value = [];
|
||||
};
|
||||
|
||||
return {
|
||||
logs,
|
||||
addLog,
|
||||
clearLogs,
|
||||
};
|
||||
});
|
||||
@@ -1,48 +1,7 @@
|
||||
import { ref, computed } from 'vue';
|
||||
import { computed } from 'vue';
|
||||
import { defineStore } from 'pinia';
|
||||
import { useLocalStorage } from '@vueuse/core';
|
||||
|
||||
export interface Language {
|
||||
displayName: string; // UI 显示的中文名,如 "英语(英国)"
|
||||
englishName: string; // 文件中的第二列,用于 {SOURCE_LANG}
|
||||
code: string; // 文件中的第一列,用于 {SOURCE_CODE}
|
||||
}
|
||||
|
||||
export const LANGUAGES: Language[] = [
|
||||
{ displayName: '中文(简体)', englishName: 'Simplified Chinese', code: 'zh-Hans' },
|
||||
{ displayName: '中文(繁体)', englishName: 'Traditional Chinese', code: 'zh-Hant' },
|
||||
{ displayName: '英语(美国)', englishName: 'American English', code: 'en-US' },
|
||||
{ displayName: '英语(英国)', englishName: 'British English', code: 'en-GB' },
|
||||
{ displayName: '西班牙语', englishName: 'Spanish', code: 'es' },
|
||||
{ displayName: '葡萄牙语', englishName: 'Portuguese', code: 'pt' },
|
||||
{ displayName: '日语', englishName: 'Japanese', code: 'ja' },
|
||||
{ displayName: '韩语', englishName: 'Korean', code: 'ko' },
|
||||
{ displayName: '法语', englishName: 'French', code: 'fr' },
|
||||
{ displayName: '德语', englishName: 'German', code: 'de' },
|
||||
{ displayName: '意大利语', englishName: 'Italian', code: 'it' },
|
||||
{ displayName: '俄语', englishName: 'Russian', code: 'ru' },
|
||||
{ displayName: '越南语', englishName: 'Vietnamese', code: 'vi' },
|
||||
{ displayName: '泰语', englishName: 'Thai', code: 'th' },
|
||||
{ displayName: '阿拉伯语', englishName: 'Arabic', code: 'ar' },
|
||||
];
|
||||
|
||||
export const SPEAKER_IDENTITY_OPTIONS = [
|
||||
{ label: '男性', value: 'Male' },
|
||||
{ label: '女性', value: 'Female' },
|
||||
{ label: '中性', value: 'Gender-neutral' },
|
||||
];
|
||||
|
||||
export const TONE_REGISTER_OPTIONS = [
|
||||
{ label: '自动识别', value: 'Auto-detect', description: '分析并保持原文的语气、情绪和礼貌程度' },
|
||||
{ label: '正式专业', value: 'Formal & Professional', description: '商务邮件、法律合同、官方报告' },
|
||||
{ label: '礼貌客气', value: 'Polite & Respectful', description: '与长辈、客户或初次见面的人交流' },
|
||||
{ label: '礼貌随和', value: 'Polite & Conversational', description: '得体但不刻板的日常对话' },
|
||||
{ label: '中性标准', value: 'Neutral & Standard', description: '维基百科、说明书、客观的新闻报道' },
|
||||
{ label: '非正式', value: 'Casual & Informal', description: '朋友聊天、社交媒体、非正式简讯' },
|
||||
{ label: '亲切友好', value: 'Warm & Friendly', description: '社区信函、给朋友的建议、温馨提示' },
|
||||
{ label: '严谨权威', value: 'Strict & Authoritative', description: '警示标志、强制规定、上级指令' },
|
||||
{ label: '热情生动', value: 'Enthusiastic & Vivid', description: '广告文案、旅游推荐、博主推文' },
|
||||
];
|
||||
import { LANGUAGES, SPEAKER_IDENTITY_OPTIONS, TONE_REGISTER_OPTIONS, type ApiProfile, type Language } from '../domain/translation';
|
||||
|
||||
export const DEFAULT_TEMPLATE = `You are a professional {SOURCE_LANG} ({SOURCE_CODE}) to {TARGET_LANG} ({TARGET_CODE}) translator. Your goal is to accurately convey the meaning and nuances of the original {SOURCE_LANG} text while adhering to {TARGET_LANG} grammar, vocabulary, and cultural sensitivities.
|
||||
|
||||
@@ -106,98 +65,54 @@ export const DEFAULT_REFINEMENT_TEMPLATE = `You are a senior translation editor.
|
||||
4. If a piece of feedback contradicts the [Source Text], prioritize accuracy and provide a balanced refinement.
|
||||
5. Produce ONLY the refined {TARGET_LANG} translation, without any additional explanations, notes, or commentary.`;
|
||||
|
||||
export interface ApiProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
apiBaseUrl: string;
|
||||
apiKey: string;
|
||||
modelName: string;
|
||||
}
|
||||
export const CONVERSATION_SYSTEM_PROMPT_TEMPLATE = `# Role: Professional Real-time Conversation Translator
|
||||
|
||||
export interface HistoryItem {
|
||||
id: string;
|
||||
timestamp: string;
|
||||
sourceLang: Language;
|
||||
targetLang: Language;
|
||||
sourceText: string;
|
||||
targetText: string;
|
||||
context: string;
|
||||
speakerIdentity: string;
|
||||
toneRegister: string;
|
||||
modelName: string;
|
||||
}
|
||||
# Participants:
|
||||
- Participant A: [Name: {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}]
|
||||
- Participant B: [Name: {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}]
|
||||
|
||||
export interface Participant {
|
||||
name: string;
|
||||
gender: string;
|
||||
language: Language;
|
||||
tone: string;
|
||||
}
|
||||
|
||||
export interface ChatMessage {
|
||||
id: string;
|
||||
sender: 'me' | 'partner';
|
||||
original: string;
|
||||
translated: string;
|
||||
timestamp: string;
|
||||
evaluation?: string; // AI 审计结果 (JSON 字符串)
|
||||
isEvaluating?: boolean; // 审计状态
|
||||
isRefining?: boolean; // 润色状态
|
||||
}
|
||||
|
||||
export interface ChatSession {
|
||||
id: string;
|
||||
title: string;
|
||||
me: Participant;
|
||||
partner: Participant;
|
||||
messages: ChatMessage[];
|
||||
lastActivity: string;
|
||||
}
|
||||
|
||||
export const CONVERSATION_SYSTEM_PROMPT_TEMPLATE = `You are a professional real-time conversation translator.
|
||||
Current Context:
|
||||
- Role A (Me): {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}.
|
||||
- Role B (Other): {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}.
|
||||
|
||||
[Conversation History]
|
||||
# Recent Conversation Flow:
|
||||
{HISTORY_BLOCK}
|
||||
|
||||
[Current Task]
|
||||
Translate the incoming text from {FROM_LANG} to {TO_LANG}.
|
||||
# Current Turn to Translate:
|
||||
- Speaker: {SENDER_NAME}
|
||||
- Source Language: {FROM_LANG}
|
||||
- Target Language: {TO_LANG}
|
||||
- Intended Tone/Register: {TARGET_TONE}
|
||||
|
||||
[Constraints]
|
||||
# Constraints
|
||||
1. Contextual Awareness: Use the [Conversation History] to resolve pronouns (it, that, etc.) and maintain consistency.
|
||||
2. Tone & Register:
|
||||
- If translating for 'Me', strictly use the tone: {MY_TONE}.
|
||||
- If translating for 'Other', auto-detect and preserve their original tone/emotion.
|
||||
2. Personalization & Tone: Ensure all grammatical agreements and self-referential terms reflect speaker's gender. Faithfully replicate the intended tone, maintaining the formality, emotional nuance, and unique style of the source text without neutralizing it.
|
||||
3. Natural Flow: Keep the translation concise and natural for a chat environment. Avoid "translationese".
|
||||
4. Strictly avoid over-translation: Do not add extra information not present in the source text.
|
||||
5. Output ONLY the translated text, no explanations.`;
|
||||
|
||||
export const CONVERSATION_EVALUATION_PROMPT_TEMPLATE = `# Role: Expert Conversation Auditor
|
||||
|
||||
# Context Info
|
||||
- Role A (Me): {ME_NAME} ({ME_GENDER}, Native {ME_LANG})
|
||||
- Role B (Other): {PART_NAME} ({PART_GENDER}, Native {PART_LANG})
|
||||
# Participants:
|
||||
- Participant A: [Name: {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}]
|
||||
- Participant B: [Name: {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}]
|
||||
|
||||
# Recent Conversation Flow (Original Messages Only):
|
||||
# Recent Conversation Flow:
|
||||
{HISTORY_BLOCK}
|
||||
|
||||
# Current Turn to Audit:
|
||||
- Speaker: {SENDER_NAME}
|
||||
- Direction: {FROM_LANG} -> {TO_LANG}
|
||||
- Source Text ({FROM_LANG}): {ORIGINAL_TEXT}
|
||||
- Translation ({TO_LANG}): {CURRENT_TRANSLATION}
|
||||
- Source Language: {FROM_LANG}
|
||||
- Target Language: {TO_LANG}
|
||||
- Intended Tone/Register: {TARGET_TONE}
|
||||
|
||||
# Audit Priorities
|
||||
1. **Contextual Accuracy**: Does the translation correctly reflect the meaning based on the [Recent Conversation Flow]?
|
||||
2. **Relational Tone**:
|
||||
- If the Speaker is 'Me', does it match the target tone({TARGET_TONE})?
|
||||
- If the Speaker is 'Other', does it preserve their original tone/emotion?
|
||||
3. **Naturalness**: Is it concise and fit for an IM (Instant Messaging) environment?
|
||||
# Audit Criteria
|
||||
1. **Contextual Inaccuracy**: Failure to correctly reflect the meaning based on the [Recent Conversation Flow]
|
||||
2. **Semantic Error**: Objective misalignment with the source meaning or complete hallucinations.
|
||||
3. **Grammatical Error**: Clear violations of target language grammar or syntax rules.
|
||||
4. **Tone Failure**: A tone that is the opposite or significantly different from the [Intended Tone/Register].
|
||||
5. **Poor Readability**: The phrasing is so stiff, unnatural, or convoluted that it hinders smooth comprehension (e.g., obvious "translationese" or broken logic).
|
||||
|
||||
**Note**: Do NOT penalize if the translation is simply "not the most elegant" or if there's a subjective preference for a different synonym. If it's natural enough for a native speaker to understand without effort, it's acceptable.
|
||||
|
||||
# Instructions
|
||||
1. **Evaluation**: Compare the [Source Text] and [Translation] based on the [Audit Priorities].
|
||||
1. **Evaluation**: Compare the [Source Text] and [Translation] based on the [Audit Criteria].
|
||||
2. **Scoring Strategy**:
|
||||
- **90-100**: Accurate, grammatically sound, and flows naturally.
|
||||
- **75-89**: Accurate meaning, but suffers from "stiff" phrasing or minor flow issues that need adjustment.
|
||||
@@ -217,26 +132,23 @@ Respond ONLY in JSON. "analysis" and "text" MUST be in Simplified Chinese:
|
||||
|
||||
export const CONVERSATION_REFINEMENT_PROMPT_TEMPLATE = `# Role: Professional Conversation Editor
|
||||
|
||||
# Context:
|
||||
- Role A (Me): {ME_NAME} ({ME_GENDER}, Native {ME_LANG})
|
||||
- Role B (Other): {PART_NAME} ({PART_GENDER}, Native {PART_LANG})
|
||||
# Participants:
|
||||
- Participant A: [Name: {ME_NAME}, Gender: {ME_GENDER}, Language: {ME_LANG}]
|
||||
- Participant B: [Name: {PART_NAME}, Gender: {PART_GENDER}, Language: {PART_LANG}]
|
||||
|
||||
# Recent Conversation Flow (Original Messages Only):
|
||||
# Recent Conversation Flow:
|
||||
{HISTORY_BLOCK}
|
||||
|
||||
# Current Turn to Refine:
|
||||
- Speaker: {SENDER_NAME}
|
||||
- Direction: {FROM_LANG} -> {TO_LANG}
|
||||
- Source Text ({FROM_LANG}): {ORIGINAL_TEXT}
|
||||
- Current Translation ({TO_LANG}): {CURRENT_TRANSLATION}
|
||||
|
||||
# Suggestions to Apply:
|
||||
{SUGGESTIONS}
|
||||
- Source Language: {FROM_LANG}
|
||||
- Target Language: {TO_LANG}
|
||||
- Intended Tone/Register: {TARGET_TONE}
|
||||
|
||||
# Instructions:
|
||||
1. Carefully review the [Suggestions] and apply the requested improvements to the [Current Translation] while ensuring it fits naturally into the [Recent Conversation Flow].
|
||||
2. Ensure that the refined translation remains semantically identical to the [Source Text].
|
||||
3. If the Speaker is 'Me', strictly maintain the target tone({TARGET_TONE}); if the Speaker is 'Other', auto-detect and preserve their original tone/emotion.
|
||||
3. Maintain the speaker's gender and [Intended Tone/Register] as specified.
|
||||
4. If a piece of feedback contradicts the [Source Text], prioritize accuracy and provide a balanced refinement.
|
||||
5. Produce ONLY the refined {TO_LANG} translation, without any additional explanations, notes, or commentary.`;
|
||||
|
||||
@@ -276,126 +188,6 @@ 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; curl?: string }[]>([]);
|
||||
const history = useLocalStorage<HistoryItem[]>('translation-history-v1', []);
|
||||
|
||||
// 对话模式状态
|
||||
const chatSessions = useLocalStorage<ChatSession[]>('chat-sessions-v1', []);
|
||||
const activeSessionId = useLocalStorage<string | null>('active-session-id-v1', null);
|
||||
|
||||
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')}`;
|
||||
|
||||
logs.value.unshift({
|
||||
id: crypto.randomUUID(),
|
||||
timestamp,
|
||||
type,
|
||||
content,
|
||||
curl
|
||||
});
|
||||
if (logs.value.length > 50) logs.value.pop(); // 稍微增加日志保留数量
|
||||
};
|
||||
|
||||
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,
|
||||
timestamp
|
||||
});
|
||||
|
||||
// 限制 100 条
|
||||
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 };
|
||||
}
|
||||
};
|
||||
|
||||
// 对话模式方法
|
||||
const createSession = (me: Participant, partner: Participant) => {
|
||||
const id = crypto.randomUUID();
|
||||
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 newSession: ChatSession = {
|
||||
id,
|
||||
title: `${partner.name} 的对话`,
|
||||
me,
|
||||
partner,
|
||||
messages: [],
|
||||
lastActivity: timestamp
|
||||
};
|
||||
|
||||
chatSessions.value.unshift(newSession);
|
||||
activeSessionId.value = id;
|
||||
return id;
|
||||
};
|
||||
|
||||
const deleteSession = (id: string) => {
|
||||
chatSessions.value = chatSessions.value.filter(s => s.id !== id);
|
||||
if (activeSessionId.value === id) {
|
||||
activeSessionId.value = chatSessions.value[0]?.id || null;
|
||||
}
|
||||
};
|
||||
|
||||
const addMessageToSession = (sessionId: string, sender: 'me' | 'partner', original: string, translated: string = '') => {
|
||||
const session = chatSessions.value.find(s => s.id === sessionId);
|
||||
if (session) {
|
||||
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 newMessage: ChatMessage = {
|
||||
id: crypto.randomUUID(),
|
||||
sender,
|
||||
original,
|
||||
translated,
|
||||
timestamp
|
||||
};
|
||||
|
||||
session.messages.push(newMessage);
|
||||
session.lastActivity = timestamp;
|
||||
|
||||
// 将活跃会话移至顶部
|
||||
const index = chatSessions.value.findIndex(s => s.id === sessionId);
|
||||
if (index > 0) {
|
||||
const [s] = chatSessions.value.splice(index, 1);
|
||||
chatSessions.value.unshift(s);
|
||||
}
|
||||
|
||||
return newMessage.id;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const updateChatMessage = (sessionId: string, messageId: string, updates: Partial<ChatMessage>) => {
|
||||
const session = chatSessions.value.find(s => s.id === sessionId);
|
||||
if (session) {
|
||||
const message = session.messages.find(m => m.id === messageId);
|
||||
if (message) {
|
||||
Object.assign(message, updates);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const deleteChatMessage = (sessionId: string, messageId: string) => {
|
||||
const session = chatSessions.value.find(s => s.id === sessionId);
|
||||
if (session) {
|
||||
session.messages = session.messages.filter(m => m.id !== messageId);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
isDark,
|
||||
apiBaseUrl,
|
||||
@@ -415,17 +207,5 @@ export const useSettingsStore = defineStore('settings', () => {
|
||||
targetLang,
|
||||
speakerIdentity,
|
||||
toneRegister,
|
||||
logs,
|
||||
history,
|
||||
chatSessions,
|
||||
activeSessionId,
|
||||
addLog,
|
||||
addHistory,
|
||||
updateHistoryItem,
|
||||
createSession,
|
||||
deleteSession,
|
||||
addMessageToSession,
|
||||
updateChatMessage,
|
||||
deleteChatMessage
|
||||
};
|
||||
});
|
||||
|
||||
53
src/stores/translation-workspace.ts
Normal file
53
src/stores/translation-workspace.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { ref } from 'vue';
|
||||
import { defineStore } from 'pinia';
|
||||
import type { EvaluationResult } from '../lib/translation-service';
|
||||
|
||||
export const useTranslationWorkspaceStore = defineStore('translationWorkspace', () => {
|
||||
const sourceText = ref('');
|
||||
const context = ref('');
|
||||
const targetText = ref('');
|
||||
const isTranslating = ref(false);
|
||||
const currentHistoryId = ref<string | null>(null);
|
||||
|
||||
const evaluationResult = ref<EvaluationResult | null>(null);
|
||||
const isEvaluating = ref(false);
|
||||
const isRefining = ref(false);
|
||||
const selectedSuggestionIds = ref<number[]>([]);
|
||||
const appliedSuggestionIds = ref<number[]>([]);
|
||||
const activeStreamRequestId = ref<string | null>(null);
|
||||
|
||||
const resetEvaluationState = () => {
|
||||
evaluationResult.value = null;
|
||||
selectedSuggestionIds.value = [];
|
||||
appliedSuggestionIds.value = [];
|
||||
};
|
||||
|
||||
const clearWorkspace = () => {
|
||||
sourceText.value = '';
|
||||
targetText.value = '';
|
||||
resetEvaluationState();
|
||||
};
|
||||
|
||||
const toggleSuggestion = (id: number) => {
|
||||
const index = selectedSuggestionIds.value.indexOf(id);
|
||||
if (index > -1) selectedSuggestionIds.value.splice(index, 1);
|
||||
else selectedSuggestionIds.value.push(id);
|
||||
};
|
||||
|
||||
return {
|
||||
sourceText,
|
||||
context,
|
||||
targetText,
|
||||
isTranslating,
|
||||
currentHistoryId,
|
||||
evaluationResult,
|
||||
isEvaluating,
|
||||
isRefining,
|
||||
selectedSuggestionIds,
|
||||
appliedSuggestionIds,
|
||||
activeStreamRequestId,
|
||||
resetEvaluationState,
|
||||
clearWorkspace,
|
||||
toggleSuggestion,
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user