-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
223 lines (196 loc) · 6.7 KB
/
background.js
File metadata and controls
223 lines (196 loc) · 6.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/**
* DeepSeek 网页翻译 - Background Service Worker
* 管理翻译 API 调用、配置、并发控制
*/
// 默认配置
const DEFAULTS = {
apiKey: '',
apiUrl: 'https://api.deepseek.com/v1/chat/completions',
targetLang: '中文',
sourceLang: 'auto',
model: 'deepseek-chat',
concurrency: 6,
mergeSize: 100,
maxMergeChars: 10000,
maxTextLength: 2000
};
// 初始化默认配置
chrome.runtime.onInstalled.addListener(async () => {
const data = await chrome.storage.sync.get(Object.keys(DEFAULTS));
const needsDefaults = {};
for (const [key, val] of Object.entries(DEFAULTS)) {
if (data[key] === undefined) needsDefaults[key] = val;
}
if (Object.keys(needsDefaults).length > 0) {
await chrome.storage.sync.set(needsDefaults);
}
});
// API 基础配置缓存(避免每次请求都读 storage)
let _apiConfig = null;
async function getApiConfig() {
if (_apiConfig) return _apiConfig;
_apiConfig = await chrome.storage.sync.get(['apiKey', 'apiUrl', 'model']);
return _apiConfig;
}
// storage 变化时清除缓存
chrome.storage.onChanged.addListener((changes) => {
if (changes.apiKey || changes.apiUrl || changes.model) {
_apiConfig = null;
}
});
/** 中文语言名 → 英文标准语言名映射 */
const LANG_MAP = {
'中文': 'Chinese',
'英文': 'English',
'日文': 'Japanese',
'韩文': 'Korean',
'法文': 'French',
'德文': 'German',
'西班牙文': 'Spanish',
'俄文': 'Russian',
'葡萄牙文': 'Portuguese',
'阿拉伯文': 'Arabic'
};
/**
* 调用 DeepSeek API 翻译一段文本
*/
async function translateOne(text, targetLang, sourceLang) {
const { apiKey, apiUrl, model } = await getApiConfig();
if (!apiKey) {
throw new Error('请先在设置中配置 DeepSeek API Key');
}
if (!text || !text.trim()) return '';
// 把中文语言名转成英文标准名给模型
const targetEn = LANG_MAP[targetLang] || targetLang;
const sourceEn = LANG_MAP[sourceLang] || sourceLang;
const sourceDesc = sourceLang === 'auto' ? '(auto-detected)' : `from ${sourceEn} (${sourceLang})`;
const systemPrompt = `You are a professional web page translator. Translate the following content ${sourceDesc} into ${targetEn} (${targetLang}).
Rules:
- Only translate text content. Do NOT modify code, URLs, HTML tags, CSS class names, or any markup.
- If a segment looks like code (programming language, command line, config, JSON, XML, SQL, pure numbers/symbols, etc.), return it AS-IS without translation.
- Preserve technical terms accurately.
- Translation should be natural and fluent in ${targetEn}.
- The input contains MULTIPLE SEGMENTS, each wrapped in markers like:
[SEGMENT_START 0]
text here
[SEGMENT_END 0]
- Translate each segment's text content, but keep the [SEGMENT_START n] and [SEGMENT_END n] markers EXACTLY as-is.
- Return ALL segments in the same order, each with its markers preserved.
- Return ONLY the translated text with markers. No explanations, notes, or extra words.`;
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: model || 'deepseek-chat',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: text }
],
temperature: 0.3,
max_tokens: 4096
})
});
if (!response.ok) {
const err = await response.text();
throw new Error(`API 请求失败 (${response.status}): ${err}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
/**
* 并发翻译 - 所有文本同时发起请求,带并发数控制
* @param {string[]} texts - 待翻译文本数组
* @param {number} concurrency - 最大并发请求数
* @param {function} onProgress - 进度回调 (completed, total)
*/
async function translateAll(texts, targetLang, sourceLang, concurrency = 6, onProgress) {
const total = texts.length;
if (total === 0) return [];
const results = new Array(total).fill(null);
let completed = 0;
// 包装单次翻译,失败时用原文兜底
async function doTranslate(index) {
try {
results[index] = await translateOne(texts[index], targetLang, sourceLang);
} catch (err) {
console.error(`[${index}] 翻译失败:`, err.message);
results[index] = texts[index]; // 失败返回原文
}
completed++;
if (onProgress) onProgress(completed, total);
}
// 并发控制:一次启动 concurrency 个请求,边完成边补充
async function worker() {
while (true) {
const idx = await nextIndex();
if (idx === -1) break;
await doTranslate(idx);
}
}
let currentIndex = 0;
let resolveNext;
let nextPromise;
function initNext() {
nextPromise = new Promise(r => { resolveNext = r; });
}
initNext();
async function nextIndex() {
const idx = currentIndex++;
if (idx < total) return idx;
return -1;
}
// 启动 workers
const workerCount = Math.min(concurrency, total);
await Promise.all(Array.from({ length: workerCount }, () => worker()));
return results;
}
// 消息处理
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
switch (request.action) {
case 'translate': // 单段翻译
translateOne(request.text, request.targetLang, request.sourceLang)
.then(r => sendResponse({ success: true, data: r }))
.catch(e => sendResponse({ success: false, error: e.message }));
return true;
case 'translateAll': // 并发翻译全部文本
(async () => {
try {
const results = await translateAll(
request.texts,
request.targetLang,
request.sourceLang,
request.concurrency || 6,
(completed, total) => {
chrome.tabs.sendMessage(sender.tab.id, {
action: 'translateProgress',
completed,
total
}).catch(() => {});
}
);
sendResponse({ success: true, data: results });
} catch (err) {
sendResponse({ success: false, error: err.message });
}
})();
return true;
case 'getConfig':
chrome.storage.sync.get(Object.keys(DEFAULTS))
.then(config => sendResponse({ success: true, data: config }))
.catch(err => sendResponse({ success: false, error: err.message }));
return true;
case 'setConfig':
chrome.storage.sync.set(request.config)
.then(() => {
_apiConfig = null;
sendResponse({ success: true });
})
.catch(err => sendResponse({ success: false, error: err.message }));
return true;
default:
sendResponse({ success: false, error: '未知操作' });
}
});