-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathocr_tool.py
1794 lines (1486 loc) · 67.3 KB
/
ocr_tool.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 __future__ import annotations
import time
import imagehash # type: ignore
# from tesserocr import PyTessBaseAPI, PSM, OEM # type: ignore
import contextlib
import signal
from typing import Union
import cv2 # type: ignore
import appdirs
import copy
import io
import itertools
import os
import pathlib
import platform
import re
import shutil
import math
import sys
from collections import deque
from shutil import which
from tempfile import NamedTemporaryFile
from typing import Any, Optional, cast
import subprocess
import numpy
import pyperclip # type: ignore
import pytesseract # type: ignore
import soundcard # type: ignore
import tomli
import tomli_w
import typer
from appdirs import user_config_dir
from easyprocess import EasyProcess # type: ignore
from loguru import logger
from PIL import Image, ImageOps, ImageGrab
from PIL.ImageQt import ImageQt
from pynput import keyboard # type: ignore
from PySide6.QtCore import QBuffer, QObject, QRect, Qt, QThread, Signal, SignalInstance, QMimeData, QUrl, Slot
from PySide6.QtGui import (
QAction,
QColor,
QCursor,
QIcon,
QKeySequence,
QMouseEvent,
QPainter,
QPainterPath,
QPaintEvent,
QPixmap,
)
from PySide6.QtWidgets import (
QApplication,
QCheckBox,
QComboBox,
QDialog,
QHBoxLayout,
QLabel,
QLineEdit,
QMenu,
QProgressBar,
QPushButton,
QScrollArea,
QSlider,
QSpinBox,
QStyle,
QSystemTrayIcon,
QVBoxLayout,
QWidget,
)
from scipy.io import wavfile # type: ignore
ffmpeg_command: Optional[str] = ""
tesseract_command: Optional[str] = ""
def resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
base_path = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path)
if platform.system() == "Windows":
if os.path.isfile(resource_path("ffmpeg.exe")):
ffmpeg_command = resource_path("ffmpeg.exe")
if os.path.isfile(resource_path("./tesseract/tesseract.exe")):
tesseract_command = resource_path("./tesseract/tesseract.exe")
elif os.path.isfile(resource_path("./Game2Text/resources/bin/win/tesseract/tesseract.exe")):
tesseract_command = resource_path("./Game2Text/resources/bin/win/tesseract/tesseract.exe")
if not tesseract_command:
tesseract_command = which("tesseract.exe")
elif os.path.isfile(resource_path("./ffmpeg")):
ffmpeg_command = resource_path("./ffmpeg")
if not tesseract_command:
tesseract_command = which("tesseract.exe")
if not ffmpeg_command:
ffmpeg_command = which("ffmpeg")
class ProgressWindow(QDialog):
def __init__(self):
super().__init__()
self.setWindowTitle("Migaku Download Window")
self.setWindowFlags(Qt.WindowStaysOnTopHint) # type: ignore
self.setWindowModality(Qt.WindowModal)
self.setBaseSize(400, 100)
self.downlods_dict = {}
self.download_list_layout = QVBoxLayout()
self.setLayout(self.download_list_layout)
def add_download_item(self, item: str):
self.downlods_dict[item] = QProgressBar()
self.downlods_dict[item].setValue(0)
self.download_list_layout.addWidget(QLabel(item))
self.download_list_layout.addWidget(self.downlods_dict[item])
def update_progress(self, item: str, value: int):
self.downlods_dict[item].setValue(value)
class ProgramManager:
BASE_DOWNLOAD_URI = "https://migaku-public-data.s3.filebase.com/"
def __init__(self, program_name: str):
self.program_path = None
self.program_name = program_name
self.download_uri = self.BASE_DOWNLOAD_URI + program_name + "/"
self.program_executable_name = f"{program_name}.exe" if platform.system() == "Windows" else program_name
self.migaku_shared_path = appdirs.user_data_dir("MigakuShared", "Migaku")
self.shared_user_program_name = os.path.join(self.migaku_shared_path, self.program_executable_name)
self.make_available()
def make_available(self):
# Attempt global installation
if self.check_set_program_path(self.program_executable_name):
return
if self.check_set_program_path(self.shared_user_program_name):
return
self.start_download()
def start_download(self):
class DownloadThread(QThread):
def __init__(self, target=None, parent=None):
super().__init__(parent)
self.target = target
def run(self):
self.target()
aqt.mw.progress.start(label=f"Downloading ffmpeg and ffprobe", max=100)
self.program_path = self.migaku_shared_path + "/" + self.program_executable_name
print(self.program_path)
download_thread = DownloadThread(self._download, self.parent())
download_thread.finished.connect(self.finished_download)
download_thread.start()
def check_set_program_path(self, path):
if not path:
return False
try:
subprocess.call([path, "-version"])
self.program_path = path
return True
except OSError:
return False
selected_mic = None
class Rectangle:
def __init__(self, x1=0.0, y1=0.0, x2=0.0, y2=0.0):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def __bool__(self):
return bool(self.x2 or self.y1 or self.x2 or self.y2)
def get_width(self) -> int:
return self.x2 - self.x1
def get_height(self) -> int:
return self.y2 - self.y1
# from: https://stackoverflow.com/a/7205107
def merge(a, b, path=None):
"merges b into a"
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge(a[key], b[key], path + [str(key)])
else:
a[key] = b[key]
return a
class Configuration:
def __init__(self) -> None:
default_settings = {
"hotkeys": {
"single_screenshot_hotkey": "<ctrl>+<alt>+Q",
"persistent_window_hotkey": "<ctrl>+<alt>+W",
"persistent_screenshot_hotkey": "<ctrl>+<alt>+E",
"stop_recording_hotkey": "<ctrl>+<alt>+S",
},
"enable_global_hotkeys": False,
"texthooker_mode": False,
"enable_recording": False,
"auto_save_recording": False,
"recording_seconds": 8,
"enable_srs_image": True,
"ocr_settings": {
"upscale_amount": 3,
"enable_thresholding": True,
"thresholding_value": 130,
"smart_image_inversion": True,
"add_border": True,
},
}
self.config_dict: dict[str, Any]
self.config_dict = self.load_config(default_settings)
def load_config(self, default_settings) -> dict[str, Any]:
config_dir = user_config_dir("migaku-ocr")
pathlib.Path(config_dir).mkdir(parents=True, exist_ok=True)
config_file = os.path.join(config_dir, "config.toml")
config_dict = default_settings
try:
with open(config_file, "r") as f:
config_text = f.read()
# merge default config and user config, user config has precedence
config_dict = cast(dict, merge(tomli.loads(config_text), config_dict))
logger.debug(config_dict)
except FileNotFoundError:
logger.info("no config file exists, loading default values")
return config_dict
def save_config(self):
config_dir = user_config_dir("migaku-ocr")
pathlib.Path(config_dir).mkdir(parents=True, exist_ok=True)
config_file = os.path.join(config_dir, "config.toml")
with open(config_file, "wb") as f:
tomli_w.dump(self.config_dict, f)
valid_keys = {
Qt.Key_0: "0",
Qt.Key_1: "1",
Qt.Key_2: "2",
Qt.Key_3: "3",
Qt.Key_4: "4",
Qt.Key_5: "5",
Qt.Key_6: "6",
Qt.Key_7: "7",
Qt.Key_8: "8",
Qt.Key_9: "9",
Qt.Key_Escape: "ESCAPE",
Qt.Key_Backspace: "BACKSPACE",
Qt.Key_Return: "RETURN",
Qt.Key_Enter: "ENTER",
Qt.Key_Insert: "INS",
Qt.Key_Delete: "DEL",
Qt.Key_Pause: "PAUSE",
Qt.Key_Print: "PRINT",
Qt.Key_Home: "HOME",
Qt.Key_End: "END",
Qt.Key_Left: "LEFT",
Qt.Key_Up: "UP",
Qt.Key_Right: "RIGHT",
Qt.Key_Down: "DOWN",
Qt.Key_PageUp: "PGUP",
Qt.Key_PageDown: "PGDOWN",
Qt.Key_Comma: ",",
Qt.Key_Underscore: "_",
Qt.Key_Minus: "-",
Qt.Key_Period: ".",
Qt.Key_Slash: "/",
Qt.Key_Colon: ":",
Qt.Key_Semicolon: ";",
Qt.Key_F1: "F1",
Qt.Key_F2: "F2",
Qt.Key_F3: "F3",
Qt.Key_F4: "F4",
Qt.Key_F5: "F5",
Qt.Key_F6: "F6",
Qt.Key_F7: "F7",
Qt.Key_F8: "F8",
Qt.Key_F9: "F9",
Qt.Key_F10: "F10",
Qt.Key_F11: "F11",
Qt.Key_F12: "F12",
Qt.Key_A: "A",
Qt.Key_B: "B",
Qt.Key_C: "C",
Qt.Key_D: "D",
Qt.Key_E: "E",
Qt.Key_F: "F",
Qt.Key_G: "G",
Qt.Key_H: "H",
Qt.Key_I: "I",
Qt.Key_J: "J",
Qt.Key_K: "K",
Qt.Key_L: "L",
Qt.Key_M: "M",
Qt.Key_N: "N",
Qt.Key_O: "O",
Qt.Key_P: "P",
Qt.Key_Q: "Q",
Qt.Key_R: "R",
Qt.Key_S: "S",
Qt.Key_T: "T",
Qt.Key_U: "U",
Qt.Key_V: "V",
Qt.Key_W: "W",
Qt.Key_X: "X",
Qt.Key_Y: "Y",
Qt.Key_Z: "Z",
}
class MainWindow(QWidget):
def __init__(
self,
config: Configuration,
master_object: MasterObject,
srs_screenshot: SRSScreenshot,
audio_worker: AudioWorker,
main_hotkey_qobject: MainHotkeyQObject,
):
super().__init__()
self.setWindowTitle("Migaku OCR")
self.setWindowFlags(Qt.Dialog) # type: ignore
self.config = config
self.srs_screenshot = srs_screenshot
self.audio_worker = audio_worker
self.main_hotkey_qobject = main_hotkey_qobject
self.master_object = master_object
self.ocr_settings_window: Optional[OCRSettingsWindow] = None
processed_image = master_object.processed_image
selection_ocr_button = QPushButton("Selection OCR")
selection_ocr_button.clicked.connect(master_object.take_single_screenshot) # type: ignore
show_persistent_window_button = QPushButton("Show Persistent Window")
show_persistent_window_button.clicked.connect(master_object.show_persistent_screenshot_window) # type: ignore
persistent_window_container = QWidget()
persistent_window_layout = QHBoxLayout()
persistent_window_layout.setContentsMargins(0, 0, 0, 0)
persistent_window_container.setLayout(persistent_window_layout)
persistent_window_ocr_button = QPushButton("Persistent Window OCR")
persistent_window_ocr_button.clicked.connect(master_object.take_screenshot_from_persistent_window) # type: ignore
persistent_window_layout.addWidget(persistent_window_ocr_button)
persistent_window_auto_ocr_button = QPushButton("Auto OCR")
persistent_window_auto_ocr_button.clicked.connect(self.toggle_auto_ocr) # type: ignore
persistent_window_layout.addWidget(persistent_window_auto_ocr_button)
hotkey_config_button = QPushButton("Configure Hotkeys")
hotkey_config_button.clicked.connect(self.show_hotkey_config) # type: ignore
ocr_settings_button = QPushButton("OCR Settings")
ocr_settings_button.clicked.connect(self.show_ocr_settings_window) # type: ignore
self.ocr_text_linedit_current = QLineEdit("This will contain the latest ocr result")
self.ocr_text_linedit_last = QLineEdit("This will contain the previous ocr result")
thresholding_widget = QWidget()
thresholding_layout = QHBoxLayout()
thresholding_layout.setContentsMargins(0, 0, 0, 0)
thresholding_widget.setLayout(thresholding_layout)
def toggle_thresholding(state):
if state == Qt.Checked:
self.config.config_dict["ocr_settings"]["enable_thresholding"] = True
self.thresholding_slider.setEnabled(True)
else:
self.config.config_dict["ocr_settings"]["enable_thresholding"] = False
self.thresholding_slider.setEnabled(False)
master_object.ocr.start_ocr_in_thread(master_object.unprocessed_image)
self.enable_thresholding_checkbox = QCheckBox("Enable Thresholding")
self.enable_thresholding_checkbox.setChecked(config.config_dict["ocr_settings"]["enable_thresholding"])
self.enable_thresholding_checkbox.stateChanged.connect(toggle_thresholding) # type: ignore
thresholding_layout.addWidget(self.enable_thresholding_checkbox)
def change_thresholding_value():
self.config.config_dict["ocr_settings"]["thresholding_value"] = self.thresholding_slider.value()
print(f"thresholding: {self.thresholding_slider.value()}")
print(f"image: {master_object.unprocessed_image}")
self.master_object.ocr.start_ocr_in_thread(master_object.unprocessed_image)
self.thresholding_slider = QSlider(Qt.Horizontal)
self.thresholding_slider.setRange(0, 255)
self.thresholding_slider.setPageStep(1)
self.thresholding_slider.setValue(config.config_dict["ocr_settings"]["thresholding_value"])
self.thresholding_slider.sliderReleased.connect(change_thresholding_value) # type: ignore
self.thresholding_slider.setEnabled(config.config_dict["ocr_settings"]["enable_thresholding"])
processed_image = master_object.processed_image
self.image_preview = ImagePreview(processed_image)
srs_screenshot_widget1 = QWidget()
srs_screenshot_layout1 = QHBoxLayout()
srs_screenshot_layout1.setContentsMargins(0, 0, 0, 0)
srs_screenshot_widget1.setLayout(srs_screenshot_layout1)
srs_screenshot_checkbox = QCheckBox("SRS Screenshot 🛈")
srs_screenshot_checkbox.setChecked(config.config_dict["enable_srs_image"])
srs_screenshot_checkbox.setToolTip("A screenshot will be taken that can be added to your SRS cards")
def srs_screenshot_checkbox_toggl(state):
self.config.config_dict["enable_srs_image"] = state == Qt.Checked
srs_screenshot_checkbox.stateChanged.connect(srs_screenshot_checkbox_toggl) # type: ignore
self.texthooker_mode_checkbox = QCheckBox("Texthooker mode 🛈")
self.texthooker_mode_checkbox.setChecked(config.config_dict["texthooker_mode"])
def texthooker_mode_checkbox_toggl(state):
self.config.config_dict["texthooker_mode"] = state == Qt.Checked
if state == Qt.Checked:
self.srs_screenshot.start_texthooker_mode()
self.texthooker_mode_checkbox.stateChanged.connect(texthooker_mode_checkbox_toggl) # type: ignore
self.texthooker_mode_checkbox.setToolTip("Screenshot is taken automatically on clipboard change")
srs_screenshot_widget2 = QWidget()
srs_screenshot_layout2 = QHBoxLayout()
srs_screenshot_layout2.setContentsMargins(0, 0, 0, 0)
srs_screenshot_widget2.setLayout(srs_screenshot_layout2)
manual_srs_screenshot_button = QPushButton("Manual SRS Screenshot")
manual_srs_screenshot_button.clicked.connect(self.srs_screenshot.take_srs_screenshot) # type: ignore
srs_screenshot_layout2.addWidget(manual_srs_screenshot_button)
def copy_screenshot_to_clipboard():
if self.srs_screenshot.image:
im = ImageQt(self.srs_screenshot.image).copy()
print(type(im))
QApplication.clipboard().setImage(im)
srs_screenshot_to_clipboard_button = QPushButton("Copy Screenshot to Clipboard")
srs_screenshot_to_clipboard_button.clicked.connect(copy_screenshot_to_clipboard) # type: ignore
srs_screenshot_layout2.addWidget(srs_screenshot_to_clipboard_button)
srs_screenshot_layout1.addWidget(srs_screenshot_checkbox)
srs_screenshot_layout1.addWidget(self.texthooker_mode_checkbox)
srs_image_location_button = QPushButton("Set Screenshot Location for SRS Image")
srs_image_location_button.clicked.connect(srs_screenshot.set_srs_image_location) # type: ignore
self.recording_checkbox = QCheckBox("Enable Recording")
self.recording_checkbox.setChecked(config.config_dict["enable_recording"])
self.recording_checkbox.stateChanged.connect(self.recording_checkbox_toggl) # type: ignore
self.auto_save_recording_checkbox = QCheckBox("Save Recording on OCR")
self.auto_save_recording_checkbox.setChecked(config.config_dict["auto_save_recording"])
self.auto_save_recording_checkbox.stateChanged.connect(self.auto_save_recording_checkbox_toggl) # type: ignore
save_icon = QApplication.style().standardIcon(QStyle.SP_DialogSaveButton)
self.audio_save_button = QPushButton("Save Recording")
self.audio_save_button.setIcon(save_icon)
self.audio_save_button.clicked.connect(audio_worker.save_audio_and_restart_recording) # type: ignore
self.audio_save_button.setEnabled(config.config_dict["enable_recording"])
self.audio_clipboard_button = QPushButton("Copy last recording to clipboard")
self.audio_clipboard_button.clicked.connect(audio_worker.save_last_file_to_clipboard) # type: ignore
self.audio_clipboard_button.setEnabled(config.config_dict["enable_recording"])
recording_layout1 = QHBoxLayout()
recording_layout1.setContentsMargins(0, 0, 0, 0)
recording_layout1.addWidget(self.recording_checkbox)
recording_layout1.addWidget(self.auto_save_recording_checkbox)
recording_widget1 = QWidget()
recording_widget1.setLayout(recording_layout1)
recording_layout2 = QHBoxLayout()
recording_layout2.setContentsMargins(0, 0, 0, 0)
recording_layout2.addWidget(self.audio_save_button)
recording_layout2.addWidget(self.audio_clipboard_button)
recording_widget2 = QWidget()
recording_widget2.setLayout(recording_layout2)
recording_seconds_label = QLabel("Seconds to continuously record:")
self.recording_seconds_spinbox = QSpinBox()
self.recording_seconds_spinbox.setValue(config.config_dict["recording_seconds"])
self.recording_seconds_spinbox.setMinimum(1)
self.recording_seconds_spinbox.valueChanged.connect(self.spinbox_valuechange) # type: ignore
recording_seconds_layout = QHBoxLayout()
recording_seconds_layout.setContentsMargins(0, 0, 0, 0)
recording_seconds_layout.addWidget(recording_seconds_label)
recording_seconds_layout.addWidget(self.recording_seconds_spinbox)
recording_seconds_widget = QWidget()
recording_seconds_widget.setLayout(recording_seconds_layout)
try:
self.mics = soundcard.all_microphones(include_loopback=True)
except RuntimeError:
self.mics = []
mic_names = [mic.name for mic in self.mics]
self.mic_combobox = QComboBox()
self.mic_combobox.addItems(mic_names)
loopback = get_loopback_device(self.mics)
if loopback:
self.mic_combobox.setCurrentText(loopback.name)
global selected_mic
try:
selected_mic = next(x for x in self.mics if x.name == self.mic_combobox.currentText())
except (RuntimeError, StopIteration):
selected_mic = None
self.mic_combobox.activated.connect(self.mic_selection_change) # type: ignore
if config.config_dict["enable_recording"]:
self.audio_worker.save_audio_and_restart_recording()
self.audio_peak_progressbar = QProgressBar()
self.audio_peak_progressbar.setRange(0, 1000)
self.audio_peak_progressbar.setTextVisible(False)
progressbar_style = """
min-height: 10px;
max-height: 10px;
"""
self.audio_peak_progressbar.setStyleSheet(progressbar_style)
self.update_audio_progressbar_in_thread()
save_settings_button = QPushButton("Save Settings")
save_settings_button.clicked.connect(config.save_config) # type: ignore
layout = QVBoxLayout()
layout.addWidget(selection_ocr_button)
layout.addWidget(show_persistent_window_button)
layout.addWidget(persistent_window_container)
layout.addWidget(ocr_settings_button)
layout.addWidget(self.image_preview)
layout.addWidget(self.ocr_text_linedit_current)
layout.addWidget(self.ocr_text_linedit_last)
layout.addWidget(thresholding_widget)
layout.addWidget(self.thresholding_slider)
layout.addWidget(hotkey_config_button)
layout.addWidget(srs_screenshot_widget1)
layout.addWidget(srs_screenshot_widget2)
layout.addWidget(srs_image_location_button)
layout.addWidget(recording_widget1)
layout.addWidget(recording_widget2)
layout.addWidget(recording_seconds_widget)
layout.addWidget(self.mic_combobox)
layout.addWidget(self.audio_peak_progressbar)
layout.addWidget(save_settings_button)
self.setLayout(layout)
def toggle_auto_ocr(self):
if self.master_object.auto_ocr_thread:
self.master_object.auto_ocr_thread.stop_signal = True
self.master_object.auto_ocr_thread.wait()
else:
self.master_object.start_auto_ocr_in_thread()
def update_linedit_text(self, text: str):
self.ocr_text_linedit_last.setText(self.ocr_text_linedit_current.text())
self.ocr_text_linedit_current.setText(text)
def refresh_preview_image(self, image):
self.image_preview.setImage(image)
def show_ocr_settings_window(self):
self.ocr_settings_window = OCRSettingsWindow(self.master_object)
self.ocr_settings_window.show()
def show_hotkey_config(self):
# global, so it doesn't get garbage collected
self.hotkey_window = HotKeySettingsWindow(self.config, self.main_hotkey_qobject)
self.hotkey_window.show()
def update_audio_progressbar_in_thread(self):
self.update_audio_progress_thread = MainWindow.UpdateAudioProgressThread()
self.update_audio_progress_thread.volume_signal.connect(self.update_volume_progressbar)
self.update_audio_progress_thread.start()
def update_volume_progressbar(self, volume: int):
self.audio_peak_progressbar.setValue(volume)
def auto_save_recording_checkbox_toggl(self, state):
self.config.config_dict["auto_save_recording"] = state == Qt.Checked
def recording_checkbox_toggl(self, state):
self.config.config_dict["enable_recording"] = state == Qt.Checked
if state == Qt.Checked:
self.audio_worker.save_audio_and_restart_recording()
self.audio_save_button.setEnabled(True)
self.audio_clipboard_button.setEnabled(True)
else:
self.audio_worker.stop_recording()
self.audio_save_button.setEnabled(False)
self.audio_clipboard_button.setEnabled(False)
def spinbox_valuechange(self):
self.config.config_dict["recording_seconds"] = self.recording_seconds_spinbox.value()
def mic_selection_change(self):
global selected_mic
mic_name = self.mic_combobox.currentText()
selected_mic = next(x for x in self.mics if x.name == mic_name)
self.update_audio_progress_thread.stop()
self.update_audio_progress_thread.wait()
self.update_audio_progressbar_in_thread()
class UpdateAudioProgressThread(QThread):
volume_signal = cast(SignalInstance, Signal(int))
def __init__(self):
QThread.__init__(self)
self.stop_signal = False
def run(self):
samplerate = 48000
global selected_mic
loopback = selected_mic
if not loopback:
return
with loopback.recorder(samplerate=samplerate) as rec:
while not self.stop_signal:
data: numpy.ndarray
data = rec.record()
added_data = [abs(sum(instance)) for instance in data]
volume = int(math.ceil(numpy.mean(added_data) * 1000)) # type: ignore
self.volume_signal.emit(volume)
def stop(self):
self.stop_signal = True
class ImagePreview(QLabel):
def __init__(self, image=None):
super().__init__()
self.image = image
self.setMinimumSize(350, 170)
self._update_pixmap()
def _update_pixmap(self):
if self.image:
im = ImageQt(self.image).copy()
pixmap = QPixmap.fromImage(im).scaled(self.width(), self.height(), Qt.KeepAspectRatio)
self.setPixmap(pixmap)
else:
self.setText("This will show a preview of your screenshots.")
def setImage(self, image):
self.image = image
self._update_pixmap()
def resizeEvent(self, _):
self._update_pixmap()
class SRSScreenshot:
def __init__(self, app, config: Configuration):
self.app = app
self.config = config
self.srs_image_location = Rectangle()
self.image: Optional[Image.Image] = None
def set_srs_image_location(self):
QApplication.setOverrideCursor(Qt.CrossCursor)
selection_window = SelectorWidget(self.app)
selection_window.show()
selection_window.activateWindow()
if selection_window.exec() == QDialog.Accepted and selection_window.coordinates:
self.srs_image_location.x1 = selection_window.coordinates.x1
self.srs_image_location.y1 = selection_window.coordinates.y1
self.srs_image_location.x2 = selection_window.coordinates.x2
self.srs_image_location.y2 = selection_window.coordinates.y2
QApplication.restoreOverrideCursor()
def take_srs_screenshot(self):
if not self.config.config_dict["enable_srs_image"]:
# exit function if srs_image is disabled
return
if (
not self.srs_image_location.x1
and not self.srs_image_location.y1
and not self.srs_image_location.x2
and not self.srs_image_location.y2
):
screen = QApplication.primaryScreen()
size = screen.size()
self.srs_image_location.x2 = size.width()
self.srs_image_location.y2 = size.height()
if image := ImageGrab.grab(
bbox=(
int(self.srs_image_location.x1),
int(self.srs_image_location.y1),
int(self.srs_image_location.x2),
int(self.srs_image_location.y2),
),
):
MAX_SIZE = (848, 480)
image.thumbnail(MAX_SIZE)
with NamedTemporaryFile(suffix=".webp", delete=False) as temp_webp_file:
image.save(temp_webp_file.name, optimize=True, quality=75)
self.image = Image.open(temp_webp_file.name)
shutil.copyfile(temp_webp_file.name, "test.webp")
def trigger_srs_screenshot_on_clipboard_change(self):
while True:
pyperclip.waitForNewPaste()
if not self.config.config_dict["texthooker_mode"]:
break
self.take_srs_screenshot()
def take_srs_screenshot_in_thread(self):
with contextlib.suppress(AttributeError):
if self.srs_screenshot_thread:
self.srs_screenshot_thread.wait()
self.srs_screenshot_thread = SRSScreenshot.SRSScreenshotThread(self, self.config)
self.srs_screenshot_thread.start()
class SRSScreenshotThread(QThread):
def __init__(self, srs_screenshot: SRSScreenshot, config: Configuration):
QThread.__init__(self)
self.config = config
self.srs_screenshot = srs_screenshot
def run(self):
self.srs_screenshot.take_srs_screenshot()
def start_texthooker_mode(self):
self.texthooker_mode_thread = SRSScreenshot.TexthookerModeThread(self, self.config)
self.texthooker_mode_thread.start()
class TexthookerModeThread(QThread):
def __init__(self, srs_screenshot: SRSScreenshot, config: Configuration):
QThread.__init__(self)
self.srs_screenshot = srs_screenshot
self.config = config
def run(self):
self.srs_screenshot.trigger_srs_screenshot_on_clipboard_change()
class OCRSettingsWindow(QWidget):
def __init__(self, master_object: MasterObject):
super().__init__()
self.master_object = master_object
self.config = self.master_object.config
self.setWindowTitle("Migaku OCR Settings")
self.setWindowFlags(Qt.Dialog) # type: ignore
self.unprocessed_image_label = QLabel()
self.processed_image_label = QLabel()
unprocessed_image = master_object.unprocessed_image
processed_image = master_object.processed_image
layout = QHBoxLayout()
left_side_layout = QVBoxLayout()
right_side_layout = QVBoxLayout()
if unprocessed_image:
im = ImageQt(unprocessed_image).copy()
pixmap = QPixmap.fromImage(im)
self.unprocessed_image_label.setPixmap(pixmap)
else:
self.unprocessed_image_label.setText("No screenshot taken yet...")
if processed_image:
im = ImageQt(processed_image).copy()
pixmap = QPixmap.fromImage(im)
self.processed_image_label.setPixmap(pixmap)
else:
self.processed_image_label.setText("...therefore there's nothing to process.")
self.ocr_text_label = QLabel("This will show the resulting OCR text.")
unprocessed_image_layout = QHBoxLayout()
unprocessed_image_scrollarea = QScrollArea()
unprocessed_image_scrollarea.setLayout(unprocessed_image_layout)
unprocessed_image_scrollarea.setWidgetResizable(True)
unprocessed_image_layout.addWidget(self.unprocessed_image_label)
processed_image_layout = QHBoxLayout()
processed_image_scrollarea = QScrollArea()
processed_image_scrollarea.setLayout(processed_image_layout)
processed_image_scrollarea.setWidgetResizable(True)
processed_image_layout.addWidget(self.processed_image_label)
left_side_layout.addWidget(unprocessed_image_scrollarea)
left_side_layout.addWidget(processed_image_scrollarea)
left_side_layout.addWidget(self.ocr_text_label)
left_side_layout.addStretch()
left_side_widget = QWidget()
left_side_widget.setLayout(left_side_layout)
layout.addWidget(left_side_widget)
def change_upscale_value(state):
self.config.config_dict["ocr_settings"]["upscale_amount"] = state
master_object.ocr.start_ocr_in_thread(unprocessed_image)
upscale_spinbox = QSpinBox()
upscale_spinbox.setValue(self.config.config_dict["ocr_settings"]["upscale_amount"])
upscale_spinbox.setMinimum(1)
upscale_spinbox.setMaximum(6)
upscale_spinbox.valueChanged.connect(change_upscale_value) # type: ignore
right_side_layout.addWidget(upscale_spinbox)
right_side_widget = QWidget()
right_side_widget.setLayout(right_side_layout)
layout.addWidget(right_side_widget)
self.setLayout(layout)
def refresh_unprocessed_image(self, image):
im = ImageQt(image).copy()
pixmap = QPixmap.fromImage(im)
self.unprocessed_image_label.setPixmap(pixmap)
def refresh_processed_image(self, image):
im = ImageQt(image).copy()
pixmap = QPixmap.fromImage(im)
self.processed_image_label.setPixmap(pixmap)
def refresh_ocr_text(self, text):
self.ocr_text_label.setText(text)
class HotKeySettingsWindow(QWidget):
def __init__(self, config: Configuration, main_hotkey_qobject):
super().__init__()
self.main_hotkey_qobject = main_hotkey_qobject
self.config = config
self.main_hotkey_qobject.stop()
self.original_config = copy.deepcopy(config.config_dict)
self.setWindowTitle("Migaku OCR Hotkey Settings")
self.setWindowFlags(Qt.Dialog) # type: ignore
layout = QVBoxLayout()
self.hotkeyCheckBox = QCheckBox("Enable Global Hotkeys")
self.hotkeyCheckBox.setChecked(config.config_dict["enable_global_hotkeys"])
self.hotkeyCheckBox.stateChanged.connect(self.checkbox_toggl) # type: ignore
layout.addWidget(self.hotkeyCheckBox)
single_screenshot_hotkey_field = HotKeyField(config, "single_screenshot_hotkey", "Single screenshot OCR")
layout.addWidget(single_screenshot_hotkey_field)
persistent_window_hotkey_field = HotKeyField(config, "persistent_window_hotkey", "Spawn persistent window")
layout.addWidget(persistent_window_hotkey_field)
persistent_screenshot_hotkey_field = HotKeyField(
config, "persistent_screenshot_hotkey", "Persistent window OCR"
)
layout.addWidget(persistent_screenshot_hotkey_field)
stop_recording_hotkey_field = HotKeyField(config, "stop_recording_hotkey", "Stop recording")
layout.addWidget(stop_recording_hotkey_field)
button_layout = QHBoxLayout()
layout.addLayout(button_layout)
self.okButton = QPushButton("OK")
self.okButton.clicked.connect(self.save_close) # type: ignore
button_layout.addWidget(self.okButton)
self.cancelButton = QPushButton("Cancel")
self.cancelButton.clicked.connect(self.cancel_close) # type: ignore
button_layout.addWidget(self.cancelButton)
self.setLayout(layout)
def checkbox_toggl(self, state):
self.config.config_dict["enable_global_hotkeys"] = state == Qt.Checked
def save_close(self):
self.config.save_config()
self.close()
def cancel_close(self):
self.config.config_dict = self.original_config
self.close()
def closeEvent(self, *args, **kwargs):
super().closeEvent(*args, **kwargs)
self.main_hotkey_qobject.start()
class HotKeyField(QWidget):
def __init__(self, config: Configuration, hotkey_functionality: str, hotkey_name: str):
super().__init__()
hotkey_label = QLabel(hotkey_name)
layout = QHBoxLayout()
layout.addWidget(hotkey_label)
self.keyEdit = KeySequenceLineEdit(config, hotkey_functionality)
layout.addWidget(self.keyEdit)
self.clearButton = QPushButton("Clear")
self.clearButton.clicked.connect(self.keyEdit.clear) # type: ignore
layout.addWidget(self.clearButton)
self.setLayout(layout)
class KeySequenceLineEdit(QLineEdit):
def __init__(self, config: Configuration, hotkey_functionality: str):
super().__init__()
self.config = config
self.modifiers: Qt.KeyboardModifiers = Qt.NoModifier # type: ignore
self.key: Qt.Key = Qt.Key_unknown
self.keysequence = QKeySequence()
self.hotkey_functionality = hotkey_functionality
self.setText(self.getQtText(config.config_dict["hotkeys"][self.hotkey_functionality]))
def clear(self):
self.setText("")
self.config.config_dict["hotkeys"][self.hotkey_functionality] = ""
def keyPressEvent(self, event):
super().keyPressEvent(event)
self.modifiers = event.modifiers()
self.key = event.key()
self.updateKeySequence()
self.updateConfig()
def updateConfig(self):
self.config.config_dict["hotkeys"][self.hotkey_functionality] = self.getPynputText()
def updateKeySequence(self):
if self.key not in valid_keys:
self.keysequence = QKeySequence(self.modifiers)
else:
self.keysequence = QKeySequence(self.modifiers | self.key) # type: ignore
self.updateText()
def updateText(self):
self.setText(self.keysequence.toString())
def getPynputText(self):
def upper_repl(match):
return match.group(1).upper()
qt_string: str = self.keysequence.toString()
tmp = qt_string.lower()
tmp = re.sub(r"shift\+(\w)", upper_repl, tmp)
tmp = re.sub(r"(f\d{1,2})", r"<\1>", tmp)
tmp = tmp.replace("ctrl", "<ctrl>")
tmp = tmp.replace("alt", "<alt>")
tmp = tmp.replace("meta", "<cmd>")
tmp = tmp.replace("return", "<enter>")
tmp = tmp.replace("backspace", "<backspace>")
tmp = tmp.replace("pgdown", "page_down")
tmp = tmp.replace("pgup", "page_up")
return tmp
def getQtText(self, pynputText):
tmp = re.sub(r"([A-Z])", lambda match: f"Shift+{match.group(1).lower()}", pynputText)
tmp = re.sub(r"<f(\d{1,2})>", r"F\1", tmp)
tmp = re.sub(r"([a-z])$", lambda match: match.group(1).upper(), tmp)
tmp = tmp.replace("<ctrl>", "Ctrl")
tmp = tmp.replace("<alt>", "Alt")
tmp = tmp.replace("<cmd>", "Meta")
return tmp
class PersistentWindow(QWidget):
def __init__(self, master_object: MasterObject, x=0, y=0, w=400, h=200):
super().__init__()
self.setWindowTitle("Migaku OCR")
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Dialog) # type: ignore
self.is_resizing = False
self.is_moving = False
self.setMouseTracking(True)
self.original_cursor_x = 0
self.original_cursor_y = 0
self.original_window_x = 0