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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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
# ocr_manager.py
"""

OCR Manager for handling multiple OCR providers

Handles installation, model downloading, and OCR processing

Updated with HuggingFace donut model and proper bubble detection integration

"""
import os
import sys
import cv2
import json
import subprocess
import threading
import traceback
from typing import List, Dict, Optional, Tuple, Any
import numpy as np
from dataclasses import dataclass
from PIL import Image
import logging
import time
import random
import base64
import io
import requests

# Lazy import flags - don't import torch dependencies at module level
# This prevents PyInstaller from loading torch DLLs before proper initialization
HAS_GPTQ = None
HAS_OPTIMUM = None
HAS_ACCELERATE = None

def _check_accelerate():
    """Lazy check for accelerate availability"""
    global HAS_ACCELERATE
    if HAS_ACCELERATE is None:
        try:
            import accelerate
            HAS_ACCELERATE = True
        except ImportError:
            HAS_ACCELERATE = False
    return HAS_ACCELERATE

def _check_gptq():
    """Lazy check for GPTQ availability"""
    global HAS_GPTQ
    if HAS_GPTQ is None:
        try:
            import gptqmodel
            HAS_GPTQ = True
        except ImportError:
            try:
                import auto_gptq
                HAS_GPTQ = True
            except ImportError:
                HAS_GPTQ = False
    return HAS_GPTQ

def _check_optimum():
    """Lazy check for optimum availability"""
    global HAS_OPTIMUM
    if HAS_OPTIMUM is None:
        try:
            import optimum
            HAS_OPTIMUM = True
        except ImportError:
            HAS_OPTIMUM = False
    return HAS_OPTIMUM

logger = logging.getLogger(__name__)

@dataclass
class OCRResult:
    """Unified OCR result format with built-in sanitization to prevent data corruption."""
    text: str
    bbox: Tuple[int, int, int, int]  # x, y, w, h
    confidence: float
    vertices: Optional[List[Tuple[int, int]]] = None

    def __post_init__(self):
        """

        This special method is called automatically after the object is created.

        It acts as a final safeguard to ensure the 'text' attribute is ALWAYS a clean string.

        """
        # --- THIS IS THE DEFINITIVE FIX ---
        # If the text we received is a tuple, we extract the first element.
        # This makes it impossible for a tuple to exist in a finished object.
        if isinstance(self.text, tuple):
            # Log that we are fixing a critical data error.
            print(f"CRITICAL WARNING: Corrupted tuple detected in OCRResult. Sanitizing '{self.text}' to '{self.text[0]}'.")
            self.text = self.text[0]
        
        # Ensure the final result is always a stripped string.
        self.text = str(self.text).strip()
    
class OCRProvider:
    """Base class for OCR providers"""
    
    def __init__(self, log_callback=None):
        # Set thread limits early if environment indicates single-threaded mode
        try:
            if os.environ.get('OMP_NUM_THREADS') == '1':
                # Already in single-threaded mode, ensure it's applied to this process
                try:
                    import sys
                    if 'torch' in sys.modules:
                        import torch
                        torch.set_num_threads(1)
                except (ImportError, RuntimeError, AttributeError):
                    pass
                try:
                    import cv2
                    cv2.setNumThreads(1)
                except (ImportError, AttributeError):
                    pass
        except Exception:
            pass
        
        self.log_callback = log_callback
        self.is_installed = False
        self.is_loaded = False
        self.model = None
        self.stop_flag = None
        self._stopped = False
        
    def _log(self, message: str, level: str = "info"):
        """Log message with stop suppression"""
        # Suppress logs when stopped (allow only essential stop confirmation messages)
        if self._check_stop():
            essential_stop_keywords = [
                "⏹️ Translation stopped by user",
                "⏹️ OCR processing stopped",
                "cleanup", "🧹"
            ]
            if not any(keyword in message for keyword in essential_stop_keywords):
                return
        
        if self.log_callback:
            self.log_callback(message, level)
        else:
            print(f"[{level.upper()}] {message}")
    
    def set_stop_flag(self, stop_flag):
        """Set the stop flag for checking interruptions"""
        self.stop_flag = stop_flag
        self._stopped = False
    
    def _check_stop(self) -> bool:
        """Check if stop has been requested"""
        if self._stopped:
            return True
        if self.stop_flag and self.stop_flag.is_set():
            self._stopped = True
            return True
        # Check global manga translator cancellation
        try:
            from manga_translator import MangaTranslator
            if MangaTranslator.is_globally_cancelled():
                self._stopped = True
                return True
        except Exception:
            pass
        return False
    
    def reset_stop_flags(self):
        """Reset stop flags when starting new processing"""
        self._stopped = False
    
    def check_installation(self) -> bool:
        """Check if provider is installed"""
        raise NotImplementedError
    
    def install(self, progress_callback=None) -> bool:
        """Install the provider"""
        raise NotImplementedError
    
    def load_model(self, **kwargs) -> bool:
        """Load the OCR model"""
        raise NotImplementedError
    
    def detect_text(self, image: np.ndarray, **kwargs) -> List[OCRResult]:
        """Detect text in image"""
        raise NotImplementedError

