forked from nih23/Tibetan-NLP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui_ocr_workbench.py
More file actions
2247 lines (2088 loc) · 86.3 KB
/
ui_ocr_workbench.py
File metadata and controls
2247 lines (2088 loc) · 86.3 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
from __future__ import annotations
import json
import os
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import gradio as gr
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from ui_workbench import (
_apply_donut_ui_preprocess,
_compute_line_projection_state,
_load_donut_ocr_runtime_cached,
_resolve_donut_runtime_dirs,
_segment_lines_in_text_crop,
run_tibetan_text_line_split_classical,
)
try:
from pechabridge.ocr.preprocess_bdrc import (
BDRCPreprocessConfig,
preprocess_image_bdrc,
)
except Exception:
BDRCPreprocessConfig = None
preprocess_image_bdrc = None
try:
from pechabridge.ocr.preprocess_rgb import (
RGBLinePreprocessConfig,
preprocess_image_rgb_lines,
)
except Exception:
RGBLinePreprocessConfig = None
preprocess_image_rgb_lines = None
try:
import torch
except Exception:
torch = None
ROOT = Path(__file__).resolve().parent
MODE_AUTO = "Fully Automatic OCR"
MODE_MANUAL = "Manual Mode"
_DONUT_ACTIVE_RUNTIME: Dict[str, Any] = {"checkpoint": "", "runtime": None}
def _is_manual_mode(mode: str) -> bool:
return str(mode or "").strip() == MODE_MANUAL
def _load_font() -> ImageFont.ImageFont:
try:
return ImageFont.truetype("DejaVuSans.ttf", 13)
except Exception:
return ImageFont.load_default()
def _is_hf_model_dir(p: Path) -> bool:
if not p.exists() or not p.is_dir():
return False
if not (p / "config.json").exists():
return False
return (
(p / "pytorch_model.bin").exists()
or (p / "model.safetensors").exists()
or (p / "model.safetensors.index.json").exists()
)
def _is_repro_checkpoint(p: Path) -> bool:
if not _is_hf_model_dir(p):
return False
repro = p / "repro"
return (
repro.exists()
and (repro / "generate_config.json").exists()
and (repro / "image_preprocess.json").exists()
and (repro / "tokenizer").exists()
and (repro / "image_processor").exists()
)
def _checkpoint_step(p: Path) -> int:
name = p.name.strip().lower()
if name.startswith("checkpoint-"):
raw = name.replace("checkpoint-", "", 1)
try:
return int(raw)
except Exception:
return -1
return -1
def _is_plain_checkpoint_with_runtime_assets(p: Path) -> bool:
if not _is_hf_model_dir(p):
return False
parent = p.parent
has_parent_assets = (parent / "tokenizer").exists() and (parent / "image_processor").exists()
has_local_gen_cfg = (p / "generation_config.json").exists()
return bool(has_parent_assets or has_local_gen_cfg)
def _find_donut_checkpoint() -> Tuple[str, str]:
preferred = (ROOT / "models" / "ocr").resolve()
fallback_root = (ROOT / "models").resolve()
repro_candidates: List[Path] = []
plain_candidates: List[Path] = []
if preferred.exists():
for p in sorted(preferred.rglob("checkpoint-*")):
if _is_repro_checkpoint(p):
repro_candidates.append(p.resolve())
elif _is_plain_checkpoint_with_runtime_assets(p):
plain_candidates.append(p.resolve())
if not repro_candidates and not plain_candidates:
for p in sorted(preferred.rglob("*")):
if p.is_dir() and _is_repro_checkpoint(p):
repro_candidates.append(p.resolve())
elif p.is_dir() and _is_plain_checkpoint_with_runtime_assets(p):
plain_candidates.append(p.resolve())
if not repro_candidates and not plain_candidates and fallback_root.exists():
for p in sorted(fallback_root.rglob("checkpoint-*")):
if _is_repro_checkpoint(p):
repro_candidates.append(p.resolve())
elif _is_plain_checkpoint_with_runtime_assets(p):
plain_candidates.append(p.resolve())
if not repro_candidates and not plain_candidates:
for p in sorted(fallback_root.rglob("*")):
if p.is_dir() and _is_repro_checkpoint(p):
repro_candidates.append(p.resolve())
elif p.is_dir() and _is_plain_checkpoint_with_runtime_assets(p):
plain_candidates.append(p.resolve())
if repro_candidates:
repro_candidates = sorted(repro_candidates, key=_checkpoint_step, reverse=True)
return str(repro_candidates[0]), f"Auto-selected DONUT checkpoint (repro): {repro_candidates[0]}"
if plain_candidates:
plain_candidates = sorted(plain_candidates, key=_checkpoint_step, reverse=True)
return (
str(plain_candidates[0]),
"Auto-selected DONUT checkpoint (without repro, using parent tokenizer/image_processor): "
f"{plain_candidates[0]}",
)
return "", "No DONUT checkpoint found (expected under models/ocr/ or models/)."
def _find_layout_model() -> Tuple[str, str]:
preferred = (ROOT / "models" / "layoutAnalysis").resolve()
fallback_root = (ROOT / "models").resolve()
model_exts = {".pt", ".onnx", ".torchscript"}
candidates: List[Path] = []
def _scan(base: Path) -> None:
if not base.exists():
return
for p in sorted(base.rglob("*")):
if not p.is_file():
continue
if p.suffix.lower() not in model_exts:
continue
candidates.append(p.resolve())
_scan(preferred)
if not candidates:
_scan(fallback_root)
if not candidates:
return "", "No layout analysis model found (expected under models/layoutAnalysis/)."
return str(candidates[0]), f"Auto-selected layout model: {candidates[0]}"
def _normalize_box(box: List[int], w: int, h: int) -> Optional[List[int]]:
if not isinstance(box, (list, tuple)) or len(box) != 4:
return None
try:
x1, y1, x2, y2 = [int(v) for v in box]
except Exception:
return None
x1 = max(0, min(w - 1, x1))
y1 = max(0, min(h - 1, y1))
x2 = max(0, min(w, x2))
y2 = max(0, min(h, y2))
if x2 <= x1 or y2 <= y1:
return None
return [x1, y1, x2, y2]
def _sort_lines(rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
return sorted(rows, key=lambda r: (int(r["line_box"][1]), int(r["line_box"][0]), int(r["line_id"])))
def _render_overlay(image: np.ndarray, lines: List[Dict[str, Any]], roi: Optional[List[int]] = None) -> np.ndarray:
panel = Image.fromarray(np.asarray(image).astype(np.uint8)).convert("RGB")
draw = ImageDraw.Draw(panel)
font = _load_font()
def _draw_strong_rect(box: List[int], color: Tuple[int, int, int], inner_width: int = 4, outer_width: int = 8) -> None:
x1, y1, x2, y2 = [int(v) for v in box]
# Outer dark stroke for contrast on bright backgrounds.
draw.rectangle((x1, y1, x2, y2), outline=(0, 0, 0), width=max(2, int(outer_width)))
# Inner bright stroke.
draw.rectangle((x1, y1, x2, y2), outline=color, width=max(2, int(inner_width)))
for i, rec in enumerate(_sort_lines(lines), start=1):
x1, y1, x2, y2 = [int(v) for v in rec["line_box"]]
_draw_strong_rect([x1, y1, x2, y2], color=(0, 255, 255), inner_width=4, outer_width=8)
tag = f"line {i}"
tx1 = x1 + 2
ty1 = max(0, y1 - 20)
tx2 = x1 + 18 + 8 * len(tag)
ty2 = max(16, y1 - 2)
draw.rectangle((tx1, ty1, tx2, ty2), fill=(0, 0, 0))
draw.rectangle((tx1, ty1, tx2, ty2), outline=(0, 255, 255), width=2)
draw.text((tx1 + 4, ty1 + 2), tag, fill=(255, 255, 255), font=font)
if roi and len(roi) == 4:
rx1, ry1, rx2, ry2 = [int(v) for v in roi]
_draw_strong_rect([rx1, ry1, rx2, ry2], color=(255, 64, 255), inner_width=4, outer_width=8)
return np.asarray(panel).astype(np.uint8, copy=False)
def _line_text(rows: List[Dict[str, Any]]) -> str:
lines = _sort_lines(rows)
return "\n".join([str(r.get("text", "") or "") for r in lines])
def _to_rgb_uint8(path: str) -> np.ndarray:
arr = np.asarray(Image.open(path).convert("RGB")).astype(np.uint8)
return arr
def _resolve_device_for_runtime(pref: str) -> str:
p = str(pref or "auto").strip().lower()
if p in {"", "auto"}:
if torch is not None and bool(getattr(torch.cuda, "is_available", lambda: False)()):
return "cuda:0"
return "cpu"
if p.startswith("cuda"):
if torch is None or not bool(getattr(torch.cuda, "is_available", lambda: False)()):
return "cpu"
return p
def _ensure_donut_runtime_loaded(
donut_checkpoint: str,
device_pref: str,
) -> Tuple[Optional[Dict[str, Any]], str]:
if torch is None:
return None, "PyTorch not available."
model_dir, tokenizer_dir, image_processor_dir, err = _resolve_donut_runtime_dirs(donut_checkpoint)
if err:
return None, str(err)
checkpoint_key = str(Path(donut_checkpoint).expanduser().resolve())
target_device = _resolve_device_for_runtime(device_pref)
active_ckpt = str(_DONUT_ACTIVE_RUNTIME.get("checkpoint") or "")
active_runtime = _DONUT_ACTIVE_RUNTIME.get("runtime")
if active_runtime is not None and active_ckpt == checkpoint_key:
cur_device = str(active_runtime.get("device") or "")
if cur_device != target_device:
try:
active_runtime["model"].to(target_device)
active_runtime["device"] = target_device
active_runtime["device_msg"] = f"Moved DONUT runtime to {target_device}"
return active_runtime, str(active_runtime["device_msg"])
except Exception:
# Fall back to loading a fresh runtime below.
pass
return active_runtime, f"DONUT runtime ready on {cur_device or target_device}"
try:
runtime = _load_donut_ocr_runtime_cached(
str(model_dir),
str(tokenizer_dir),
str(image_processor_dir),
target_device,
)
except Exception as exc:
return None, f"Failed loading DONUT runtime: {type(exc).__name__}: {exc}"
_DONUT_ACTIVE_RUNTIME["checkpoint"] = checkpoint_key
_DONUT_ACTIVE_RUNTIME["runtime"] = runtime
return runtime, f"DONUT runtime loaded on {runtime.get('device', target_device)}"
def _strip_special_token_strings_local(text: str, tokenizer: Any) -> str:
out = str(text or "")
try:
toks = sorted(
[str(t) for t in getattr(tokenizer, "all_special_tokens", []) if isinstance(t, str) and t],
key=len,
reverse=True,
)
except Exception:
toks = []
for tok in toks:
out = out.replace(tok, "")
return out
def _normalize_preprocess_preset(value: str) -> str:
mode = str(value or "").strip().lower()
if mode in {"bdrc_no_bin", "grey"}:
mode = "gray"
if mode in {"rgb_lines", "rgb_line"}:
mode = "rgb"
if mode not in {"bdrc", "gray", "rgb"}:
mode = "bdrc"
return mode
def _effective_preprocess_overrides(
preprocess_preset: str,
bdrc_preprocess_overrides: Optional[Dict[str, Any]] = None,
rgb_preprocess_overrides: Optional[Dict[str, Any]] = None,
) -> Optional[Dict[str, Any]]:
mode = _normalize_preprocess_preset(preprocess_preset)
if mode == "rgb":
if isinstance(rgb_preprocess_overrides, dict) and len(rgb_preprocess_overrides) > 0:
return dict(rgb_preprocess_overrides)
return None
if mode in {"bdrc", "gray"}:
out: Dict[str, Any] = {}
if isinstance(bdrc_preprocess_overrides, dict) and len(bdrc_preprocess_overrides) > 0:
out.update(dict(bdrc_preprocess_overrides))
if mode == "gray":
out["binarize"] = False
# Keep gray preset aligned with training-side defaults.
out["gray_mode"] = "min_rgb"
return out or None
return None
def _apply_workbench_preprocess(
image: Image.Image,
preprocess_preset: str,
bdrc_preprocess_overrides: Optional[Dict[str, Any]] = None,
rgb_preprocess_overrides: Optional[Dict[str, Any]] = None,
) -> Image.Image:
rgb = image.convert("RGB")
mode = _normalize_preprocess_preset(preprocess_preset)
effective_overrides = _effective_preprocess_overrides(
preprocess_preset=mode,
bdrc_preprocess_overrides=bdrc_preprocess_overrides,
rgb_preprocess_overrides=rgb_preprocess_overrides,
)
if mode in {"bdrc", "gray"} and preprocess_image_bdrc is not None and BDRCPreprocessConfig is not None:
try:
if isinstance(effective_overrides, dict) and hasattr(BDRCPreprocessConfig, "from_dict"):
cfg = BDRCPreprocessConfig.from_dict(effective_overrides)
else:
cfg = BDRCPreprocessConfig.vit_defaults()
return preprocess_image_bdrc(image=rgb, config=cfg).convert("RGB")
except Exception:
return rgb
if mode == "rgb" and preprocess_image_rgb_lines is not None and RGBLinePreprocessConfig is not None:
try:
if isinstance(effective_overrides, dict) and hasattr(RGBLinePreprocessConfig, "from_dict"):
rgb_cfg = RGBLinePreprocessConfig.from_dict(effective_overrides)
else:
rgb_cfg = RGBLinePreprocessConfig.vit_defaults()
return preprocess_image_rgb_lines(image=rgb, config=rgb_cfg).convert("RGB")
except Exception:
return rgb
try:
return _apply_donut_ui_preprocess(
rgb,
mode,
bdrc_config_override=(
effective_overrides
if mode == "bdrc" and isinstance(effective_overrides, dict)
else None
),
).convert("RGB")
except Exception:
return rgb
def _donut_preprocess_preview(
crop: np.ndarray,
preprocess_preset: str = "bdrc",
bdrc_preprocess_overrides: Optional[Dict[str, Any]] = None,
rgb_preprocess_overrides: Optional[Dict[str, Any]] = None,
) -> Tuple[np.ndarray, np.ndarray, str]:
pil = Image.fromarray(np.asarray(crop).astype(np.uint8)).convert("RGB")
pre = np.asarray(pil).astype(np.uint8, copy=False)
effective_preproc = _normalize_preprocess_preset(preprocess_preset)
try:
proc = _apply_workbench_preprocess(
image=pil,
preprocess_preset=effective_preproc,
bdrc_preprocess_overrides=bdrc_preprocess_overrides,
rgb_preprocess_overrides=rgb_preprocess_overrides,
)
post = np.asarray(proc).astype(np.uint8, copy=False)
except Exception:
post = pre
return pre, post, effective_preproc
def _run_donut_on_crop_fallback(
crop: np.ndarray,
donut_checkpoint: str,
device: str,
max_len: int,
preprocess_preset: str = "bdrc",
bdrc_preprocess_overrides: Optional[Dict[str, Any]] = None,
rgb_preprocess_overrides: Optional[Dict[str, Any]] = None,
) -> Tuple[str, Dict[str, Any]]:
if torch is None:
raise RuntimeError("PyTorch not available.")
runtime, rt_msg = _ensure_donut_runtime_loaded(donut_checkpoint, device)
if runtime is None:
raise RuntimeError(rt_msg)
effective_preproc = _normalize_preprocess_preset(preprocess_preset)
effective_overrides = _effective_preprocess_overrides(
preprocess_preset=effective_preproc,
bdrc_preprocess_overrides=bdrc_preprocess_overrides,
rgb_preprocess_overrides=rgb_preprocess_overrides,
)
effective_max_len = max(8, int(max_len))
pil = Image.fromarray(np.asarray(crop).astype(np.uint8)).convert("RGB")
proc_pil = _apply_workbench_preprocess(
image=pil,
preprocess_preset=effective_preproc,
bdrc_preprocess_overrides=bdrc_preprocess_overrides,
rgb_preprocess_overrides=rgb_preprocess_overrides,
)
image_processor = runtime["image_processor"]
tokenizer = runtime["tokenizer"]
model = runtime["model"]
dev = runtime["device"]
pixel_values = image_processor(images=proc_pil, return_tensors="pt").pixel_values.to(dev)
with torch.no_grad():
generated = model.generate(pixel_values=pixel_values, max_length=int(effective_max_len), num_beams=1)
text = tokenizer.batch_decode(generated, skip_special_tokens=True)[0] if len(generated) else ""
text = _strip_special_token_strings_local(text, tokenizer)
return str(text or ""), {
"ok": True,
"fallback_used": False,
"runtime_status": rt_msg,
"image_preprocess_pipeline_requested": _normalize_preprocess_preset(preprocess_preset),
"image_preprocess_pipeline_effective": effective_preproc,
"preprocess_overrides_applied": bool(isinstance(effective_overrides, dict) and len(effective_overrides) > 0),
"preprocess_overrides": (dict(effective_overrides) if isinstance(effective_overrides, dict) else None),
"generation_max_length_effective": int(effective_max_len),
"device": str(dev),
}
def _run_donut_on_crop(
crop: np.ndarray,
donut_checkpoint: str,
device: str,
max_len: int,
preprocess_preset: str = "bdrc",
bdrc_preprocess_overrides: Optional[Dict[str, Any]] = None,
rgb_preprocess_overrides: Optional[Dict[str, Any]] = None,
) -> Tuple[str, Dict[str, Any], np.ndarray, np.ndarray]:
pre_img, post_img, effective_preproc = _donut_preprocess_preview(
crop,
preprocess_preset=preprocess_preset,
bdrc_preprocess_overrides=bdrc_preprocess_overrides,
rgb_preprocess_overrides=rgb_preprocess_overrides,
)
try:
text_fb, dbg_fb = _run_donut_on_crop_fallback(
crop,
donut_checkpoint,
device,
max_len,
preprocess_preset=preprocess_preset,
bdrc_preprocess_overrides=bdrc_preprocess_overrides,
rgb_preprocess_overrides=rgb_preprocess_overrides,
)
dbg_fb.setdefault("effective_preprocess_preview", effective_preproc)
return text_fb, dbg_fb, pre_img, post_img
except Exception as exc:
return "", {
"ok": False,
"error": f"{type(exc).__name__}: {exc}",
"image_preprocess_pipeline_effective": effective_preproc,
"effective_preprocess_preview": effective_preproc,
}, pre_img, post_img
@dataclass
class OCRRuntime:
donut_path: str
layout_path: str
def _base_state() -> Dict[str, Any]:
return {
"image_path": "",
"image_name": "",
"image": None,
"line_rows": [],
"manual_anchor": None,
"last_mode": "",
"last_debug_text": "",
}
def _bdrc_ui_defaults() -> Dict[str, Any]:
base: Dict[str, Any] = {}
try:
if BDRCPreprocessConfig is not None:
base = dict(BDRCPreprocessConfig.vit_defaults().to_dict())
except Exception:
base = {}
return {
"gray_mode": str(base.get("gray_mode", "luma")),
"normalize_background": bool(base.get("normalize_background", False)),
"background_blur_ksize": int(base.get("background_blur_ksize", 0)),
"background_strength": float(base.get("background_strength", 1.0)),
"upscale_factor": float(base.get("upscale_factor", 1.0)),
"upscale_interpolation": str(base.get("upscale_interpolation", "lanczos")),
"binarize": bool(base.get("binarize", True)),
"threshold_method": str(base.get("threshold_method", "adaptive")),
"threshold_block_size": int(base.get("threshold_block_size", 51)),
"threshold_c": int(base.get("threshold_c", 13)),
"fixed_threshold": int(base.get("fixed_threshold", 120)),
"morph_close": bool(base.get("morph_close", False)),
"morph_close_kernel": int(base.get("morph_close_kernel", 2)),
"remove_small_components": bool(base.get("remove_small_components", False)),
"min_component_area": int(base.get("min_component_area", 12)),
}
def _build_bdrc_preprocess_overrides_ui(
gray_mode: str,
normalize_background: bool,
background_blur_ksize: int,
background_strength: float,
upscale_factor: float,
upscale_interpolation: str,
binarize: bool,
threshold_method: str,
threshold_block_size: int,
threshold_c: int,
fixed_threshold: int,
morph_close: bool,
morph_close_kernel: int,
remove_small_components: bool,
min_component_area: int,
) -> Dict[str, Any]:
gm = str(gray_mode or "luma").strip().lower()
if gm not in {"luma", "min_rgb", "max_rgb", "r", "g", "b"}:
gm = "luma"
interp = str(upscale_interpolation or "lanczos").strip().lower()
if interp not in {"nearest", "linear", "cubic", "lanczos"}:
interp = "lanczos"
tmethod = str(threshold_method or "adaptive").strip().lower()
if tmethod not in {"adaptive", "otsu", "fixed"}:
tmethod = "adaptive"
block = int(max(3, int(threshold_block_size)))
if block % 2 == 0:
block += 1
blur_k = int(max(0, int(background_blur_ksize)))
if blur_k > 0 and blur_k % 2 == 0:
blur_k += 1
close_k = int(max(0, int(morph_close_kernel)))
if close_k > 0 and close_k % 2 == 0:
close_k += 1
return {
"gray_mode": gm,
"normalize_background": bool(normalize_background),
"background_blur_ksize": blur_k,
"background_strength": float(max(0.0, min(3.0, float(background_strength)))),
"upscale_factor": float(max(1.0, float(upscale_factor))),
"upscale_interpolation": interp,
"binarize": bool(binarize),
"threshold_method": tmethod,
"adaptive_threshold": bool(tmethod == "adaptive"),
"threshold_block_size": int(block),
"threshold_c": int(threshold_c),
"fixed_threshold": int(max(0, min(255, int(fixed_threshold)))),
"morph_close": bool(morph_close),
"morph_close_kernel": int(close_k),
"remove_small_components": bool(remove_small_components),
"min_component_area": int(max(0, int(min_component_area))),
}
def _rgb_ui_defaults() -> Dict[str, Any]:
base: Dict[str, Any] = {}
try:
if RGBLinePreprocessConfig is not None:
base = dict(RGBLinePreprocessConfig.vit_defaults().to_dict())
except Exception:
base = {}
return {
"preserve_color": bool(base.get("preserve_color", True)),
"normalize_background": bool(base.get("normalize_background", True)),
"background_method": str(base.get("background_method", "shade_correct")),
"background_blur_ksize": int(base.get("background_blur_ksize", 0)),
"background_strength": float(base.get("background_strength", 0.35)),
"contrast": float(base.get("contrast", 1.0)),
"denoise": bool(base.get("denoise", False)),
"morph_close": bool(base.get("morph_close", False)),
"morph_close_kernel": int(base.get("morph_close_kernel", 3)),
"remove_small_components": bool(base.get("remove_small_components", False)),
"min_component_area": int(base.get("min_component_area", 12)),
"upscale_factor": float(base.get("upscale_factor", 1.0)),
"upscale_interpolation": str(base.get("upscale_interpolation", "lanczos")),
"ink_normalization": bool(base.get("ink_normalization", True)),
"ink_strength": float(base.get("ink_strength", 0.2)),
}
def _build_rgb_preprocess_overrides_ui(
preserve_color: bool,
normalize_background: bool,
background_method: str,
background_blur_ksize: int,
background_strength: float,
contrast: float,
denoise: bool,
morph_close: bool,
morph_close_kernel: int,
remove_small_components: bool,
min_component_area: int,
upscale_factor: float,
upscale_interpolation: str,
ink_normalization: bool,
ink_strength: float,
) -> Dict[str, Any]:
bg_method = str(background_method or "shade_correct").strip().lower()
if bg_method not in {"none", "shade_correct", "rolling_ball_like", "top_hat"}:
bg_method = "shade_correct"
interp = str(upscale_interpolation or "lanczos").strip().lower()
if interp not in {"nearest", "linear", "cubic", "lanczos"}:
interp = "lanczos"
blur_k = int(max(0, int(background_blur_ksize)))
if blur_k > 0 and blur_k % 2 == 0:
blur_k += 1
close_k = int(max(0, int(morph_close_kernel)))
if close_k > 0 and close_k % 2 == 0:
close_k += 1
return {
"preserve_color": bool(preserve_color),
"normalize_background": bool(normalize_background),
"background_method": bg_method,
"background_blur_ksize": int(blur_k),
"background_strength": float(max(0.0, min(1.0, float(background_strength)))),
"contrast": float(max(0.5, min(2.5, float(contrast)))),
"denoise": bool(denoise),
"morph_close": bool(morph_close),
"morph_close_kernel": int(close_k),
"remove_small_components": bool(remove_small_components),
"min_component_area": int(max(0, int(min_component_area))),
"upscale_factor": float(max(1.0, float(upscale_factor))),
"upscale_interpolation": interp,
"ink_normalization": bool(ink_normalization),
"ink_strength": float(max(0.0, min(1.0, float(ink_strength)))),
# Keep deterministic preprocessing behavior.
"to_grayscale_prob": 0.0,
}
def _compose_preprocess_ui_settings(
preprocess_preset: str,
*,
gray_mode: str,
normalize_background: bool,
background_blur_ksize: int,
background_strength: float,
upscale_factor: float,
upscale_interpolation: str,
binarize: bool,
threshold_method: str,
threshold_block_size: int,
threshold_c: int,
fixed_threshold: int,
morph_close: bool,
morph_close_kernel: int,
remove_small_components: bool,
min_component_area: int,
rgb_preserve_color: bool,
rgb_normalize_background: bool,
rgb_background_method: str,
rgb_background_blur_ksize: int,
rgb_background_strength: float,
rgb_contrast: float,
rgb_denoise: bool,
rgb_morph_close: bool,
rgb_morph_close_kernel: int,
rgb_remove_small_components: bool,
rgb_min_component_area: int,
rgb_upscale_factor: float,
rgb_upscale_interpolation: str,
rgb_ink_normalization: bool,
rgb_ink_strength: float,
) -> Tuple[str, Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:
preset = _normalize_preprocess_preset(preprocess_preset)
bdrc_overrides = _build_bdrc_preprocess_overrides_ui(
gray_mode=gray_mode,
normalize_background=normalize_background,
background_blur_ksize=int(background_blur_ksize),
background_strength=float(background_strength),
upscale_factor=float(upscale_factor),
upscale_interpolation=upscale_interpolation,
binarize=binarize,
threshold_method=threshold_method,
threshold_block_size=int(threshold_block_size),
threshold_c=int(threshold_c),
fixed_threshold=int(fixed_threshold),
morph_close=morph_close,
morph_close_kernel=int(morph_close_kernel),
remove_small_components=remove_small_components,
min_component_area=int(min_component_area),
)
rgb_overrides = _build_rgb_preprocess_overrides_ui(
preserve_color=rgb_preserve_color,
normalize_background=rgb_normalize_background,
background_method=rgb_background_method,
background_blur_ksize=int(rgb_background_blur_ksize),
background_strength=float(rgb_background_strength),
contrast=float(rgb_contrast),
denoise=rgb_denoise,
morph_close=rgb_morph_close,
morph_close_kernel=int(rgb_morph_close_kernel),
remove_small_components=rgb_remove_small_components,
min_component_area=int(rgb_min_component_area),
upscale_factor=float(rgb_upscale_factor),
upscale_interpolation=rgb_upscale_interpolation,
ink_normalization=rgb_ink_normalization,
ink_strength=float(rgb_ink_strength),
)
if preset == "rgb":
return preset, None, rgb_overrides
if preset == "gray":
gray_overrides = dict(bdrc_overrides)
gray_overrides["binarize"] = False
gray_overrides["gray_mode"] = "min_rgb"
return preset, gray_overrides, None
return preset, bdrc_overrides, None
def _run_full_auto(
state: Dict[str, Any],
donut_checkpoint: str,
layout_model: str,
device: str,
max_len: int,
preprocess_preset: str = "bdrc",
bdrc_preprocess_overrides: Optional[Dict[str, Any]] = None,
rgb_preprocess_overrides: Optional[Dict[str, Any]] = None,
) -> Tuple[np.ndarray, str, str, Dict[str, Any], str, Optional[np.ndarray], Optional[np.ndarray]]:
image = state.get("image")
if image is None:
return None, "", "Please upload an image first.", state, "{}", state.get("last_donut_pre"), state.get("last_donut_post")
if not donut_checkpoint.strip():
return image, "", "DONUT checkpoint is missing.", state, "{}", state.get("last_donut_pre"), state.get("last_donut_post")
if not layout_model.strip():
return image, "", "Layout model is missing.", state, "{}", state.get("last_donut_pre"), state.get("last_donut_post")
split_out = run_tibetan_text_line_split_classical(
image=np.asarray(image).astype(np.uint8, copy=False),
model_path=layout_model,
conf=0.25,
imgsz=1024,
device=device if device != "auto" else "",
min_line_height=10,
projection_smooth=9,
projection_threshold_rel=0.20,
merge_gap_px=5,
draw_parent_boxes=True,
detect_red_text=False,
red_min_redness=26,
red_min_saturation=35,
red_column_fill_rel=0.07,
red_merge_gap_px=14,
red_min_width_px=18,
draw_red_boxes=False,
)
overlay, split_status, split_json, _, _, _, _, _, click_state = split_out
line_records_raw = []
if isinstance(click_state, dict):
line_records_raw = click_state.get("line_boxes") or []
src = np.asarray(image).astype(np.uint8, copy=False)
h, w = src.shape[:2]
rows: List[Dict[str, Any]] = []
last_pre: Optional[np.ndarray] = None
last_post: Optional[np.ndarray] = None
for rec in line_records_raw:
box = _normalize_box(rec.get("line_box") or [], w, h)
if box is None:
continue
x1, y1, x2, y2 = box
crop = src[y1:y2, x1:x2]
text, dbg, pre_img, post_img = _run_donut_on_crop(
crop,
donut_checkpoint,
device,
max_len,
preprocess_preset=preprocess_preset,
bdrc_preprocess_overrides=bdrc_preprocess_overrides,
rgb_preprocess_overrides=rgb_preprocess_overrides,
)
last_pre, last_post = pre_img, post_img
rows.append(
{
"line_id": int(rec.get("line_id", len(rows) + 1)),
"line_box": box,
"text": text,
"ocr_debug": dbg,
"source": "full_auto",
}
)
rows = _sort_lines(rows)
state["line_rows"] = rows
state["manual_anchor"] = None
state["last_mode"] = "full_auto"
state["last_donut_pre"] = last_pre
state["last_donut_post"] = last_post
state["last_debug_text"] = str(rows[-1].get("text", "") if rows else "")
transcript = _line_text(rows)
debug = {
"ok": True,
"mode": "full_auto",
"split_status": split_status,
"line_count": len(rows),
"image_preprocess_pipeline": _normalize_preprocess_preset(preprocess_preset),
"preprocess_overrides": _effective_preprocess_overrides(
preprocess_preset=preprocess_preset,
bdrc_preprocess_overrides=bdrc_preprocess_overrides,
rgb_preprocess_overrides=rgb_preprocess_overrides,
),
"bdrc_preprocess_overrides": (
dict(bdrc_preprocess_overrides)
if isinstance(bdrc_preprocess_overrides, dict)
else None
),
"rgb_preprocess_overrides": (
dict(rgb_preprocess_overrides)
if isinstance(rgb_preprocess_overrides, dict)
else None
),
"split_json": json.loads(split_json) if (split_json or "").strip().startswith("{") else split_json,
}
strong_overlay = _render_overlay(src, rows)
return (
strong_overlay,
transcript,
f"{split_status} OCR executed on {len(rows)} line(s).",
state,
json.dumps(debug, ensure_ascii=False, indent=2),
state.get("last_donut_pre"),
state.get("last_donut_post"),
)
def _find_line_hit(rows: List[Dict[str, Any]], x: int, y: int) -> Optional[Dict[str, Any]]:
hits: List[Tuple[int, Dict[str, Any]]] = []
for rec in rows:
box = rec.get("line_box") or []
if len(box) != 4:
continue
x1, y1, x2, y2 = [int(v) for v in box]
if x1 <= x <= x2 and y1 <= y <= y2:
area = max(1, (x2 - x1) * (y2 - y1))
hits.append((area, rec))
if not hits:
return None
hits.sort(key=lambda t: t[0])
return hits[0][1]
def _roi_is_single_line(roi_w: int, roi_h: int) -> bool:
if roi_h <= 0 or roi_w <= 0:
return False
ratio = float(roi_w) / float(max(1, roi_h))
return ratio >= 4.0 or roi_h <= 80
def _add_or_update_line(rows: List[Dict[str, Any]], row: Dict[str, Any]) -> List[Dict[str, Any]]:
box = row.get("line_box") or [0, 0, 0, 0]
for i, rec in enumerate(rows):
if list(rec.get("line_box") or []) == list(box):
rows[i] = row
return _sort_lines(rows)
rows.append(row)
return _sort_lines(rows)
def _manual_click(
state: Dict[str, Any],
donut_checkpoint: str,
layout_model: str,
device: str,
max_len: int,
preprocess_preset: str,
bdrc_preprocess_overrides: Optional[Dict[str, Any]],
rgb_preprocess_overrides: Optional[Dict[str, Any]],
evt: gr.SelectData,
) -> Tuple[np.ndarray, str, str, Dict[str, Any], str, Optional[np.ndarray], Optional[np.ndarray]]:
image = state.get("image")
if image is None:
return None, "", "Please upload an image first.", state, "{}", state.get("last_donut_pre"), state.get("last_donut_post")
if not donut_checkpoint.strip():
return image, "", "DONUT checkpoint is missing.", state, "{}", state.get("last_donut_pre"), state.get("last_donut_post")
idx = getattr(evt, "index", None)
if not isinstance(idx, (tuple, list)) or len(idx) < 2:
return np.asarray(image), _line_text(state.get("line_rows") or []), "Click position not available.", state, "{}", state.get("last_donut_pre"), state.get("last_donut_post")
try:
click_x, click_y = int(idx[0]), int(idx[1])
except Exception:
return np.asarray(image), _line_text(state.get("line_rows") or []), "Invalid click position.", state, "{}", state.get("last_donut_pre"), state.get("last_donut_post")
src = np.asarray(image).astype(np.uint8, copy=False)
h, w = src.shape[:2]
click_x = max(0, min(w - 1, click_x))
click_y = max(0, min(h - 1, click_y))
rows = list(state.get("line_rows") or [])
hit = _find_line_hit(rows, click_x, click_y)
if hit is not None:
x1, y1, x2, y2 = [int(v) for v in hit["line_box"]]
crop = src[y1:y2, x1:x2]
text, dbg, pre_img, post_img = _run_donut_on_crop(
crop,
donut_checkpoint,
device,
max_len,
preprocess_preset=preprocess_preset,
bdrc_preprocess_overrides=bdrc_preprocess_overrides,
rgb_preprocess_overrides=rgb_preprocess_overrides,
)
new_row = dict(hit)
new_row["text"] = text
new_row["ocr_debug"] = dbg
new_row["source"] = "manual_line_click"
rows = _add_or_update_line(rows, new_row)
state["line_rows"] = rows
state["last_donut_pre"] = pre_img
state["last_donut_post"] = post_img
state["last_debug_text"] = str(text or "")
overlay = _render_overlay(src, rows)
return overlay, _line_text(rows), f"Re-transcribed line at click ({click_x},{click_y}).", state, json.dumps(
{"ok": True, "mode": "manual", "action": "clicked_existing_line", "line_box": new_row["line_box"]},
ensure_ascii=False,
indent=2,
), state.get("last_donut_pre"), state.get("last_donut_post")
anchor = state.get("manual_anchor")
if not isinstance(anchor, (list, tuple)) or len(anchor) != 2:
state["manual_anchor"] = [int(click_x), int(click_y)]
overlay = _render_overlay(src, rows)
return overlay, _line_text(rows), f"Start point set at ({click_x},{click_y}). Click a second point to define ROI.", state, "{}", state.get("last_donut_pre"), state.get("last_donut_post")
ax, ay = int(anchor[0]), int(anchor[1])
state["manual_anchor"] = None
x1, x2 = sorted([ax, click_x])
y1, y2 = sorted([ay, click_y])
if (x2 - x1) < 3 or (y2 - y1) < 3:
overlay = _render_overlay(src, rows)
return overlay, _line_text(rows), "ROI is too small. Please select a larger area.", state, "{}", state.get("last_donut_pre"), state.get("last_donut_post")
roi = _normalize_box([x1, y1, x2, y2], w, h)
return _manual_process_roi(
state,
donut_checkpoint,
device,
max_len,
roi,
preprocess_preset=preprocess_preset,
bdrc_preprocess_overrides=bdrc_preprocess_overrides,
rgb_preprocess_overrides=rgb_preprocess_overrides,
)