-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
translate.js
328 lines (293 loc) · 11.1 KB
/
translate.js
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
const uuidv4 = require('uuid/v4');
const fetch = require( "node-fetch" );
const ComfyDB = require( "comfydb" );
const fs = require( "fs" );
const ignorelist = fs.readFileSync( "ignore-words.txt", "utf-8" ).split( ", " ).filter( Boolean );
const { naughtyToNice, hasBlacklistedWord } = require( './censor' );
const { parseEmotes, whitespaceRegex } = require( './emotes' );
const languages = require( './languages' );
const langDetect = require("@chattylabs/language-detection");
const maxMessageLength = 64;
const memTranslations = [];
const memLimit = 1000;
const twitchUsernameRegex = /@[a-zA-Z0-9_]{4,25}\b/gi
let translationCalls = 0;
function translateMessage( channel, userstate, message, app ) {
try {
const { translations, request, channels } = app
const language = channels[ channel ].lang;
const ignore = channels[ channel ].ignore || {};
// User filtering
if( userstate.username && ignore[ userstate.username ] ) return;
// Check if the language is already the target language
const result = langDetect( message );
if( result.language === language ) return;
// Ignorelist Filtering
if( ignorelist.some( w => message.toLowerCase() === w ) ) return;
// Blacklist filtering
if( hasBlacklistedWord( message ) ) return;
// Parsing for emotes
let filteredMessage = message
if( userstate.emotes ) {
filteredMessage = parseEmotes( userstate.emotes, filteredMessage );
}
filteredMessage = filteredMessage
.replace( twitchUsernameRegex, '' )
.replace( whitespaceRegex, ' ' )
.trim()
if( !filteredMessage ) return;
// Caching
if( filteredMessage.length < maxMessageLength ) {
// Attempt to retrieve from cache
const resp = translations.get( filteredMessage ) || undefined;
if( resp && resp[ language ] )
return sendTranslationFromResponse( language, filteredMessage, channel, userstate, resp, app )
} else {
// Check memTranslations for long-message caches
const resp = memTranslations.find( translation => translation.message == filteredMessage )
if( resp && resp[ language ] )
return sendTranslationFromResponse( language, filteredMessage, channel, userstate, resp, app )
}
// Get Translation from yandex
request.get(
"https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + process.env.YANDEX_KEY + "&lang=" + language + "&text=" + encodeURI( filteredMessage ),
( err, res, body ) => {
translationCalls++;
if( translationCalls % 50 === 0 ) console.log( "API calls" + translationCalls );
// Error handling
if( err ) {
return console.log( "Error in translation request", err );
}
try {
const resp = JSON.parse( body );
if( resp && resp.lang ) {
sendTranslationFromResponse( language, filteredMessage, channel, userstate, resp, app, true );
// Cache translation
if( filteredMessage.length < maxMessageLength ) {
const translation = translations.get( filteredMessage ) || {};
translation[ language ] = resp;
translations.put( filteredMessage, translation );
}
else {
if( memTranslations.length >= memLimit ) {
memTranslations.splice( 0, 1 );
}
memTranslations.push( {
message: filteredMessage,
[ language ]: resp
} );
}
}
} catch( e ) {
console.log( e );
}
} );
}
catch( err ) {
return;
}
}
async function translateMessageWithAzure( channel, userstate, message, app ) {
{
const { translations, request, channels } = app
const language = channels[ channel ].lang;
const ignore = channels[ channel ].ignore || {};
// User filtering
if( userstate.username && ignore[ userstate.username ] ) return;
// Check if the language is already the target language
const result = langDetect( message );
if( result.language === language ) return;
// Ignorelist Filtering
if( ignorelist.some( w => message.toLowerCase() === w ) ) return;
// Blacklist filtering
if( hasBlacklistedWord( message ) ) return;
// Parsing for emotes
let filteredMessage = message
if( userstate.emotes ) {
filteredMessage = parseEmotes( userstate.emotes, filteredMessage );
}
filteredMessage = filteredMessage
.replace( twitchUsernameRegex, '' )
.replace( whitespaceRegex, ' ' )
.trim()
// console.log( filteredMessage );
if( !filteredMessage ) return;
// Caching
const cachedTranslation = await ComfyDB.Get( filteredMessage, "translations" ) || undefined;
if( cachedTranslation && cachedTranslation[ language ] ) {
// console.log( "found cache!", cachedTranslation );
return sendTranslationFromResponse( language, filteredMessage, channel, userstate, cachedTranslation, app );
}
try {
// Get Translation from translateMessageWithAzure
let body = await fetch( `https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=${ language }`, {
method: "POST",
headers: {
'Ocp-Apim-Subscription-Key': process.env.AZURE_KEY,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
body: JSON.stringify([
{
'text': filteredMessage
}
]),
} ).then( r => r.json() );
// TODO: batch translations into single calls by time for performance
// console.log( body );
// console.log( body, body[ 0 ].translations );
translationCalls++;
if( translationCalls % 50 === 0 ) console.log( "API calls" + translationCalls );
if( body && body.length > 0 ) {
var resp = {
text: [ body[ 0 ].translations[ 0 ].text ],
lang: body[ 0 ].detectedLanguage.language
};
sendTranslationFromResponse( language, filteredMessage, channel, userstate, resp, app, true );
// Cache translation
const translation = await ComfyDB.Get( filteredMessage, "translations" ) || {};
translation[ language ] = resp;
await ComfyDB.Store( filteredMessage, translation, "translations" );
}
}
catch( err ) {
return console.log( "Error in translation request", err );
}
}
}
const ComfySheets = require( "comfysheets" );
let comfyTranslations = {};
async function loadTranslations() {
var translationList = await ComfySheets.Read( process.env.SHEETID, 'Form Responses 1', {
"Original": "message",
"Original Language": "from",
"Translation": "translation",
"Translation Language": "to",
} );
translationList.forEach( t => {
const message = t.message.toLowerCase();
if( !comfyTranslations[ message ] ) {
comfyTranslations[ message ] = {
lang: t.from
};
}
comfyTranslations[ message ][ t.to ] = t.translation;
});
console.log( comfyTranslations );
}
async function addTranslation( message, langFrom, translation, langTo ) {
if( !comfyTranslations[ message ] ) {
comfyTranslations[ message ] = {
lang: langFrom.split("-")[ 0 ]
};
}
comfyTranslations[ message ][ langTo ] = translation;
let result = await ComfySheets.Submit( process.env.FORMID, {
'entry.364437775': message,
'entry.1672632710': langFrom.split("-")[ 0 ],
'entry.1464209519': translation,
'entry.1190780107': langTo,
});
}
// loadTranslations();
function translateMessageComfyTranslations( channel, userstate, message, app ) {
try {
const { translations, request, channels } = app
const language = channels[ channel ].lang;
const ignore = channels[ channel ].ignore || {};
// User filtering
if( userstate.username && ignore[ userstate.username ] ) return;
// Check if the language is already the target language
const result = langDetect( message );
if( result.language === language ) return;
// Blacklist filtering
if( hasBlacklistedWord( message ) ) return;
// Parsing for emotes
let filteredMessage = message
if( userstate.emotes ) {
filteredMessage = parseEmotes( userstate.emotes, filteredMessage );
}
filteredMessage = filteredMessage
.replace( twitchUsernameRegex, '' )
.replace( whitespaceRegex, ' ' )
.trim()
if( !filteredMessage ) return;
// Caching
if( filteredMessage.length < maxMessageLength ) {
// Attempt to retrieve from cache
const trans = comfyTranslations[ filteredMessage.toLowerCase() ] || undefined;
if( trans && trans[ language ] ) {
const resp = {
[ language ] : {
text: [ trans[ language ] ],
lang: trans.lang,
}
};
return sendTranslationFromResponse( language, filteredMessage, channel, userstate, resp, app );
}
} else {
// Check memTranslations for long-message caches
const resp = memTranslations.find( translation => translation.message == filteredMessage )
if( resp && resp[ language ] )
return sendTranslationFromResponse( language, filteredMessage, channel, userstate, resp, app )
}
// Get Translation from yandex
request.get(
"https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + process.env.YANDEX_KEY + "&lang=" + language + "&text=" + encodeURI( filteredMessage ),
( err, res, body ) => {
translationCalls++;
if( translationCalls % 50 === 0 ) console.log( "API calls" + translationCalls );
// Error handling
if( err ) {
return console.log( "Error in translation request", err );
}
try {
const resp = JSON.parse( body );
if( resp && resp.lang ) {
sendTranslationFromResponse( language, filteredMessage, channel, userstate, resp, app, true );
// Cache translation
if( filteredMessage.length < maxMessageLength ) {
addTranslation( filteredMessage.toLowerCase(), resp.lang, resp.text[ 0 ], language );
}
else {
if( memTranslations.length >= memLimit ) {
memTranslations.splice( 0, 1 );
}
memTranslations.push( {
message: filteredMessage,
[ language ]: resp
} );
}
}
} catch( e ) {
console.log( e );
}
} );
}
catch( err ) {
return;
}
}
function sendTranslationFromResponse( language, filteredMessage, channel, userstate, resp, app, fromRequest = false ) {
const { client, channels } = app
const { uncensored, color, langshow } = channels[ channel ]
let text, langFrom;
if( fromRequest ) {
text = resp.text[ 0 ] || "";
langFrom = resp.lang;
} else {
text = resp[ language ].text[ 0 ] || "";
langFrom = resp[ language ].lang;
}
if( !langFrom || langFrom.startsWith( language ) ) return
// No need to send duplicate in same language
if( text == filteredMessage ) {
return;
}
// Censoring
if( !uncensored ) {
text = naughtyToNice( text );
}
client.say( channel, `${ color ? "/me " : "" }${ langshow ? "(" + languages[ langFrom.split("-")[ 0 ] ] + ") " : "" }${ userstate[ "display-name" ] }: ${ text }` );
}
module.exports = { translateMessage, translateMessageWithAzure, translateMessageComfyTranslations }