class CustomAPIProvider(OCRProvider):
    """Custom API OCR provider that uses existing GUI variables"""
    
    def __init__(self, log_callback=None):
        super().__init__(log_callback)
        
        # Use EXISTING environment variables from TranslatorGUI
        self.api_url = os.environ.get('OPENAI_CUSTOM_BASE_URL', '')
        self.api_key = os.environ.get('API_KEY', '') or os.environ.get('OPENAI_API_KEY', '')
        self.model_name = os.environ.get('MODEL', 'gpt-4o-mini')
        
        # OCR prompt - use system prompt or a dedicated OCR prompt variable
        self.ocr_prompt = os.environ.get('OCR_SYSTEM_PROMPT', 
            os.environ.get('SYSTEM_PROMPT', 
            "YOU ARE A TEXT EXTRACTION MACHINE. EXTRACT EXACTLY WHAT YOU SEE.\n\n"
            "ABSOLUTE RULES:\n"
            "1. OUTPUT ONLY THE VISIBLE TEXT/SYMBOLS - NOTHING ELSE\n"
            "2. NEVER TRANSLATE OR MODIFY\n"
            "3. NEVER EXPLAIN, DESCRIBE, OR COMMENT\n"
            "4. NEVER SAY \"I can't\" or \"I cannot\" or \"no text\" or \"blank image\"\n"
            "5. IF YOU SEE DOTS, OUTPUT THE DOTS: .\n"
            "6. IF YOU SEE PUNCTUATION, OUTPUT THE PUNCTUATION\n"
            "7. IF YOU SEE A SINGLE CHARACTER, OUTPUT THAT CHARACTER\n"
            "8. IF YOU SEE NOTHING, OUTPUT NOTHING (empty response)\n\n"
            "LANGUAGE PRESERVATION:\n"
            "- Korean text β†’ Output in Korean\n"
            "- Japanese text β†’ Output in Japanese\n"
            "- Chinese text β†’ Output in Chinese\n"
            "- English text β†’ Output in English\n"
            "- CJK quotation marks (γ€Œγ€γ€Žγ€γ€γ€‘γ€Šγ€‹γ€ˆγ€‰) β†’ Preserve exactly as shown\n\n"
            "FORMATTING:\n"
            "- OUTPUT ALL TEXT ON A SINGLE LINE WITH NO LINE BREAKS\n"
            "- NEVER use \\n or line breaks in your output\n\n"
            "FORBIDDEN RESPONSES:\n"
            "- \"I can see this appears to be...\"\n"
            "- \"I cannot make out any clear text...\"\n"
            "- \"This appears to be blank...\"\n"
            "- \"If there is text present...\"\n"
            "- ANY explanatory text\n\n"
            "YOUR ONLY OUTPUT: The exact visible text. Nothing more. Nothing less.\n"
            "If image has a dot β†’ Output: .\n"
            "If image has two dots β†’ Output: . .\n"
            "If image has text β†’ Output: [that text]\n"
            "If image is truly blank β†’ Output: [empty/no response]"
            ))
        
        # Use existing temperature and token settings  
        self.temperature = float(os.environ.get('TRANSLATION_TEMPERATURE', '0.01'))
        # NOTE: max_tokens is NOT cached here - it's read fresh from environment in detect_text()
        # to ensure we always get the latest value from the GUI
        
        # Image settings from existing compression variables
        self.image_format = 'jpeg' if os.environ.get('IMAGE_COMPRESSION_FORMAT', 'auto') != 'png' else 'png'
        self.image_quality = int(os.environ.get('JPEG_QUALITY', '100'))
        
        # Simple defaults
        self.api_format = 'openai'  # Most custom endpoints are OpenAI-compatible
        self.timeout = int(os.environ.get('CHUNK_TIMEOUT', '30'))
        self.api_headers = {}  # Additional custom headers
        
        # Retry configuration for Custom API OCR calls
        self.max_retries = int(os.environ.get('CUSTOM_OCR_MAX_RETRIES', '3'))
        self.retry_initial_delay = float(os.environ.get('CUSTOM_OCR_RETRY_INITIAL_DELAY', '0.8'))
        self.retry_backoff = float(os.environ.get('CUSTOM_OCR_RETRY_BACKOFF', '1.8'))
        self.retry_jitter = float(os.environ.get('CUSTOM_OCR_RETRY_JITTER', '0.4'))
        self.retry_on_empty = os.environ.get('CUSTOM_OCR_RETRY_ON_EMPTY', '1') == '1'
        
    def check_installation(self) -> bool:
        """Always installed - uses UnifiedClient"""
        self.is_installed = True
        return True
    
    def install(self, progress_callback=None) -> bool:
        """No installation needed for API-based provider"""
        return self.check_installation()
    
    def load_model(self, **kwargs) -> bool:
        """Initialize UnifiedClient with current settings"""
        try:
            from unified_api_client import UnifiedClient
            
            # Support passing API key from GUI if available
            if 'api_key' in kwargs:
                api_key = kwargs['api_key']
            else:
                api_key = os.environ.get('API_KEY', '') or os.environ.get('OPENAI_API_KEY', '')
            
            if 'model' in kwargs:
                model = kwargs['model']
            else:
                model = os.environ.get('MODEL', 'gpt-4o-mini')
            
            if not api_key:
                self._log("❌ No API key configured", "error")
                return False
            
            # Create UnifiedClient just like translations do
            self.client = UnifiedClient(model=model, api_key=api_key)
            
            #self._log(f"βœ… Using {model} for OCR via UnifiedClient")
            self.is_loaded = True
            return True
            
        except Exception as e:
            self._log(f"❌ Failed to initialize UnifiedClient: {str(e)}", "error")
            return False
    
    def _test_connection(self) -> bool:
        """Test API connection with a simple request"""
        try:
            # Create a small test image
            test_image = np.ones((100, 100, 3), dtype=np.uint8) * 255
            cv2.putText(test_image, "TEST", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2)
            
            # Encode image
            image_base64 = self._encode_image(test_image)
            
            # Prepare test request based on API format
            if self.api_format == 'openai':
                test_payload = {
                    "model": self.model_name,
                    "messages": [
                        {
                            "role": "user",
                            "content": [
                                {"type": "text", "text": "What text do you see?"},
                                {"type": "image_url", "image_url": {"url": f"data:image/{self.image_format};base64,{image_base64}"}}
                            ]
                        }
                    ],
                    "max_tokens": 50
                }
            else:
                # For other formats, just try a basic health check
                return True
            
            headers = self._prepare_headers()
            response = requests.post(
                self.api_url,
                headers=headers,
                json=test_payload,
                timeout=10
            )
            
            return response.status_code == 200
            
        except Exception:
            return False
    
    def _encode_image(self, image: np.ndarray) -> str:
        """Encode numpy array to base64 string"""
        # Convert BGR to RGB if needed
        if len(image.shape) == 3 and image.shape[2] == 3:
            image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        else:
            image_rgb = image
        
        # Convert to PIL Image
        pil_image = Image.fromarray(image_rgb)
        
        # Save to bytes buffer
        buffer = io.BytesIO()
        if self.image_format.lower() == 'png':
            pil_image.save(buffer, format='PNG')
        else:
            pil_image.save(buffer, format='JPEG', quality=self.image_quality)
        
        # Encode to base64
        buffer.seek(0)
        image_base64 = base64.b64encode(buffer.read()).decode('utf-8')
        
        return image_base64
    
    def _prepare_headers(self) -> dict:
        """Prepare request headers"""
        headers = {
            "Content-Type": "application/json"
        }
        
        # Add API key if configured
        if self.api_key:
            if self.api_format == 'anthropic':
                headers["x-api-key"] = self.api_key
            else:
                headers["Authorization"] = f"Bearer {self.api_key}"
        
        # Add any custom headers
        headers.update(self.api_headers)
        
        return headers
    
    def _prepare_request_payload(self, image_base64: str) -> dict:
        """Prepare request payload based on API format"""
        if self.api_format == 'openai':
            return {
                "model": self.model_name,
                "messages": [
                    {
                        "role": "user",
                        "content": [
                            {"type": "text", "text": self.ocr_prompt},
                            {
                                "type": "image_url",
                                "image_url": {
                                    "url": f"data:image/{self.image_format};base64,{image_base64}"
                                }
                            }
                        ]
                    }
                ],
                "max_tokens": self.max_tokens,
                "temperature": self.temperature
            }
        
        elif self.api_format == 'anthropic':
            return {
                "model": self.model_name,
                "max_tokens": self.max_tokens,
                "temperature": self.temperature,
                "messages": [
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "text",
                                "text": self.ocr_prompt
                            },
                            {
                                "type": "image",
                                "source": {
                                    "type": "base64",
                                    "media_type": f"image/{self.image_format}",
                                    "data": image_base64
                                }
                            }
                        ]
                    }
                ]
            }
        
        else:
            # Custom format - use environment variable for template
            template = os.environ.get('CUSTOM_OCR_REQUEST_TEMPLATE', '{}')
            payload = json.loads(template)
            
            # Replace placeholders
            payload_str = json.dumps(payload)
            payload_str = payload_str.replace('{{IMAGE_BASE64}}', image_base64)
            payload_str = payload_str.replace('{{PROMPT}}', self.ocr_prompt)
            payload_str = payload_str.replace('{{MODEL}}', self.model_name)
            payload_str = payload_str.replace('{{MAX_TOKENS}}', str(self.max_tokens))
            payload_str = payload_str.replace('{{TEMPERATURE}}', str(self.temperature))
            
            return json.loads(payload_str)
    
    def _extract_text_from_response(self, response_data: dict) -> str:
        """Extract text from API response based on format"""
        try:
            if self.api_format == 'openai':
                # OpenAI format: response.choices[0].message.content
                return response_data.get('choices', [{}])[0].get('message', {}).get('content', '')
            
            elif self.api_format == 'anthropic':
                # Anthropic format: response.content[0].text
                content = response_data.get('content', [])
                if content and isinstance(content, list):
                    return content[0].get('text', '')
                return ''
            
            else:
                # Custom format - use environment variable for path
                response_path = os.environ.get('CUSTOM_OCR_RESPONSE_PATH', 'text')
                
                # Navigate through the response using the path
                result = response_data
                for key in response_path.split('.'):
                    if isinstance(result, dict):
                        result = result.get(key, '')
                    elif isinstance(result, list) and key.isdigit():
                        idx = int(key)
                        result = result[idx] if idx < len(result) else ''
                    else:
                        result = ''
                        break
                
                return str(result)
                
        except Exception as e:
            self._log(f"Failed to extract text from response: {e}", "error")
            return ''
    
    def detect_text(self, image: np.ndarray, **kwargs) -> List[OCRResult]:
        """Process image using UnifiedClient.send_image()"""
        results = []
        
        try:
            # CRITICAL: Reload OCR prompt from environment before each detection
            # This ensures we use the latest prompt set by manga_integration.py
            self.ocr_prompt = os.environ.get('OCR_SYSTEM_PROMPT', self.ocr_prompt)
            
            # Get fresh max_tokens from environment - GUI will have set this
            max_tokens = int(os.environ.get('MAX_OUTPUT_TOKENS', '8192'))
            if not self.is_loaded:
                if not self.load_model():
                    return results
            
            import cv2
            from PIL import Image
            import base64
            import io
            
            # Validate and resize image if too small (consistent with Google/Azure logic)
            h, w = image.shape[:2]
            MIN_SIZE = 50  # Minimum dimension for good OCR quality
            MIN_AREA = 2500  # Minimum area (50x50)
            
            # Skip completely invalid/corrupted images (0 or negative dimensions)
            if h <= 0 or w <= 0:
                self._log(f"⚠️ Invalid image dimensions ({w}x{h}px), skipping", "warning")
                return results
            
            if h < MIN_SIZE or w < MIN_SIZE or h * w < MIN_AREA:
                # Image too small - resize it
                scale_w = MIN_SIZE / w if w < MIN_SIZE else 1.0
                scale_h = MIN_SIZE / h if h < MIN_SIZE else 1.0
                scale = max(scale_w, scale_h)
                
                if scale > 1.0:
                    new_w = int(w * scale)
                    new_h = int(h * scale)
                    image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_CUBIC)
                    self._log(f"πŸ” Image resized from {w}x{h}px to {new_w}x{new_h}px for Custom API OCR", "debug")
                    h, w = new_h, new_w
            
            # Convert numpy array to PIL Image
            image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            pil_image = Image.fromarray(image_rgb)
            
            # Convert PIL Image to base64 string
            buffer = io.BytesIO()
            
            # Use the image format from settings
            if self.image_format.lower() == 'png':
                pil_image.save(buffer, format='PNG')
            else:
                pil_image.save(buffer, format='JPEG', quality=self.image_quality)
            
            buffer.seek(0)
            image_base64 = base64.b64encode(buffer.read()).decode('utf-8')
            
            # For OpenAI vision models, we need BOTH:
            # 1. System prompt with instructions
            # 2. User message that includes the image
            messages = [
                {
                    "role": "system",
                    "content": self.ocr_prompt  # The OCR instruction as system prompt
                },
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "text",
                            "text": "Image:"  # Minimal text, just to have something
                        },
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": f"data:image/jpeg;base64,{image_base64}"
                            }
                        }
                    ]
                }
            ]
            
            # Now send this properly formatted message
            # The UnifiedClient should handle this correctly
            # But we're NOT using send_image, we're using regular send

            # Retry-aware call
            from unified_api_client import UnifiedClientError  # local import to avoid hard dependency at module import time
            max_attempts = max(1, self.max_retries)
            attempt = 0
            last_error = None

            # Common refusal/error phrases that indicate a non-OCR response (expanded list)
            refusal_phrases = [
                "I can't extract", "I cannot extract",
                "I'm sorry", "I am sorry",
                "I'm unable", "I am unable",
                "I'm afraid I cannot help with that",
                "designed to ensure appropriate use",
                "cannot process images",
                "I can't help with that",
                "cannot view images",
                "no text in the image",
                "I can see this appears",
                "I cannot make out",
                "appears to be blank",
                "appears to be a mostly blank",
                "mostly blank or white image",
                "If there is text present",
                "too small, faint, or unclear",
                "cannot accurately extract",
                "may be too",
                "However, I cannot",
                "I don't see any",
                "no clear text",
                "no visible text",
                "does not contain",
                "doesn't contain",
                "I do not see"
            ]

            while attempt < max_attempts:
                # Check for stop before each attempt
                if self._check_stop():
                    self._log("⏹️ OCR processing stopped by user", "warning")
                    return results
                
                try:
                    response = self.client.send(
                        messages=messages,
                        temperature=self.temperature,
                        max_tokens=max_tokens
                    )

                    # Extract content from response object
                    content, finish_reason = response

                    # Validate content
                    has_content = bool(content and str(content).strip())
                    refused = False
                    if has_content:
                        # Filter out explicit failure markers
                        if "[" in content and "FAILED]" in content:
                            refused = True
                        elif any(phrase.lower() in content.lower() for phrase in refusal_phrases):
                            refused = True

                    # Decide success or retry
                    if has_content and not refused:
                        text = str(content).strip()
                        results.append(OCRResult(
                            text=text,
                            bbox=(0, 0, w, h),
                            confidence=kwargs.get('confidence', 0.85),
                            vertices=[(0, 0), (w, 0), (w, h), (0, h)]
                        ))
                        self._log(f"βœ… Detected: {text[:50]}...")
                        break  # success
                    else:
                        reason = "empty result" if not has_content else "refusal/non-OCR response"
                        last_error = f"{reason} (finish_reason: {finish_reason})"
                        # Check if we should retry on empty or refusal
                        should_retry = (not has_content and self.retry_on_empty) or refused
                        attempt += 1
                        if attempt >= max_attempts or not should_retry:
                            # No more retries or shouldn't retry
                            if not has_content:
                                self._log(f"⚠️ No text detected (finish_reason: {finish_reason})")
                            else:
                                self._log(f"❌ Model returned non-OCR response: {str(content)[:120]}", "warning")
                            break
                        # Backoff before retrying
                        delay = self.retry_initial_delay * (self.retry_backoff ** (attempt - 1)) + random.uniform(0, self.retry_jitter)
                        self._log(f"πŸ”„ Retry {attempt}/{max_attempts - 1} after {delay:.1f}s due to {reason}...", "warning")
                        time.sleep(delay)
                        time.sleep(0.1)  # Brief pause for stability
                        self._log("πŸ’€ OCR retry pausing briefly for stability", "debug")
                        continue

                except UnifiedClientError as ue:
                    msg = str(ue)
                    last_error = msg
                    # Do not retry on explicit user cancellation
                    if 'cancelled' in msg.lower() or 'stopped by user' in msg.lower():
                        self._log(f"❌ OCR cancelled: {msg}", "error")
                        break
                    attempt += 1
                    if attempt >= max_attempts:
                        self._log(f"❌ OCR failed after {attempt} attempts: {msg}", "error")
                        break
                    delay = self.retry_initial_delay * (self.retry_backoff ** (attempt - 1)) + random.uniform(0, self.retry_jitter)
                    self._log(f"πŸ”„ API error, retry {attempt}/{max_attempts - 1} after {delay:.1f}s: {msg}", "warning")
                    time.sleep(delay)
                    time.sleep(0.1)  # Brief pause for stability
                    self._log("πŸ’€ OCR API error retry pausing briefly for stability", "debug")
                    continue
                except Exception as e_inner:
                    last_error = str(e_inner)
                    attempt += 1
                    if attempt >= max_attempts:
                        self._log(f"❌ OCR exception after {attempt} attempts: {last_error}", "error")
                        break
                    delay = self.retry_initial_delay * (self.retry_backoff ** (attempt - 1)) + random.uniform(0, self.retry_jitter)
                    self._log(f"πŸ”„ Exception, retry {attempt}/{max_attempts - 1} after {delay:.1f}s: {last_error}", "warning")
                    time.sleep(delay)
                    time.sleep(0.1)  # Brief pause for stability
                    self._log("πŸ’€ OCR exception retry pausing briefly for stability", "debug")
                    continue
        
        except Exception as e:
            self._log(f"❌ Error: {str(e)}", "error")
            import traceback
            self._log(traceback.format_exc(), "debug")
        
        return results

