Spaces:
Running
Running
Deploy Cham-OCR v24.1-R4 (W=480 default SOTA) + v24.1-R3.1 (W=320), diacritic suppression & calibrated confidence
Browse filesFiles changed (23)
- .gitattributes+6
- Dockerfile+41-41
- ocr-studio/PaddleOCR/ppocr/modeling/backbones/rec_lcnetv3.py+1-1
- ocr-studio/app.py
- ocr-studio/data/cham_dict_v24_1_r3_1.txtAdded+114
- ocr-studio/data/cham_dict_v24_1_r4.txtAdded+114
- ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/cham_dict_v24_1.txtAdded+114
- ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/inference.jsonAdded
- ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/inference.pdiparamsAdded+3
- ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/inference.pdiparams.infoAdded+3
- ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/inference.pdmodelAdded+3
- ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/inference.ymlAdded+156
- ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/model_manifest.jsonAdded+63
- ocr-studio/data/output/rec_cham_inference_v24_1_r4/cham_dict_v24_1.txtAdded+114
- ocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.jsonAdded
- ocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdiparamsAdded+3
- ocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdiparams.infoAdded+3
- ocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdmodelAdded+3
- ocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.ymlAdded+156
- ocr-studio/data/output/rec_cham_inference_v24_1_r4/model_manifest.jsonAdded+65
- ocr-studio/index.html
- ocr-studio/tests/test_quality_gates.py+334-272
- ocr-training/scripts/export_active_learning_r4.pyAdded+249
332 unmodified lines333334335332 unmodified linesocr-studio/data/output/rec_cham_inference_v24_1_r3/inference.pdiparams filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r3/inference.pdiparams.info filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r3/inference.pdmodel filter=lfs diff=lfs merge=lfs -text332 unmodified lines333334335336337338339340341332 unmodified linesocr-studio/data/output/rec_cham_inference_v24_1_r3/inference.pdiparams filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r3/inference.pdiparams.info filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r3/inference.pdmodel filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r3_1/inference.pdiparams filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r3_1/inference.pdiparams.info filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r3_1/inference.pdmodel filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdiparams filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdiparams.info filter=lfs diff=lfs merge=lfs -textocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdmodel filter=lfs diff=lfs merge=lfs -text
1234567891011121314151617181920212223242526272829303132333435363738394041FROM python:3.11-slim# Rebuild timestamp: 2026-08-01T09:26:20Z - Re-assign components using true_core_coords for full line bbox height [30..78]ENV DEBIAN_FRONTEND=noninteractive# Install system dependencies required for OpenCV, PaddlePaddle, and OpenMPRUN apt-get update && apt-get install -y --no-install-recommends \git \libgl1 \libglib2.0-0 \libgomp1 \build-essential \&& rm -rf /var/lib/apt/lists/*# Set working directoryWORKDIR /app# Copy requirements and install python packagesCOPY requirements.txt /app/requirements.txtRUN pip install --no-cache-dir -r requirements.txt# Force cache bust for updated app code & Cham-SVTR V24.1-R3 default modelRUN echo "Cache bust 2026-11-16T16:15:00+07:00 - V24.1-R3 default promotion (POSIX paths fix), Temperature Scaling calibrated_confidence, Stage R4 active learning loop"# Copy application filesCOPY . /app# Environment variables for CPU optimization & HF Spaces portENV PORT=7860ENV CPU_THREADS=1ENV ENABLE_MKLDNN=FalseENV OMP_NUM_THREADS=1ENV MKL_NUM_THREADS=1ENV KMP_DUPLICATE_LIB_OK=TRUEENV PYTHONUNBUFFERED=1# Expose Hugging Face Space default portEXPOSE 7860# Run Cham OCR StudioCMD ["python", "-u", "ocr-studio/app.py"]1234567891011121314151617181920212223242526272829303132333435363738394041FROM python:3.11-slim# Rebuild timestamp: 2026-08-01T09:26:20Z - Re-assign components using true_core_coords for full line bbox height [30..78]ENV DEBIAN_FRONTEND=noninteractive# Install system dependencies required for OpenCV, PaddlePaddle, and OpenMPRUN apt-get update && apt-get install -y --no-install-recommends \git \libgl1 \libglib2.0-0 \libgomp1 \build-essential \&& rm -rf /var/lib/apt/lists/*# Set working directoryWORKDIR /app# Copy requirements and install python packagesCOPY requirements.txt /app/requirements.txtRUN pip install --no-cache-dir -r requirements.txt# Force cache bust for updated app code & Cham-SVTR V24.1-R4 (W=480) + V24.1-R3.1 (W=320) modelsRUN echo "Cache bust 2026-11-17T12:25:00+07:00 - V24.1-R4 (W=480) default SOTA + V24.1-R3.1 (W=320), diacritic fragment suppression, Temperature Scaling calibrated_confidence"# Copy application filesCOPY . /app# Environment variables for CPU optimization & HF Spaces portENV PORT=7860ENV CPU_THREADS=1ENV ENABLE_MKLDNN=FalseENV OMP_NUM_THREADS=1ENV MKL_NUM_THREADS=1ENV KMP_DUPLICATE_LIB_OK=TRUEENV PYTHONUNBUFFERED=1# Expose Hugging Face Space default portEXPOSE 7860# Run Cham OCR StudioCMD ["python", "-u", "ocr-studio/app.py"]
484 unmodified lines485486487488489490491484 unmodified linesreturn out_listif self.training:x = F.adaptive_avg_pool2d(x, [1, 40])else:x = F.avg_pool2d(x, [3, 2])return x484 unmodified lines485486487488489490491484 unmodified linesreturn out_listif self.training:x = F.adaptive_avg_pool2d(x, [1, int(x.shape[3]) // 2])else:x = F.avg_pool2d(x, [3, 2])return x
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114:ꨀꨁꨂꨃꨄꨅꨆꨇꨈꨉꨊꨋꨌꨍꨎꨏꨐꨑꨒꨓꨔꨕꨖꨗꨘꨙꨚꨛꨜꨝꨞꨟꨠꨡꨢꨣꨤꨥꨦꨧꨨꨩꨪꨫꨬꨭꨮꨯꨰꨱꨳꨴꨵꨶꩀꩂꩃꩄꩅꩆꩇꩈꩉꩊꩋꩌꩍ꩐꩑꩒꩓꩔꩕꩖꩗꩘꩙꩜꩝꩞꩟ꨲꩁ0123456789[]().,;-/?!#&*<>{}\_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114:ꨀꨁꨂꨃꨄꨅꨆꨇꨈꨉꨊꨋꨌꨍꨎꨏꨐꨑꨒꨓꨔꨕꨖꨗꨘꨙꨚꨛꨜꨝꨞꨟꨠꨡꨢꨣꨤꨥꨦꨧꨨꨩꨪꨫꨬꨭꨮꨯꨰꨱꨳꨴꨵꨶꩀꩂꩃꩄꩅꩆꩇꩈꩉꩊꩋꩌꩍ꩐꩑꩒꩓꩔꩕꩖꩗꩘꩙꩜꩝꩞꩟ꨲꩁ0123456789[]().,;-/?!#&*<>{}\_123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114:ꨀꨁꨂꨃꨄꨅꨆꨇꨈꨉꨊꨋꨌꨍꨎꨏꨐꨑꨒꨓꨔꨕꨖꨗꨘꨙꨚꨛꨜꨝꨞꨟꨠꨡꨢꨣꨤꨥꨦꨧꨨꨩꨪꨫꨬꨭꨮꨯꨰꨱꨳꨴꨵꨶꩀꩂꩃꩄꩅꩆꩇꩈꩉꩊꩋꩌꩍ꩐꩑꩒꩓꩔꩕꩖꩗꩘꩙꩜꩝꩞꩟ꨲꩁ0123456789[]().,;-/?!#&*<>{}\_123version https://git-lfs.github.com/spec/v1oid sha256:5fb0d8e4d512b4c0d20933a103e9b7f940d97c14ded247dcabeba353c47e215bsize 7616465123version https://git-lfs.github.com/spec/v1oid sha256:7921a250bcb88c0ecc83e5a107dcb6acda5853d4697273dfb8b4aa0719bbf793size 102540123version https://git-lfs.github.com/spec/v1oid sha256:6ba5572c81eee4250a7c83cc53a4688078ef8606e737ff4f67a7bf5f23a2361csize 137964123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156Global: model_name: PP-OCRv4_mobile_recHpi: backend_configs: paddle_infer: trt_dynamic_shapes: &id001 x: - - 1 - 3 - 48 - 160 - - 1 - 3 - 48 - 320 - - 8 - 3 - 48 - 3200 tensorrt: dynamic_shapes: *id001PreProcess: transform_ops: - DecodeImage: channel_first: false img_mode: BGR - MultiLabelEncode: gtc_encode: NRTRLabelEncode - RecResizeImg: image_shape: - 3 - 48 - 320 - KeepKeys: keep_keys: - image - label_ctc - label_gtc - lengthPostProcess: name: CTCLabelDecode character_dict: - ':' - ꨀ - ꨁ - ꨂ - ꨃ - ꨄ - ꨅ - ꨆ - ꨇ - ꨈ - ꨉ - ꨊ - ꨋ - ꨌ - ꨍ - ꨎ - ꨏ - ꨐ - ꨑ - ꨒ - ꨓ - ꨔ - ꨕ - ꨖ - ꨗ - ꨘ - ꨙ - ꨚ - ꨛ - ꨜ - ꨝ - ꨞ - ꨟ - ꨠ - ꨡ - ꨢ - ꨣ - ꨤ - ꨥ - ꨦ - ꨧ - ꨨ - ꨩ - ꨪ - ꨫ - ꨬ - ꨭ - ꨮ - ꨯ - ꨰ - ꨱ - ꨳ - ꨴ - ꨵ - ꨶ - ꩀ - ꩂ - ꩃ - ꩄ - ꩅ - ꩆ - ꩇ - ꩈ - ꩉ - ꩊ - ꩋ - ꩌ - ꩍ - ꩐ - ꩑ - ꩒ - ꩓ - ꩔ - ꩕ - ꩖ - ꩗ - ꩘ - ꩙ - ꩜ - ꩝ - ꩞ - ꩟ - ꨲ - ꩁ - '0' - '1' - '2' - '3' - '4' - '5' - '6' - '7' - '8' - '9' - '[' - ']' - ( - ) - . - ',' - ; - '-' - / - '?' - '!' - '#' - '&' - '*' - < - '>' - '{' - '}' - \ - _123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263{
"model_id": "v24_1_r3_1",
"display_name": "Cham-OCR v24.1 Stage R3.1 (W=320 Sesquisyllabic + Erosion)",
"stage": "R3_1_CLOSURE",
"epoch": 3,
"packaged_at": "2026-11-17T03:32:01.336967+00:00",
"source_kernel": "gustavnguyen/paddleocr-cham-v24-1-r3-1-gate-closure",
"source_checkpoint": "ocr-training/output/r3_1_closure_checkpoints/iter_epoch_3.pdparams",
"source_checkpoint_sha256": "ae8631e38ba7057c8449c65ba52bcc77d7089f83e817ba2ef74c590a3f554d21",
"dictionary_path": "ocr-studio/data/cham_dict_v24_1_r3_1.txt",
"dictionary_sha256": "ec1e1f08254dbde6f71604c6581d712a59e724bdb410d98d5d85d3b3446a7643",
"dictionary_tokens": 114,
"rec_image_shape": "3, 48, 320",
"logical_order": true,
"export_with_pir": false,
"files": {
"cham_dict_v24_1.txt": {
"size_bytes": 394,
"sha256": "ec1e1f08254dbde6f71604c6581d712a59e724bdb410d98d5d85d3b3446a7643"
},
"inference.json": {
"size_bytes": 217712,
"sha256": "207f52bcdab782cf5c94d0f23f81a785844a96f6dfaf8965893661629763bdcb"
},
"inference.pdiparams": {
"size_bytes": 7616465,
"sha256": "5fb0d8e4d512b4c0d20933a103e9b7f940d97c14ded247dcabeba353c47e215b"
},
"inference.pdiparams.info": {
"size_bytes": 102540,
"sha256": "7921a250bcb88c0ecc83e5a107dcb6acda5853d4697273dfb8b4aa0719bbf793"
},
"inference.pdmodel": {
"size_bytes": 137964,
"sha256": "6ba5572c81eee4250a7c83cc53a4688078ef8606e737ff4f67a7bf5f23a2361c"
},
"inference.yml": {
"size_bytes": 1614,
"sha256": "b166ddd1f59e2b6c05d324076dfa2b15b21b3dee067c61545c619069abab89fc"
}
},
"benchmark_metrics": {
"clean_cer_pct": 4.98,
"char_cer_pct": 3.67,
"stress_82_cer_pct": 6.46,
"hyphen_acc_pct": 92.86,
"harum_crops_cer_pct": 4.62,
"harum_e2e_cer_pct": 5.08,
"audit_18_doc_cer_pct": 10.82
},
"confidence_temperature": 0.914851,
"confidence_calibration": {
"fit_split": "held_out_diagnostic_probe_100",
"eval_split": "realscan_gold_v1/harum_palei_01",
"policy": "raw_probe_100_mle",
"ece_before": 0.001724,
"ece_after": 0.008951,
"brier_before": 0.001739,
"brier_after": 0.001801,
"nll_before": 0.185365,
"nll_after": 0.186705
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114:ꨀꨁꨂꨃꨄꨅꨆꨇꨈꨉꨊꨋꨌꨍꨎꨏꨐꨑꨒꨓꨔꨕꨖꨗꨘꨙꨚꨛꨜꨝꨞꨟꨠꨡꨢꨣꨤꨥꨦꨧꨨꨩꨪꨫꨬꨭꨮꨯꨰꨱꨳꨴꨵꨶꩀꩂꩃꩄꩅꩆꩇꩈꩉꩊꩋꩌꩍ꩐꩑꩒꩓꩔꩕꩖꩗꩘꩙꩜꩝꩞꩟ꨲꩁ0123456789[]().,;-/?!#&*<>{}\_123version https://git-lfs.github.com/spec/v1oid sha256:508141c596bf43cbdbe0efea6cfbb2c4e68aa2d1cfab1b0a144c570721ecfe88size 7616465123version https://git-lfs.github.com/spec/v1oid sha256:80e0b00bf7ee7d84785905b18f82791a37d99271271151510c236cae3addb93dsize 102540123version https://git-lfs.github.com/spec/v1oid sha256:6ba5572c81eee4250a7c83cc53a4688078ef8606e737ff4f67a7bf5f23a2361csize 137964123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156Global: model_name: PP-OCRv4_mobile_recHpi: backend_configs: paddle_infer: trt_dynamic_shapes: &id001 x: - - 1 - 3 - 48 - 160 - - 1 - 3 - 48 - 480 - - 8 - 3 - 48 - 3200 tensorrt: dynamic_shapes: *id001PreProcess: transform_ops: - DecodeImage: channel_first: false img_mode: BGR - MultiLabelEncode: gtc_encode: NRTRLabelEncode - RecResizeImg: image_shape: - 3 - 48 - 480 - KeepKeys: keep_keys: - image - label_ctc - label_gtc - lengthPostProcess: name: CTCLabelDecode character_dict: - ':' - ꨀ - ꨁ - ꨂ - ꨃ - ꨄ - ꨅ - ꨆ - ꨇ - ꨈ - ꨉ - ꨊ - ꨋ - ꨌ - ꨍ - ꨎ - ꨏ - ꨐ - ꨑ - ꨒ - ꨓ - ꨔ - ꨕ - ꨖ - ꨗ - ꨘ - ꨙ - ꨚ - ꨛ - ꨜ - ꨝ - ꨞ - ꨟ - ꨠ - ꨡ - ꨢ - ꨣ - ꨤ - ꨥ - ꨦ - ꨧ - ꨨ - ꨩ - ꨪ - ꨫ - ꨬ - ꨭ - ꨮ - ꨯ - ꨰ - ꨱ - ꨳ - ꨴ - ꨵ - ꨶ - ꩀ - ꩂ - ꩃ - ꩄ - ꩅ - ꩆ - ꩇ - ꩈ - ꩉ - ꩊ - ꩋ - ꩌ - ꩍ - ꩐ - ꩑ - ꩒ - ꩓ - ꩔ - ꩕ - ꩖ - ꩗ - ꩘ - ꩙ - ꩜ - ꩝ - ꩞ - ꩟ - ꨲ - ꩁ - '0' - '1' - '2' - '3' - '4' - '5' - '6' - '7' - '8' - '9' - '[' - ']' - ( - ) - . - ',' - ; - '-' - / - '?' - '!' - '#' - '&' - '*' - < - '>' - '{' - '}' - \ - _1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465{
"model_id": "v24_1_r4",
"display_name": "Cham-OCR v24.1 Stage R4 (W=480 Wide-Canvas Corpus + Optical)",
"stage": "R4_WIDE_CANVAS_W480",
"epoch": 3,
"packaged_at": "2026-11-17T04:55:43.150569+00:00",
"source_kernel": "gustavnguyen/paddleocr-cham-v24-1-r4-wide-w480",
"source_checkpoint": "ocr-training/output/r4_w480_checkpoints/iter_epoch_3.pdparams",
"source_checkpoint_sha256": "b98e0c3400d520d4ba1d4d80ca513619036fa32c8da1b9b811219c668f1b7de2",
"dictionary_path": "ocr-studio/data/cham_dict_v24_1_r4.txt",
"dictionary_sha256": "ec1e1f08254dbde6f71604c6581d712a59e724bdb410d98d5d85d3b3446a7643",
"dictionary_tokens": 114,
"rec_image_shape": "3, 48, 480",
"logical_order": true,
"export_with_pir": false,
"files": {
"cham_dict_v24_1.txt": {
"size_bytes": 394,
"sha256": "ec1e1f08254dbde6f71604c6581d712a59e724bdb410d98d5d85d3b3446a7643"
},
"inference.json": {
"size_bytes": 217712,
"sha256": "207f52bcdab782cf5c94d0f23f81a785844a96f6dfaf8965893661629763bdcb"
},
"inference.pdiparams": {
"size_bytes": 7616465,
"sha256": "508141c596bf43cbdbe0efea6cfbb2c4e68aa2d1cfab1b0a144c570721ecfe88"
},
"inference.pdiparams.info": {
"size_bytes": 102540,
"sha256": "80e0b00bf7ee7d84785905b18f82791a37d99271271151510c236cae3addb93d"
},
"inference.pdmodel": {
"size_bytes": 137964,
"sha256": "6ba5572c81eee4250a7c83cc53a4688078ef8606e737ff4f67a7bf5f23a2361c"
},
"inference.yml": {
"size_bytes": 1614,
"sha256": "942f160dbbb5b8ddbb0630ac2dce87c2c74b83381818006ba10011e3f8df4d9e"
}
},
"benchmark_metrics": {
"clean_cer_pct": 5.06,
"char_cer_pct": 2.76,
"symbols_acc_pct": 98.93,
"hyphen_acc_pct": 94.29,
"stress_82_cer_pct": 6.45,
"erode_3_cer_pct": 18.59,
"harum_crops_cer_pct": 2.68,
"harum_wer_pct": 9.63,
"harum_e2e_cer_pct": 3.19
},
"confidence_temperature": 0.913876,
"confidence_calibration": {
"fit_split": "held_out_diagnostic_probe_100",
"eval_split": "realscan_gold_v1/harum_palei_01",
"policy": "raw_probe_100_mle",
"ece_before": 0.022263,
"ece_after": 0.011346,
"brier_before": 0.001234,
"brier_after": 0.000827,
"nll_before": 0.125595,
"nll_after": 0.121042
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272"""Regression tests for the 2026-11-04 stress-test fixes (blank page, reading order, review gates).Run: python ocr-studio/tests/test_quality_gates.pyOnly needs numpy + opencv (no PaddlePaddle models are loaded)."""import osimport sysimport cv2import numpy as npsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))import app # noqa: E402def _meta(text, conf, bbox):return {'line_id': 0, 'bbox': bbox, 'core_box': [bbox[1], bbox[3]], 'selected_crop_type': 'dbnet','candidates': {'dbnet': {'prediction': text, 'confidence': conf}}}def test_blank_page_is_detected():blank = np.full((460, 1500, 3), 250, np.uint8)noise = np.clip(blank.astype(np.int16) + np.random.RandomState(0).randint(-6, 7, blank.shape), 0, 255).astype(np.uint8)assert app.is_blank_page(app.analyze_text_ink(blank))assert app.is_blank_page(app.analyze_text_ink(noise))page = blank.copy()for i in range(4):cv2.putText(page, 'Cham OCR line %d' % i, (40, 80 + 90 * i), cv2.FONT_HERSHEY_SIMPLEX, 1.6, (20, 20, 20), 3)assert not app.is_blank_page(app.analyze_text_ink(page))def test_uncovered_ink_ratio():page = np.full((400, 900, 3), 245, np.uint8)for i in range(4):cv2.putText(page, 'line number %d text' % i, (30, 70 + 90 * i), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (10, 10, 10), 3)ink = app.analyze_text_ink(page)boxes = [np.array([[20, 30 + 90 * i], [880, 30 + 90 * i], [880, 85 + 90 * i], [20, 85 + 90 * i]], np.float32) for i in range(4)]full, _ = app.compute_uncovered_ink(ink, boxes, 55)half, _ = app.compute_uncovered_ink(ink, boxes[:2], 55)assert full < 0.02, fullassert 0.35 < half < 0.65, halfdef test_two_column_reading_order():rects = []for i in range(8): # left columnrects.append((60, 90 + 47 * i, 420, 125 + 47 * i))for i in range(8): # right column, row-aligned with the left columnrects.append((580, 90 + 47 * i, 890, 125 + 47 * i))order, layout = app.order_lines_reading(rects, 1100)assert layout == {'reading_order': 'columns', 'columns': 2}, layoutassert order == list(range(16)), orderdef test_title_then_two_columns():rects = [(60, 20, 890, 60)] # full-width titlerects += [(60, 90 + 47 * i, 420, 125 + 47 * i) for i in range(6)]rects += [(580, 90 + 47 * i, 890, 125 + 47 * i) for i in range(6)]order, layout = app.order_lines_reading(rects, 1000)assert order == list(range(13)), orderassert layout['columns'] == 2def test_single_column_keeps_top_to_bottom():rects = [(40 + (i % 3) * 30, 50 + 45 * i, 700 - (i % 2) * 200, 85 + 45 * i) for i in range(10)]order, layout = app.order_lines_reading(rects, 800)assert order == list(range(10))assert layout['reading_order'] == 'rows'def test_line_quality_gates():metas = [_meta('ꨀꨇꨉ ꨆꨮꨭ', 0.95, [10, 10, 500, 50]),_meta('', 0.0, [10, 60, 500, 100]), # empty -> dropped_meta('R', 0.12, [10, 110, 500, 150]), # very low conf -> dropped_meta('ꨌꨯꨱꩃ', 0.45, [10, 160, 500, 200]), # kept, low confidence -> review_meta('ꨨꨎꩆ ꨀꨊꨪꩆ', 0.91, [10, 210, 500, 330])] # kept, merged-height -> reviewkept, crops = app.apply_line_quality_gates(metas, list(range(len(metas))))assert crops == [0, 3, 4], cropsassert kept[0]['needs_review'] is Falseassert 'low_confidence' in kept[1]['reason']assert 'possible_merged_lines' in kept[2]['reason']def test_document_status_never_auto_verified():ok_line = {'segmentation': {'needs_review': False}}bad_line = {'segmentation': {'needs_review': True}}assert app.build_document_status([], ['blank_page'])['status'] == 'no_text'assert app.build_document_status([], ['no_reliable_text'])['status'] == 'needs_review'assert app.build_document_status([ok_line], [])['status'] == 'ocr_done'assert app.build_document_status([ok_line, bad_line], [])['status'] == 'needs_review'assert app.build_document_status([ok_line], ['possible_missed_lines'])['status'] == 'needs_review'def test_expand_quad_pads_along_line_axis():quad = np.array([[100, 100], [400, 100], [400, 140], [100, 140]], np.float32)out = app.expand_quad(quad, 0.25, 0.0, 1000, 1000)assert np.allclose(out[:, 1], [90, 90, 150, 150]), outdef test_merge_line_boxes_preserves_stacked_wavy_lines():# Exact raw boxes from test_161_lvl5 (lines 6 & 7 had AABB vertical overlap 0.57 due to wave/tilt)raw_boxes = [[[89.0, 226.0], [673.0, 226.0], [673.0, 263.0], [89.0, 263.0]],[[80.0, 191.0], [967.0, 194.0], [967.0, 243.0], [80.0, 239.0]],[[96.0, 178.0], [436.0, 182.0], [436.0, 208.0], [96.0, 204.0]],[[90.0, 154.0], [464.0, 155.0], [464.0, 181.0], [90.0, 179.0]],[[81.0, 125.0], [396.0, 132.0], [396.0, 158.0], [81.0, 151.0]],[[84.0, 102.0], [573.0, 102.0], [573.0, 134.0], [84.0, 134.0]],[[81.0, 73.0], [532.0, 79.0], [531.0, 112.0], [81.0, 106.0]],[[103.0, 50.0], [434.0, 54.0], [434.0, 80.0], [103.0, 76.0]],]merged = app.merge_line_boxes(raw_boxes, 1050, 289)assert len(merged) == 8, len(merged)# Horizontally separated fragments on the same line should still be merged into one boxfragments = [[[50.0, 100.0], [210.0, 100.0], [210.0, 134.0], [50.0, 134.0]],[[235.0, 102.0], [480.0, 102.0], [480.0, 135.0], [235.0, 135.0]],]merged_frags = app.merge_line_boxes(fragments, 1000, 300)assert len(merged_frags) == 1, len(merged_frags)def test_merge_line_boxes_keeps_tilted_stacked_lines_apart():# Two parallel lines tilted ~3.5 deg on a perspective page: each AABB is ~2.5x the text# thickness, so the AABBs overlap ~60% vertically although the lines are 24px apart# (pattern of benchmark test_384_a4_lvl5, where AABB merging collapsed 19 lines into 14).def tilted(y0, x1=80.0, x2=920.0, slope=0.06, t=22.0):return [[x1, y0], [x2, y0 + slope * (x2 - x1)], [x2, y0 + slope * (x2 - x1) + t], [x1, y0 + t]]lines = [tilted(140.0), tilted(164.0), tilted(188.0)]merged = app.merge_line_boxes(lines, 1000, 400)assert len(merged) == 3, len(merged)assert app.max_stacked_overlap(lines) > 0.45 # legacy-gate trigger fires on such pages# Overlapping fragments of the SAME tilted line (h_overlap > 0.25, shared centerline) must# still merge: the centerline guard only separates genuinely stacked lines.frags = [tilted(140.0, 80.0, 500.0), tilted(140.0 + 0.06 * 270.0, 350.0, 920.0)]assert len(app.merge_line_boxes(frags, 1000, 400)) == 1def test_dropped_text_lines_are_reported():metas = [_meta('ꨀꨇꨉ ꨆꨮꨭ', 0.95, [10, 10, 500, 50]),_meta('ꨯꨮꨯꨮ ꨯꨱ', 0.11, [10, 60, 520, 100]), # full-size unreadable Cham line_meta('ꨯ', 0.05, [10, 110, 30, 120]), # tiny fragment -> plain noise_meta('ꨌꨯꨱꩃ ꨀꨊ', 0.90, [10, 160, 480, 200])]dropped = []kept, crops = app.apply_line_quality_gates(metas, list(range(len(metas))), dropped)assert crops == [0, 3], cropsassert len(dropped) == 1 and dropped[0]['bbox'] == [10, 60, 520, 100]def test_model_info_always_reports_detector_and_paddle():# Blank-page requests return before the detector is needed: model_info must still say so# explicitly instead of omitting the detector (post-deploy check 2026-11-16).saved = dict(app.det_model_info)try:app.det_model_info.clear()info = app.get_model_info('v24_1_r2_1_6')assert info['detector']['loaded'] is False and info['detector']['mode'] == app.DET_MODEassert 'paddle_version' in infofinally:app.det_model_info.update(saved)def test_default_cham_model_and_auto_info():assert app.DEFAULT_CHAM_MODEL.startswith('v24_1'), app.DEFAULT_CHAM_MODELinfo = app.get_model_info('auto')# When ocr_model_paths is not yet populated in unit tests, ensure get_model_info runs cleanly;# when populated, recognizer #0 must match DEFAULT_CHAM_MODEL.recs = info.get('recognizers', [])if recs:assert recs[0]['version'] == app.DEFAULT_CHAM_MODEL, recsapp.ocr_model_paths.setdefault(app.DEFAULT_CHAM_MODEL,{'model_dir': os.path.join(app.PROJECT_ROOT, 'data', 'output', f'rec_cham_inference_{app.DEFAULT_CHAM_MODEL}'),'dict_path': os.path.join(app.PROJECT_ROOT, 'data', 'cham_dict_v24_1.txt')})info2 = app.get_model_info('auto')assert info2['recognizers'][0]['version'] == app.DEFAULT_CHAM_MODEL, info2def test_confidence_calibration_temperature_scaling():# Identity at T = 1.0assert abs(app.calibrate_line_confidence(0.85, temperature=1.0) - 0.85) < 1e-6assert app.calibrate_line_confidence(0.0, temperature=2.0) == 0.0assert app.calibrate_line_confidence(1.0, temperature=2.0) == 1.0# T > 1.0 softens high confidence (0.95 -> closer to 0.5) and stays strictly monotonec_low = app.calibrate_line_confidence(0.60, temperature=1.8)c_high = app.calibrate_line_confidence(0.95, temperature=1.8)assert 0.50 < c_low < 0.60, c_lowassert 0.50 < c_high < 0.95, c_highassert c_low < c_high# T < 1.0 sharpens high confidence (> 0.5 moves closer to 1.0)c_sharp = app.calibrate_line_confidence(0.80, temperature=0.5)assert c_sharp > 0.80, c_sharpdef test_active_learning_save_correction_and_export_r4():import base64import jsonimport tempfilewith tempfile.TemporaryDirectory() as tmpdir:# Prepare 5 fake line crops across 2 synthetic documentsimgs_b64 = []for idx in range(5):arr = np.full((32, 120, 3), 240 - idx * 10, dtype=np.uint8)cv2.putText(arr, f'T{idx}', (10, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (20, 20, 20), 2)ok, buf = cv2.imencode('.png', arr)assert okimgs_b64.append('data:image/png;base64,' + base64.b64encode(buf.tobytes()).decode('ascii'))# Verify Logical Order normalize_unicode on out-of-order Cham text (ꨙꨯꨳꨮ -> ꨙꨳꨯꨮ)samples = [('doc_alpha.png', 1, 'ꨙꨯꨳꨮ', 'ꨙꨯꨳꨮ', imgs_b64[0]),('doc_alpha.png', 2, 'ꨨꨣꨭꩌ ꨚꨤꨬ', 'ꨨꨣꨭꩌ', imgs_b64[1]),('doc_beta.png', 1, 'ꨌꩌ ꨚꨤꨬ ꨣꩌ', 'ꨌꩌ ꨚꨤꨬ', imgs_b64[2]),('doc_gamma.png', 1, '꩒꩐꩐꩞ ꨀꨇꩉ', '꩒꩐꩞', imgs_b64[3]),('doc_delta.png', 1, 'ꨓꨶꨮꩉ ꨆꨭꨖꨩ', 'ꨓꨶꨮꩉ', imgs_b64[4]),]res0 = Nonefor doc_name, lidx, submitted, orig, b64 in samples:r = app.save_correction_entry({'text': submitted,'original_text': orig,'confidence': 0.87,'calibrated_confidence': 0.81,'model': 'v24_1_r2_1_6','bbox': [10, 20, 130, 52],'image_name': doc_name,'line_idx': lidx,'crop_image': b64,}, base_dir=tmpdir)if res0 is None:res0 = rassert r['success'] is Trueassert res0['normalized_text'] == 'ꨙꨳꨯꨮ', res0txt_lines = open(os.path.join(tmpdir, 'ocr_corrections.txt'), encoding='utf-8').read().splitlines()assert len(txt_lines) == 5 and txt_lines[0] == 'ꨙꨳꨯꨮ', txt_linesjsonl_path = os.path.join(tmpdir, 'active_learning', 'corrections.jsonl')rows = [json.loads(l) for l in open(jsonl_path, encoding='utf-8') if l.strip()]assert len(rows) == 5assert rows[0]['text'] == 'ꨙꨳꨯꨮ'assert rows[0]['crop_relpath'].startswith('active_learning/crops/')assert os.path.exists(os.path.join(tmpdir, rows[0]['crop_relpath']))# Test export_active_learning_r4.py document-grouped 80/20 exporttraining_scripts = os.path.join(os.path.dirname(app.PROJECT_ROOT), 'ocr-training', 'scripts')if training_scripts not in sys.path:sys.path.insert(0, training_scripts)from export_active_learning_r4 import export_active_learning_datasetout_r4 = os.path.join(tmpdir, 'export_r4')manifest = export_active_learning_dataset(jsonl_path, out_r4, val_ratio=0.25, seed=42, crops_root=tmpdir)assert manifest['train_samples'] + manifest['val_samples'] == 5, manifestassert manifest['train_samples'] >= 3 and manifest['val_samples'] >= 1, manifesttr_rel = open(manifest['train_list'], encoding='utf-8').read().splitlines()va_rel = open(manifest['val_list'], encoding='utf-8').read().splitlines()for entry in tr_rel + va_rel:img_rel, lbl = entry.split('\t', 1)assert os.path.exists(os.path.join(out_r4, img_rel)), img_relassert len(lbl) > 0if __name__ == '__main__':tests = [v for k, v in sorted(globals().items()) if k.startswith('test_') and callable(v)]for t in tests:t()print('PASS', t.__name__)print(f'{len(tests)} tests passed')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334"""Regression tests for the 2026-11-04 stress-test fixes (blank page, reading order, review gates).Run: python ocr-studio/tests/test_quality_gates.pyOnly needs numpy + opencv (no PaddlePaddle models are loaded)."""import osimport sysimport cv2import numpy as npsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))import app # noqa: E402def _meta(text, conf, bbox):return {'line_id': 0, 'bbox': bbox, 'core_box': [bbox[1], bbox[3]], 'selected_crop_type': 'dbnet','candidates': {'dbnet': {'prediction': text, 'confidence': conf}}}def test_blank_page_is_detected():blank = np.full((460, 1500, 3), 250, np.uint8)noise = np.clip(blank.astype(np.int16) + np.random.RandomState(0).randint(-6, 7, blank.shape), 0, 255).astype(np.uint8)assert app.is_blank_page(app.analyze_text_ink(blank))assert app.is_blank_page(app.analyze_text_ink(noise))page = blank.copy()for i in range(4):cv2.putText(page, 'Cham OCR line %d' % i, (40, 80 + 90 * i), cv2.FONT_HERSHEY_SIMPLEX, 1.6, (20, 20, 20), 3)assert not app.is_blank_page(app.analyze_text_ink(page))def test_uncovered_ink_ratio():page = np.full((400, 900, 3), 245, np.uint8)for i in range(4):cv2.putText(page, 'line number %d text' % i, (30, 70 + 90 * i), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (10, 10, 10), 3)ink = app.analyze_text_ink(page)boxes = [np.array([[20, 30 + 90 * i], [880, 30 + 90 * i], [880, 85 + 90 * i], [20, 85 + 90 * i]], np.float32) for i in range(4)]full, _ = app.compute_uncovered_ink(ink, boxes, 55)half, _ = app.compute_uncovered_ink(ink, boxes[:2], 55)assert full < 0.02, fullassert 0.35 < half < 0.65, halfdef test_two_column_reading_order():rects = []for i in range(8): # left columnrects.append((60, 90 + 47 * i, 420, 125 + 47 * i))for i in range(8): # right column, row-aligned with the left columnrects.append((580, 90 + 47 * i, 890, 125 + 47 * i))order, layout = app.order_lines_reading(rects, 1100)assert layout == {'reading_order': 'columns', 'columns': 2}, layoutassert order == list(range(16)), orderdef test_title_then_two_columns():rects = [(60, 20, 890, 60)] # full-width titlerects += [(60, 90 + 47 * i, 420, 125 + 47 * i) for i in range(6)]rects += [(580, 90 + 47 * i, 890, 125 + 47 * i) for i in range(6)]order, layout = app.order_lines_reading(rects, 1000)assert order == list(range(13)), orderassert layout['columns'] == 2def test_single_column_keeps_top_to_bottom():rects = [(40 + (i % 3) * 30, 50 + 45 * i, 700 - (i % 2) * 200, 85 + 45 * i) for i in range(10)]order, layout = app.order_lines_reading(rects, 800)assert order == list(range(10))assert layout['reading_order'] == 'rows'def test_line_quality_gates():metas = [_meta('ꨀꨇꨉ ꨆꨮꨭ', 0.95, [10, 10, 500, 50]),_meta('', 0.0, [10, 60, 500, 100]), # empty -> dropped_meta('R', 0.12, [10, 110, 500, 150]), # very low conf -> dropped_meta('ꨌꨯꨱꩃ', 0.45, [10, 160, 500, 200]), # kept, low confidence -> review_meta('ꨨꨎꩆ ꨀꨊꨪꩆ', 0.91, [10, 210, 500, 330])] # kept, merged-height -> reviewkept, crops = app.apply_line_quality_gates(metas, list(range(len(metas))))assert crops == [0, 3, 4], cropsassert kept[0]['needs_review'] is Falseassert 'low_confidence' in kept[1]['reason']assert 'possible_merged_lines' in kept[2]['reason']def test_document_status_never_auto_verified():ok_line = {'segmentation': {'needs_review': False}}bad_line = {'segmentation': {'needs_review': True}}assert app.build_document_status([], ['blank_page'])['status'] == 'no_text'assert app.build_document_status([], ['no_reliable_text'])['status'] == 'needs_review'assert app.build_document_status([ok_line], [])['status'] == 'ocr_done'assert app.build_document_status([ok_line, bad_line], [])['status'] == 'needs_review'assert app.build_document_status([ok_line], ['possible_missed_lines'])['status'] == 'needs_review'def test_expand_quad_pads_along_line_axis():quad = np.array([[100, 100], [400, 100], [400, 140], [100, 140]], np.float32)out = app.expand_quad(quad, 0.25, 0.0, 1000, 1000)assert np.allclose(out[:, 1], [90, 90, 150, 150]), outdef test_merge_line_boxes_preserves_stacked_wavy_lines():# Exact raw boxes from test_161_lvl5 (lines 6 & 7 had AABB vertical overlap 0.57 due to wave/tilt)raw_boxes = [[[89.0, 226.0], [673.0, 226.0], [673.0, 263.0], [89.0, 263.0]],[[80.0, 191.0], [967.0, 194.0], [967.0, 243.0], [80.0, 239.0]],[[96.0, 178.0], [436.0, 182.0], [436.0, 208.0], [96.0, 204.0]],[[90.0, 154.0], [464.0, 155.0], [464.0, 181.0], [90.0, 179.0]],[[81.0, 125.0], [396.0, 132.0], [396.0, 158.0], [81.0, 151.0]],[[84.0, 102.0], [573.0, 102.0], [573.0, 134.0], [84.0, 134.0]],[[81.0, 73.0], [532.0, 79.0], [531.0, 112.0], [81.0, 106.0]],[[103.0, 50.0], [434.0, 54.0], [434.0, 80.0], [103.0, 76.0]],]merged = app.merge_line_boxes(raw_boxes, 1050, 289)assert len(merged) == 8, len(merged)# Horizontally separated fragments on the same line should still be merged into one boxfragments = [[[50.0, 100.0], [210.0, 100.0], [210.0, 134.0], [50.0, 134.0]],[[235.0, 102.0], [480.0, 102.0], [480.0, 135.0], [235.0, 135.0]],]merged_frags = app.merge_line_boxes(fragments, 1000, 300)assert len(merged_frags) == 1, len(merged_frags)def test_merge_line_boxes_keeps_tilted_stacked_lines_apart():# Two parallel lines tilted ~3.5 deg on a perspective page: each AABB is ~2.5x the text# thickness, so the AABBs overlap ~60% vertically although the lines are 24px apart# (pattern of benchmark test_384_a4_lvl5, where AABB merging collapsed 19 lines into 14).def tilted(y0, x1=80.0, x2=920.0, slope=0.06, t=22.0):return [[x1, y0], [x2, y0 + slope * (x2 - x1)], [x2, y0 + slope * (x2 - x1) + t], [x1, y0 + t]]lines = [tilted(140.0), tilted(164.0), tilted(188.0)]merged = app.merge_line_boxes(lines, 1000, 400)assert len(merged) == 3, len(merged)assert app.max_stacked_overlap(lines) > 0.45 # legacy-gate trigger fires on such pages# Overlapping fragments of the SAME tilted line (h_overlap > 0.25, shared centerline) must# still merge: the centerline guard only separates genuinely stacked lines.frags = [tilted(140.0, 80.0, 500.0), tilted(140.0 + 0.06 * 270.0, 350.0, 920.0)]assert len(app.merge_line_boxes(frags, 1000, 400)) == 1def test_dropped_text_lines_are_reported():metas = [_meta('ꨀꨇꨉ ꨆꨮꨭ', 0.95, [10, 10, 500, 50]),_meta('ꨯꨮꨯꨮ ꨯꨱ', 0.11, [10, 60, 520, 100]), # full-size unreadable Cham line_meta('ꨯ', 0.05, [10, 110, 30, 120]), # tiny fragment -> plain noise_meta('ꨌꨯꨱꩃ ꨀꨊ', 0.90, [10, 160, 480, 200])]dropped = []kept, crops = app.apply_line_quality_gates(metas, list(range(len(metas))), dropped)assert crops == [0, 3], cropsassert len(dropped) == 1 and dropped[0]['bbox'] == [10, 60, 520, 100]def test_model_info_always_reports_detector_and_paddle():# Blank-page requests return before the detector is needed: model_info must still say so# explicitly instead of omitting the detector (post-deploy check 2026-11-16).saved = dict(app.det_model_info)try:app.det_model_info.clear()info = app.get_model_info('v24_1_r2_1_6')assert info['detector']['loaded'] is False and info['detector']['mode'] == app.DET_MODEassert 'paddle_version' in infofinally:app.det_model_info.update(saved)def test_default_cham_model_and_auto_info():assert app.DEFAULT_CHAM_MODEL.startswith('v24_1'), app.DEFAULT_CHAM_MODELinfo = app.get_model_info('auto')# When ocr_model_paths is not yet populated in unit tests, ensure get_model_info runs cleanly;# when populated, recognizer #0 must match DEFAULT_CHAM_MODEL.recs = info.get('recognizers', [])if recs:assert recs[0]['version'] == app.DEFAULT_CHAM_MODEL, recsapp.ocr_model_paths.setdefault(app.DEFAULT_CHAM_MODEL,{'model_dir': os.path.join(app.PROJECT_ROOT, 'data', 'output', f'rec_cham_inference_{app.DEFAULT_CHAM_MODEL}'),'dict_path': os.path.join(app.PROJECT_ROOT, 'data', 'cham_dict_v24_1.txt')})info2 = app.get_model_info('auto')assert info2['recognizers'][0]['version'] == app.DEFAULT_CHAM_MODEL, info2def test_confidence_calibration_temperature_scaling():# Identity at T = 1.0assert abs(app.calibrate_line_confidence(0.85, temperature=1.0) - 0.85) < 1e-6assert app.calibrate_line_confidence(0.0, temperature=2.0) == 0.0assert app.calibrate_line_confidence(1.0, temperature=2.0) == 1.0# T > 1.0 softens high confidence (0.95 -> closer to 0.5) and stays strictly monotonec_low = app.calibrate_line_confidence(0.60, temperature=1.8)c_high = app.calibrate_line_confidence(0.95, temperature=1.8)assert 0.50 < c_low < 0.60, c_lowassert 0.50 < c_high < 0.95, c_highassert c_low < c_high# T < 1.0 sharpens high confidence (> 0.5 moves closer to 1.0)c_sharp = app.calibrate_line_confidence(0.80, temperature=0.5)assert c_sharp > 0.80, c_sharpdef test_active_learning_save_correction_and_export_r4():import base64import jsonimport tempfilewith tempfile.TemporaryDirectory() as tmpdir:# Prepare 5 fake line crops across 2 synthetic documentsimgs_b64 = []for idx in range(5):arr = np.full((32, 120, 3), 240 - idx * 10, dtype=np.uint8)cv2.putText(arr, f'T{idx}', (10, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (20, 20, 20), 2)ok, buf = cv2.imencode('.png', arr)assert okimgs_b64.append('data:image/png;base64,' + base64.b64encode(buf.tobytes()).decode('ascii'))# Verify Logical Order normalize_unicode on out-of-order Cham text (ꨙꨯꨳꨮ -> ꨙꨳꨯꨮ)samples = [('doc_alpha.png', 1, 'ꨙꨯꨳꨮ', 'ꨙꨯꨳꨮ', imgs_b64[0]),('doc_alpha.png', 2, 'ꨨꨣꨭꩌ ꨚꨤꨬ', 'ꨨꨣꨭꩌ', imgs_b64[1]),('doc_beta.png', 1, 'ꨌꩌ ꨚꨤꨬ ꨣꩌ', 'ꨌꩌ ꨚꨤꨬ', imgs_b64[2]),('doc_gamma.png', 1, '꩒꩐꩐꩞ ꨀꨇꩉ', '꩒꩐꩞', imgs_b64[3]),('doc_delta.png', 1, 'ꨓꨶꨮꩉ ꨆꨭꨖꨩ', 'ꨓꨶꨮꩉ', imgs_b64[4]),]res0 = Nonefor doc_name, lidx, submitted, orig, b64 in samples:r = app.save_correction_entry({'text': submitted,'original_text': orig,'confidence': 0.87,'calibrated_confidence': 0.81,'model': 'v24_1_r2_1_6','bbox': [10, 20, 130, 52],'image_name': doc_name,'line_idx': lidx,'crop_image': b64,}, base_dir=tmpdir)if res0 is None:res0 = rassert r['success'] is Trueassert res0['normalized_text'] == 'ꨙꨳꨯꨮ', res0txt_lines = open(os.path.join(tmpdir, 'ocr_corrections.txt'), encoding='utf-8').read().splitlines()assert len(txt_lines) == 5 and txt_lines[0] == 'ꨙꨳꨯꨮ', txt_linesjsonl_path = os.path.join(tmpdir, 'active_learning', 'corrections.jsonl')rows = [json.loads(l) for l in open(jsonl_path, encoding='utf-8') if l.strip()]assert len(rows) == 5assert rows[0]['text'] == 'ꨙꨳꨯꨮ'assert rows[0]['crop_relpath'].startswith('active_learning/crops/')assert os.path.exists(os.path.join(tmpdir, rows[0]['crop_relpath']))# Test export_active_learning_r4.py document-grouped 80/20 exporttraining_scripts = os.path.join(os.path.dirname(app.PROJECT_ROOT), 'ocr-training', 'scripts')if training_scripts not in sys.path:sys.path.insert(0, training_scripts)from export_active_learning_r4 import export_active_learning_datasetout_r4 = os.path.join(tmpdir, 'export_r4')manifest = export_active_learning_dataset(jsonl_path, out_r4, val_ratio=0.25, seed=42, crops_root=tmpdir)assert manifest['train_samples'] + manifest['val_samples'] == 5, manifestassert manifest['train_samples'] >= 3 and manifest['val_samples'] >= 1, manifesttr_rel = open(manifest['train_list'], encoding='utf-8').read().splitlines()va_rel = open(manifest['val_list'], encoding='utf-8').read().splitlines()for entry in tr_rel + va_rel:img_rel, lbl = entry.split('\t', 1)assert os.path.exists(os.path.join(out_r4, img_rel)), img_relassert len(lbl) > 0def test_suppress_detached_diacritic_fragments_keeps_short_lines():def _q(x1, y1, x2, y2):return [[float(x1), float(y1)], [float(x2), float(y1)], [float(x2), float(y2)], [float(x1), float(y2)]]# Main full-height lines (~45px tall) + 3 real harum_palei_01 detached diacritic specks (~10x9px)# + 1 standalone short stanza header ('꩑꩞') + 1 standalone page number ('12')raw_boxes = [_q(30, 5, 85, 42), # standalone short stanza header (h=37, w=55) -> MUST KEEP_q(21, 55, 780, 100), # Line 1_q(235, 99, 245, 108), # Speck #1 (w=10, h=9) touching Line 1/2 -> MUST DROP_q(17, 105, 788, 152), # Line 2_q(18, 160, 683, 206), # Line 3_q(16, 411, 656, 463), # Line 4_q(67, 415, 78, 423), # Speck #2 (w=11, h=8) inside Line 4 -> MUST DROP_q(22, 496, 585, 540), # Line 5_q(295, 497, 307, 505), # Speck #3 (w=12, h=8) inside Line 5 -> MUST DROP_q(480, 960, 498, 994), # standalone page number (h=34, w=18, far below) -> MUST KEEP]merged = app.merge_line_boxes(raw_boxes, 900, 1050)assert len(merged) == 7, f"Expected 7 valid lines (3 specks dropped), got {len(merged)}"widths = [float(np.ptp(np.array(b)[:, 0])) for b in merged]assert all(w >= 17.0 for w in widths), widthsdef test_v24_1_r4_and_r3_1_manifest_and_shapes():assert app.DEFAULT_CHAM_MODEL == 'v24_1_r4', app.DEFAULT_CHAM_MODELm_r4 = app.get_model_manifest('v24_1_r4')m_r31 = app.get_model_manifest('v24_1_r3_1')assert m_r4.get('rec_image_shape') == '3, 48, 480', m_r4assert m_r31.get('rec_image_shape') == '3, 48, 320', m_r31assert 0.80 <= float(m_r4.get('confidence_temperature', 0)) <= 1.20, m_r4assert 0.80 <= float(m_r31.get('confidence_temperature', 0)) <= 1.20, m_r31app.ocr_model_paths['v24_1_r4'] = {'model_dir': os.path.join(app.PROJECT_ROOT, 'data', 'output', 'rec_cham_inference_v24_1_r4'),'dict_path': os.path.join(app.PROJECT_ROOT, 'data', 'cham_dict_v24_1_r4.txt'),}app.ocr_model_paths['v24_1_r3_1'] = {'model_dir': os.path.join(app.PROJECT_ROOT, 'data', 'output', 'rec_cham_inference_v24_1_r3_1'),'dict_path': os.path.join(app.PROJECT_ROOT, 'data', 'cham_dict_v24_1_r3_1.txt'),}info_r4 = app.get_model_info('v24_1_r4')info_r31 = app.get_model_info('v24_1_r3_1')assert info_r4['recognizers'][0]['rec_image_shape'] == '3, 48, 480', info_r4assert info_r4['recognizers'][0]['weights_sha256_16'] == '508141c596bf43cb', info_r4assert '\\' not in info_r4['recognizers'][0]['model_dir'], info_r4assert info_r31['recognizers'][0]['rec_image_shape'] == '3, 48, 320', info_r31assert info_r31['recognizers'][0]['weights_sha256_16'] == '5fb0d8e4d512b4c0', info_r31import unittest # noqa: E402class TestQualityGates(unittest.TestCase):passfor _fn_name, _fn_obj in list(globals().items()):if _fn_name.startswith('test_') and callable(_fn_obj):setattr(TestQualityGates, _fn_name, staticmethod(_fn_obj))if __name__ == '__main__':tests = [v for k, v in sorted(globals().items()) if k.startswith('test_') and callable(v)]for t in tests:t()print('PASS', t.__name__)print(f'{len(tests)} tests passed')
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Cham-OCR Stage R4 Active Learning Export Utility================================================Converts structured Studio human-verified corrections (`ocr-studio/data/active_learning/corrections.jsonl`+ `crops/<sha256_16>.png`) into a leakage-filtered, document-grouped train/val dataset ready for Stage R4 fine-tuning."""
import osimport sysimport jsonimport randomimport shutilimport hashlibimport argparsefrom datetime import datetime, timezone
if sys.stdout and hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8")
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))TRAINING_DIR = os.path.dirname(SCRIPT_DIR)PROJECT_ROOT = os.path.dirname(TRAINING_DIR)
if SCRIPT_DIR not in sys.path: sys.path.insert(0, SCRIPT_DIR)if os.path.join(PROJECT_ROOT, "scripts") not in sys.path: sys.path.insert(0, os.path.join(PROJECT_ROOT, "scripts"))
def _sha256_file(path: str) -> str: h = hashlib.sha256() with open(path, "rb") as f: while chunk := f.read(65536): h.update(chunk) return h.hexdigest().lower()
def _load_allowed_chars(dict_path: str) -> set: with open(dict_path, "r", encoding="utf-8") as f: chars = {line.strip("\r\n") for line in f if line.strip("\r\n")} chars.add(" ") return chars
def _load_protected_sets(): """Loads held-out benchmark, Frozen-838, Probe-100, and RealScan-Gold v1 texts & image hashes to block leakage.""" protected_texts = set() protected_hashes = set() try: from audit_r2_1_4c_contamination import load_benchmark_texts, hash_directory_files, BENCHMARK_DIR, FROZEN_DIR from audit_r3_contamination import load_realscan_texts_and_hashes gt_sets, _ = load_benchmark_texts() for s in gt_sets.values(): protected_texts.update(s) rs_texts, rs_hashes = load_realscan_texts_and_hashes() protected_texts.update(rs_texts) protected_hashes.update(rs_hashes) for d in ( os.path.join(FROZEN_DIR, "crops"), os.path.join(BENCHMARK_DIR, "images"), os.path.join(BENCHMARK_DIR, "images_diagnostic"), os.path.join(BENCHMARK_DIR, "images_stress_500"), os.path.join(BENCHMARK_DIR, "images_advanced"), ): if os.path.exists(d): _, _, hs = hash_directory_files(d, extensions=[".jpg", ".png", ".jpeg"]) protected_hashes.update(hs) except Exception as e: print(f"Warning: could not load full protected benchmark filter ({e}); proceeding with empty external filter.") return protected_texts, protected_hashes
def export_active_learning_dataset( input_jsonl: str, output_dir: str, val_ratio: float = 0.2, seed: int = 42, dict_path: str = None, crops_root: str = None,) -> dict: assert os.path.exists(input_jsonl), f"Missing corrections JSONL: {input_jsonl}" dict_path = dict_path or os.path.join(PROJECT_ROOT, "ocr-studio", "data", "cham_dict_v24_1.txt") allowed_chars = _load_allowed_chars(dict_path) crops_root = crops_root or os.path.dirname(os.path.dirname(os.path.abspath(input_jsonl)))
from generate_data import normalize_unicode
protected_texts, protected_hashes = _load_protected_sets()
# Deduplicate by (crop_sha256, normalized_text) or (crop_sha256) keeping the latest correction latest_by_crop = {} stats = { "total_rows": 0, "skipped_no_crop": 0, "skipped_empty_or_invalid_chars": 0, "skipped_protected_leak": 0, "dedup_kept": 0, }
with open(input_jsonl, "r", encoding="utf-8") as f: for raw_line in f: raw_line = raw_line.strip() if not raw_line: continue stats["total_rows"] += 1 rec = json.loads(raw_line) crop_rel = rec.get("crop_relpath") if not crop_rel: stats["skipped_no_crop"] += 1 continue crop_abs = os.path.join(crops_root, crop_rel.replace("/", os.sep)) if not os.path.exists(crop_abs): # Fallback if crop_rel is relative to input_jsonl parent directory alt_abs = os.path.join(os.path.dirname(os.path.abspath(input_jsonl)), os.path.basename(crop_rel)) alt2_abs = os.path.join(os.path.dirname(os.path.abspath(input_jsonl)), "crops", os.path.basename(crop_rel)) if os.path.exists(alt_abs): crop_abs = alt_abs elif os.path.exists(alt2_abs): crop_abs = alt2_abs else: stats["skipped_no_crop"] += 1 continue
crop_sha = (rec.get("crop_sha256") or _sha256_file(crop_abs)).lower() text = (rec.get("text") or "").strip() if any("\uAA00" <= ch <= "\uAA5F" for ch in text): text = normalize_unicode(text) if not text or any(ch not in allowed_chars for ch in text): stats["skipped_empty_or_invalid_chars"] += 1 continue
if text in protected_texts or crop_sha in protected_hashes: stats["skipped_protected_leak"] += 1 continue
# Keep latest correction per crop_sha256 (avoid conflicting multi-labels for identical image crop) prev = latest_by_crop.get(crop_sha) ts = rec.get("timestamp_utc") or "" if prev is None or ts >= prev["timestamp_utc"]: latest_by_crop[crop_sha] = { "crop_sha256": crop_sha, "crop_abs": crop_abs, "text": text, "image_name": str(rec.get("image_name") or crop_sha[:16]), "timestamp_utc": ts, }
items = list(latest_by_crop.values()) stats["dedup_kept"] = len(items)
# Document-grouped split by image_name so lines from one page never appear in both train and val by_doc = {} for it in items: by_doc.setdefault(it["image_name"], []).append(it)
doc_names = sorted(by_doc.keys()) rng = random.Random(seed) rng.shuffle(doc_names)
n_docs = len(doc_names) if n_docs <= 1: val_docs = set() else: n_val_docs = max(1, int(round(n_docs * val_ratio))) if n_val_docs >= n_docs: n_val_docs = n_docs - 1 val_docs = set(doc_names[:n_val_docs])
train_items, val_items = [], [] for d in doc_names: if d in val_docs: val_items.extend(by_doc[d]) else: train_items.extend(by_doc[d])
# Avoid identical non-empty text appearing in both splits if another doc has the exact same string train_texts = {it["text"] for it in train_items} val_items_clean = [] for it in val_items: if it["text"] in train_texts: train_items.append(it) else: val_items_clean.append(it) val_items = val_items_clean
imgs_out = os.path.join(output_dir, "images") os.makedirs(imgs_out, exist_ok=True)
def _write_split(split_items, filename, prefix): lines = [] for idx, it in enumerate(split_items): dst_name = f"al_r4_{prefix}_{idx:05d}_{it['crop_sha256'][:12]}.png" shutil.copy2(it["crop_abs"], os.path.join(imgs_out, dst_name)) lines.append(f"images/{dst_name}\t{it['text']}\n") out_p = os.path.join(output_dir, filename) with open(out_p, "w", encoding="utf-8", newline="\n") as lf: lf.writelines(lines) return out_p, len(lines)
tr_path, tr_n = _write_split(train_items, "train_list.txt", "tr") va_path, va_n = _write_split(val_items, "val_list.txt", "va")
manifest = { "exported_at": datetime.now(timezone.utc).isoformat(), "input_jsonl": os.path.abspath(input_jsonl), "output_dir": os.path.abspath(output_dir), "dict_path": os.path.abspath(dict_path), "seed": seed, "val_ratio": val_ratio, "stats": stats, "total_documents": n_docs, "val_documents": sorted(val_docs), "train_samples": tr_n, "val_samples": va_n, "train_list": tr_path, "val_list": va_path, } m_path = os.path.join(output_dir, "export_manifest.json") with open(m_path, "w", encoding="utf-8") as mf: json.dump(manifest, mf, indent=2, ensure_ascii=False) return manifest
def main(): parser = argparse.ArgumentParser(description="Export Studio active-learning corrections to Stage R4 dataset.") parser.add_argument( "--input-jsonl", default=os.path.join(PROJECT_ROOT, "ocr-studio", "data", "active_learning", "corrections.jsonl"), ) parser.add_argument( "--output-dir", default=os.path.join(PROJECT_ROOT, "ocr-training", "data", "active_learning_r4"), ) parser.add_argument("--val-ratio", type=float, default=0.2) parser.add_argument("--seed", type=int, default=42) args = parser.parse_args() manifest = export_active_learning_dataset( input_jsonl=args.input_jsonl, output_dir=args.output_dir, val_ratio=args.val_ratio, seed=args.seed, ) print(json.dumps(manifest, indent=2, ensure_ascii=False))
if __name__ == "__main__": main().gitattributes+6
Dockerfile+41-41
ocr-studio/PaddleOCR/ppocr/modeling/backbones/rec_lcnetv3.py+1-1
ocr-studio/app.py
ocr-studio/data/cham_dict_v24_1_r3_1.txtAdded+114
ocr-studio/data/cham_dict_v24_1_r4.txtAdded+114
ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/cham_dict_v24_1.txtAdded+114
ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/inference.jsonAdded
ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/inference.pdiparamsAdded+3
ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/inference.pdiparams.infoAdded+3
ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/inference.pdmodelAdded+3
ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/inference.ymlAdded+156
ocr-studio/data/output/rec_cham_inference_v24_1_r3_1/model_manifest.jsonAdded+63
ocr-studio/data/output/rec_cham_inference_v24_1_r4/cham_dict_v24_1.txtAdded+114
ocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.jsonAdded
ocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdiparamsAdded+3
ocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdiparams.infoAdded+3
ocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.pdmodelAdded+3
ocr-studio/data/output/rec_cham_inference_v24_1_r4/inference.ymlAdded+156
ocr-studio/data/output/rec_cham_inference_v24_1_r4/model_manifest.jsonAdded+65
ocr-studio/index.html
ocr-studio/tests/test_quality_gates.py+334-272
ocr-training/scripts/export_active_learning_r4.pyAdded+249