-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpy3TranslateLLM.py
More file actions
2370 lines (1964 loc) · 184 KB
/
py3TranslateLLM.py
File metadata and controls
2370 lines (1964 loc) · 184 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
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
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Description: py3TranslateLLM.py translates text using Neural Machine Translation (NMT) and Large Language Models (LLM).
Usage: See py3TranslateLLM.py -h', README.md, and the source code below.
License:
- This .py file and the libraries under resources/* are Copyright (c) 2024 gdiaz384 ; License: GNU Affero GPL v3.
- https://www.gnu.org/licenses/agpl-3.0.html
- Exclusion: The libraries under resources/translationEngines/* may each have different licenses.
- For the various 3rd party libraries outside of resources/, see the Readme for their licenses, source code, and project pages.
"""
__version__ = '2024.11.17-alpha'
# Set defaults and static variables.
# Do not change the defaultTextEncoding. This is heavily overloaded.
defaultTextEncoding = 'utf-8'
defaultConsoleEncoding = 'utf-8'
#These default paths are relative to the location of py3TranslateLLM.py, -not- relative to the current path of the command prompt.
defaultLanguageCodesFile = 'resources/languageCodes.csv'
defaultSourceLanguage = None
#defaultSourceLanguage = 'Japanese'
defaultTargetLanguage = None
#defaultTargetLanguage = 'English'
# Valid options are 'English (American)' or 'English (British)'
defaultEnglishLanguage = 'English (American)'
# Valid options are 'Chinese (simplified)' or 'Chinese (traditional)'
defaultChineseLanguage = 'Chinese (simplified)'
# Valid options are 'Portuguese (European)' or 'Portuguese (Brazilian)'
defaultPortugueseLanguage = 'Portuguese (European)'
validSpreadsheetExtensions = [ '.csv', '.xlsx', '.xls', '.ods', '.tsv' ]
defaultAddress = 'http://localhost'
defaultKoboldCppPort = 5001
defaultPy3translationServerPort = 14366
defaultSugoiPort = 14366
minimumPortNumber = 1
maximumPortNumber = 65535 #16 bit integer -1
defaultPortForHTTP = 80
defaultPortForHTTPS = 443
defaultTimeout = 360 # Per request to translation engine in seconds. Set to 0 to disable.
# LLMs tend to hallucinate, so setting this overly high tends to corrupt the output. It should also be reset back to 0 periodically, like when it gets full, so the corruption of one bad entry does not spread too much. Sane values are 4-10.
defaultContextHistoryMaxLength = 6
# This setting only affects LLMs, not NMTs.
defaultEnableBatchesForLLMs = False
# Valid options for defaultBatchSizeLimit are an integer or None. Sensible limits are 100-10000 depending upon hardware. In addition to this setting, translation engines also have internal limiters.
#defaultBatchSizeLimit = None
defaultBatchSizeLimit = 1000
defaultSceneSummaryLength = 40
defaultInputTextEncodingErrorHandler = 'strict'
#defaultOutputTextEncodingErrorHandler = 'namereplace' # This get set dynamically further below.
defaultLinesThatBeginWithThisAreComments = '#'
defaultAssignmentOperatorInSettingsFile = '='
defaultMetadataDelimiter = '_'
defaultScriptSettingsFileExtension = '.ini'
# if a column begins with one of these entries, then it will be assumed to be invalid for cacheAnyMatch. Case insensitive.
defaultBlacklistedHeadersForCache = [ 'rawText', 'speaker', 'hashedText', 'metadata' ] #'cache', 'cachedEntry', 'cache entry'
# Currently, these are relative to py3TranslateLLM.py, but it might also make sense to move them either relative to the target or to a system folder intended for holding program data.
# There is no gurantee that being relative to the target is a sane thing to do since that depends upon runtime usage, and centralized backups also make sense. Leaving it as-is makes sense too as long as py3TranslateLLM is not being used as a library. If it is not being used as a library, then a centralized location under $HOME or %localappdata% makes more sense than relative to py3TranslateLLM.py. Same with the default location for the cache file.
# Maybe a good way to check for this is the name = __main__ check?
# It might make sense to create the spreadsheet.translated.backup.[date].xlsx relative to the target spreadsheed or perhaps in a backups folder that is relative to the target. However, cache should be either centralized in an os specific application data directory or stored along with main program.
defaultBackupsFolder = 'backups'
defaultExportExtension = '.xlsx'
defaultCacheFileLocation = defaultBackupsFolder + '/cache' + defaultExportExtension
defaultSceneSummaryCacheLocation = defaultBackupsFolder + '/sceneSummaryCache' + defaultExportExtension
# cache and mainSpreadsheet are always saved at the end of an operation, so these timers are only used for translations that take a very long time. cache will not be saved if there were not any new entries added to it.
defaultMinimumSaveIntervalForMainSpreadsheet = 540 #240 # In seconds. 240 is every 4 minutes. 540 is every 9 minutes
#defaultMinimumSaveIntervalForCache = 60 # For debugging.
defaultMinimumSaveIntervalForCache = 300 # In seconds. 300 if 5 min. 240 is once every four minutes which means that, at most, only four minutes worth of processing time should be lost due to a program or translation engine error.
defaultMinimumSaveIntervalForSceneSummaryCache = 240 # In seconds. 540 is 9 minutes. 300 is 5 min. SceneSummary tends to be a large number of lines compressed into relatively few entries, and be missing translationEngines that do not support the sceneSummary feature, so it should not grow in size as much as regular cache and mainSpreadsheet. For that reason, backing it up more often should not impose an undo burden on the hardware.
# These two lists do not determine if the values are True/ False by default. Use action='store_true' and 'store_false' in the CLI options to toggle defaults and then update these two lists. These lists ensure the values are toggled correctly if a different than default setting is specified in program.ini when merging the CLI options with the options from the .ini .
booleanValuesTrueByDefault = [ 'cache', 'contextHistory', 'contextHistoryReset', 'batches', 'backups']
booleanValuesFalseByDefault = [ 'cacheAnyMatch', 'overwriteWithCache', 'overwriteWithSpreadsheet', 'reTranslate', 'readOnlyCache', 'sceneSummaryEnableTranslation', 'batchesEnabledForLLMs', 'rebuildCache', 'resume', 'testRun', 'verbose', 'debug', 'version' ]
translationEnginesAvailable = 'cacheOnly, koboldcpp, py3translationserver, sugoi, deepl_api_free, deepl_api_pro, deepl_web, pykakasi, cutlet'
usageHelp = 'Usage: python py3TranslateLLM --help Translation Engines: \n' + translationEnginesAvailable + '. Example: py3TranslateLLM -te KoboldCpp -f myInputFile.ks.xlsx -sl jpn -tl eng'
# import various libraries that py3TranslateLLM depends on.
import argparse # Used to add command line options.
import os, os.path # Extract extension from filename, and test if file exists.
#from pathlib import Path # Override file in file system with another and create subfolders.
#import pathlib.Path # Does not work. Why not? Maybe because Path is a class and not a Path.py file? So 'from' crawls into files? Maybe from 'requires' it. Like Path must be a class inside of pathlib instead of a file named Path.py. 'import' does not seem to care whether it is importing files or classes. They are both made available. But 'from' might.
import pathlib # Works. #dir(pathlib) does list 'Path', so just always use as pathlib.Path Constructor is pathlib.Path(mystring). Remember to convert it back to a string if printing it out.
import sys # End program on fail condition.
import io # Manipulate files (open/read/write/close).
import random # Used to get a random number. Used when writing out cache and sceneSummaryCache to a temporary file.
#import datetime # Used to get current date and time.
import time # Used to write out cache no more than once every 300s and also limit writes to mySpreadsheet.backup.xlsx .
# Technically, these two are optional for parseOnly. To support or not support such a thing... probably yes. # Update: Maybe. # Update removed parseOnly. Added --testRun functionality as a replacement.
#from collections import deque # Used to hold rolling history of translated items to use as context for new translations.
import collections # Newer syntax. For collections.deque. Used to hold rolling history of translated items to use as context for new translations.
#import queue # collections.deque is probably better but it lacks a lot of the methods, like full/empty booleans, that make queue convenient. Just give up and use lists instead. This needs to be changed to a superset of deque or something. Maybe a custom data structure based on lists?
import hashlib # Allow calculating the sha1 hash for batches of entries when using the experimental sceneSummary feature.
import requests # Do basic http stuff, like submitting post/get requests to APIs. Must be installed using: 'pip install requests' # Update: Moved to functions.py # Update: Also imported here because it can be useful to parse exceptions (errors) when submitting entries for translation.
#import openpyxl # Used as the core internal data structure and to read/write xlsx files. Must be installed using pip. # Update: Moved to chocolate.py
import resources.chocolate as chocolate # Implements openpyxl. A helper/wrapper library to aid in using openpyxl as a datastructure.
import resources.dealWithEncoding as dealWithEncoding # dealWithEncoding implements the 'chardet' library which is installed with 'pip install chardet' Same with 'pip install charamel' and 'pip install charset-normalizer'
import resources.functions as functions # Moved most generic functions here to increase code readability and enforce function best practices for logic not directly relevant to main().
# The above syntax assumes all of the libraries are under resources. To import the libraries directly regardless of where they are on the file system:
# import sys
# import pathlib
# sys.path.append( str( pathlib.Path('C:/resources/chocolate.py').resolve().parent ) )
# import chocolate
#from resources.functions import * # Do not use this syntax if at all possible. The * is fine, but the 'from' breaks everything because it copies everything instead of pointing to the original resources which makes updating library variables borderline impossible.
try:
import tqdm # Optional library to add pretty progress bars.
tqdmAvailable = True
except:
tqdmAvailable = False
#Using the 'namereplace' error handler for text encoding requires Python 3.5+, so use an older one if necessary.
if sys.version_info.minor >= 5:
defaultOutputTextEncodingErrorHandler = 'namereplace'
elif sys.version_info.minor < 5:
defaultOutputTextEncodingErrorHandler = 'backslashreplace'
# py3translateLLM.py supports reading program settings from py3translateLLM.ini in addition to the command prompt.
# Rule #1) is that settings from the command line take precedence.
# Then #2) entries from .ini
# Then #3) backup settings hardcoded in .py
# So, initialize all non-boolean CLI settings to None. Then, only change them using settings.ini or defaultSettings if they are still None after reading from CLI. Any settings that are not None were set using the CLI, so leave them alone.
# For boolean values, they are not set default. Only toggle True/False value if the scriptSettings set them.
# TODO:
# Implement -w --warning flag to warn if the spreadsheet has any None values by the end when it is time to output.
# There is a bug related to adding entries to cache where sometimes entries that have new lines \n in the middle will have their non-newline and the original both added to cache as separate entries. It might be related to the sceneSummaryCache code. Need to test more. What could cause it is sending a pair to translate, the processing code adjusting the list it is sent in real time, and then that same list, with the preprocessed text, being used to update the cache. Need to fix this. The easiest way to be sure is with a fresh cache.
# https://docs.python.org/3/library/copy.html # Maybe fix it with
# import copy
# newDictionary=copy.deepcopy(oldDictionary)
def createCommandLineOptions():
# Add command line options.
commandLineParser = argparse.ArgumentParser( description='Description: Translates text using various NMT and LLM models.\n ' + usageHelp )
commandLineParser.add_argument( '-te', '--translationEngine', help='Specify translation engine to use, options=' + translationEnginesAvailable + '. Not all engines have been implemented.', type=str )
commandLineParser.add_argument( '-f', '--fileToTranslate', help='Either the raw file to translate or the spreadsheet file to resume translating from, including path.', default=None, type=str )
commandLineParser.add_argument( '-fe', '--fileToTranslateEncoding', help='The encoding of the input file. Default=' + str( defaultTextEncoding ), default=None, type=str )
commandLineParser.add_argument( '-of', '--outputFile', help='The file to insert translations into, including path. Default is same as input file.', default=None, type=str )
commandLineParser.add_argument( '-ofe', '--outputFileEncoding', help='The encoding of the output file. Default is same as input file.', default=None, type=str)
commandLineParser.add_argument( '-pf', '--promptFile', help='This file has the prompt for the LLM containing the main instructions.', default=None, type=str )
commandLineParser.add_argument( '-pfe', '--promptFileEncoding', help='Specify encoding for prompt file, default=' + str( defaultTextEncoding ), default=None, type=str )
commandLineParser.add_argument( '-mf', '--memoryFile', help='This file has the memory for the LLM containing background information. Optional.', default=None, type=str )
commandLineParser.add_argument( '-mfe', '--memoryFileEncoding', help='Specify encoding for the memory file, default=' + str( defaultTextEncoding ), default=None, type=str )
commandLineParser.add_argument( '-lcf', '--languageCodesFile', help='Specify a custom name and path for languageCodes.csv. Default=\'' + str( defaultLanguageCodesFile ) + '\'.', default=None, type=str )
commandLineParser.add_argument( '-lcfe', '--languageCodesFileEncoding', help='The encoding of file languageCodes.csv. Default=' + str( defaultTextEncoding ), default=None, type=str )
commandLineParser.add_argument( '-sl', '--sourceLanguage', help='Specify language of source text. Default=' + str( defaultSourceLanguage ), default=None, type=str )
commandLineParser.add_argument( '-tl', '--targetLanguage', help='Specify target language. Default=' + str( defaultTargetLanguage ), default=None, type=str )
commandLineParser.add_argument( '-cnd', '--characterNamesDictionary', help='The file name and path of characterNames.csv', default=None, type=str )
commandLineParser.add_argument( '-cnde', '--characterNamesDictionaryEncoding', help='The encoding of file characterNames.csv. Default=' + str( defaultTextEncoding ), default=None, type=str )
commandLineParser.add_argument( '-revd', '--revertAfterTranslationDictionary', help='The file name and path of revertAfterTranslation.csv', default=None, type=str )
commandLineParser.add_argument( '-revde', '--revertAfterTranslationDictionaryEncoding', help='The encoding of file revertAfterTranslation.csv. Default=' + str( defaultTextEncoding ), default=None, type=str )
commandLineParser.add_argument( '-pred', '--preTranslationDictionary', help='The file name and path of preTranslation.csv', default=None, type=str)
commandLineParser.add_argument( '-prede', '--preTranslationDictionaryEncoding', help='The encoding of file preTranslation.csv. Default=' + str( defaultTextEncoding ), default=None, type=str)
commandLineParser.add_argument( '-postd', '--postTranslationDictionary', help='The file name and path of postTranslation.csv.', default=None, type=str )
commandLineParser.add_argument( '-postde', '--postTranslationDictionaryEncoding', help='The encoding of file postTranslation.csv. Default=' + str( defaultTextEncoding ), default=None, type=str )
# Update: postWritingToFileDictionary might only make sense for text files.
commandLineParser.add_argument( '-postwd', '--postWritingToFileDictionary', help='The file name and path of postWritingToFile.csv.', default=None, type=str )
commandLineParser.add_argument( '-postwde', '--postWritingToFileDictionaryEncoding', help='The encoding of file postWritingToFile.csv. Default=' + str( defaultTextEncoding ), default=None, type=str )
commandLineParser.add_argument( '-c', '--cache', help='Toggles cache. Specifying this will disable using or updating the cache file for translated entries. Default=Use the cache file to fill in previously translated entries and update it with new entries to speed up future translations.', action='store_false' )
commandLineParser.add_argument( '-cf', '--cacheFile', help='The location of the cache file. Must be in a spreadsheet format like .xlsx. Default=' + str( defaultCacheFileLocation ), default=None, type=str )
commandLineParser.add_argument( '-cam', '--cacheAnyMatch', help='Use all translation engines when considering the cache. Default=Only consider the current translation engine as valid for cache hits.', action='store_true' )
commandLineParser.add_argument( '-owc', '--overwriteWithCache', help='Override any already translated lines in mainSpreadsheet with results from the cache. Default=Do not override already translated lines. This setting is overridden by reTranslate. This setting takes precedence over overwriteWithSpreadsheet.', action='store_true' )
commandLineParser.add_argument( '-ows', '--overwriteWithSpreadsheet', help='Override any already translated lines in the cache using mainSpreadsheet. Default=Do not override the cache. This setting is overridden by reTranslate. overwriteWithCache takes precedence over this setting.', action='store_true' )
commandLineParser.add_argument( '-rt', '--reTranslate', help='Translate all lines even if they already have translations or are in the cache. Update the cache and spreadsheet with the new translations. Default=Do not translate cells that already have entries. Use the cache to fill in previously translated lines. This setting takes precedence over overwriteWithCache and overwriteWithSpreadsheet.', action='store_true' )
commandLineParser.add_argument( '-roc', '--readOnlyCache', help='Opens the cache file in read-only mode and disables updates to it or rebuilding it. This dramatically decreases the memory used by the cache file. Default=Read and write to the cache file. This setting takes precedence over rebuildCache.', action='store_true' )
commandLineParser.add_argument( '-rbc', '--rebuildCache', help='If there is any error detected when generating cache, this rebuilds the cache based on an existing spreadsheet. Rebuilding cache means removing blank lines and duplicates. Use this if the cache ever becomes corrupt. Rebuilding the cache lowers memory usage. The first column will be used as the untranslated data. Default=Error out if there is any error reading the cache file. The cache cannot be rebuilt if readOnlyCache is enabled.', action='store_true' )
commandLineParser.add_argument( '-ch', '--contextHistory', help='Toggles context history setting. This will toggle whether or not to keep track of previously translated entries and send them to the translation engine for subsequent translations to boost awareness of the current context. Default=Keep track of previously translated entries and submit them to the translation engines that support history to improve the quality of future translations. Specifying this will disable history.', action='store_false' )
# TODO: This UI is inconsistent. 0 should mean 'unlimited history' which means never clear history and just keep making the prompt longer and longer, as horrible an idea as that is.
# That contextHistory exists only within a given batchSizeLimit context should be considered a bug. Here is an algorithm to recover context history for the first translation despite the history not being part of the current batch:
# Algorithm If the rowNumber > 2, take the current rowNumber, like 20. Subtract another number, contextHistoryMaxLength, like 6. Get the range of numbers between the current number and the number after subtraction (13-20). Return every number in that range that is > 2. Use those numbers to lookup previously translated data from mainSpreadsheet and append that data to contextHistory before attempting to translate the first entry of the current batch.
# Implementing the above logic might not make sense right now because batchSizeLimit is currently overloaded to mean both interal and external batch sizes to simplify processing of the sceneSummary feature. That may change which might mean reimplementing the above algorithim a second time which is somewhat annoying.
commandLineParser.add_argument( '-chml', '--contextHistoryMaxLength', help='The number of previous translations that should be sent to the translation engine to provide context for the current translation. Sane values are 2-10. Set to 0 to disable a limit to contextHistory which is a bad idea because LLMs tend to start hallucinating after a while. Not all translation engines support context. The maximum size of contextHistory will always be less than batchSizeLimit and sceneSummaryLength, even if batches are disabled. Default=' + str( defaultContextHistoryMaxLength ), default=None, type=int )
commandLineParser.add_argument( '-chr', '--contextHistoryReset', help='Should contextHistory be fully reset when contextHistoryMaxLength is reached or should only the oldest entry be removed? Default=Fully reset contextHistory after reaching contextHistoryMaxLength in order to set a max to LLM hallucination errors that corrupt surrounding entries. Specifying this option means to remove the oldest entry instead of fully reseting the contextHistory buffer.', action='store_false' )
commandLineParser.add_argument( '-ssp', '--sceneSummaryPrompt', help='Experimental feature. The location of the sceneSummaryPrompt.txt file, a text file used to generate a summary of the untranslated text prior to translation. Only valid with specific translation engines. Specifying this text file will enable generating a scene summary prior to translation to potentially boost translation quality. Due to the highly experimental nature of this feature, translations are disabled by default when this feature is enabled in order to provide time to quality check the generated summary before attempting translation and to potentially use one engines/API to generate the summary and another for the subsequent translation. After quality checking the generated summaries, use -sset --sceneSummaryEnableTranslation to enable translations when using this feature. Actually using the summary during translation requires the following string to be present in either memory.txt or prompt.txt: {scene} Default=Do not generate a summary prior to translation.', default=None, type=str )
commandLineParser.add_argument( '-sspe', '--sceneSummaryPromptEncoding', help='Experimental feature. The encoding of the sceneSummaryPrompt.txt file. Default=' + defaultTextEncoding, default=None, type=str )
commandLineParser.add_argument( '-ssl', '--sceneSummaryLength', help='Experimental feature. The number of entries that should be summarized at any one time. If batches are enabled, batches and this will be reduced to the same number depending on whichever is lower. Set to 0 to disable limits when generating a summary. Reasonable amounts are 40-100. Default=' + str( defaultSceneSummaryLength ), default=None, type=int )
commandLineParser.add_argument( '-sset', '--sceneSummaryEnableTranslation', help='Enable the use of summaries of untranslated text when translating data. This always requires prompt.txt and sceneSummaryPrompt.txt files. sceneSummaryCache.xlsx will be used as cache. Default=Do not translate when generating a summary. The summary will be inserted in place of {scene} of memory.txt and prompt.txt', action='store_true' )
commandLineParser.add_argument( '-sscf', '--sceneSummaryCacheFile', help='Experimental feature. The location of the sceneSummaryCache.xlsx which stores a cache of every previously generated summary. Default=' + defaultSceneSummaryCacheLocation, default=None, type=str )
commandLineParser.add_argument( '-sscam', '--sceneSummaryCacheAnyMatch', help='Use all translation engines when considering the cache. Default=Only consider the current translation engine as valid for cache hits. This setting only affects sceneSummaryCache.', action='store_true' )
commandLineParser.add_argument( '-b', '--batches', help='Toggles if entries should be submitted for translations engines that support them. Enabling batches disables context history. Default=Batches are automatically enabled for NMTs that support batches and web APIs like DeepL, but disabled for LLMs. Specifying this will disable them globally for all engines.', action='store_false' )
commandLineParser.add_argument( '-bllm', '--batchesEnabledForLLMs', help='For translation engines that support both batches and single translations, should batches be enabled? Batches are automatically enabled for NMTs that support batches and DeepL regardless of this setting. Enabling batches for LLMs disables context history. Default=' + str( defaultEnableBatchesForLLMs ), action='store_true' )
commandLineParser.add_argument( '-bsl', '--batchSizeLimit', help='Specify the maximum number of translations that should be sent to the translation engine if that translation engine supports batches. Not all translation engines support batches. Set to 0 to not place any limits on the size of batches. Some translation engines might also have their own internal limiters not affected by this setting. If the scene summary feature is enabled, this and sceneSummaryLength will be reduced to the same number depending on whichever is lower. Default=' + str( defaultBatchSizeLimit ), default=None, type=int )
commandLineParser.add_argument( '-a', '--address', help='Specify the protocol and IP for NMT/LLM server, Example: http://192.168.0.100', default=None,type=str )
commandLineParser.add_argument( '-port', '--port', help='Specify the port for the NMT/LLM server. Example: 5001', default=None, type=int )
commandLineParser.add_argument( '-to', '--timeout', help='Specify the maximum number of seconds each individual request can take before quiting. Default=' + str( defaultTimeout ), default=None, type=int )
commandLineParser.add_argument( '-bk', '--backups', help='This setting toggles writing backup files for mainSpreadsheet. This setting does not affect cache. Default=Write mainSpreadsheet to backups/[date]/* periodically for use with --resume. Specifying this will disable creating backups.', action='store_false' )
commandLineParser.add_argument( '-r', '--resume', help='Attempt to resume previously interupted operation. No gurantees. Only checks backups made today and yesterday. Not currently implemented.', action='store_true' )
commandLineParser.add_argument( '-tr', '--testRun', help='Specifying this will read all input files and import the translation engine, but there will be no translation or output files written. Default=Translate contents and write output.', action='store_true' )
commandLineParser.add_argument( '-sf', '--settingsFile', help='The is the ' + defaultScriptSettingsFileExtension + ' file from which to read program settings. Default= The name of the program ' + defaultScriptSettingsFileExtension + ' Example: py3TranslateLLM.ini This file must be encoded as ' + defaultTextEncoding + '.', default=None, type=str )
commandLineParser.add_argument( '-ieh', '--inputErrorHandling', help='If the wrong input codec is specified, how should the resulting conversion errors be handled? See: docs.python.org/3.7/library/codecs.html#error-handlers Default=\'' + str( defaultInputTextEncodingErrorHandler ) + '\'.', default=None, type=str )
commandLineParser.add_argument( '-oeh', '--outputErrorHandling', help='How should output conversion errors between incompatible encodings be handled? See: docs.python.org/3.7/library/codecs.html#error-handlers Default=\'' + str( defaultOutputTextEncodingErrorHandler ) + '\'.', default=None, type=str )
commandLineParser.add_argument( '-ce', '--consoleEncoding', help='Specify encoding for standard output. Default=' + str( defaultConsoleEncoding ), default=None,type=str )
commandLineParser.add_argument( '-vb', '--verbose', help='Print more information.', action='store_true' )
commandLineParser.add_argument( '-d', '--debug', help='Print too much information.', action='store_true' )
commandLineParser.add_argument( '-v', '--version', help='Print version information and exit.', action='store_true' )
# Import options from command line options.
commandLineArguments = commandLineParser.parse_args()
#print( 'debugSettingFromCLI = '+ str( commandLineArguments.debug ) )
if commandLineArguments.version == True:
print( __version__ )
sys.exit( 0 )
userInput = {}
userInput[ 'translationEngine' ] = commandLineArguments.translationEngine
userInput[ 'fileToTranslate' ] = commandLineArguments.fileToTranslate
userInput[ 'outputFile' ] = commandLineArguments.outputFile
userInput[ 'promptFile' ] = commandLineArguments.promptFile
userInput[ 'memoryFile' ] = commandLineArguments.memoryFile
userInput[ 'languageCodesFile' ] = commandLineArguments.languageCodesFile
userInput[ 'sourceLanguage' ] = commandLineArguments.sourceLanguage
userInput[ 'targetLanguage' ] = commandLineArguments.targetLanguage
userInput[ 'characterNamesDictionary' ] = commandLineArguments.characterNamesDictionary
userInput[ 'revertAfterTranslationDictionary' ] = commandLineArguments.revertAfterTranslationDictionary
userInput[ 'preTranslationDictionary' ] = commandLineArguments.preTranslationDictionary
userInput[ 'postTranslationDictionary' ] = commandLineArguments.postTranslationDictionary
userInput[ 'postWritingToFileDictionary' ] = commandLineArguments.postWritingToFileDictionary
userInput[ 'cache' ] = commandLineArguments.cache
userInput[ 'cacheFile' ] = commandLineArguments.cacheFile
userInput[ 'cacheAnyMatch' ] = commandLineArguments.cacheAnyMatch
userInput[ 'overwriteWithCache' ] = commandLineArguments.overwriteWithCache
userInput[ 'overwriteWithSpreadsheet' ] = commandLineArguments.overwriteWithSpreadsheet
userInput[ 'reTranslate' ] = commandLineArguments.reTranslate
userInput[ 'readOnlyCache' ] = commandLineArguments.readOnlyCache
userInput[ 'rebuildCache' ] = commandLineArguments.rebuildCache
userInput[ 'contextHistory' ] = commandLineArguments.contextHistory
userInput[ 'contextHistoryMaxLength' ] = commandLineArguments.contextHistoryMaxLength
userInput[ 'contextHistoryReset' ] = commandLineArguments.contextHistoryReset
userInput[ 'sceneSummaryPrompt' ] = commandLineArguments.sceneSummaryPrompt
userInput[ 'sceneSummaryLength' ] = commandLineArguments.sceneSummaryLength
userInput[ 'sceneSummaryEnableTranslation' ] = commandLineArguments.sceneSummaryEnableTranslation
userInput[ 'sceneSummaryCacheFile' ] = commandLineArguments.sceneSummaryCacheFile
userInput[ 'sceneSummaryCacheAnyMatch' ] = commandLineArguments.sceneSummaryCacheAnyMatch
userInput[ 'batches' ] = commandLineArguments.batches
userInput[ 'batchesEnabledForLLMs' ] = commandLineArguments.batchesEnabledForLLMs
userInput[ 'batchSizeLimit' ] = commandLineArguments.batchSizeLimit
userInput[ 'address' ] = commandLineArguments.address #Must be reachable. How to test for that?
userInput[ 'port' ] = commandLineArguments.port #Port should be conditionaly guessed. If no port specified and an address was specified, then try to guess port as either 80, 443, or default settings depending upon protocol and translationEngine selected.
userInput[ 'timeout' ] = commandLineArguments.timeout
userInput[ 'backups' ] = commandLineArguments.backups
userInput[ 'resume' ] = commandLineArguments.resume
userInput[ 'testRun' ] = commandLineArguments.testRun
userInput[ 'settingsFile' ] = commandLineArguments.settingsFile
userInput[ 'inputErrorHandling' ] = commandLineArguments.inputErrorHandling
userInput[ 'outputErrorHandling' ] = commandLineArguments.outputErrorHandling
userInput[ 'consoleEncoding' ] = commandLineArguments.consoleEncoding
userInput[ 'verbose' ] = commandLineArguments.verbose
userInput[ 'debug' ] = commandLineArguments.debug
userInput[ 'version' ] = commandLineArguments.version
# Add stub encoding options. All of these are most certainly None, but they need to exist for locals() to find them so they can get updated.
userInput[ 'fileToTranslateEncoding' ] = commandLineArguments.fileToTranslateEncoding
userInput[ 'outputFileEncoding' ] = commandLineArguments.outputFileEncoding
userInput[ 'promptFileEncoding' ] = commandLineArguments.promptFileEncoding
userInput[ 'memoryFileEncoding' ] = commandLineArguments.memoryFileEncoding
userInput[ 'languageCodesFileEncoding' ] = commandLineArguments.languageCodesFileEncoding
userInput[ 'characterNamesDictionaryEncoding' ] = commandLineArguments.characterNamesDictionaryEncoding
userInput[ 'revertAfterTranslationDictionaryEncoding' ] = commandLineArguments.revertAfterTranslationDictionaryEncoding
userInput[ 'preTranslationDictionaryEncoding' ] = commandLineArguments.preTranslationDictionaryEncoding
userInput[ 'postTranslationDictionaryEncoding' ] = commandLineArguments.postTranslationDictionaryEncoding
userInput[ 'postWritingToFileDictionaryEncoding' ] = commandLineArguments.postWritingToFileDictionaryEncoding
userInput[ 'sceneSummaryPromptEncoding' ] = commandLineArguments.sceneSummaryPromptEncoding
# Basically, the final value of consoleEncoding is unclear because the settings.ini has not been read yet, but it needs to be used immediately, so remember to update it later.
# if the user specified one at the CLI, use that setting, otherwise use the hardcoded defaults.
if userInput[ 'consoleEncoding' ] != None:
userInput[ 'tempConsoleEncoding' ] = userInput[ 'consoleEncoding' ]
else:
userInput[ 'tempConsoleEncoding' ] = defaultConsoleEncoding
if userInput[ 'debug' ] == True:
print( ( 'userInput (CLI)=' + str( userInput ) ).encode( userInput[ 'tempConsoleEncoding' ] ) )
return userInput
# Settings specified at the command prompt take precedence, but py3translateLLM.ini still needs to be parsed.
# This function parses that file and places the settings discovered into a dictionary. That dictionary can then be used along with the command line options to determine the program settings prior to validation of those settings. The settings after validation are the final program settings.
def mergeUserInputSettings( userInput, scriptSettingsFile = __file__ ):
if 'tempConsoleEncoding' in userInput:
consoleEncoding = userInput[ 'tempConsoleEncoding' ]
userInput.pop( 'tempConsoleEncoding' )
else:
consoleEncoding = userInput[ 'consoleEncoding' ]
# In order to read from settings.ini, the name of the current script must first be determined.
#currentScriptFullFileNameAndPath=os.path.realpath( __file__ ) # Old code. This returns a string and the full path of the currently running script including the name and extension.
currentScriptPathObject = pathlib.Path( __file__ ).absolute()
userInput[ 'currentScriptPathOnly' ] = str( currentScriptPathObject.parent ) # Does not include last / and this will return one subfolder up if it is called on a folder.
userInput[ 'currentScriptNameWithoutPath' ] = currentScriptPathObject.name
userInput[ 'currentScriptNameWithoutPathOrExt' ] = currentScriptPathObject.stem
userInput[ 'currentScriptNameWithPathNoExt' ] = userInput[ 'currentScriptPathOnly' ] + '/' + userInput[ 'currentScriptNameWithoutPathOrExt' ]
userInput[ 'backupsFolder' ] = userInput[ 'currentScriptPathOnly' ] + '/' + defaultBackupsFolder
if scriptSettingsFile == __file__ :
scriptSettingsFileFullNameAndPath = userInput[ 'currentScriptNameWithPathNoExt' ] + defaultScriptSettingsFileExtension
else:
scriptSettingsFileFullNameAndPath = str( pathlib.Path( scriptSettingsFile ).absolute() )
scriptSettingsFileNameOnly = pathlib.Path( scriptSettingsFileFullNameAndPath ).name
if ( userInput[ 'verbose' ] == True) or ( userInput[ 'debug' ] == True):
print( str( currentScriptPathObject ).encode(consoleEncoding) )
print( ( 'currentScriptPathOnly=' + str( userInput[ 'currentScriptPathOnly' ] ) ).encode(consoleEncoding) )
print( ( 'currentScriptNameWithoutPath=' + str( userInput[ 'currentScriptNameWithoutPath' ] ) ).encode(consoleEncoding) )
print( ( 'currentScriptNameWithoutPathOrExt=' + str( userInput[ 'currentScriptNameWithoutPathOrExt' ] ) ).encode(consoleEncoding) )
if functions.checkIfThisFileExists( scriptSettingsFileFullNameAndPath ) != True:
return userInput
print( ( 'Settings file found. Reading settings from: ' + scriptSettingsFileNameOnly ).encode(consoleEncoding) )
# This function reads program settings from text files using a predetermined list of rules using code at resources/functions.readSettingsFromTextFile()
# The text file uses the syntax: setting=value, # are comments, empty/whitespace lines ignored.
# This function builds a dictionary and then returns it to the caller.
# Syntax: def readSettingsFromTextFile( fileNameWithPath, fileNameEncoding, consoleEncoding=defaultConsoleEncoding, errorHandlingType=defaultInputTextEncodingErrorHandler, debug=debug ):
# Usage: functions.readSettingsFromTextFile( myfile, myfileEncoding )
scriptSettingsDictionary = functions.readSettingsFromTextFile( scriptSettingsFileFullNameAndPath, defaultTextEncoding, consoleEncoding=consoleEncoding ) # Other settings can be specified, but are basically completely unknown at this point, so just use hardcoded defaults instead.
# Since both userInput and scriptSettingsDictionary are dictionaries, just merge them directly if the CLI value is not None. Hummmmmm. # Update: This is not viable due to the existence of booleans.
# One alternative to this is to remove all boolean types from the CLI and have them as 'None'. Then update them to be booleans later based upon a predefined list. Which is simpler?
# Current algorithim:
# Use scriptSettingsDictionary as the base for processing/finding values to merge and userInput (CLI) as the final output. If the value was not specified at the CLI, override the value in userInput (CLI) with all non-boolean settings in scriptSettingsDictionary.
# For booleans, booleans need to be handled in a special way. Check each boolean individually in both dictionaries to determine the final value. Once the final value is determined, update/integrate the value in the userInput dictionary to become the final value.
# Send the userInput dictionary to the translationEngine in case it is useful there. This potentially half-makes sense for API keys and engine specific variables so that the main program does not have to worry about them. Does that make sense, or should main program always worry about engine specific variables in order to validate them? Are there any examples of engine variables that main program should not validate besides API keys?
# Answer: Any values related to pre or post processing text should not be validated. In addition, the API of certain translation engines should be able to be changed without main program needing any direct update. Updating the engine and perhaps adding an engine specific value in the .ini should be enough to update as it is. Since updating main program should not be necessary for translation engine API changes, especially minor changes, therefore no validation should be done at all for engine specific variables. This includes pykakasi/cutlet's romaji format. TODO: Remove such ill-advised validation attempts from the CLI and .ini. Update: Done.
if not isinstance( scriptSettingsDictionary, dict ):
print( ( 'Warning: Unable to read settings from \'' + str( scriptSettingsFileFullNameAndPath ) + '\'' ).encode( consoleEncoding ) )
return userInput
for key,value in scriptSettingsDictionary:
# The types have already been converted. 'none' => None Do not worry about it here.
# Merge any unrecognized values literally.
if not key in userInput:
userInput[ key ] = value
else:
# There is something at the CLI that corresponds to a key extracted from scriptSettingsDictionary. Might be None or some type of value.
# Deal with booleans first.
# if the CLI's value of the key in scriptSettingsDictionary is a boolean, then treat the key from scriptSettingsDictionary as a boolean.
if isinstance( userInput[ key ], bool ):
# Sanity check. The value extracted from the scriptSettingsDictionary must also be a boolean.
assert( isinstance( value, bool ) )
# if the existing value is true by default,
if key in booleanValuesTrueByDefault:
# and the key in scriptSettingsDictionary is also true, then do nothing.
if value == True:
pass
# else if the key in scriptSettingsDictionary is false, then update it.
# elif value == False:
else:
userInput[ key ] = value
# elif the existing value is false by default:
elif key in booleanValuesFalseByDefault:
# and the key in scriptSettingsDictionary is true, then update it.
if value == True:
userInput[ key ] = value
# else if the key in scriptSettingsDictionary is false, then do nothing
# elif value == False:
else:
pass
# else if the key is in not in either booleanValuesTrueByDefault or booleanValuesFalseByDefault, then something is wrong. The value needs to be added to one of those two lists.
else:
print( ( 'Error: Unable to merge .ini and CLI settings because the key \''+ key + '\'could not be found in either booleanValuesTrueByDefault or booleanValuesFalseByDefault. Please update the appropriate list and try again.' ).encode( consoleEncoding ) )
sys.exit( 1 )
# User specified something at the CLI that is not a boolean. Always use that instead. Valid types are str and int.
elif userInput[ key ] != None:
pass
# User did not specify anything in the text file. Do nothing.
# There are some values that must be specified or the program cannot function. For those values, validateUserInput() should be used instead to check each individual value and combinations of values and error out if a valid combination does not exist. This function is only responsible for merging the input, so do nothing here.
elif key == None:
pass
else:
# The userInput[ key ] value is None, and also the setting specified in the scriptSettingsDictionary is not None. In this case, update the value with whatever was specified at the .ini but not at the CLI.
userInput[ key ] = value
# if version was specified in the .ini, then print out version string and exit.
if userInput[ 'version' ] == True:
print( __version__ )
sys.exit( 0 )
return userInput
# This should set all of the defaults if values are still None and validate the input combination as required by the chosen translation engine.
def validateUserInput( userInput=None ):
#print( 'userInput=', userInput )
# Now that they have been merged, rename the variable names to be more descriptive.
userInput[ 'fileToTranslateFileName' ] = userInput[ 'fileToTranslate' ]
userInput[ 'outputFileName' ] = userInput[ 'outputFile' ]
userInput[ 'promptFileName' ] = userInput[ 'promptFile' ]
userInput[ 'memoryFileName' ] = userInput[ 'memoryFile' ]
userInput[ 'languageCodesFileName' ] = userInput[ 'languageCodesFile' ]
userInput[ 'sourceLanguageRaw' ] = userInput[ 'sourceLanguage' ]
userInput[ 'targetLanguageRaw' ] = userInput[ 'targetLanguage' ]
userInput[ 'characterNamesDictionaryFileName' ] = userInput[ 'characterNamesDictionary' ]
userInput[ 'revertAfterTranslationDictionaryFileName' ] = userInput[ 'revertAfterTranslationDictionary' ]
userInput[ 'preDictionaryFileName' ] = userInput[ 'preTranslationDictionary' ]
userInput[ 'postDictionaryFileName' ] = userInput[ 'postTranslationDictionary' ]
userInput[ 'postWritingToFileDictionaryFileName' ] = userInput[ 'postWritingToFileDictionary' ]
userInput[ 'cacheEnabled' ] = userInput[ 'cache' ]
userInput[ 'cacheFileName' ] = userInput[ 'cacheFile' ]
userInput[ 'contextHistoryEnabled' ] = userInput[ 'contextHistory' ]
userInput[ 'sceneSummaryPromptFileName' ] = userInput[ 'sceneSummaryPrompt' ]
userInput[ 'sceneSummaryCacheFileName' ] = userInput[ 'sceneSummaryCacheFile' ]
userInput[ 'batchesEnabled' ] = userInput[ 'batches' ]
userInput[ 'backupsEnabled' ] = userInput[ 'backups' ]
# Remove old value names.
# https://www.w3schools.com/python/python_ref_dictionary.asp
userInput.pop( 'fileToTranslate' )
userInput.pop( 'outputFile' )
userInput.pop( 'promptFile' )
userInput.pop( 'memoryFile' )
userInput.pop( 'languageCodesFile' )
userInput.pop( 'sourceLanguage' )
userInput.pop( 'targetLanguage' )
userInput.pop( 'characterNamesDictionary' )
userInput.pop( 'revertAfterTranslationDictionary' )
userInput.pop( 'preTranslationDictionary' )
userInput.pop( 'postTranslationDictionary' )
userInput.pop( 'postWritingToFileDictionary' )
userInput.pop( 'cache' )
userInput.pop( 'cacheFile' )
userInput.pop( 'contextHistory' )
userInput.pop( 'sceneSummaryPrompt' )
userInput.pop( 'sceneSummaryCacheFile' )
userInput.pop( 'batches' )
userInput.pop( 'backups' )
# Some values need to be set to hardcoded defaults if they were not specified at the command prompt or in settings.ini, so fill in any missing None entries here.
if userInput[ 'translationEngine' ] == None:
print( 'Error: Please specify a translation engine. ' + usageHelp )
sys.exit( 1 )
if userInput[ 'fileToTranslateFileName' ] == None:
print( 'Error: Please specify a --fileToTranslate (-f).' )
sys.exit( 1 )
# This cannot be set here because fileToTranslateFileExtensionOnly has not been determined yet which means this is a derived value.
#if userInput[ 'outputFileName' ] == None:
# if no outputFileName was specified, then set it the same as the input file with 'translation' and the date appended.
#userInput[ 'outputFileName' ] = userInput[ 'fileToTranslateFileName' ] + '.translated.' + functions.getDateAndTimeFull() + userInput[ 'fileToTranslateFileExtensionOnly' ]
if userInput[ 'languageCodesFileName' ] == None:
userInput[ 'languageCodesFileName' ] = userInput[ 'currentScriptPathOnly' ] + '/' + defaultLanguageCodesFile
if userInput[ 'sourceLanguageRaw' ] == None:
userInput[ 'sourceLanguageRaw' ] = defaultSourceLanguage
if userInput[ 'targetLanguageRaw' ] == None:
userInput[ 'targetLanguageRaw' ] = defaultTargetLanguage
if userInput[ 'cacheFileName' ] == None:
userInput[ 'cacheFileName' ] = userInput[ 'currentScriptPathOnly' ] + '/' + defaultCacheFileLocation
if userInput[ 'contextHistoryMaxLength' ] == None:
userInput[ 'contextHistoryMaxLength' ] = defaultContextHistoryMaxLength
if userInput[ 'sceneSummaryLength' ] == None:
userInput[ 'sceneSummaryLength' ] = defaultSceneSummaryLength
if userInput[ 'sceneSummaryCacheFileName' ] == None:
userInput[ 'sceneSummaryCacheFileName' ] = userInput[ 'currentScriptPathOnly' ] + '/' + defaultSceneSummaryCacheLocation
if userInput[ 'batchSizeLimit' ] == None:
userInput[ 'batchSizeLimit' ] = defaultBatchSizeLimit
# if using py3translationserver or sugoi, address must be specified, but default to using http://localhost. Warn user later.
addressIsDefault = False
if userInput[ 'address' ] == None:
userInput[ 'address' ] = defaultAddress
addressIsDefault = True
# if port not specified, then set port to default port based upon translation engine. Warn user later.
portIsDefault = False
if userInput[ 'port' ] == None:
if userInput[ 'translationEngine' ].lower() == 'koboldcpp':
userInput[ 'port' ] = defaultKoboldCppPort
portIsDefault = True
elif userInput[ 'translationEngine' ].lower() == 'py3translationserver':
userInput[ 'port' ] = defaultPy3translationServerPort
portIsDefault = True
elif userInput[ 'translationEngine' ].lower() == 'sugoi':
userInput[ 'port' ] = defaultSugoiPort
portIsDefault = True
if userInput[ 'timeout' ] == None:
userInput[ 'timeout' ] = defaultTimeout
# Old code. Probably useful for later for use with different translation engines.
#if port == None:
# Try to guess port from protocol and warn user.
# split address using : and return everything before:
# protocol = address.split(':')[0]
# if protocol.lower() == 'http':
# port = defaultPortForHTTP
# elif protocol.lower() == 'https':
# port = defaultPortForHTTPS
# else:
# print( ( 'Port not specified and unable to guess port from protocol \'' + protocol + '\' of address \'' + address + '\' Please specify a valid port number between 1-65535.').encode(consoleEncoding) )
# sys.exit( 1 )
# print( ('Warning: No port was specified. Defaulting to port \''+port+'\' based on protocol \''+protocol+'\'. This is probably incorrect.') )
if userInput[ 'inputErrorHandling' ] == None:
userInput[ 'inputErrorHandling' ] = defaultInputTextEncodingErrorHandler
if userInput[ 'outputErrorHandling' ] == None:
userInput[ 'outputErrorHandling' ] = defaultOutputTextEncodingErrorHandler
# if consoleEncoding is still None after reading both the CLI and the settings.ini, then just set it to the default value.
if userInput[ 'consoleEncoding' ] == None:
userInput[ 'consoleEncoding' ] = defaultConsoleEncoding
consoleEncoding = defaultConsoleEncoding
else:
consoleEncoding = userInput[ 'consoleEncoding' ]
if userInput[ 'debug' ] == True:
userInput[ 'verbose' ] = True
print( ( 'translationEngine=' + str( userInput[ 'translationEngine' ] ) ).encode( consoleEncoding ) )
#print( ( 'fileToTranslateEncoding=' + str( userInput[ 'fileToTranslateEncoding' ] ) ).encode( consoleEncoding ) )
# Add derived values like file paths and inferred values.
# Determine file paths now. Will be useful later.
# pathlib.Path() does not mind mixing / and \ so always use /.
fileToTranslatePathObject = pathlib.Path( userInput[ 'fileToTranslateFileName' ] ).absolute()
#fileToTranslateFileNameWithPathNoExt, fileToTranslateFileExtensionOnly = os.path.splitext( fileToTranslateFileName ) # Old code.
userInput[ 'fileToTranslateFileExtensionOnly' ] = fileToTranslatePathObject.suffix # .txt .ks .ts .csv .xlsx .xls .ods
userInput[ 'fileToTranslatePathOnly' ] = str( fileToTranslatePathObject.parent ) # pathlib.Path().parent returns not-a-string. Does not include final / at the end and will return one subfolder up if it is called on a folder.
userInput[ 'fileToTranslateFileNameWithoutPath' ] = fileToTranslatePathObject.name # pathlib.Path().name returns a string.
userInput[ 'fileToTranslateFileNameWithoutPathOrExt' ] = fileToTranslatePathObject.stem # pathlib.Path().stem returns a string.
userInput[ 'fileToTranslateFileNameWithPathNoExt' ] = userInput[ 'fileToTranslatePathOnly' ] + '/' + userInput[ 'fileToTranslateFileNameWithoutPathOrExt' ]
if userInput[ 'verbose' ] == True:
print( str( fileToTranslatePathObject ).encode(consoleEncoding) )
print( ( 'fileToTranslateFileExtensionOnly=' + userInput[ 'fileToTranslateFileExtensionOnly' ] ).encode(consoleEncoding) )
print( ( 'fileToTranslatePathOnly=' + userInput[ 'fileToTranslatePathOnly' ] ).encode(consoleEncoding) )
print( ( 'fileToTranslateFileNameWithoutPath=' + userInput[ 'fileToTranslateFileNameWithoutPath' ] ).encode(consoleEncoding) )
print( ( 'fileToTranslateFileNameWithoutPathOrExt=' + userInput[ 'fileToTranslateFileNameWithoutPathOrExt' ] ).encode(consoleEncoding) )
print( ( 'fileToTranslateFileNameWithPathNoExt=' + userInput[ 'fileToTranslateFileNameWithPathNoExt' ] ).encode(consoleEncoding) )
if userInput[ 'fileToTranslateFileExtensionOnly' ] in validSpreadsheetExtensions:
userInput[ 'fileToTranslateIsASpreadsheet' ] = True
else:
userInput[ 'fileToTranslateIsASpreadsheet' ] = False
# fileToTranslateFileExtensionOnly was only just determined which means outputFileName which uses it is a derived value.
if userInput[ 'outputFileName' ] == None:
# If no outputFileName was specified, then set it the same as the input file with 'translation' and the date appended.
userInput[ 'outputFileName' ] = userInput[ 'fileToTranslateFileName' ] + '.translated.' + functions.getDateAndTimeFull() + userInput[ 'fileToTranslateFileExtensionOnly' ]
userInput[ 'outputFileNameWithoutPathOrExt' ] = pathlib.Path( userInput[ 'outputFileName' ] ).stem
userInput[ 'outputFileExtensionOnly' ] = pathlib.Path( userInput[ 'outputFileName' ] ).suffix
#userInput[ 'promptFileContents' ] = None
#userInput[ 'memoryFileContents' ] = None
cacheFileNameObject = pathlib.Path( str(userInput[ 'cacheFileName' ] ) ).absolute()
userInput[ 'cacheFilePathOnly' ] = str( cacheFileNameObject.parent )
userInput[ 'cacheFileExtensionOnly' ] = cacheFileNameObject.suffix
if userInput[ 'sceneSummaryPromptFileName' ] == None:
userInput[ 'sceneSummaryEnabled' ] = False
userInput[ 'sceneSummaryCacheEnabled' ] = False
else:
userInput[ 'sceneSummaryEnabled' ] = True
userInput[ 'sceneSummaryCacheEnabled' ] = True # Currently, this will still be disabled if the global setting for cache is disabled. Should this functionality be split to make --cache not global? What is the use-case for that? # Update: The use case is to generate translations with one engine without intending to create any translations, leaving sceneSummaryEnableTranslation disabled. Since no translations are being performed, there is no need to load the cache for those translations.
sceneSummaryCachePathObject = pathlib.Path( str( userInput[ 'sceneSummaryCacheFileName' ] ) )
userInput[ 'sceneSummaryCacheFilePathOnly' ] = str( sceneSummaryCachePathObject.parent )
userInput[ 'sceneSummaryCacheExtensionOnly' ] = sceneSummaryCachePathObject.suffix
#userInput[ 'sceneSummaryPromptFileContents' ] = None
# Now that command line options and .ini have been parsed, and None values filled in, update the settings for the imported libraries.
# The libraries must be imported using the syntax: import resources.libraryName as libraryName . Otherwise, if using the 'from libraryName import...' syntax, a copy is made which makes it, near?, impossible to update these variables correctly.
chocolate.verbose = userInput[ 'verbose' ]
chocolate.debug = userInput[ 'debug' ]
chocolate.consoleEncoding = userInput[ 'consoleEncoding' ]
chocolate.inputErrorHandling = userInput[ 'inputErrorHandling' ]
chocolate.outputErrorHandling = userInput[ 'outputErrorHandling' ]
functions.verbose = userInput[ 'verbose' ]
functions.debug = userInput[ 'debug' ]
functions.consoleEncoding = userInput[ 'consoleEncoding' ]
functions.inputErrorHandling = userInput[ 'inputErrorHandling' ]
functions.outputErrorHandling = userInput[ 'outputErrorHandling' ]
functions.linesThatBeginWithThisAreComments = defaultLinesThatBeginWithThisAreComments
functions.assignmentOperatorInSettingsFile = defaultAssignmentOperatorInSettingsFile
dealWithEncoding.verbose = userInput[ 'verbose' ]
dealWithEncoding.debug = userInput[ 'debug' ]
dealWithEncoding.consoleEncoding = userInput[ 'consoleEncoding' ]
# Start to validate input settings and input combinations from parsed imported command line option values.
# Certain files must be present, like fileToTranslateFileName and usually languageCodesFileName.
# Reading from text files is easy since the only thing that needs to be checked is if they exist.
# Update: py3TranslateLLM only accepts spreadsheet inputs in order to divide the logic between parsing files and translating spreadsheets. There is only very basic line-by-line logic for i/o related to text files included in chocolate.Strawberry(). Use py3AnyText2Spreadsheet to create spreadsheets from raw text files for more complicated cases (.epub, subtitles, .ks, .scn.txt).
# if output is .txt, .ks... if input is not a spreadsheet, then output is writing to text file, so set output encoding and extension based upon input.
# if the user specified a spreadsheet as input and a text file as output, then export whatever the column of mainSpreadsheet to whatever the current translation engine is.
# Start checking if files exist or not, combinations of settings, and mode specific settings.
# Syntax:
#def verifyThisFileExists( myFile, nameOfFileToOutputInCaseOfError=None ):
#def checkIfThisFolderExists( myFolder ):
# Usage:
# Errors out if myFile does not exist.
#functions.verifyThisFileExists( 'myfile.csv', 'myfile.csv' )
#functions.verifyThisFolderExists( myVar, 'myVar' )
#functions.verifyThisFolderExists( myVar )
# Returns True or False depending upon if a file or folder was specified.
#functions.checkIfThisFileExists( 'myfile.csv' )
#functions.checkIfThisFolderExists( myVar )
# Verify translationEngine
# The syntax below all of the libraries are under resources/translationEngines/*. To import the libraries directly regardless of where they are on the file system:
# import sys
# import pathlib
# sys.path.append( str( pathlib.Path('C:/resources/translationEngines/koboldCppEngine.py').resolve().parent ) )
# import koboldCppEngine
userInput[ 'mode' ] = None
userInput[ 'translationEngineIsAnLLM' ] = False
implemented = False
#validate input from command line options
# This section should probably be updated with more helpful error messages like what to do if the engines did not import correctly. pip install pykakasi ...etc
# Is this mode still valid? # Update: This should be renamed to enable a test run mode. # Update2: parseOnly was removed completely and cacheOnly is taking its place. --testRun, a flag, was also implemented as a replacement for --translationEngine parseOnly.
if ( userInput[ 'translationEngine' ].lower() == 'cacheonly' ):
userInput[ 'mode' ] = 'cacheonly'
global cacheOnlyEngine
import resources.translationEngines.cacheOnly as cacheOnlyEngine
implemented=False
elif ( userInput[ 'translationEngine' ].lower() == 'koboldcpp' ):
userInput[ 'mode' ] = 'koboldcpp'
global koboldCppEngine
import resources.translationEngines.koboldCppEngine as koboldCppEngine
userInput[ 'translationEngineIsAnLLM' ] = True
implemented=True
elif ( userInput[ 'translationEngine' ].lower() == 'deepl_api_free' ) or ( userInput[ 'translationEngine' ].lower() == 'deepl-api-free' ):
userInput[ 'mode' ] = 'deepl_api_free'
global deepLAPIFreeEngine
import resources.translationEngines.deepLAPIFreeEngine as deepLAPIFreeEngine
implemented=False
#import deepl
elif ( userInput[ 'translationEngine' ].lower() == 'deepl_api_pro' ) or ( userInput[ 'translationEngine' ].lower() == 'deepl-api-pro' ):
userInput[ 'mode' ] = 'deepl_api_pro'
global deepLAPIProEngine
import resources.translationEngines.deepLAPIProEngine as deepLAPIProEngine
implemented=False
elif ( userInput[ 'translationEngine' ].lower() == 'deepl_web' ) or ( userInput[ 'translationEngine' ].lower() == 'deepl-web' ):
userInput[ 'mode' ] = 'deepl_web'
global deepLWebEngine
import resources.translationEngines.deepLWebEngine as deepLWebEngine
implemented=False
elif ( userInput[ 'translationEngine' ].lower() == 'py3translationserver' ):
userInput[ 'mode' ] = 'py3translationserver'
global py3translationServerEngine
import resources.translationEngines.py3translationServerEngine as py3translationServerEngine
implemented = True
elif ( userInput[ 'translationEngine' ].lower() == 'sugoi' ):
userInput[ 'mode'] = 'sugoi'
# Sugoi has a default port association and only supports Jpn->Eng translations, so having a dedicated entry for it is still useful for input validation, especially since it only supports a subset of the py3translationserver API.
global sugoiEngine
import resources.translationEngines.sugoiEngine as sugoiEngine
implemented = False
elif ( userInput[ 'translationEngine' ].lower() == 'pykakasi' ):
userInput[ 'mode' ] = 'pykakasi'
global pykakasiEngine
import resources.translationEngines.pykakasiEngine as pykakasiEngine
implemented = True
if userInput[ 'cacheEnabled' ] == True:
print( 'Info: Disabling cache for local pykakasi library.' )
userInput[ 'cacheEnabled' ] = False # Since pykakasi is a local library with a fast dictionary, enabling cache would only make things slower.
elif ( userInput[ 'translationEngine' ].lower() == 'cutlet' ):
userInput[ 'mode' ] = 'cutlet'
global cutletEngine
import resources.translationEngines.cutletEngine as cutletEngine
implemented = True
if userInput[ 'cacheEnabled' ] == True:
print( 'Info: Disabling cache for local cutlet library.' )
userInput [ 'cacheEnabled' ] = False # Is enabling cache worth it for cutlet? Unlikely.
else:
print( ( 'Error. Invalid translation engine specified: \'' + userInput[ 'translationEngine' ] + '\'' + usageHelp ).encode( consoleEncoding ))
sys.exit( 1 )
userInput.pop( 'translationEngine' )
print( ( 'Mode is set to: \'' + str( userInput[ 'mode'] ) + '\'' ).encode( consoleEncoding ) )
if implemented == False:
print( '\n\'' + userInput[ 'mode' ] + '\' not yet implemented. Please pick another translation engine. \n Translation engines: ' + str( translationEnginesAvailable ) )
sys.exit( 1 )
functions.verifyThisFileExists( userInput[ 'fileToTranslateFileName' ], 'fileToTranslate' ) #, 'fileToTranslate'
if userInput[ 'fileToTranslateIsASpreadsheet' ] == False:
# if the extension is not .txt or .text, then warn the user about it.
if not ( ( userInput[ 'fileToTranslateFileExtensionOnly' ] == '.txt' ) or ( userInput[ 'fileToTranslateFileExtensionOnly' ] == '.text' ) ):
print( ( 'Warning: Unrecognized extension for spreadsheet: ' + str( userInput[ 'fileToTranslateFileExtensionOnly' ] + ' File will be parsed line-by-line as a text file. Consider using a dedicated parser if this is incorrect.' ) ).encode( consoleEncoding ) )
# outputFileName does not need to exist.
# promptFileName only needs to exist if using an LLM. If using an LLM, make sure it exists. Technically, it is not needed if the summary feature is enabled and also if translations are disabled, but since it will be needed soon after, just require it anyway. In addition, if the user specified it, even if it is not needed, then verify it exists.
#if userInput[ 'mode' ] == 'koboldcpp':
if ( userInput[ 'translationEngineIsAnLLM' ] == True ) or ( userInput[ 'promptFileName' ] != None ):
functions.verifyThisFileExists( userInput[ 'promptFileName' ], 'promptFile' )
# memoryFileName never has to exist, but if it is specified, then make sure it exists.
if userInput[ 'memoryFileName' ] != None:
functions.verifyThisFileExists( userInput[ 'memoryFileName' ], 'memoryFile' )
functions.verifyThisFileExists( userInput[ 'languageCodesFileName' ], 'languageCodesFile' )
if not pathlib.Path( userInput[ 'languageCodesFileName' ] ).suffix in validSpreadsheetExtensions:
print( ('\n Error: languageCodesFile must have a spreadsheet extension instead of \''+ pathlib.Path( userInput[ 'languageCodesFileName' ] ).suffix + '\'' ).encode( consoleEncoding ) )
print( 'validSpreadsheetExtensions=' + str( validSpreadsheetExtensions ) )
print( ( 'cacheFile: \'' + str( userInput[ 'languageCodesFileName' ] ) ).encode( consoleEncoding) )
sys.exit( 1 )
# The target language is required to be present, but source language can be optional for NMTs, LLMs, and DeepL.
# The problem with not specifying the source language, even if the translationEngine itself does not need it, is that the source language is still used for selecting the correct sheet in the cache.xlsx workbook. So only cache == disabled would be valid. The same is true for the summary feature. Therefore, always require it and add an "Unknown" option to the languageCodes.csv for user to use if they are unsure.
if userInput[ 'sourceLanguageRaw' ] == None:
print( 'Error: A source language must be specified.' )
sys.exit( 1 )
if userInput[ 'targetLanguageRaw' ] == None:
print( 'Error: A target language must be specified.' )
sys.exit( 1 )
# TODO: Some of this should be moved to the deepLTranslationEngine, but that engine needs to be implemented first.
if userInput[ 'sourceLanguageRaw' ] != None:
# Substitute a few language entries to certain defaults due to collisions and aliases.
if userInput[ 'sourceLanguageRaw' ].lower() == 'english':
userInput[ 'sourceLanguageRaw' ] = 'English (American)'
elif userInput[ 'sourceLanguageRaw' ].lower() == 'castilian':
userInput[ 'sourceLanguageRaw' ] = 'Spanish'
elif userInput[ 'sourceLanguageRaw' ].lower() == 'chinese':
userInput[ 'sourceLanguageRaw' ] = 'Chinese (simplified)'
elif userInput[ 'sourceLanguageRaw' ].lower() == 'portuguese':
userInput[ 'sourceLanguageRaw' ] = 'Portuguese (European)'
if userInput[ 'targetLanguageRaw' ] != None:
# Substitute a few language entries to certain defaults due to collisions and aliases.
if userInput[ 'targetLanguageRaw' ].lower() == 'english':
userInput[ 'targetLanguageRaw' ] = 'English (American)'
elif userInput[ 'targetLanguageRaw' ].lower() == 'castilian':
userInput[ 'targetLanguageRaw' ] = 'Spanish'
# if any dictionaries were specified, then make sure they exist.
if userInput[ 'characterNamesDictionaryFileName' ] != None:
functions.verifyThisFileExists( userInput[ 'characterNamesDictionaryFileName' ], 'characterNamesDictionary' )
if userInput[ 'revertAfterTranslationDictionaryFileName' ] != None:
functions.verifyThisFileExists( userInput[ 'revertAfterTranslationDictionaryFileName' ], 'revertAfterTranslationDictionary' )
if userInput[ 'preDictionaryFileName' ] != None:
functions.verifyThisFileExists( userInput[ 'preDictionaryFileName' ], 'preDictionary' )
if userInput[ 'postDictionaryFileName' ] != None:
functions.verifyThisFileExists( userInput[ 'postDictionaryFileName' ], 'postDictionary' )
if userInput[ 'postWritingToFileDictionaryFileName' ] != None:
functions.verifyThisFileExists( userInput[ 'postWritingToFileDictionaryFileName' ], 'postWritingToFileDictionary' )
# The cache file does not need to exist. if it does not exist, then it will be created dynamically when it is needed as a chocolate.Strawberry(), so only verify the extension.
if userInput[ 'cacheEnabled' ] == True:
# Verify cache file extension is .xlsx. Shouldn't .csv also work? .csv would be harder for user to edit but might take less space on disk. Need to check. # Update: It was backwards. .csv files take more space on disk but can be potentially the most compatible. They might compress the best via lzma2 with python's zip library. In practice, .ods should be the most compatible in exchange for larger file size compared to .xlsx, but .ods support is not yet implemented in chocolate.py library.
if not userInput[ 'cacheFileExtensionOnly' ] in validSpreadsheetExtensions:
print( ( '\n Error: cacheFile must have a spreadsheet extension instead of \''+ userInput[ 'cacheFileExtensionOnly' ] +'\'' ).encode( consoleEncoding ) )
print( 'validSpreadsheetExtensions=' + str( validSpreadsheetExtensions ) )
print( ( 'cacheFile: \'' + str( userInput[ 'cacheFileName' ] ) ).encode( consoleEncoding ) )
sys.exit( 1 )
# overwriteWithCache means to ignore the current translation and fill it in with entries from the cache. overwriteWithSpreadsheet means to ignore what is in the cache and replace it with a translation from mainSpreadsheet. reTranslate means to ignore the current translation and fill it in with fresh entries from the translation engine. These settings directly conflict. When then conflict, reTranslate should take precedence.
if userInput[ 'reTranslate' ] == True: # userInput[ 'overwriteWithCache' ] == True ) and ()
userInput[ 'overwriteWithCache' ] = False
userInput[ 'overwriteWithSpreadsheet' ] = False
# readOnlyCache means to not write/alter the current cache.xlsx. rebuildCache means to alter the current cache.xlsx. When these settings conflict, disable rebuildCache.
if ( userInput[ 'readOnlyCache' ] == True ) and ( userInput[ 'rebuildCache' ] == True ):
userInput[ 'rebuildCache' ] = False
#if contextHistoryMaxLength was specified as == 0, then disable it. Update: 0 should mean unlimited contextHistory
#if userInput[ 'contextHistoryMaxLength' ] == 0:
# userInput[ 'contextHistoryEnabled' ] = False
if userInput[ 'sceneSummaryPromptFileName' ] != None:
functions.verifyThisFileExists( userInput[ 'sceneSummaryPromptFileName' ], 'sceneSummaryPrompt' )
if userInput[ 'sceneSummaryEnabled' ] == True:
# if a cache file was specified, then verify the extension is .xlsx # Update: Shouldn't .csv also work? CSV would be harder for user to edit but might take less space on disk. Need to check.
if not userInput[ 'sceneSummaryCacheExtensionOnly' ] in validSpreadsheetExtensions:
print( ( '\n Error: cacheFile must have a spreadsheet extension instead of \'' + userInput[ 'sceneSummaryCacheExtensionOnly' ] + '\'' ).encode(consoleEncoding) )
print( ( 'sceneSummaryCacheFile: \'' + str( userInput[ 'sceneSummaryCacheFileName' ] ) ).encode(consoleEncoding) )
sys.exit(1)
# Moved.
#if userInput[ 'batchSize' ] > userInput[ 'summarySize' ]:
# userInput[ 'batchSize' ] = userInput[ 'summarySize' ]
#elif userInput[ 'summarySize' ] > userInput[ 'batchSize' ]:
# userInput[ 'summarySize' ] = userInput[ 'batchSize' ]
# A batch size of 0 means unlimited.
# if sceneSummaryEnabled == True, then reduce the batchSizeLimit and sceneSummaryLength to whatever is lower.
# This code must run even if batchesEnabled == False because batchSizeLimit is overloaded and also used to determine the size of batches for internal processing in addition to the batchTranslate processing size for the translationEngine.
if ( userInput[ 'sceneSummaryEnabled' ] == True ): # and ( userInput[ 'batchesEnabled' ] == True ):
if ( userInput[ 'sceneSummaryLength' ] == 0 ) or ( userInput[ 'sceneSummaryLength' ] > userInput[ 'batchSizeLimit' ] ):
userInput[ 'sceneSummaryLength' ] = userInput[ 'batchSizeLimit' ]
elif ( userInput[ 'batchSizeLimit' ] == 0 ) or ( userInput[ 'batchSizeLimit' ] > userInput[ 'sceneSummaryLength' ] ):
userInput[ 'batchSizeLimit' ] = userInput[ 'sceneSummaryLength' ]
assert( userInput[ 'batchSizeLimit' ] == userInput[ 'sceneSummaryLength' ] )
# if sceneSummaryEnabled == False, then neither sceneSummaryLength nor batchSizeLimit get reduced in size and so should not necessarily match.
# However, sceneSummaryLength is not used at all after this point since batchSizeLimit must always == sceneSummaryLength to simplify internal processing regarding the scope of sceneSummary.
# Internal processing of data in py3TranslateLLM is always done in batches even if submission of entries to translationEngine as batches are disabled. This means that what 'batches' mean is somewhat overloaded. With fancier and messier logic, this could be de-coupled. Hmmm. Is there any point in de-coupling the sceneSummary code from the internal batch size code though? De-doupling for the sake of de-coupling is pointless especially if the end result would be less readable. What practical benefits are there?
# Maybe simplified explanations of how the batch options work to users? A mere explanation alone does not justify the increase in complexity. What other benefits are there?
#if userInput[ 'sceneSummaryEnabled' ] != True:
# assert( userInput[ 'batchSizeLimit' ] == userInput[ 'sceneSummaryLength' ] )
if userInput[ 'verbose' ] == True:
print( 'sceneSummaryLength=' + str( userInput[ 'sceneSummaryLength' ] ) )
print( 'batchSizeLimit=' + str( userInput[ 'batchSizeLimit' ] ) )
if userInput[ 'batchesEnabled' ] == False:
userInput[ 'batchesEnabledForLLMs' ] = False
# if using cacheOnly...
if userInput[ 'mode' ] == 'cacheOnly':
pass
# Check for local LLMs/NMTs. Warn if defaulting to default address or default port. Validate specific port assignment.
if ( userInput[ 'mode' ] == 'koboldcpp' ) or ( userInput[ 'mode' ] == 'py3translationserver' ) or ( userInput[ 'mode' ] == 'sugoi' ):
if addressIsDefault == True:
print( ( 'Warning: No address was specified for: '+ userInput[ 'mode' ] +'. Defaulting to: '+ defaultAddress + ' This is probably incorrect.' ).encode(consoleEncoding) )
if portIsDefault == True:
print( 'Warning: No port specified for ' + userInput[ 'mode' ] + ' translation engine. Using default port of: ' + str( userInput[ 'port' ] ) )
try:
assert( userInput[ 'port' ] >= minimumPortNumber ) #1
assert( userInput[ 'port' ] <= maximumPortNumber ) #65535
except:
print( ( 'Error: Unable to verify port number: \'' + str( userInput[ 'port' ] ) + '\' Must be '+ str( minimumPortNumber ) + '-' + str( maximumPortNumber ) + '.').encode( consoleEncoding ) )
sys.exit( 1 )
# if using deepl_api_free, pro or any engine that requires internet access, then insist the internet is available.
if ( userInput[ 'mode' ] == 'deepl_api_free' ) or ( userInput[ 'mode' ] == 'deepl_api_pro' ) or ( userInput[ 'mode' ] == 'deepl_web' ):
# Must have internet access. How to check? # Moved to functions.py. This should be moved to verifyInput() because deepL always requires internet access since it is a cloud service. # Update: Done.
# Added functions.checkIfInternetIsAvailable() function that uses requests/socket to fetch a web page or resolve an address.
assert( functions.checkIfInternetIsAvailable() == True )
# if using deepl_web... TODO validate anything it needs
#probably the external chrome.exe right? Maybe requests library and scraping library.
#Might need G-Chrome, + chromedriver.exe, and also a library wrapper, like Selenium.
#Could require Chromium to be downloaded to resources/chromium/[platform]/chrome[.exe]
#if userInput[ 'mode' ] == 'pykakasi':
#pass
#if userInput[ 'mode' ] == 'cutlet':
#pass
# Set encodings last using dealWithEncoding.py helper library.
# API: def ofThisFile( myFileName, userInputForEncoding=None, fallbackEncoding=defaultTextFileEncoding ):
# Usage: newEncoding = dealWithEncoding.ofThisFile( myFileName, rawCommandLineOption, fallbackEncoding )
#.csv's work normally since those are both plaintext and spreadsheets but reading encoding from .xlsx, .xls, and .ods is not possible without either hardcoding a specific encoding or using the designated libraries. dealWithEncoding should deal with it. If asked what the encoding of a binary spreadsheet format, then it should just return what the user specified at the command prompt or the default/fallbackEncoding.
# For the output file encoding, if the user specified an input file encoding, use the input file's encoding for the output file.
if ( userInput[ 'fileToTranslateEncoding' ] != None ) and ( userInput[ 'outputFileEncoding' ] == None ):
userInput[ 'outputFileEncoding' ] = userInput[ 'fileToTranslateEncoding' ]
userInput[ 'fileToTranslateEncoding' ] = dealWithEncoding.ofThisFile( userInput[ 'fileToTranslateFileName' ], userInput[ 'fileToTranslateEncoding' ], defaultTextEncoding )
# For the outputfile, use the input file encoding as a fallback.
userInput[ 'outputFileEncoding' ] = dealWithEncoding.ofThisFile( userInput[ 'outputFileName' ], userInput[ 'outputFileEncoding' ], userInput[ 'fileToTranslateEncoding' ] )
userInput[ 'promptFileEncoding' ] = dealWithEncoding.ofThisFile( userInput[ 'promptFileName' ], userInput[ 'promptFileEncoding' ], defaultTextEncoding )
userInput[ 'memoryFileEncoding' ] = dealWithEncoding.ofThisFile( userInput[ 'memoryFileName' ], userInput[ 'memoryFileEncoding' ], defaultTextEncoding )
userInput[ 'languageCodesFileEncoding' ] = dealWithEncoding.ofThisFile( userInput[ 'languageCodesFileName' ], userInput[ 'languageCodesFileEncoding' ], defaultTextEncoding )
userInput[ 'characterNamesDictionaryEncoding' ] = dealWithEncoding.ofThisFile( userInput[ 'characterNamesDictionaryFileName' ], userInput[ 'characterNamesDictionaryEncoding' ], defaultTextEncoding )
userInput[ 'revertAfterTranslationDictionaryEncoding' ] = dealWithEncoding.ofThisFile( userInput[ 'revertAfterTranslationDictionaryFileName' ], userInput[ 'revertAfterTranslationDictionaryEncoding' ], defaultTextEncoding )
userInput[ 'preDictionaryEncoding' ] = dealWithEncoding.ofThisFile( userInput[ 'preDictionaryFileName' ], userInput[ 'preTranslationDictionaryEncoding' ], defaultTextEncoding )
userInput[ 'postDictionaryEncoding' ] = dealWithEncoding.ofThisFile( userInput[ 'postDictionaryFileName' ], userInput[ 'postTranslationDictionaryEncoding' ], defaultTextEncoding )
userInput[ 'postWritingToFileDictionaryEncoding' ] = dealWithEncoding.ofThisFile( userInput[ 'postWritingToFileDictionaryFileName' ], userInput[ 'postWritingToFileDictionaryEncoding' ], defaultTextEncoding )
userInput[ 'sceneSummaryPromptEncoding' ] = dealWithEncoding.ofThisFile( userInput[ 'sceneSummaryPromptFileName' ], userInput[ 'sceneSummaryPromptEncoding' ], defaultTextEncoding )
return userInput
def readInputFiles( userInput=None ):
consoleEncoding = userInput[ 'consoleEncoding' ]
if ( userInput[ 'verbose' ] == True ) or ( userInput[ 'debug' ] == True ):
print( ( 'verbose=' + str( userInput[ 'verbose' ] ) ).encode( consoleEncoding ) )
print( ( 'debug=' + str( userInput[ 'debug'] ) ).encode( consoleEncoding ) )
print( ( 'sourceLanguageRaw=' + str( userInput[ 'sourceLanguageRaw' ] ) ).encode( consoleEncoding ) )
print( ( 'targetLanguageRaw=' + str( userInput[ 'targetLanguageRaw' ] ) ).encode( consoleEncoding ) )
# Instantiate basket of Strawberries. Start with languageCodes.csv # languageCodes.csv, cache.xlsx, sceneSummaryCache.xlsx, and mainSpreadsheet are chocolate.Strawberry() instances. For the various dictionary.csv files, use Python dictionaries instead. The prompt files are regular files (strings).
# languageCodes.csv could also be a dictionary with key=[ list ] or multidimensional array [[][][]], but then searching through that would be annoying, so leave as a chocolate.Strawberry().
# Read in and process languageCodes.csv
# Format specificiation for languageCodes.csv
# Name of language in English, ISO 639 Code, ISO 639-2 Code
# https://www.loc.gov/standards/iso639-2/php/code_list.php
# Language list (Mostly) only languages supported by DeepL are currently listed, case insensitive.
# Syntax:
# The first row is entirely headers (column labels). Entries start from the 2nd row (row[1] if python list, row[2] if spreadsheet data structure):
# Spec:
# column 0) [ languageNameReadable,
# column 1) TwoLetterLanguageCodeThatIsNotAlwaysTwoLetters,
# column 2) ThreeLetterLanguageCodeThatIsNotAlwaysThreeLetters,
# column 3) DoesDeepLSupportThisLanguageTrueOrFalse,
# column 4) DoesThisLanguageNeedACustomSourceLanguageTrueOrFalse (for single source language but many target language languages like EN->EN-US/EN-GB)
# column 5) If #4 is True, then the full name source language
# column 6) If #4 is True, then the two letter code of the source language
# column 7) If #4 is True, then the three letter code of the source language
# Examples for 5-7: English, EN, ENG; Portuguese, PT-PT, POR
# Each row/entry is/has eight columns total.
# Skip reading languageCodesFileName if mode is parseOnly. # Update: parseOnly mode is not really supported anymore. It should probably be renamed to dryRun mode or --testRun where the purpose is to check for parsing errors in everything, including the languageCodes.csv and cache.xlsx files.
#if userInput[ 'mode' ] != 'parseOnly':
if userInput[ 'verbose' ] == True:
print('languageCodesFileName=' + userInput[ 'languageCodesFileName' ] )
print('languageCodesFileEncoding=' + userInput[ 'languageCodesFileEncoding' ] )
userInput[ 'languageCodesSpreadsheet' ] = chocolate.Strawberry( myFileName=userInput[ 'languageCodesFileName' ], fileEncoding=userInput[ 'languageCodesFileEncoding' ], removeWhitespaceForCSV=True )
#sourceLanguageCellRow, sourceLanguageCellColumn = userInput[ 'languageCodesSpreadsheet' ].searchColumnsCaseInsensitive( 'lav')
#sourceLanguageCellRow, sourceLanguageCellColumn = userInput[ 'languageCodesSpreadsheet' ].searchColumnsCaseInsensitive( 'japanese' )
sourceLanguageCellRow, sourceLanguageCellColumn = userInput[ 'languageCodesSpreadsheet' ].searchColumnsCaseInsensitive( userInput[ 'sourceLanguageRaw' ] )
if ( sourceLanguageCellRow == None ) or ( sourceLanguageCellColumn == None ):
print( ( 'Error: Unable to find source language \'' + str( sourceLanguageRaw ) + '\' in file: ' + str( userInput[ 'languageCodesFileName' ] ) ).encode( consoleEncoding ) )
sys.exit(1)
print( ( 'Using sourceLanguage \'' + str( userInput[ 'sourceLanguageRaw' ] ) + '\' found at \'' + str( sourceLanguageCellColumn ) + str( sourceLanguageCellRow ) + '\' of: ' + userInput[ 'languageCodesFileName' ] ).encode( consoleEncoding ) )
userInput[ 'sourceLanguageFullRow' ] = userInput[ 'languageCodesSpreadsheet' ].getRow( sourceLanguageCellRow )
userInput[ 'internalSourceLanguageName' ] = userInput[ 'sourceLanguageFullRow' ][0]
userInput[ 'internalSourceLanguageTwoCode' ] = userInput[ 'sourceLanguageFullRow' ][1]
userInput[ 'internalSourceLanguageThreeCode' ] = userInput[ 'sourceLanguageFullRow' ][2]
if userInput[ 'debug' ] == True:
print( str( userInput[ 'sourceLanguageFullRow' ] ).encode( consoleEncoding ) )
print( ('internalSourceLanguageName=' + userInput[ 'internalSourceLanguageName' ] ).encode( consoleEncoding ) )
print( ('internalSourceLanguageTwoCode=' + userInput[ 'internalSourceLanguageTwoCode' ] ).encode( consoleEncoding ) )
print( ('internalSourceLanguageThreeCode=' + userInput[ 'internalSourceLanguageThreeCode' ] ).encode( consoleEncoding ) )