class MangaOCRProvider(OCRProvider):
    """Manga OCR provider using HuggingFace model directly"""
    
    def __init__(self, log_callback=None):
        super().__init__(log_callback)
        self.processor = None
        self.model = None
        self.tokenizer = None
        
    def check_installation(self) -> bool:
        """Check if transformers is installed"""
        try:
            import transformers
            import torch
            self.is_installed = True
            return True
        except ImportError:
            return False 
    
    def install(self, progress_callback=None) -> bool:
        """Install transformers and torch"""
        pass
    
    def _is_valid_local_model_dir(self, path: str) -> bool:
        """Check that a local HF model directory has required files."""
        try:
            if not path or not os.path.isdir(path):
                return False
            needed_any_weights = any(
                os.path.exists(os.path.join(path, name)) for name in (
                    'pytorch_model.bin',
                    'model.safetensors'
                )
            )
            has_config = os.path.exists(os.path.join(path, 'config.json'))
            has_processor = (
                os.path.exists(os.path.join(path, 'preprocessor_config.json')) or
                os.path.exists(os.path.join(path, 'processor_config.json'))
            )
            has_tokenizer = (
                os.path.exists(os.path.join(path, 'tokenizer.json')) or
                os.path.exists(os.path.join(path, 'tokenizer_config.json'))
            )
            return has_config and needed_any_weights and has_processor and has_tokenizer
        except Exception:
            return False
    
    def load_model(self, **kwargs) -> bool:
        """Load the manga-ocr model, preferring a local directory to avoid re-downloading"""
        print("\n>>> MangaOCRProvider.load_model() called")
        try:
            if not self.is_installed and not self.check_installation():
                print("ERROR: Transformers not installed")
                self._log("❌ Transformers not installed", "error")
                return False

            # Always disable progress bars to avoid tqdm issues in some environments
            import os
            os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")

            from transformers import VisionEncoderDecoderModel, AutoTokenizer, AutoImageProcessor
            import torch

            # Prefer a local model directory if present to avoid any Hub access
            candidates = []
            env_local = os.environ.get("MANGA_OCR_LOCAL_DIR")
            if env_local:
                candidates.append(env_local)

            # Project root one level up from this file
            root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
            candidates.append(os.path.join(root_dir, 'models', 'manga-ocr-base'))
            candidates.append(os.path.join(root_dir, 'models', 'kha-white', 'manga-ocr-base'))

            model_source = None
            local_only = False
            # Find a valid local dir
            for cand in candidates:
                if self._is_valid_local_model_dir(cand):
                    model_source = cand
                    local_only = True
                    break

            # If no valid local dir, use Hub
            if not model_source:
                model_source = "kha-white/manga-ocr-base"
                # Make sure we are not forcing offline mode
                if os.environ.get("HF_HUB_OFFLINE") == "1":
                    try:
                        del os.environ["HF_HUB_OFFLINE"]
                    except Exception:
                        pass
                self._log("πŸ”₯ Loading manga-ocr model from Hugging Face Hub")
                self._log(f"   Repo: {model_source}")
            else:
                # Only set offline when local dir is fully valid
                os.environ.setdefault("HF_HUB_OFFLINE", "1")
                self._log("πŸ”₯ Loading manga-ocr model from local directory")
                self._log(f"   Local path: {model_source}")

            # Decide target device once; we will move after full CPU load to avoid meta tensors
            use_cuda = torch.cuda.is_available()

            # Try loading components, falling back to Hub if local-only fails
            def _load_components(source: str, local_flag: bool):
                self._log("   Loading tokenizer...")
                tok = AutoTokenizer.from_pretrained(source, local_files_only=local_flag)

                self._log("   Loading image processor...")
                try:
                    from transformers import AutoProcessor
                except Exception:
                    AutoProcessor = None
                try:
                    proc = AutoImageProcessor.from_pretrained(source, local_files_only=local_flag)
                except Exception as e_proc:
                    if AutoProcessor is not None:
                        self._log(f"   ⚠️ AutoImageProcessor failed: {e_proc}. Trying AutoProcessor...", "warning")
                        proc = AutoProcessor.from_pretrained(source, local_files_only=local_flag)
                    else:
                        raise

                self._log("   Loading model...")
                # Prevent meta tensors by forcing full materialization on CPU at load time
                os.environ.setdefault('TORCHDYNAMO_DISABLE', '1')
                mdl = VisionEncoderDecoderModel.from_pretrained(
                    source,
                    local_files_only=local_flag,
                    low_cpu_mem_usage=False,
                    device_map=None,
                    torch_dtype=torch.float32  # Use torch_dtype instead of dtype
                )
                return tok, proc, mdl

            try:
                self.tokenizer, self.processor, self.model = _load_components(model_source, local_only)
            except Exception as e_local:
                if local_only:
                    # Fallback to Hub once if local fails
                    self._log(f"   ⚠️ Local model load failed: {e_local}", "warning")
                    try:
                        if os.environ.get("HF_HUB_OFFLINE") == "1":
                            del os.environ["HF_HUB_OFFLINE"]
                    except Exception:
                        pass
                    model_source = "kha-white/manga-ocr-base"
                    local_only = False
                    self._log("   Retrying from Hugging Face Hub...")
                    self.tokenizer, self.processor, self.model = _load_components(model_source, local_only)
                else:
                    raise

            # Move to CUDA only after full CPU materialization
            target_device = 'cpu'
            if use_cuda:
                try:
                    self.model = self.model.to('cuda')
                    target_device = 'cuda'
                except Exception as move_err:
                    self._log(f"   ⚠️ Could not move model to CUDA: {move_err}", "warning")
                    target_device = 'cpu'

            # Finalize eval mode
            self.model.eval()

            # Sanity-check: ensure no parameter remains on 'meta' device
            try:
                for n, p in self.model.named_parameters():
                    dev = getattr(p, 'device', None)
                    if dev is not None and getattr(dev, 'type', '') == 'meta':
                        raise RuntimeError(f"Parameter {n} is on 'meta' after load")
            except Exception as sanity_err:
                self._log(f"❌ Manga-OCR model load sanity check failed: {sanity_err}", "error")
                return False

            print(f"SUCCESS: Model loaded on {target_device.upper()}")
            self._log(f"   βœ… Model loaded on {target_device.upper()}")
            self.is_loaded = True
            self._log("βœ… Manga OCR model ready")
            print(">>> Returning True from load_model()")
            return True

        except Exception as e:
            print(f"\nEXCEPTION in load_model: {e}")
            import traceback
            print(traceback.format_exc())
            self._log(f"❌ Failed to load manga-ocr model: {str(e)}", "error")
            self._log(traceback.format_exc(), "error")
            try:
                if 'local_only' in locals() and local_only:
                    self._log("Hint: Local load failed. Ensure your models/manga-ocr-base contains required files (config.json, preprocessor_config.json, tokenizer.json or tokenizer_config.json, and model weights).", "warning")
            except Exception:
                pass
            return False
    
    def _run_ocr(self, pil_image):
        """Run OCR on a PIL image using the HuggingFace model"""
        import torch
        
        # Process image (keyword arg for broader compatibility across transformers versions)
        inputs = self.processor(images=pil_image, return_tensors="pt")
        pixel_values = inputs["pixel_values"]
        
        # Move to same device as model
        try:
            model_device = next(self.model.parameters()).device
        except StopIteration:
            model_device = torch.device('cpu')
        pixel_values = pixel_values.to(model_device)
        
        # Generate text
        with torch.no_grad():
            generated_ids = self.model.generate(pixel_values)
        
        # Decode
        generated_text = self.tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
        
        return generated_text
    
    def detect_text(self, image: np.ndarray, **kwargs) -> List[OCRResult]:
        """

        Process the image region passed to it.

        This could be a bubble region or the full image.

        """
        results = []
        
        # Check for stop at start
        if self._check_stop():
            self._log("⏹️ Manga-OCR processing stopped by user", "warning")
            return results
        
        try:
            if not self.is_loaded:
                if not self.load_model():
                    return results
            
            import cv2
            from PIL import Image
            
            # Get confidence from kwargs
            confidence = kwargs.get('confidence', 0.7)
            
            # Convert numpy array to PIL
            image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            pil_image = Image.fromarray(image_rgb)
            h, w = image.shape[:2]
            
            self._log("πŸ” Processing region with manga-ocr...")
            
            # Check for stop before inference
            if self._check_stop():
                self._log("⏹️ Manga-OCR inference stopped by user", "warning")
                return results
            
            # Run OCR on the image region
            text = self._run_ocr(pil_image)
            
            if text and text.strip():
                # Return result for this region with its actual bbox
                results.append(OCRResult(
                    text=text.strip(),
                    bbox=(0, 0, w, h),  # Relative to the region passed in
                    confidence=confidence,
                    vertices=[(0, 0), (w, 0), (w, h), (0, h)]
                ))
                self._log(f"βœ… Detected text: {text[:50]}...")
            
        except Exception as e:
            self._log(f"❌ Error in manga-ocr: {str(e)}", "error")
            
        return results

