Repository navigation
Expand file tree
/
Copy pathocr_runner.py
More file actions
1484 lines (1336 loc) · 51.1 KB
/
Copy pathocr_runner.py
File metadata and controls
1484 lines (1336 loc) · 51.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""High-speed, zero-corruption PDF & Image OCR engine for /xocr (v2.1.0).
Features:
1. Single-pass C++ PyMuPDF (`fitz`) coordinate-sorted text (`sort=True`) and
Two-Stage Grid + LaTeX `booktabs` table extraction (`page.find_tables()`),
with optional `pdfplumber` fallback.
2. Deterministic Thai/English glyph normalization (fixes legacy Thai PUA
codepoints `U+F700..U+F71A`, decomposed Sara Am `\u0e4d\u0e32` -> `\u0e33`,
and detects `(cid:...)` / `\ufffd` mojibake).
3. Surgical Hybrid Page Router: scores each PDF page for text density, image
coverage, and garble ratio (`needs_ocr`), rasterizing only scanned or
corrupted pages in `--mode auto`.
4. 4-Tier OCR Backend Ladder for scanned pages and standalone images
(`--vlm-backend {auto,typhoon-2b,typhoon-3b-qat,typhoon-3b-4bit,unlimited-ocr,sglang}`):
Tier 1: Live SGLang Server (`http://127.0.0.1:10000` / `infer.py` with
exact `--pdf` / `--image_dir` / `--output_dir` flags)
Tier 2: Local CUDA VLMs - SCB 10X `Typhoon-OCR v1.5` (`typhoon-ai/typhoon-ocr1.5-2b`
on `Qwen3-VL-2B` & `typhoon-ai/typhoon-ocr1.5-3b-qat` in `bfloat16` / `4-bit NF4`)
and Baidu `Unlimited-OCR-2` / `Unlimited-OCR` (`no_repeat_ngram_size=35`),
with automatic HTML `<table>` (`rowspan`/`colspan`) -> RFC-4180 `.csv` surgery
Tier 3: Local `EasyOCR` (`['th', 'en']` / `['en']`)
Tier 4: Local `pytesseract` / `fitz` Tesseract bridge
5. Parallel page rasterization (`--workers`) and surgical page slicing
(`--pages "1-5,8,10-12"`).
"""
import argparse
import contextlib
import csv
import gc
import html.parser
import json
import os
import re
import shutil
import subprocess
import sys
import time
import warnings
from concurrent.futures import ThreadPoolExecutor
sys.dont_write_bytecode = True
warnings.filterwarnings("ignore", category=UserWarning)
if sys.stdout and hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
# Legacy Windows / Adobe Thai Private Use Area (PUA) glyph remapping table
THAI_PUA_MAP = {
"\uf700": "\u0e10", # Tho Than (baseless)
"\uf701": "\u0e34", # Sara I (shifted left)
"\uf702": "\u0e35", # Sara Ii (shifted left)
"\uf703": "\u0e36", # Sara Ue (shifted left)
"\uf704": "\u0e37", # Sara Uee (shifted left)
"\uf705": "\u0e48", # Mai Ek (low left)
"\uf706": "\u0e49", # Mai Tho (low left)
"\uf707": "\u0e4a", # Mai Tri (low left)
"\uf708": "\u0e4b", # Mai Chattawa (low left)
"\uf709": "\u0e4c", # Thanthakhat (low left)
"\uf70a": "\u0e48", # Mai Ek (low)
"\uf70b": "\u0e49", # Mai Tho (low)
"\uf70c": "\u0e4a", # Mai Tri (low)
"\uf70d": "\u0e4b", # Mai Chattawa (low)
"\uf70e": "\u0e4c", # Thanthakhat (low)
"\uf70f": "\u0e0d", # Yo Ying (baseless)
"\uf710": "\u0e31", # Mai Han-Akat (shifted left)
"\uf711": "\u0e4d", # Nikhahit (shifted left)
"\uf712": "\u0e47", # Maitaikhu (shifted left)
"\uf713": "\u0e48", # Mai Ek (high left)
"\uf714": "\u0e49", # Mai Tho (high left)
"\uf715": "\u0e4a", # Mai Tri (high left)
"\uf716": "\u0e4b", # Mai Chattawa (high left)
"\uf717": "\u0e4c", # Thanthakhat (high left)
"\uf718": "\u0e38", # Sara U (low)
"\uf719": "\u0e39", # Sara Uu (low)
"\uf71a": "\u0e3a", # Phinthu (low)
}
THAI_PUA_TRANS = str.maketrans(THAI_PUA_MAP)
CID_PATTERN = re.compile(r"\(cid:\d+\)")
SARA_AM_PATTERN = re.compile(r"\u0e4d([\u0e48-\u0e4b]?)\u0e32")
def non_ws_count(text):
"""Return count of non-whitespace characters in text."""
return len(re.sub(r"\s+", "", text or ""))
def normalize_text(raw_text):
"""Normalize Thai PUA codepoints, Sara Am, and zero-width chars."""
if not raw_text:
return ""
text = raw_text.translate(THAI_PUA_TRANS)
# Normalize decomposed Nikhahit + optional tone mark + Sara Aa -> Sara Am
text = SARA_AM_PATTERN.sub("\\1\u0e33", text)
# Remove zero-width space / BOM artifacts inside text streams
text = text.replace("\u200b", "").replace("\ufeff", "")
return text
def evaluate_page_quality(raw_text, page):
"""Compute text quality metrics and decide whether a page needs OCR."""
cid_matches = CID_PATTERN.findall(raw_text or "")
cid_count = len(cid_matches)
rep_count = (raw_text or "").count("\ufffd")
cleaned = CID_PATTERN.sub("", normalize_text(raw_text or "")).strip()
non_ws_len = non_ws_count(cleaned)
total_len = max(1, len(raw_text or ""))
garble_ratio = round((cid_count * 6 + rep_count) / total_len, 4)
image_count = 0
image_area_ratio = 0.0
try:
image_count = len(page.get_images(full=False))
page_area = max(1.0, abs(page.rect.width * page.rect.height))
img_infos = page.get_image_info() or []
max_img_area = 0.0
for info in img_infos:
bbox = info.get("bbox")
if bbox and len(bbox) == 4:
area = max(0.0, (bbox[2] - bbox[0]) * (bbox[3] - bbox[1]))
if area > max_img_area:
max_img_area = area
image_area_ratio = round(min(1.0, max_img_area / page_area), 4)
except Exception: # nosec B110
image_count = 0
needs_ocr = (
non_ws_len < 25
or garble_ratio > 0.05
or (image_count > 0 and non_ws_len < 60)
or (image_area_ratio >= 0.45 and non_ws_len < 250)
)
return {
"clean_text": cleaned,
"char_count": non_ws_len,
"cid_count": cid_count,
"replacement_count": rep_count,
"garble_ratio": garble_ratio,
"image_count": image_count,
"image_area_ratio": image_area_ratio,
"needs_ocr": needs_ocr,
}
def parse_page_selection(pages_arg, total_pages):
"""Parse 1-based page spec like '1-5,8,11-13' into 0-based indices."""
if not pages_arg or pages_arg.strip().lower() in ("all", "*"):
return list(range(total_pages))
selected = set()
for part in pages_arg.split(","):
part = part.strip()
if not part:
continue
if "-" in part:
bounds = part.split("-", 1)
start = max(1, int(bounds[0]))
end = min(total_pages, int(bounds[1]))
for p_num in range(start, end + 1):
selected.add(p_num - 1)
else:
p_num = int(part)
if 1 <= p_num <= total_pages:
selected.add(p_num - 1)
return sorted(selected)
def clean_table_rows(raw_rows):
"""Normalize table cells, prune empty columns/rows, and validate tables."""
if not raw_rows:
return []
rows = []
for raw_r in raw_rows:
if not raw_r:
continue
norm_r = []
has_val = False
for cell in raw_r:
val = normalize_text(str(cell or "")).replace("\n", " ").strip()
val = re.sub(r"\s{2,}", " ", val)
if val:
has_val = True
norm_r.append(val)
if has_val:
rows.append(norm_r)
if len(rows) < 2:
return []
ncol = max(len(r) for r in rows)
keep_cols = [
ci for ci in range(ncol) if any(ci < len(r) and r[ci] for r in rows)
]
if len(keep_cols) < 2:
return []
pruned = [
[r[ci] if ci < len(r) else "" for ci in keep_cols] for r in rows
]
multi_col_rows = sum(1 for r in pruned if sum(1 for c in r if c) >= 2)
if multi_col_rows < 2 or (multi_col_rows / len(pruned)) < 0.60:
return []
total_cells = len(pruned) * len(keep_cols)
raw_total = max(1, len(raw_rows) * ncol)
filled_cells = sum(1 for r in pruned for c in r if c)
if (
total_cells > 0
and (
(filled_cells / total_cells) < 0.52
or (filled_cells / raw_total) < 0.32
)
):
return []
return pruned
def _is_booktabs_strip(rows):
"""Return True if a table region looks like a 1-2 row booktabs strip."""
if len(rows) <= 2:
return True
max_nl = max(
(str(c or "").count("\n") for r in rows for c in r), default=0
)
return max_nl >= 2
def _find_booktabs_rule_bboxes(page, drawings=None):
"""Detect LaTeX booktabs horizontal rule clusters (top/mid/bottomrule)."""
if drawings is None:
try:
drawings = page.get_drawings() or []
except Exception: # nosec B110
return []
h_rules = []
for drw in drawings:
rect = drw.get("rect")
if not rect:
continue
width = rect.x1 - rect.x0
height = rect.y1 - rect.y0
if width >= 200 and height <= 4.5:
h_rules.append(
[
float(rect.x0),
float(rect.y0),
float(rect.x1),
float(rect.y1),
]
)
if len(h_rules) < 3:
return []
h_rules.sort(key=lambda r: (r[1], r[0]))
clusters = []
for rule in h_rules:
placed = False
for cl in clusters:
if (
abs(rule[0] - cl["x0"]) < 25
and abs(rule[2] - cl["x1"]) < 25
and 0 <= (rule[1] - cl["last_y"]) < 240
):
if (rule[1] - cl["last_y"]) > 3.5:
cl["rule_count"] += 1
cl["y1"] = max(cl["y1"], rule[3])
cl["last_y"] = rule[3]
placed = True
break
if not placed:
clusters.append(
{
"x0": rule[0],
"y0": rule[1],
"x1": rule[2],
"y1": rule[3],
"last_y": rule[3],
"rule_count": 1,
}
)
return [
[cl["x0"], cl["y0"], cl["x1"], cl["y1"]]
for cl in clusters
if cl["rule_count"] >= 3 and (cl["y1"] - cl["y0"]) >= 25
]
def extract_tables_from_page(page, fitz_mod, raw_text=""):
"""Two-Stage Grid + LaTeX booktabs table extractor using PyMuPDF."""
extracted = []
try:
drawings = page.get_drawings() or []
except Exception: # nosec B110
drawings = []
if not drawings:
return extracted
h_rules_cnt = 0
g_rects_cnt = 0
for drw in drawings:
rect = drw.get("rect")
if not rect:
continue
w = rect.x1 - rect.x0
h = rect.y1 - rect.y0
if w >= 150 and h <= 5:
h_rules_cnt += 1
elif w >= 25 and h >= 10 and drw.get("type") != "f":
g_rects_cnt += 1
if h_rules_cnt < 3 and g_rects_cnt < 8:
return extracted
if (
len(drawings) > 200
and g_rects_cnt < 12
and not re.search(
r"(?:^|\n)\s*(?:Table|Tab\.|ตาราง)\s*(?:\d+|[IVXLCDM]+)?\s*[:.|\-–—]",
raw_text or "",
re.IGNORECASE,
)
):
return extracted
try:
raw_tabs = page.find_tables().tables
except Exception: # nosec B110
raw_tabs = []
# Pre-extract rows before any subsequent page.find_tables(clip=...) call,
# which mutates PyMuPDF's internal table buffers on the same Page object.
cached_tabs = []
for tab in sorted(raw_tabs, key=lambda x: (x.bbox[1], x.bbox[0])):
try:
cached_tabs.append((list(tab.bbox), tab.extract() or []))
except Exception: # nosec B110
pass
groups = []
for box, rows in cached_tabs:
if len(rows) >= 5:
r_ncol = max((len(r) for r in rows if r), default=1)
r_fill = sum(
1 for r in rows for c in (r or []) if c and str(c).strip()
) / max(1, len(rows) * r_ncol)
if r_fill < 0.08:
continue
if (
groups
and abs(box[1] - groups[-1]["bbox"][3]) < 15
and abs(box[0] - groups[-1]["bbox"][0]) < 20
and abs(box[2] - groups[-1]["bbox"][2]) < 20
and (
_is_booktabs_strip(groups[-1]["last_rows"])
or _is_booktabs_strip(rows)
)
):
groups[-1]["bbox"][3] = max(groups[-1]["bbox"][3], box[3])
groups[-1]["rows_list"].append(rows)
groups[-1]["last_rows"] = rows
else:
groups.append(
{
"bbox": box,
"rows_list": [rows],
"last_rows": rows,
"reextract": False,
}
)
# Merge or append pure horizontal-rule booktabs clusters (3-rule tables
# or header bands between \toprule and \midrule missed by lines strategy).
for rbox in _find_booktabs_rule_bboxes(page, drawings=drawings):
matched = False
for grp in groups:
gbox = grp["bbox"]
y_overlap = min(gbox[3], rbox[3]) - max(gbox[1], rbox[1])
if (
abs(gbox[0] - rbox[0]) < 25
and abs(gbox[2] - rbox[2]) < 25
and y_overlap > -15
):
if rbox[1] < gbox[1] - 4 or rbox[3] > gbox[3] + 4:
grp["bbox"] = [
min(gbox[0], rbox[0]),
min(gbox[1], rbox[1]),
max(gbox[2], rbox[2]),
max(gbox[3], rbox[3]),
]
grp["reextract"] = True
matched = True
break
if not matched:
near_rect = fitz_mod.Rect(
0, rbox[1] - 48, page.rect.width, rbox[3] + 48
)
top_rect = fitz_mod.Rect(rbox[0], rbox[1], rbox[2], rbox[1] + 24)
near_txt = page.get_text("text", clip=near_rect) or ""
top_txt = (page.get_text("text", clip=top_rect) or "").strip()
if re.search(
r"(?:^|\n)\s*(?:Table|Tab\.|ตาราง)\s*(?:\d+[A-Za-z]?|[IVXLCDM]+)\s*[:.|\-–—\s]",
near_txt,
re.IGNORECASE,
) and not re.match(
r"^(Algorithm|Figure|Fig\.)\b", top_txt, re.IGNORECASE
):
groups.append(
{
"bbox": rbox,
"rows_list": [],
"last_rows": [],
"reextract": True,
}
)
groups.sort(key=lambda g: (g["bbox"][1], g["bbox"][0]))
for grp in groups:
t0_rows = grp["rows_list"][0] if grp["rows_list"] else []
max_nl = max(
(str(c or "").count("\n") for r in t0_rows for c in r), default=0
)
candidates = []
grp_w = grp["bbox"][2] - grp["bbox"][0]
if (
grp_w < 200
or (
not grp.get("reextract")
and len(grp["rows_list"]) == 1
and len(t0_rows) >= 2
and max_nl < 2
)
):
candidates.append(t0_rows)
else:
try:
clip_rect = fitz_mod.Rect(grp["bbox"])
min_v = 2 if not grp["rows_list"] else 3
sub_tabs = page.find_tables(
clip=clip_rect,
vertical_strategy="text",
horizontal_strategy="text",
min_words_vertical=min_v,
).tables
for st in sub_tabs:
candidates.append(st.extract())
except Exception: # nosec B110
pass
if not candidates and t0_rows:
candidates.append(t0_rows)
for cand in candidates:
cleaned = clean_table_rows(cand)
if cleaned:
extracted.append(cleaned)
return extracted
def rows_to_markdown(rows):
"""Format a 2D list of cleaned table rows as a GFM Markdown table."""
if not rows:
return ""
col_count = max(len(r) for r in rows)
padded = [r + [""] * (col_count - len(r)) for r in rows]
header = [c.replace("|", "\\|") for c in padded[0]]
md_lines = [
"| " + " | ".join(header) + " |",
"| " + " | ".join(["---"] * col_count) + " |",
]
for r in padded[1:]:
escaped = [c.replace("|", "\\|") for c in r]
md_lines.append("| " + " | ".join(escaped) + " |")
return "\n".join(md_lines)
class _HTMLTableParser(html.parser.HTMLParser):
"""Parse HTML <table>...</table> blocks with full rowspan/colspan expansion."""
def __init__(self):
super().__init__()
self.tables = []
self._in_table = False
self._in_row = False
self._in_cell = False
self._cell_parts = []
self._rowspan = 1
self._colspan = 1
self._raw_rows = []
self._cur_row = []
def _flush_cell(self):
if self._in_cell:
self._in_cell = False
txt = normalize_text(
re.sub(r"\s+", " ", "".join(self._cell_parts)).strip()
)
self._cur_row.append((txt, self._rowspan, self._colspan))
self._cell_parts = []
def _flush_row(self):
self._flush_cell()
if self._in_row:
self._in_row = False
if self._cur_row:
self._raw_rows.append(self._cur_row)
self._cur_row = []
def handle_starttag(self, tag, attrs):
t = tag.lower()
if t == "table":
if self._in_table:
self._flush_row()
grid = self._expand_grid(self._raw_rows)
if grid:
self.tables.append(grid)
self._in_table = True
self._raw_rows = []
elif self._in_table and t == "tr":
self._flush_row()
self._in_row = True
self._cur_row = []
elif self._in_row and t in ("td", "th"):
self._flush_cell()
self._in_cell = True
self._cell_parts = []
ad = {k.lower(): (v or "1") for k, v in attrs}
try:
self._rowspan = max(1, int(ad.get("rowspan", "1")))
except ValueError:
self._rowspan = 1
try:
self._colspan = max(1, int(ad.get("colspan", "1")))
except ValueError:
self._colspan = 1
elif self._in_cell and t == "br":
self._cell_parts.append(" ")
def handle_data(self, data):
if self._in_cell:
self._cell_parts.append(data)
def handle_endtag(self, tag):
t = tag.lower()
if t in ("td", "th") and self._in_cell:
self._flush_cell()
elif t == "tr" and self._in_row:
self._flush_row()
elif t == "table" and self._in_table:
self._flush_row()
self._in_table = False
grid = self._expand_grid(self._raw_rows)
if grid:
self.tables.append(grid)
@staticmethod
def _expand_grid(raw_rows):
if not raw_rows:
return []
occupied = {}
max_col = 0
num_rows = len(raw_rows)
for r_idx, row in enumerate(raw_rows):
c_idx = 0
for txt, rspan, cspan in row:
while (r_idx, c_idx) in occupied:
c_idx += 1
for dr in range(rspan):
for dc in range(cspan):
nr = r_idx + dr
nc = c_idx + dc
num_rows = max(num_rows, nr + 1)
max_col = max(max_col, nc + 1)
occupied[(nr, nc)] = (
txt if (dr == 0 and dc == 0) else ""
)
c_idx += cspan
grid = []
for r in range(num_rows):
r_vals = [occupied.get((r, c), "") for c in range(max_col)]
if any(v.strip() for v in r_vals):
grid.append(r_vals)
return grid
def extract_html_tables_from_text(text):
"""Extract and clean HTML <table>...</table> blocks emitted by VLM OCR."""
if not text or "<table" not in text.lower():
return []
parser = _HTMLTableParser()
try:
parser.feed(text)
except Exception: # nosec B110
return []
cleaned_tables = []
for raw_grid in parser.tables:
cleaned = clean_table_rows(raw_grid)
if cleaned:
cleaned_tables.append(cleaned)
elif raw_grid:
cleaned_tables.append(raw_grid)
return cleaned_tables
TYPHOON_V15_PROMPT = (
"Extract all text from the image.\n\n\n"
"Instructions:\n"
"- Only return the clean Markdown.\n"
"- Do not include any explanation or extra text.\n"
"- You must include all information on the page.\n\n\n"
"Formatting Rules:\n"
"- Tables: Render tables using <table>...</table> in clean HTML format.\n"
"- Equations: Render equations using LaTeX syntax with inline ($...$) and block ($$...$$).\n"
"- Images/Charts/Diagrams: Wrap any clearly defined visual areas (e.g. charts, diagrams, pictures) in:\n\n\n"
"<figure>\n"
"Describe the image's main elements (people, objects, text), note any contextual clues "
"(place, event, culture), mention visible text and its meaning, provide deeper analysis "
"when relevant (especially for financial charts, graphs, or documents), comment on style "
"or architecture if relevant, then give a concise overall summary. Describe in Thai.\n"
"</figure>\n\n\n"
"- Page Numbers: Wrap page numbers in <page_number>...</page_number> "
"(e.g., <page_number>14</page_number>).\n"
"- Checkboxes: Use ☐ for unchecked and ☑ for checked boxes.\n"
)
def _resize_image_if_needed(img, max_size=1800):
"""Downscale PIL image only when width or height exceeds max_size (never upscale)."""
width, height = img.size
if width <= 0 or height <= 0 or max_size <= 0:
return img
if width > max_size or height > max_size:
from PIL import Image
if width >= height:
scale = max_size / float(width)
new_size = (max_size, max(1, int(height * scale)))
else:
scale = max_size / float(height)
new_size = (max(1, int(width * scale)), max_size)
return img.resize(new_size, Image.Resampling.LANCZOS)
return img
def _get_torch_device():
"""Return 'cuda' on NVIDIA GPUs, 'mps' on Apple Silicon Metal, or 'cpu'."""
try:
import torch
if torch.cuda.is_available():
return "cuda"
if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
return "mps"
except ImportError:
pass
return "cpu"
def _has_gpu_accel():
"""Return True when CUDA or Apple Silicon MPS acceleration is available."""
return _get_torch_device() in ("cuda", "mps")
def unload_vlm_models():
"""Explicitly release CUDA/MPS VRAM caches between sequential VLM runs."""
gc.collect()
try:
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
elif hasattr(torch, "mps") and hasattr(torch.mps, "empty_cache"):
torch.mps.empty_cache()
except ImportError:
pass
def _run_typhoon_transformers_vlm(
image_paths,
model_id="typhoon-ai/typhoon-ocr1.5-2b",
load_in_4bit=False,
max_new_tokens=2048,
max_image_dim=1800,
):
"""Run SCB 10X Typhoon-OCR v1.5 (Qwen3-VL-2B or Qwen2.5-VL-3B-QAT) 100% locally on GPU/MPS."""
import torch
from PIL import Image
from transformers import AutoModelForImageTextToText, AutoProcessor
unload_vlm_models()
device = _get_torch_device()
use_4bit = bool(load_in_4bit and torch.cuda.is_available())
load_kwargs = {
"device_map": "auto" if device == "cuda" else device,
"attn_implementation": "sdpa",
}
if use_4bit:
from transformers import BitsAndBytesConfig
load_kwargs["quantization_config"] = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_quant_type="nf4",
)
else:
load_kwargs["dtype"] = torch.bfloat16
model = AutoModelForImageTextToText.from_pretrained(
model_id, **load_kwargs
).eval()
processor = AutoProcessor.from_pretrained(model_id)
vlm_texts = {}
try:
for img_p in image_paths:
pil_img = Image.open(img_p).convert("RGB")
pil_img = _resize_image_if_needed(pil_img, max_size=max_image_dim)
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": TYPHOON_V15_PROMPT},
{"type": "image", "image": pil_img},
],
}
]
inputs = processor.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
return_dict=True,
return_tensors="pt",
).to(model.device)
with torch.inference_mode():
generated_ids = model.generate(
**inputs,
max_new_tokens=max_new_tokens,
do_sample=False,
repetition_penalty=1.1,
)
in_len = inputs["input_ids"].shape[1]
out_ids = [out[in_len:] for out in generated_ids]
decoded = processor.batch_decode(
out_ids,
skip_special_tokens=True,
clean_up_tokenization_spaces=False,
)[0]
vlm_texts[img_p] = normalize_text(decoded.strip())
del inputs, generated_ids, out_ids
finally:
del model, processor
unload_vlm_models()
suffix = "_4bit" if use_4bit else "_bf16"
short_name = model_id.split("/")[-1].lower().replace("-", "_")
return {
"vlm_executed": True,
"engine": f"hf_{short_name}{suffix}_{device}",
"vlm_texts": vlm_texts,
}
def _render_page_batch(batch_args):
"""Worker helper opening fitz.Document once per worker batch of pages."""
pdf_path, dpi, items = batch_args
import fitz
if hasattr(fitz, "no_recommend_layout"):
fitz.no_recommend_layout()
rendered = []
doc = fitz.open(pdf_path)
try:
for page_idx, out_png in items:
pix = doc[page_idx].get_pixmap(dpi=dpi)
pix.save(out_png)
rendered.append((page_idx, out_png))
return rendered
finally:
doc.close()
_EASYOCR_READERS = {}
def ocr_image_local(image_path, langs=None):
"""Run local offline OCR on an image via EasyOCR or pytesseract."""
if langs is None:
langs = ["th", "en"]
lang_key = tuple(langs)
try:
with contextlib.redirect_stdout(sys.stderr):
import easyocr
reader = _EASYOCR_READERS.get(lang_key)
if reader is None:
use_gpu = _has_gpu_accel()
try:
reader = easyocr.Reader(
list(langs), gpu=use_gpu, verbose=False
)
except Exception: # nosec B110
reader = easyocr.Reader(
["en"], gpu=use_gpu, verbose=False
)
_EASYOCR_READERS[lang_key] = reader
lines = reader.readtext(image_path, detail=0, paragraph=True)
text = normalize_text("\n".join(lines).strip())
if text:
return {"engine": "easyocr", "text": text}
except Exception: # nosec B110
pass
try:
import pytesseract
from PIL import Image
img = Image.open(image_path)
text = normalize_text(pytesseract.image_to_string(img).strip())
if text:
return {"engine": "pytesseract", "text": text}
except Exception: # nosec B110
pass
return {"engine": "none", "text": ""}
def _read_text_file(path):
"""Read UTF-8 text from a file if it exists, otherwise return empty."""
if path and os.path.isfile(path):
with open(path, "r", encoding="utf-8", errors="replace") as fh:
return normalize_text(fh.read().strip())
return ""
def run_vlm_engine(
target_path, output_dir, image_paths=None, vlm_backend="auto"
):
"""Attempt SGLang server, SCB 10X Typhoon-OCR v1.5, or Baidu Unlimited-OCR VLM."""
targets = image_paths or [target_path]
# Explicit Typhoon-OCR v1.5 local backends
if vlm_backend in ("typhoon-2b", "typhoon-3b-qat", "typhoon-3b-4bit"):
try:
if _has_gpu_accel():
t_model = (
"typhoon-ai/typhoon-ocr1.5-2b"
if vlm_backend == "typhoon-2b"
else "typhoon-ai/typhoon-ocr1.5-3b-qat"
)
return _run_typhoon_transformers_vlm(
targets,
model_id=t_model,
load_in_4bit=(vlm_backend == "typhoon-3b-4bit"),
)
except Exception as exc: # nosec B110
return {
"vlm_executed": False,
"engine": "local_fallback",
"vlm_texts": {},
"reason": f"Typhoon VLM ({vlm_backend}) failed: {exc}",
}
script_dir = os.path.dirname(os.path.abspath(__file__))
candidates = [
os.path.join(script_dir, "infer.py"),
os.path.join(os.getcwd(), "tools", "Unlimited-OCR", "infer.py"),
]
infer_script = next(
(p for p in candidates if p and os.path.isfile(p)), None
)
sglang_live = False
if vlm_backend in ("auto", "sglang"):
try:
import urllib.request
with urllib.request.urlopen(
"http://127.0.0.1:10000/health", timeout=1.5
) as resp:
sglang_live = resp.status == 200
except Exception: # nosec B110
sglang_live = False
if infer_script and sglang_live:
stage_dir = os.path.join(output_dir, "_vlm_stage")
shutil.rmtree(stage_dir, ignore_errors=True)
os.makedirs(stage_dir, exist_ok=True)
staged_map = {}
for img_p in targets:
if img_p.lower().endswith(".pdf"):
continue
base_name = os.path.basename(img_p)
stem, ext = os.path.splitext(base_name)
if ext.lower() in (".tif", ".tiff"):
dst_p = os.path.join(stage_dir, f"{stem}.png")
from PIL import Image
Image.open(img_p).save(dst_p)
else:
dst_p = os.path.join(stage_dir, base_name)
if os.path.abspath(img_p) != os.path.abspath(dst_p):
shutil.copy2(img_p, dst_p)
staged_map[img_p] = os.path.join(output_dir, f"{stem}.md")
flag = "--image_dir" if staged_map else "--pdf"
flag_val = stage_dir if staged_map else target_path
cmd = [
sys.executable,
infer_script,
flag,
flag_val,
"--output_dir",
output_dir,
]
proc = subprocess.run(
cmd, capture_output=True, text=True, check=False
)
if proc.returncode == 0:
vlm_texts = {
img_p: _read_text_file(md_p)
for img_p, md_p in staged_map.items()
}
return {
"vlm_executed": True,
"engine": "sglang_infer_py",
"vlm_texts": vlm_texts,
"stdout_tail": (proc.stdout or "")[-400:],
}
# In "auto" mode on CUDA/MPS, try Typhoon-OCR v1.5 (2B) first if available, then Unlimited-OCR-2
if vlm_backend == "auto":
try:
if _has_gpu_accel():
typhoon_env = os.environ.get(
"TYPHOON_OCR_MODEL", "typhoon-ai/typhoon-ocr1.5-2b"
).strip()
return _run_typhoon_transformers_vlm(
targets, model_id=typhoon_env, load_in_4bit=False
)
except Exception: # nosec B110
pass
if vlm_backend in ("auto", "unlimited-ocr"):
try:
import torch
device = _get_torch_device()
if device in ("cuda", "mps"):
from transformers import AutoModel, AutoTokenizer
unload_vlm_models()
env_model = os.environ.get("UNLIMITED_OCR_MODEL", "").strip()
model_candidates = (
[env_model]
if env_model
else ["baidu/Unlimited-OCR-2", "baidu/Unlimited-OCR"]
)
tokenizer = None
model = None
model_name = model_candidates[0]
for cand_model in model_candidates:
try:
tokenizer = AutoTokenizer.from_pretrained(
cand_model, trust_remote_code=True
)
model = (
AutoModel.from_pretrained(
cand_model,
trust_remote_code=True,
use_safetensors=True,
torch_dtype=torch.bfloat16,
)
.eval()
.to(device)
)
model_name = cand_model
break
except Exception: # nosec B110
continue
if model is None or tokenizer is None:
raise RuntimeError("No Unlimited-OCR model available")
vlm_texts = {}
try:
if image_paths and len(image_paths) > 1:
res = model.infer_multi(
tokenizer,
prompt="<image>Multi page parsing.",
image_files=image_paths,
output_path=output_dir,
image_size=1024,
max_length=32768,
no_repeat_ngram_size=35,
ngram_window=1024,
save_results=True,