forked from devmaxxing/videocr-PaddleOCR
-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathVideOCR.py
More file actions
4009 lines (3274 loc) · 173 KB
/
VideOCR.py
File metadata and controls
4009 lines (3274 loc) · 173 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
# Compilation instructions
# nuitka-project: --standalone
# nuitka-project: --enable-plugin=tk-inter
# nuitka-project: --windows-console-mode=disable
# nuitka-project: --include-windows-runtime-dlls=yes
# nuitka-project: --include-data-files=Installer/*.ico=VideOCR.ico
# nuitka-project: --include-data-files=Installer/*.png=VideOCR.png
# nuitka-project: --include-data-dir=languages=languages
# Windows-specific metadata for the executable
# nuitka-project-if: {OS} == "Windows":
# nuitka-project-set: APP_VERSION = __import__("_version").__version__
# nuitka-project: --file-description="VideOCR"
# nuitka-project: --file-version={APP_VERSION}
# nuitka-project: --product-name="VideOCR-GUI"
# nuitka-project: --product-version={APP_VERSION}
# nuitka-project: --copyright="timminator"
# nuitka-project: --windows-icon-from-ico=Installer/VideOCR.ico
from __future__ import annotations
import ast
import configparser
import contextlib
import ctypes
import datetime
import io
import json
import math
import os
import pathlib
import queue
import re
import subprocess
import sys
import threading
import time
import tkinter.font as tkFont
import urllib.request
import webbrowser
from typing import IO, Any, cast
import av
import numpy as np
import psutil # type: ignore
import PySimpleGUI as sg # type: ignore
from PIL import Image
from wakepy import keep
if sys.platform == "win32":
import PyTaskbar # type: ignore
from winotify import Notification, audio # type: ignore
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('VideOCR')
else:
from plyer import notification # type: ignore
from _version import __version__
# -- Save errors to log file ---
def log_error(message: str, log_name: str = "error_log.txt") -> str:
"""Logs error messages to a platform-appropriate log file location."""
portable_flag = os.path.join(APP_DIR, 'portable_mode.txt')
if os.path.exists(portable_flag):
log_dir = APP_DIR
else:
if sys.platform == "win32":
log_dir = os.path.join(os.environ.get('LOCALAPPDATA') or os.path.join(str(pathlib.Path.home()), 'AppData', 'Local'), "VideOCR")
else:
xdg_state = os.environ.get("XDG_STATE_HOME")
if xdg_state:
log_dir = os.path.join(xdg_state, "VideOCR")
else:
log_dir = os.path.join(str(pathlib.Path.home()), ".local", "state", "VideOCR")
os.makedirs(log_dir, exist_ok=True)
log_path = os.path.join(log_dir, log_name)
timestamp = datetime.datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
with open(log_path, "a", encoding="utf-8") as f:
f.write(f"{timestamp} {message}\n")
return log_path
# --- Make application DPI aware ---
def make_dpi_aware() -> None:
"""Makes the application DPI aware on Windows to prevent scaling issues."""
if sys.platform == "win32":
try:
ctypes.windll.shcore.SetProcessDpiAwareness(True)
except AttributeError:
log_error("Could not set DPI awareness.")
# --- Determine DPI scaling factor ---
def get_dpi_scaling() -> float:
"""Determines DPI scaling factor for the current OS."""
def round_to_quarter_step(scale: float) -> float:
dpi_scaling_factors = [1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]
return min(dpi_scaling_factors, key=lambda x: abs(x - scale))
if sys.platform == "win32":
try:
dpi = int(ctypes.windll.shcore.GetScaleFactorForDevice(0)) # 0 = primary monitor
return dpi / 100.0
except Exception:
return 1.0
else:
# Linux has no proper way of reporting scaling factor. Linespace is instead used as DPI proxy. Base linespace ~16px at 100% scaling is assumed.
try:
root = sg.tk.Tk()
root.withdraw()
default_font = tkFont.nametofont("TkDefaultFont")
metrics = default_font.metrics()
root.destroy()
baseline_linespace = 16.0
actual_linespace = metrics.get("linespace", baseline_linespace)
scale = actual_linespace / baseline_linespace
return round_to_quarter_step(scale)
except Exception:
return 1.0
def get_gui_scaling_multiplier() -> float | None:
"""Reads the custom GUI scaling multiplier from the config file."""
if os.path.exists(CONFIG_FILE):
temp_config = configparser.ConfigParser()
try:
temp_config.read(CONFIG_FILE)
if temp_config.has_option(CONFIG_SECTION, 'gui_scaling'):
val = temp_config.get(CONFIG_SECTION, 'gui_scaling')
if val != 'System Default':
return float(val)
except Exception:
pass
return None
def get_scaled_graph_size(custom_scale: float | None, base_w: int, base_h: int) -> tuple[int, int]:
"""Calculates graph size using a custom scale, falling back to OS DPI if None."""
scale = custom_scale if custom_scale is not None else get_dpi_scaling()
return int(base_w * scale), int(base_h * scale)
# --- Send notification --
def send_notification(title: str, message: str) -> None:
"""Sends a notification via winotify on Windows and via Plyer on Linux."""
if sys.platform == "win32":
try:
toast = Notification(
app_id="VideOCR",
title=title,
msg=message,
icon=os.path.join(APP_DIR, 'VideOCR.ico')
)
toast.set_audio(audio.Default, loop=False)
toast.show()
except Exception as e:
log_error(f"Failed to send notification. Error: {e}")
else:
try:
notification.notify(
title=title,
message=message,
app_name='VideOCR',
app_icon=os.path.join(APP_DIR, 'VideOCR.png')
)
except Exception as e:
log_error(f"Failed to send notification. Error: {e}")
# --- Determine VideOCR location ---
def find_videocr_program() -> str | None:
"""Determines the path to the videocr-cli executable (.exe or .bin)."""
program_name = 'videocr-cli'
extension = ".exe" if sys.platform == "win32" else ".bin"
root_path = os.path.join(APP_DIR, f'{program_name}{extension}')
if os.path.exists(root_path):
return root_path
return None
# --- Determine Config file location ---
def get_config_file_path() -> str:
"""Determines the correct path for the config file depending on installation mode."""
portable_flag = os.path.join(APP_DIR, 'portable_mode.txt')
if os.path.exists(portable_flag):
config_dir = APP_DIR
else:
if sys.platform == "win32":
config_dir = os.path.join(os.environ.get('APPDATA') or os.path.join(str(pathlib.Path.home()), 'AppData', 'Roaming'), 'VideOCR')
else:
xdg_config = os.environ.get("XDG_CONFIG_HOME")
if xdg_config:
config_dir = os.path.join(xdg_config, "VideOCR")
else:
config_dir = os.path.join(str(pathlib.Path.home()), ".config", "VideOCR")
os.makedirs(config_dir, exist_ok=True)
return os.path.join(config_dir, 'videocr_gui_config.ini')
# --- Configuration ---
PROGRAM_VERSION = __version__
APP_DIR = os.path.dirname(os.path.abspath(__file__))
LANGUAGES_DIR = os.path.join(APP_DIR, 'languages')
VIDEOCR_PATH = find_videocr_program()
DEFAULT_OUTPUT_SRT = ""
DEFAULT_LANG = "en"
DEFAULT_OCR_ENGINE = "PaddleOCR (Det. + Rec.)"
DEFAULT_SUBTITLE_LANGUAGE = 'English'
DEFAULT_SUBTITLE_POSITION = "center"
DEFAULT_SUBTITLE_ALIGNMENT = "bottom-center"
DEFAULT_CONF_THRESHOLD = 75
DEFAULT_SIM_THRESHOLD = 80
DEFAULT_MAX_MERGE_GAP = 0.1
DEFAULT_MIN_SUBTITLE_DURATION = 0.2
DEFAULT_SSIM_THRESHOLD = 92
DEFAULT_OCR_IMAGE_MAX_WIDTH = 720
DEFAULT_FRAMES_TO_SKIP = 1
DEFAULT_TIME_START = "0:00"
KEY_SEEK_STEP = 1
CONFIG_FILE = get_config_file_path()
CONFIG_SECTION = 'Settings'
try:
DEFAULT_DOCUMENTS_DIR = str(pathlib.Path.home() / "Documents")
except Exception:
DEFAULT_DOCUMENTS_DIR = ""
# --- Language Data ---
LANGUAGE_CODE_TO_NATIVE_NAME = {
'en': 'English',
'de': 'Deutsch',
'ch': '中文',
'es': 'Español',
'fr': 'Français',
'pt': 'Português',
'it': 'Italiano',
'ar': 'العربية',
'ru': 'Русский',
'id': 'Bahasa Indonesia',
'th': 'ไทย',
'ko': '한국어',
'ja': '日本語',
'vi': 'Tiếng Việt',
}
# --- Language Data ---
PADDLEOCR_LANGUAGES_LIST = [
('Abaza', 'abq'), ('Adyghe', 'ady'), ('Afrikaans', 'af'), ('Albanian', 'sq'),
('Angika', 'ang'), ('Arabic', 'ar'), ('Avar', 'ava'), ('Azerbaijani', 'az'),
('Baluchi', 'bal'), ('Bashkir', 'ba'), ('Basque', 'eu'), ('Belarusian', 'be'),
('Bhojpuri', 'bho'), ('Bihari', 'bh'), ('Bosnian', 'bs'), ('Bulgarian', 'bg'),
('Buryat', 'bua'), ('Catalan', 'ca'), ('Chechen', 'che'), ('Chinese & English', 'ch'),
('Chinese Traditional', 'chinese_cht'), ('Chuvash', 'cv'), ('Croatian', 'hr'),
('Czech', 'cs'), ('Danish', 'da'), ('Dargwa', 'dar'), ('Dutch', 'nl'),
('English', 'en'), ('Estonian', 'et'), ('Finnish', 'fi'), ('French', 'fr'),
('Galician', 'gl'), ('Georgian', 'ka'), ('German', 'german'), ('Goan Konkani', 'gom'),
('Greek', 'el'), ('Haryanvi', 'bgc'), ('Hindi', 'hi'), ('Hungarian', 'hu'),
('Icelandic', 'is'), ('Indonesian', 'id'), ('Ingush', 'inh'), ('Irish', 'ga'),
('Italian', 'it'), ('Japanese', 'japan'), ('Kabardian', 'kbd'), ('Kalmyk', 'xal'),
('Karakalpak', 'kaa'), ('Kazakh', 'kk'), ('Komi', 'kv'), ('Korean', 'korean'),
('Kurdish', 'ku'), ('Kyrgyz', 'ky'), ('Lak', 'lbe'), ('Latin', 'la'),
('Latvian', 'lv'), ('Lezghian', 'lez'), ('Lithuanian', 'lt'), ('Luxembourgish', 'lb'),
('Macedonian', 'mk'), ('Magahi', 'mah'), ('Maithili', 'mai'), ('Malay', 'ms'),
('Maltese', 'mt'), ('Maori', 'mi'), ('Marathi', 'mr'), ('Meadow Mari', 'mhr'),
('Moldovan', 'mo'), ('Mongolian', 'mn'), ('Nagpuri', 'sck'), ('Nepali', 'ne'),
('Newari', 'new'), ('Norwegian', 'no'), ('Occitan', 'oc'), ('Ossetian', 'os'),
('Pali', 'pi'), ('Pashto', 'ps'), ('Persian', 'fa'), ('Polish', 'pl'),
('Portuguese', 'pt'), ('Quechua', 'qu'), ('Romansh', 'rm'), ('Romanian', 'ro'),
('Russian', 'ru'), ('Sanskrit', 'sa'), ('Serbian(cyrillic)', 'rs_cyrillic'),
('Serbian(latin)', 'rs_latin'), ('Sindhi', 'sd'), ('Slovak', 'sk'),
('Slovenian', 'sl'), ('Spanish', 'es'), ('Swahili', 'sw'), ('Swedish', 'sv'),
('Tabassaran', 'tab'), ('Tagalog', 'tl'), ('Tajik', 'tg'), ('Tamil', 'ta'),
('Tatar', 'tt'), ('Telugu', 'te'), ('Thai', 'th'), ('Turkish', 'tr'),
('Tuvan', 'tyv'), ('Udmurt', 'udm'), ('Ukrainian', 'uk'), ('Urdu', 'ur'),
('Uyghur', 'ug'), ('Uzbek', 'uz'), ('Vietnamese', 'vi'), ('Welsh', 'cy'),
('Sakha', 'sah'),
]
PADDLEOCR_LANGUAGES_LIST.sort(key=lambda x: x[0])
paddle_display_names = [lang[0] for lang in PADDLEOCR_LANGUAGES_LIST]
paddle_abbr_lookup = {name: abbr for name, abbr in PADDLEOCR_LANGUAGES_LIST}
GOOGLE_LENS_LANGUAGES_LIST = [
("Afrikaans", "af"), ("Albanian", "sq"), ("Arabic", "ar"), ("Armenian", "hy"),
("Belarusian", "be"), ("Bengali", "bn"), ("Bulgarian", "bg"), ("Catalan", "ca"),
("Chinese", "zh"), ("Croatian", "hr"), ("Czech", "cs"), ("Danish", "da"),
("Dutch", "nl"), ("English", "en"), ("Estonian", "et"), ("Filipino", "fil"),
("Finnish", "fi"), ("French", "fr"), ("German", "de"), ("Greek", "el"),
("Gujarati", "gu"), ("Hebrew", "iw"), ("Hindi", "hi"), ("Hungarian", "hu"),
("Icelandic", "is"), ("Indonesian", "id"), ("Italian", "it"), ("Japanese", "ja"),
("Kannada", "kn"), ("Khmer", "km"), ("Korean", "ko"), ("Lao", "lo"),
("Latvian", "lv"), ("Lithuanian", "lt"), ("Macedonian", "mk"), ("Malay", "ms"),
("Malayalam", "ml"), ("Marathi", "mr"), ("Nepali", "ne"), ("Norwegian", "no"),
("Persian", "fa"), ("Polish", "pl"), ("Portuguese", "pt"), ("Punjabi", "pa"),
("Romanian", "ro"), ("Russian", "ru"), ("Russian (PETR1708)", "ru-PETR1708"),
("Serbian", "sr"), ("Serbian (Latin)", "sr-Latn"), ("Slovak", "sk"), ("Slovenian", "sl"),
("Spanish", "es"), ("Swedish", "sv"), ("Tagalog", "tl"), ("Tamil", "ta"),
("Telugu", "te"), ("Thai", "th"), ("Turkish", "tr"), ("Ukrainian", "uk"),
("Vietnamese", "vi"), ("Yiddish", "yi"), ("Amharic", "am"), ("Ancient Greek", "grc"),
("Assamese", "as"), ("Azerbaijani", "az"), ("Azerbaijani (Cyrl)", "az-Cyrl"), ("Basque", "eu"),
("Bosnian", "bs"), ("Burmese", "my"), ("Cebuano", "ceb"), ("Cherokee", "chr"),
("Dhivehi", "dv"), ("Dzonkha", "dz"), ("Esperanto", "eo"), ("Galician", "gl"),
("Georgian", "ka"), ("Haitian Creole", "ht"), ("Irish", "ga"), ("Javanese", "jv"),
("Kazakh", "kk"), ("Kirghiz", "ky"), ("Latin", "la"), ("Maltese", "mt"),
("Mongolian", "mn"), ("Oriya", "or"), ("Pashto", "ps"), ("Sanskrit", "sa"),
("Sinhala", "si"), ("Swahili", "sw"), ("Syriac", "syr"), ("Tibetan", "bo"),
("Tigirinya", "ti"), ("Urdu", "ur"), ("Uzbek", "uz"), ("Uzbek (Cyrl)", "uz-Cyrl"),
("Welsh", "cy"), ("Zulu", "zu"), ("Acehnese", "ace"), ("Acholi", "ach"),
("Adangme", "ada"), ("Akan", "ak"), ("Algonquinian", "alg"), ("Araucanian/Mapuche", "arn"),
("Asturian", "ast"), ("Athabaskan", "ath"), ("Aymara", "ay"), ("Balinese", "ban"),
("Bambara", "bm"), ("Bantu", "bnt"), ("Bashkir", "ba"), ("Batak", "btk"),
("Bemba", "bem"), ("Bikol", "bik"), ("Bislama", "bi"), ("Breton", "br"),
("Chechen", "ce"), ("Chinese (Simplified)", "zh-Hans"), ("Chinese (Traditional)", "zh-Hant"), ("Chinese (Hong Kong)", "zh-Hant-HK"),
("Choctaw", "cho"), ("Chuvash", "cv"), ("Cree", "cr"), ("Creek", "mus"),
("Crimean Tatar", "crh"), ("Dakota", "dak"), ("Duala", "dua"), ("Efik", "efi"),
("English (British)", "en-GB"), ("Ewe", "ee"), ("Faroese", "fo"), ("Fijian", "fj"),
("Fon", "fon"), ("French (Canadian)", "fr-CA"), ("Fulah", "ff"), ("Ga", "gaa"),
("Ganda", "lg"), ("Gayo", "gay"), ("Gilbertese", "gil"), ("Gothic", "got"),
("Guarani", "gn"), ("Hausa", "ha"), ("Hawaiian", "haw"), ("Herero", "hz"),
("Hiligaynon", "hil"), ("Iban", "iba"), ("Igbo", "ig"), ("Iloko", "ilo"),
("Kabyle", "kab"), ("Kachin", "kac"), ("Kalaallisut", "kl"), ("Kamba", "kam"),
("Kanuri", "kr"), ("Kara-Kalpak", "kaa"), ("Khasi", "kha"), ("Kikuyu", "ki"),
("Kinyarwanda", "rw"), ("Komi", "kv"), ("Kongo", "kg"), ("Kosraean", "kos"),
("Kuanyama", "kj"), ("Lingala", "ln"), ("Low German", "nds"), ("Lozi", "loz"),
("Luba-Katanga", "lu"), ("Luo", "luo"), ("Madurese", "mad"), ("Malagasy", "mg"),
("Mandingo", "man"), ("Manx", "gv"), ("Maori", "mi"), ("Marshallese", "mh"),
("Mende", "men"), ("Middle English", "enm"), ("Middle High German", "gmh"), ("Minangkabau", "min"),
("Mohawk", "moh"), ("Mongo", "lol"), ("Nahuatl", "nah"), ("Navajo", "nv"),
("Ndonga", "ng"), ("Niuean", "niu"), ("North Ndebele", "nd"), ("Northern Sotho", "nso"),
("Nyanja", "ny"), ("Nyankole", "nyn"), ("Nyasa Tonga", "tog"), ("Nzima", "nzi"),
("Occitan", "oc"), ("Ojibwa", "oj"), ("Old English", "ang"), ("Old French", "fro"),
("Old High German", "goh"), ("Old Norse", "non"), ("Old Provencal", "pro"), ("Ossetic", "os"),
("Pampanga", "pam"), ("Pangasinan", "pag"), ("Papiamento", "pap"), ("Portuguese (European)", "pt-PT"),
("Quechua", "qu"), ("Romansh", "rm"), ("Romany", "rom"), ("Rundi", "rn"),
("Sakha", "sah"), ("Samoan", "sm"), ("Sango", "sg"), ("Scots", "sco"),
("Scottish Gaelic", "gd"), ("Shona", "sn"), ("Songhai", "son"), ("Southern Sotho", "st"),
("Spanish (Latin American)", "es-419"), ("Sundanese", "su"), ("Swati", "ss"), ("Tahitian", "ty"),
("Tajik", "tg"), ("Tatar", "tt"), ("Temne", "tem"), ("Tongan", "to"),
("Tsonga", "ts"), ("Tswana", "tn"), ("Turkmen", "tk"), ("Udmurt", "udm"),
("Venda", "ve"), ("Votic", "vot"), ("Western Frisian", "fy"), ("Wolof", "wo"),
("Xhosa", "xh"), ("Yoruba", "yo"), ("Zapotec", "zap")
]
GOOGLE_LENS_LANGUAGES_LIST.sort(key=lambda x: x[0])
lens_display_names = [lang[0] for lang in GOOGLE_LENS_LANGUAGES_LIST]
lens_abbr_lookup = {name: abbr for name, abbr in GOOGLE_LENS_LANGUAGES_LIST}
OCR_ENGINES = [
'PaddleOCR (Det. + Rec.)',
'PaddleOCR (Det.) + Google Lens (Rec.)'
]
# Mapping from PaddleOCR internal codes to standard ISO 639 codes for deviating abbreviations
PADDLE_TO_ISO_MAP = {
'ch': 'zh',
'chinese_cht': 'zh',
'german': 'de',
'japan': 'ja',
'korean': 'ko',
'rs_cyrillic': 'sr',
'rs_latin': 'sr',
'ang': 'anp',
'mah': 'mag',
'mo': 'ro',
# Prefer 2-Letter Codes
'ava': 'av',
'che': 'ce',
}
# --- Subtitle Position Data ---
SUBTITLE_POSITIONS_LIST = [
('pos_center', 'center'),
('pos_left', 'left'),
('pos_right', 'right'),
('pos_any', 'any')
]
DEFAULT_INTERNAL_SUBTITLE_POSITION = 'center'
# --- Subtitle Alignment Data ---
SUBTITLE_ALIGNMENT_LIST = [
('align_bottom_center', 'bottom-center'),
('align_bottom_left', 'bottom-left'),
('align_bottom_right', 'bottom-right'),
('align_top_center', 'top-center'),
('align_top_left', 'top-left'),
('align_top_right', 'top-right'),
('align_middle_center', 'middle-center'),
('align_middle_left', 'middle-left'),
('align_middle_right', 'middle-right')
]
# --- Post-Action Master List ---
if sys.platform == "win32":
POST_ACTION_KEYS = ['action_none', 'action_sleep', 'action_hibernate', 'action_shutdown', 'action_lock']
else:
POST_ACTION_KEYS = ['action_none', 'action_sleep', 'action_shutdown']
DEFAULT_ACTION_TEXTS = {
'action_none': 'Do Nothing',
'action_sleep': 'Sleep',
'action_hibernate': 'Hibernate',
'action_shutdown': 'Shutdown',
'action_lock': 'Lock'
}
# --- Status Translation Helpers ---
INTERNAL_STATUS_TO_LANG_KEY = {
'Pending': 'status_pending',
'Processing': 'status_processing',
'Completed': 'status_completed',
'Cancelled': 'status_cancelled_queue',
'Error': 'status_error',
'Paused': 'status_paused'
}
DEFAULT_STATUS_TEXTS = {
'status_pending': 'Pending',
'status_processing': 'Processing',
'status_completed': 'Completed',
'status_cancelled_queue': 'Cancelled',
'status_error': 'Error',
'status_paused': 'Paused'
}
# --- GUI Scaling Data ---
GUI_SCALING_LIST = [
('system_default', 'System Default'),
('scale_1_0', '1.0'),
('scale_1_25', '1.25'),
('scale_1_5', '1.5'),
('scale_1_75', '1.75'),
('scale_2_0', '2.0')
]
DEFAULT_GUI_SCALING = 'System Default'
# --- Cross-Platform Cursor Mapping ---
if sys.platform == "win32":
CURSORS = {
'vertical': 'size_ns',
'horizontal': 'size_we',
'diag_nw_se': 'size_nw_se',
'diag_ne_sw': 'size_ne_sw',
'move': 'fleur',
'crosshair': 'crosshair',
}
else:
CURSORS = {
'vertical': 'sb_v_double_arrow',
'horizontal': 'sb_h_double_arrow',
'diag_nw_se': 'bottom_right_corner',
'diag_ne_sw': 'bottom_left_corner',
'move': 'fleur',
'crosshair': 'crosshair',
}
# --- Global Variables ---
video_path = None
original_frame_width = 0
original_frame_height = 0
video_duration_ms = 0.0
current_time_ms = 0.0
resized_frame_width = 0
resized_frame_height = 0
image_offset_x = 0
image_offset_y = 0
gui_scale_multiplier = get_gui_scaling_multiplier()
graph_size = get_scaled_graph_size(custom_scale=gui_scale_multiplier, base_w=672, base_h=378)
current_image_bytes = None
prog = None
previous_taskbar_state = None
LANG: dict[str, str] = {}
current_wake_lock: Any = None
batch_queue: list[dict[str, Any]] = []
gui_queue: queue.Queue[tuple[str, Any]] = queue.Queue()
# --- i18n Language Functions ---
def get_available_languages() -> dict[str, str]:
"""Scans the 'languages' directory and returns a dict mapping native names to language codes."""
langs: dict[str, str] = {}
if not os.path.isdir(LANGUAGES_DIR):
log_error(f"Languages directory not found at {LANGUAGES_DIR}")
return {'English': 'en'}
for filename in os.listdir(LANGUAGES_DIR):
if filename.endswith('.json'):
lang_code = filename[:-5]
native_name = LANGUAGE_CODE_TO_NATIVE_NAME.get(lang_code, lang_code.capitalize())
langs[native_name] = lang_code
return langs if langs else {'English': 'en'}
def load_language(lang_code: str) -> None:
"""Loads a language JSON file into a dictionary. Falls back to 'en'."""
global LANG
def load_file(code: str) -> dict[str, str] | None:
lang_path = os.path.join(LANGUAGES_DIR, f"{code}.json")
if os.path.exists(lang_path):
try:
with open(lang_path, encoding='utf-8') as f:
return cast(dict[str, str], json.load(f))
except json.JSONDecodeError as e:
log_error(f"Syntax error in language file {code}.json: {e}")
return None
loaded = load_file(lang_code)
if loaded is None:
log_error(f"Language file for '{lang_code}' not found or invalid. Falling back to English.")
loaded = load_file('en')
if loaded is None:
log_error("CRITICAL: English language file 'en.json' is missing or invalid.")
sg.popup_error("Critical Error: Default language file 'en.json' is missing or corrupt.\nPlease reinstall the application.", title="Fatal Error")
sys.exit()
LANG = loaded
def update_gui_text(window: sg.Window, is_paused: bool = False) -> None:
"""Updates all text elements in the GUI based on the loaded LANG dictionary."""
if not LANG:
return
key_map = {
# Tab 1
'-SAVE_AS_BTN-': {'text': 'btn_save_as'},
'-BTN-OPEN-FILE-': {'text': 'btn_browse'},
'-BTN-OPEN-FOLDER-': {'text': 'btn_browse_folder'},
'-TAB-VIDEO-': {'text': 'tab_video'},
'-LBL-SOURCE-': {'text': 'lbl_source'},
'-LBL-OUTPUT_SRT-': {'text': 'lbl_output_srt'},
'-LBL-OCR_ENGINE-': {'text': 'lbl_ocr_engine', 'tooltip': 'tip_ocr_engine'},
'-OCR_ENGINE_COMBO-': {'tooltip': 'tip_ocr_engine'},
'-LBL-SUB_LANG-': {'text': 'lbl_sub_lang'},
'-LBL-SUB_POS-': {'text': 'lbl_sub_pos', 'tooltip': 'tip_sub_pos'},
'-SUBTITLE_POS_COMBO-': {'tooltip': 'tip_sub_pos'},
'-BTN-HELP-': {'text': 'btn_how_to_use'},
'-LBL-SEEK-': {'text': 'lbl_seek'},
'-LBL-CROP_BOX-': {'text': 'lbl_crop_box'},
'-CROP_COORDS-': {'text': 'crop_not_set'},
'-TIME_TEXT-': {'text': 'time_text_empty'},
'-BTN-RUN-': {'text': 'btn_run'},
'-BTN-CANCEL-': {'text': 'btn_cancel'},
'-BTN-CLEAR_CROP-': {'text': 'btn_clear_crop'},
'-LBL-PROGRESS-': {'text': 'lbl_progress'},
'-LBL-LOG-': {'text': 'lbl_log'},
'-LBL-WHEN_READY-': {'text': 'lbl_when_ready'},
'-BTN-ADD-BATCH-': {'text': 'btn_add_to_queue'},
'-BTN-BATCH-ADD-ALL-': {'text': 'btn_add_all_to_queue'},
# Queue Tab
'-TAB-BATCH-': {'text': 'tab_batch'},
'-LBL-QUEUE-TITLE-': {'text': 'lbl_queue_title'},
'-BTN-BATCH-START-': {'text': 'btn_start_queue'},
'-BTN-BATCH-STOP-': {'text': 'btn_stop_queue'},
'-BTN-BATCH-UP-': {'tooltip': 'tip_batch_up'},
'-BTN-BATCH-DOWN-': {'tooltip': 'tip_batch_down'},
'-BTN-BATCH-RESET-': {'text': 'btn_reset', 'tooltip': 'tip_batch_reset'},
'-BTN-BATCH-EDIT-': {'text': 'btn_edit', 'tooltip': 'tip_batch_edit'},
'-BTN-BATCH-REMOVE-': {'text': 'btn_remove', 'tooltip': 'tip_batch_remove'},
'-BTN-BATCH-CLEAR-': {'text': 'btn_clear_queue', 'tooltip': 'tip_batch_clear'},
# Tab 2
'-TAB-ADVANCED-': {'text': 'tab_advanced'},
'-LBL-OCR_SETTINGS-': {'text': 'lbl_ocr_settings'},
'-LBL-TIME_START-': {'text': 'lbl_time_start', 'tooltip': 'tip_time_start'},
'--time_start': {'tooltip': 'tip_time_start'},
'-LBL-TIME_END-': {'text': 'lbl_time_end', 'tooltip': 'tip_time_end'},
'--time_end': {'tooltip': 'tip_time_end'},
'-LBL-CONF_THRESHOLD-': {'text': 'lbl_conf_threshold', 'tooltip': 'tip_conf_threshold'},
'--conf_threshold': {'tooltip': 'tip_conf_threshold'},
'-LBL-SIM_THRESHOLD-': {'text': 'lbl_sim_threshold', 'tooltip': 'tip_sim_threshold'},
'--sim_threshold': {'tooltip': 'tip_sim_threshold'},
'-LBL-MERGE_GAP-': {'text': 'lbl_merge_gap', 'tooltip': 'tip_merge_gap'},
'--max_merge_gap': {'tooltip': 'tip_merge_gap'},
'-LBL-BRIGHTNESS-': {'text': 'lbl_brightness', 'tooltip': 'tip_brightness'},
'--brightness_threshold': {'tooltip': 'tip_brightness'},
'-LBL-SSIM-': {'text': 'lbl_ssim', 'tooltip': 'tip_ssim'},
'--ssim_threshold': {'tooltip': 'tip_ssim'},
'-LBL-OCR_WIDTH-': {'text': 'lbl_ocr_width', 'tooltip': 'tip_ocr_width'},
'--ocr_image_max_width': {'tooltip': 'tip_ocr_width'},
'-LBL-FRAMES_SKIP-': {'text': 'lbl_frames_skip', 'tooltip': 'tip_frames_skip'},
'--frames_to_skip': {'tooltip': 'tip_frames_skip'},
'-LBL-MIN_DURATION-': {'text': 'lbl_min_duration', 'tooltip': 'tip_min_duration'},
'--min_subtitle_duration': {'tooltip': 'tip_min_duration'},
'--use_gpu': {'text': 'chk_use_gpu', 'tooltip': 'tip_use_gpu'},
'--use_fullframe': {'text': 'chk_full_frame', 'tooltip': 'tip_full_frame'},
'--use_dual_zone': {'text': 'chk_dual_zone', 'tooltip': 'tip_dual_zone'},
'enable_subtitle_alignment': {'text': 'chk_enable_subtitle_alignment', 'tooltip': 'tip_enable_subtitle_alignment'},
'-LBL-SUBTITLE-ALIGNMENT-': {'text': 'lbl_subtitle_alignment1', 'tooltip': 'tip_subtitle_alignment1'},
'--subtitle_alignment': {'tooltip': 'tip_subtitle_alignment1'},
'-LBL-SUBTITLE-ALIGNMENT2-': {'text': 'lbl_subtitle_alignment2', 'tooltip': 'tip_subtitle_alignment2'},
'--subtitle_alignment2': {'tooltip': 'tip_subtitle_alignment2'},
'--use_angle_cls': {'text': 'chk_angle_cls', 'tooltip': 'tip_angle_cls'},
'--post_processing': {'text': 'chk_post_processing', 'tooltip': 'tip_post_processing'},
'--use_server_model': {'text': 'chk_server_model', 'tooltip': 'tip_server_model'},
'-LBL-VIDEOCR_SETTINGS-': {'text': 'lbl_videocr_settings'},
'-LBL-UI_LANG-': {'text': 'lbl_ui_lang', 'tooltip': 'tip_ui_lang'},
'-UI_LANG_COMBO-': {'tooltip': 'tip_ui_lang'},
'-LBL-GUI_SCALING-': {'text': 'lbl_gui_scaling', 'tooltip': 'tip_gui_scaling'},
'gui_scaling': {'tooltip': 'tip_gui_scaling'},
'--save_crop_box': {'text': 'chk_save_crop_box', 'tooltip': 'tip_save_crop_box'},
'--save_in_video_dir': {'text': 'chk_save_in_video_dir', 'tooltip': 'tip_save_in_video_dir'},
'-LBL-OUTPUT_DIR-': {'text': 'lbl_output_dir', 'tooltip': 'tip_output_dir'},
'-BTN-FOLDER_BROWSE-': {'text': 'btn_browse_folder'},
'-LBL-SEEK_STEP-': {'text': 'lbl_seek_step', 'tooltip': 'tip_seek_step'},
'--keyboard_seek_step': {'tooltip': 'tip_seek_step'},
'--send_notification': {'text': 'chk_send_notification', 'tooltip': 'tip_send_notification'},
'--check_for_updates': {'text': 'chk_check_updates', 'tooltip': 'tip_check_updates'},
'prevent_system_sleep': {'text': 'chk_prevent_sleep', 'tooltip': 'tip_prevent_sleep'},
'--normalize_to_simplified_chinese': {'text': 'chk_normalize_chinese', 'tooltip': 'tip_normalize_chinese'},
'-BTN-CHECK_UPDATE_MANUAL-': {'text': 'btn_check_now'},
# Tab 3
'-TAB-ABOUT-': {'text': 'tab_about'},
'-LBL-ABOUT_VERSION-': {'text': 'lbl_about_version'},
'-LBL-GET_NEWEST-': {'text': 'lbl_get_newest'},
'-LBL-BUG_REPORT-': {'text': 'lbl_bug_report'},
}
tab_group = window['-TABGROUP-']
for key, lang_keys in key_map.items():
if key.startswith('-TAB-'):
if 'text' in lang_keys and lang_keys['text'] in LANG:
tab_element_widget = window[key].Widget
tab_group.Widget.tab(tab_element_widget, text=LANG[lang_keys['text']])
continue
if key in window.AllKeysDict:
element = window[key]
if 'text' in lang_keys and lang_keys['text'] in LANG:
new_content = LANG[lang_keys['text']]
if lang_keys['text'] == 'lbl_about_version':
new_content = new_content.format(version=PROGRAM_VERSION)
if isinstance(element, (sg.Button, sg.Checkbox)):
element.update(text=new_content)
else:
element.update(value=new_content)
if 'tooltip' in lang_keys and lang_keys['tooltip'] in LANG:
element.SetTooltip(LANG[lang_keys['tooltip']])
if is_paused:
pause_btn_text = LANG.get('btn_resume', "Resume")
else:
pause_btn_text = LANG.get('btn_pause', "Pause")
if '-BTN-PAUSE-' in window.AllKeysDict:
window['-BTN-PAUSE-'].update(text=pause_btn_text)
if '-BTN-BATCH-PAUSE-' in window.AllKeysDict:
window['-BTN-BATCH-PAUSE-'].update(text=pause_btn_text)
if '-BATCH-TABLE-' in window.AllKeysDict:
try:
table_widget = window['-BATCH-TABLE-'].Widget
table_widget.heading('#1', text=LANG.get('col_video_file', 'Video File'))
table_widget.heading('#2', text=LANG.get('col_output_file', 'Output File'))
table_widget.heading('#3', text=LANG.get('col_status', 'Status'))
except Exception as e:
log_error(f"Failed to update table headings: {e}")
refresh_batch_table(window)
current_idx = window['-POST_ACTION-'].Widget.current()
update_post_action_combo(window, current_idx)
current_idx1 = window['--subtitle_alignment'].Widget.current()
current_idx2 = window['--subtitle_alignment2'].Widget.current()
update_alignment_combos(window, current_idx1, current_idx2)
current_scale_idx = window['gui_scaling'].Widget.current()
update_gui_scaling_combo(window, current_scale_idx)
# --- Helper Functions ---
def kill_process_tree(pid: int) -> None:
"""Kills the process with the given PID and its descendants."""
if sys.platform == "win32":
try:
subprocess.run(['taskkill', '/F', '/T', '/PID', str(pid)], check=True, capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW)
except subprocess.CalledProcessError as e:
log_error(f"Error terminating process tree {pid}: {e.stderr}")
except FileNotFoundError:
log_error("taskkill command not found. Cannot terminate process tree.")
except Exception as e:
log_error(f"An unexpected error occurred during taskkill: {e}")
else:
try:
os.killpg(os.getpgid(pid), 15)
except OSError as e:
log_error(f"Error terminating process group {pid}: {e}")
except Exception as e:
log_error(f"An unexpected error occurred during process kill: {e}")
def format_time(seconds: float | int) -> str:
"""Formats total seconds into HH:MM:SS or MM:SS string."""
seconds = int(seconds)
h = seconds // 3600
m = (seconds % 3600) // 60
s = seconds % 60
if h > 0:
return f"{h:02d}:{m:02d}:{s:02d}"
else:
return f"{m:02d}:{s:02d}"
def format_seconds(seconds: float | int | None) -> str:
"""Converts seconds to '1h 05m' or '05m 30s' format."""
if seconds is None or seconds < 0:
return "--:--"
m, s = divmod(int(seconds), 60)
h, m = divmod(m, 60)
if h > 0:
return f"{h}h {m:02d}m"
return f"{m:02d}m {s:02d}s"
def update_time_display(window: sg.Window, current_ms: float, total_ms: float) -> None:
"""Updates the time text elements."""
time_text_format = LANG.get('time_text_format', 'Time: {} / {}')
if total_ms > 0:
current_sec = current_ms / 1000.0
total_sec = total_ms / 1000.0
time_text = f"{format_time(current_sec)} / {format_time(total_sec)}"
window["-TIME_TEXT-"].update(time_text_format.format(time_text))
else:
time_text_empty = LANG.get('time_text_empty', 'Time: -/-')
window["-TIME_TEXT-"].update(time_text_empty)
def _parse_and_validate_time_parts(time_str: str | None) -> tuple[int, int, int] | None:
"""Internal helper to parse MM:SS or HH:MM:SS and validate parts."""
if not time_str:
return None
parts = time_str.split(':')
try:
if len(parts) == 2:
m = int(parts[0])
s = int(parts[1])
if m < 0 or s < 0 or s >= 60:
return None
return (0, m, s)
elif len(parts) == 3:
h = int(parts[0])
m = int(parts[1])
s = int(parts[2])
if h < 0 or m < 0 or s < 0 or m >= 60 or s >= 60:
return None
return (h, m, s)
else:
return None
except ValueError:
return None
def is_valid_time_format(time_str: str | None) -> bool:
"""Checks if a string is in MM:SS or HH:MM:SS format with valid ranges."""
if not time_str:
return True
return _parse_and_validate_time_parts(time_str) is not None
def time_string_to_seconds(time_str: str | None) -> int | None:
"""Converts MM:SS or HH:MM:SS string to total seconds. Returns None if invalid."""
if not time_str:
return None
parsed_time = _parse_and_validate_time_parts(time_str)
if parsed_time is None:
return None
h, m, s = parsed_time
return h * 3600 + m * 60 + s
def parse_srt_time_to_seconds(time_str: str) -> float:
"""Parses a timestamp string like '00:00:01,500' or '00:01:00' into seconds (float)."""
try:
parts = time_str.replace(',', '.').split(':')
if len(parts) == 3:
return float(parts[0]) * 3600 + float(parts[1]) * 60 + float(parts[2])
except Exception:
return 0.0
return 0.0
def center_popup(parent_window: sg.Window, popup_window: sg.Window) -> None:
"""Center a popup relative to the parent window."""
x0, y0 = parent_window.current_location()
w0, h0 = parent_window.current_size_accurate()
w1, h1 = popup_window.current_size_accurate()
x1 = x0 + (w0 - w1) // 2
y1 = y0 + (h0 - h1) // 2
popup_window.move(x1, y1)
def custom_popup(parent_window: sg.Window, title: str, message: str, icon: str | bytes | None = None, modal: bool = True) -> None:
"""Create and show a centered popup relative to the parent window."""
layout = [
[sg.Text(message)],
[sg.Push(), sg.Button(LANG.get('btn_ok', 'OK'), key='OK', bind_return_key=True), sg.Push()]
]
popup_window = sg.Window(title, layout, alpha_channel=0, finalize=True, icon=icon, modal=modal)
popup_window.refresh()
center_popup(parent_window, popup_window)
popup_window.refresh()
popup_window.set_alpha(1)
popup_window['OK'].set_focus()
while True:
popup_event, _ = popup_window.read()
if popup_event in (sg.WIN_CLOSED, 'OK'):
break
popup_window.close()
def update_popup(parent_window: sg.Window, version_info: dict[str, str], current_version: str, icon: str | bytes | None = None) -> None:
"""Creates and shows a centered popup to notify the user of a new version relative to the parent window."""
url = version_info['url']
new_version = version_info['version']
popup_layout = [
[sg.Text(LANG.get('update_available_1', 'A new version of VideOCR ({}) is available!').format(new_version))],
[sg.Text(LANG.get('update_available_2', 'You are currently using version {}.').format(current_version))],
[sg.Text(LANG.get('update_available_3', 'Click the link below to visit the download page:'))],
[sg.Text(url, font=("Arial", scale_font_size(11), 'underline'), enable_events=True, key='-UPDATE_LINK-')],
[sg.Push(), sg.Button(LANG.get('btn_dismiss', 'Dismiss'), key='Dismiss'), sg.Push()]
]
update_window = sg.Window(LANG.get('update_title', "Update Available"), popup_layout, alpha_channel=0, finalize=True, modal=True, icon=icon)
update_window.refresh()
center_popup(parent_window, update_window)
update_window.refresh()
update_window.set_alpha(1)
update_window['-UPDATE_LINK-'].Widget.config(cursor="hand2")
while True:
popup_event, _ = update_window.read()
if popup_event in (sg.WIN_CLOSED, 'Dismiss'):
break
elif popup_event == '-UPDATE_LINK-':
webbrowser.open(url)
break
update_window.close()
def custom_popup_yes_no(parent_window: sg.Window, title: str, message: str, icon: str | bytes | None = None) -> str:
"""Creates and shows a centered Yes/No popup relative to the parent window."""
layout = [
[sg.Text(message)],
[sg.Push(),
sg.Button(LANG.get('btn_yes', 'Yes'), key='Yes', size=(10, 1), bind_return_key=True),
sg.Button(LANG.get('btn_no', 'No'), key='No', size=(10, 1)),
sg.Push()]
]
popup_window = sg.Window(title, layout, alpha_channel=0, finalize=True, icon=icon, modal=True)
popup_window.refresh()
center_popup(parent_window, popup_window)
popup_window.refresh()
popup_window.set_alpha(1)
popup_window['No'].set_focus()
choice = 'No'
while True:
popup_event, _ = popup_window.read()
if popup_event in (sg.WIN_CLOSED, 'No'):
choice = 'No'
break
elif popup_event == 'Yes':
choice = 'Yes'
break
popup_window.close()
return choice
def popup_post_action_countdown(parent_window: sg.Window, action_text: str, icon: str | bytes | None = None) -> bool:
"""Displays a countdown popup relative to the parent window."""
timeout_seconds = 60
layout = [
[sg.Text(LANG.get('title_countdown', "Action Required"), font=("Arial", scale_font_size(12), "bold"), pad=(0, 10))],
[sg.Text(LANG.get('lbl_action_countdown', "System will execute '{}' in {} seconds.").format(action_text, timeout_seconds),
key='-LBL-COUNTDOWN-', font=("Arial", scale_font_size(10)), pad=(10, 10))],
[sg.Push(),
sg.Button(LANG.get('btn_proceed', "Proceed Now"), key='-BTN-PROCEED-', size=(12, 1)),
sg.Button(LANG.get('btn_cancel', "Cancel"), key='-BTN-CANCEL-', size=(10, 1)),
sg.Push()]
]
popup_window = sg.Window(LANG.get('title_countdown', "Action Required"), layout, keep_on_top=True, modal=True, finalize=True, icon=icon)
popup_window.refresh()
center_popup(parent_window, popup_window)
popup_window.refresh()
popup_window.set_alpha(1)
counter = timeout_seconds
should_proceed = False
while True:
event, _ = popup_window.read(timeout=1000)
if event in (sg.WIN_CLOSED, '-BTN-CANCEL-'):
should_proceed = False
break
if event == '-BTN-PROCEED-':
should_proceed = True
break
if event == sg.TIMEOUT_EVENT:
counter -= 1
if counter <= 0:
should_proceed = True
break
new_text = LANG.get('lbl_action_countdown', "System will execute '{}' in {} seconds.").format(action_text, counter)
popup_window['-LBL-COUNTDOWN-'].update(new_text)
popup_window.close()
return should_proceed
def check_for_updates(window: sg.Window, manual_check: bool = False) -> None:
"""Checks GitHub for a new release."""
try:
headers = {'User-Agent': 'VideOCR-GUI'}
req = urllib.request.Request("https://api.github.com/repos/timminator/VideOCR/releases/latest", headers=headers)
with urllib.request.urlopen(req, timeout=5) as response:
if response.status == 200:
data = json.loads(response.read().decode())
latest_version_str = data['tag_name']
current_version_tuple = tuple(map(int, (PROGRAM_VERSION.split('.'))))
latest_version_tuple = tuple(map(int, (latest_version_str.lstrip('v').split('.'))))
if latest_version_tuple > current_version_tuple:
release_url = data['html_url']
window.write_event_value('-NEW_VERSION_FOUND-', {'version': latest_version_str, 'url': release_url})
elif manual_check:
window.write_event_value('-NO_UPDATE_FOUND-', None)
except Exception as e:
log_error(f"Failed to check for updates: {e}")
if manual_check:
window.write_event_value('-UPDATE_CHECK_FAILED-', None)
def update_subtitle_pos_combo(window: sg.Window, selected_internal_pos: str | None = None) -> None:
"""Updates the Subtitle Position combo box with translated values and sets the selected item."""
pos_to_select = selected_internal_pos if selected_internal_pos is not None else DEFAULT_INTERNAL_SUBTITLE_POSITION
internal_to_display_name_map = {internal_val: LANG.get(lang_key, lang_key) for lang_key, internal_val in SUBTITLE_POSITIONS_LIST}
display_pos = internal_to_display_name_map.get(pos_to_select, internal_to_display_name_map[DEFAULT_INTERNAL_SUBTITLE_POSITION])
translated_pos_names = [internal_to_display_name_map[internal_val] for lang_key, internal_val in SUBTITLE_POSITIONS_LIST]
window['-SUBTITLE_POS_COMBO-'].update(value=display_pos, values=translated_pos_names, size=(38, 4))
def get_alignment_index(key: str) -> int:
"""Returns the index for a given alignment key"""
return next((i for i, (_, v) in enumerate(SUBTITLE_ALIGNMENT_LIST) if v == key), 0)
def update_alignment_combos(window: sg.Window, selected_index1: int | None = None, selected_index2: int | None = None) -> None:
internal_to_display_map = {internal_val: LANG.get(lang_key, internal_val) for lang_key, internal_val in SUBTITLE_ALIGNMENT_LIST}
translated_names = list(internal_to_display_map.values())
idx1 = selected_index1 if selected_index1 is not None else 0
display_val1 = translated_names[idx1] if 0 <= idx1 < len(translated_names) else translated_names[0]
window['--subtitle_alignment'].update(value=display_val1, values=translated_names)
idx2 = selected_index2 if selected_index2 is not None else 0
display_val2 = translated_names[idx2] if 0 <= idx2 < len(translated_names) else translated_names[0]
window['--subtitle_alignment2'].update(value=display_val2, values=translated_names)
def update_alignment_controls(window: sg.Window, values: dict[str, Any]) -> None:
"""Updates the subtitle alignment combo boxes based on current settings."""
is_checked = values.get('enable_subtitle_alignment', False)
is_dual_zone = values.get('--use_dual_zone', False)
window['--subtitle_alignment'].update(disabled=not is_checked)