-
Notifications
You must be signed in to change notification settings - Fork 0
/
esolang.py
1890 lines (1587 loc) · 75.2 KB
/
esolang.py
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
# -*- coding: utf-8 -*-
import argparse
import sys
import os
import inspect
import re
import struct
import codecs
import chardet
from difflib import SequenceMatcher
from ruamel.yaml.scalarstring import PreservedScalarString
import ruamel.yaml
import section_constants as section
"""
From powershell 6.1.7600.16385 you may see question marks rather then the Korean or Chinese text on windows 7.
However, running esolang with powershell 7 on windows 10 the docstrings should print correctly.
On windows 7 in GitBash 2.35.1.2 you may see a UnicodeEncodeError charmap error.
The issue is related to the encoding used when printing Unicode characters in different terminal environments.
"""
# List to hold information about callable functions
callable_functions = []
def mainFunction(func):
"""Decorator to mark functions as callable and add them to the list."""
callable_functions.append(func)
return func
def print_help():
print("Available callable functions:")
for func in callable_functions:
print("- {}: {}".format(func.__name__, func.__doc__))
def print_docstrings():
print("Docstrings for callable functions:")
for func in callable_functions:
print("\nFunction: {}".format(func.__name__))
docstring = inspect.getdoc(func)
if docstring:
encoded_docstring = docstring.encode('utf-8', errors='ignore').decode(sys.stdout.encoding)
print(encoded_docstring)
else:
print("No docstring available.")
def main():
parser = argparse.ArgumentParser(description="A script to perform various operations on text files.")
parser.add_argument("--help-functions", action="store_true", help="Print available functions and their docstrings.")
parser.add_argument("--list-functions", action="store_true", help="List available functions without docstrings.")
parser.add_argument("--usage", action="store_true", help="Display usage information.")
parser.add_argument("function", nargs="?", help="The name of the function to execute.")
parser.add_argument("args", nargs=argparse.REMAINDER, help="Arguments for the function.")
args = parser.parse_args()
if args.usage:
print("Usage: esokr.py function [args [args ...]]")
print(" esokr.py --help-functions, or help")
print(" esokr.py --list-functions, or list")
elif args.help_functions or args.function == "help":
print_docstrings()
elif args.list_functions or args.function == "list":
print("Available functions:")
for func in callable_functions:
print(func.__name__)
elif args.function:
function_name = args.function
for func in callable_functions:
if func.__name__ == function_name:
func_args = args.args
if func == addIndexToLangFile and len(func_args) < 2:
print("Usage: {} <txtFilename> <idFilename>".format(func.__name__))
else:
func(*func_args)
break
else:
print("Unknown function: {}".format(function_name))
else:
print("No command provided.")
# Regular Expressions for Text Processing -------------------------------------
"""
Here's a breakdown of how the reClientUntaged expression works:
^: Anchors the start of the string.
\[(.+?)\]: Matches a string enclosed in square brackets and captures the content
inside the brackets as group 1 (.*?). The (.+?) is a non-greedy match for any
characters within the brackets.
= ": Matches the space, equals sign, and double quotation mark that follow the square brackets.
(?!.*{[CP]:): A negative lookahead assertion that checks that the text ahead does
not contain either {C: or {P:. This ensures that the text within the double
quotation marks is not tagged as a language constant.
(.*?): Captures the text between the double quotation marks as group 2 (.*?).
": Matches the closing double quotation mark.
$: Anchors the end of the string.
"""
# Matches a language index in the format {{identifier:}}text
reLangIndex = re.compile(r'^\{\{([^:]+):}}(.+?)$')
# Matches an old-style language index in the format identifier text
reLangIndexOld = re.compile(r'^(\d{1,10}-\d{1,7}-\d{1,7}) (.+)$')
# Matches untagged client strings or empty lines in the format [key] = "value" or [key] = ""
reClientUntaged = re.compile(r'^\[(.+?)\] = "(?!.*{[CP]:)(.*?)"$')
# Matches tagged client strings in the format [key] = "{tag:value}text"
reClientTaged = re.compile(r'^\[(.+?)\] = "(\{[CP]:.+?\})(.+?)"$')
# Matches empty client strings in the format [key] = ""
reEmptyString = re.compile(r'^\[(.+?)\] = ""$')
# Matches a font tag in the format [Font:font_name]
reFontTag = re.compile(r'^\[Font:(.+?)\] = "(.+?)"')
# Global Dictionaries ---------------------------------------------------------
textUntranslatedLiveDict = {}
textUntranslatedPTSDict = {}
textTranslatedDict = {}
textUntranslatedDict = {}
# Global Dictionaries Use for reading en.lang, en_pts.lang, kr.lang -----------
currentFileIndexes = {}
currentFileStrings = {}
previousFileIndexes = {}
previousFileStrings = {}
translatedFileIndexes = {}
translatedFileStrings = {}
# Helper for escaped chars ----------------------------------------------------
def get_section_id(section_key):
return section.section_info.get(section_key, {}).get('sectionId', None)
def get_section_name(section_key):
return section.section_info.get(section_key, {}).get('sectionName', None)
def get_section_key_by_id(section_id):
for key, value in section.section_info.items():
if value['sectionId'] == section_id:
return key
return None
def escape_special_characters(text):
return text.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n').replace(r'\\\"', r'\"')
def isTranslatedText(line):
if line is None:
return False
return any(ord(char) > 127 for char in line)
# Conversion ------------------------------------------------------------------
# (txtFilename, idFilename)
@mainFunction
def addIndexToLangFile(txtFilename, idFilename):
"""
Add numeric identifiers as tags to language entries in a target file.
This function reads a source text file containing language data and a corresponding identifier file
containing unique numeric identifiers for each language entry. It then appends these identifiers as tags
to the respective lines in the target language file. The resulting output is saved in a new file named 'output.txt'.
Args:
txtFilename (str): The filename of the source text file containing language data (e.g., 'en.lang.txt').
idFilename (str): The filename of the identifier file containing unique numeric identifiers
(e.g., 'en.lang.id.txt').
Notes:
The source text file should contain text data, one entry per line, while the identifier file should
contain numeric identifiers corresponding to each entry in the same order.
The function reads both files, associates numeric identifiers with their respective entries, and appends
these identifiers as tags in the output file. The output file is saved in the same directory as the script.
Example:
Given a source text file 'en.lang.txt':
```
Hello, world!
How are you?
```
And an identifier file 'en.lang.id.txt':
```
18173141-0-2944
7949764-0-51729
```
Calling `addIndexToLangFile('en.lang.txt', 'en.lang.id.txt')` will produce an output file 'output.txt':
```
{{18173141-0-2944:}}Hello, world!
{{7949764-0-51729:}}How are you?
```
"""
textLines = []
idLines = []
# Read text file and count lines
textLineCount = 0
with open(txtFilename, 'r', encoding="utf8") as textIns:
for line in textIns:
newstr = line.rstrip()
textLines.append(newstr)
textLineCount += 1
# Read identifier file and count lines
idLineCount = 0
with open(idFilename, 'r', encoding="utf8") as idIns:
for line in idIns:
newstr = line.strip()
idLines.append(newstr)
idLineCount += 1
if textLineCount != idLineCount:
print("Error: Number of lines in text and identifier files do not match. Aborting.")
return
with open('output.txt', 'w', encoding="utf8") as output:
for i in range(len(textLines)):
lineOut = '{{{{{}:}}}}'.format(idLines[i]) + textLines[i] + '\n'
output.write(lineOut)
@mainFunction
def removeIndexToLangFile(txtFilename):
"""
Remove numeric identifiers from language entries in a target file.
This function reads a target text file containing language entries with numeric identifiers as tags
and removes these identifiers, resulting in a clean language text file. The output is saved in a new file named 'output.txt'.
Args:
txtFilename (str): The filename of the target text file containing language entries with identifiers (e.g., 'en.lang.txt').
Notes:
The function uses regular expressions to detect and remove numeric identifiers that are enclosed in double curly braces.
It then writes the cleaned entries to the output file 'output.txt' in the same directory as the script.
Example:
Given a target text file 'en.lang.txt':
```
{{18173141-0-2944:}}Hello, world!
{{7949764-0-51729:}}How are you?
```
Calling `removeIndexToLangFile('en.lang.txt')` will produce an output file 'output.txt':
```
Hello, world!
How are you?
```
"""
# Get ID numbers ------------------------------------------------------
textLines = []
with open(txtFilename, 'r', encoding="utf8") as textIns:
for line in textIns:
matchIndex = reLangIndex.match(line)
matchIndexOld = reLangIndexOld.match(line)
if matchIndex:
text = matchIndex.group(2)
textLines.append(text)
if matchIndexOld:
text = matchIndexOld.group(2)
newString = text.lstrip()
textLines.append(newString)
with open("output.txt", 'w', encoding="utf8") as out:
for line in textLines:
lineOut = '{}\n'.format(line)
out.write(lineOut)
@mainFunction
def koreanToEso(txtFilename):
"""
Convert Korean UTF-8 encoded text to Chinese UTF-8 encoded text with byte offset.
This function reads a source text file containing Korean UTF-8 encoded text and applies a byte offset to convert it to
Chinese UTF-8 encoded text. The byte offset is used to shift the Korean text to a range that is normally occupied by
Chinese characters. This technique is used in Elder Scrolls Online (ESO) to display Korean text using a nonstandard font
that resides in the Chinese character range. The converted text is saved in a new file named 'output.txt'.
Args:
txtFilename (str): The filename of the source text file containing Korean UTF-8 encoded text.
Notes:
- The function reads the source file in binary mode and applies a byte-level analysis to determine the proper conversion.
- A byte offset is added to the Unicode code points of the Korean characters to position them within the Chinese character range.
- The resulting Chinese UTF-8 encoded text is written to the 'output.txt' file in UTF-8 encoding.
Example:
Given a source text file 'korean.txt' with Korean UTF-8 encoded text:
```
나는 가고 싶다
```
Calling `koreanToEso('korean.txt')` will produce an output file 'output.txt':
```
犘璔 渀滠 蓶瓤
```
"""
not_eof = True
with open(txtFilename, 'rb') as textIns:
with open("output.txt", 'w', encoding="utf8") as out:
while not_eof:
shift = 1
char = textIns.read(shift)
value = int.from_bytes(char, "big")
next_char = None
if value > 0x00 and value <= 0x74:
shift = 1
elif value >= 0xc0 and value <= 0xdf:
shift = 2
elif value >= 0xe0 and value <= 0xef:
shift = 3
elif value >= 0xf0 and value <= 0xf7:
shift = 4
if shift > 1:
next_char = textIns.read(shift - 1)
if next_char:
char = b''.join([char, next_char])
if not char:
# eof
break
temp = int.from_bytes(char, "big")
if temp >= 0xE18480 and temp <= 0xE187BF:
temp = temp + 0x43400
elif temp > 0xE384B0 and temp <= 0xE384BF:
temp = temp + 0x237D0
elif temp > 0xE38580 and temp <= 0xE3868F:
temp = temp + 0x23710
elif temp >= 0xEAB080 and temp <= 0xED9EAC:
if temp >= 0xEAB880 and temp <= 0xEABFBF:
temp = temp - 0x33800
elif temp >= 0xEBB880 and temp <= 0xEBBFBF:
temp = temp - 0x33800
elif temp >= 0xECB880 and temp <= 0xECBFBF:
temp = temp - 0x33800
else:
temp = temp - 0x3F800
char = temp.to_bytes(shift, byteorder='big')
outText = codecs.decode(char, 'UTF-8')
out.write(outText)
@mainFunction
def esoToKorean(txtFilename):
"""
Convert Chinese UTF-8 encoded text to traditional Korean UTF-8 encoded text with byte offset reversal.
This function reads a source text file containing Chinese UTF-8 encoded text and applies an opposite byte offset to
convert it to traditional Korean UTF-8 encoded text. The byte offset reversal is used to shift the Chinese text back
to its original traditional Korean character range. This technique is used when working with Chinese text that has
been encoded using a byte offset to simulate Korean characters. The converted text is saved in a new file named 'output.txt'.
Args:
txtFilename (str): The filename of the source text file containing Chinese UTF-8 encoded text (e.g., 'kr.lang.txt').
Notes:
- The function reads the source file in binary mode and applies a byte-level analysis to determine the proper conversion.
- An opposite byte offset is subtracted from the Unicode code points of the Chinese characters to convert them back to
their original traditional Korean characters.
- The resulting traditional Korean UTF-8 encoded text is written to the 'output.txt' file in UTF-8 encoding.
Example:
Given a source text file 'kr.lang.txt' with Chinese UTF-8 encoded text:
```
犘璔 渀滠 蓶瓤
```
Calling `esoToKorean('kr.lang.txt')` will produce an output file 'output.txt':
```
나는 가고 싶다
```
"""
not_eof = True
with open(txtFilename, 'rb') as textIns:
with open("output.txt", 'w', encoding="utf8") as out:
while not_eof:
shift = 1
char = textIns.read(shift)
value = int.from_bytes(char, "big")
next_char = None
if value > 0x00 and value <= 0x74:
shift = 1
elif value >= 0xc0 and value <= 0xdf:
shift = 2
elif value >= 0xe0 and value <= 0xef:
shift = 3
elif value >= 0xf0 and value <= 0xf7:
shift = 4
if shift > 1:
next_char = textIns.read(shift - 1)
if next_char:
char = b''.join([char, next_char])
if not char:
# eof
break
temp = int.from_bytes(char, "big")
if temp >= 0xE5B880 and temp <= 0xE5BBBF:
temp = temp - 0x43400
elif temp > 0xE5BC80 and temp <= 0xE5BC8F:
temp = temp - 0x237D0
elif temp > 0xE5BC90 and temp <= 0xE5BD9F:
temp = temp - 0x23710
elif temp >= 0xE6B880 and temp <= 0xE9A6AC:
if temp >= 0xE78080 and temp <= 0xE787BF:
temp = temp + 0x33800
elif temp >= 0xE88080 and temp <= 0xE887BF:
temp = temp + 0x33800
elif temp >= 0xE98080 and temp <= 0xE987BF:
temp = temp + 0x33800
else:
temp = temp + 0x3F800
char = temp.to_bytes(shift, byteorder='big')
outText = codecs.decode(char, 'UTF-8')
out.write(outText)
@mainFunction
def addIndexToEosui(txtFilename):
"""
Add numeric tags to language entries in kr_client.str or kr_pregame.str for use with translation files.
This function reads a target text file containing language entries in the format of [key] = "value" pairs,
such as 'kr_client.str' or 'kr_pregame.str'. It then adds numeric tags to the entries and generates new entries
with the format [key] = "{C:numeric_tag}value" or [key] = "{P:numeric_tag}value", based on whether the entries
are intended for the client or pregame context.
Args:
txtFilename (str): The filename of the target text file containing language entries (e.g., 'kr_client.str' or 'kr_pregame.str').
Notes:
- The function uses regular expressions to detect and modify the entries.
- Entries listed in the 'no_prefix_indexes' list will retain their original format without numeric tags.
Example:
Given a target text file 'kr_client.str':
```
[SI_PLAYER_NAME] = "Player Name"
[SI_PLAYER_LEVEL] = "Player Level"
```
Calling `addIndexToEosui('kr_client.str')` will produce an output file 'output.txt':
```
[SI_PLAYER_NAME] = "{C:1}Player Name"
[SI_PLAYER_LEVEL] = "{C:2}Player Level"
```
"""
no_prefix_indexes = [
"SI_INTERACT_PROMPT_FORMAT_PLAYER_NAME",
"SI_PLAYER_NAME",
"SI_PLAYER_NAME_WITH_TITLE_FORMAT",
"SI_MEGASERVER0",
"SI_MEGASERVER1",
"SI_MEGASERVER2",
"SI_KEYBINDINGS_LAYER_BATTLEGROUNDS",
"SI_KEYBINDINGS_LAYER_DIALOG",
"SI_KEYBINDINGS_LAYER_GENERAL",
"SI_KEYBINDINGS_LAYER_HOUSING_EDITOR",
"SI_KEYBINDINGS_LAYER_HOUSING_EDITOR_PLACEMENT_MODE",
"SI_KEYBINDINGS_LAYER_HUD_HOUSING",
"SI_KEYBINDINGS_LAYER_INSTANCE_KICK_WARNING",
"SI_KEYBINDINGS_LAYER_NOTIFICATIONS",
"SI_KEYBINDINGS_LAYER_SIEGE",
"SI_KEYBINDINGS_LAYER_USER_INTERFACE_SHORTCUTS",
"SI_KEYBINDINGS_LAYER_UTILITY_WHEEL",
"SI_SLASH_CAMP",
"SI_SLASH_CHATLOG",
"SI_SLASH_DUEL_INVITE",
"SI_SLASH_ENCOUNTER_LOG",
"SI_SLASH_FPS",
"SI_SLASH_GROUP_INVITE",
"SI_SLASH_JUMP_TO_FRIEND",
"SI_SLASH_JUMP_TO_GROUP_MEMBER",
"SI_SLASH_JUMP_TO_GUILD_MEMBER",
"SI_SLASH_JUMP_TO_LEADER",
"SI_SLASH_LATENCY",
"SI_SLASH_LOGOUT",
"SI_SLASH_PLAYED_TIME",
"SI_SLASH_QUIT",
"SI_SLASH_READY_CHECK",
"SI_SLASH_RELOADUI",
"SI_SLASH_REPORT_BUG",
"SI_SLASH_REPORT_CHAT",
"SI_SLASH_REPORT_FEEDBACK",
"SI_SLASH_REPORT_HELP",
"SI_SLASH_ROLL",
"SI_SLASH_SCRIPT",
"SI_SLASH_STUCK",
]
textLines = []
indexPrefix = ""
if re.search('client', txtFilename):
indexPrefix = "C:"
if re.search('pregame', txtFilename):
indexPrefix = "P:"
with open(txtFilename, 'r', encoding="utf8") as textIns:
for indexCount, line in enumerate(textIns, start=1):
maFontTag = reFontTag.match(line)
maClientUntaged = reClientUntaged.match(line)
maEmptyString = reEmptyString.match(line)
if maFontTag:
textLines.append(line)
continue
elif maEmptyString:
conIndex = maEmptyString.group(1) # Key (conIndex)
lineOut = '[{}] = ""\n'.format(conIndex)
textLines.append(lineOut)
elif maClientUntaged:
conIndex = maClientUntaged.group(1) # Key (conIndex)
conText = maClientUntaged.group(2) if maClientUntaged.group(2) is not None else ''
if conIndex not in no_prefix_indexes and maClientUntaged.group(2) is not None:
lineOut = '[{}] = "{{{}}}{}"\n'.format(conIndex, indexPrefix + str(indexCount), conText)
else:
lineOut = '[{}] = "{}"\n'.format(conIndex, conText)
textLines.append(lineOut)
with open("output.txt", 'w', encoding="utf8") as out:
for line in textLines:
out.write(line)
@mainFunction
def removeIndexFromEosui(txtFilename):
"""
Remove tags and identifiers from either kr_client.str or kr_pregame.str for use with official release.
This function reads a target text file containing entries with tags and identifiers and removes these tags and identifiers,
resulting in a clean language text file. The output is saved in a new file named 'output.txt'.
Args:
txtFilename (str): The filename of the target text file containing entries with tags and identifiers
(e.g., 'kr_client.str' or 'kr_pregame.str').
Notes:
- The function uses regular expressions to detect and remove tags, identifiers, and empty lines.
- Entries containing '[Font:' are skipped, as well as empty lines.
- The cleaned entries are written to the output file 'output.txt' in the same directory as the script.
Example:
Given a target text file 'kr_client.str':
```
[SI_LOCATION_NAME] = "{C:10207}Gonfalon Bay"
```
Calling `removeIndexFromEosui('kr_client.str')` will produce an output file 'output.txt':
```
[SI_LOCATION_NAME] = "Gonfalon Bay"
```
"""
textLines = []
with open(txtFilename, 'r', encoding="utf8") as textIns:
for line in textIns:
line = line.rstrip()
maFontTag = reFontTag.search(line)
maEmptyString = reEmptyString.search(line)
if maFontTag or maEmptyString:
textLines.append(line + "\n")
continue
maClientTaged = reClientTaged.match(line)
if maClientTaged:
conIndex = maClientTaged.group(1)
conText = maClientTaged.group(3)
lineOut = '[{}] = "{}"\n'.format(conIndex, conText)
textLines.append(lineOut)
# When text is present without {P:650} or {C:345}
if line is not None:
if not maFontTag and not maEmptyString and not maClientTaged:
textLines.append(line + "\n")
with open("output.txt", 'w', encoding="utf8") as out:
for lineOut in textLines:
out.write(lineOut)
def readUInt32(file): return struct.unpack('>I', file.read(4))[0]
def writeUInt32(file, value): file.write(struct.pack('>I', value))
def readNullStringByChar(offset, start, file):
"""Reads one byte and any subsequent bytes of a multi byte sequence."""
nullChar = False
textLine = None
currentPosition = file.tell()
file.seek(start + offset)
while not nullChar:
shift = 1
char = file.read(shift)
value = int.from_bytes(char, "big")
next_char = None
if value > 0x00 and value <= 0x74:
shift = 1
elif value >= 0xc0 and value <= 0xdf:
shift = 2
elif value >= 0xe0 and value <= 0xef:
shift = 3
elif value >= 0xf0 and value <= 0xf7:
shift = 4
if shift > 1:
next_char = file.read(shift - 1)
if next_char:
char = b''.join([char, next_char])
if not char:
# eof
break
if textLine is None:
textLine = char
continue
if textLine is not None and char != b'\x00':
textLine = b''.join([textLine, char])
# if textLine is not None and char != b'\x00' and char == b'\x0A':
# textLine = b''.join([textLine, b'\x5C\x6E'])
if textLine is not None and char == b'\x00':
nullChar = True
file.seek(currentPosition)
return textLine
def readNullString(offset, start, file):
"""Reads a null-terminated string from the file, starting at the given offset within the chunk.
Args:
offset (int): The offset within the chunk to start reading the string.
start (int): The starting position within the file.
file (file): The file object to read from.
Returns:
bytes: The read null-terminated string.
"""
chunkSize = 1024
nullChar = False
textLine = b''
currentPosition = file.tell()
file.seek(start + offset)
while not nullChar:
chunk = file.read(chunkSize)
if not chunk:
# End of file
break
null_index = chunk.find(b"\x00")
if null_index >= 0:
# Found the null terminator within the chunk
textLine += chunk[:null_index]
nullChar = True
else:
# Null terminator not found in this chunk, so append the whole chunk to textLine
textLine += chunk
file.seek(currentPosition)
return textLine
def readLangFile(languageFileName):
"""Read a language file and extract index and string information.
Args:
languageFileName (str): The name of the language file to read.
Returns:
dict, dict: Dictionaries containing index and string information.
"""
with open(languageFileName, 'rb') as lineIn:
numSections = readUInt32(lineIn)
numIndexes = readUInt32(lineIn)
stringsStartPosition = 8 + (16 * numIndexes)
predictedOffset = 0
stringCount = 0
fileIndexes = {'numIndexes': numIndexes, 'numSections': numSections}
fileStrings = {'stringCount': stringCount}
for index in range(numIndexes):
chunk = lineIn.read(16)
sectionId, sectionIndex, stringIndex, stringOffset = struct.unpack('>IIII', chunk)
indexString = readNullString(stringOffset, stringsStartPosition, lineIn)
fileIndexes[index] = {
'sectionId': sectionId,
'sectionIndex': sectionIndex,
'stringIndex': stringIndex,
'stringOffset': stringOffset,
'string': indexString
}
if indexString not in fileStrings:
# Create a dictionary entry for the offset with the indexString as a key
fileStrings[indexString] = {
'stringOffset': predictedOffset,
}
# Create a dictionary entry for the string with stringCount as a key
fileStrings[stringCount] = {
'string': indexString,
}
# add one to stringCount
stringCount += 1
# 1 extra for the null terminator
predictedOffset += (len(indexString) + 1)
fileStrings['stringCount'] = stringCount
return fileIndexes, fileStrings
def writeLangFile(languageFileName, fileIndexes, fileStrings):
"""Write index and string information back to a language file.
Args:
languageFileName (str): The name of the language file to write to.
fileIndexes (dict): Dictionary containing index information.
fileStrings (dict): Dictionary containing string information.
"""
numIndexes = fileIndexes['numIndexes']
numSections = fileIndexes['numSections']
numStrings = fileStrings['stringCount']
# Read the indexes and update offset if string length has changed.
for index in range(numIndexes):
currentIndex = fileIndexes[index]
dictString = currentIndex['string']
currentStringInfo = fileStrings[dictString]
currentOffset = currentStringInfo['stringOffset']
fileIndexes[index]['stringOffset'] = currentOffset
with open(languageFileName, 'wb') as indexOut:
writeUInt32(indexOut, numSections)
writeUInt32(indexOut, numIndexes)
for index in range(numIndexes):
currentIndex = fileIndexes[index]
sectionId = currentIndex['sectionId']
sectionIndex = currentIndex['sectionIndex']
stringIndex = currentIndex['stringIndex']
stringOffset = currentIndex['stringOffset']
chunk = struct.pack('>IIII', sectionId, sectionIndex, stringIndex, stringOffset)
indexOut.write(chunk)
for index in range(numStrings):
currentDict = fileStrings[index]
currentString = currentDict['string']
indexOut.write(currentString + b'\x00')
@mainFunction
def readCurrentLangFile(currentLanguageFile):
"""Reads a language file, stores index and string data, and writes to an output file.
Args:
currentLanguageFile (str): The name of the current language file to read.
Note:
This function reads the provided language file, extracts index and string information,
updates string offsets if needed, and writes the data back to an output file named 'output.lang'.
"""
currentFileIndexes, currentFileStrings = readLangFile(currentLanguageFile)
print(currentFileStrings['stringCount'])
writeLangFile('output.lang', currentFileIndexes, currentFileStrings)
def processSectionIDs(outputFileName, currentFileIndexes):
numIndexes = currentFileIndexes['numIndexes']
currentSection = None
sectionCount = 0
with open(outputFileName, 'w') as sectionOut:
for index in range(numIndexes):
currentIndex = currentFileIndexes[index]
sectionId = currentIndex['sectionId']
if sectionId != currentSection:
sectionCount += 1
sectionOut.write(" 'section_unknown_{}': {{'sectionId': {}, 'sectionName': 'section_unknown_{}'}},\n".format(sectionCount, sectionId, sectionCount))
currentSection = sectionId
@mainFunction
def extractSectionIDs(currentLanguageFile, outputFileName):
"""
Extract section ID numbers from a language file and write them to an output file.
This function reads a provided language file, extracts the section ID numbers
associated with the strings in the language file, and writes a list of unique
section ID numbers to the specified output file.
Args:
currentLanguageFile (str): The name of the current language file to read.
outputFileName (str): The name of the output file to write section ID numbers to.
Note:
The extracted section ID numbers are written to the output file in the format:
section_unknown_1 = <section_id>
section_unknown_2 = <section_id>
...
Example:
Given a language file 'en.lang' containing strings and section ID information,
calling extractSectionIDs('en.lang', 'section_ids.txt') will create 'section_ids.txt'
with a list of unique section ID numbers.
"""
currentFileIndexes, currentFileStrings = readLangFile(currentLanguageFile)
processSectionIDs(outputFileName, currentFileIndexes)
@mainFunction
def combineClientFiles(client_filename, pregame_filename):
"""
Combine content from en_client.str and en_pregame.str files.
This function reads the content of en_client.str and en_pregame.str files, extracts
constant entries that match the pattern defined by reClientUntaged, and saves the combined
information into an 'output.txt' file. The goal is to avoid duplication of SI_ constants
by combining the entries from both files. If a constant exists in both files, only one
entry will be written to the output file to eliminate duplicated constants for translation.
Args:
client_filename (str): The filename of the en_client.str file.
pregame_filename (str): The filename of the en_pregame.str file.
Notes:
This function uses regular expressions to identify and extract constant entries
from the input files. The extracted entries are then formatted and stored in the
'output.txt' file.
Example:
Given en_client.str:
```
[SI_MY_CONSTANT] = "My Constant Text"
[SI_CONSTANT] = "Some Constant Text"
```
Given en_pregame.str:
```
[SI_CONSTANT] = "Some Constant Text"
[SI_ADDITIONAL_CONSTANT] = "Additional Constant Text"
```
Calling `combineClientFiles('en_client.str', 'en_pregame.str')` will produce an output file 'output.txt':
```
[SI_MY_CONSTANT] = "My Constant Text"
[SI_CONSTANT] = "Some Constant Text"
[SI_ADDITIONAL_CONSTANT] = "Additional Constant Text"
```
"""
textLines = []
conIndex_set = set()
def extract_constant(line):
conIndex = None
conText = None
maClientUntaged = reClientUntaged.match(line)
maEmptyString = reEmptyString.match(line)
if maEmptyString:
conIndex = maEmptyString.group(1) # Key (conIndex)
conText = ''
elif maClientUntaged:
conIndex = maClientUntaged.group(1) # Key (conIndex)
conText = maClientUntaged.group(2) if maClientUntaged.group(2) is not None else ''
return conIndex, conText
def add_line(conIndex, conText):
if conIndex not in conIndex_set:
escaped_conText = escape_special_characters(conText)
textLines.append('[{}] = "{}"\n'.format(conIndex, escaped_conText))
conIndex_set.add(conIndex)
def process_text_file(filename):
with open(filename, 'r', encoding="utf8") as textInsClient:
for line in textInsClient:
line = line.rstrip()
if line.startswith("["):
conIndex, conText = extract_constant(line)
add_line(conIndex, conText)
else:
textLines.append(line + "\n")
# Process client.str file
process_text_file(client_filename)
# Process pregame.str file
process_text_file(pregame_filename)
# Write output to output.txt
with open("output.txt", 'w', encoding="utf8") as out:
for lineOut in textLines:
out.write(lineOut)
@mainFunction
def createWeblateFile(input_filename, langValue, langTag):
"""
Generate separate YAML-like files for Weblate translation.
This function reads the 'output.txt' file generated by the combineClientFiles function
and creates separate YAML-like files for use with Weblate translation. The langValue parameter
is used to specify the language value, such as 'turkish', to be used as the name of the translated
string in the resulting YAML files. The langTag parameter specifies the language tag to be used
as the first line in the output files.
Args:
input_filename (str): The filename of the 'output.txt' file generated by combineClientFiles.
langValue (str): The language value to use as the name of the translated string.
langTag (str): The language tag to be used as the first line in the output files.
Notes:
This function extracts constant entries using the reClientUntaged pattern from the input file,
creates separate dictionaries of translations for each language, and generates separate YAML-like
files with the format suitable for Weblate.
Example:
Given 'output.txt':
```
[SI_MY_CONSTANT] = "My Constant Text"
[SI_CONSTANT] = "Some Constant Text"
[SI_ADDITIONAL_CONSTANT] = "Additional Constant Text"
```
Calling `createWeblateFile('output.txt', 'turkish', 'tr')` will produce two output files:
- 'output_tr.yaml':
```
tr:
SI_MY_CONSTANT:
turkish: "My Constant Text"
SI_CONSTANT:
turkish: "Some Constant Text"
SI_ADDITIONAL_CONSTANT:
turkish: "Additional Constant Text"
```
- 'output_en.yaml':
```
en:
SI_MY_CONSTANT:
english: "My Constant Text"
SI_CONSTANT:
english: "Some Constant Text"
SI_ADDITIONAL_CONSTANT:
english: "Additional Constant Text"
```
"""
output_filename = os.path.splitext(input_filename)[0] + "_output_" + langTag + ".yaml"
try:
with open(input_filename, 'r', encoding="utf8") as textIns:
translations = {}
for line in textIns:
maEmptyString = reEmptyString.match(line)
maClientUntaged = reClientUntaged.match(line)
if maEmptyString:
conIndex = maEmptyString.group(1) # Key (conIndex)
conText = ''
translations[conIndex] = conText
elif maClientUntaged:
conIndex = maClientUntaged.group(1) # Key (conIndex)
conText = maClientUntaged.group(2) if maClientUntaged.group(2) is not None else ''
translations[conIndex] = conText
except FileNotFoundError:
print("{} not found. Aborting.".format(input_filename))
return
if not translations:
print("No translations found in {}. Aborting.".format(input_filename))
return
# Generate the YAML-like output
with open(output_filename, 'w', encoding="utf8") as weblate_file:
weblate_file.write("weblate:\n")
for conIndex, conText in translations.items():
weblate_file.write(' {}: "{}"\n'.format(conIndex, conText))
print("Generated Weblate file: {}".format(output_filename))
@mainFunction
def importClientTranslations(inputYaml, inputClientFile, langValue):
"""
Import translated text from a YAML file into the client or pregame file.
This function reads the translated text from the specified inputYaml file,
which is generated by the createWeblateFile function. It then updates the specified
language's translation in either the inputClientFile (en_client.str) or inputPregameFile (en_pregame.str).
Args: