-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmyMemoryTranslator.js
More file actions
94 lines (81 loc) · 3.29 KB
/
myMemoryTranslator.js
File metadata and controls
94 lines (81 loc) · 3.29 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
const axios = require('axios');
// Free translation via MyMemory API (≈50K chars/day/IP)
class MyMemoryTranslator {
constructor() {
this.apiUrl = 'https://api.mymemory.translated.net/get';
this.emailIndex = 1;
this.maxRetries = 10;
}
// Generate pseudo emails; rotate on quota exceed
generateEmail() {
const emailTemplates = [
`user${this.emailIndex}@example.com`,
`translate${this.emailIndex}@gmail.com`,
`subtitle${this.emailIndex}@yahoo.com`,
`video${this.emailIndex}@hotmail.com`,
`media${this.emailIndex}@outlook.com`,
];
const randomTemplate = emailTemplates[Math.floor(Math.random() * emailTemplates.length)];
return randomTemplate;
}
async translate(text, sourceLang = 'auto', targetLang = 'ko') {
let attempts = 0;
while (attempts < this.maxRetries) {
try {
const email = this.generateEmail();
console.log(`[MyMemory] Attempt ${attempts + 1}/${this.maxRetries}: ${email.substring(0, 10)}...`);
// Language code mapping
const fromLang = this.getLanguageCode(sourceLang);
const toLang = this.getLanguageCode(targetLang);
const params = {
q: text,
langpair: `${fromLang}|${toLang}`,
de: email
};
const response = await axios.get(this.apiUrl, { params });
if (response.data && response.data.responseData) {
return response.data.responseData.translatedText;
} else if (response.data && response.data.responseStatus === 403) {
// Quota exceeded, try next email
console.log('[MyMemory] Quota exceeded, trying next email...');
this.emailIndex++;
attempts++;
continue;
} else {
throw new Error('Unable to get translation result');
}
} catch (error) {
console.log(`[MyMemory] Failed: ${error.message}, retrying...`);
this.emailIndex++;
attempts++;
if (attempts >= this.maxRetries) {
throw new Error(`MyMemory daily quota exceeded. Try again tomorrow or use DeepL/OpenAI.`);
}
// Wait briefly then retry
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
throw new Error('MyMemory daily quota exceeded. Try again tomorrow or use DeepL/OpenAI.');
}
getLanguageCode(lang) {
const langMap = {
'auto': 'autodetect',
'ko': 'ko',
'en': 'en',
'ja': 'ja',
'zh': 'zh',
'es': 'es',
'fr': 'fr',
'de': 'de',
'it': 'it',
'pt': 'pt',
'ru': 'ru',
'hu': 'hu',
'ar': 'ar',
'pl': 'pl',
'fa': 'fa'
};
return langMap[lang] || lang;
}
}
module.exports = MyMemoryTranslator;