Pinning the image deps changed nothing on the Space, so the prod/local gap
is probably the platform rather than the versions. /health now shows python,
OS/arch and paddle, paddleocr, paddlex, cv2, numpy so the two can be compared.
Ship local working tree: det multiscale, UVDoc unwarp, Qwen route
Detection gains a multiscale union pass and ink-based scoring; page_unwarp
flattens curved photos only when measured curvature clears 0.15, since
unconditional flattening took the 15-image bench from 4.20% to 20.26% CER.
Qwen re-read stays off by default (VOCR_QWEN=0) and its module is not shipped.
api: expose a fingerprint of the running source in /health
The HF API reported the Space at the newest sha while its output still
matched the previous build, so there was no way to tell a deployed change
from a stale container. /health now carries the first 12 hex of sha256
for vocr_pipeline.py, postprocess_v2.py and api.py, which can be compared
against `git show HEAD:<file> | shasum -a 256`.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
_apply_prep runs in api.py before the pipeline, while the light-on-dark
check lives inside run(), so a slide was eroded while still a negative.
Erosion shrinks the bright region: on a normal page that thickens the ink
(7836 -> 9858 ink pixels on a sample) but on a negative it thins the text
(7836 -> 5862). Exactly backwards for the images the inversion support was
added for.
Both the API path and the bench's prep_path now invert first, which also
keeps bench and prod doing the same thing. run()'s own check then finds
the image already upright and does nothing.
Also carries the bench's VOCR_BENCH_CTX knob from the corrector work.
15-image regression: CER 4.03%, every text identical character for
character.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
fix: three defects found by running the Space locally
Confidence was being reported as the rerank score once beam search went on.
That score is alpha times the CTC posterior plus (1-alpha) times a softmax over
the K candidates, which lives on a different scale: a page the recogniser reads
at 0.93 was reported at 0.21, and every box in the annotated image turned red
because the colour thresholds are 0.9 and 0.7. The displayed number and the
average now come from the recogniser's own confidence again; best_score stays
for the reranker's bookkeeping.
/ocr and /ocr/text still asked for "v11", a key that left MODEL_REPOS when it
shrank to ppv6_3 and ppv6_1, so the documented default endpoint answered 503 to
every client. The web UI hid it by only calling /ocr/batch. They now use
DEFAULT_VER.
The result pane was capped at 60vh with its own scrollbar while the image beside
it ran full length, so comparing the two meant scrolling twice.
Also adds trim_orphan_tail, off the back of a reported defect: books of exam
records print a name and its Ch…
rec: turn beam search on for v11, K=10 at alpha 0.30
Measured against the rule chain settled earlier today rather than the ten-rule
chain the benchmarks had been running by mistake. Over 20 pages accuracy goes
0.5090 to 0.5254 and CER 3.98 to 3.89, 34 lines better against 12 worse,
p=0.002; over the 15 labelled images CER goes 4.35 to 4.03 with 8 better and 1
worse. It costs 17% more wall time, about 1.1s a page; VOCR_BEAM=0 turns it off.
The earlier call to leave it off was made on that contaminated baseline, where
the ten-rule chain was itself breaking 45 lines and hiding what beam gained.
Beam and tone correction do not overlap even though both arbitrate tone marks
with the same language model: together they score above beam alone, because
tone correction now only adds a mark where the syllable has none, which is
where CTC saw no stroke and every beam hypothesis is bare too.
alpha stays at 0.30. The 0.10 that wins on pre-cut crops is a wash end to end
(52 better / 46 worse against the current chain), since crops contain none of
the…
det: fix the orientation scorer so rotated pages actually get flipped
The score used the space-fixer vocab, which accepts junk syllables, so rec v11
garbage matched at rate 1.000 and the score collapsed to text length; a
180-flipped read is only ~17% shorter and never cleared the 1.25x margin.
Score with ViLM.lm_score instead (syllable bigrams put correct reads at -1.4
and flipped ones at -4.5), and let the fast-path gate measure the same joined
string it scores. 15/15 rotated cases now read like upright ones (90 deg:
91-100% -> 2.4-5.6% CER); 0 of 15 upright images change. On by default.
prep: thicken strokes (erode 2x2) by default for ppv6_3
First pixel-level preprocessing that wins here: labelled bench 4.58% -> 3.75%
(11 better / 3 worse), 20 held-out book pages 3.55% -> 2.46% (17 / 3). Most of
it is det no longer splitting faint lines. prep=auto picks it only for the v11
rec; ppv6_1 keeps none. The whiten options lose on v11 and leave the UI.
prod: switch default rec to ppv6_3 (v11), keep ppv6_1 as secondary
v11 fixes CTC training on PP-OCRv6: PPLCNetV4 pooled to a fixed 40 steps in
train mode, so no line over ~40 chars ever got CTC loss. Labelled bench:
6.81% (ppv6_1 + rules + BARTpho) -> 4.58%, 9 images better / 5 worse.
The full rule chain and BARTpho lose on v11 output, so ppv6_3 runs only
fix_tone (margin 6) + fix_d_stroke via fix_text_v11; numbers in its docstring.
Fix crop/deskew/orientation handling for rotated and tight-spaced pages
- Tighten line crops to the main ink band: det unclip 1.5 makes crops bleed
into the next line, which wrecks recognition even on sharp scans (one line
read "hế," at 135px tall vs the full sentence at 102px).
- deskew: default max angle 15 -> 45, expand canvas when rotating (the old
fixed-size warp cut off page corners), and fill borders with the page's own
colour instead of white.
- Add opt-in orientation search (VOCR_AUTO_ORIENT=1) scoring each of the four
rotations by how Vietnamese the text reads; rotated pages previously
returned nothing at 90/270 degrees.
- Merge line fragments only when the page was actually skewed, with a looser
gap for rotated pages; merging everywhere hurt straight pages.
- Draw boxes on the deskewed image so they line up with the text.
- Resolve the corrector path from __file__ with a fallback, and warn loudly
when it is missing - it was silently disabling the correction layer.
- Surface per-line postprocess changes in the API and UI, plus a t…
ui: say when an image falls outside what the model was trained on
A typewritten letter reads at 15.79% CER and a street sign at 70.79% — the
sign returns 'DÍCHLCSỬĂHAN' for 'DI TÍCH LỊCH SỬ VĂN HÓA CẤP TỈNH'. Both sit
outside the 995k lines of old printed books the recogniser was tuned on, and
the pipeline's own domain check already spots it (8 of 17 lines on the
letter, 2 of 4 on the sign). That warning only reached the log, so users saw
inexplicable garbage instead of a reason.
The batch response now carries the out-of-domain line count and the page
says so plainly when most of an image is out of domain.
Also checked whether the sign fails because its text is white on red, the
opposite polarity to the training data: inverting the crops changes nothing,
so it is the letterforms, not the polarity. Recorded in docs along with what
would actually fix it.
prod: one model, batch upload with PDF page ranges, and a written record
Three changes asked for once ppv6_1 with BARTpho settled as the version to
keep.
Only ppv6_1 loads now. v4, v11, v11.2 and ppv6_2 came off the Space — they
were there to compare against and the measurements are done, while each one
cost a rec model, a ViLM (70s of startup) and RAM on cpu-basic. Their code
is untouched; adding a repo back to MODEL_REPOS brings one back. The
corrector lives in the v11 repo, so it is now fetched on its own when
VOCR_CONTEXT_FIX is set.
/ocr/batch takes several files at once, images and PDFs mixed. A PDF reads
its pages from ?pages=1-5,8 or 180- and renders them at 200 DPI; empty means
from page one. Twenty pages a call, since each costs 5-15s on CPU, and a
request that asks for more says how many it dropped rather than quietly
truncating. The page picker and multi-file input are wired into the UI; the
version and BARTpho selects are gone, image preprocessing stays because it
is the one option that still changes the answer usefully.
docs/PIPELINE.md rec…
Measured on 3000 lines of real ppv6 output, after space-fixer + rule chain
+ fix_d_stroke: acc 0.2287 -> 0.2843, CER 27.98% -> 27.48%, 655 better /
159 worse (4.12:1). A 5.6-point accuracy gain is far beyond what any of the
string-shape rules bought, because it reaches the class they are blind to —
lines where every syllable is a real word but the wrong one.
Runs on every line, not the OOV-routed subset: routing skips exactly that
class. v11 keeps routing, where its own numbers say 2.00:1 against 1.32:1.
Four hand-labelled book pages agree but by much less: 6.43% -> 6.29%, two
pages better and two worse. The layer earns its keep on degraded input and
is roughly a wash on clean pages, so expect the gain to show up on hard
scans rather than good ones. Costs ~3s a page on CPU.
ctx: turning BARTpho on by hand now runs it on every line
Switching the UI toggle on changed nothing on real pages, and the reason was
the OOV routing: the pipeline attaches the LM to the corrector, so should_fix
only lets through lines containing an out-of-vocabulary word. Lines like
'Tứ hai. con phải dùng...' or 'thì con phải thiệt hai biết' score OOV = 0 —
every syllable is a real Vietnamese word, just the wrong one — so the layer
built for exactly that error class never saw them.
An explicit use_ctx now bypasses the routing; the pipeline default keeps it,
since v11 measured 2.00:1 with routing against 1.32:1 without.
On 4 pages with hand-typed labels: off 6.63%, routed 6.46%, every line 6.41%.
The margin is thin and it is not a free win — on the Tựa page it fixes four
lines (Tứ hai -> Thứ hai, thiệt hai -> thiệt hại, in dã -> in đã, lai -> lại)
and damages eight (Cha muốn -> Chúa muốn, Song le -> Song lẽ, nên thánh ->
nên thành), so that page gets worse, 5.33% -> 5.57%. Default stays off.
ui: correct the stale numbers and drop the sales tone
The blurb still described the v11 setup: PP-OCRv5 on 400.000 lines with a
seven-step chain. Current ppv6 is PP-OCRv6 fine-tuned on 995.040 lines, the
chain is ten steps, and there is a space-fixer on top.
Rewrote the page copy to read like the coursework it is: says plainly where
it still fails (faded print, italics, proper nouns), tells people a few
cropped lines work as well as a full page (true since the strip padding
fix), and states the real per-page cost on CPU. Version and BARTpho options
now say what they actually do instead of "khuyến nghị".
fix: ppv6 never loaded the corrector, so the UI toggle did nothing
The shared corrector path was resolved with os.path.isdir before the
download loop ran, when ./hf_v11 does not exist yet, so ppv6 always got
ctx_model_dir=None and ?ctx=1 was a no-op on the Space (identical output
to ?ctx=0, which is how this was caught).
Resolve it when each pipeline is built instead — v11 is downloaded earlier
in the same loop, so the directory is there by the time ppv6 is
constructed. The compare responses now also report ctx_available and
ctx_used so a silent miss like this is visible in the payload.
ui: add a BARTpho on/off select, and run it last for ppv6
The rule chain only looks at string shape, so it is blind to lines where
every syllable is a real word but the wrong one (linh khổn / sư ấy / chệ
bó). That is what the BARTpho layer is for, but ppv6 did not even load it.
ppv6 now loads the corrector — pointed at the v11 copy, so the 1.6 GB sits
in RAM once — with ctx_default=False, and the UI gets a third select to
force it on or off per request (?ctx=1 / ?ctx=0). Default stays off since
the corrector was tuned on v11 errors.
For ppv6 it also has to run AFTER the space-fixer and the rule chain, not
before: raw v6 output is glued, and correcting glued text is meaningless.
v11 keeps the old position and default.
On the 3 labelled pages it does help, against the earlier read that it hurt
v6 — that verdict was about the old v11-tuned corrector, not the 795k
v6-aware one deployed this session:
off 7.03% on 6.77% (p8 5.56 -> 4.88, p20 13.21 -> 13.09)
Cost ~2.7s per page.
ppv6: run the rule chain after the space-fixer, and turn it back on
The chain was disabled for ppv6 because it mangled the model's glued
output (iansuynghĩ... -> iaữệiê). That only happened because fix_text
ran BEFORE the space-fixer, so it saw glued runs. Deferring it until
after the space-fixer removes the cause: it now sees ordinary spaced
Vietnamese.
Measured on 3 pages of 'Cách Mầu Nhiệm' with hand-typed labels (2496
chars, rec ppv6_1): CER 7.88% -> 7.14%. It wins on the faded page with
broken detection too (13.21% -> 12.86%), not just clean pages, so no
per-line quality gate is needed — gating by confidence or OOV scored
worse (7.29%) than applying it everywhere.
Beam stays off for ppv6: use_fix no longer doubles as the beam switch.
Cost: ppv6 now trains ViLM at startup (~70s, pickle-cached).
Root cause of mangled lines: crop_preprocessor (tuned for old data) wrecks
v6 crops ('iansuynghĩ...'->'iaữệiê', conf 0.84->0.91 when off); beam is
unstable on v6; textfix mangles glued v6 output. ppv6 now = deskew + crop
+ greedy rec_v6 + space-fixer + '('->'C'. No ViLM -> faster startup, less
RAM. v11/v11.2 unchanged.
Disable BARTpho for ppv6 (v11-tuned corrector hurts v6)
Corrector is fine-tuned on v11 errors; on ppv6 it fails to fix v6-style
proper-noun errors ('Giết-su') and sometimes worsens output ('à'->'mà').
v11/v11.2 keep it. ppv6 keeps generalizing fixes (crop, space, '('->'C').
Enable shared BARTpho corrector for ppv6 (singleton, no extra RAM)
ppv6_1/ppv6_2 point ctx_model_dir at v11's corrector dir; get_corrector
caches by path so all pipelines share one BARTpho instance. Helps
all-real-word context errors on body lines (Lev<=3 guard still skips
heavily garbled ornate footer).
Add Vietnamese space-fixer for glued OCR output (ppv6)
space_fix.py: DP re-segmentation into corpus syllables to re-insert
missing spaces ('conlàkẻ'->'con là kẻ'); conservative (keeps runs with
OCR errors intact). Wired into VOCRPipeline (space_fix flag, applied
after text post-fix) and enabled for ppv6_1/ppv6_2 in api.
Reorder options so ppv6_1 (PP-OCRv6) is first/default; drop the
misleading 'weak on long lines' label (prod loader reads long lines
fine). v11/v4 kept as fallback options.
Show post-processing in UI for ppv6/v11.2 via generic /{ver}/compare
Add /{ver}/compare (before/after post-fix) for any version; route all
post-proc versions (v11, v11.2, ppv6_1, ppv6_2) through it; render
detects compare view from text_fixed in response.
Frontend dropdown was hardcoded to v4/v11/v11.2; add ppv6 options.
Add catch-all /{ver}/ocr routes (after specific ones) so any version
in pipelines is reachable; _run_ocr already resolves by ver.
Add PP-OCRv6 rec support + ppv6_1/ppv6_2 versions
rec_v6.py loads PP-OCRv6 rec via raw paddle.inference (paddlex lacks v6).
vocr_pipeline auto-detects PP-OCRv6 from inference.yml and uses that loader.
api adds ppv6_1 (v1 0.64) and ppv6_2 (v2, long-line fix); v4/v11 unchanged.
Surface the context-layer load error instead of swallowing it
/health said da_khoi_tao=True, dang_chay=False, thu_vien=co — the model loads and
throws, and the except block only logged a warning nobody can read on a Space. Keep
the exception text on the object and report it, plus the files actually present and
the model size, so a bad download is distinguishable from an OOM.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The layer fails silently: a missing model, missing torch, or an OOM all just log one
warning and skip, so the output is indistinguishable from having it off. Hit that for
real — the env var was set and the Space ran the right commit, yet output matched the
disabled build exactly. /health now says whether it is enabled, whether the model
folder arrived, and whether it actually loaded.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Wire context-correction model into the Space download path
Ships torch (CPU wheel) + transformers + rapidfuzz in the image so the layer can be
toggled by env without a rebuild. The corrector lives in the v11 model repo under
models/corrector/, so ctx_model_dir resolves to it with no api.py plumbing.
Two download-path gotchas the naive version would hit:
- the skip check only looked at models/inference_rec, so a Space with a cached model
would never fetch models/corrector and the layer would silently do nothing
- snapshot_download pulls the whole repo, so with the layer off every startup would
drag 1.5 GB for nothing — now filtered out unless VOCR_CONTEXT_FIX=1
Still off by default; enabling needs VOCR_CONTEXT_FIX=1 plus the model uploaded.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Let the LM pick among up to 8 edit-distance-1 candidates behind a logprob
margin, instead of only firing when exactly one candidate exists. Capped at
8 rather than 20: same CER, four times fewer regressions.
CER 9.58% -> 9.55% greedy, 8.64% -> 8.62% with beam.
CTC sometimes spills one character into a token of its own next to the source
word ('Khi c con gau'). Drop it when the fragment is a 1-char prefix or suffix
of its neighbour after stripping diacritics. Has to run right after fix_repeat,
or fix_merge glues the fragment onto the wrong side.
205 lines fixed / 54 broken. acc 0.3860 -> 0.3893, CER 8.73% -> 8.64%
fix_case only lowercases when the result is in the vocab, so 'McNamara' is
left alone. Plus four narrow punctuation rules. Four other ideas were measured
and dropped, including a 4-gram syllable LM that won its narrow test but lost
end to end - numbers are in the docstrings.
acc 0.3810 -> 0.3860, CER 8.83% -> 8.73%
Fix double softmax in the beam decoder, add fix_merge
_to_log_probs ran log_softmax over the already-softmaxed rec output, squashing
the logprob range from 16.6 to 0.99 nat, so beam search was exploring a nearly
uniform distribution. Alpha drops 0.7 -> 0.10 now that CTC scores mean
something. Beam also moves in-process: PaddleOCR/ is gitignored, so the built
image silently fell back to greedy. fix_merge glues token pairs that cannot
stand alone ('gi au sang' -> 'giau sang').
acc 0.3237 -> 0.3807, CER 9.78% -> 8.83%
Wire the prep param into all 14 file endpoints
Lâm Quỳnh Hương
0bf7eb1
Only /v11/ocr and /v11/compare declared prep, so FastAPI silently ignored it
everywhere else - prep=none and prep=whiten returned identical output with no
error, which is worse than failing. Verified by walking app.routes: 14 accept
prep, 0 missing.
Add background whitening preprocess modes
Lâm Quỳnh Hương
61715d2
Idea from ds4v/NomNaOCR: add the threshold mask to the original image so the
background saturates to white while strokes keep their grey levels. Both modes
lose to doing nothing on 5 scanned pages (syllable OOV 2.11% vs 3.74% and
5.60%), so the default stays off - shipped as an option so it can be rechecked
on other scans.
Replace the static docs at / with a working demo page
Upload a page and get the annotated image next to the recognised text, plus
the list of lines postprocessing changed. Living inside the Space means no
CORS setup and nothing extra to host. Uses /v11/compare with annotate=1 so one
request covers both text and image instead of two model runs.
Add /v11.2: same model as v11 but page preprocess on
A user reported worse OCR after the last deploy. The API path never changed -
VOCR_NO_ENHANCE defaults to off in both builds; what moved was the CLI
default. /v11.2 brings the old behaviour back so the two can be compared on
the same image. Our own 11-page measurement says off is better, but scans
differ enough that it is worth checking per source.
needs_enhance fired on 84% of pages because yellowed paper counts as "coloured
background", and enhance itself halves the resolution, hard-binarises and
erases 93.2% of blobs in the 20-30px band - which is where tone marks live.
Every metric gets worse with it on (syllable OOV 4.22% -> 7.31%).
Ensemble of 5 models is off by default: acc 0.3067 -> 0.3823 at 5.2x the time.
Also adds annotated-image output to the API.