class Qwen2VL(OCRProvider):
    """OCR using Qwen2-VL - Vision Language Model that can read Korean text"""
    
    def __init__(self, log_callback=None):
        super().__init__(log_callback)
        self.processor = None
        self.model = None
        self.tokenizer = None
        self.model_id = None
        self.qwen2vl_model_size = '1'  # Default to 2B
        # Get OCR prompt from environment or use default (UPDATED: Improved prompt)
        self.ocr_prompt = os.environ.get('OCR_SYSTEM_PROMPT', 
            "YOU ARE A TEXT EXTRACTION MACHINE. EXTRACT EXACTLY WHAT YOU SEE.\n\n"
            "ABSOLUTE RULES:\n"
            "1. OUTPUT ONLY THE VISIBLE TEXT/SYMBOLS - NOTHING ELSE\n"
            "2. NEVER TRANSLATE OR MODIFY\n"
            "3. NEVER EXPLAIN, DESCRIBE, OR COMMENT\n"
            "4. NEVER SAY \"I can't\" or \"I cannot\" or \"no text\" or \"blank image\"\n"
            "5. IF YOU SEE DOTS, OUTPUT THE DOTS: .\n"
            "6. IF YOU SEE PUNCTUATION, OUTPUT THE PUNCTUATION\n"
            "7. IF YOU SEE A SINGLE CHARACTER, OUTPUT THAT CHARACTER\n"
            "8. IF YOU SEE NOTHING, OUTPUT NOTHING (empty response)\n\n"
            "LANGUAGE PRESERVATION:\n"
            "- Korean text β†’ Output in Korean\n"
            "- Japanese text β†’ Output in Japanese\n"
            "- Chinese text β†’ Output in Chinese\n"
            "- English text β†’ Output in English\n"
            "- CJK quotation marks (γ€Œγ€γ€Žγ€γ€γ€‘γ€Šγ€‹γ€ˆγ€‰) β†’ Preserve exactly as shown\n\n"
            "FORMATTING:\n"
            "- OUTPUT ALL TEXT ON A SINGLE LINE WITH NO LINE BREAKS\n"
            "- NEVER use \\n or line breaks in your output\n\n"
            "FORBIDDEN RESPONSES:\n"
            "- \"I can see this appears to be...\"\n"
            "- \"I cannot make out any clear text...\"\n"
            "- \"This appears to be blank...\"\n"
            "- \"If there is text present...\"\n"
            "- ANY explanatory text\n\n"
            "YOUR ONLY OUTPUT: The exact visible text. Nothing more. Nothing less.\n"
            "If image has a dot β†’ Output: .\n"
            "If image has two dots β†’ Output: . .\n"
            "If image has text β†’ Output: [that text]\n"
            "If image is truly blank β†’ Output: [empty/no response]"
        )
    
    def set_ocr_prompt(self, prompt: str):
        """Allow setting the OCR prompt dynamically"""
        self.ocr_prompt = prompt
        
    def check_installation(self) -> bool:
        """Check if required packages are installed"""
        try:
            import transformers
            import torch
            self.is_installed = True
            return True
        except ImportError:
            return False
    
    def install(self, progress_callback=None) -> bool:
        """Install requirements for Qwen2-VL"""
        pass
    
    def load_model(self, **kwargs) -> bool:
        """Load Qwen2-VL model with size selection"""
        # Use either passed size or saved size
        model_size = kwargs.get('model_size', self.qwen2vl_model_size)
        self._log(f"DEBUG: load_model called with model_size={model_size}")
        
        # Map model size to model ID
        model_options = {
            "1": "Qwen/Qwen2-VL-2B-Instruct",
            "2": "Qwen/Qwen2-VL-7B-Instruct",
            "3": "Qwen/Qwen2-VL-72B-Instruct"
        }
        
        if str(model_size).startswith("custom:"):
            model_id = str(model_size).replace("custom:", "")
        else:
            model_id = model_options.get(str(model_size), model_options["1"])
        
        self._log(f"Using model: {model_id}")

        try:
            if not self.is_installed and not self.check_installation():
                self._log("❌ Not installed", "error")
                return False
            
            self._log("πŸ”₯ Loading Qwen2-VL for Advanced OCR...")
            
            from transformers import AutoProcessor, AutoTokenizer, AutoModelForVision2Seq
            import torch
            
            # Clear, sequential initialization like in the dialog
            self._log("Downloading processor...")
            self.processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
            self._log("βœ“ Processor downloaded")
            
            self._log("Downloading tokenizer...")
            self.tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
            self._log("βœ“ Tokenizer downloaded")
            
            self._log("Downloading model weights (this may take several minutes)...")


            
            from transformers import AutoProcessor, AutoTokenizer
            import torch
            
            # Model options
            model_options = {
                "1": "Qwen/Qwen2-VL-2B-Instruct",
                "2": "Qwen/Qwen2-VL-7B-Instruct",
                "3": "Qwen/Qwen2-VL-72B-Instruct",
                "4": "custom"
            }
            # CHANGE: Default to 7B instead of 2B
            # Check for saved preference first
            if model_size is None:
                # Try to get from environment or config
                import os
                model_size = os.environ.get('QWEN2VL_MODEL_SIZE', '1')
            
            # Determine which model to load
            if model_size and str(model_size).startswith("custom:"):
                # Custom model passed with ID
                model_id = str(model_size).replace("custom:", "")
                self.loaded_model_size = "Custom"
                self.model_id = model_id
                self._log(f"Loading custom model: {model_id}")
            elif model_size == "4":
                # Custom option selected but no ID - shouldn't happen
                self._log("❌ Custom model selected but no ID provided", "error")
                return False
            elif model_size and str(model_size) in model_options:
                # Standard model option
                option = model_options[str(model_size)]
                if option == "custom":
                    self._log("❌ Custom model needs an ID", "error")
                    return False
                model_id = option
                # Set loaded_model_size for status display
                if model_size == "1":
                    self.loaded_model_size = "2B"
                elif model_size == "2":
                    self.loaded_model_size = "7B"
                elif model_size == "3":
                    self.loaded_model_size = "72B"
            else:
                # CHANGE: Default to 7B (option "2") instead of 2B
                model_id = model_options["1"]  # Changed from "1" to "2"
                self.loaded_model_size = "2B"   # Changed from "2B" to "7B"
                self._log("No model size specified, defaulting to 2B")  # Changed message
            
            self._log(f"Loading model: {model_id}")
            
            # Load processor and tokenizer
            self._log("πŸ“₯ Loading processor...")
            self.processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
            self._log("πŸ“₯ Loading tokenizer...")
            self.tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
            self._log("βœ… Processor and tokenizer loaded successfully")
            
            # Load the model - let it figure out the class dynamically
            if torch.cuda.is_available():
                self._log(f"Using GPU: {torch.cuda.get_device_name(0)}")
                self.model = AutoModelForVision2Seq.from_pretrained(
                    model_id,
                    torch_dtype=torch.float16,
                    device_map="auto",
                    trust_remote_code=True
                )
                self._log("βœ… Model loaded on GPU")
            else:
                self._log("No GPU detected, will load on CPU")
                self.model = AutoModelForVision2Seq.from_pretrained(
                    model_id,
                    torch_dtype=torch.float32,
                    trust_remote_code=True
                )
                self._log("βœ… Model loaded on CPU")
            
            self.model.eval()
            self.is_loaded = True
            self._log("βœ… Qwen2-VL ready for Advanced OCR!")
            return True
            
        except Exception as e:
            self._log(f"❌ Failed to load: {str(e)}", "error")
            import traceback
            full_error = traceback.format_exc()
            self._log("Full error trace:")
            for line in full_error.split('\n'):
                self._log(f"    {line}")
            return False

    def detect_text(self, image: np.ndarray, **kwargs) -> List[OCRResult]:
        """Process image with Qwen2-VL for Korean text extraction"""
        results = []
        if hasattr(self, 'model_id'):
            self._log(f"DEBUG: Using model: {self.model_id}", "debug")
            
        # Check if OCR prompt was passed in kwargs (for dynamic updates)
        if 'ocr_prompt' in kwargs:
            self.ocr_prompt = kwargs['ocr_prompt']
        
        try:
            if not self.is_loaded:
                if not self.load_model():
                    return results
            
            import cv2
            from PIL import Image
            import torch
            
            # Convert to PIL
            image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            pil_image = Image.fromarray(image_rgb)
            h, w = image.shape[:2]
            
            self._log(f"πŸ” Processing with Qwen2-VL ({w}x{h} pixels)...")
            
            # Use the configurable OCR prompt
            messages = [
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image",
                            "image": pil_image,
                        },
                        {
                            "type": "text", 
                            "text": self.ocr_prompt  # Use the configurable prompt
                        }
                    ]
                }
            ]
            
            # Alternative simpler prompt if the above still causes issues:
            # "text": "OCR: Extract text as-is"
            
            # Process with Qwen2-VL
            text = self.processor.apply_chat_template(
                messages, 
                tokenize=False, 
                add_generation_prompt=True
            )

            inputs = self.processor(
                text=[text],
                images=[pil_image],
                padding=True,
                return_tensors="pt"
            )

            # Get the device and dtype the model is currently on
            model_device = next(self.model.parameters()).device
            model_dtype = next(self.model.parameters()).dtype

            # Move inputs to the same device as the model and cast float tensors to model dtype
            try:
                # Move first
                inputs = inputs.to(model_device)
                # Then align dtypes only for floating tensors (e.g., pixel_values)
                for k, v in inputs.items():
                    if isinstance(v, torch.Tensor) and torch.is_floating_point(v):
                        inputs[k] = v.to(model_dtype)
            except Exception:
                # Fallback: ensure at least pixel_values is correct if present
                try:
                    if isinstance(inputs, dict) and "pixel_values" in inputs:
                        pv = inputs["pixel_values"].to(model_device)
                        if torch.is_floating_point(pv):
                            inputs["pixel_values"] = pv.to(model_dtype)
                except Exception:
                    pass

            # Ensure pixel_values explicitly matches model dtype if present
            try:
                if isinstance(inputs, dict) and "pixel_values" in inputs:
                    inputs["pixel_values"] = inputs["pixel_values"].to(device=model_device, dtype=model_dtype)
            except Exception:
                pass

            # Generate text with stricter parameters to avoid creative responses
            use_amp = (hasattr(torch, 'cuda') and model_device.type == 'cuda' and model_dtype in (torch.float16, torch.bfloat16))
            autocast_dev = 'cuda' if model_device.type == 'cuda' else 'cpu'
            autocast_dtype = model_dtype if model_dtype in (torch.float16, torch.bfloat16) else None

            with torch.no_grad():
                if use_amp and autocast_dtype is not None:
                    with torch.autocast(autocast_dev, dtype=autocast_dtype):
                        generated_ids = self.model.generate(
                            **inputs,
                            max_new_tokens=128,      # Reduced from 512 - manga bubbles are typically short
                            do_sample=False,        # Keep deterministic
                            temperature=0.01,       # Keep your very low temperature
                            top_p=1.0,             # Keep no nucleus sampling
                            repetition_penalty=1.0, # Keep no repetition penalty
                            num_beams=1,           # Ensure greedy decoding (faster than beam search)
                            use_cache=True,        # Enable KV cache for speed
                            early_stopping=True,   # Stop at EOS token
                            pad_token_id=self.tokenizer.pad_token_id,      # Proper padding
                            eos_token_id=self.tokenizer.eos_token_id,      # Proper stopping
                        )
                else:
                    generated_ids = self.model.generate(
                        **inputs,
                        max_new_tokens=128,      # Reduced from 512 - manga bubbles are typically short
                        do_sample=False,        # Keep deterministic
                        temperature=0.01,       # Keep your very low temperature
                        top_p=1.0,             # Keep no nucleus sampling
                        repetition_penalty=1.0, # Keep no repetition penalty
                        num_beams=1,           # Ensure greedy decoding (faster than beam search)
                        use_cache=True,        # Enable KV cache for speed
                        early_stopping=True,   # Stop at EOS token
                        pad_token_id=self.tokenizer.pad_token_id,      # Proper padding
                        eos_token_id=self.tokenizer.eos_token_id,      # Proper stopping
                    )
            
            # Decode the output
            generated_ids_trimmed = [
                out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
            ]
            output_text = self.processor.batch_decode(
                generated_ids_trimmed, 
                skip_special_tokens=True, 
                clean_up_tokenization_spaces=False
            )[0]
            
            if output_text and output_text.strip():
                text = output_text.strip()
                
                # ADDED: Filter out any response that looks like an explanation or apology
                # Common patterns that indicate the model is being "helpful" instead of just extracting
                unwanted_patterns = [
                    "μ£„μ†‘ν•©λ‹ˆλ‹€",  # "I apologize"
                    "sorry",
                    "apologize",
                    "μ΄λ―Έμ§€μ—λŠ”",  # "in this image"
                    "ν…μŠ€νŠΈκ°€ μ—†μŠ΅λ‹ˆλ‹€",  # "there is no text"
                    "I cannot",
                    "I don't see",
                    "There is no",
                    "질문이 μžˆμœΌμ‹œλ©΄",  # "if you have questions"
                ]
                
                # Check if response contains unwanted patterns
                text_lower = text.lower()
                is_explanation = any(pattern.lower() in text_lower for pattern in unwanted_patterns)
                
                # Also check if the response is suspiciously long for a bubble
                # Most manga bubbles are short, if we get 50+ chars it might be an explanation
                is_too_long = len(text) > 100 and ('.' in text or ',' in text or '!' in text)
                
                if is_explanation or is_too_long:
                    self._log(f"⚠️ Model returned explanation instead of text, ignoring", "warning")
                    # Return empty result or just skip this region
                    return results
                
                # Check language
                has_korean = any('\uAC00' <= c <= '\uD7AF' for c in text)
                has_japanese = any('\u3040' <= c <= '\u309F' or '\u30A0' <= c <= '\u30FF' for c in text)
                has_chinese = any('\u4E00' <= c <= '\u9FFF' for c in text)
                
                if has_korean:
                    self._log(f"βœ… Korean detected: {text[:50]}...")
                elif has_japanese:
                    self._log(f"βœ… Japanese detected: {text[:50]}...")
                elif has_chinese:
                    self._log(f"βœ… Chinese detected: {text[:50]}...")
                else:
                    self._log(f"βœ… Text: {text[:50]}...")
                
                results.append(OCRResult(
                    text=text,
                    bbox=(0, 0, w, h),
                    confidence=0.9,
                    vertices=[(0, 0), (w, 0), (w, h), (0, h)]
                ))
            else:
                self._log("⚠️ No text detected", "warning")
        
        except Exception as e:
            self._log(f"❌ Error: {str(e)}", "error")
            import traceback
            self._log(traceback.format_exc(), "debug")
        
        return results
    
