-
Notifications
You must be signed in to change notification settings - Fork 1
/
PolyglotTranslator.lua
2183 lines (1985 loc) · 92.9 KB
/
PolyglotTranslator.lua
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--[[ --- START OF VERSION ---
MAJOR:1
MINOR:5
PATCH:1
CHANGELOG
- Fixed broken ChatGPT translation method.
- Fixed broken restoring of translation method upon script startup.
- Added new ChatGPT templates.
- Changed in input method of sending outgoing messages, now using the native interface of GTA instead of the commandbox. This makes it easier to use IME for input especially for Chinese and Japanese players.
- You can now send private translated messages to specific player. You can find the button in Players tab. Private messages looks like `[To <PlayerName>] <TranslatedMessage>`.
- Refactoring and code cleanup.
- Added Portuguese localization.
- Credits to all contributors.
--- END OF VERSION --- ]]
-- LEGACY
--[[ local versionInfo = {
major = 9,
minor = 9,
patch = 9
} ]]
package.preload['src.lib.utils'] = (function (...)
local _ENV = _ENV;
local function module(name, ...)
local t = package.loaded[name] or _ENV[name] or { _NAME = name };
package.loaded[name] = t;
for i = 1, select("#", ...) do
(select(i, ...))(t);
end
_ENV = t;
_M = t;
return t;
end
-- package.loaded["src.lib.utils"] = nil
local moduleExports = {}
function moduleExports.tableToUrlParams(t)
local url_params = {}
for k, v in pairs(t) do
table.insert(url_params, moduleExports.url_encode(k) .. '=' .. moduleExports.url_encode(v))
end
return table.concat(url_params, "&")
end
function moduleExports.url_encode(text)
if (text) then
text = string.gsub(text, "\n", "\r\n")
text = string.gsub(text, "([^%w ])", function(c)
return string.format("%%%02X", string.byte(c))
end)
text = string.gsub(text, " ", "+")
end
return text
end
function moduleExports.url_decode(text)
return string.gsub(text, "%+", " ")
end
function moduleExports.unicode_escape(unicode)
return utf8.char(tonumber(unicode, 16))
end
function moduleExports.templateReplace(template, ...)
local args = { ... }
local result = template:gsub("{arg(%d+)}", function(n)
return args[tonumber(n)]
end)
return result
end
function moduleExports.toast(template, ...)
local args = { ... }
local result = template:gsub("{arg(%d+)}", function(n)
return args[tonumber(n)]
end)
util.toast(result, TOAST_ALL)
end
function moduleExports.debugLog(message)
if Config.debugMode then
local formattedMessage = string.format("[%s] %s", SCRIPT_NAME, message)
util.toast(formattedMessage)
util.log(formattedMessage)
end
end
function moduleExports.extractJSON(responseText)
local jsonStr = responseText:match("(%b{})")
return jsonStr and json.decode(jsonStr) or nil
end
function moduleExports.isJSON(text)
local jsonStr = text:match("(%b{})")
return jsonStr ~= nil
end
---@param windowName string #Must be a label
---@param maxInput integer
---@param defaultText string
---@return string
function moduleExports.get_input_from_screen_keyboard(windowName, maxInput, defaultText)
MISC.DISPLAY_ONSCREEN_KEYBOARD(0, windowName, "", defaultText, "", "", "", maxInput);
while MISC.UPDATE_ONSCREEN_KEYBOARD() == 0 do util.yield_once() end
if MISC.UPDATE_ONSCREEN_KEYBOARD() == 1 then return MISC.GET_ONSCREEN_KEYBOARD_RESULT() end
return ""
end
return moduleExports
end)
package.preload['src.lib.updater'] = (function (...)
local _ENV = _ENV;
local function module(name, ...)
local t = package.loaded[name] or _ENV[name] or { _NAME = name };
package.loaded[name] = t;
for i = 1, select("#", ...) do
(select(i, ...))(t);
end
_ENV = t;
_M = t;
return t;
end
local moduleExports = {}
local mainGitHubPath = "/Totoro-Li/PolyglotTranslator/main/"
local mainFileName = "PolyglotTranslator.lua"
local function parseVersionInfo(content)
local majorPattern = "MAJOR%s*:%s*(%d+)"
local minorPattern = "MINOR%s*:%s*(%d+)"
local patchPattern = "PATCH%s*:%s*(%d+)"
local changelogPattern = "CHANGELOG%s*(.-)%-%-%-%s*END OF VERSION"
local major = tonumber(content:match(majorPattern))
local minor = tonumber(content:match(minorPattern))
local patch = tonumber(content:match(patchPattern))
local changelog = content:match(changelogPattern)
if not major or not minor or not patch then
return nil
end
local changelogLines = {}
for line in changelog:gmatch("[^\r\n]+") do
table.insert(changelogLines, line)
end
return {
major = major,
minor = minor,
patch = patch,
changelog = changelogLines
}
end
local function isUpdateNeeded(currentVersion, newVersion)
if not newVersion then return false end
polyglotUtils.debugLog("Current version: " .. currentVersion.major .. "." .. currentVersion.minor .. "." .. currentVersion.patch)
polyglotUtils.debugLog("New version: " .. newVersion.major .. "." .. newVersion.minor .. "." .. newVersion.patch)
if newVersion.major > currentVersion.major or
(newVersion.major == currentVersion.major and newVersion.minor > currentVersion.minor) or
(newVersion.major == currentVersion.major and newVersion.minor == currentVersion.minor and newVersion.patch > currentVersion.patch) then
return true
end
return false
end
local function startUpdate(content, updateCallback)
local newVersionInfo = parseVersionInfo(content)
if not newVersionInfo then
polyglotUtils.toast(LOC.unexpectedResponse)
return
end
---@type file*?
local scriptFile = io.open(filesystem.scripts_dir() .. mainFileName, "rb")
if scriptFile == nil then
updateCallback(newVersionInfo)
return
end
-- Read current version info and match with parseVersionInfo
local versionInfo = parseVersionInfo(scriptFile:read("*a"))
scriptFile:close()
if isUpdateNeeded(versionInfo, newVersionInfo) then
updateCallback(newVersionInfo)
else
polyglotUtils.toast(LOC.noUpdatesAvailable)
end
end
local State <const> =
{
Idle = 0,
DownloadingScript = 1
}
local state = State.Idle
function moduleExports.runUpdater(clickType)
if state == State.DownloadingScript then
polyglotUtils.toast(LOC.updateInProgress)
return
end
async_http.init("https://raw.githubusercontent.com", mainGitHubPath .. mainFileName, function(resBody, _, statusCode)
if statusCode >= 200 and statusCode < 300 and resBody and resBody:len() > 0 then
startUpdate(resBody, function(newVersionInfo)
state = State.DownloadingScript
polyglotUtils.toast(LOC.updating)
local scriptFile = io.open(filesystem.scripts_dir() .. mainFileName, "wb")
if not scriptFile then
polyglotUtils.toast(LOC.unexpectedResponse)
state = State.Idle
return
end
scriptFile:write(resBody .. "\n")
scriptFile:close()
polyglotUtils.toast(LOC.templates.updateSuccessful,
newVersionInfo.major .. "." .. newVersionInfo.minor .. "." .. newVersionInfo.patch)
polyglotUtils.toast(LOC.changelog .. "\n" .. table.concat(newVersionInfo.changelog, "\n"))
util.restart_script()
end)
else
polyglotUtils.toast(LOC.failedToUpdate)
end
end, function()
polyglotUtils.toast(LOC.failedToDownloadFromGitHub)
end)
async_http.dispatch()
end
return moduleExports
end)
package.preload['src.lib.translation'] = (function (...)
local _ENV = _ENV;
local function module(name, ...)
local t = package.loaded[name] or _ENV[name] or { _NAME = name };
package.loaded[name] = t;
for i = 1, select("#", ...) do
(select(i, ...))(t);
end
_ENV = t;
_M = t;
return t;
end
-- package.loaded["src.lib.translation"] = nil
local moduleExports = {}
local Languages = {
{
Name = "Afrikaans",
Key = "af"
}, {
Name = "Albanian",
Key = "sq"
}, {
Name = "Arabic",
Key = "ar"
}, {
Name = "Azerbaijani",
Key = "az"
}, {
Name = "Basque",
Key = "eu"
}, {
Name = "Belarusian",
Key = "be"
}, {
Name = "Bengali",
Key = "bn"
}, {
Name = "Bulgarian",
Key = "bg"
}, {
Name = "Catalan",
Key = "ca"
}, {
Name = "Chinese Simplified",
Key = "zh-cn"
}, {
Name = "Chinese Traditional",
Key = "zh-tw"
}, {
Name = "Croatian",
Key = "hr"
}, {
Name = "Czech",
Key = "cs"
}, {
Name = "Danish",
Key = "da"
}, {
Name = "Dutch",
Key = "nl"
}, {
Name = "English",
Key = "en"
}, {
Name = "Esperanto",
Key = "eo"
}, {
Name = "Estonian",
Key = "et"
}, {
Name = "Filipino",
Key = "tl"
}, {
Name = "Finnish",
Key = "fi"
}, {
Name = "French",
Key = "fr"
}, {
Name = "Galician",
Key = "gl"
}, {
Name = "Georgian",
Key = "ka"
}, {
Name = "German",
Key = "de"
}, {
Name = "Greek",
Key = "el"
}, {
Name = "Gujarati",
Key = "gu"
}, {
Name = "Haitian Creole",
Key = "ht"
}, {
Name = "Hebrew",
Key = "iw"
}, {
Name = "Hindi",
Key = "hi"
}, {
Name = "Hungarian",
Key = "hu"
}, {
Name = "Icelandic",
Key = "is"
}, {
Name = "Indonesian",
Key = "id"
}, {
Name = "Irish",
Key = "ga"
}, {
Name = "Italian",
Key = "it"
}, {
Name = "Japanese",
Key = "ja"
}, {
Name = "Kannada",
Key = "kn"
}, {
Name = "Korean",
Key = "ko"
}, {
Name = "Latin",
Key = "la"
}, {
Name = "Latvian",
Key = "lv"
}, {
Name = "Lithuanian",
Key = "lt"
}, {
Name = "Macedonian",
Key = "mk"
}, {
Name = "Malay",
Key = "ms"
}, {
Name = "Maltese",
Key = "mt"
}, {
Name = "Norwegian",
Key = "no"
}, {
Name = "Persian",
Key = "fa"
}, {
Name = "Polish",
Key = "pl"
}, {
Name = "Portuguese",
Key = "pt"
}, {
Name = "Romanian",
Key = "ro"
}, {
Name = "Russian",
Key = "ru"
}, {
Name = "Serbian",
Key = "sr"
}, {
Name = "Slovak",
Key = "sk"
}, {
Name = "Slovenian",
Key = "sl"
}, {
Name = "Spanish",
Key = "es"
}, {
Name = "Swahili",
Key = "sw"
}, {
Name = "Swedish",
Key = "sv"
}, {
Name = "Tamil",
Key = "ta"
}, {
Name = "Telugu",
Key = "te"
}, {
Name = "Thai",
Key = "th"
}, {
Name = "Turkish",
Key = "tr"
}, {
Name = "Ukrainian",
Key = "uk"
}, {
Name = "Urdu",
Key = "ur"
}, {
Name = "Vietnamese",
Key = "vi"
}, {
Name = "Welsh",
Key = "cy"
}, {
Name = "Yiddish",
Key = "yi"
}}
LangPairs = {} -- Aux for sorting
LangKeyList = {}
LangNameList = {}
LangLookupByName = {}
LangLookupByKey = {}
for i = 1, #Languages do
local Language = Languages[i]
LangPairs[i] = {
key = Language.Key,
name = Language.Name
}
LangLookupByName[Language.Name] = Language.Key
LangLookupByKey[Language.Key] = Language.Name
end
table.sort(LangPairs, function(a, b) return a.name < b.name end)
for i = 1, #LangPairs do
LangKeyList[i] = LangPairs[i].key
LangNameList[i] = LangPairs[i].name
end
ChatGPTPromptPresets = {
["Basic"] = "Translate the following message to {{lang}} in a natural and Internet style.",
["Cute with Emoticons"] = "Please translate the following text into {{lang}}, in the style of game message scenario with one emoticon at the end of message, be natural and without the feeling of machine translation. Context is related to Grand Theft Auto OL. Use simple emoticons containing ASCII letters like parentheses and quotation marks.",
["Add Emoticon At End"] = "Please add one cute emoticon(Kaomoji) at the end of message, according to the mood and emotion of message. Do not modify the words.",
["Model Roleplay"] = "You are a translation model. Please translate the following text to {{lang}}.",
["AI Self-aware"] = "As an AI language model, please convert the following text to {{lang}}."
}
ChatGPTPromptPresetsOptions = {}
for k, v in pairs(ChatGPTPromptPresets) do
table.insert(ChatGPTPromptPresetsOptions, k)
end
local function googleTranslateCall(text, targetLang, onSuccess)
local HEADERS = {
["User-Agent"] = "User-Agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.1 Safari/605.1.15"
}
local params = {
client = "dict-chrome-ex",
sl = "auto",
tl = targetLang,
dt = "t",
dj = "1",
source = "input",
q = polyglotUtils.url_encode(text)
}
async_http.init("translate.googleapis.com", "/translate_a/t?" .. polyglotUtils.tableToUrlParams(params),
function(body, header_fields, status_code)
if status_code == 200 and body ~= "" then
polyglotUtils.debugLog("Google translate response: " .. body)
local translation, sourceLang = body:match('%[%["(.-)","(.-)"%]%]')
translation = translation:gsub("\\u(%x%x%x%x)", polyglotUtils.unicode_escape)
translation = translation:gsub(" <code> 0 </code> ", "\n")
translation = translation:gsub("<code>0</code>", "\n")
translation = translation:gsub("\\(.)", "%1")
onSuccess(translation, sourceLang)
else
polyglotUtils.toast(LOC.templates.errorTranslating, text, tostring(status_code))
end
end)
for key, value in pairs(HEADERS) do async_http.add_header(key, value) end
async_http.dispatch()
end
local function generatePromptFromPreset(preset, text, targetLang)
local prompt = ChatGPTPromptPresets[preset] ..
" The translation should be provided in the following JSON format:\n```json\n{\n \"translations\": [\n {\n \"t\": \"{{translated_message}}\",\n \"s\": \"{{English name of source_language}}\"\n }\n ]\n}\n```\nMessage: {{text}}"
prompt = prompt:gsub("{{lang}}", LangLookupByKey[targetLang]) -- Replace {lang} placeholder
prompt = prompt:gsub("{{text}}", text) -- Replace {text} placeholder
return prompt
end
local function chatGPTTranslateCall(text, targetLang, onSuccess)
local apiKey = Config.apiKey
if apiKey == nil or apiKey == "" then
polyglotUtils.toast(LOC.templates.apiKeyNotSet)
return
end
local prompt = generatePromptFromPreset(Config.chatGPTPromptPreset, text, targetLang)
local postData = {
model = "gpt-3.5-turbo",
messages = {
{
role = "user",
content = prompt
}
},
stream = false
}
postData = json.encode(postData)
async_http.init("api.openai.com", "/v1/chat/completions", function(body, header_fields, status_code)
if status_code == 200 and body ~= "" then
polyglotUtils.debugLog("ChatGPT response: " .. body)
local response = json.decode(body)
local responseContent = response.choices[1].message.content
polyglotUtils.debugLog("ChatGPT response content: " .. responseContent)
if polyglotUtils.isJSON(responseContent) then
local translation = polyglotUtils.extractJSON(responseContent).translations[1]
local translatedMessage = translation.t
translatedMessage = translatedMessage:gsub("\\u0026", "&")
translatedMessage = translatedMessage:gsub("\\\"", "\"")
translatedMessage = translatedMessage:gsub("\\\\", "\\")
translatedMessage = translatedMessage:gsub("~", " ")
translatedMessage = translatedMessage:match("^%s*(.-)%s*$") -- Remove heading and trailing spaces
local sourceLang = LangLookupByName[translation.s]
onSuccess(translatedMessage, sourceLang or "en")
else
polyglotUtils.toast("The API returned a natural language response: " .. responseContent)
end
else
polyglotUtils.toast(LOC.templates.errorTranslating, text, tostring(status_code))
end
end, function() polyglotUtils.toast(LOC.templates.errorConnectingToChatGPTAPI) end)
async_http.set_post("application/json", postData)
async_http.add_header("Authorization", "Bearer " .. apiKey)
async_http.dispatch()
polyglotUtils.debugLog("ChatGPT request sent with post data: " .. postData)
end
local translationMethods = {
["Google Translate"] = googleTranslateCall,
-- ["Bing"] = bingTranslateCall,
["ChatGPT"] = chatGPTTranslateCall
}
TranslationMethodOptions = {
"Google Translate",
-- "Bing",
"ChatGPT"
}
function moduleExports.translateText(text, targetLang, translationMethod, onSuccess)
if translationMethods[translationMethod] then
translationMethods[translationMethod](text, targetLang, function(translation, sourceLang)
onSuccess(translation, sourceLang:lower())
end)
end
end
return moduleExports
end)
package.preload['src.lib.chat'] = (function (...)
local _ENV = _ENV;
local function module(name, ...)
local t = package.loaded[name] or _ENV[name] or { _NAME = name };
package.loaded[name] = t;
for i = 1, select("#", ...) do
(select(i, ...))(t);
end
_ENV = t;
_M = t;
return t;
end
-- package.loaded["src.lib.chat"] = nil
local scaleformHandleTable = {}
local scaleformTypes = {
["number"] = GRAPHICS.SCALEFORM_MOVIE_METHOD_ADD_PARAM_FLOAT,
["string"] = GRAPHICS.SCALEFORM_MOVIE_METHOD_ADD_PARAM_PLAYER_NAME_STRING,
["boolean"] = GRAPHICS.SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL
}
local checkScaleformAndLoad = function(scaleformName)
if not scaleformHandleTable[scaleformName] or
not GRAPHICS.HAS_SCALEFORM_MOVIE_LOADED(scaleformHandleTable[scaleformName]) then
local scaleformHandle = GRAPHICS.REQUEST_SCALEFORM_MOVIE(scaleformName)
while not GRAPHICS.HAS_SCALEFORM_MOVIE_LOADED(scaleformHandle) do util.yield() end
scaleformHandleTable[scaleformName] = scaleformHandle
GRAPHICS.DRAW_SCALEFORM_MOVIE_FULLSCREEN(scaleformHandle, 255, 255, 255, 255, 1)
end
end
local function callScaleformMethod(scaleformName, method, ...)
local args = {...}
checkScaleformAndLoad(scaleformName)
if GRAPHICS.BEGIN_SCALEFORM_MOVIE_METHOD(scaleformHandleTable[scaleformName], method) then
for i = 1, #args do
local arg = args[i]
local type = type(arg)
local pushFunc = scaleformTypes[type]
if pushFunc then
pushFunc(arg)
else
error("Invalid type passed to scaleform method: " .. type)
end
end
GRAPHICS.END_SCALEFORM_MOVIE_METHOD()
end
end
---@param player string
---@param message string
---@param scope string
---@param teamOnly boolean
---@param eHudColour number
local function drawScaleformMultiplayerChat(player, message, scope, teamOnly, eHudColour)
callScaleformMethod("MULTIPLAYER_CHAT", "ADD_MESSAGE", player, message, scope, teamOnly, eHudColour)
end
local moduleExports = {}
local colors = {
topbar = {
["r"] = 50 / 255,
["g"] = 50 / 255,
["b"] = 50 / 255,
["a"] = 1.0
}, -- grayish
background = {
["r"] = 5 / 255,
["g"] = 5 / 255,
["b"] = 5 / 255,
["a"] = 0.5
}, -- blackish
subhead = {
["r"] = 1,
["g"] = 1,
["b"] = 1,
["a"] = 1.0
}, -- white
label = {
["r"] = 1,
["g"] = 1,
["b"] = 1,
["a"] = 1.0
}, -- white
highlight = {
["r"] = 160 / 255,
["g"] = 160 / 255,
["b"] = 160 / 255,
["a"] = 1.0
} -- also grayish
}
TranslatedMsgLocationOptions = {
LOC.translatedMsgLocationOptions.teamChatNotNetworked, LOC.translatedMsgLocationOptions.teamChatNetworked,
LOC.translatedMsgLocationOptions.globalChatNotNetworked, LOC.translatedMsgLocationOptions.globalChatNetworked,
LOC.translatedMsgLocationOptions.notification, LOC.translatedMsgLocationOptions.popup}
local messages = {}
local display_duration = 3000 -- Time in ms to display each message
local max_messages = 5 -- Maximum number of messages to display at a time
local function calculate_max_scale(text, max_width)
local text_width, _ = directx.get_text_size(text)
local scale = 1.0
if text_width > max_width then scale = max_width / text_width end
return scale
end
-- Helper function to wrap the text to fit the given width
local function wrap_text(text, width)
local lines = {}
local words = {}
local line = ""
local line_width
for word in text:gmatch("%S+") do table.insert(words, word) end
for i, word in ipairs(words) do
if line == "" then
line = word
else
line_width, _ = directx.get_text_size(line)
if line_width < width then
line = line .. " " .. word
else
table.insert(lines, line)
line = word
end
end
if i == #words then table.insert(lines, line) end
end
return lines
end
local function display_popup(sender, message, src_language)
local current_time = util.current_time_millis()
table.insert(messages, {
sender = sender,
message = message,
src_language = src_language,
banner_color = {
r = math.random(),
g = math.random(),
b = math.random(),
a = 1.0
},
start_time = current_time
})
if #messages > max_messages then table.remove(messages, 1) end
end
util.create_tick_handler(function()
local current_time = util.current_time_millis()
for i, msg in ipairs(messages) do
if current_time - msg.start_time > display_duration then
table.remove(messages, i)
break
end
local x, y, width, height = 0.75, 0.05 * (i - 1), 0.2, 0.05
local padding = 0.005
-- Calculate the maximum scale for sender name and message
local sender_scale = calculate_max_scale(msg.sender, width * 0.4)
local message_scale = calculate_max_scale(msg.message, width * 0.6)
-- Draw the background rectangle
directx.draw_rect(x, y, width, height, colors.background)
directx.draw_rect(x, y, padding, height, msg.banner_color)
-- Draw the sender name
directx.draw_text(x + padding, y + padding / 2, msg.sender, ALIGN_TOP_LEFT, sender_scale, colors.label, true)
-- Draw the message with word wrapping
local wrapped_message = wrap_text(msg.message, width * 0.6)
local line_spacing = 0.01
local message_y = y + height / 2
for _, line in ipairs(wrapped_message) do
directx.draw_text(x + padding * 2 + width * 0.4, message_y, line, ALIGN_TOP_LEFT, message_scale,
colors.subhead, true)
message_y = message_y + line_spacing
end
-- Draw the source language
directx.draw_text(x + width - padding, y + padding / 2, msg.src_language, ALIGN_TOP_RIGHT, 1.0, colors.highlight)
end
end)
local botSend = false -- To avoid infinite loop
function moduleExports.createOnMessageCallback(translateTextCB)
return function(sender, reserved, text, team_chat, networked, is_auto)
if not Config.translateOn then return end
if not botSend then
if not Config.translateSelf and (sender == players.user()) then
return
else
translateTextCB(text, Config.targetLanguageIncoming, Config.translationMethodIncoming,
function(translation, sourceLang)
---@type string
local senderName = players.get_name(sender)
local resultText = translation
---@type number
local colorFinal = Config.colorSelect
local translatedMsgLocation = Config.translatedMsgLocation
---@type string
local teamChatLabel = Config.teamChatLabel
---@type string
local allChatLabel = Config.allChatLabel
if Config.blacklistedLanguages[sourceLang] == true then return end
-- "Team Chat not networked", "Team Chat networked", "Global Chat not networked", "Global Chat networked", "Notification"
if (translatedMsgLocation == 1) then
drawScaleformMultiplayerChat(senderName, resultText, teamChatLabel, false, colorFinal)
end
if (translatedMsgLocation == 2) then
botSend = true
-- void chat.send_message(string text, bool team_chat, bool add_to_local_history, bool networked)
-- add_to_local_history set to false so that the message doesn't appear twice
chat.send_message(senderName .. " : " .. resultText, true, false, true)
drawScaleformMultiplayerChat(senderName, resultText, teamChatLabel, false, colorFinal)
end
if (translatedMsgLocation == 3) then
drawScaleformMultiplayerChat(senderName, resultText, allChatLabel, false, colorFinal)
end
if (translatedMsgLocation == 4) then
botSend = true
-- Ref : void chat.send_message(string text, bool team_chat, bool add_to_local_history, bool networked)
chat.send_message(senderName .. " : " .. resultText, false, false, true)
drawScaleformMultiplayerChat(senderName, resultText, allChatLabel, false, colorFinal)
end
if (translatedMsgLocation == 5) then
polyglotUtils.toast(senderName .. " : " .. resultText)
end
if (translatedMsgLocation == 6) then
display_popup(senderName, resultText, sourceLang)
end
end)
end
end
botSend = false
end
end
function moduleExports.sendMessage(myText, translateTextCB)
translateTextCB(myText, Config.targetLanguageOutgoing, Config.translationMethodOutgoing,
function(translation, sourceLang)
-- for _, pId in ipairs(players.list()) do
-- chat.send_targeted_message(pId, players.user(), translation, false)
-- end
-- void chat.send_message(string text, bool team_chat, bool add_to_local_history, bool networked)
chat.send_message(translation, false, true, true)
polyglotUtils.debugLog("Message sent: " .. translation)
end)
end
function moduleExports.sendPrivateMessage(myText, pid, translateTextCB)
translateTextCB(myText, Config.targetLanguageOutgoing, Config.translationMethodOutgoing,
function(translation, sourceLang)
local msg = polyglotUtils.templateReplace(LOC.sendingToPlayerLookupByKey[Config.targetLanguageOutgoing], players.get_name(pid)) .. translation
chat.send_targeted_message(pid, players.user(), msg, true)
chat.send_message(msg, true, true, false)
polyglotUtils.debugLog("Message sent: " .. translation)
end)
end
return moduleExports
end)
package.preload['src.lib.localization'] = (function (...)
local _ENV = _ENV;
local function module(name, ...)
local t = package.loaded[name] or _ENV[name] or { _NAME = name };
package.loaded[name] = t;
for i = 1, select("#", ...) do
(select(i, ...))(t);
end
_ENV = t;
_M = t;
return t;
end
-- package.loaded["src.lib.localization"] = nil
local engTranslations = {
noInternetAccess = "To use Polyglot Translator, please enable internet access",
checkForUpdates = "Check for updates",
checkForUpdatesD = "Check for updates for Polyglot Translator",
updateInProgress = "Update in progress...",
updating = "Updating...",
failedToUpdate = "Failed to update the script file.",
unexpectedResponse = "Unexpected update file. Local file will stay unchanged.",
failedToDownloadFromGitHub = "Failed to download from GitHub.",
changelog = "Changelog",
noUpdatesAvailable = "No updates available.",
chatGPTSettings = "ChatGPT Settings",
chatGPTSettingsD = "ChatGPT Settings",
apiKeyInput = "API Key",
apiKeyInputD = "Enter your API key",
chatGPTPromptPreset = "ChatGPT Prompt Preset",
chatGPTPromptPresetD = "Choose the prompt preset for ChatGPT",
temperature = "Temperature",
temperatureD = "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or top p but not both. (Default: 1)",
topP = "Top P",
topPD = "Number between 0 and 1. An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. (Default: 1)",
presencePenalty = "Presence Penalty",
presencePenaltyD = "Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. (Default: 0)",
frequencyPenalty = "Frequency Penalty",
frequencyPenaltyD = "Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. (Default: 0)",
translatorListenerOn = "Translator Listener On",
translatorListenerOnD = "Translator will listen to incoming messages and translate",
translateYourself = "Translate Own Messages",
translateYourselfD = "Translate messages sent by yourself",
translatedMessageDisplay = "Translated Message Display",
translatedMessageDisplayD = "Location of translated Message. You need to click to apply change",
scriptSettings = "Other Settings For Polyglot Translator",
scriptSettingsD = "Including color settings and updates",
playerNameColor = "Player Name Color",
customLabelForTeamTranslationD = "Leaving it blank will revert it to the original label",
customLabelForAllTranslationD = "Leaving it blank will revert it to the original label",
translatorListenerBlacklist = "Translator Listener Blacklist",
translatorListenerBlacklistD = "Ignore messages in languages toggled on in this list",
translationMethod = "Translation Method",
translationMethodD = "Choose the translation method",
incomingMessages = "Incoming Messages",
incomingMessagesD = "Choose the translation method for incoming messages",
outgoingMessages = "Outgoing Messages",
outgoingMessagesD = "Choose the translation method for outgoing messages",
targetLanguageIncoming = "Target Language Incoming",
targetLanguageIncomingD = "Language to translate incoming messages to. You need to click to apply change",
sendTranslatedMessage = "Send Translated Message",
targetLanguageOutgoing = "Target Language Outgoing",
targetLanguageOutgoingD = "Language to translate your messages to. You need to click to apply change",
sendMessage = "Send Message",
sendMessageD = "Input the text for your message",
credits = "Credits",
translatedMsgLocationOptions = {
teamChatNotNetworked = "Team Chat not networked",
teamChatNetworked = "Team Chat networked",
globalChatNotNetworked = "Global Chat not networked",
globalChatNetworked = "Global Chat networked",
notification = "Stand Notification",
popup = "Popup"
},
templates = {
-- Example: "ChatGPT Prompt Preset changed to {arg1} "
updateSuccessful = "Update successful, current version: {arg1}",
apiKeyNotSet = "API key not set. Please enter your API key in the settings",
errorTranslating = "Error translating, Original message: {arg1}, Status code: {arg2}",
errorConnectingToChatGPTAPI = "Error connecting to ChatGPT API",
chatGPTPromptChangedTo = "ChatGPT Prompt Preset changed to {arg1}",
selectedColor = "Selected color: {arg1}",
customLabelForTeamTranslation = "Custom Label For [{arg1}] Translation",
customLabelForAllTranslation = "Custom Label For [{arg1}] Translation",
translationMethodIncomingChangedTo = "Translation Method Incoming changed to {arg1}",
translationMethodOutgoingChangedTo = "Translation Method Outgoing changed to {arg1}",
sendingToPlayer = "[To {arg1}] "
},
CustomLabels = {
inputMessage = "Please input your message"
}
}
local esTranslations = {
noInternetAccess = "Para usar Polyglot Translator, habilite el acceso a internet",
checkForUpdates = "Buscar actualizaciones",
checkForUpdatesD = "Buscar actualizaciones para Polyglot Translator",
updateInProgress = "Actualización en curso...",
updating = "Actualizando...",
failedToUpdate = "Error al actualizar el archivo de script.",
unexpectedResponse = "Archivo de actualización inesperado. El archivo local no cambiará.",
failedToDownloadFromGitHub = "Error al descargar desde GitHub.",
noUpdatesAvailable = "No hay actualizaciones disponibles.",
changelog = "Registro de cambios",
chatGPTSettings = "Ajustes de ChatGPT",
chatGPTSettingsD = "Ajustes de ChatGPT",
apiKeyInput = "Clave API",
apiKeyInputD = "Ingrese su clave API",
chatGPTPromptPreset = "Preajuste de indicaciones de ChatGPT",
chatGPTPromptPresetD = "Elija el preajuste de indicaciones para ChatGPT",
temperature = "Temperatura",
temperatureD = "La temperatura de muestreo a utilizar, entre 0 y 2. Valores más altos como 0.8 harán que la salida sea más aleatoria, mientras que valores más bajos como 0.2 la harán más enfocada y determinista. Generalmente recomendamos alterar esto o el top p pero no ambos. (Por defecto: 1)",
topP = "Top P",
topPD = "Número entre 0 y 1. Una alternativa al muestreo con temperatura, llamada muestreo del núcleo, donde el modelo considera los resultados de los tokens con la masa de probabilidad top p. Entonces, 0.1 significa que solo se consideran los tokens que comprenden el 10% superior de la masa de probabilidad. Generalmente recomendamos alterar esto o la temperatura, pero no ambos. (Por defecto: 1)",
presencePenalty = "Penalización de presencia",
presencePenaltyD = "Número entre -2.0 y 2.0. Los valores positivos penalizan los nuevos tokens según si aparecen en el texto hasta ahora, aumentando la probabilidad del modelo de hablar sobre nuevos temas. (Por defecto: 0)",
frequencyPenalty = "Penalización de frecuencia",
frequencyPenaltyD = "Número entre -2.0 y 2.0. Los valores positivos penalizan los nuevos tokens según su frecuencia existente en el texto hasta ahora, disminuyendo la probabilidad del modelo de repetir la misma línea textual. (Por defecto: 0)",
translatorListenerOn = "Escucha del traductor activada",
translatorListenerOnD = "El traductor escuchará los mensajes entrantes y los traducirá",
translateYourself = "Traducir mensajes propios",
translateYourselfD = "Traducir mensajes enviados por usted mismo",
translatedMessageDisplay = "Visualización del mensaje traducido",
translatedMessageDisplayD = "Ubicación del mensaje traducido. Debe hacer clic para aplicar el cambio",
scriptSettings = "Otros ajustes para Polyglot Translator",
scriptSettingsD = "Incluyendo ajustes de color y actualizaciones",
playerNameColor = "Color del nombre del jugador",
customLabelForTeamTranslationD = "Dejar en blanco volverá a la etiqueta original",
customLabelForAllTranslationD = "Dejar en blanco volverá a la etiqueta original",
translatorListenerBlacklist = "Lista negra del escucha del traductor",
translatorListenerBlacklistD = "Ignorar mensajes en idiomas activados en esta lista",
translationMethod = "Método de traducción",