-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackground.js
More file actions
337 lines (300 loc) · 9.63 KB
/
Copy pathbackground.js
File metadata and controls
337 lines (300 loc) · 9.63 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
chrome.runtime.onMessage.addListener((message, _, sendResponse) => {
if (message.type === "TRANSLATE_BATCH") {
doTranslate(message.items, message.languages).then(sendResponse);
return true;
}
if (message.type === "GET_SETTINGS") {
chrome.storage.sync.get(
[
"provider",
"apiKey",
"githubToken",
"openaiKey",
"geminiKey",
"groqKey",
"openrouterKey",
],
sendResponse
);
return true;
}
});
async function doTranslate(items, languages) {
const settings = await chrome.storage.sync.get([
"provider",
"apiKey",
"githubToken",
"openaiKey",
"geminiKey",
"groqKey",
"openrouterKey",
]);
const provider = settings.provider || "anthropic";
if (provider === "openai")
return await translateWithOpenAI(items, languages, settings.openaiKey);
if (provider === "gemini")
return await translateWithGemini(items, languages, settings.geminiKey);
if (provider === "groq")
return await translateWithGroq(items, languages, settings.groqKey);
if (provider === "openrouter")
return await translateWithOpenRouter(
items,
languages,
settings.openrouterKey
);
if (provider === "github")
return await translateWithGitHub(items, languages, settings.githubToken);
return await translateWithAnthropic(items, languages, settings.apiKey);
}
async function translateWithAnthropic(items, languages, apiKey) {
if (!apiKey || apiKey.length < 10) {
return {
error:
"No Anthropic API key set. Click the extension icon (🌐) to enter your API key.",
};
}
const sourceObj = {};
items.forEach((text, i) => {
const key = textToKey(text, i);
sourceObj[key] = text;
});
const sourceJson = JSON.stringify(sourceObj, null, 2);
const prompt = buildPrompt(sourceJson, languages);
try {
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": apiKey,
"anthropic-version": "2023-06-01",
"anthropic-dangerous-direct-browser-access": "true",
},
body: JSON.stringify({
model: "claude-haiku-4-5-20251001",
max_tokens: 2048,
messages: [{ role: "user", content: prompt }],
}),
});
if (!response.ok) {
const err = await response.json();
return { error: err.error?.message || "API error. Check your API key." };
}
const data = await response.json();
const raw = data.content?.[0]?.text || "";
const clean = raw.replace(/```json|```/g, "").trim();
const parsed = JSON.parse(clean);
return { result: parsed };
} catch (e) {
return { error: `Failed: ${e.message}` };
}
}
async function translateWithGitHub(items, languages, githubToken) {
if (!githubToken || githubToken.length < 10) {
return {
error:
"No GitHub token set. Click the extension icon (🌐) to enter your token.",
};
}
const sourceObj = {};
items.forEach((text, i) => {
const key = textToKey(text, i);
sourceObj[key] = text;
});
const sourceJson = JSON.stringify(sourceObj, null, 2);
const prompt = buildPrompt(sourceJson, languages);
try {
const response = await fetch(
"https://models.inference.ai.azure.com/chat/completions",
{
method: "POST",
headers: {
Authorization: `Bearer ${githubToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-4o-mini",
messages: [{ role: "user", content: prompt }],
max_tokens: 2048,
temperature: 0.3,
}),
}
);
if (!response.ok) {
const err = await response.json();
return {
error:
err.error?.message || err.message || "API error. Check your token.",
};
}
const data = await response.json();
const raw = data.choices?.[0]?.message?.content || "";
const clean = raw.replace(/```json|```/g, "").trim();
const parsed = JSON.parse(clean);
return { result: parsed };
} catch (e) {
return { error: `Failed: ${e.message}` };
}
}
async function translateWithOpenAICompat(
items,
languages,
apiKey,
endpoint,
model,
providerName
) {
if (!apiKey || apiKey.length < 10) {
return {
error: `No ${providerName} key set. Click the extension icon (🌐) to enter your key.`,
};
}
const sourceObj = {};
items.forEach((text, i) => {
sourceObj[textToKey(text, i)] = text;
});
const prompt = buildPrompt(JSON.stringify(sourceObj, null, 2), languages);
try {
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model,
messages: [{ role: "user", content: prompt }],
max_tokens: 4096,
temperature: 0.3,
}),
});
if (!response.ok) {
const err = await response.json();
return { error: err.error?.message || err.message || "API error." };
}
const data = await response.json();
const raw = data.choices?.[0]?.message?.content || "";
const clean = raw.replace(/```json|```/g, "").trim();
return { result: JSON.parse(clean) };
} catch (e) {
return { error: `Failed: ${e.message}` };
}
}
async function translateWithOpenAI(items, languages, apiKey) {
return translateWithOpenAICompat(
items,
languages,
apiKey,
"https://api.openai.com/v1/chat/completions",
"gpt-4o-mini",
"OpenAI"
);
}
async function translateWithGroq(items, languages, apiKey) {
return translateWithOpenAICompat(
items,
languages,
apiKey,
"https://api.groq.com/openai/v1/chat/completions",
"llama-3.3-70b-versatile",
"Groq"
);
}
async function translateWithOpenRouter(items, languages, apiKey) {
return translateWithOpenAICompat(
items,
languages,
apiKey,
"https://openrouter.ai/api/v1/chat/completions",
"openai/gpt-4o-mini",
"OpenRouter"
);
}
async function translateWithGemini(items, languages, apiKey) {
if (!apiKey || apiKey.length < 10) {
return {
error:
"No Gemini key set. Click the extension icon (🌐) to enter your key.",
};
}
const sourceObj = {};
items.forEach((text, i) => {
sourceObj[textToKey(text, i)] = text;
});
const prompt = buildPrompt(JSON.stringify(sourceObj, null, 2), languages);
try {
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: { maxOutputTokens: 4096, temperature: 0.3 },
}),
}
);
if (!response.ok) {
const err = await response.json();
return { error: err.error?.message || "Gemini API error." };
}
const data = await response.json();
const raw = data.candidates?.[0]?.content?.parts?.[0]?.text || "";
const clean = raw.replace(/```json|```/g, "").trim();
return { result: JSON.parse(clean) };
} catch (e) {
return { error: `Failed: ${e.message}` };
}
}
function buildPrompt(sourceJson, languages) {
const langList = Array.isArray(languages) ? languages.join(", ") : languages;
const langStructure = Array.isArray(languages)
? languages
.map((l) => ` "${l}": { ...same keys, ${l} translated values... }`)
.join(",\n")
: ` "English": { ...same keys, English translated values... }`;
return `You are a professional localization engineer.
Translate all values in the source JSON into the following languages: ${langList}.
Source JSON (keys must be preserved exactly):
${sourceJson}
Return ONLY a valid JSON object with this exact structure:
{
"source": { ...original key-value pairs... },
"languages": {
${langStructure}
}
}
Rules:
- No markdown, no code fences, no explanation. Raw JSON only.
- Preserve every key exactly as-is.
- Keep existing placeholders like {name}, %s, {{var}} unchanged.
- If the source text is already in one of the target languages, keep it as-is for that language.
- Translate naturally and professionally.
- IMPORTANT — detect dynamic runtime values and replace them with {{placeholder}} syntax:
* Standalone leading integers or numbers followed by a noun (e.g. "1 branch", "3 tags", "10 commits") — the number MUST become {{count}}: "{{count}} branch", "{{count}} tags", "{{count}} commits"
* Proper names of people (e.g. "Nazir", "John") → {{name}}
* Company or organization names (e.g. "NAZIR DEVELOPMENT", "Acme Corp") → {{company}}
* Dates or times (e.g. "Monday", "Jan 1 2024") → {{date}}
* Any other value that is clearly injected at runtime → {{value}}
* Apply this to ALL language translations including the source.
* The raw digit must NEVER appear in the output — always replace it with {{count}}.
* Example: "1 branch" → "{{count}} branch", "3 tags" → "{{count}} tags", "100 users" → "{{count}} users"
* Example: "Hello, Nazir 👋" → "Hello, {{name}} 👋"
* Example: "Overview of NAZIR DEVELOPMENT" → "Overview of {{company}}"`;
}
function textToKey(text, index) {
const words = text
.toLowerCase()
.replace(/[^a-z0-9\s]/g, "")
.trim()
.split(/\s+/)
.filter(Boolean)
.slice(0, 8); // limit word count before slicing
if (!words.length) return `item${index + 1}`;
const camel =
words[0] +
words
.slice(1)
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
.join("");
return camel.slice(0, 40) || `item${index + 1}`;
}