class EasyOCRProvider(OCRProvider):
    """EasyOCR provider for multiple languages"""
    
    def __init__(self, log_callback=None, languages=None):
        super().__init__(log_callback)
        # Default to safe language combination
        self.languages = languages or ['ja', 'en']  # Safe default
        self._validate_language_combination()

    def _validate_language_combination(self):
        """Validate and fix EasyOCR language combinations"""
        # EasyOCR language compatibility rules
        incompatible_pairs = [
            (['ja', 'ko'], 'Japanese and Korean cannot be used together'),
            (['ja', 'zh'], 'Japanese and Chinese cannot be used together'),
            (['ko', 'zh'], 'Korean and Chinese cannot be used together')
        ]
        
        for incompatible, reason in incompatible_pairs:
            if all(lang in self.languages for lang in incompatible):
                self._log(f"⚠️ EasyOCR: {reason}", "warning")
                # Keep first language + English
                self.languages = [self.languages[0], 'en']
                self._log(f"πŸ”§ Auto-adjusted to: {self.languages}", "info")
                break
    
    def check_installation(self) -> bool:
        """Check if easyocr is installed"""
        try:
            import easyocr
            self.is_installed = True
            return True
        except ImportError:
            return False
    
    def install(self, progress_callback=None) -> bool:
        """Install easyocr"""
        pass
    
    def load_model(self, **kwargs) -> bool:
        """Load easyocr model"""
        try:
            if not self.is_installed and not self.check_installation():
                self._log("❌ easyocr not installed", "error")
                return False
            
            self._log(f"πŸ”₯ Loading easyocr model for languages: {self.languages}...")
            import easyocr
            
            # This will download models on first run
            self.model = easyocr.Reader(self.languages, gpu=True)
            self.is_loaded = True
            
            self._log("βœ… easyocr model loaded successfully")
            return True
            
        except Exception as e:
            self._log(f"❌ Failed to load easyocr: {str(e)}", "error")
            # Try CPU mode if GPU fails
            try:
                import easyocr
                self.model = easyocr.Reader(self.languages, gpu=False)
                self.is_loaded = True
                self._log("βœ… easyocr loaded in CPU mode")
                return True
            except:
                return False
    
    def detect_text(self, image: np.ndarray, **kwargs) -> List[OCRResult]:
        """Detect text using easyocr"""
        results = []
        
        try:
            if not self.is_loaded:
                if not self.load_model():
                    return results
            
            # EasyOCR can work directly with numpy arrays
            ocr_results = self.model.readtext(image, detail=1)
            
            # Parse results
            for (bbox, text, confidence) in ocr_results:
                # bbox is a list of 4 points
                xs = [point[0] for point in bbox]
                ys = [point[1] for point in bbox]
                x_min, x_max = min(xs), max(xs)
                y_min, y_max = min(ys), max(ys)
                
                results.append(OCRResult(
                    text=text,
                    bbox=(int(x_min), int(y_min), int(x_max - x_min), int(y_max - y_min)),
                    confidence=confidence,
                    vertices=[(int(p[0]), int(p[1])) for p in bbox]
                ))
            
            self._log(f"βœ… Detected {len(results)} text regions")
            
        except Exception as e:
            self._log(f"❌ Error in easyocr detection: {str(e)}", "error")
        
        return results


