-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsublens.py
More file actions
2068 lines (1806 loc) · 81 KB
/
Copy pathsublens.py
File metadata and controls
2068 lines (1806 loc) · 81 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
#!/usr/bin/env python3
"""
SubLens - Live game subtitle/dialog translator (PySide6)
Features:
- Fast multi-monitor capture via mss (Pillow fallback)
- LRU translation cache (200 entries)
- Unicode emoji/symbol filter (icons aren't mistaken for text)
- "Stroke" subtitle mode: for outlined game subtitles (RDR2/SM2)
- Advanced adaptive thresholding (bright/complex backgrounds)
- Fast subtitle mode: short interval + hash-based change detection
- Minimal draggable overlay
- Global hotkeys (F2/F3/F4 + Ctrl+Alt+R/T/G/H) - works while game is fullscreen
- Auto-pause: scanning pauses when the game window loses focus
- Glossary: protects proper names and terms from translation
- Automatic mode detection (tries 6 OCR modes and picks the best)
- Minimize to system tray
"""
from __future__ import annotations
import sys
import os
import json
import time
import threading
import urllib.request
import urllib.parse
import urllib.error
import re
import hashlib
import difflib
import unicodedata
import shutil
from collections import OrderedDict
from pathlib import Path
from PIL import (
Image, ImageGrab, ImageEnhance, ImageFilter, ImageStat, ImageChops, ImageOps
)
import pytesseract
try:
import mss # fast screen capture
HAS_MSS = True
except Exception:
HAS_MSS = False
try:
import keyboard # global hotkey
HAS_KEYBOARD = True
except Exception:
HAS_KEYBOARD = False
try:
import win32gui
import win32process
HAS_WIN32 = True
except Exception:
HAS_WIN32 = False
from PySide6.QtCore import Qt, QObject, Signal, QRect, QPoint, QTimer, QSize, QEvent, QUrl
from PySide6.QtGui import (
QPainter, QColor, QPen, QBrush, QFont, QPixmap, QImage, QShortcut,
QKeySequence, QGuiApplication, QCursor, QFontMetrics, QClipboard, QIcon,
QTextCursor, QPalette, QAction, QDesktopServices,
)
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QLabel, QPushButton, QComboBox,
QLineEdit, QCheckBox, QRadioButton, QDoubleSpinBox, QFrame, QHBoxLayout,
QVBoxLayout, QGridLayout, QDialog, QTextBrowser, QTextEdit, QButtonGroup,
QSizePolicy, QSplitter, QGraphicsDropShadowEffect, QMessageBox,
QScrollArea, QToolButton, QSystemTrayIcon, QMenu, QPlainTextEdit,
)
TESSERACT_URL = "https://github.com/UB-Mannheim/tesseract/wiki"
def find_tesseract() -> str | None:
"""Locate the Tesseract binary; return None if not found."""
# 1) Bundled inside a frozen EXE?
if getattr(sys, "frozen", False):
bundled = Path(sys._MEIPASS) / "tesseract" / "tesseract.exe"
if bundled.exists():
tessdata = bundled.parent / "tessdata"
if tessdata.exists():
os.environ["TESSDATA_PREFIX"] = str(tessdata)
return str(bundled)
# 2) Standard Windows install paths
for cand in (
r"C:\Program Files\Tesseract-OCR\tesseract.exe",
r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe",
os.path.expandvars(r"%LOCALAPPDATA%\Programs\Tesseract-OCR\tesseract.exe"),
os.path.expanduser(r"~\AppData\Local\Tesseract-OCR\tesseract.exe"),
):
if cand and Path(cand).exists():
return cand
# 3) On PATH
p = shutil.which("tesseract")
if p:
return p
return None
_tess_path = find_tesseract()
if _tess_path:
pytesseract.pytesseract.tesseract_cmd = _tess_path
APP_NAME = "SubLens"
APP_DIR = Path(os.environ.get("APPDATA") or Path.home()) / APP_NAME
CONFIG_PATH = APP_DIR / "config.json"
LEGACY_CONFIG = Path(os.environ.get("APPDATA") or Path.home()) / "GameTranslator" / "config_qt.json"
OCR_LANG_MAP = {
"English": "eng", "Turkish": "tur", "Japanese": "jpn",
"Korean": "kor", "Chinese": "chi_sim", "French": "fra",
"German": "deu", "Spanish": "spa", "Russian": "rus",
"Italian": "ita", "Portuguese": "por", "Polish": "pol",
"Auto-Detect": "eng",
}
LANGS = ["English", "Turkish", "Japanese", "Korean", "Chinese",
"French", "German", "Spanish", "Russian", "Italian",
"Portuguese", "Polish", "Auto-Detect"]
PSM_OPTIONS = [
"6 - Single text block (recommended)",
"7 - Single line",
"11 - Sparse text",
"13 - Raw line",
]
OCR_MODES = [
("auto", "Automatic"),
("light", "Light text / dark background"),
("dark", "Dark text / light background"),
("subtitle", "Subtitle (top-hat)"),
("stroke", "Outlined subtitle (RDR2/SM2)"),
("equalize", "Complex background (eq)"),
]
# Colors
BG_DARK = "#0d0f14"
BG_CARD = "#1a1e2a"
ACCENT = "#7c6af7"
ACCENT_GLOW = "#9d8fff"
TEXT_PRIMARY = "#e8e6ff"
TEXT_DIM = "#7a7993"
SUCCESS = "#4ecb71"
WARNING = "#f5a623"
ERROR = "#f76a6a"
BORDER = "#252840"
ENGINE_ACCENT = {
"lmstudio": "#9d8fff",
"deepl": "#06c8f0",
"google": "#69a8ff",
}
# -----------------------------------------------------------------------------
# Translation engines (existing logic unchanged)
# -----------------------------------------------------------------------------
class LMStudioEngine:
name = "LM Studio"; key = "lmstudio"
note = "Local AI - No internet needed - Resource heavy"
def __init__(self):
self.url = "http://localhost:1234"
self.model = "local-model"
def translate(self, text, src, tgt, ctx=""):
prompt = (
f"You are a professional game translator. Translate from {src} to {tgt}. "
f"Keep names, preserve tone. Output ONLY the translation.\n"
+ (f"Context: {ctx}\n" if ctx else "")
+ f"Text: {text}\nTranslation:"
)
payload = json.dumps({
"model": self.model,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.3, "max_tokens": 500,
}).encode()
req = urllib.request.Request(
f"{self.url}/v1/chat/completions", data=payload,
headers={"Content-Type": "application/json"}, method="POST")
with urllib.request.urlopen(req, timeout=30) as r:
return json.loads(r.read())["choices"][0]["message"]["content"].strip()
def test(self):
req = urllib.request.Request(f"{self.url}/v1/models",
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=5) as r:
data = json.loads(r.read())
return [m["id"] for m in data.get("data", [])]
class DeepLFreeEngine:
name = "DeepL Free"; key = "deepl"
note = "DeepL free API - 500k characters/month - High quality"
LANG_MAP = {
"Turkish": "TR", "English": "EN-US", "Japanese": "JA", "Korean": "KO",
"Chinese": "ZH", "French": "FR", "German": "DE", "Spanish": "ES",
"Russian": "RU", "Italian": "IT", "Portuguese": "PT-BR", "Polish": "PL",
"Auto-Detect": None,
}
def __init__(self):
self.api_key = ""
def _request(self, url, params, timeout=15):
data = urllib.parse.urlencode(params).encode()
req = urllib.request.Request(url, data=data, headers={
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": f"DeepL-Auth-Key {self.api_key}",
}, method="POST")
for delay in [1, 3, 7, None]:
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read())
except urllib.error.HTTPError as e:
if e.code == 429 and delay is not None:
time.sleep(delay); continue
raise
def translate(self, text, src, tgt, ctx=""):
tgt_code = self.LANG_MAP.get(tgt, tgt.upper())
src_code = self.LANG_MAP.get(src)
params = {"text": text, "target_lang": tgt_code}
if src_code:
params["source_lang"] = src_code[:2]
data = self._request("https://api-free.deepl.com/v2/translate", params)
return data["translations"][0]["text"]
def test(self):
if not self.api_key:
raise ValueError("API key is empty")
u = self._request("https://api-free.deepl.com/v2/usage", {}, timeout=10)
return f"{u['character_count']:,} / {u['character_limit']:,} characters used"
class GoogleFreeEngine:
name = "Google Translate"; key = "google"
note = "Unofficial free API - No API key required"
LANG_MAP = {
"Turkish": "tr", "English": "en", "Japanese": "ja", "Korean": "ko",
"Chinese": "zh", "French": "fr", "German": "de", "Spanish": "es",
"Russian": "ru", "Italian": "it", "Portuguese": "pt", "Polish": "pl",
"Auto-Detect": "auto",
}
def translate(self, text, src, tgt, ctx=""):
sl = self.LANG_MAP.get(src, "auto")
tl = self.LANG_MAP.get(tgt, "tr")
url = ("https://translate.googleapis.com/translate_a/single"
f"?client=gtx&sl={sl}&tl={tl}&dt=t&q={urllib.parse.quote(text)}")
req = urllib.request.Request(url, headers={
"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 Chrome/124.0 Safari/537.36")})
with urllib.request.urlopen(req, timeout=15) as r:
data = json.loads(r.read().decode("utf-8"))
return "".join(seg[0] for seg in data[0] if seg[0])
def test(self):
result = self.translate("Hello world", "English", "Turkish")
if not result:
raise ValueError("Empty response")
return f"'Hello world' -> '{result}'"
# -----------------------------------------------------------------------------
# Screen capture (mss preferred, Pillow fallback)
# -----------------------------------------------------------------------------
class Grabber:
"""Thread-safe screen grabber. mss needs a separate instance per thread."""
def __init__(self):
self._local = threading.local()
def _sct(self):
s = getattr(self._local, "sct", None)
if s is None and HAS_MSS:
# mss >=10: mss.MSS, older: mss.mss
ctor = getattr(mss, "MSS", None) or mss.mss
s = ctor()
self._local.sct = s
return s
def grab(self, region):
x1, y1, x2, y2 = region
if HAS_MSS:
try:
sct = self._sct()
shot = sct.grab({"left": x1, "top": y1, "width": x2 - x1, "height": y2 - y1})
return Image.frombytes("RGB", shot.size, shot.bgra, "raw", "BGRX")
except Exception:
pass
try:
return ImageGrab.grab(bbox=region, all_screens=True)
except TypeError:
return ImageGrab.grab(bbox=region)
GRABBER = Grabber()
# -----------------------------------------------------------------------------
# LRU translation cache
# -----------------------------------------------------------------------------
class LRUCache:
def __init__(self, capacity=200):
self.cap = capacity
self.d = OrderedDict()
def get(self, k):
if k in self.d:
self.d.move_to_end(k)
return self.d[k]
return None
def put(self, k, v):
self.d[k] = v
self.d.move_to_end(k)
if len(self.d) > self.cap:
self.d.popitem(last=False)
# -----------------------------------------------------------------------------
# OCR helpers
# -----------------------------------------------------------------------------
def otsu_threshold(gray: Image.Image) -> int:
hist = gray.histogram()
hist = (hist + [0] * 256)[:256]
total = sum(hist)
if total == 0:
return 128
sum_total = sum(i * hist[i] for i in range(256))
sum_b, w_b, max_var, thr = 0, 0, 0.0, 128
for t in range(256):
w_b += hist[t]
w_f = total - w_b
if w_b == 0 or w_f == 0:
continue
sum_b += t * hist[t]
md = (sum_b / w_b) - ((sum_total - sum_b) / w_f)
var = w_b * w_f * md * md
if var > max_var:
max_var, thr = var, t
return thr
def preprocess(img: Image.Image, scale: int, mode: str) -> Image.Image:
w, h = img.size
img = img.resize((w * scale, h * scale), Image.LANCZOS)
gray = img.convert("L").filter(ImageFilter.MedianFilter(size=3))
if mode == "subtitle":
r = max(10, min(gray.size) // 30)
bg = gray.filter(ImageFilter.GaussianBlur(radius=r))
diff = ImageChops.subtract(gray, bg)
diff = ImageEnhance.Contrast(diff).enhance(2.5)
binary = diff.point(lambda x: 255 if x < 45 else 0)
binary = binary.filter(ImageFilter.MaxFilter(3))
binary = binary.filter(ImageFilter.MinFilter(3))
return binary
if mode == "stroke":
# Outlined game subtitles (RDR2, Spider-Man 2, etc.): bright text +
# dark outline. First find edges, then "fill" inside the outline.
edges = gray.filter(ImageFilter.FIND_EDGES)
edges = ImageEnhance.Contrast(edges).enhance(2.0)
edge_mask = edges.point(lambda x: 255 if x > 60 else 0)
edge_mask = edge_mask.filter(ImageFilter.MaxFilter(3))
# High brightness + proximity to edges = text
bright = gray.point(lambda x: 255 if x > 180 else 0)
# Intersect bright region with edge mask
combined = ImageChops.multiply(bright, edge_mask)
# Invert for Tesseract: text=0, bg=255
result = combined.point(lambda x: 0 if x > 80 else 255)
result = result.filter(ImageFilter.MinFilter(3))
return result
if mode == "equalize":
# Histogram equalization for complex backgrounds
gray = ImageOps.equalize(gray)
gray = ImageEnhance.Contrast(gray).enhance(1.8)
avg = ImageStat.Stat(gray).mean[0]
if avg < 128:
gray = gray.point(lambda x: 255 - x)
t = otsu_threshold(gray)
return gray.point(lambda x: 0 if x < t else 255)
# auto / light / dark
gray = ImageEnhance.Contrast(gray).enhance(2.0)
if mode == "auto":
invert = ImageStat.Stat(gray).mean[0] < 128
elif mode == "light":
invert = True
else:
invert = False
if invert:
gray = gray.point(lambda x: 255 - x)
t = otsu_threshold(gray)
return gray.point(lambda x: 0 if x < t else 255)
def is_noise_word(word: str) -> bool:
"""Is this an emoji/icon/symbol leftover?"""
if not word:
return True
letters = sum(1 for c in word if c.isalpha())
digits = sum(1 for c in word if c.isdigit())
# Pure symbol / emoji
if letters == 0 and digits == 0:
return True
# Drop if symbol category (So = Symbol, other) density is high
sym = sum(1 for c in word if unicodedata.category(c).startswith(("So", "Sk")))
if sym >= max(1, len(word) // 3):
return True
# Single character and not a letter
if len(word) == 1 and not word.isalpha():
return True
return False
def strip_emoji(s: str) -> str:
return "".join(c for c in s if not unicodedata.category(c).startswith(("So", "Sk", "Cn", "Co")))
# -----------------------------------------------------------------------------
# Glossary (term protection) - pre-protect / post-restore
# -----------------------------------------------------------------------------
def parse_glossary(text: str) -> list[tuple[str, str]]:
"""Each line is 'source=target' or just 'source' (do not translate). '#' is a comment."""
out = []
for raw in (text or "").splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
if "=" in line:
src, tgt = line.split("=", 1)
src, tgt = src.strip(), tgt.strip()
else:
src, tgt = line, line
if src:
out.append((src, tgt))
# Match longer terms first (avoid substring conflicts)
out.sort(key=lambda kv: -len(kv[0]))
return out
def protect_terms(text: str, glossary: list[tuple[str, str]]) -> tuple[str, dict[str, str]]:
"""Replace glossary terms with sentinels; return a placeholder->target map."""
if not glossary:
return text, {}
placeholders: dict[str, str] = {}
out = text
for i, (src, tgt) in enumerate(glossary):
token = f"GT{i}" # invisible separator, preserved by most engines
pattern = re.compile(rf"(?i)\b{re.escape(src)}\b")
if pattern.search(out):
out = pattern.sub(token, out)
placeholders[token] = tgt
return out, placeholders
def restore_terms(text: str, placeholders: dict[str, str]) -> str:
for token, tgt in placeholders.items():
text = text.replace(token, tgt)
# If the engine partially swallowed the sentinel, also match the bare 'GT3' pattern
def _fallback(m):
idx = m.group(1)
for tok, tgt in placeholders.items():
if tok.strip("") == f"GT{idx}":
return tgt
return m.group(0)
text = re.sub(r"\bGT(\d+)\b", _fallback, text)
return text
# -----------------------------------------------------------------------------
# Win32 helpers
# -----------------------------------------------------------------------------
def get_foreground_info() -> tuple[int, int, str]:
"""Active window (hwnd, pid, title). Returns (0,0,'') if win32 is missing."""
if not HAS_WIN32:
return 0, 0, ""
try:
hwnd = win32gui.GetForegroundWindow()
_, pid = win32process.GetWindowThreadProcessId(hwnd)
title = win32gui.GetWindowText(hwnd) or ""
return hwnd, pid, title
except Exception:
return 0, 0, ""
# -----------------------------------------------------------------------------
# Tray icon (no asset required, drawn at runtime)
# -----------------------------------------------------------------------------
def make_tray_icon(active: bool = False) -> QIcon:
pm = QPixmap(32, 32)
pm.fill(Qt.transparent)
p = QPainter(pm)
p.setRenderHint(QPainter.Antialiasing)
bg = QColor(SUCCESS if active else ACCENT)
p.setBrush(QBrush(bg))
p.setPen(QPen(QColor(BG_DARK), 2))
p.drawRoundedRect(2, 2, 28, 28, 7, 7)
p.setPen(QPen(QColor(BG_DARK)))
p.setFont(QFont("Segoe UI", 14, QFont.Black))
p.drawText(pm.rect(), Qt.AlignCenter, "S")
p.end()
return QIcon(pm)
# -----------------------------------------------------------------------------
# Region Selector
# -----------------------------------------------------------------------------
class RegionSelector(QWidget):
selected = Signal(tuple)
def __init__(self):
super().__init__(None)
self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.Tool)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setCursor(Qt.CrossCursor)
# Cover the entire virtual desktop
geo = QRect()
for scr in QGuiApplication.screens():
geo = geo.united(scr.geometry())
self.setGeometry(geo)
self._origin_screen = geo.topLeft()
self._start = None
self._end = None
self._dragging = False
def paintEvent(self, _):
p = QPainter(self)
p.fillRect(self.rect(), QColor(0, 0, 0, 110))
# Top text
p.setFont(QFont("Segoe UI", 14, QFont.Bold))
p.setPen(QColor(ACCENT_GLOW))
p.drawText(self.rect().adjusted(0, 30, 0, 0), Qt.AlignHCenter | Qt.AlignTop,
"Select the dialog box · ESC = Cancel")
if self._start and self._end:
r = QRect(self._start, self._end).normalized()
# Clear the selection area
p.setCompositionMode(QPainter.CompositionMode_Clear)
p.fillRect(r, Qt.transparent)
p.setCompositionMode(QPainter.CompositionMode_SourceOver)
pen = QPen(QColor(ACCENT_GLOW), 2)
p.setPen(pen)
p.setBrush(Qt.NoBrush)
p.drawRect(r)
# Size label
p.setFont(QFont("Consolas", 10, QFont.Bold))
p.setPen(QColor(TEXT_PRIMARY))
p.drawText(r.adjusted(6, -22, 0, 0), Qt.AlignLeft | Qt.AlignTop,
f"{r.width()} × {r.height()}")
def mousePressEvent(self, e):
if e.button() == Qt.LeftButton:
self._start = e.position().toPoint()
self._end = self._start
self._dragging = True
self.update()
def mouseMoveEvent(self, e):
if self._dragging:
self._end = e.position().toPoint()
self.update()
def mouseReleaseEvent(self, e):
if e.button() != Qt.LeftButton or not self._dragging:
return
self._dragging = False
self._end = e.position().toPoint()
r = QRect(self._start, self._end).normalized()
if r.width() < 20 or r.height() < 10:
self.close()
return
ox, oy = self._origin_screen.x(), self._origin_screen.y()
self.selected.emit((r.left() + ox, r.top() + oy,
r.right() + ox, r.bottom() + oy))
self.close()
def keyPressEvent(self, e):
if e.key() == Qt.Key_Escape:
self.close()
# -----------------------------------------------------------------------------
# Overlay
# -----------------------------------------------------------------------------
class OverlayWindow(QWidget):
def __init__(self, engine_key="google"):
super().__init__(None)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool)
self.setAttribute(Qt.WA_TranslucentBackground)
self.engine_key = engine_key
self._drag_pos = None
accent = ENGINE_ACCENT.get(engine_key, ACCENT)
# Rounded-corner card
self.card = QFrame(self)
self.card.setObjectName("card")
self.card.setStyleSheet(f"""
QFrame#card {{
background: rgba(13, 15, 20, 230);
border: 1px solid {accent};
border-radius: 10px;
}}
""")
shadow = QGraphicsDropShadowEffect(self.card)
shadow.setBlurRadius(28)
shadow.setOffset(0, 6)
shadow.setColor(QColor(0, 0, 0, 180))
self.card.setGraphicsEffect(shadow)
outer = QVBoxLayout(self)
outer.setContentsMargins(14, 14, 14, 14)
outer.addWidget(self.card)
v = QHBoxLayout(self.card)
v.setContentsMargins(14, 10, 10, 10)
v.setSpacing(6)
self.lbl = QLabel("...")
self.lbl.setWordWrap(True)
self.lbl.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
self.lbl.setStyleSheet(
f"color: {TEXT_PRIMARY}; background: transparent; "
f"font: 13pt 'Segoe UI';")
self.lbl.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
v.addWidget(self.lbl, 1)
close_btn = QToolButton()
close_btn.setText("✕")
close_btn.setCursor(Qt.PointingHandCursor)
close_btn.setStyleSheet(
f"QToolButton {{ color: {TEXT_DIM}; background: transparent; "
f"border: none; font: bold 11pt; padding: 0 4px; }} "
f"QToolButton:hover {{ color: {ERROR}; }}")
close_btn.clicked.connect(self.hide)
v.addWidget(close_btn, 0, Qt.AlignTop)
self.resize(480, 90)
def set_engine(self, key: str):
self.engine_key = key
accent = ENGINE_ACCENT.get(key, ACCENT)
self.card.setStyleSheet(f"""
QFrame#card {{
background: rgba(13, 15, 20, 230);
border: 1px solid {accent};
border-radius: 10px;
}}
""")
def set_text(self, text: str, region=None):
self.lbl.setText(text)
scr = QGuiApplication.primaryScreen().virtualGeometry()
if region:
w = max(420, min(region[2] - region[0] + 40, scr.width() - 40))
else:
w = self.width()
self.lbl.setFixedWidth(w - 80)
h_lbl = self.lbl.sizeHint().height()
h = h_lbl + 48
if region:
rx1, ry1, rx2, _ = region
x = max(scr.left(), min(rx1 - 10, scr.right() - w))
y = ry1 - h - 8
if y < scr.top():
y = region[3] + 8
y = max(scr.top(), min(y, scr.bottom() - h - 4))
else:
x, y = self.x(), self.y()
self.setGeometry(x, y, w, h)
self.show()
self.raise_()
def mousePressEvent(self, e):
if e.button() == Qt.LeftButton:
self._drag_pos = e.globalPosition().toPoint() - self.frameGeometry().topLeft()
def mouseMoveEvent(self, e):
if self._drag_pos and e.buttons() & Qt.LeftButton:
self.move(e.globalPosition().toPoint() - self._drag_pos)
def mouseReleaseEvent(self, _):
self._drag_pos = None
# -----------------------------------------------------------------------------
# Bridge (thread -> UI signals)
# -----------------------------------------------------------------------------
class Bridge(QObject):
log = Signal(str, str)
result = Signal(str)
status = Signal(str, str)
preview = Signal(QPixmap)
models = Signal(list)
show_overlay = Signal(str)
# Fired from global hotkeys (kbd thread -> UI thread)
trigger_pick = Signal()
trigger_once = Signal()
trigger_toggle = Signal()
trigger_hide_overlay = Signal()
# -----------------------------------------------------------------------------
# Main Window
# -----------------------------------------------------------------------------
class MainWindow(QMainWindow):
ENGINES = {
"lmstudio": LMStudioEngine(),
"deepl": DeepLFreeEngine(),
"google": GoogleFreeEngine(),
}
def __init__(self):
super().__init__()
self.setWindowTitle("SubLens")
self.resize(620, 720)
self.setMinimumSize(540, 560)
cfg = self._load_config()
self.engine_key = cfg.get("engine_key", "google")
self.region = tuple(cfg["region"]) if isinstance(cfg.get("region"), list) and len(cfg["region"]) == 4 else None
self.lm_url = cfg.get("lm_url", "http://localhost:1234")
self.lm_model = cfg.get("lm_model", "local-model")
self.deepl_key = cfg.get("deepl_key", "")
self.ctx = cfg.get("ctx", "")
self.interval = float(cfg.get("interval", 1.5))
self.show_overlay_opt = bool(cfg.get("show_overlay", True))
self.ocr_scale = int(cfg.get("ocr_scale", 3))
self.ocr_mode = cfg.get("ocr_mode", "auto")
self.ocr_psm = cfg.get("ocr_psm", PSM_OPTIONS[0])
if self.ocr_psm not in PSM_OPTIONS:
self.ocr_psm = PSM_OPTIONS[0]
self.src_lang = cfg.get("src_lang", "English")
self.tgt_lang = cfg.get("tgt_lang", "Turkish")
self.fast_mode = bool(cfg.get("fast_mode", False))
# New features
self.global_hotkeys_on = bool(cfg.get("global_hotkeys", HAS_KEYBOARD))
self.auto_pause_on = bool(cfg.get("auto_pause", HAS_WIN32))
self.minimize_to_tray = bool(cfg.get("minimize_to_tray", True))
self.glossary_text = cfg.get("glossary", "")
self.glossary = parse_glossary(self.glossary_text)
self.running = False
self._paused = False # auto-pause state (thread keeps running, OCR is skipped)
self._stop_evt = threading.Event()
self.last_text = ""
self.last_hash = ""
self.overlay: OverlayWindow | None = None
self._cache = LRUCache(200)
self._region_selector: RegionSelector | None = None
self._target_hwnd = 0 # auto-pause target window
self._self_pid = os.getpid()
self._registered_hotkeys: list = []
self._tray: QSystemTrayIcon | None = None
self._force_quit = False
self.bridge = Bridge()
self.bridge.log.connect(self._append_log)
self.bridge.status.connect(self._set_status)
self.bridge.preview.connect(self._set_preview)
self.bridge.models.connect(self._apply_models)
self.bridge.show_overlay.connect(self._show_overlay)
self.bridge.trigger_pick.connect(self._pick_region)
self.bridge.trigger_once.connect(self._translate_once)
self.bridge.trigger_toggle.connect(self._toggle_scan)
self.bridge.trigger_hide_overlay.connect(self._hide_overlay)
self._build_ui()
self._apply_style()
self._switch_engine(self.engine_key)
self._bind_shortcuts()
self._update_start_state()
# Connect the signal after the UI is built
self.bridge.result.connect(self.result_lbl.setText)
# Tray
self._setup_tray()
# Global hotkeys
if self.global_hotkeys_on:
self._register_global_hotkeys()
# Auto-pause QTimer (every 800 ms)
self._pause_timer = QTimer(self)
self._pause_timer.setInterval(800)
self._pause_timer.timeout.connect(self._check_auto_pause)
if self.auto_pause_on:
self._pause_timer.start()
if self.region:
self._update_region_label()
QTimer.singleShot(250, self._refresh_preview)
# -- Style ---------------------------------------------------------------
def _apply_style(self):
self.setStyleSheet(f"""
QMainWindow, QDialog {{ background: {BG_DARK}; }}
QWidget {{ color: {TEXT_PRIMARY}; font-family: 'Segoe UI'; font-size: 10pt; }}
QLabel#title {{ font: bold 20pt 'Segoe UI'; color: {ACCENT}; }}
QLabel#title2 {{ font: bold 20pt 'Segoe UI'; color: {TEXT_PRIMARY}; }}
QLabel.section {{ color: {TEXT_DIM}; font: bold 9pt 'Consolas'; letter-spacing: 1px; }}
QLabel.dim {{ color: {TEXT_DIM}; }}
QLineEdit, QComboBox, QDoubleSpinBox {{
background: {BG_CARD}; color: {TEXT_PRIMARY}; border: 1px solid {BORDER};
border-radius: 6px; padding: 5px 8px; selection-background-color: {ACCENT};
}}
QLineEdit:focus, QComboBox:focus, QDoubleSpinBox:focus {{
border: 1px solid {ACCENT};
}}
QComboBox::drop-down {{ border: none; width: 18px; }}
QComboBox QAbstractItemView {{
background: {BG_CARD}; color: {TEXT_PRIMARY};
selection-background-color: {ACCENT}; border: 1px solid {BORDER};
}}
QPushButton {{
background: {ACCENT}; color: {BG_DARK}; border: none; border-radius: 6px;
padding: 7px 14px; font: bold 9pt 'Segoe UI';
}}
QPushButton:hover {{ background: {ACCENT_GLOW}; }}
QPushButton:disabled {{ background: {BORDER}; color: {TEXT_DIM}; }}
QPushButton.secondary {{ background: {BG_CARD}; color: {TEXT_PRIMARY}; }}
QPushButton.secondary:hover {{ background: {BORDER}; }}
QPushButton.success {{ background: {SUCCESS}; color: {BG_DARK}; }}
QPushButton.warning {{ background: {WARNING}; color: {BG_DARK}; }}
QFrame.sep {{ background: {BORDER}; max-height: 1px; min-height: 1px; border: none; }}
QFrame.accentBar {{ background: {ACCENT}; max-height: 2px; min-height: 2px; }}
QFrame.card {{ background: {BG_CARD}; border-radius: 8px; }}
QCheckBox, QRadioButton {{ color: {TEXT_DIM}; spacing: 6px; }}
QCheckBox::indicator, QRadioButton::indicator {{ width: 14px; height: 14px; }}
QCheckBox::indicator:unchecked, QRadioButton::indicator:unchecked {{
background: {BG_CARD}; border: 1px solid {BORDER}; border-radius: 3px;
}}
QCheckBox::indicator:checked, QRadioButton::indicator:checked {{
background: {ACCENT}; border: 1px solid {ACCENT}; border-radius: 3px;
}}
QTextEdit, QTextBrowser {{
background: {BG_CARD}; color: {TEXT_PRIMARY}; border: 1px solid {BORDER};
border-radius: 6px; padding: 8px; font-family: 'Consolas'; font-size: 9pt;
}}
QScrollBar:vertical {{ background: {BG_DARK}; width: 10px; }}
QScrollBar::handle:vertical {{ background: {BORDER}; border-radius: 5px; min-height: 20px; }}
QScrollBar::handle:vertical:hover {{ background: {ACCENT}; }}
QScrollBar::add-line, QScrollBar::sub-line {{ height: 0; }}
""")
# -- UI build ------------------------------------------------------------
def _build_ui(self):
central = QWidget()
self.setCentralWidget(central)
root = QVBoxLayout(central)
root.setContentsMargins(20, 18, 20, 16)
root.setSpacing(10)
# Header
hdr = QHBoxLayout()
t1 = QLabel("SUB"); t1.setObjectName("title")
t2 = QLabel("LENS"); t2.setObjectName("title2")
hdr.addWidget(t1); hdr.addWidget(t2); hdr.addStretch(1)
self.info_btn = QPushButton("ⓘ Info")
self.info_btn.setProperty("class", "secondary"); self.info_btn.setObjectName("infoBtn")
self.info_btn.setStyleSheet(f"background: {BG_CARD}; color: {TEXT_DIM};")
self.info_btn.clicked.connect(self._open_info)
self.settings_btn = QPushButton("⚙ Settings")
self.settings_btn.setStyleSheet(f"background: {BG_CARD}; color: {TEXT_DIM};")
self.settings_btn.clicked.connect(self._open_settings)
hdr.addWidget(self.info_btn); hdr.addWidget(self.settings_btn)
root.addLayout(hdr)
bar = QFrame(); bar.setProperty("class", "accentBar")
bar.setStyleSheet(f"background: {ACCENT}; max-height: 2px;")
root.addWidget(bar)
# -- Quick-start card (collapsible) --
self.help_toggle = QToolButton()
self.help_toggle.setText("\U0001f4a1 Quick start (show)")
self.help_toggle.setCursor(Qt.PointingHandCursor)
self.help_toggle.setStyleSheet(
f"QToolButton {{ color: {TEXT_DIM}; background: transparent; border: none; "
f"font: 9pt 'Consolas'; padding: 2px 0; text-align: left; }} "
f"QToolButton:hover {{ color: {ACCENT_GLOW}; }}")
self.help_toggle.clicked.connect(self._toggle_help)
root.addWidget(self.help_toggle)
self.help_card = QLabel(self._help_text())
self.help_card.setWordWrap(True)
self.help_card.setTextFormat(Qt.RichText)
self.help_card.setStyleSheet(
f"background: {BG_CARD}; color: {TEXT_PRIMARY}; padding: 10px 14px; "
f"border-left: 3px solid {ACCENT}; border-radius: 6px; font: 9pt 'Segoe UI';")
self.help_card.hide()
root.addWidget(self.help_card)
# Engine selection
eng = QHBoxLayout()
lab = QLabel("Engine:"); lab.setStyleSheet(f"color: {TEXT_DIM};")
eng.addWidget(lab)
self.engine_btns = {}
for key, e in self.ENGINES.items():
b = QPushButton(e.name)
b.setCursor(Qt.PointingHandCursor)
b.clicked.connect(lambda _=False, k=key: self._switch_engine(k))
eng.addWidget(b)
self.engine_btns[key] = b
eng.addStretch(1)
root.addLayout(eng)
self.status_lbl = QLabel(""); self.status_lbl.setStyleSheet(f"color: {TEXT_DIM};")
root.addWidget(self.status_lbl)
root.addWidget(self._sep())
# Language selection
lang = QHBoxLayout()
lang.addWidget(self._dim("Language:"))
self.src_combo = QComboBox(); self.src_combo.addItems(LANGS)
self.src_combo.setCurrentText(self.src_lang if self.src_lang in LANGS else "English")
lang.addWidget(self.src_combo)
arrow = QLabel("→"); arrow.setStyleSheet(f"color: {ACCENT}; font: bold 14pt;")
lang.addWidget(arrow)
self.tgt_combo = QComboBox(); self.tgt_combo.addItems(LANGS[:-1])
self.tgt_combo.setCurrentText(self.tgt_lang if self.tgt_lang in LANGS[:-1] else "Turkish")
lang.addWidget(self.tgt_combo)
lang.addStretch(1)
root.addLayout(lang)
root.addWidget(self._sep())
# Region
reg = QHBoxLayout()
self.pick_btn = QPushButton("\U0001f4d0 Pick Region (F2)")
self.pick_btn.clicked.connect(self._pick_region)
reg.addWidget(self.pick_btn)
self.auto_mode_btn = QPushButton("✨ Find Mode")
self.auto_mode_btn.setToolTip(
"Automatically picks the best OCR mode for the selected region "
"(tries 6 modes and chooses the one with the highest confidence)")
self.auto_mode_btn.setStyleSheet(f"background: {BG_CARD}; color: {TEXT_PRIMARY};")
self.auto_mode_btn.clicked.connect(self._auto_detect_mode)
reg.addWidget(self.auto_mode_btn)
self.region_lbl = QLabel("Not selected yet")
self.region_lbl.setStyleSheet(f"color: {TEXT_DIM};")
reg.addWidget(self.region_lbl); reg.addStretch(1)
root.addLayout(reg)
self.preview = QLabel("Preview will appear here once a region is selected")
self.preview.setAlignment(Qt.AlignCenter)
self.preview.setMinimumHeight(80)
self.preview.setStyleSheet(
f"background: {BG_CARD}; color: {TEXT_DIM}; border-radius: 6px; padding: 6px;")
root.addWidget(self.preview)
root.addWidget(self._sep())
# Controls
ctrl = QHBoxLayout()
self.start_btn = QPushButton("▶ START (F4)")
self.start_btn.setProperty("class", "success")
self.start_btn.setStyleSheet(f"background: {SUCCESS}; color: {BG_DARK};")
self.start_btn.clicked.connect(self._toggle_scan)
ctrl.addWidget(self.start_btn)
once = QPushButton("✦ Once (F3)")
once.clicked.connect(self._translate_once)
ctrl.addWidget(once)
ctrl.addWidget(self._dim("Interval:"))
self.interval_spin = QDoubleSpinBox()
self.interval_spin.setRange(0.3, 15.0); self.interval_spin.setSingleStep(0.1)
self.interval_spin.setDecimals(1); self.interval_spin.setValue(self.interval)
self.interval_spin.setFixedWidth(70)
ctrl.addWidget(self.interval_spin)
ctrl.addWidget(self._dim("s"))
self.overlay_cb = QCheckBox("Overlay"); self.overlay_cb.setChecked(self.show_overlay_opt)