Row grouping interleaves the two halves of an open-book photo: 6 of 7 spread
pages flipped sides 32-69 times per page, now 1. Cut at the sparsest vertical
slice near the middle, not at a gap -- one box across the gutter hid the gap
on ht_3. Only cut within 0.08 of centre, or the index page vandailoaingu/495
splits between its name and page-number fields (31.24% -> 74.17% CER).
Reinstall opencv last so both sides run the same cv2
paddlex pulls opencv-contrib-python, which overwrites the cv2 module, so the
pinned headless 4.11.0.86 lost and the Space ran cv2 4.10.0 against 4.11.0 on
the dev machine. Forcing it after the paddle install makes the two agree.
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.
Same source gave 3 lines locally and 1 on the Space for one photo, and the
reverse on another, because every rebuild pulled whatever `>=` resolved to.
Base moves 3.10 to 3.12 to match. torch stays 2.6.0: the CPU index has no
cp312 linux wheel for the local 2.10.0, and the corrector is off anyway.
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.
det: pick the facing-page filter on geometry ratios, not box counts
The first version keyed on how many boxes a cluster held and how much its
line angles spread. It worked on my machine and never fired in prod: on
the same photo detection yields 43 boxes locally and 26 on the Space, and
both of those quantities move with it - the minority share goes 0.30 to
0.73 and the main cluster's angle spread 2.2 to 10.2 degrees, so each
gate fails there.
Two ratios do not move: the facing page is squeezed to about a fifth of
the main page's text width (0.205 local, 0.211 Space) and its boxes are
about one and a half times taller because the lines run at a slant (1.52
and 1.49). Both describe the geometry of a page seen edge-on rather than
how many boxes detection happened to find.
A third condition, at least four boxes in the cluster, came from a
measured regression: without it the index page vandailoaingu/page_495
lost the single-box cluster holding its page number 501, which is narrow
and tall enough to pass the other two gates, and its CER went 10.17% to
10.…
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>
det: drop boxes belonging to the facing page of an open book
A phone photo of an open book usually catches the other page edge-on.
Detection boxes it like any other ink, the recogniser returns fragments,
and worse: reading order groups by row, so the two pages interleave. On
the reported photo the output began with a scrap of the facing page and
had 6 backward jumps in y across 42 pairs.
The two pages separate on two signals, both required. They do not
overlap horizontally - a sweep of the gap threshold from 0 to 0.016 over
42 test images splits exactly one image, the open-book photo, and leaves
the other 41 as a single cluster. And a page seen edge-on gives each line
a different slope: 15.8 degrees of spread against 2.2 for the flat page.
The second signal is what keeps two-column documents safe, since both
columns of a flat page share one angle.
Where it runs matters more than the thresholds. Called straight after
detection it never fired: there are 58 boxes at that point and one of
them spans x[0.005-0.999] across both pages, so no horizont…
full_text already skipped them, but `results` did not, so the API and the
UI still drew a box and counted them as lines. Seen on a page of Chinese
verse: detection boxes the characters correctly, the recogniser has
nothing in its 233-character table to emit, and returns an empty string
with confidence 0.705 and 0.559 - high enough to pass the confidence
gate meant for bleed-through.
A box that recognises to nothing is not a line, so it is dropped
regardless of confidence.
20 pages acc 0.5254, NE 0.9524, CER 3.89% and 15 images CER 4.03%, both
unchanged, with every text identical character for character.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
docs: bring the pipeline overview back in line with the code
Section 1 still showed the flow as it was before orientation handling,
polarity inversion, beam search and fix_ortho went in, and it listed
space_fix and BARTpho as part of the chain although both are off. The
diagram now follows the actual call order, including that page
preprocessing runs in api.py outside the pipeline.
Adds the current numbers and a list of what is deliberately switched off
with the measurement that settled each one, so the next person does not
re-enable them blind.
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>
post: repair words that break Vietnamese spelling rules
Vietnamese has hard orthographic constraints, and breaking one means the
word is certainly wrong: q only ever occurs in qu, gh/ngh only before
e/ê/i/y and g/ng never there, k only before e/ê/i/y and c never there,
and a final consonant must be one of c ch m n ng nh p t.
The dictionary-derived rime inventory already in _impossible() cannot
express the co-occurrence half of this: "nge" splits into ng + e and both
pieces exist, yet Vietnamese writes "nghe". So _ortho_violation() states
those laws directly.
The laws also generate the candidates, and that is where the win is.
Generic Lev-1 offers 62 candidates for "ce", 50 for "ka", 34 for "nge"
and 21 for "qa", then asks the language model to pick one. Each law
admits only a few legal repairs: 1, 1, 1 and 4.
Context gate: a first version broke a real line, turning "Qách mần nhiên
linh mến" into "Quách" where the label reads "Cách mầu nhiệm kính mến".
The right candidate was in the list but lost, 19.73 to 18.73 - the whole
line was misre…
det: invert light-on-dark images before detection
DBNet det and the recogniser are both trained on dark text on light
paper. On a slide or a negative scan det finds nothing at all: dep
inverted gives 0 lines and 100% CER against 17 lines normally. Reported
from the UI as "1 line, 56% confidence" on a 5-line slide.
_is_light_on_dark() runs before everything else, deskew included, since
deskew also thresholds on the assumption that ink is the dark class.
Otsu split, majority class is the background, and the background must be
dark in two regions: the central 60% block and an 8% border ring. Each
one alone has a case that fools it - without the centre a page shot on a
dark table flips, without the ring a single-line crop flips because
strokes dominate the middle of a text strip.
Measured on 1500 real images from the corpus: centre only gives 43 false
positives, all under crop_img/; adding the ring gives 0, while still
catching 15/15 inverted bench images. End to end the inverted image now
matches the normal one line for line on dep, p8…
orient: generalise rotation to any angle, keep 4 directions as default
run_oriented() now takes tiers instead of a fixed angle list, and
_rotate_any() rotates by an arbitrary angle with canvas expansion and a
paper-coloured border (multiples of 90 still go through cv2.rotate, so
the default path is unchanged).
Measured before choosing the default. Deskew does not leave a +-45
residual as assumed: it lands the page on a multiple of 90, because the
score picks the angle that makes text lines horizontal and "horizontal"
is only defined mod 90. Across 4 images x 24 angles, 92/96 landed within
3 degrees of a multiple of 90, the other 4 within 5. So deskew plus the
three 90-multiples already covers the full circle: a 24-angle OCR sweep
reads 0.20-0.98% CER at every angle against 0.39% upright, and 12
diagonal cases score identically with and without a diagonal tier (no
diagonal rotation file was ever written).
Diagonal tier stays available behind VOCR_ORIENT_DIAG=1, off by default
so a junk image costs 4 det+rec passes rather than 8.
Regression, 15 hand-labe…
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…
docs: separate the compound-word idea from the PMI way of measuring it
PMI computed from this corpus fails, but that does not retire the idea. The
corpus is built from this archive's own labels, so it does not know tue cong or
dinh Quang Ngai are collocations; recomputing statistics over it will not teach
it. The idea needs a compound or gazetteer list from outside.
post: let tone correction only restore a missing mark, never swap one
Over 20 pages the free version fixed 22 lines and broke 8. Every one of the 8
was a swap between two real words: cong to cong with a different mark, hai to
hai, diem to diem, da to da, Thuy to Thuy. Restoring a mark on a syllable that
carries none is a different kind of claim: faint print drops the mark, mostly
the dot below, and more than half the good fixes are dam to dam, huyen to
huyen, truyen to truyen, ruong to ruong.
Restricting to that direction keeps the same accuracy, lowers CER from 3.99 to
3.98, and goes from 22/8 to 14 better and none worse, p 0.016 to 0.0001. Other
restrictions were weaker: allowing the dot below as well gives 14/3, forbidding
only removals 17/5, the dot below alone 13/3.
Collocation PMI as a veto was re-tested at page level and still fails: the two
highest values sit among the lines the rule fixed, not the ones it broke.
docs: record the tone-placement lock and the rejected capitalisation veto
Thuy with the mark on the y and on the u are the same syllable spelled two
ways, both correct; the corpus holds both because it was gathered from editions
that follow different conventions, so the language model picks by frequency.
Three of the nine lines tone correction broke over 20 pages were exactly this,
all of them hill names. Candidates that only move the mark are now refused:
22 better / 8 worse against 22/9, CER 4.00 to 3.99, p 0.029 to 0.016.
A proper-noun veto is in but off. Blocking a syllable whose neighbour is
capitalised mid-sentence loses 3 to 10; blocking only the capitalised syllable
itself loses 3 to 5. The idea is right, five of the nine failures sit next to a
capitalised word, but this corpus is dense with place names and office titles,
so a rule keyed on capitalisation blocks more good corrections than bad ones.
docs: fix the places that still described the dropped d-stroke rule
The overview line and the production summary both still listed it, and the
section that used it as the example of re-checking old numbers now carries the
full arc: rejected on v11, adopted on v6 crops, dropped end to end.
post: drop the d-stroke rule, keep only tone correction for v11 rec
The rule was adopted on a line-level number (8 better / 3 worse on pre-cut
crops). End to end it loses: 0 better / 4 worse over 20 pages and 1/1 over the
15 labelled images, and chaining it after tone correction scores below tone
alone. All four lines it broke are the same failure: dinh -> dinh with a stroke,
da -> da with a stroke, trading administrative Sino-Vietnamese words for common
ones because the n-gram always bets on the frequent form, and two of the four
were already correct. All four add a stroke, while the model's own bias is to
add one 72 times against dropping one 34 times.
The benchmarks were also running the wrong chain: they built the pipeline with
textfix=True but never installed fix_text_v11 the way api.py does, so they
measured the full ten-rule chain. VOCR_BENCH_RULES now selects which rules run.
prep: measure whether thickening helps detection or recognition
Thickening the whole page before the pipeline was justified by "most of the gain
comes from detection", which turned out to be only part of the story. Thickening
just the crops, with detection on the untouched page, wins 144 lines to 46 on
its own, so recognition really does read bolder strokes better. It still only
recovers about 38% of what whole-page thickening gets, and eroding twice
overshoots, so the default is unchanged.
The old line-level number said the opposite (239 better / 370 worse). That set's
crops have a median height of 33px against 60px for real pipeline lines, so the
same 2px erosion bites twice as hard there. Scale-sensitive operations measured
on it do not carry over.
Adds env switches for the detection post-processing steps so they can be ablated
one at a time, and a box dedup pass left off: the whole 20-page set contains one
overlapping pair, too rare to validate a rule on.
bench: match predictions to labels by polygon, in deskewed coordinates
run_pages.py matched bounding boxes against labels in the original frame, but
run() deskews before detecting, so boxes came back rotated ~63px off, and a
skewed label's axis-aligned box is three line-heights tall and swallows its
neighbour. One page read nearly right and scored 80% CER. It now rebuilds the
deskew matrix, warps the labels, and intersects polygons.
That flipped the beam verdict at page level: 26 lines better / 13 worse and 12
pages better / 3 worse at alpha 0.30, not the wash the earlier crude protocol
reported. Also recorded that alpha tuned on cropped lines (0.10) is a wash
end-to-end, since cropped lines contain no detection damage.
rec: add beam search + LM rerank for v6, measured, left off
rec_v6 now exposes topk() built from the same probability matrix greedy reads,
so both decoders see one image; ctc_beam_rec.BeamRecognizer cannot be reused
because it pads to the v11 width. The pipeline uses the loaded RecV6Predictor
as its n-best source rather than loading the model twice.
On 3000 test crops this wins clearly (acc 0.6123 -> 0.6367, 275 better / 136
worse) but end-to-end on 20 scanned pages it moves CER by 0.01 point for +20%
time, and it hurts phone photos. Left off; numbers and the alpha/gate sweep are
in docs/PIPELINE.md 4.4. Adds run_pages.py, a 20-page end-to-end benchmark.
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…
det: fall back to detection when the small-image shortcut reads nothing
An image 1170x117 came back with no lines at all. run() has a shortcut that
treats a small image as an already-cropped line and hands it straight to
rec, skipping detection — and every piece of thin-strip handling with it.
Here rec read the whole strip as empty, the confidence filter dropped the
empty line, and the user got nothing, while the ordinary detection path
reads the line fine.
Try the shortcut first, and when it returns empty or low confidence, fall
through to detection. That image goes from 0 lines to 0.00% CER. Costs one
wasted rec call, about 35ms.
Also moves the labelled benchmark into the repo at tests/bench/ — it had
been living in a scratch directory and was lost when that was cleaned. 15
images now, each aimed at a different failure: thin strips, faded ink,
show-through, indented verse, a typed letter and a street sign that are both
out of domain. run_bench.py prints per-image wins and losses next to the
combined CER and refuses a change where losses outnumber wins,…
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…
det: choose between autocrop and full frame by how much ink lands in boxes
Skipping autocrop on thin strips fixed a one-line photo (52% -> 4%) and
broke a four-line one: on IMG_2130 the full frame made detection shred each
line, dropping 'nhận ra' and 'một nỗi xúc động tương tự' entirely, 28.67%
against 16.78% with autocrop kept. Neither choice is right for both.
So run detection both ways on strip-shaped images and keep whichever covers
more of the page's ink. Shredded detections leave words outside every box —
faint ones especially — so ink coverage separates them without needing to
guess from the image up front. One extra detection pass, only on strips.
Twelve labelled images: 5.70% -> 5.43%. IMG_2130 28.67% -> 4.90%, temp3
11.62% -> 5.56%, the one-line photo holds at 4.00%, nothing else moves.
det: add gap rescan between boxes on a line, measured and left off
Detection also punches holes mid-line, not just at the edges: on IMG_2130 it
boxed 'tay tôi đã' and 'vẻ đẹp của nàng và' and left the words between them
out of every box, so they vanished from the output.
_rescan_gaps walks each line's columns, takes the ink reference from the
parts that did get boxed, and re-detects the uncovered stretches. Columns
inside a word are not contiguous — the gaps between letters break the run —
so the hot mask is dilated by half a line height before runs are measured,
otherwise nothing ever qualifies.
It locates the hole correctly (x613-809 on IMG_2130, exactly where 'nhận ra'
sits) and still recovers nothing: the ink there is so faint that detection
returns no box, and forcing the crop through rec reads '312'. Twelve
labelled images: 6.37% -> 6.37%, not one changed. The limit is contrast,
not localisation.
What does help on that image is whitening the background — 28.67% ->
13.29% with whiten_local — but it costs on ordinary book scans (an older
measur…
rec: drop lines whose confidence says they are show-through ink
Ink pressed through from the back of the sheet gets detected as lines, and
rec dutifully reads the smudge — a photo of two lines of verse came back
with 'Ô TH' and 'L4' appended from the faint text underneath. Those two
scored 0.36 and 0.44 while the real lines on the same image scored 0.96 and
0.98, so confidence separates them cleanly.
Eleven hand-labelled images, combined CER by threshold:
none 5.87% · 0.3 5.87% · 0.4 5.76% · 0.5 5.70% · 0.6 5.81%
0.5 it is: the show-through image goes 10.96% -> 0.00%, dep.jpg edges down,
and only temp3 loses 0.51. At 0.6 it starts eating real lines (dep.jpg 3.54
-> 4.52).
det: rescan the top and bottom edges for lines detection dropped
The detector loses the first or last line of a text block — the opening line
of dep.jpg, the closing line of another photo. The two whole-page remedies
measured earlier both disturbed images that were already fine, so neither
shipped.
This one only looks outside the boxes already found, and only fires where
there is ink at a density comparable to the lines the detector did find. The
reference is that page's own ink profile rather than a constant, so scanner
smudge in the margin does not trigger it. When a band qualifies it is cut
out, padded, and detected on its own, and the boxes merge back in reading
order.
Ten hand-labelled images: 6.62% -> 5.79%. All of it from dep.jpg, 11.39% ->
3.73% as the opening line comes back. The other nine are unchanged — a few
gain a box (a page number) without moving CER. Nothing regressed.
Two mistakes worth recording, both hit while writing this: the band has to
go through _prep_for_detection like the main path rather than being handed
raw to _detec…
det: add two-pass union and line-fragment merge, both measured and left off
Two ideas for the detector's remaining failures — it drops lines at the top
or bottom of a block, and it splits one line into pieces that each go to rec
without context ('niệm ».' alone reads back as 'viện».').
_union_boxes runs detection a second time without the background division,
then merges box sets, so a line either pass finds survives. _merge_line
_fragments joins pieces of one line into a single crop, with a gap under
0.6x line height and no fragment shorter than 0.55x the line, so specks do
not swell the crop.
Neither ships on. Ten hand-labelled images, CER by image:
1dong dep temp3 temp6 p20 | all
current 4.00 11.39 11.11 0.00 10.43 | 6.62%
+ merge 4.00 10.22 26.26 0.00 11.01 | 7.24%
+ union 4.00 4.91 17.17 22.22 11.94 | 7.01%
+ both 4.00 1.96 26.26 0.00 11.70 | 6.41%
"Both" wins on aggregate CER but only through dep.jpg, while wrecking temp3
and p20 — two images better,…
det: skip autocrop for thin strips — it removes the margin det needs
A photo of a single line came back as five fragments ('Tiên bọc v', '1',
CER 52%). Autocrop was trimming the white margin right down to the glyphs,
and the detector has nothing to anchor on: padding that tight strip to page
shape still produced garbage, and the earlier 0.5w fallback only softened
it.
Keep the original margins instead when the autocropped result is a thin
strip, then pad as before. Same line now reads 'Tiên học võ, hậu học văn.'
at CER 4%.
Ten hand-labelled images: the one-line photo 52.00% -> 4.00%, IMG_2132
0.00% -> 1.52%, everything else unchanged — book pages never trigger it
since autocrop leaves them portrait.
det: order boxes by reading order, not a flat y sort
Boxes came back sorted by (mean_y, mean_x). That breaks whenever the
detector splits one visual line into pieces: two fragments of the same line
differ by a few pixels of centre-y, a box from another line sorts between
them, and the page comes back scrambled — one line read out as 'mà không
bằng khái' / 'viện».' / 'làm để phòng' in three separate places.
Group boxes into lines first, by vertical overlap of more than half the
shorter box's height, then sort each line left to right. Overlap rather
than a fixed tolerance so mixed type sizes on one page still group.
Five hand-labelled images: CER 7.46% -> 6.47%. The gain is entirely on
pages the detector fragments (dep.jpg 15.52% -> 11.39%, the faded p20 12.63%
-> 10.43%); the three single-column book pages are untouched, they were
already in order.
Also adds a fallback for thin strips: when the h=1.4w padding yields no
boxes at all, retry detection at 0.5w and then unpadded. A one-line photo
returned nothing before this.
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.
ppv6: enable fix_d_stroke — it loses on v11 but wins on v6
fix_d_stroke has sat in the file unused since it was measured on rec v11
and lost: 12 better / 16 worse. The docstring said to keep it only so
nobody retried it. On ppv6 output the same function with the same
thresholds reverses: 77 better / 17 worse (4.53:1), acc 0.2233 -> 0.2287.
The d bar is thin and drops out on faded print. v6 loses it fairly
consistently in one direction, so the n-gram has a direction to bet on; v11
confused both ways and the model could not call it.
On 4 pages of 'Cách Mầu Nhiệm' with hand labels: 6.63% -> 6.43%, three
pages better, one unchanged, none worse. Catches dều -> đều, dã phong -> đã
phong, Cho dược -> Cho được, diều -> điều.
Wired as fix_text(..., d_stroke=True) on the ppv6 path only, so v11 keeps
the behaviour its own numbers justify.
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.
space_fix: also protect long capitalised words from letter rewrites
The ALL-CAPS guard missed title-case foreign words: 'Figure' came back as
'Giá trị' and 'Timbre' as 'Tiến ra', the same way MONTFORT once became
'Một loạt'. Words starting with a capital and at least 5 letters long now
join ALL-CAPS runs in split-only mode.
Measured on real ppv6_1 output (3000 lines, 28.10% CER with the current
guard):
+ title-case >= 4 CER 27.96% 86 better / 13 worse 6.6:1
+ contains f/j/w/z CER 28.10% 1 better / 0 worse (touches 1 line)
+ title-case >= 5 CER 27.95% 86 better / 12 worse 7.2:1 <- chosen
Threshold 5 keeps both Figure and Timbre while touching fewer lines than 4.
The f/j/w/z rule (letters absent from the Vietnamese alphabet) sounds right
but barely fires — the title-case rule already covers it.
The three labelled book pages improve too: 7.14% -> 7.03%.
det: pad thin strips to page shape before detection
Photos or crops of just a few lines came out as garbage: the detector is
fine-tuned on full book pages, so on a 1214x198 strip it shreds each line
into fragments ('hiều', 'nb', 'Qun', 'am') and drops the last line
entirely. After autocrop, anything wider than 2.5x its height now gets
white padding top and bottom until it is 1.4x taller than wide, and box
coordinates are shifted back by the pad.
What actually fixes it is the FRAME RATIO, not resolution — upscaling the
same strip 2x/3x/4x still scored 38-42% CER — and it has to be portrait:
padding to h=1.0w or h=0.7w still broke (41%/29%).
Measured on 4 strip images with hand-typed labels, CER off -> on:
photo of 3 lines 65.91% -> 2.27% (9 boxes -> 3)
temp3 60.61% -> 6.57% (11 -> 6)
temp6 0.00% -> 0.00%
temp7 7.87% -> 13.43% (the one regression)
combined 36.25% -> 7.28%
Book pages are portrait after autocrop (~0.7) so they never trigger it;
re-measured the 3 labelled…
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).
The fuzzy segmenter allows 2 edits per syllable, which mangles proper
nouns and headings: MONTFORT -> Một loạt, QUYỀÊỀN 115 -> Quân về 115,
TUY ĐƯỜÔNNG -> TUY Đều dùng. ALL-CAPS runs now use split-only mode —
spaces may still be inserted (ANNAMCHÍLƯỢC -> AN NAM CHÍ LƯỢC) but the
letters are left alone.
Measured on the 3000-line test set: CER 11.34% -> 11.28%, 25 better /
1 worse. Blocking those runs entirely scored a hair better on CER but
refuses to split glued caps headings, which is the ppv6 failure mode.
space_fix: add fuzzy multi-syllable correction via bigram
Fixes garbled clusters where OCR drops chars inside glued syllables
(e.g. rtniều -> rất nhiều), which the exact-match DP couldn't reach.
Uses corpus bigram counts to disambiguate short fuzzy matches instead
of raw unigram frequency. Also strips Roman-numeral noise (i, ii, ...)
that had leaked into the high-freq vocab from old book indices.
Tested on 19 cases incl. regressions; ~2ms/line overhead.