class PaddleOCRProvider(OCRProvider):
    """PaddleOCR provider with memory safety measures"""
    
    def check_installation(self) -> bool:
        """Check if paddleocr is installed"""
        try:
            from paddleocr import PaddleOCR
            self.is_installed = True
            return True
        except ImportError:
            return False
    
    def install(self, progress_callback=None) -> bool:
        """Install paddleocr"""
        pass
    
    def load_model(self, **kwargs) -> bool:
        """Load paddleocr model with memory-safe configurations"""
        try:
            if not self.is_installed and not self.check_installation():
                self._log("❌ paddleocr not installed", "error")
                return False
            
            self._log("πŸ”₯ Loading PaddleOCR model...")
            
            # Set memory-safe environment variables BEFORE importing
            import os
            os.environ['OMP_NUM_THREADS'] = '1'  # Prevent OpenMP conflicts
            os.environ['MKL_NUM_THREADS'] = '1'  # Prevent MKL conflicts
            os.environ['OPENBLAS_NUM_THREADS'] = '1'  # Prevent OpenBLAS conflicts
            os.environ['FLAGS_use_mkldnn'] = '0'  # Disable MKL-DNN
            
            from paddleocr import PaddleOCR
            
            # Try memory-safe configurations
            configs_to_try = [
                # Config 1: Most memory-safe configuration
                {
                    'use_angle_cls': False,  # Disable angle to save memory
                    'lang': 'ch',
                    'rec_batch_num': 1,  # Process one at a time
                    'max_text_length': 100,  # Limit text length
                    'drop_score': 0.5,  # Higher threshold to reduce detections
                    'cpu_threads': 1,  # Single thread to avoid conflicts
                },
                # Config 2: Minimal memory footprint
                {
                    'lang': 'ch',
                    'rec_batch_num': 1,
                    'cpu_threads': 1,
                },
                # Config 3: Absolute minimal
                {
                    'lang': 'ch'
                },
                # Config 4: Empty config
                {}
            ]
            
            for i, config in enumerate(configs_to_try):
                try:
                    self._log(f"   Trying configuration {i+1}/{len(configs_to_try)}: {config}")
                    
                    # Force garbage collection before loading
                    import gc
                    gc.collect()
                    
                    self.model = PaddleOCR(**config)
                    self.is_loaded = True
                    self.current_config = config
                    self._log(f"βœ… PaddleOCR loaded successfully with config: {config}")
                    return True
                except Exception as e:
                    error_str = str(e)
                    self._log(f"   Config {i+1} failed: {error_str}", "debug")
                    
                    # Clean up on failure
                    if hasattr(self, 'model'):
                        del self.model
                    gc.collect()
                    continue
            
            self._log(f"❌ PaddleOCR failed to load with any configuration", "error")
            return False
            
        except Exception as e:
            self._log(f"❌ Failed to load paddleocr: {str(e)}", "error")
            import traceback
            self._log(traceback.format_exc(), "debug")
            return False
    
    def detect_text(self, image: np.ndarray, **kwargs) -> List[OCRResult]:
        """Detect text with memory safety measures"""
        results = []
        
        try:
            if not self.is_loaded:
                if not self.load_model():
                    return results
            
            import cv2
            import numpy as np
            import gc
            
            # Memory safety: Ensure image isn't too large
            h, w = image.shape[:2] if len(image.shape) >= 2 else (0, 0)
            
            # Limit image size to prevent memory issues
            MAX_DIMENSION = 1500
            if h > MAX_DIMENSION or w > MAX_DIMENSION:
                scale = min(MAX_DIMENSION/h, MAX_DIMENSION/w)
                new_h, new_w = int(h*scale), int(w*scale)
                self._log(f"⚠️ Resizing large image from {w}x{h} to {new_w}x{new_h} for memory safety", "warning")
                image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
                scale_factor = 1/scale
            else:
                scale_factor = 1.0
            
            # Ensure correct format
            if len(image.shape) == 2:  # Grayscale
                image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
            elif len(image.shape) == 4:  # Batch
                image = image[0]
            
            # Ensure uint8 type
            if image.dtype != np.uint8:
                if image.max() <= 1.0:
                    image = (image * 255).astype(np.uint8)
                else:
                    image = image.astype(np.uint8)
            
            # Make a copy to avoid memory corruption
            image_copy = image.copy()
            
            # Force garbage collection before OCR
            gc.collect()
            
            # Process with timeout protection
            import signal
            import threading
            
            ocr_results = None
            ocr_error = None
            
            def run_ocr():
                nonlocal ocr_results, ocr_error
                try:
                    ocr_results = self.model.ocr(image_copy)
                except Exception as e:
                    ocr_error = e
            
            # Run OCR in a separate thread with timeout
            ocr_thread = threading.Thread(target=run_ocr)
            ocr_thread.daemon = True
            ocr_thread.start()
            ocr_thread.join(timeout=30)  # 30 second timeout
            
            if ocr_thread.is_alive():
                self._log("❌ PaddleOCR timeout - taking too long", "error")
                return results
            
            if ocr_error:
                raise ocr_error
            
            # Parse results
            results = self._parse_ocr_results(ocr_results)
            
            # Scale coordinates back if image was resized
            if scale_factor != 1.0 and results:
                for r in results:
                    x, y, width, height = r.bbox
                    r.bbox = (int(x*scale_factor), int(y*scale_factor), 
                            int(width*scale_factor), int(height*scale_factor))
                    r.vertices = [(int(v[0]*scale_factor), int(v[1]*scale_factor)) 
                                for v in r.vertices]
            
            if results:
                self._log(f"βœ… Detected {len(results)} text regions", "info")
            else:
                self._log("No text regions found", "debug")
            
            # Clean up
            del image_copy
            gc.collect()
            
        except Exception as e:
            error_msg = str(e) if str(e) else type(e).__name__
            
            if "memory" in error_msg.lower() or "0x" in error_msg:
                self._log("❌ Memory access violation in PaddleOCR", "error")
                self._log("   This is a known Windows issue with PaddleOCR", "info")
                self._log("   Please switch to EasyOCR or manga-ocr instead", "warning")
            elif "trace_order.size()" in error_msg:
                self._log("❌ PaddleOCR internal error", "error")
                self._log("   Please switch to EasyOCR or manga-ocr", "warning")
            else:
                self._log(f"❌ Error in paddleocr detection: {error_msg}", "error")
            
            import traceback
            self._log(traceback.format_exc(), "debug")
        
        return results
    
    def _parse_ocr_results(self, ocr_results) -> List[OCRResult]:
        """Parse OCR results safely"""
        results = []
        
        if isinstance(ocr_results, bool) and ocr_results == False:
            return results
        
        if ocr_results is None or not isinstance(ocr_results, list):
            return results
        
        if len(ocr_results) == 0:
            return results
        
        # Handle batch format
        if isinstance(ocr_results[0], list) and len(ocr_results[0]) > 0:
            first_item = ocr_results[0][0]
            if isinstance(first_item, list) and len(first_item) > 0:
                if isinstance(first_item[0], (list, tuple)) and len(first_item[0]) == 2:
                    ocr_results = ocr_results[0]
        
        # Parse detections
        for detection in ocr_results:
            if not detection or isinstance(detection, bool):
                continue
            
            if not isinstance(detection, (list, tuple)) or len(detection) < 2:
                continue
            
            try:
                bbox_points = detection[0]
                text_data = detection[1]
                
                if not isinstance(bbox_points, (list, tuple)) or len(bbox_points) != 4:
                    continue
                
                if not isinstance(text_data, (tuple, list)) or len(text_data) < 2:
                    continue
                
                text = str(text_data[0]).strip()
                confidence = float(text_data[1])
                
                if not text or confidence < 0.3:
                    continue
                
                xs = [float(p[0]) for p in bbox_points]
                ys = [float(p[1]) for p in bbox_points]
                x_min, x_max = min(xs), max(xs)
                y_min, y_max = min(ys), max(ys)
                
                if (x_max - x_min) < 5 or (y_max - y_min) < 5:
                    continue
                
                results.append(OCRResult(
                    text=text,
                    bbox=(int(x_min), int(y_min), int(x_max - x_min), int(y_max - y_min)),
                    confidence=confidence,
                    vertices=[(int(p[0]), int(p[1])) for p in bbox_points]
                ))
                
            except Exception:
                continue
        
        return results

