-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1302 lines (1161 loc) · 57.9 KB
/
Copy pathmain.py
File metadata and controls
1302 lines (1161 loc) · 57.9 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
import os
import base64
import subprocess
import json
import sys
import configparser
import requests
import shutil
import uuid
import send2trash
from bs4 import BeautifulSoup
import atexit
from PySide2 import QtCore, QtWidgets,QtGui
from PySide2.QtWidgets import QTreeView, QVBoxLayout, QMainWindow, QPushButton, QFileDialog, QMessageBox, QTableView, QTableWidgetItem, QHeaderView,QApplication, QVBoxLayout, QLineEdit,QTabWidget,QPlainTextEdit,QLabel,QSpinBox,QListView,QAction,QDialog,QCheckBox,QFontComboBox,QProgressBar,QShortcut,QSplitter,QHBoxLayout,QMenu,QInputDialog,QStatusBar
from PySide2.QtGui import QKeySequence,QFont,QPalette, QColor,QStandardItem, QStandardItemModel,QIntValidator,QDesktopServices
from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import QThread, Signal,QFile, Qt,QUrl
def initFolder():
folder_path = "TranslateFiles"
# 检查目录是否存在
if not os.path.exists(folder_path):
os.makedirs(folder_path)
def initConfig():
global config
# global api_key,secret_key,enable_translate,ui_font_Family,ui_font_Size,dirname
# 判断配置文件是否存在,若不存在则新建配置文件并初始化
if not os.path.exists('config.ini'):
config = configparser.ConfigParser()
config['BAIDU_TRANSLATE_API'] = {'api_key': '',
'secret_key': '',
'enable': 'false'}
config['UI_FONT'] = {'ui_font_Family': '5b6u6L2v6ZuF6buR',
'ui_font_Size': '10'}
config['SYSTEM_SETTINGS'] = {'dirname': '',
'dark_mode':'false',
'auto_apply_layout':'true',
'layout':{},
'case_sensitive':'false',
'exit_dont_ask_again':'false',
'exit_save':'false',
'rename':'zh_cn.json',
'ensure_ascii':'false'}
with open('config.ini', 'w', encoding='utf-8') as f:
config.write(f)
# 读取配置文件
config = configparser.ConfigParser()
with open('config.ini', 'r', encoding='utf-8') as f:
config.read_file(f)
# 获取百度翻译API的AK、SK和是否开启机翻
try:
api_key = config.get('BAIDU_TRANSLATE_API', 'api_key')
secret_key = config.get('BAIDU_TRANSLATE_API', 'secret_key')
enable_translate = config.getboolean('BAIDU_TRANSLATE_API', 'enable')
ui_font_Family = config.get('UI_FONT', 'ui_font_Family')
ui_font_Size = config.getint('UI_FONT', 'ui_font_Size')
dirname = base64.b64decode(config.get('SYSTEM_SETTINGS', 'dirname')).decode('utf-8')
dark_mode = config.getboolean('SYSTEM_SETTINGS', 'dark_mode')
auto_apply_layout = config.getboolean('SYSTEM_SETTINGS', 'auto_apply_layout')
case_sensitive = config.getboolean('SYSTEM_SETTINGS', 'case_sensitive')
ensure_ascii = config.getboolean('SYSTEM_SETTINGS', 'ensure_ascii')
exit_dont_ask_again = config.getboolean('SYSTEM_SETTINGS', 'exit_dont_ask_again')
exit_save = config.getboolean('SYSTEM_SETTINGS', 'exit_save')
layout = json.loads(config.get('SYSTEM_SETTINGS', 'layout'))
rename = config.get('SYSTEM_SETTINGS', 'rename')
except:
QMessageBox.warning(None, "错误", "配置文件出现错误,已重置为初始值")
if os.path.exists("config.ini"):
os.remove("config.ini")
initConfig()
def add_unique_id_to_json(file_path):
# 加载并解析 JSON 文件
def parse_json_file(file_path):
with open(file_path, 'r',encoding='utf-8') as f:
data = json.load(f)
return data
# 保存 JSON 文件
def save_json_file(data, file_path):
with open(file_path, 'w',encoding='utf-8') as f:
json.dump(data, f, indent=4)
# 解析 JSON 文件
data = parse_json_file(file_path)
# 检查是否已经包含 "MonianHelloTranslateUUID" 键
if "MonianHelloTranslateUUID" in data:
return data["MonianHelloTranslateUUID"]
# 获取第一个键值对的键
key = list(data.keys())[0]
# 生成唯一标识符
unique_id = str(uuid.uuid4())
# 将唯一标识符添加到字典中
data['MonianHelloTranslateUUID'] = unique_id
# 保存 JSON 文件
save_json_file(data, file_path)
# 返回唯一标识符
return unique_id
def get_access_token(api_key, secret_key):
url = "https://aip.baidubce.com/oauth/2.0/token"
params = {
"grant_type": "client_credentials",
"client_id": api_key,
"client_secret": secret_key
}
response = requests.get(url, params=params)
result = response.json()
access_token = result["access_token"]
return access_token
def translate_text(text, from_lang, to_lang, access_token):
url = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1"
headers = {
"Content-Type": "application/json;charset=utf-8"
}
body = {
"from": from_lang,
"to": to_lang,
"q": text
}
params = {
"access_token": access_token
}
response = requests.post(url, headers=headers, params=params, json=body)
result = response.json()
try:
translated_text = result["result"]["trans_result"][0]["dst"]
except Exception as e:
translated_text = ""
QMessageBox.warning(QMessageBox.warning, '翻译错误', "由于未知原因,无法翻译文本\"{}\"。请参考以下错误信息:\n{}\n{}".format(text, response.json(), e))
return translated_text
class TranslatorThread(QThread):
finished = Signal()
progress = Signal(int)
error = Signal(str)
def __init__(self, file_path, from_lang, to_lang, api_key, secret_key):
super().__init__()
self.file_path = file_path
self.from_lang = from_lang
self.to_lang = to_lang
self.api_key = api_key
self.secret_key = secret_key
def run(self):
initFolder()
#执行前保存一遍文件
file_browser.on_savebutton_clicked()
try:
access_token = get_access_token(self.api_key, self.secret_key)
except Exception as e:
self.error.emit(str(e))
else:
uuid = add_unique_id_to_json(self.file_path)
try:
# 如果已经有保存翻译结果的文件,则读取该文件,将其转为 Python 字典
with open('TranslateFiles/'+uuid+'.json', 'r', encoding='utf-8') as f:
translated_dict = json.load(f)
except FileNotFoundError:
# 如果没有保存翻译结果的文件,则将 translated_dict 初始化为空字典
translated_dict = {}
with open(self.file_path, 'r', encoding='utf-8') as f:
content = json.load(f)
keys = []
values = []
for key, value in content.items():
keys.append(key)
values.append(value)
item_count = len(keys)
for i, key in enumerate(keys):
# 如果 key 已经在字典中,则跳过本次循环
# if key in translated_dict:
# continue
# 跳过特定 key
if key == "MonianHelloTranslateUUID":
continue
value = str(values[i])
translated_value = translate_text(str(value), self.from_lang, self.to_lang, access_token)
# 添加新翻译到字典中
translated_dict[key] = translated_value
progress = (i+1) / item_count * 100
self.progress.emit(progress) # 更新进度条
# 将字典实时保存到文件中
with open('TranslateFiles/'+uuid+'.json', 'w', encoding='utf-8') as f:
json.dump(translated_dict, f, indent=4)
self.finished.emit()
class FileBrowser(QMainWindow):
def __init__(self):
super(FileBrowser, self).__init__()
self.row = 0
self.file_name = ""
self.replacelineEditonEdit = False
# 加载UI文件
ui_file = QFile('MainWindow.ui')
ui_file.open(QFile.ReadOnly)
loader = QUiLoader()
self.window = loader.load(ui_file)
ui_file.close()
# # 创建一个状态栏
# self.statusBar = QStatusBar()
# self.setStatusBar(self.statusBar)
# # 在状态栏上显示文本信息
# self.statusBar.showMessage("欢迎使用我的应用!")
# 从配置文件中读取字体信息
font_family = base64.b64decode(config.get('UI_FONT', 'ui_font_Family')).decode('utf-8')
font_size = config.getint('UI_FONT', 'ui_font_Size')
# 应用保存在配置文件中的字体
ui_font = QFont(font_family, font_size)
app.setFont(ui_font)
self.tree_view = self.window.findChild(QTreeView, 'treeView')
self.printbutton = self.window.findChild(QPushButton, 'printButton')
self.savebutton = self.window.findChild(QPushButton, 'saveButton')
self.translatebutton = self.window.findChild(QPushButton, 'translateButton')
self.copyButton = self.window.findChild(QPushButton, 'copyButton')
self.selectAllPushButton = self.window.findChild(QPushButton, 'selectAllPushButton')
self.invertSelectionPushButton = self.window.findChild(QPushButton, 'invertSelectionPushButton')
self.dict_table = self.window.findChild(QTableView, 'TableView')
self.searchLineEdit = self.window.findChild(QLineEdit, 'searchLineEdit')
self.reviewJumpPageLineEdit = self.window.findChild(QLineEdit, 'reviewJumpPageLineEdit')
self.searchTableView = self.window.findChild(QTableView, 'searchTableView')
self.tabWidget = self.window.findChild(QTabWidget, 'tabWidget')
self.originalReviewPlainTextEdit = self.window.findChild(QPlainTextEdit, 'originalReviewPlainTextEdit')
self.translateReviewPlainTextEdit = self.window.findChild(QPlainTextEdit, 'translateReviewPlainTextEdit')
self.machineTranslateReviewPlainTextEdit = self.window.findChild(QPlainTextEdit, 'machineTranslateReviewPlainTextEdit')
self.reviewPreviousPushButton = self.window.findChild(QPushButton,'reviewPreviousPushButton')
self.reviewNextPushButton = self.window.findChild(QPushButton,'reviewNextPushButton')
self.reviewLabel = self.window.findChild(QLabel,'reviewLabel')
self.replacelineEdit = self.window.findChild(QLineEdit,'replacelineEdit')
self.replacelistView = self.window.findChild(QListView,'replacelistView')
self.actionClearSpaces = self.window.findChild(QAction, 'actionClearSpaces')
self.actionSettings = self.window.findChild(QAction, 'actionSettings')
self.actionAbout = self.window.findChild(QAction, 'actionAbout')
self.actionSaveLayout = self.window.findChild(QAction, 'actionSaveLayout')
self.actionSaveAsSafeMode = self.window.findChild(QAction, 'actionSaveAsSafeMode')
self.translateProgressBar = self.window.findChild(QProgressBar, 'translateProgressBar')
self.splitter = self.window.findChild(QSplitter, 'splitter')
#快捷键
shortcutCtrl_F = QShortcut(QKeySequence('Ctrl+F'), self.searchLineEdit)
shortcutCtrl_F.activated.connect(self.handle_Ctrl_F_action)
shortcutCtrl_H = QShortcut(QKeySequence('Ctrl+H'), self.searchLineEdit)
shortcutCtrl_H.activated.connect(self.handle_Ctrl_H_action)
shortcutCtrl_Down = QShortcut(QKeySequence('Ctrl+Down'), self.replacelineEdit)
shortcutCtrl_Down.activated.connect(self.handle_Ctrl_Down_action)
shortcutCtrl_Up = QShortcut(QKeySequence('Ctrl+Up'), self.replacelineEdit)
shortcutCtrl_Up.activated.connect(self.handle_Ctrl_Up_action)
shortcutCtrl_A = QShortcut(QKeySequence('Ctrl+Shift+A'), self.selectAllPushButton)
shortcutCtrl_A.activated.connect(self.handle_Ctrl_A_action)
self.translateProgressBar.hide()
#QAction
self.actionClearSpaces.triggered.connect(self.handleActionClearSpaces)
self.actionSaveAsSafeMode.triggered.connect(self.handleActionSaveAsSafeMode)
self.actionSettings.triggered.connect(self.handleActionSettings)
self.actionAbout.triggered.connect(self.handleActionAbout)
self.actionSaveLayout.triggered.connect(self.handleActionSaveLayout)
#禁止用户编辑replacelistView
self.replacelistView.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
#设置数字校验器
self.reviewJumpPageLineEdit.setValidator(QIntValidator())
#绑定回车事件
self.searchLineEdit.returnPressed.connect(self.on_searchLineEdit_return_pressed)
self.replacelineEdit.returnPressed.connect(self.on_replacelineEdit_return_pressed)
self.reviewJumpPageLineEdit.returnPressed.connect(self.on_reviewJumpPageLineEdit_return_pressed)
# 创建文件浏览器模型
self.model = QtWidgets.QFileSystemModel()
self.model.setRootPath(base64.b64decode(config.get('SYSTEM_SETTINGS', 'dirname')).decode('utf-8'))
self.model.setFilter(QtCore.QDir.NoDotAndDotDot | QtCore.QDir.AllEntries)
# 将模型设置为 QTreeView 的模型
self.tree_view.setModel(self.model)
# 设置根索引为桌面文件夹的索引
root_index = self.model.index(base64.b64decode(config.get('SYSTEM_SETTINGS', 'dirname')).decode('utf-8'))
self.tree_view.setRootIndex(root_index)
self.tabWidget.currentChanged.connect(self.tabChanged)
# 隐藏列
self.tree_view.setColumnHidden(1, True)
self.tree_view.setColumnHidden(2, True)
self.tree_view.setColumnHidden(3, True)
# 将“Name”列的宽度设置为固定值
self.tree_view.setColumnWidth(0, 200) # 设置“Name”列的宽度为 200 像素
# 绑定双击事件
self.tree_view.doubleClicked.connect(self.on_treeView_doubleClicked)
# 将按钮与其回调函数关联
self.printbutton.clicked.connect(self.on_printbutton_clicked)
self.savebutton.clicked.connect(self.on_savebutton_clicked)
self.translatebutton.clicked.connect(self.on_translatebutton_clicked)
self.copyButton.clicked.connect(self.on_copyButton_clicked)
self.reviewPreviousPushButton.clicked.connect(self.on_reviewPreviousPushButton_clicked)
self.reviewNextPushButton.clicked.connect(self.on_reviewNextPushButton_clicked)
self.invertSelectionPushButton.clicked.connect(self.on_invertSelectionPushButton_clicked)
self.selectAllPushButton.clicked.connect(self.on_selectAllPushButton_clicked)
self.invertSelectionPushButton.hide()
self.selectAllPushButton.hide()
self.dict_table.verticalHeader().sectionClicked.connect(self.handleHeaderClicked)
self.tree_view.setContextMenuPolicy(Qt.CustomContextMenu)
self.tree_view.customContextMenuRequested.connect(self.showContextMenu)
# 显示窗口
self.window.show()
# 初始化百度翻译API
self.translate = None
# 在 __init__ 函数中连接 clicked 信号到响应函数
self.replacelistView.clicked.connect(self.handle_replacelistView_cell_clicked)
#应用保存的UI配置信息
if config.getboolean('SYSTEM_SETTINGS', 'auto_apply_layout'):
try:
data = json.loads(config.get('SYSTEM_SETTINGS', 'layout'))
pos = tuple(data['pos'])
self.window.move(pos[0], pos[1])
except Exception as e:
print(e)
try:
size = tuple(data['size'])
self.window.resize(size[0], size[1])
except Exception as e:
print(e)
try:
if data['is_maximized']:
self.window.showMaximized()
except Exception as e:
print(e)
# 读取和应用布局设置
try:
sizes_dict = json.loads(config.get('SYSTEM_SETTINGS', 'layout'))
left = sizes_dict.get('left')
middle = sizes_dict.get('middle')
right = sizes_dict.get('right')
sizes = [left, middle, right]
self.splitter.setSizes(sizes)
except Exception as e:
print(e)
def showContextMenu(self, pos):
index = self.tree_view.indexAt(pos)
if not index.isValid():
return
menu = QMenu(self)
open_action = QAction("在资源管理器中打开", self)
rename_action = QAction("重命名", self)
delete_action = QAction("移动到回收站", self)
copy_rename_action = QAction("复制并重命名", self)
menu.addAction(open_action)
menu.addAction(delete_action)
menu.addAction(copy_rename_action)
menu.addAction(rename_action)
# 连接动作的信号
open_action.triggered.connect(self.contextMenuOpenFileInExplorer)
rename_action.triggered.connect(self.contextMenuRenameFile)
delete_action.triggered.connect(self.contextMenuDeleteFile)
copy_rename_action.triggered.connect(self.contextMenuCopyAndRenameFile)
# 显示菜单
menu.exec_(self.tree_view.viewport().mapToGlobal(pos))
def contextMenuCopyAndRenameFile(self):
index = self.tree_view.currentIndex()
file_path = self.model.filePath(index).replace('/', '\\')
directory = os.path.dirname(file_path)
default_file_name =config.get('SYSTEM_SETTINGS', 'rename')
# 提示用户保存当前内容
save_prompt = QMessageBox.question(self, "保存提示", "复制前是否保存当前内容?", QMessageBox.Yes | QMessageBox.No)
if save_prompt == QMessageBox.Yes:
self.on_savebutton_clicked() # 调用保存功能
new_name, ok = QInputDialog.getText(self, "复制并重命名", "请输入新的文件名:", textEchoMode=QLineEdit.Normal, text=default_file_name)
if ok and new_name:
# 构建新的文件路径
new_file_path = os.path.join(directory, new_name)
try:
# 复制文件
shutil.copy2(file_path, new_file_path)
# 更新模型数据以反映新文件的添加
self.model.setRootPath(directory)
except OSError as e:
QMessageBox.warning(self, "复制并重命名失败", str(e))
def contextMenuOpenFileInExplorer(self):
index = self.tree_view.currentIndex()
file_path = (self.model.filePath(index)).replace('/', '\\')
subprocess.Popen('explorer /select,"{}"'.format(file_path), creationflags=subprocess.CREATE_NO_WINDOW)
def contextMenuRenameFile(self):
index = self.tree_view.currentIndex()
file_path = (self.model.filePath(index)).replace('/', '\\')
new_name, ok = QInputDialog.getText(self, "重命名", "请输入新的文件名:", textEchoMode=QLineEdit.Normal,text=os.path.basename(file_path))
if ok and new_name:
# 获取文件所在目录
directory = os.path.dirname(file_path)
# 构建新的文件路径
new_file_path = os.path.join(directory, new_name)
try:
os.rename(file_path, new_file_path)
# 更新模型数据以反映重命名
self.model.setRootPath(directory)
except OSError as e:
# 处理重命名失败的情况
QMessageBox.warning(self, "重命名失败", str(e))
def contextMenuDeleteFile(self):
index = self.tree_view.currentIndex()
file_path = (self.model.filePath(index)).replace('/', '\\')
send2trash.send2trash(file_path)
def onExit(self):
if config.getboolean('SYSTEM_SETTINGS', 'exit_dont_ask_again'):
if config.getboolean('SYSTEM_SETTINGS', 'exit_save'):
self.on_savebutton_clicked()
return
else:
return
msgBox = QMessageBox()
msgBox.setWindowTitle("退出")
msgBox.setText("是否将更改保存到文件 ")
# 添加QCheckBox控件,并设置靠右对齐
dont_ask_checkbox = QCheckBox("不再提示", msgBox)
# checkbox_style = """
# QCheckBox::indicator {
# subcontrol-position: left;
# left:100%;
# }
# """
# dont_ask_checkbox.setStyleSheet(checkbox_style)
# 创建一个水平布局管理器,并将QCheckBox添加到其中
layout = QHBoxLayout()
layout.addWidget(dont_ask_checkbox)
# 将布局管理器添加到QMessageBox中
box_layout = msgBox.layout()
box_layout.addLayout(layout, 1, 0, 1, box_layout.columnCount())
# 添加“保存”和“取消”按钮
save_button = msgBox.addButton("保存", QMessageBox.YesRole)
save_button.setObjectName("save_button")
cancel_button = msgBox.addButton("取消", QMessageBox.NoRole)
cancel_button.setObjectName("cancel_button")
# 执行QMessageBox并获取用户的选择
reply = msgBox.exec_()
if msgBox.clickedButton() == save_button:
self.on_savebutton_clicked()
if dont_ask_checkbox.isChecked():
config.set('SYSTEM_SETTINGS', 'exit_dont_ask_again', 'true')
config.set('SYSTEM_SETTINGS', 'exit_save', 'true')
with open("config.ini", 'w', encoding='utf-8') as f:
config.write(f)
elif msgBox.clickedButton() == cancel_button:
if dont_ask_checkbox.isChecked():
config.set('SYSTEM_SETTINGS', 'exit_dont_ask_again', 'true')
config.set('SYSTEM_SETTINGS', 'exit_save', 'false')
with open("config.ini", 'w', encoding='utf-8') as f:
config.write(f)
else:
return
def handleActionSaveLayout(self):
sizes_dict = {'left':self.splitter.sizes()[0], 'middle':self.splitter.sizes()[1], 'right':self.splitter.sizes()[2],'pos': [self.window.pos().x(), self.window.pos().y()],'size': [self.window.size().width(), self.window.size().height()],'is_maximized': self.window.isMaximized()}
print(sizes_dict)
config.set("SYSTEM_SETTINGS", "layout", json.dumps(sizes_dict))
try:
with open('config.ini', 'w') as f:
config.write(f)
except:
QMessageBox.warning(self, "警告", "保存失败")
else:
QMessageBox.information(self, "提示", "保存成功")
def handle_Ctrl_F_action(self):
self.searchLineEdit.setFocus()
def handle_Ctrl_H_action(self):
self.replacelineEdit.setFocus()
def handle_Ctrl_Down_action(self):
self.on_reviewNextPushButton_clicked()
def handle_Ctrl_A_action(self):
self.on_selectAllPushButton_clicked()
def handle_Ctrl_Up_action(self):
self.on_reviewPreviousPushButton_clicked()
def updateRootIndex(self):
# 更新文件浏览器的根索引
root_index = self.model.index(base64.b64decode(config.get('SYSTEM_SETTINGS', 'dirname')).decode('utf-8'))
self.tree_view.setRootIndex(root_index)
def handleActionSettings(self):
# 创建设置对话框
settings_dialog = SettingsDialog(self)
# 显示新窗口
settings_dialog.exec_()
def handleActionClearSpaces(self):
self.tabWidget.setCurrentIndex(0)
model = self.dict_table.model()
# 遍历所有行
for row in range(model.rowCount()):
# 获取当前行的 value 列的 QStandardItem 实例
item = model.item(row, 1)
# 获取该实例中的字符串并清除其中的空格
text = item.text().replace(' ', '')
# 将新字符串设置回该实例中
item.setText(text)
def handleActionSaveAsSafeMode(self):
# 创建保存错误的警告对话框
msg_box = QMessageBox()
msg_box.setIcon(QMessageBox.Warning)
msg_box.setWindowTitle("提示信息")
msg_box.setText("是否以安全模式保存?")
msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msg_box.setDefaultButton(QMessageBox.No)
# 获取用户选项
user_choice = msg_box.exec_()
# 根据用户选项进行操作
if user_choice == QMessageBox.Yes:
import os
from PySide2.QtCore import QDateTime
# 获取当前时间
current_datetime = QDateTime.currentDateTime().toString("yy-MM-dd-hh-mm-ss")
# 构建保存文件路径
safe_folder = "C:/SafeMode" # 安全模式文件夹路径
os.makedirs(safe_folder, exist_ok=True)
file_name = f"{current_datetime}.json" # 文件名,例如 13-13.json
save_path = os.path.join(safe_folder, file_name).replace('\\', '/')
self.tabWidget.setCurrentIndex(0)
# 获取表格中的数据
model = self.dict_table.model()
data = {}
for row in range(model.rowCount()):
key = model.index(row, 0).data()
value = model.index(row, 1).data()
data[key] = value
# 以安全模式保存文件
with open(save_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=4)
# 显示保存成功消息框
msg_box = QMessageBox()
msg_box.setIcon(QMessageBox.Information)
msg_box.setWindowTitle("提示信息")
msg_box.setText("文件已以安全模式保存至{}".format(save_path))
msg_box.exec_()
else:
pass
def handle_replacelistView_cell_clicked(self, index):
# 获取所单击单元格的值
value = self.replacelistView.model().data(index)
# 将其按照空格分割并获取第一片
try:
first_piece = value.split(' ')[0]
except IndexError:
# 如果切片不成功就取消焦点
self.dict_table.clearSelection()
return
# 将该数字转换为整数
try:
row_index = int(first_piece) - 1 # 从 0 开始计算行数
except:
pass
# 将焦点移动到 dict_table 中对应的行
model = self.dict_table.model()
if row_index >= 0 and row_index < model.rowCount():
self.dict_table.selectRow(row_index)
def get_file_path(self, index):
return self.model.filePath(index)
def on_treeView_doubleClicked(self, index):
file_path = self.get_file_path(index)
# 判断是否为 JSON 文件
if not os.path.splitext(file_path)[1].lower() == '.json':
QMessageBox.warning(self, '错误', '不是 JSON 文件!')
return
self.file_name = self.tree_view.selectedIndexes()[0].data()
if os.path.isfile(file_path):
# 如果是文件则执行打印文件的回调函数
self.on_printbutton_clicked()
# “打印文件”按钮的回调函数
def set_model_data(self, table, data):
table.clear()
table.setRowCount(len(data))
table.setColumnCount(len(data[0]))
header = QHeaderView(Qt.Orientation.Horizontal)
table.setHorizontalHeader(header)
for i, row in enumerate(data):
for j, col in enumerate(row):
item = QTableWidgetItem(str(col))
table.setItem(i, j, item)
def search_dictionary(self, key):
url = "https://dict.mcmod.cn/connection/search.php"
headers = {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"X-Requested-With": "XMLHttpRequest",
"Origin": "https://dict.mcmod.cn",
"Referer": "https://dict.mcmod.cn/"
}
data = {
"key": key,
"max":16,
"range": 1
}
response = requests.post(url, headers=headers, data=data)
response.raise_for_status()
# print(response.text)
try:
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')
except:
return 0
data = []
for row in rows:
cells = row.find_all(['td', 'th'])
row_data = [cell.get_text(strip=True) for cell in cells]
data.append(row_data)
# print(data)
def extract_first_two_elements(array):
extracted_array = [[sublist[0], sublist[1]] for sublist in array]
# print(extracted_array)
return extracted_array
def swap_values(array):
swapped_array = [[sublist[1], sublist[0]] for sublist in array]
return swapped_array
# 调用函数提取每个一维数组的前两个元素
extracted_array = extract_first_two_elements(data)
swapped_array = swap_values(extracted_array)
return swapped_array
def on_searchLineEdit_return_pressed(self):
searchResult= self.search_dictionary(self.searchLineEdit.text())
# print(searchResult)
if searchResult:
keys = []
values = []
for i in searchResult:
if i==['原文', '翻译结果']:
continue
keys.append(i[0])
values.append(i[1])
model = QStandardItemModel(len(keys), 2, self)
for i, key in enumerate(keys):
value = str(values[i])
model.setItem(i, 0, QStandardItem(key))
model.setItem(i, 1, QStandardItem(value))
# 将填充好数据的表格模型应用到 QTableView 中
self.searchTableView.setModel(model)
# 设置表头标题
model.setHeaderData(0, Qt.Horizontal, "原文")
model.setHeaderData(1, Qt.Horizontal, "翻译结果")
else:
model = QStandardItemModel(1, 1, self)
model.setItem(0, 0, QStandardItem("无搜索结果"))
self.searchTableView.setModel(model)
model.setHeaderData(0, Qt.Horizontal, "")
def on_copyButton_clicked(self):
self.tabWidget.setCurrentIndex(0)
# 获取当前的模型
model = self.dict_table.model()
index = self.tree_view.currentIndex()
file_path = self.get_file_path(index)
uuid = add_unique_id_to_json(file_path)
# print(uuid)
TranslateFilespath = 'TranslateFiles/' + uuid + '.json'
if os.path.exists(TranslateFilespath):
# print('翻译文件存在')
for row in range(model.rowCount()):
# 跳过第一列值为'MonianHelloTranslateUUID'的行
# item = model.item(row, 0)
# print(item.text())
# if item and item.text() == 'MonianHelloTranslateUUID':
# continue
# 交换第2、3列的值
index1 = model.index(row, 1)
index2 = model.index(row, 2)
data1 = model.data(index1)
data2 = model.data(index2)
model.setData(index1, data2)
model.setData(index2, data1)
def on_printbutton_clicked(self):
self.row = 0
# 获取当前选中文件的路径
self.tabWidget.setCurrentIndex(0)
index = self.tree_view.currentIndex()
file_path = self.get_file_path(index)
try:
# 打开选中的 JSON 文件,并按 key:value 的形式显示其中的内容
uuid = add_unique_id_to_json(file_path)
# print(uuid)
TranslateFilespath = 'TranslateFiles/' + uuid + '.json'
if os.path.exists(TranslateFilespath):
# print('翻译文件存在')
translationFileExists = True
else:
# print('翻译文件不存在')
translationFileExists = False
with open(file_path, 'r', encoding='utf-8') as f:
file_content = f.read()
content = json.loads(file_content)
keys = []
values = []
for key, value in content.items():
if key == "MonianHelloTranslateUUID":
continue
keys.append(key)
values.append(value)
if translationFileExists:
with open(TranslateFilespath, 'r',encoding='utf-8') as ff:
data2 = json.load(ff)
model = QStandardItemModel(len(keys), 3, self)
for i, key in enumerate(keys):
value = str(values[i])
model.setItem(i, 0, QStandardItem(key))
model.setItem(i, 1, QStandardItem(value))
model.setItem(i, 2, QStandardItem(data2.get(key)))
else:
model = QStandardItemModel(len(keys), 2, self)
for i, key in enumerate(keys):
value = str(values[i])
model.setItem(i, 0, QStandardItem(key))
model.setItem(i, 1, QStandardItem(value))
# 将填充好数据的表格模型应用到 QTableView 中
self.dict_table.setModel(model)
# 设置表头标题
model.setHeaderData(0, Qt.Horizontal, "键名")
model.setHeaderData(1, Qt.Horizontal, "原文")
model.setHeaderData(2, Qt.Horizontal, "译文")
except ValueError:
# 不是 JSON 格式,直接显示文本
self.text_edit.setPlainText(file_content)
def on_savebutton_clicked(self):
self.tabWidget.setCurrentIndex(0)
# 获取当前的模型
model = self.dict_table.model()
index = self.tree_view.currentIndex()
file_path = self.get_file_path(index)
# 获取表格中的数据
model = self.dict_table.model()
data = {}
for row in range(model.rowCount()):
key = model.index(row, 0).data()
value = model.index(row, 1).data()
data[key] = value
try:
data["MonianHelloTranslateUUID"] = add_unique_id_to_json(file_path)
except:
pass
# 将数据写入文件
with open(file_path, 'w',encoding='utf-8') as f:
json.dump(data, f, indent=4,ensure_ascii=config.getboolean('SYSTEM_SETTINGS', 'ensure_ascii'))
# 显示保存成功消息框
msg_box = QMessageBox(QMessageBox.Information, "提示信息", "文件已保存至 {}".format(file_path))
msg_box.exec_()
def on_reviewNextPushButton_clicked(self):
model = self.dict_table.model()
self.tabWidget.setCurrentIndex(1)
if 0<=self.row and self.row<model.rowCount()-1:
try:
# 更新模型中的数据
model.setData(model.index(self.row, 0), self.originalReviewPlainTextEdit.toPlainText())
model.setData(model.index(self.row, 1), self.translateReviewPlainTextEdit.toPlainText())
except:
return 0
self.row += 1
self.reviewLabel.setText("第{}个/共{}个".format(self.row+1,model.rowCount()))
self.tabChanged(1)
def on_reviewPreviousPushButton_clicked(self):
model = self.dict_table.model()
self.tabWidget.setCurrentIndex(1)
if 0<self.row and self.row<=model.rowCount():
try:
# 更新模型中的数据
model.setData(model.index(self.row, 0), self.originalReviewPlainTextEdit.toPlainText())
model.setData(model.index(self.row, 1), self.translateReviewPlainTextEdit.toPlainText())
except:
return 0
self.row -= 1
self.reviewLabel.setText("第{}个/共{}个".format(self.row+1,model.rowCount()))
self.tabChanged(1)
def handleHeaderClicked(self, logicalIndex):
# print(f"Selected row: {logicalIndex}")
if self.tabWidget.currentIndex() == 0:
self.reviewLabel.setText("第{}个/共{}个".format(logicalIndex+1,self.dict_table.model().rowCount()))
self.row = logicalIndex
self.tabWidget.setCurrentIndex(1)
def on_reviewJumpPageLineEdit_return_pressed(self):
inputrow = 1
inputrow = int(self.reviewJumpPageLineEdit.text())
self.reviewJumpPageLineEdit.clear()
try:
model = self.dict_table.model()
assert 0<= self.row <=model.rowCount()
try:
# 更新模型中的数据
model.setData(model.index(self.row, 0), self.originalReviewPlainTextEdit.toPlainText())
model.setData(model.index(self.row, 1), self.translateReviewPlainTextEdit.toPlainText())
except:
return 0
except:
return 0
if 0 < inputrow and inputrow <= model.rowCount():
self.row = inputrow-1
try:
self.reviewLabel.setText("第{}个/共{}个".format(self.row+1,self.dict_table.model().rowCount()))
self.originalReviewPlainTextEdit.setPlainText(model.index(self.row, 0).data())
self.translateReviewPlainTextEdit.setPlainText(model.index(self.row, 1).data())
self.machineTranslateReviewPlainTextEdit.setPlainText(model.index(self.row, 2).data())
except:
return 0
def tabChanged(self,index):
# print(f"Selected tab index: {index}")
try:
model = self.dict_table.model()
assert 0<= self.row <=model.rowCount()
except:
return 0
if index == 1:
try:
self.reviewLabel.setText("第{}个/共{}个".format(self.row+1,self.dict_table.model().rowCount()))
self.originalReviewPlainTextEdit.setPlainText(model.index(self.row, 0).data())
self.translateReviewPlainTextEdit.setPlainText(model.index(self.row, 1).data())
self.machineTranslateReviewPlainTextEdit.setPlainText(model.index(self.row, 2).data())
except:
return 0
if index == 0:
try:
# 更新模型中的数据
self.dict_table.selectRow(self.row)
model.setData(model.index(self.row, 0), self.originalReviewPlainTextEdit.toPlainText())
model.setData(model.index(self.row, 1), self.translateReviewPlainTextEdit.toPlainText())
except:
return 0
def on_translatebutton_clicked(self):
# 获取选中文件的路径
index = self.tree_view.currentIndex()
file_path = self.get_file_path(index)
# 判断是否为 JSON 文件
if not os.path.splitext(file_path)[1].lower() == '.json':
QMessageBox.warning(self, '错误', '不是 JSON 文件!')
return
if not config.getboolean('BAIDU_TRANSLATE_API', 'enable'):
QMessageBox.warning(self, '错误', '配置文件中未启用翻译功能')
return
# 显示进度条
self.translateProgressBar.show()
# 创建翻译线程,启动翻译
self.translator_thread = TranslatorThread(file_path, "en", "zh", config.get('BAIDU_TRANSLATE_API', 'api_key'), config.get('BAIDU_TRANSLATE_API', 'secret_key'))
self.translator_thread.finished.connect(self.on_translation_finished)
self.translator_thread.progress.connect(self.translateProgressBar.setValue)
self.translator_thread.error.connect(self.on_translation_failed)
self.translator_thread.start()
def on_translation_finished(self):
# 隐藏进度条,恢复用户界面
self.translateProgressBar.hide()
# 刷新树形视图和属性视图
self.on_printbutton_clicked()
def on_translation_failed(self, error_msg):
# 隐藏进度条,恢复用户界面
self.translateProgressBar.hide()
# 弹出错误提示框
QMessageBox.warning(self, '翻译错误', f'翻译过程中发生错误:{error_msg}')
def on_selectAllPushButton_clicked(self):
# 获取视图绑定的模型
model = self.replacelistView.model()
# 遍历模型中的所有项,并将其选中状态设置为Checked
for i in range(model.rowCount()-1):
item = model.item(i+1)
item.setCheckState(QtCore.Qt.Checked)
def on_invertSelectionPushButton_clicked(self):
# 获取视图绑定的模型
model = self.replacelistView.model()
# 遍历模型中的所有项,并将其选中状态取反
for i in range(model.rowCount()-1):
item = model.item(i+1)
if item.checkState() == QtCore.Qt.Checked:
item.setCheckState(QtCore.Qt.Unchecked)
else:
item.setCheckState(QtCore.Qt.Checked)
def on_replacelineEdit_return_pressed(self):
if self.replacelineEditonEdit:
newString = self.replacelineEdit.text()
# print("读取到替换字符串:",newString)
if not newString:
self.replacelistView.model().removeRows(0, self.replacelistView.model().rowCount())
self.replacelineEditonEdit = False
self.replacelineEdit.clear()
self.replacelineEdit.setPlaceholderText("请输入要替换的值")
self.invertSelectionPushButton.hide()
self.selectAllPushButton.hide()
return 0
self.invertSelectionPushButton.hide()
self.selectAllPushButton.hide()
self.tabWidget.setCurrentIndex(0)
tab_index = self.tabWidget.currentIndex()
needReplaces = []
model = self.replacelistView.model()
for row in range(model.rowCount()):
item = model.item(row)
# 判断该行item是否为复选框
if item.isCheckable():
# 获取复选框状态
checked = item.checkState() == QtCore.Qt.CheckState.Checked
if checked:
needReplaces.append(row)
if tab_index == 0:
model = self.dict_table.model()
data = [] # 一维数组
for row in range(model.rowCount()):
key_item = model.item(row, 0)
value_item = model.item(row, 1)
if key_item and value_item:
data.append(value_item.text())
updates = [] # 匹配到的序号列表
new_values = [] # 替换的内容列表
temp = 0
for i in data:
if config.getboolean('SYSTEM_SETTINGS', 'case_sensitive'):
if self.oldString in i:
updates.append(temp)
new_values.append(i.replace(self.oldString, newString))
else:
pass
temp += 1
else:
import re
if self.oldString.lower() in i.lower():
updates.append(temp)
pattern = re.compile(re.escape(self.oldString), re.IGNORECASE)
new_values.append(pattern.sub(lambda m: newString if m.group().lower() == self.oldString.lower() else m.group(), i))
else:
pass
temp += 1
# print(updates)
# print(new_values)
updates = [updates[i-1] for i in needReplaces]
new_values = [new_values[i-1] for i in needReplaces]