-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathpyqt5_momotranslator.py
13517 lines (11883 loc) · 559 KB
/
pyqt5_momotranslator.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
from opencc import OpenCC
import codecs
import os
import os.path
import pickle
import re
import sys
from collections import OrderedDict
from csv import reader, writer, QUOTE_MINIMAL
from filecmp import cmp
from functools import partial, lru_cache, reduce, wraps
from getpass import getuser
from hashlib import md5
from io import StringIO
from locale import getdefaultlocale
from math import sqrt
from os.path import abspath, dirname, exists, expanduser, getsize, isfile, normpath
from pathlib import Path
from platform import machine, processor, python_version, system, uname
from re import I, IGNORECASE, escape, findall, match
from shutil import copy2
from subprocess import PIPE, Popen
from time import strftime, time
from traceback import print_exc
from unicodedata import normalize
from uuid import getnode
import yaml
from PIL import Image
from PyQt6.QtCore import QEventLoop, QTimer, QItemSelectionModel, QSize, Qt, pyqtSignal, QTranslator, QPoint
from PyQt6.QtGui import QAction, QActionGroup, QBrush, QDoubleValidator, QFont, QIcon, QImage, \
QKeySequence, QPainter, QPixmap, QStandardItemModel, QColor, QPen, QStandardItem
from PyQt6.QtWidgets import QAbstractItemView, QApplication, QDockWidget, QFileDialog, \
QGraphicsScene, QGraphicsView, QHBoxLayout, QLabel, QLineEdit, QListView, \
QListWidget, QListWidgetItem, QMainWindow, QMenu, QStatusBar, QGraphicsSceneMouseEvent, \
QTabWidget, QToolBar, QToolButton, QVBoxLayout, QWidget, QFrame, QHeaderView, QPlainTextEdit, QSizePolicy, \
QTableView, QGraphicsTextItem, QGraphicsEllipseItem, QGraphicsItem, QGraphicsItemGroup, QStyledItemDelegate
from cv2 import COLOR_BGR2RGB, COLOR_BGRA2BGR, COLOR_GRAY2BGR, COLOR_RGB2BGR, cvtColor, imdecode, imencode
from loguru import logger
from matplotlib import colormaps
from natsort import natsorted
from numpy import array, clip, fromfile, ndarray, ones, sqrt, uint8
from psutil import virtual_memory
from qtawesome import icon as qicon
from ruamel.yaml import YAML
from webcolors import hex_to_rgb, name_to_rgb, rgb_to_name
from webcolors._definitions import _reversedict, _CSS3_NAMES_TO_HEX
from PyQt6.QtCore import QByteArray, QCommandLineOption, QCommandLineParser, QCoreApplication, QDate, \
QEventLoop, QItemSelection, QItemSelectionModel, QModelIndex, QPoint, QRegularExpression, QSettings, QSize, \
QThread, QTimer, QTranslator, QUrl, QVariant, Qt, pyqtSignal
from PyQt6.QtGui import QAction, QColor, QFont, QGuiApplication, QImage, QKeySequence, QPainter, QPalette, \
QPixmap, QRegularExpressionValidator, QStandardItem, QStandardItemModel, QTextDocumentFragment, QWindow
from PyQt6.QtNetwork import QNetworkProxyFactory
from PyQt6.QtPrintSupport import QPrintDialog, QPrinter
from PyQt6.QtWidgets import QAbstractItemView, QApplication, QButtonGroup, QCalendarWidget, QCheckBox, \
QComboBox, QDockWidget, QFontComboBox, QFontDialog, QFrame, QGridLayout, QGroupBox, QHBoxLayout, \
QHeaderView, QLCDNumber, QLabel, QLineEdit, QListWidget, QMainWindow, QMenu, QMenuBar, QMessageBox, \
QPlainTextEdit, QProgressBar, QPushButton, QRadioButton, QScrollArea, QSizePolicy, QSlider, QSpacerItem, \
QSpinBox, QSplitter, QStatusBar, QStyleFactory, QTabBar, QTabWidget, QTableView, QTextEdit, QToolBar, \
QToolButton, QTreeWidget, QVBoxLayout, QWidget, QStyledItemDelegate
from PyQt6.QtWebEngineWidgets import QWebEngineView
from manga_ocr import MangaOcr
from nltk.tokenize import sent_tokenize
from pandas import DataFrame
import asyncio
import builtins
import codecs
import json
import math
import os
import os.path
import pickle
import re
import string
import sys
import warnings
import webbrowser
from ast import AsyncFunctionDef, Attribute, ClassDef, FunctionDef, Import, ImportFrom, Name, NodeTransformer, \
NodeVisitor, Pass, parse, unparse, walk
from collections import Counter, OrderedDict, defaultdict
from colorsys import hsv_to_rgb, rgb_to_hsv
from concurrent.futures import ThreadPoolExecutor, as_completed
from copy import deepcopy
from csv import reader, writer, QUOTE_MINIMAL
from datetime import datetime
from difflib import SequenceMatcher
from filecmp import cmp
from getpass import getuser
from hashlib import md5
from html import unescape
from io import BytesIO, StringIO
from itertools import chain, groupby, zip_longest
from locale import getdefaultlocale
from math import ceil, cos, floor, radians, sin, sqrt
from operator import mod
from os import getcwd, makedirs
from os.path import abspath, dirname, exists, expanduser, getmtime, getsize, isdir, isfile, normpath
from pathlib import Path
from platform import machine, platform, processor, python_version, release, system, uname, version
from pprint import pprint
from re import I, IGNORECASE, Pattern, escape, findall, finditer, match, search, sub, split
from re import compile as recompile
from shutil import copy2
from socket import gethostbyname, gethostname
from statistics import mean, median, multimode
from string import ascii_uppercase
from subprocess import PIPE, Popen, call
from textwrap import dedent, indent
from time import localtime, sleep, strftime, time
from tokenize import COMMENT, generate_tokens
from traceback import print_exc
from typing import List, Union
from unicodedata import normalize
from uuid import getnode, uuid4
from warnings import filterwarnings
import cv2
import numpy as np
import pkg_resources
import pyautogui
import pyperclip
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import xmltodict
import yaml
from PIL import Image, ImageDraw, ImageFont
from PIL.Image import fromarray
from PyQt6.QtCore import QPointF, QRectF, QSettings, QSize, QTranslator, Qt, pyqtSignal
from PyQt6.QtGui import QAction, QActionGroup, QBrush, QColor, QDoubleValidator, QFont, QFontMetrics, QIcon, QImage, \
QKeySequence, QPainter, QPainterPath, QPen, QPixmap, QPolygonF
from PyQt6.QtWidgets import QAbstractItemView, QApplication, QButtonGroup, QComboBox, QDialog, QDockWidget, QFileDialog, \
QGraphicsDropShadowEffect, QGraphicsEllipseItem, QGraphicsItem, QGraphicsLineItem, QGraphicsPixmapItem, \
QGraphicsPolygonItem, QGraphicsScene, QGraphicsTextItem, QGraphicsView, QHBoxLayout, QLabel, QLineEdit, QListView, \
QListWidget, QListWidgetItem, QMainWindow, QMenu, QMessageBox, QProgressBar, QPushButton, QRadioButton, QStatusBar, \
QTabWidget, QToolBar, QToolButton, QVBoxLayout, QWidget
from aip import AipOcr
from astor import to_source
from bs4 import BeautifulSoup, NavigableString, Tag
from cv2 import BORDER_CONSTANT, CHAIN_APPROX_SIMPLE, COLOR_BGR2BGRA, COLOR_BGR2GRAY, COLOR_BGR2RGB, COLOR_BGRA2BGR, \
COLOR_BGRA2RGBA, COLOR_GRAY2BGR, COLOR_GRAY2BGRA, COLOR_RGB2BGR, CV_16U, FILLED, GaussianBlur, IMREAD_COLOR, \
INPAINT_NS, INTER_LINEAR, MORPH_ELLIPSE, MORPH_RECT, RANSAC, RETR_EXTERNAL, RETR_LIST, RETR_TREE, \
ROTATE_90_COUNTERCLOCKWISE, THRESH_BINARY, THRESH_OTSU, add, arcLength, bitwise_and, bitwise_not, bitwise_or, \
bitwise_xor, boundingRect, boxPoints, circle, connectedComponentsWithStats, contourArea, copyMakeBorder, cvtColor, \
dilate, dnn, drawContours, erode, fillPoly, findContours, findHomography, getStructuringElement, imdecode, imencode, \
inRange, inpaint, line, minAreaRect, moments, pointPolygonTest, rectangle, resize, rotate, subtract, threshold, \
warpPerspective
from deep_translator import GoogleTranslator
from docx import Document
from docx.shared import Inches
from easyocr import Reader
from fontTools.ttLib import TTCollection, TTFont
from html2text import HTML2Text
from jieba import cut
from libcst import CSTTransformer, RemovalSentinel, parse_module
from loguru import logger
from mammoth import convert_to_html
from matplotlib import colormaps, font_manager
from natsort import natsorted
from nltk.corpus import names, words
from nltk.stem import WordNetLemmatizer
from numpy import arange, argmax, argmin, argsort, argwhere, array, asarray, ascontiguousarray, clip, diff, float16, \
float32, float64, frombuffer, fromfile, greater, int16, int32, int64, linalg, maximum, minimum, mod, ndarray, \
nonzero, ones, ones_like, percentile, sqrt, squeeze, std, subtract, transpose, uint8, unique, where, zeros, \
zeros_like
from paddleocr import PaddleOCR
from pathvalidate import sanitize_filename
from prettytable import PrettyTable
from psd_tools import PSDImage
from psutil import virtual_memory
from pyautogui import locateOnScreen, locateAllOnScreen, center, click, press, keyDown, keyUp
from pyclipper import ET_CLOSEDPOLYGON, JT_ROUND, PyclipperOffset
from pypandoc import convert_text
from pytesseract import image_to_data, image_to_string
from pytz import UTC
from qtawesome import icon as qicon
from ruamel.yaml import YAML
from scipy import ndimage
from scipy.optimize import lsq_linear, nnls
from scipy.signal import argrelextrema
from shapely.geometry import LineString, MultiLineString, MultiPoint, Point, Polygon, box
from shapely.ops import nearest_points
from skimage.segmentation import watershed
from stdlib_list import stdlib_list
from unidecode import unidecode
from webcolors import hex_to_rgb, name_to_rgb, rgb_to_name
from webcolors._definitions import _reversedict, _CSS3_NAMES_TO_HEX
filterwarnings("ignore", category=DeprecationWarning)
use_torch = True
# use_torch = False
if use_torch:
import torch
use_nlp = True
use_nlp = False
if use_nlp:
import spacy
nlp = spacy.load("en_core_web_sm")
# python3 -m spacy download en_core_web_sm #Mac
# python.exe -m spacy download en_core_web_sm #Win
# import nltk
# nltk.download('words')
# nltk.download('names')
# nltk.download('wordnet')
# nltk.download('omw-1.4')
# 合并常见单词和人名
good_words = set(words.words())
good_names = set(names.words())
good_words = good_words.union(good_names)
lemmatizer = WordNetLemmatizer()
python_ver = python_version()
# 创建转换实例,s2t表示简体到繁体,t2s表示繁体到简体
cc_s2t = OpenCC('s2t') # 简体到繁体
cc_t2s = OpenCC('t2s') # 繁体到简体
# ================================参数区================================
def a1_const():
return
# Platforms
SYSTEM = ''
platform_system = system()
platform_uname = uname()
os_kernal = platform_uname.machine
if os_kernal in ['x86_64', 'AMD64']:
if platform_system == 'Windows':
SYSTEM = 'WINDOWS'
elif platform_system == 'Linux':
SYSTEM = 'LINUX'
else: # 'Darwin'
SYSTEM = 'MAC'
else: # os_kernal = 'arm64'
if platform_system == 'Windows':
SYSTEM = 'WINDOWS'
elif platform_system == 'Darwin':
SYSTEM = 'M1'
else:
SYSTEM = 'PI'
locale_tup = getdefaultlocale()
lang_code = locale_tup[0]
username = getuser()
homedir = expanduser("~")
homedir = Path(homedir)
DOWNLOADS = homedir / 'Downloads'
DOCUMENTS = homedir / 'Documents'
mac_address = ':'.join(findall('..', '%012x' % getnode()))
node_name = platform_uname.node
current_dir = dirname(abspath(__file__))
current_dir = Path(current_dir)
dirpath = os.getcwd()
ProgramFolder = Path(dirpath)
UserDataFolder = ProgramFolder / 'MomoHanhuaUserData'
python_vs = f"{sys.version_info.major}.{sys.version_info.minor}"
APP_NAME = 'MomoTranslator'
MAJOR_VERSION = 2
MINOR_VERSION = 0
PATCH_VERSION = 0
APP_VERSION = f'v{MAJOR_VERSION}.{MINOR_VERSION}.{PATCH_VERSION}'
APP_AUTHOR = '墨问非名'
if SYSTEM == 'WINDOWS':
encoding = 'gbk'
line_feed = '\n'
cmct = 'ctrl'
else:
encoding = 'utf-8'
line_feed = '\n'
cmct = 'command'
if SYSTEM in ['MAC', 'M1']:
import applescript
from Vision import VNImageRequestHandler, VNRecognizeTextRequest
from Quartz import CGEventCreateMouseEvent, CGEventPost, kCGEventLeftMouseDown, kCGEventLeftMouseUp, \
kCGMouseButtonLeft, kCGHIDEventTap, CGEventSetType, kCGRenderingIntentDefault
from Quartz.CoreGraphics import CGDataProviderCreateWithData, CGColorSpaceCreateDeviceRGB, CGImageCreate, CGPoint
processor_name = processor()
else:
processor_name = machine()
if SYSTEM == 'WINDOWS':
import pytesseract
# 如果PATH中没有tesseract可执行文件,请指定tesseract路径
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
from winocr import recognize_pil
line_feeds = line_feed * 2
lf = line_feed
lfs = line_feeds
ignores = ('~$', '._')
type_dic = {
'xlsx': '.xlsx',
'csv': '.csv',
'pr': '.prproj',
'psd': '.psd',
'tor': '.torrent',
'xml': '.xml',
'audio': ('.aif', '.mp3', '.wav', '.flac', '.m4a', '.ogg'),
'video': ('.mp4', '.mkv', '.avi', '.flv', '.mov', '.wmv'),
'compressed': ('.zip', '.rar', '.7z', '.tar', '.gz', '.bz2'),
'font': ('.ttc', '.ttf', '.otf'),
'comic': ('.cbr', '.cbz', '.rar', '.zip', '.pdf', '.txt'),
'pic': ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp'),
'log': '.log',
'json': '.json',
'pickle': '.pkl',
'python': '.py',
'txt': '.txt',
'doc': ('.doc', '.docx'),
'ppt': ('.ppt', '.pptx'),
'pdf': '.pdf',
'html': ('.html', '.htm'),
'css': '.css',
'js': '.js',
'markdown': ('.md', '.markdown'),
'yml': ('.yml', '.yaml'),
}
ram = str(round(virtual_memory().total / (1024.0 ** 3)))
video_width = 1920
video_height = 1080
video_size = (video_width, video_height)
pylupdate = 'pylupdate6'
lrelease = 'lrelease'
window_title_prefix = f'{APP_NAME} {APP_VERSION}'
py_path = Path(__file__).resolve()
py_dev_path = py_path.parent / f'{py_path.stem}_dev.py'
py_i18n_path = py_path.parent / f'{py_path.stem}_i18n.py'
py_frag_path = py_path.parent / f'{py_path.stem}_frag.py'
py_lite_path = py_path.parent / f'{py_path.stem}_lite.py'
py_struct_path = py_path.parent / f'{py_path.stem}_struct.py'
google_max_chars = 5000
pictures_exclude = '加框,分框,框,涂白,填字,修图,-,copy,副本,拷贝,顺序,打码,测试,标注,边缘,标志,伪造'
pic_tuple = tuple(pictures_exclude.split(','))
pre_tuple = (
'zzz,'
)
scan_tuple = (
'zSoU-Nerd',
'zWater',
'ZZZZZ',
'zzzDQzzz',
'zzz DQ zzz',
'zzz LDK6 zzz',
'zzz-mephisto',
'zzz MollK6 zzz',
'z',
'zzz empire',
'zzdelirium_dargh',
'zzTLK',
'zzz6 (Darkness-Empire)',
'zfire',
)
spacing_ratio = 0.2
pos_0 = (0, 0)
pos_c = ('center', 'center')
color_blue = (255, 0, 0)
color_green = (0, 255, 0)
color_red = (0, 0, 255)
color_white = (255, 255, 255)
color_black = (0, 0, 0)
color_yellow = (0, 255, 255) # 黄色
color_cyan = (255, 255, 0) # 青色
color_magenta = (255, 0, 255) # 洋红色
color_silver = (192, 192, 192) # 银色
color_gray = (128, 128, 128) # 灰色
color_maroon = (0, 0, 128) # 褐红色
color_olive = (0, 128, 128) # 橄榄色
color_purple = (128, 0, 128) # 紫色
color_teal = (128, 128, 0) # 蓝绿色
color_navy = (128, 0, 0) # 海军蓝色
color_orange = (0, 165, 255) # 橙色
color_pink = (203, 192, 255) # 粉色
color_brown = (42, 42, 165) # 棕色
color_gold = (0, 215, 255) # 金色
color_lavender = (250, 230, 230) # 薰衣草色
color_beige = (220, 245, 245) # 米色
color_mint_green = (189, 255, 172) # 薄荷绿
color_turquoise = (208, 224, 64) # 绿松石色
color_indigo = (130, 0, 75) # 靛蓝色
color_coral = (80, 127, 255) # 珊瑚色
color_salmon = (114, 128, 250) # 鲑鱼色
color_chocolate = (30, 105, 210) # 巧克力色
color_tomato = (71, 99, 255) # 番茄色
color_violet = (226, 43, 138) # 紫罗兰色
color_goldenrod = (32, 165, 218) # 金菊色
color_fuchsia = (255, 0, 255) # 紫红色
color_crimson = (60, 20, 220) # 深红色
color_dark_orchid = (204, 50, 153) # 暗兰花色
color_slate_blue = (205, 90, 106) # 石板蓝色
color_medium_sea_green = (113, 179, 60) # 中等海洋绿色
rgba_white = (255, 255, 255, 255)
trans_white = (255, 255, 255, 127)
q_trans_white = QColor(255, 255, 255, 127)
rgba_zero = (0, 0, 0, 0)
rgba_black = (0, 0, 0, 255)
index_color = (0, 0, 255, 255)
trans_red = (255, 0, 0, 128) # 半透明红色
trans_green = (0, 255, 0, 128) # 半透明绿色
trans_purple = (128, 0, 128, 168) # 半透明紫色
trans_yellow = (255, 255, 0, 128) # 半透明黄色
trans_blue = (0, 255, 255, 128) # 半透明蓝色
trans_olive = (0, 128, 128, 128) # 半透明橄榄色
mark_px = [0, 0, 0, 1]
pad = 5
lower_bound_white = array([255 - pad, 255 - pad, 255 - pad])
upper_bound_white = array([255, 255, 255])
lower_bound_black = array([0, 0, 0])
upper_bound_black = array([pad, pad, pad])
# 定义一个字符串,包含常见的结束标点符号,不能出现在断句最前
not_start_punct = ',,.。;;::??!!”’·-》>:】【]、))…'
# 定义一个字符串,包含常见的起始标点符号,不能出现在断句最后
not_end_punct = '“‘《<【[(('
# 定义一个字符串,包含常见的结束字,不能出现在断句最前
not_start_char = '上中下内出完的地得了么呢吗嘛呗吧着个就前世里图们来'
# 定义一个字符串,包含常见的起始字,不能出现在断句最后
not_end_char = '太每帮跟另向'
valid_chars = set('.,;!?-—`~!@#$%^&*()_+={}[]|\\:;"\'<>,.?/')
punc_table_full = str.maketrans(r':;,。!?“”‘’()', r""":;,.!?""''()""")
punc_table_simple = str.maketrans(r':;,。!?()', r""":;,.!?()""")
proper_nouns = {
'Insomnia',
}
sep_word = "supercalifragilisticexpialidocious"
fine_words = [
'jai',
'jin',
'jor',
'fer',
'binnu',
]
replacements = {
'‘': "'",
'’': "'",
'“': '"',
'”': '"',
}
corrections = [
('LI', 'U'),
('X', 'Y'),
# ('P', 'D'),
# ('R', 'D'),
('ther', 'them'),
]
punct_rep_rules = {
'.': ['…', '… ', '--'],
'. ': ['…', '… ', '--'],
',': ['…', '.'],
"'": ['“', '”', '"'],
'I': [','],
'l': ['j'],
'‡': ['I'],
}
# 定义替换规则表
replace_rules = {
'…': '...',
'GET! T': 'GET IT',
'WH!': 'NH!',
'al/': 'all',
'/T': 'IT',
# '|': 'I',
# '/': '!',
}
better_abbrs = {
"YOL'RE": "YOU'RE",
"YOL'LL": "YOU'LL",
"YOL'VE": "YOU'VE",
"WE'YE": "WE'VE",
"WEIVE": "WE'VE",
"WEVE": "WE'VE",
"WHOVE": "WHO'VE",
"L'VE": "I'VE",
"L've": "I've",
"Ijust": "I just",
"IT'SA": "IT'S A",
"IT'5": "IT'S",
"IM": "I'M",
"T'm": "I'M",
"they'l": "they'll",
"THEYIRE": "THEY'RE",
"DONIT": "DON'T",
"BOUT": "ABOUT",
"ABOLIT": "ABOUT",
"JLIST": "JUST",
"SONLIVA": "SONUVA",
"WORR'ED": "WORRIED",
"SISTERIS": "SISTER'S",
"LUCIFERIS": "LUCIFER'S",
"CALLERIS": "CALLER'S",
"IE": "IF",
"I6": "IS",
"SPELIEL": "SPECIAL",
"LACIES": "LADIES",
"LBT": "LBJ",
'ALOCA': 'A LOCA',
# 'WH': 'NH',
'YOW': 'YOU',
'OKAX': 'OKAY',
'TO-': 'TO--',
'Daramit': 'Dammit',
}
# ================语气词================
interjections = ('huh', 'hn')
src_head_2c = ['Source', '目标语言']
media_type_dict = {
0: 'Comic',
1: 'Manga',
}
media_lang_dict = {
0: 'English',
1: 'Chinese Simplified',
2: 'Chinese Traditional',
3: 'Japanese',
4: 'Korean',
}
easyocr_language_map = {
'English': 'en',
'Chinese Simplified': 'ch_sim',
'Japanese': 'ja',
}
# 南非语(af),阿塞拜疆语(az),波斯尼亚语(bs),简体中文(ch_sim),繁体中文(ch_tra),捷克语(cs),威尔士语(cy),丹麦语(da),德语(de),英语(en) ),西班牙语(es),爱沙尼亚语(et),法语(fr),爱尔兰语(ga),克罗地亚语(hr),匈牙利语(hu),印度尼西亚语(id),冰岛语(is),意大利语(it),日语(ja) ),韩文(ko),库尔德(ku),拉丁语(la),立陶宛语(lt),拉脱维亚语(lv),毛利人(mi),马来语(ms),马耳他语(mt),荷兰语(nl),挪威语(否),奥克西唐(oc),波兰语(pl),葡萄牙语(pt),罗马尼亚语(ro),塞尔维亚语(拉丁语)(rs_latin),斯洛伐克语(sk)(需要重新访问),斯洛文尼亚语(sl),阿尔巴尼亚语(sq),瑞典语(sv),斯瓦希里语(sw),泰语(th),他加禄语(tl),土耳其语(tr),乌兹别克(uz),越南语(vi)
paddleocr_language_map = {
'English': 'en',
'Chinese Simplified': 'ch',
'Chinese Traditional': 'chinese_cht',
'Japanese': 'japan',
}
paddle_langs = [
'ch', 'en', 'korean', 'japan', 'chinese_cht', 'ta', 'te', 'ka', 'latin', 'arabic', 'cyrillic', 'devanagari',
]
similar_chars_map = {
'а': 'a',
'А': 'A',
'Ä': 'A',
'д': 'A',
'в': 'B',
'В': 'B',
'ь': 'b',
'Ь': 'B',
'е': 'e',
'Е': 'E',
'н': 'H',
'Н': 'H',
'Ы': 'H',
'І': 'I',
'к': 'k',
'К': 'K',
'М': 'M',
'П': 'N',
'о': 'o',
'О': 'O',
'р': 'p',
'Р': 'P',
'с': 'c',
'С': 'C',
'т': 'T',
'Т': 'T',
'и': 'u',
'И': 'U',
'х': 'x',
'Х': 'X',
'у': 'y',
'У': 'Y',
'ч': '4',
'Ч': '4',
}
special_keywords = [
'setIcon', 'icon',
'setShortcut', 'QKeySequence',
'QSettings', 'value', 'setValue',
'triggered',
'setWindowTitle', 'windowTitle',
]
language_tuples = [
# ================支持的语言================
('zh_CN', 'Simplified Chinese', '简体中文', '简体中文'),
('zh_TW', 'Traditional Chinese', '繁体中文', '繁體中文'),
('en_US', 'English', '英语', 'English'),
('ja_JP', 'Japanese', '日语', '日本語'),
('ko_KR', 'Korean', '韩语', '한국어'),
# ================未来支持的语言================
# ('es_ES', 'Spanish', '西班牙语', 'Español'),
# ('fr_FR', 'French', '法语', 'Français'),
# ('de_DE', 'German', '德语', 'Deutsch'),
# ('it_IT', 'Italian', '意大利语', 'Italiano'),
# ('pt_PT', 'Portuguese', '葡萄牙语', 'Português'),
# ('ru_RU', 'Russian', '俄语', 'Русский'),
# ('ar_AR', 'Arabic', '阿拉伯语', 'العربية'),
# ('nl_NL', 'Dutch', '荷兰语', 'Nederlands'),
# ('sv_SE', 'Swedish', '瑞典语', 'Svenska'),
# ('tr_TR', 'Turkish', '土耳其语', 'Türkçe'),
# ('pl_PL', 'Polish', '波兰语', 'Polski'),
# ('he_IL', 'Hebrew', '希伯来语', 'עברית'),
# ('da_DK', 'Danish', '丹麦语', 'Dansk'),
# ('fi_FI', 'Finnish', '芬兰语', 'Suomi'),
# ('no_NO', 'Norwegian', '挪威语', 'Norsk'),
# ('hu_HU', 'Hungarian', '匈牙利语', 'Magyar'),
# ('cs_CZ', 'Czech', '捷克语', 'Čeština'),
# ('ro_RO', 'Romanian', '罗马尼亚语', 'Română'),
# ('el_GR', 'Greek', '希腊语', 'Ελληνικά'),
# ('id_ID', 'Indonesian', '印度尼西亚语', 'Bahasa Indonesia'),
# ('th_TH', 'Thai', '泰语', 'ภาษาไทย'),
]
input_size = 1024
input_h = 1024
input_w = 1024
device = 'cpu'
scaleup = True
stride = 64
p_zh_char = re.compile(r'[^\u4e00-\u9fffA-Za-z,。、,\. ]')
p_zh = re.compile(r'[\u4e00-\u9fff]')
p_en = re.compile(r'\b[A-Za-z]+\b')
p_color = re.compile(r'([a-fA-F0-9]{6})-?(\d{0,3})', I)
p_issue_w_dot = re.compile(r'(.+?)(?!\d) (\d{2,5})', I)
p_num_chara = re.compile(r'(\d+)(\D+)')
p_comment = re.compile(r'^(\*|[①-⑨])')
p_lp_coor = re.compile(r'----------------\[(\d+)\]----------------\[(\d+\.\d+),(\d+\.\d+),(\d+)\]', I)
# 使用matplotlib的tab20颜色映射
colormap_tab20 = colormaps['tab20']
tesseract_language_options = {
'Chinese Simplified': 'chi_sim',
'Chinese Traditional': 'chi_tra',
'English': 'eng',
'Japanese': 'jpn',
'Korean': 'kor',
}
vision_language_options = {
'Chinese Simplified': 'zh-Hans',
'Chinese Traditional': 'zh-Hant',
'English': 'en',
'Japanese': 'ja',
'Korean': 'ko',
}
winocr_language_options = {
'Chinese Simplified': 'zh-CN',
'Chinese Traditional': 'zh-TW',
'English': 'en',
'Japanese': 'ja',
'Korean': 'ko',
}
baidu_language_options = {
'Chinese Simplified': 'CHN_ENG',
'Chinese Traditional': 'CHN_ENG',
'English': 'ENG',
'Japanese': 'JPN',
'Korean': 'KOR',
}
font2ps_dic = {
'时尚中黑': 'TRENDS',
'苹方': 'PingFangSC-Regular',
'手札': 'HannotateSC-W5',
'微软雅黑': 'MicrosoftYaHei',
}
# 创建一个新的 KeyboardEvent,模拟按下回车键。
# 'keydown' 是事件类型,表示一个按键被按下。
# 'key' 和 'code' 属性分别表示按下的按键和按键代码。
# 'which' 属性表示按键的字符编码。
# 'bubbles' 和 'cancelable' 属性表示事件是否可以冒泡和被取消。
press_enter_js = '''
var event = new KeyboardEvent('keydown', {
'key': 'Enter',
'code': 'Enter',
'which': 13,
'bubbles': true,
'cancelable': true
});
Array.from(document.querySelectorAll('textarea'))[0].dispatchEvent(event);
'''
as_paste = f'''
delay 0.5
tell application "System Events"
key code 9 using command down
end tell
'''
as_paste_n_enter = f'''
delay 0.5
tell application "System Events"
key code 9 using command down
delay 0.5
key code 36
end tell
'''
as_enter = f'''
delay 0.5
tell application "System Events"
key code 36
end tell
'''
as_funk = """
set soundName to "Funk"
do shell script "afplay /System/Library/Sounds/" & soundName & ".aiff"
"""
as_submarine = """
set soundName to "Submarine"
do shell script "afplay /System/Library/Sounds/" & soundName & ".aiff"
"""
as_Tingting_uploaded = f"""
say "全部上传完毕" speaking rate 180
"""
button_js_code = """
var buttons = Array.from(document.querySelectorAll('button[aria-label=\'附加文件\']'));
if (buttons.length > 0) {
buttons[0].click();
}
console.log('找到按钮数量:', buttons.length);
"""
chatGPT4o_prompt = """请分画格详细描述以下内容:
1. 描述每个画格的场景和剧情。
2. 描述每个画格中的角色的外貌、服装、情绪,和角色之间的互动和动作。
3. 描述漫画的视觉效果,例如颜色、光线、阴影等。
4. 提供每个画格中出现的文本,标注说话人,并将文本翻译成中文。"""
chatGPT4o_prompt = """请分画格详细描述以下内容:
1. 描述每个画格的场景和剧情。
2. 提供每个画格中出现的文本,标注说话人,并将文本翻译成中文。"""
chatGPT4o_prompt = """请分画格详细描述每个画格的场景和剧情,提供每个画格中出现的文本,标注说话人,并将文本翻译成中文。"""
prompt_1st_line = chatGPT4o_prompt.splitlines()[0]
chatgpt_prefix = 'https://chatgpt.com/'
gpt4o_spec_str = '这张图片是来自漫画'
# ================================基础函数区================================
def a2_base():
return
def kernel(size):
return ones((size, size), uint8)
def kernel_hw(h, w):
return ones((h, w), uint8)
kernel1 = kernel(1)
kernel2 = kernel(2)
kernel3 = kernel(3)
kernel4 = kernel(4)
kernel5 = kernel(5)
kernel6 = kernel(6)
kernel7 = kernel(7)
kernel8 = kernel(8)
kernel9 = kernel(9)
kernel10 = kernel(10)
kernel11 = kernel(11)
kernel12 = kernel(12)
kernel13 = kernel(13)
kernel14 = kernel(14)
kernel15 = kernel(15)
kernel20 = kernel(20)
kernel25 = kernel(25)
kernel30 = kernel(30)
kernel35 = kernel(35)
kernel40 = kernel(40)
kernel50 = kernel(50)
kernel60 = kernel(60)
kernalh1w5 = kernel_hw(1, 5)
kernalh1w6 = kernel_hw(1, 6)
kernalh1w7 = kernel_hw(1, 7)
kernalh1w8 = kernel_hw(1, 8)
kernalh1w9 = kernel_hw(1, 9)
kernalh1w10 = kernel_hw(1, 10)
kernalh1w11 = kernel_hw(1, 11)
kernalh1w12 = kernel_hw(1, 12)
kernalh1w13 = kernel_hw(1, 13)
kernalh1w14 = kernel_hw(1, 14)
kernalh1w15 = kernel_hw(1, 15)
kernalh1w16 = kernel_hw(1, 16)
kernalh1w17 = kernel_hw(1, 17)
kernalh1w18 = kernel_hw(1, 18)
kernalh1w19 = kernel_hw(1, 19)
kernalh1w20 = kernel_hw(1, 20)
kernalh5w1 = kernel_hw(5, 1)
kernalh8w1 = kernel_hw(8, 1)
kernalh10w1 = kernel_hw(10, 1)
CSS3_HEX_TO_NAMES = _reversedict(_CSS3_NAMES_TO_HEX)
def timer_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time()
result = func(*args, **kwargs)
elapsed_time = time() - start_time
hours, rem = divmod(elapsed_time, 3600)
minutes, seconds = divmod(rem, 60)
if hours > 0:
show_run_time = f"{int(hours)}时{int(minutes)}分{seconds:.2f}秒"
elif minutes > 0:
show_run_time = f"{int(minutes)}分{seconds:.2f}秒"
else:
show_run_time = f"{seconds:.2f}秒"
logger.debug(f"{func.__name__} took: {show_run_time}")
return result
return wrapper
def is_decimal_or_comma(s):
pattern = r'^\d*\.?\d*$|^\d*[,]?\d*$'
return bool(match(pattern, s))
def is_valid_file(file_path, suffixes):
if not file_path.is_file():
return False
if not file_path.stem.startswith(ignores):
if suffixes:
return file_path.suffix.lower() in suffixes
else:
return True
return False
def printe(e):
print(e)
logger.error(e)
print_exc()
def clamp(value, min_value, max_value):
return max(min_value, min(value, max_value))
def reduce_list(input_list):
try:
# 尝试使用dict.fromkeys方法
output_list = list(OrderedDict.fromkeys(input_list))
except TypeError:
# 如果发生TypeError(可能是因为列表包含不可哈希的对象),
# 则改用更慢的方法
output_list = []
for input in input_list:
if input not in output_list:
output_list.append(input)
return output_list
# ================创建目录================
def make_dir(file_path):
if not exists(file_path):
try:
os.makedirs(file_path)
except BaseException as e:
print(e)
# ================获取文件夹列表================
def get_dirs(rootdir):
dirs_list = []
if rootdir and rootdir.exists():
# 列出目录下的所有文件和目录
lines = os.listdir(rootdir)
for line in lines:
filepath = Path(rootdir) / line
if filepath.is_dir():
dirs_list.append(filepath)
dirs_list.sort()
return dirs_list
def get_files(rootdir, file_type=None, direct=False):
rootdir = Path(rootdir)
file_paths = []
# 获取文件类型的后缀
# 默认为所有文件
suffixes = type_dic.get(file_type, file_type)
if isinstance(suffixes, str):
suffixes = (suffixes,)
# 如果根目录存在
if rootdir and rootdir.exists():
# 只读取当前文件夹下的文件
if direct:
files = os.listdir(rootdir)
for file in files:
file_path = Path(rootdir) / file
if is_valid_file(file_path, suffixes):
file_paths.append(file_path)
# 读取所有文件
else:
for root, dirs, files in os.walk(rootdir):
for file in files:
file_path = Path(root) / file
if is_valid_file(file_path, suffixes):
file_paths.append(file_path)
# 使用natsorted()进行自然排序,
# 使列表中的字符串按照数字顺序进行排序
file_paths = natsorted(file_paths)
return file_paths
def filter_items(old_list, prefix=pre_tuple, infix=scan_tuple, suffix=pic_tuple, item_attr='stem'):
"""
这个函数用于过滤一个列表,根据指定的前缀、中缀和后缀来排除不需要的元素。
可以根据文件的全名或者文件名(不包括扩展名)来进行过滤。
:param old_list: 原始列表。
:param prefix: 要排除的前缀元组。
:param infix: 要排除的中间文本元组。
:param suffix: 要排除的后缀元组。
:param item_attr: 'name' 或 'stem',基于文件全名或仅基于文件主名进行过滤。
:return: 过滤后的新列表,不包含任何匹配前缀、中缀或后缀的元素。
"""
# 定义一个内部函数来判断一个元素是否应该被排除
def is_excluded(item):
# 检查元素是否以任何给定的前缀开始