class DocTROCRProvider(OCRProvider):
    """DocTR OCR provider"""
    
    def check_installation(self) -> bool:
        """Check if doctr is installed"""
        try:
            from doctr.models import ocr_predictor
            self.is_installed = True
            return True
        except ImportError:
            return False
    
    def install(self, progress_callback=None) -> bool:
        """Install doctr"""
        pass
    
    def load_model(self, **kwargs) -> bool:
        """Load doctr model"""
        try:
            if not self.is_installed and not self.check_installation():
                self._log("❌ doctr not installed", "error")
                return False
            
            self._log("πŸ”₯ Loading DocTR model...")
            from doctr.models import ocr_predictor
            
            # Load pretrained model
            self.model = ocr_predictor(pretrained=True)
            self.is_loaded = True
            
            self._log("βœ… DocTR model loaded successfully")
            return True
            
        except Exception as e:
            self._log(f"❌ Failed to load doctr: {str(e)}", "error")
            return False
    
    def detect_text(self, image: np.ndarray, **kwargs) -> List[OCRResult]:
        """Detect text using doctr"""
        results = []
        
        try:
            if not self.is_loaded:
                if not self.load_model():
                    return results
            
            from doctr.io import DocumentFile
            
            # DocTR expects document format
            # Convert numpy array to PIL and save temporarily
            import tempfile
            import cv2
            
            with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as tmp:
                cv2.imwrite(tmp.name, image)
                doc = DocumentFile.from_images(tmp.name)
            
            # Run OCR
            result = self.model(doc)
            
            # Parse results
            h, w = image.shape[:2]
            for page in result.pages:
                for block in page.blocks:
                    for line in block.lines:
                        for word in line.words:
                            # Handle different geometry formats
                            geometry = word.geometry
                            
                            if len(geometry) == 4:
                                # Standard format: (x1, y1, x2, y2)
                                x1, y1, x2, y2 = geometry
                            elif len(geometry) == 2:
                                # Alternative format: ((x1, y1), (x2, y2))
                                (x1, y1), (x2, y2) = geometry
                            else:
                                self._log(f"Unexpected geometry format: {geometry}", "warning")
                                continue
                            
                            # Convert relative coordinates to absolute
                            x1, x2 = int(x1 * w), int(x2 * w)
                            y1, y2 = int(y1 * h), int(y2 * h)
                            
                            results.append(OCRResult(
                                text=word.value,
                                bbox=(x1, y1, x2 - x1, y2 - y1),
                                confidence=word.confidence,
                                vertices=[(x1, y1), (x2, y1), (x2, y2), (x1, y2)]
                            ))
            
            # Clean up temp file
            try:
                os.unlink(tmp.name)
            except:
                pass
            
            self._log(f"DocTR detected {len(results)} text regions")
            
        except Exception as e:
            self._log(f"Error in doctr detection: {str(e)}", "error")
            import traceback
            self._log(traceback.format_exc(), "error")
        
        return results


class RapidOCRProvider(OCRProvider):
    """RapidOCR provider for fast local OCR"""
    
    def check_installation(self) -> bool:
        """Check if rapidocr is installed"""
        try:
            import rapidocr_onnxruntime
            self.is_installed = True
            return True
        except ImportError:
            return False
    
    def install(self, progress_callback=None) -> bool:
        """Install rapidocr (requires manual pip install)"""
        # RapidOCR requires manual installation
        if progress_callback:
            progress_callback("RapidOCR requires manual pip installation")
        self._log("Run: pip install rapidocr-onnxruntime", "info")
        return False  # Always return False since we can't auto-install
    
    def load_model(self, **kwargs) -> bool:
        """Load RapidOCR model"""
        try:
            if not self.is_installed and not self.check_installation():
                self._log("RapidOCR not installed", "error")
                return False
            
            self._log("Loading RapidOCR...")
            from rapidocr_onnxruntime import RapidOCR
            
            self.model = RapidOCR()
            self.is_loaded = True
            
            self._log("RapidOCR model loaded successfully")
            return True
            
        except Exception as e:
            self._log(f"Failed to load RapidOCR: {str(e)}", "error")
            return False
    
    def detect_text(self, image: np.ndarray, **kwargs) -> List[OCRResult]:
        """Detect text using RapidOCR"""
        if not self.is_loaded:
            self._log("RapidOCR model not loaded", "error")
            return []
        
        results = []
        
        try:
            # Convert numpy array to PIL Image for RapidOCR
            if len(image.shape) == 3:
                # BGR to RGB
                image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            else:
                image_rgb = image
            
            # RapidOCR expects PIL Image or numpy array
            ocr_results, _ = self.model(image_rgb)
            
            if ocr_results:
                for result in ocr_results:
                    # RapidOCR returns [bbox, text, confidence]
                    bbox_points = result[0]  # 4 corner points
                    text = result[1]
                    confidence = float(result[2])
                    
                    if not text or not text.strip():
                        continue
                    
                    # Convert 4-point bbox to x,y,w,h format
                    xs = [point[0] for point in bbox_points]
                    ys = [point[1] for point in bbox_points]
                    x_min, x_max = min(xs), max(xs)
                    y_min, y_max = min(ys), max(ys)
                    
                    results.append(OCRResult(
                        text=text.strip(),
                        bbox=(int(x_min), int(y_min), int(x_max - x_min), int(y_max - y_min)),
                        confidence=confidence,
                        vertices=[(int(p[0]), int(p[1])) for p in bbox_points]
                    ))
            
            self._log(f"Detected {len(results)} text regions")
            
        except Exception as e:
            self._log(f"Error in RapidOCR detection: {str(e)}", "error")
        return results


