forked from NEKOparapa/AiNiee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAiNiee-chatgpt4.py
7089 lines (5316 loc) · 336 KB
/
AiNiee-chatgpt4.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
# ═══════════════════════════════════════════════════════
# ████ WARNING: Enter at Your Own Risk! ████
# ████ Congratulations, you have stumbled upon my ████
# ████ masterpiece - a mountain of 10,000 lines of ████
# ████ spaghetti code. Proceed with caution, ████
# ████ as reading this code may result in ████
# ████ immediate unhappiness and despair. ████
# ═══════════════════════════════════════════════════════
# ═══════════════════════════════════════════════════════
# ████ 警告:擅自进入,后果自负 ████
# ████ 恭喜你,你已经发现了我的杰作 ████
# ████ 一座万行意大利面条式代码的屎山 ████
# ████ 请谨慎前行,阅读这段代码可能会。 ████
# ████ 立刻让你感到不幸和绝望 ████
# ═══════════════════════════════════════════════════════
# coding:utf-8
import copy
import datetime
import json
import math
import random
import re
from qframelesswindow import FramelessWindow, TitleBar
import time
import threading
import os
import sys
import multiprocessing
import concurrent.futures
import tiktoken_ext #必须导入这两个库,否则打包后无法运行
from tiktoken_ext import openai_public
import tiktoken #需要安装库pip install tiktoken
import openpyxl #需安装库pip install openpyxl
from openpyxl import Workbook
import numpy as np #需要安装库pip install numpy
import opencc #需要安装库pip install opencc
from openai import OpenAI #需要安装库pip install openai
import google.generativeai as genai #需要安装库pip install -U google-generativeai
from PyQt5.QtGui import QBrush, QColor, QDesktopServices, QFont, QIcon, QImage, QPainter, QPixmap#需要安装库 pip3 install PyQt5
from PyQt5.QtCore import QObject, QRect, QUrl, Qt, pyqtSignal
from PyQt5.QtWidgets import QAbstractItemView,QHeaderView,QApplication, QTableWidgetItem, QFrame, QGridLayout, QGroupBox, QLabel,QFileDialog, QStackedWidget, QHBoxLayout, QVBoxLayout, QWidget
from qfluentwidgets.components import Dialog
from qfluentwidgets import ProgressRing, SegmentedWidget, TableWidget,CheckBox, DoubleSpinBox, HyperlinkButton,InfoBar, InfoBarPosition, NavigationWidget, Slider, SpinBox, ComboBox, LineEdit, PrimaryPushButton, PushButton ,StateToolTip, SwitchButton, TextEdit, Theme, setTheme ,isDarkTheme,qrouter,NavigationInterface,NavigationItemPosition
from qfluentwidgets import FluentIcon as FIF
Software_Version = "AiNiee-chatgpt4.60" #软件版本号
cache_list = [] # 全局缓存数据
Running_status = 0 # 存储程序工作的状态,0是空闲状态,1是接口测试状态
# 6是翻译任务进行状态,7是错行检查状态
# 定义线程锁
lock1 = threading.Lock() #这个用来锁缓存文件
lock2 = threading.Lock() #这个用来锁UI信号的
lock3 = threading.Lock() #这个用来锁自动备份缓存文件
# 工作目录改为python源代码所在的目录
script_dir = os.path.dirname(os.path.abspath(sys.argv[0])) # 获取当前工作目录
print("[INFO] 当前工作目录是:",script_dir,'\n')
# 设置资源文件夹路径
resource_dir = os.path.join(script_dir, "resource")
# 翻译器
class Translator():
def __init__(self):
pass
def Main(self):
global cache_list, Running_status
# ——————————————————————————————————————————配置信息初始化—————————————————————————————————————————
configurator.initialize_configuration()
request_limiter.initialize_limiter()
# ——————————————————————————————————————————读取原文到缓存—————————————————————————————————————————
# 读取文件
Input_Folder = configurator.Input_Folder
if configurator.translation_project == "Mtool导出文件":
cache_list = File_Reader.read_mtool_files(self,folder_path = Input_Folder)
elif configurator.translation_project == "T++导出文件":
cache_list = File_Reader.read_xlsx_files (self,folder_path = Input_Folder)
elif configurator.translation_project == "Ainiee缓存文件":
cache_list = File_Reader.read_cache_files(self,folder_path = Input_Folder)
# 将浮点型,整数型文本内容变成字符型文本内容
Cache_Manager.convert_source_text_to_str(self,cache_list)
# 如果翻译日语或者韩语文本时,则去除非中日韩文本
Text_Source_Language = Window.Widget_translation_settings.A_settings.comboBox_source_text.currentText()
if Text_Source_Language == "日语" or Text_Source_Language == "韩语":
Cache_Manager.process_dictionary_list(self,cache_list)
# ——————————————————————————————————————————构建并发任务池子—————————————————————————————————————————
# 计算并发任务数
line_count_configuration = configurator.text_line_counts # 获取每次翻译行数配置
total_text_line_count = Cache_Manager.count_translation_status_0(self, cache_list)
if total_text_line_count % line_count_configuration == 0:
tasks_Num = total_text_line_count // line_count_configuration
else:
tasks_Num = total_text_line_count // line_count_configuration + 1
# 更新界面UI信息,并输出各种信息
project_id = cache_list[0]["project_id"]
user_interface_prompter.signal.emit("初始化翻译界面数据",project_id,total_text_line_count,0,0) #需要输入够当初设定的参数个数
user_interface_prompter.signal.emit("翻译状态提示","开始翻译",0,0,0)
print("[INFO] 翻译项目为",configurator.translation_project, '\n')
print("[INFO] 翻译平台为",configurator.translation_platform, '\n')
print("[INFO] AI模型为",configurator.model_type, '\n')
if configurator.translation_platform == "Openai代理":
print("[INFO] 中转地址为",configurator.openai_base_url, '\n')
elif configurator.translation_platform == "Openai官方":
print("[INFO] 账号类型为",Window.Widget_Openai.comboBox_account_type.currentText(), '\n')
print("[INFO] 游戏文本从",configurator.source_language, '翻译到', configurator.target_language,'\n')
print("[INFO] 当前设定的系统提示词为:", configurator.get_system_prompt(), '\n')
original_exmaple,translation_example = configurator.get_default_translation_example()
print("[INFO] 已添加默认原文示例",original_exmaple, '\n')
print("[INFO] 已添加默认译文示例",translation_example, '\n')
print("[INFO] 文本总行数为:",total_text_line_count," 每次发送行数为:",line_count_configuration," 计划的翻译任务总数是:", tasks_Num)
print("\033[1;32m[INFO] \033[0m 五秒后开始进行翻译,请注意保持网络通畅,余额充足。", '\n')
time.sleep(5)
# 测试用,会导致任务多一个,注意下
#api_requester_instance = Api_Requester()
#api_requester_instance.Concurrent_Request_Openai()
# 创建线程池
The_Max_workers = configurator.thread_counts # 获取线程数配置
with concurrent.futures.ThreadPoolExecutor (The_Max_workers) as executor:
# 创建实例
api_requester_instance = Api_Requester()
# 向线程池提交任务
for i in range(tasks_Num):
# 根据不同平台调用不同接口
if configurator.translation_platform == "Openai官方" or configurator.translation_platform == "Openai代理":
executor.submit(api_requester_instance.Concurrent_Request_Openai)
elif configurator.translation_platform == "Google官方":
executor.submit(api_requester_instance.Concurrent_Request_Google)
# 等待线程池任务完成
executor.shutdown(wait=True)
# 检查主窗口是否已经退出
if Running_status == 10 :
return
# 检查翻译任务是否已经暂停
if Running_status == 1011 :
pass
# ——————————————————————————————————————————检查没能成功翻译的文本,拆分翻译————————————————————————————————————————
#计算未翻译文本的数量
untranslated_text_line_count = Cache_Manager.count_and_update_translation_status_0_2(self,cache_list)
#重新翻译次数限制
retry_translation_count = 1
while untranslated_text_line_count != 0 :
print("\033[1;33mWarning:\033[0m 仍然有部分未翻译,将进行拆分后重新翻译,-----------------------------------")
print("[INFO] 当前重新翻译次数:",retry_translation_count ," 到达最大次数:10 时,将停止翻译")
#根据算法计算拆分的文本行数
line_count_configuration = configurator.update_text_line_count(line_count_configuration)
print("[INFO] 未翻译文本总行数为:",untranslated_text_line_count," 每次发送行数修改为:",line_count_configuration, '\n')
#如果实时调教功能没有开的话,则每次重新翻译,增加OpenAI的随机性
if configurator.translation_platform == "Openai官方" or configurator.translation_platform == "Openai代理":
if (Window.Interface18.checkBox.isChecked() == False) and (retry_translation_count != 1) :
if configurator.openai_temperature + 0.1 <= 1.0 :
configurator.openai_temperature = configurator.openai_temperature + 0.1
else:
configurator.openai_temperature = 1.0
print("\033[1;33mWarning:\033[0m 当前AI模型的随机度设置为:",configurator.openai_temperature)
# 计算可并发任务总数
if untranslated_text_line_count % line_count_configuration == 0:
tasks_Num = untranslated_text_line_count // line_count_configuration
else:
tasks_Num = untranslated_text_line_count // line_count_configuration + 1
# 创建线程池
The_Max_workers = configurator.thread_counts # 获取线程数配置
with concurrent.futures.ThreadPoolExecutor (The_Max_workers) as executor:
# 创建实例
api_requester_instance = Api_Requester()
# 向线程池提交任务
for i in range(tasks_Num):
# 根据不同平台调用不同接口
if configurator.translation_platform == "Openai官方" or configurator.translation_platform == "Openai代理":
executor.submit(api_requester_instance.Concurrent_Request_Openai)
elif configurator.translation_platform == "Google官方":
executor.submit(api_requester_instance.Concurrent_Request_Google)
# 等待线程池任务完成
executor.shutdown(wait=True)
#检查主窗口是否已经退出
if Running_status == 10 :
return
#检查是否已经达到重翻次数限制
retry_translation_count = retry_translation_count + 1
if retry_translation_count >= 10 :
print ("\033[1;33mWarning:\033[0m 已经达到重新翻译次数限制,但仍然有部分文本未翻译,不影响使用,可手动翻译", '\n')
break
#重新计算未翻译文本的数量
untranslated_text_line_count = Cache_Manager.count_and_update_translation_status_0_2(self,cache_list)
# ——————————————————————————————————————————将数据处理并保存为文件—————————————————————————————————————————
print ("\033[1;32mSuccess:\033[0m 翻译阶段已完成,正在处理数据-----------------------------------", '\n')
#转换简繁文本
target_language = configurator.target_language
if target_language == "简中" or target_language == "繁中":
try:
cache_list = File_Outputter.simplified_and_traditional_conversion(self,cache_list, target_language)
print(f"\033[1;32mSuccess:\033[0m 文本转化{target_language}完成-----------------------------------", '\n')
except Exception as e:
print("\033[1;33mWarning:\033[0m 文本转换出现问题!!将跳过该步,错误信息如下")
print(f"Error: {e}\n")
# 将翻译结果写为文件
output_path = configurator.Output_Folder
if configurator.translation_project == "Mtool导出文件":
File_Outputter.output_json_file(self,cache_list, output_path)
elif configurator.translation_project == "T++导出文件":
File_Outputter.output_excel_file(self,cache_list, output_path)
elif configurator.translation_project == "Ainiee缓存文件":
if cache_list[0]["project_type"] == "Mtool":
File_Outputter.output_json_file(self,cache_list, output_path)
else:
File_Outputter.output_excel_file(self,cache_list, output_path)
print("\033[1;32mSuccess:\033[0m 译文文件写入完成-----------------------------------", '\n')
# —————————————————————————————————————#全部翻译完成——————————————————————————————————————————
user_interface_prompter.signal.emit("翻译状态提示","翻译完成",0,0,0)
print("\n--------------------------------------------------------------------------------------")
print("\n\033[1;32mSuccess:\033[0m 已完成全部翻译任务,程序已经停止")
print("\n\033[1;32mSuccess:\033[0m 请检查译文文件,格式是否错误,存在错行,或者有空行等问题")
print("\n-------------------------------------------------------------------------------------\n")
def Check_main(self):
global cache_list, Running_status
# ——————————————————————————————————————————配置信息初始化—————————————————————————————————————————
configurator.initialize_configuration_check()
request_limiter.initialize_limiter_check()
# ——————————————————————————————————————————读取原文到缓存—————————————————————————————————————————
# 读取文件
Input_Folder = configurator.Input_Folder
if configurator.translation_project == "Mtool导出文件":
cache_list = File_Reader.read_mtool_files(self,folder_path = Input_Folder)
elif configurator.translation_project == "T++导出文件":
cache_list = File_Reader.read_xlsx_files (self,folder_path = Input_Folder)
# —————————————————————————————————————处理读取的文件——————————————————————————————————————————
# 将浮点型,整数型文本内容变成字符型文本内容
Cache_Manager.convert_source_text_to_str(self,cache_list)
# 统计已翻译文本的tokens总量,并根据不同项目修改翻译状态
tokens_consume_all = Cache_Manager.count_tokens(self, cache_list)
# —————————————————————————————————————创建并发嵌入任务——————————————————————————————————————————
#根据tokens_all_consume与除以6090计算出需要请求的次数,并向上取整(除以6090是为了富余任务数)
tasks_Num = int(math.ceil(tokens_consume_all / 7000))
print("[DEBUG] 全部文本需要嵌入请求的次数是",tasks_Num)
# 初始化一下界面提示器里面存储的相关变量
user_interface_prompter.translated_line_count = 0
user_interface_prompter.total_text_line_count = Cache_Manager.count_translation_status_0(self, cache_list)
#测试用
#api_requester_instance = Api_Requester()
#api_requester_instance.Concurrent_request_Embeddings()
# 创建线程池
The_Max_workers = multiprocessing.cpu_count() * 4 + 1
with concurrent.futures.ThreadPoolExecutor (The_Max_workers) as executor:
# 创建实例
api_requester_instance = Api_Requester()
# 向线程池提交任务
for i in range(tasks_Num):
# 根据不同平台调用不同接口
executor.submit(api_requester_instance.Concurrent_request_Embeddings)
# 等待线程池任务完成
executor.shutdown(wait=True)
#检查主窗口是否已经退出
if Running_status == 10 :
return
print("\033[1;32mSuccess:\033[0m 全部文本检查编码完成-------------------------------------")
# —————————————————————————————————————开始检查,并整理需要重新翻译的文本——————————————————————————————————————————
#创建存储原文与译文的列表,方便复制粘贴,这里是两个空字符串,后面会被替换
sentences = ["", ""]
misaligned_text = {} #存储错行文本的字典
#创建存储每对翻译相似度计算过程日志的字符串
similarity_log = ""
log_count = 0
count_error = 0 #错误文本计数变量
# 把等于3的翻译状态改为0
for item in cache_list:
if item.get('translation_status') == 3:
item['translation_status'] = 0
# 统计翻译状态为0的文本数
List_len = Cache_Manager.count_translation_status_0(self, cache_list)
for entry in cache_list:
translation_status = entry.get('translation_status')
if translation_status == 0:
#将sentence[0]与sentence[1]转换成字符串数据,确保能够被语义相似度检查模型识别,防止数字型数据导致报错
sentences[0] = str(entry["source_text"])
sentences[1] = str(entry["translated_text"])
#输出sentence里的两个文本 和 语义相似度检查结果
print("[INFO] 原文是:", sentences[0])
print("[INFO] 译文是:", sentences[1])
#计算语义相似度----------------------------------------
Semantic_similarity =entry["semantic_similarity"]
print("[INFO] 语义相似度:", Semantic_similarity, "%")
#计算符号相似度----------------------------------------
# 用正则表达式匹配原文与译文中的标点符号
k_syms = re.findall(r'[。!?…♡♥=★♪]', sentences[0])
v_syms = re.findall(r'[。!?…♡♥=★♪]', sentences[1])
#假如v_syms与k_syms都不为空
if len(v_syms) != 0 and len(k_syms) != 0:
#计算v_syms中的符号在k_syms中存在相同符号数量,再除以v_syms的符号总数,得到相似度
Symbolic_similarity = len([sym for sym in v_syms if sym in k_syms]) / len(v_syms) * 100
#假如v_syms与k_syms都为空,即原文和译文都没有标点符号
elif len(v_syms) == 0 and len(k_syms) == 0:
Symbolic_similarity = 1 * 100
else:
Symbolic_similarity = 0
print("[INFO] 符号相似度:", Symbolic_similarity, "%")
#计算字数相似度----------------------------------------
# 计算k中的日文、中文,韩文,英文字母的个数
Q, W, E, R = Response_Parser.count_japanese_chinese_korean(self,sentences[0])
# 计算v中的日文、中文,韩文,英文字母的个数
A, S, D, F = Response_Parser.count_japanese_chinese_korean(self,sentences[1])
# 计算每个总字数
len1 = Q + W + E + R
len2 = A + S + D + F
#设定基准字数差距,暂时靠经验设定
if len1 <= 25:
Base_word_count = 15
else:
Base_word_count = 25
#计算字数差值
Word_count_difference = abs((len1 - len2) )
if Word_count_difference > Base_word_count:
Word_count_difference = Base_word_count
# 计算字数相差程度
Word_count_similarity =(1- Word_count_difference / Base_word_count) * 100
print("[INFO] 字数相似度:", Word_count_similarity, "%")
#获取设定的权重
Semantic_weight = Window.Widget_check.doubleSpinBox_semantic_weight.value()
Symbolic_weight = Window.Widget_check.doubleSpinBox_symbol_weight.value()
Word_count_weight = Window.Widget_check.doubleSpinBox_word_count_weight.value()
similarity_threshold = Window.Widget_check.spinBox_similarity_threshold.value()
#计算总相似度
similarity = Semantic_similarity * Semantic_weight + Symbolic_similarity * Symbolic_weight + Word_count_similarity * Word_count_weight
#输出各权重值
print("[INFO] 语义权重:", Semantic_weight,"符号权重:", Symbolic_weight,"字数权重:", Word_count_weight)
#如果语义相似度小于于等于阈值,需要重翻译
if similarity <= similarity_threshold:
count_error = count_error + 1
print("[INFO] 总相似度结果:", similarity, "%,小于相似度阈值", similarity_threshold,"%,需要重翻译")
#错误文本计数提醒
print("\033[1;33mWarning:\033[0m 当前错误文本数量:", count_error)
#将错误文本存储到字典里
misaligned_text[sentences[0]] = sentences[1]
# 检查通过,改变翻译状态为不需要翻译
else :
entry['translation_status'] = 1
print("[INFO] 总相似度结果:", similarity, "%", ",不需要重翻译")
#创建格式化字符串,用于存储每对翻译相似度计算过程日志
if log_count <= 10000 :#如果log_count小于等于10000,避免太大
similarity_log = similarity_log + "\n" + "原文是:" + sentences[0] + "\n" + "译文是:" + sentences[1] + "\n" + "语义相似度:" + str(Semantic_similarity) + "%" + "\n" + "符号相似度:" + str(Symbolic_similarity) + "%" + "\n" + "字数相似度:" + str(Word_count_similarity) + "%" + "\n" + "总相似度结果:" + str(similarity) + "%" + "\n" + "语义权重:" + str(Semantic_weight) + ",符号权重:" + str(Symbolic_weight) + ",字数权重:" + str(Word_count_weight) + "\n" + "当前检查进度:" + str(round((log_count+1)/List_len*100,2)) + "%" + "\n"
log_count = log_count + 1
#输出遍历进度,转换成百分百进度
print("[INFO] 当前检查进度:", round((log_count)/List_len*100,2), "% \n")
# 构建输出检查结果路径
output_path = configurator.Output_Folder
folder_path = os.path.join(output_path, "misalignment_check_result")
os.makedirs(folder_path, exist_ok=True)
#检查完毕,将错误文本字典写入json文件
with open(os.path.join(folder_path, "misaligned_text.json"), 'w', encoding='utf-8') as f:
json.dump(misaligned_text, f, ensure_ascii=False, indent=4)
#将每对翻译相似度计算过程日志写入txt文件
with open(os.path.join(folder_path, "log.txt"), 'w', encoding='utf-8') as f:
f.write(similarity_log)
# ——————————————————————————————————————————配置信息初始化—————————————————————————————————————————
configurator.initialize_configuration()
request_limiter.initialize_limiter()
# 初始化一下界面提示器里面存储的相关变量
user_interface_prompter.translated_line_count = 0
user_interface_prompter.total_text_line_count = Cache_Manager.count_translation_status_0(self, cache_list)
# —————————————————————————————————————开始重新翻译——————————————————————————————————————————
#记录循环翻译次数
Number_of_iterations = 0
#计算需要翻译文本的数量
count_not_Translate = Cache_Manager.count_translation_status_0(self, cache_list)
while count_not_Translate != 0 :
# 计算可并发任务总数
if count_not_Translate % 1 == 0:
tasks_Num = count_not_Translate // 1
else:
tasks_Num = count_not_Translate // 1 + 1
# 创建线程池
The_Max_workers = configurator.thread_counts # 获取线程数配置
with concurrent.futures.ThreadPoolExecutor (The_Max_workers) as executor:
# 创建实例
api_requester_instance = Api_Requester()
# 向线程池提交任务
for i in range(tasks_Num):
# 根据不同平台调用不同接口
executor.submit(api_requester_instance.Concurrent_Request_Openai)
# 等待线程池任务完成
executor.shutdown(wait=True)
#检查主窗口是否已经退出
if Running_status == 10 :
return
#重新计算未翻译文本的数量
count_not_Translate = Cache_Manager.count_and_update_translation_status_0_2(self, cache_list)
#记录循环次数
Number_of_iterations = Number_of_iterations + 1
print("\033[1;33mWarning:\033[0m 当前循环翻译次数:", Number_of_iterations, "次,到达最大循环次数5次后将退出翻译任务")
#检查是否已经陷入死循环
if Number_of_iterations == 5 :
print("\033[1;33mWarning:\033[0m 已达到最大循环次数,退出重翻任务,不影响后续使用-----------------------------------")
break
print("\n\033[1;32mSuccess:\033[0m 已重新翻译完成-----------------------------------")
# —————————————————————————————————————写入文件——————————————————————————————————————————
# 将翻译结果写为文件
output_path = configurator.Output_Folder
File_Outputter.output_translated_content(self,cache_list, output_path)
# —————————————————————————————————————全部翻译完成——————————————————————————————————————————
print("\n--------------------------------------------------------------------------------------")
print("\n\033[1;32mSuccess:\033[0m 已完成全部翻译任务,程序已经停止")
print("\n\033[1;32mSuccess:\033[0m 请检查译文文件,格式是否错误,存在错行,或者有空行等问题")
print("\n-------------------------------------------------------------------------------------\n")
# 接口请求器
class Api_Requester():
def __init__(self):
pass
# 整理发送内容(Openai)
def organize_send_content_openai(self,source_text_str,source_text_dict):
#创建message列表,用于发送
messages = []
#构建系统提示词
prompt = configurator.get_system_prompt()
system_prompt ={"role": "system","content": prompt }
#print("[INFO] 当前系统提示词为", prompt,'\n')
messages.append(system_prompt)
#构建原文与译文示例
original_exmaple,translation_example = configurator.get_default_translation_example()
the_original_exmaple = {"role": "user","content":original_exmaple }
the_translation_example = {"role": "assistant", "content":translation_example }
#print("[INFO] 已添加默认原文示例",original_exmaple)
#print("[INFO] 已添加默认译文示例",translation_example)
messages.append(the_original_exmaple)
messages.append(the_translation_example)
#如果开启译前替换字典功能,则根据用户字典进行替换
if Window.Interface21.checkBox1.isChecked() :
print("[INFO] 你开启了译前替换字典功能,正在进行替换", '\n')
dict_new = configurator.replace_strings_dictionary(source_text_dict)
print("[INFO] 译前替换字典功能已完成", '\n')
else:
dict_new = source_text_dict
#如果开启了译时提示字典功能,则添加新的原文与译文示例
if Window.Interface23.checkBox2.isChecked() :
original_exmaple_2,translation_example_2 = configurator.build_prompt_dictionary(dict_new)
if original_exmaple_2 and translation_example_2:
the_original_exmaple = {"role": "user","content":original_exmaple_2 }
the_translation_example = {"role": "assistant", "content":translation_example_2 }
messages.append(the_original_exmaple)
messages.append(the_translation_example)
print("[INFO] 检查到请求的原文中含有用户字典内容,已添加新的原文与译文示例")
print("[INFO] 已添加提示字典原文示例",original_exmaple_2)
print("[INFO] 已添加提示字典译文示例",translation_example_2)
#如果提示词工程界面的用户翻译示例开关打开,则添加新的原文与译文示例
if Window.Interface22.checkBox2.isChecked() :
original_exmaple_3,translation_example_3 = configurator.build_user_translation_example ()
if original_exmaple_3 and translation_example_3:
the_original_exmaple = {"role": "user","content":original_exmaple_3 }
the_translation_example = {"role": "assistant", "content":translation_example_3 }
messages.append(the_original_exmaple)
messages.append(the_translation_example)
print("[INFO] 检查到用户翻译示例开关打开,已添加新的原文与译文示例")
print("[INFO] 已添加用户原文示例",original_exmaple_3)
print("[INFO] 已添加用户译文示例",translation_example_3)
#构建需要翻译的文本
Original_text = {"role":"user","content":source_text_str}
messages.append(Original_text)
return messages
# 并发接口请求(Openai)
def Concurrent_Request_Openai(self):
global cache_list,Running_status
try:#方便排查子线程bug
# ——————————————————————————————————————————截取需要翻译的原文本——————————————————————————————————————————
lock1.acquire() # 获取锁
# 获取设定行数的文本,并修改缓存文件里的翻译状态为2,表示正在翻译中
rows = configurator.text_line_counts
source_text_list = Cache_Manager.process_dictionary_data(self,rows, cache_list)
lock1.release() # 释放锁
# ——————————————————————————————————————————转换原文本的格式——————————————————————————————————————————
# 将原文本列表改变为请求格式
source_text_dict, row_count = Cache_Manager.create_dictionary_from_list(self,source_text_list)
# 如果开启了保留换行符功能
if configurator.preserve_line_breaks_toggle:
print("[INFO] 你开启了保留换行符功能,正在进行替换", '\n')
source_text_dict = Cache_Manager.replace_special_characters(self,source_text_dict, "替换")
#将原文本字典转换成JSON格式的字符串,方便发送
source_text_str = json.dumps(source_text_dict, ensure_ascii=False)
# ——————————————————————————————————————————整合发送内容——————————————————————————————————————————
messages = Api_Requester.organize_send_content_openai(self,source_text_str,source_text_dict)
#——————————————————————————————————————————检查tokens发送限制——————————————————————————————————————————
#计算请求的tokens预计花费
request_tokens_consume = Request_Limiter.num_tokens_from_messages(self,messages) *1.02 #加上2%的修正系数
#计算回复的tokens预计花费,只计算发送的文本,不计算提示词与示例,可以大致得出
Original_text = [{"role":"user","content":source_text_str}] # 需要拿列表来包一层,不然计算时会出错
completion_tokens_consume = Request_Limiter.num_tokens_from_messages(self,Original_text)*1.02 #加上2%的修正系数
if request_tokens_consume >= request_limiter.max_tokens :
print("\033[1;31mError:\033[0m 该条消息总tokens数大于单条消息最大数量" )
print("\033[1;31mError:\033[0m 该条消息取消任务,进行拆分翻译" )
return
# ——————————————————————————————————————————开始循环请求,直至成功或失败——————————————————————————————————————————
start_time = time.time()
timeout = 850 # 设置超时时间为x秒
request_errors_count = 0 # 设置请求错误次数限制
Wrong_answer_count = 0 # 设置错误回复次数限制
model_degradation = False # 模型退化检测
while 1 :
#检查主窗口是否已经退出---------------------------------
if Running_status == 10 :
return
#检查子线程运行是否超时---------------------------------
if time.time() - start_time > timeout:
print("\033[1;31mError:\033[0m 子线程执行任务已经超时,将暂时取消本次任务")
break
# 检查是否符合速率限制---------------------------------
if request_limiter.RPM_and_TPM_limit(request_tokens_consume):
print("[INFO] 已发送请求,正在等待AI回复中-----------------------")
print("[INFO] 请求与回复的tokens数预计值是:",request_tokens_consume + completion_tokens_consume )
print("[INFO] 当前发送的原文文本:\n", source_text_str)
# ——————————————————————————————————————————发送会话请求——————————————————————————————————————————
# 记录开始请求时间
Start_request_time = time.time()
# 获取AI的参数设置
temperature,top_p,presence_penalty,frequency_penalty= configurator.get_model_parameters()
# 如果上一次请求出现模型退化,更改参数
if model_degradation:
frequency_penalty = 0.2
# 获取apikey
openai_apikey = configurator.get_apikey()
# 获取请求地址
openai_base_url = configurator.openai_base_url
# 创建openai客户端
openaiclient = OpenAI(api_key=openai_apikey,
base_url= openai_base_url)
# 发送对话请求
try:
#如果开启了回复josn格式的功能和可以开启该功能的模型
if (configurator.response_json_format_toggle) and (configurator.model_type == "gpt-3.5-turbo-1106" or configurator.model_type == "gpt-4-1106-preview"):
print("[INFO] 已开启强制回复josn格式功能")
response = openaiclient.chat.completions.create(
model= configurator.model_type,
messages = messages ,
temperature=temperature,
top_p = top_p,
presence_penalty=presence_penalty,
frequency_penalty=frequency_penalty,
response_format={"type": "json_object"}
)
else:
response = openaiclient.chat.completions.create(
model= configurator.model_type,
messages = messages ,
temperature=temperature,
top_p = top_p,
presence_penalty=presence_penalty,
frequency_penalty=frequency_penalty
)
#抛出错误信息
except Exception as e:
print("\033[1;31mError:\033[0m 进行请求时出现问题!!!错误信息如下")
print(f"Error: {e}\n")
#请求错误计次
request_errors_count = request_errors_count + 1
#如果错误次数过多,就取消任务
if request_errors_count >= 6 :
print("\033[1;31m[ERROR]\033[0m 请求发生错误次数过多,该线程取消任务!")
break
#处理完毕,再次进行请求
continue
#——————————————————————————————————————————收到回复,并截取回复内容中的文本内容 ————————————————————————————————————————
# 计算AI回复花费的时间
response_time = time.time()
Request_consumption_time = round(response_time - Start_request_time, 2)
# 计算本次请求的花费的tokens
try: # 因为有些中转网站不返回tokens消耗
prompt_tokens_used = int(response.usage.prompt_tokens) #本次请求花费的tokens
except Exception as e:
prompt_tokens_used = 0
try:
completion_tokens_used = int(response.usage.completion_tokens) #本次回复花费的tokens
except Exception as e:
completion_tokens_used = 0
# 提取回复的文本内容
response_content = response.choices[0].message.content
print('\n' )
print("[INFO] 已成功接受到AI的回复-----------------------")
print("[INFO] 该次请求已消耗等待时间:",Request_consumption_time,"秒")
print("[INFO] 本次请求与回复花费的总tokens是:",prompt_tokens_used + completion_tokens_used)
print("[INFO] AI回复的文本内容:\n",response_content ,'\n','\n')
# ——————————————————————————————————————————对AI回复内容进行各种处理和检查——————————————————————————————————————————
# 检查回复内容
check_result,error_content = Response_Parser.check_response_content(self,response_content,source_text_dict)
# 如果没有出现错误
if check_result :
# 转化为字典格式
response_dict = json.loads(response_content) #注意转化为字典的数字序号key是字符串类型
# 如果开启了保留换行符功能
if configurator.preserve_line_breaks_toggle:
response_dict = Cache_Manager.replace_special_characters(self,response_dict, "还原")
# 录入缓存文件
lock1.acquire() # 获取锁
Cache_Manager.update_cache_data(self,cache_list, source_text_list, response_dict)
lock1.release() # 释放锁
# 如果开启自动备份,则自动备份缓存文件
if Window.Widget_start_translation.B_settings.checkBox_switch.isChecked():
lock3.acquire() # 获取锁
# 创建存储缓存文件的文件夹,如果路径不存在,创建文件夹
output_path = os.path.join(configurator.Output_Folder, "cache")
os.makedirs(output_path, exist_ok=True)
# 输出备份
File_Outputter.output_cache_file(self,cache_list,output_path)
lock3.release() # 释放锁
lock2.acquire() # 获取锁
# 如果是进行平时的翻译任务
if Running_status == 6 :
# 计算进度信息
progress = (user_interface_prompter.translated_line_count+row_count) / user_interface_prompter.total_text_line_count * 100
progress = round(progress, 1)
# 更改UI界面信息,注意,传入的数值类型分布是字符型与整数型,小心浮点型混入
user_interface_prompter.signal.emit("更新翻译界面数据","翻译成功",row_count,prompt_tokens_used,completion_tokens_used)
# 如果进行的是错行检查任务,使用不同的计算方法
elif Running_status == 7 :
user_interface_prompter.translated_line_count = user_interface_prompter.translated_line_count + row_count
progress = user_interface_prompter.translated_line_count / user_interface_prompter.total_text_line_count * 100
progress = round(progress, 1)
print(f"\n--------------------------------------------------------------------------------------")
print(f"\n\033[1;32mSuccess:\033[0m AI回复内容检查通过!!!已翻译完成{progress}%")
print(f"\n--------------------------------------------------------------------------------------\n")
lock2.release() # 释放锁
break
# 如果出现回复错误
else:
# 更改UI界面信息
lock2.acquire() # 获取锁
# 如果是进行平时的翻译任务
if Running_status == 6 :
user_interface_prompter.signal.emit("更新翻译界面数据","翻译失败",row_count,prompt_tokens_used,completion_tokens_used)
lock2.release() # 释放锁
print("\033[1;33mWarning:\033[0m AI回复内容存在问题:",error_content,"\n")
# 检查一下是不是模型退化
if error_content == "AI回复内容出现高频词,并重新翻译":
print("\033[1;33mWarning:\033[0m 下次请求将修改参数,回避高频词输出","\n")
model_degradation = True
#错误回复计次
Wrong_answer_count = Wrong_answer_count + 1
print("\033[1;33mWarning:\033[0m AI回复内容格式错误次数:",Wrong_answer_count,"到达2次后将该段文本进行拆分翻译\n")
#检查回答错误次数,如果达到限制,则跳过该句翻译。
if Wrong_answer_count >= 2 :
print("\033[1;33mWarning:\033[0m 错误次数已经达限制,将该段文本进行拆分翻译!\n")
break
#进行下一次循环
time.sleep(3)
continue
#子线程抛出错误信息
except Exception as e:
print("\033[1;31mError:\033[0m 子线程运行出现问题!错误信息如下")
print(f"Error: {e}\n")
return
# 整理发送内容(Google)
def organize_send_content_google(self,source_text_str,source_text_dict):
#创建message列表,用于发送
messages = []
#获取系统提示词
prompt = configurator.get_system_prompt()
#获取原文与译文示例
original_exmaple,translation_example = configurator.get_default_translation_example()
# 构建系统提示词与默认示例
messages.append({'role':'user','parts':prompt +"\n###\n" + original_exmaple})
messages.append({'role':'model','parts':translation_example})
#如果开启译前替换字典功能,则根据用户字典进行替换
if Window.Interface21.checkBox1.isChecked() :
print("[INFO] 你开启了译前替换字典功能,正在进行替换", '\n')
dict_new = configurator.replace_strings_dictionary(source_text_dict)
print("[INFO] 译前替换字典功能已完成", '\n')
else:
dict_new = source_text_dict
#如果开启了译时提示字典功能,则添加新的原文与译文示例
if Window.Interface23.checkBox2.isChecked() :
original_exmaple_2,translation_example_2 = configurator.build_prompt_dictionary(dict_new)
if original_exmaple_2 and translation_example_2:
the_original_exmaple = {"role": "user","parts":original_exmaple_2 }
the_translation_example = {"role": "model", "parts":translation_example_2 }
messages.append(the_original_exmaple)
messages.append(the_translation_example)
print("[INFO] 检查到请求的原文中含有用户字典内容,已添加新的原文与译文示例")
print("[INFO] 已添加提示字典原文示例",original_exmaple_2)
print("[INFO] 已添加提示字典译文示例",translation_example_2)
#如果提示词工程界面的用户翻译示例开关打开,则添加新的原文与译文示例
if Window.Interface22.checkBox2.isChecked() :
original_exmaple_3,translation_example_3 = configurator.build_user_translation_example ()
if original_exmaple_3 and translation_example_3:
the_original_exmaple = {"role": "user","parts":original_exmaple_3 }
the_translation_example = {"role": "model", "parts":translation_example_3 }
messages.append(the_original_exmaple)
messages.append(the_translation_example)
print("[INFO] 检查到用户翻译示例开关打开,已添加新的原文与译文示例")
print("[INFO] 已添加用户原文示例",original_exmaple_3)
print("[INFO] 已添加用户译文示例",translation_example_3)
#构建需要翻译的文本
Original_text = {"role":"user","parts":source_text_str}
messages.append(Original_text)
return messages
# 并发接口请求(Google)
def Concurrent_Request_Google(self):
global cache_list,Running_status
try:#方便排查子线程bug
# ——————————————————————————————————————————截取需要翻译的原文本——————————————————————————————————————————
lock1.acquire() # 获取锁
# 获取设定行数的文本,并修改缓存文件里的翻译状态为2,表示正在翻译中
rows = configurator.text_line_counts
source_text_list = Cache_Manager.process_dictionary_data(self,rows, cache_list)
lock1.release() # 释放锁
# ——————————————————————————————————————————转换原文本的格式——————————————————————————————————————————
# 将原文本列表改变为请求格式
source_text_dict, row_count = Cache_Manager.create_dictionary_from_list(self,source_text_list)
# 如果开启了保留换行符功能
if configurator.preserve_line_breaks_toggle:
print("[INFO] 你开启了保留换行符功能,正在进行替换", '\n')
source_text_dict = Cache_Manager.replace_special_characters(self,source_text_dict, "替换")
#将原文本字典转换成JSON格式的字符串,方便发送
source_text_str = json.dumps(source_text_dict, ensure_ascii=False)
# ——————————————————————————————————————————整合发送内容——————————————————————————————————————————
messages = Api_Requester.organize_send_content_google(self,source_text_str,source_text_dict)
#——————————————————————————————————————————检查tokens发送限制——————————————————————————————————————————
#计算请求的tokens预计花费
request_tokens_consume = Request_Limiter.num_tokens_from_messages(self,messages) *1.02 #加上2%的修正系数
#计算回复的tokens预计花费,只计算发送的文本,不计算提示词与示例,可以大致得出
Original_text = [{"role":"user","content":source_text_str}] # 需要拿列表来包一层,不然计算时会出错
completion_tokens_consume = Request_Limiter.num_tokens_from_messages(self,Original_text)*1.02 #加上2%的修正系数
if request_tokens_consume >= request_limiter.max_tokens :
print("\033[1;33mWarning:\033[0m 该条消息总tokens数大于单条消息最大数量" )
print("\033[1;33mWarning:\033[0m 该条消息取消任务,进行拆分翻译" )
return
# ——————————————————————————————————————————开始循环请求,直至成功或失败——————————————————————————————————————————
start_time = time.time()
timeout = 850 # 设置超时时间为x秒
request_errors_count = 0 # 设置请求错误次数限制
Wrong_answer_count = 0 # 设置错误回复次数限制
while 1 :
#检查主窗口是否已经退出---------------------------------
if Running_status == 10 :
return
#检查子线程运行是否超时---------------------------------
if time.time() - start_time > timeout:
print("\033[1;31mError:\033[0m 子线程执行任务已经超时,将暂时取消本次任务")
break
# 检查是否符合速率限制---------------------------------
if request_limiter.RPM_and_TPM_limit(request_tokens_consume):
print("[INFO] 已发送请求,正在等待AI回复中-----------------------")
print("[INFO] 请求与回复的tokens数预计值是:",request_tokens_consume + completion_tokens_consume )