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
|
import { z } from "zod";
import type { Language, TranslationService, AsyncRes } from "../types";
import { AiTranslator } from "./aitranslation";
const JSON_HEADER = { "Content-Type": "application/json" };
export class GoogleTranslate implements TranslationService {
endpoint = "https://translate.googleapis.com/language/translate/v2";
constructor(private apiKey: string) {
if (!apiKey) throw new Error("Google Translate API key is required");
}
async call(path: string, body?: any) {
try {
const authH = {
"X-goog-api-key": this.apiKey,
};
const opts = body
? {
method: "POST",
headers: { ...authH, ...JSON_HEADER },
body: JSON.stringify(body),
}
: { headers: authH };
const response = await fetch(this.endpoint + path, opts);
if (!response.ok) {
const errorMessage = response.statusText;
throw new Error(
`Google Translate API error (${response.status}): ${errorMessage}`,
);
}
const data = await response.json();
return data;
} catch (e) {
throw new Error(`${e}`);
}
}
async translate(
text: string,
sourceLang: string,
targetLang: string,
): AsyncRes<string> {
try {
const body = {
q: text,
source: sourceLang === "auto" ? undefined : sourceLang,
target: targetLang,
format: "text",
};
const data = await this.call("", body);
console.log("google translate res", data);
if (!data.data?.translations?.[0]?.translatedText) {
return { error: "Invalid response format from Google Translate API" };
}
return { ok: data.data.translations[0].translatedText };
} catch (error) {
return { error: "Failed to connect to Google Translate API `${error}`" };
}
}
async getSupportedLanguages() {
try {
const res = await this.call("/languages");
const languageNames = new Intl.DisplayNames(["en"], { type: "language" });
// lnguages are ISO 639 or BCP-47
const set = new Set<string>();
const ret: Language[] = [];
for (let ll of res.data.languages) {
const l: { language: string } = ll;
const code = l.language;
const name = languageNames.of(code);
if (!name) continue;
if (!set.has(name)) ret.push({ code, name });
set.add(name);
}
return { ok: ret };
} catch (e) {
return { error: `${e}` };
}
}
}
export class MicrosoftTranslator implements TranslationService {
endpoint = "https://api.cognitive.microsofttranslator.com";
constructor(private apiKey: string) {
if (!apiKey) throw new Error("Microsoft Translator API key is required");
}
async translate(
text: string,
sourceLang: string,
targetLang: string,
): AsyncRes<string> {
const url = "https://api.cognitive.microsofttranslator.com";
// documents
// https://sortug.cognitiveservices.azure.com/
//
try {
const res = await this.call(
`/translate?api-version=3.0&from=${sourceLang === "auto" ? "" : sourceLang}&to=${targetLang}`,
[{ text }],
);
if (!res[0]?.translations?.[0]?.text) {
throw new Error(
"Invalid response format from Microsoft Translator API",
);
}
return { ok: res[0].translations[0].text };
} catch (error) {
return { error: "Failed to connect to Microsoft Translator API" };
}
}
async getSupportedLanguages() {
try {
const res = await this.call(`/languages?api-version=3.0`);
return {
ok: Object.entries(res.translation).map(([code, l]: any) => ({
code,
name: l.name,
nativeName: l.nativeName,
})),
};
} catch (e) {
return { error: `${e}` };
}
}
async dictionaryLookup(text: string, from: string, to: string) {
const res = await this.call(
`/Dictionary/Lookup?api-version=3.0&from=${from}&to=${to}`,
);
console.log({ res });
return res;
}
async pinyin() {
try {
const res = await this.call(`/languages?api-version=3.0`);
// return Object.entries(res.transliteration).map(([code, l]: any) => {
// return { code, ...l };
// });
return { ok: res.transliteration };
} catch (e) {
return { error: `${e}` };
}
}
async transliterate(
text: string[],
language: string,
from: string,
to: string,
) {
const body = text.map((t) => ({ Text: t }));
const url = `/transliterate?api-version=3.0&language=${language}&fromScript=${from}&toScript=${to}`;
console.log({ url, body });
try {
const res = await this.call(url, body);
return { ok: res[0].text };
} catch (e) {
return { error: `${e}` };
}
}
async call(path: string, body?: any) {
const authH = {
"Ocp-Apim-Subscription-Key": this.apiKey,
"Ocp-Apim-Subscription-Region": "southeastasia",
// "X-ClientTraceId": uuidv4().toString(),
// Authorization: `Bearer ${this.apiKey}`,
};
console.log({ authH });
const opts = body
? {
method: "POST",
headers: { ...authH, ...JSON_HEADER },
body: JSON.stringify(body),
}
: { headers: authH };
const res = await fetch(this.endpoint + path, opts);
console.log({ res });
if (!res.ok) {
const errorMessage = res.statusText;
throw new Error(
`Microsoft Translator API error (${res.status}): ${errorMessage}`,
);
}
const j = await res.json();
return j;
}
}
export class DeepLTranslator implements TranslationService {
// https://developers.deepl.com/docs/api-reference/client-libraries
// endpoint = "https://api.deepl.com/v2";
endpoint = "https://api-free.deepl.com/v2";
constructor(private apiKey: string) {
if (!apiKey) throw new Error("DeepL API key is required");
}
async call(path: string, body?: any) {
try {
const authH = {
Authorization: `DeepL-Auth-Key ${this.apiKey}`,
};
const opts = body
? {
method: "POST",
headers: { ...authH, ...JSON_HEADER },
body: JSON.stringify(body),
}
: { headers: authH };
const response = await fetch(this.endpoint + path, opts);
const data = await response.json();
if (!response.ok) {
const errorMessage = data.message || response.statusText;
throw new Error(
`DeepL API error (${response.status}): ${errorMessage}`,
);
}
return data;
} catch (error) {
if (error instanceof Error) {
throw error;
}
throw new Error("Failed to connect to DeepL API");
}
}
async translate(
text: string,
sourceLang: string,
targetLang: string,
context?: string,
formality?: "default" | "more" | "less" | "prefer_more" | "prefer_less",
): AsyncRes<string> {
try {
const data = await this.call("/translate", {
text: [text],
target_lang: targetLang,
source_lang: sourceLang,
context,
formality,
model_type: "prefer_quality_optimized",
});
if (!data.translations?.[0]?.text) {
throw new Error("Invalid response format from DeepL API");
}
return { ok: data.translations[0].text };
} catch (error) {
return { error: "Failed to connect to DeepL API" };
}
}
async getSupportedLanguages() {
try {
const data = await this.call("/languages");
return {
ok: data.map((l: { language: string; name: string }) => ({
code: l.language.toLowerCase(),
name: l.name,
})),
};
} catch (e) {
return { error: `${e}` };
}
}
}
// Factory function to create translation service based on provider
export function createTranslationService(provider: string): TranslationService {
const envSchema = z.object({
GOOGLE_TRANSLATE_API_KEY: z.string(),
AZURE_TRANSLATE_API_KEY: z.string(),
DEEPL_API_KEY: z.string(),
});
const env = envSchema.parse(process.env);
switch (provider) {
case "google":
return new GoogleTranslate(env.GOOGLE_TRANSLATE_API_KEY);
case "microsoft":
return new MicrosoftTranslator(env.AZURE_TRANSLATE_API_KEY);
case "deepl":
return new DeepLTranslator(env.DEEPL_API_KEY);
case "deepseek":
return new AiTranslator({ name: provider });
case "grok":
return new AiTranslator({ name: provider });
case "claude":
return new AiTranslator({ name: provider });
case "gemini":
return new AiTranslator({ name: provider });
case "chatgpt":
return new AiTranslator({ name: provider });
default:
throw new Error(`Unsupported translation provider: ${provider}`);
}
}
|