class AzureComputerVisionProvider(OCRProvider):
    """Azure Computer Vision OCR provider (the original Azure OCR service)"""
    
    def __init__(self, log_callback=None):
        super().__init__(log_callback)
        self.client = None
        self.endpoint = None
        self.key = None
        
    def check_installation(self) -> bool:
        """Check if Azure Computer Vision SDK is installed"""
        try:
            from azure.ai.vision.imageanalysis import ImageAnalysisClient
            from azure.core.credentials import AzureKeyCredential
            self.is_installed = True
            return True
        except ImportError:
            return False
    
    def install(self, progress_callback=None) -> bool:
        """Provide installation instructions"""
        if progress_callback:
            progress_callback("Azure Computer Vision requires manual installation")
        self._log("Run: pip install azure-ai-vision-imageanalysis", "info")
        return False
    
    def load_model(self, **kwargs) -> bool:
        """Initialize Azure Computer Vision client"""
        try:
            if not self.is_installed and not self.check_installation():
                self._log("❌ Azure Computer Vision SDK not installed", "error")
                self._log("   Install with: pip install azure-ai-vision-imageanalysis", "info")
                return False
            
            from azure.ai.vision.imageanalysis import ImageAnalysisClient
            from azure.core.credentials import AzureKeyCredential
            
            # Get credentials from kwargs (passed from manga integration)
            self.endpoint = kwargs.get('azure_endpoint')
            self.key = kwargs.get('azure_key')
            
            print(f"[DEBUG] Azure Computer Vision endpoint: {self.endpoint}")
            print(f"[DEBUG] Azure Computer Vision key exists: {bool(self.key)}")
            
            if not self.endpoint or not self.key:
                self._log("❌ Azure Computer Vision credentials not configured", "error")
                self._log("   Please configure Azure Key and Endpoint in the GUI", "info")
                return False
            
            # Create client
            self.client = ImageAnalysisClient(
                endpoint=self.endpoint,
                credential=AzureKeyCredential(self.key)
            )
            
            self.is_loaded = True
            self._log("βœ… Azure Computer Vision client initialized")
            return True
            
        except Exception as e:
            self._log(f"❌ Failed to initialize Azure Computer Vision: {str(e)}", "error")
            import traceback
            self._log(traceback.format_exc(), "debug")
            return False
    
    def detect_text(self, image: np.ndarray, **kwargs) -> List[OCRResult]:
        """Detect text using Azure Computer Vision"""
        results = []
        
        try:
            if not self.is_loaded:
                if not self.load_model(**kwargs):
                    return results
            
            from azure.ai.vision.imageanalysis.models import VisualFeatures
            import cv2
            
            # Convert numpy array to bytes
            _, encoded = cv2.imencode('.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, 95])
            image_bytes = encoded.tobytes()
            
            print(f"[DEBUG] Azure Computer Vision: Processing image of size {image.shape}")
            
            # Call Azure Computer Vision API
            analysis_result = self.client.analyze(
                image_data=image_bytes,
                visual_features=[VisualFeatures.READ]
            )
            
            # Extract text from result
            if analysis_result and getattr(analysis_result, 'read', None):
                for block in analysis_result.read.blocks or []:
                    for line in block.lines or []:
                        text = (getattr(line, 'text', '') or '').strip()
                        if not text:
                            continue
                        
                        # Get bounding polygon points
                        if getattr(line, 'bounding_polygon', None):
                            vertices = [(int(point.x), int(point.y)) for point in line.bounding_polygon]
                            
                            # Calculate bounding box
                            xs = [v[0] for v in vertices]
                            ys = [v[1] for v in vertices]
                            x_min, x_max = min(xs), max(xs)
                            y_min, y_max = min(ys), max(ys)
                            
                            results.append(OCRResult(
                                text=text,
                                bbox=(x_min, y_min, x_max - x_min, y_max - y_min),
                                confidence=0.9,  # Azure doesn't provide confidence scores in this API
                                vertices=vertices
                            ))
                            
                            print(f"[DEBUG] Azure Computer Vision: Found text '{text}' at ({x_min},{y_min})")
            else:
                print("[DEBUG] Azure Computer Vision: No 'read' content in analysis_result")
            
            print(f"[DEBUG] Azure Computer Vision: Detected {len(results)} text regions")
            
            if results:
                self._log(f"βœ… Detected {len(results)} text regions")
            else:
                self._log("⚠️ No text detected", "warning")
            
        except Exception as e:
            self._log(f"❌ Error in Azure Computer Vision detection: {str(e)}", "error")
            import traceback
            self._log(traceback.format_exc(), "debug")
        
        return results


class AzureDocumentIntelligenceProvider(OCRProvider):
    """Azure Document Intelligence OCR provider (successor to Azure AI Vision)

    

    Azure Document Intelligence offers superior OCR capabilities with:

    - Better text extraction accuracy

    - Layout analysis

    - Language detection

    - Reading order detection

    """
    
    def __init__(self, log_callback=None):
        super().__init__(log_callback)
        self.client = None
        self.endpoint = None
        self.key = None
        
    def check_installation(self) -> bool:
        """Check if Azure Document Intelligence SDK is installed"""
        try:
            from azure.ai.formrecognizer import DocumentAnalysisClient
            from azure.core.credentials import AzureKeyCredential
            self.is_installed = True
            return True
        except ImportError:
            return False
    
    def install(self, progress_callback=None) -> bool:
        """Provide installation instructions"""
        if progress_callback:
            progress_callback("Azure Document Intelligence requires manual installation")
        self._log("Run: pip install azure-ai-formrecognizer", "info")
        return False
    
    def load_model(self, **kwargs) -> bool:
        """Initialize Azure Document Intelligence client"""
        try:
            if not self.is_installed and not self.check_installation():
                self._log("❌ Azure Document Intelligence SDK not installed", "error")
                self._log("   Install with: pip install azure-ai-formrecognizer", "info")
                return False
            
            from azure.ai.formrecognizer import DocumentAnalysisClient
            from azure.core.credentials import AzureKeyCredential
            
            # Get credentials from multiple sources (kwargs, environment, or fall back to azure_vision_* config)
            # Priority: explicit kwargs > specific env vars > azure_vision config (GUI uses this)
            print(f"[DEBUG] Azure Document Intelligence kwargs: {kwargs}")
            
            self.endpoint = (
                kwargs.get('endpoint') or 
                kwargs.get('azure_endpoint') or
                os.environ.get('AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT') or
                os.environ.get('AZURE_ENDPOINT')
            )
            
            self.key = (
                kwargs.get('key') or 
                kwargs.get('azure_key') or
                os.environ.get('AZURE_DOCUMENT_INTELLIGENCE_KEY') or
                os.environ.get('AZURE_KEY')
            )
            
            print(f"[DEBUG] Azure endpoint: {self.endpoint}")
            print(f"[DEBUG] Azure key exists: {bool(self.key)}")
            
            if not self.endpoint or not self.key:
                self._log("❌ Azure Document Intelligence credentials not configured", "error")
                self._log("   Please configure Azure Key and Endpoint in the GUI", "info")
                return False
            
            # Create client
            self.client = DocumentAnalysisClient(
                endpoint=self.endpoint,
                credential=AzureKeyCredential(self.key)
            )
            
            self.is_loaded = True
            self._log("βœ… Azure Document Intelligence client initialized")
            return True
            
        except Exception as e:
            self._log(f"❌ Failed to initialize Azure Document Intelligence: {str(e)}", "error")
            import traceback
            self._log(traceback.format_exc(), "debug")
            return False
    
    def detect_text(self, image: np.ndarray, **kwargs) -> List[OCRResult]:
        """Detect text using Azure Document Intelligence"""
        results = []
        
        try:
            if not self.is_loaded:
                if not self.load_model(**kwargs):
                    return results
            
            # Convert numpy array to bytes
            import cv2
            from io import BytesIO
            
            # Encode image to JPEG
            _, encoded = cv2.imencode('.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, 95])
            image_bytes = encoded.tobytes()
            
            # Get language hint from kwargs if provided
            language_hint = kwargs.get('language_hint', None)
            locale = None
            
            if language_hint:
                # Map common language codes to Azure Document Intelligence locale codes
                locale_map = {
                    'ja': 'ja',      # Japanese
                    'ko': 'ko',      # Korean
                    'zh': 'zh-Hans', # Simplified Chinese
                    'zh-Hans': 'zh-Hans',
                    'zh-Hant': 'zh-Hant', # Traditional Chinese
                    'zh-TW': 'zh-Hant',
                    'en': 'en',      # English
                    'ar': 'ar',      # Arabic
                    'he': 'he'       # Hebrew
                }
                locale = locale_map.get(language_hint, language_hint)
                self._log(f"🌍 Using language hint: {locale}")
            
            self._log("πŸ” Analyzing image with Azure Document Intelligence...")
            
            # Call Document Intelligence API with read model
            # Pass locale if provided (helps with language-specific OCR)
            if locale:
                poller = self.client.begin_analyze_document(
                    "prebuilt-read",  # Use the read model for OCR
                    document=image_bytes,
                    locale=locale
                )
            else:
                poller = self.client.begin_analyze_document(
                    "prebuilt-read",  # Use the read model for OCR
                    document=image_bytes
                )
            
            # Wait for result
            result = poller.result()
            
            # Extract text from result
            if result.pages:
                for page in result.pages:
                    # Process lines (better structure than words)
                    if hasattr(page, 'lines') and page.lines:
                        for line in page.lines:
                            # Extract text
                            text = line.content.strip()
                            if not text:
                                continue
                            
                            # Get bounding polygon
                            if hasattr(line, 'polygon') and line.polygon:
                                # Convert polygon to vertices
                                vertices = [(int(point.x), int(point.y)) for point in line.polygon]
                                
                                # Calculate bounding box
                                xs = [v[0] for v in vertices]
                                ys = [v[1] for v in vertices]
                                x_min, x_max = min(xs), max(xs)
                                y_min, y_max = min(ys), max(ys)
                                
                                # Get confidence (if available)
                                confidence = getattr(line, 'confidence', 0.9)
                                
                                results.append(OCRResult(
                                    text=text,
                                    bbox=(x_min, y_min, x_max - x_min, y_max - y_min),
                                    confidence=confidence,
                                    vertices=vertices
                                ))
                            else:
                                # Fallback: use bounding regions if polygon not available
                                if hasattr(line, 'bounding_regions') and line.bounding_regions:
                                    for region in line.bounding_regions:
                                        if hasattr(region, 'polygon') and region.polygon:
                                            vertices = [(int(point.x), int(point.y)) for point in region.polygon]
                                            xs = [v[0] for v in vertices]
                                            ys = [v[1] for v in vertices]
                                            x_min, x_max = min(xs), max(xs)
                                            y_min, y_max = min(ys), max(ys)
                                            
                                            confidence = getattr(line, 'confidence', 0.9)
                                            
                                            results.append(OCRResult(
                                                text=text,
                                                bbox=(x_min, y_min, x_max - x_min, y_max - y_min),
                                                confidence=confidence,
                                                vertices=vertices
                                            ))
                                            break  # Use first region only
            
            if results:
                self._log(f"βœ… Detected {len(results)} text regions")
            else:
                self._log("⚠️ No text detected", "warning")
            
        except Exception as e:
            self._log(f"❌ Error in Azure Document Intelligence detection: {str(e)}", "error")
            import traceback
            self._log(traceback.format_exc(), "debug")
        
        return results


class OCRManager:
    """Manager for multiple OCR providers"""
    
    def __init__(self, log_callback=None):
        self.log_callback = log_callback
        self.providers = {
            'custom-api': CustomAPIProvider(log_callback) ,
            'manga-ocr': MangaOCRProvider(log_callback),
            'easyocr': EasyOCRProvider(log_callback),
            'paddleocr': PaddleOCRProvider(log_callback),
            'doctr': DocTROCRProvider(log_callback),
            'rapidocr': RapidOCRProvider(log_callback),
            'Qwen2-VL': Qwen2VL(log_callback),
            'azure': AzureComputerVisionProvider(log_callback),
            'azure-document-intelligence': AzureDocumentIntelligenceProvider(log_callback)
        }
        self.current_provider = None
        self.stop_flag = None
        
    def get_provider(self, name: str) -> Optional[OCRProvider]:
        """Get OCR provider by name"""
        return self.providers.get(name)
    
    def set_current_provider(self, name: str):
        """Set current active provider"""
        if name in self.providers:
            self.current_provider = name
            return True
        return False
    
    def check_provider_status(self, name: str) -> Dict[str, bool]:
        """Check installation and loading status of provider"""
        provider = self.providers.get(name)
        if not provider:
            return {'installed': False, 'loaded': False}
        
        result = {
            'installed': provider.check_installation(),
            'loaded': provider.is_loaded
        }
        if self.log_callback:
            self.log_callback(f"DEBUG: check_provider_status({name}) returning loaded={result['loaded']}", "debug")
        return result
    
    def install_provider(self, name: str, progress_callback=None) -> bool:
        """Install a provider"""
        provider = self.providers.get(name)
        if not provider:
            return False
        
        return provider.install(progress_callback)
    
    def load_provider(self, name: str, **kwargs) -> bool:
        """Load a provider's model with optional parameters"""
        provider = self.providers.get(name)
        if not provider:
            return False
        
        return provider.load_model(**kwargs)  # <-- Passes model_size and any other kwargs
    
    def shutdown(self):
        """Release models/processors/tokenizers for all providers and clear caches."""
        try:
            import gc
            for name, provider in list(self.providers.items()):
                try:
                    if hasattr(provider, 'model'):
                        provider.model = None
                    if hasattr(provider, 'processor'):
                        provider.processor = None
                    if hasattr(provider, 'tokenizer'):
                        provider.tokenizer = None
                    if hasattr(provider, 'reader'):
                        provider.reader = None
                    if hasattr(provider, 'is_loaded'):
                        provider.is_loaded = False
                except Exception:
                    pass
            gc.collect()
            try:
                import torch
                torch.cuda.empty_cache()
            except Exception:
                pass
        except Exception:
            pass

    def detect_text(self, image: np.ndarray, provider_name: str = None, **kwargs) -> List[OCRResult]:
        """Detect text using specified or current provider"""
        provider_name = provider_name or self.current_provider
        if not provider_name:
            return []
        
        provider = self.providers.get(provider_name)
        if not provider:
            print(f"[DEBUG] Provider '{provider_name}' not found")
            print(f"[DEBUG] Available providers: {list(self.providers.keys())}")
            return []
        
        print(f"[DEBUG] Using provider: {provider_name}")
        return provider.detect_text(image, **kwargs)
    
    def set_stop_flag(self, stop_flag):
        """Set stop flag for all providers"""
        self.stop_flag = stop_flag
        for provider in self.providers.values():
            if hasattr(provider, 'set_stop_flag'):
                provider.set_stop_flag(stop_flag)
    
    def reset_stop_flags(self):
        """Reset stop flags for all providers"""
        for provider in self.providers.values():
            if hasattr(provider, 'reset_stop_flags'):
                provider.reset_stop_flags()