| # Armenian OCR Evaluation Kit (RLALT/ACoPPer, RLALT/ACoPDoc) |
|
|
| Everything needed to score your own OCR/VLM model's predictions against the |
| `RLALT/ACoPPer` (printed newspapers) or `RLALT/ACoPDoc` (diverse documents) |
| ground truth published on the Hugging Face Hub — no other files from the |
| source repo required. |
|
|
| For the exhaustive field-by-field meaning of every key in a generated report |
| JSON, see [REPORT_JSON_METRICS.md](REPORT_JSON_METRICS.md). This document |
| explains *how* the numbers are computed and *why*. |
|
|
| ## Quick start |
|
|
| ```bash |
| pip install -r requirements.txt |
| ``` |
|
|
| 1. Run your own model on the dataset's page images (`row["image"]` per row, |
| see §9) and save its output as one JSON file per page: |
| `[{"box": [x1, y1, x2, y2], "text": "..."}]`. |
| 2. Convert those to evaluation CSVs: |
|
|
| ```bash |
| python3 convert_predictions_to_evaluation_csv.py \ |
| --predictions-dir path/to/your/predictions \ |
| --output-dir path/to/your/evaluation_csvs \ |
| --unit-level word # or line — see §3 |
| ``` |
|
|
| 3. Evaluate directly against the Hub dataset (ground truth is pulled from HF, |
| no local annotation files needed): |
|
|
| ```bash |
| python3 evaluate_from_hf.py \ |
| --dataset RLALT/ACoPPer \ |
| --predictions-dir path/to/your/evaluation_csvs \ |
| --output-dir results/ \ |
| --unit-level word |
| ``` |
|
|
| Prints per-variant CER and writes the four standard report JSONs to |
| `results/`. See §9 for what `evaluate_from_hf.py` does internally and how |
| to adapt it (e.g. to filter to one manifest split). |
|
|
| ## 1. What's in this kit |
|
|
| ``` |
| model predictions (any shape) |
| │ |
| ▼ convert_predictions_to_evaluation_csv.py |
| per-page evaluation CSV (x1,y1,x2,y2,group_row,text) |
| │ |
| ▼ evaluate_from_hf.py |
| │ (loads GT straight from the HF dataset, calls |
| │ evaluation/measure_accuracy.evaluate_rows + |
| │ evaluation/measure_overall_accuracy.aggregate_reports) |
| report JSON (summary + per-region CER + failure examples) |
| ``` |
|
|
| | Path | Purpose | |
| |---|---| |
| | `evaluate_from_hf.py` | **Main entry point.** Loads GT from a Hugging Face dataset and scores your predictions against it. | |
| | `convert_predictions_to_evaluation_csv.py` | Converts your model's raw per-page JSON into the CSV format the evaluator expects. | |
| | `evaluation/measure_accuracy.py` | Core scoring logic for one page (`evaluate_rows`) — imported by everything else. | |
| | `evaluation/measure_overall_accuracy.py` | Aggregates many page reports into one (`aggregate_reports`). | |
| | `evaluation/generate_accuracy_report_variants.py` | CLI for evaluating against **local** annotation JSONs (Label Studio export format) instead of the Hub — only useful if you have your own local GT files, and supplies the `REPORT_VARIANTS` list `evaluate_from_hf.py` reuses. | |
| | `evaluation/reports.py`, `evaluation/prediction.py`, `evaluation/text_metrics.py` | Region assembly, predicted-text reconstruction, and CER math — not run directly. | |
| | `box_grouping/` | Geometry, spatial reading-order logic, and CSV/annotation-JSON loading that `evaluation/` depends on. | |
|
|
| `box_grouping/` and `evaluation/` have a mutual dependency (not a clean |
| one-way layering) and must stay as sibling directories exactly as laid out |
| here — don't flatten or rename them. |
|
|
| This kit intentionally omits utilities that aren't needed to *run* an |
| evaluation: region-overlay visualization, cross-report comparison tools, an |
| alternate simplified CER tool, and the test suite. All full pipeline logic |
| they'd depend on is present here regardless. |
|
|
| ## 2. Input formats |
|
|
| **Ground truth**: pulled directly from the HF dataset's `annotations` column |
| per row (see §9) — you don't need a local annotation file at all when using |
| `evaluate_from_hf.py`. |
|
|
| **Prediction CSV** (one file per page), columns: |
|
|
| ``` |
| x1,y1,x2,y2,group_row,text |
| ``` |
|
|
| Each row is one predicted word/line box, matched to the dataset by filename |
| stem = `page_id`. `group_row` says which rows belong to the same predicted |
| "row" — see §3, this is where word-level vs line-level evaluation actually |
| diverges. `convert_predictions_to_evaluation_csv.py` builds this CSV from a |
| model's raw per-page JSON (`[{"box":[x1,y1,x2,y2],"text":"..."}]`), giving |
| every item its own unique `group_row` — it does not do any spatial |
| line-grouping itself (that logic now lives in the evaluator, see §3). |
|
|
| ## 3. Word-level vs line-level evaluation (`--unit-level`) |
|
|
| `--unit-level word|line` (default `word`) is accepted by every entry-point |
| script here, including `evaluate_from_hf.py`. It controls one thing only: |
| **how CSV rows are grouped into `PredictedRow` objects** in |
| `box_grouping/loading.py::load_predicted_rows`: |
|
|
| - `--unit-level line`: rows sharing the same `group_row` value are merged |
| into one `PredictedRow` (its GT-box coverage is checked as one atomic |
| unit — see §4). |
| - `--unit-level word` (default): `group_row` is **ignored entirely**; every |
| CSV row becomes its own single-word `PredictedRow`, regardless of what |
| `group_row` says. |
|
|
| Nothing else in the pipeline branches on `--unit-level`. Row-to-box matching |
| and `aggregate_reports` treat it purely as a label recorded in |
| `summary.unit_level` for the report. CER always comes from comparing |
| normalized text (§5), independent of row granularity. |
|
|
| ### What actually changes when you flip the flag |
|
|
| Whether `--unit-level word` vs `line` produces *different numbers* depends |
| entirely on what's already in the CSV: |
|
|
| - **If every CSV row is already one independent word/line** (its own unique |
| `group_row` — true for anything built with |
| `convert_predictions_to_evaluation_csv.py` in this kit): flipping |
| `--unit-level` is a no-op. There is nothing to group either way, since |
| `group_row` never repeats. |
| - **If the CSV has genuine multi-row `group_row` groupings** — several |
| individually-detected word boxes sharing one `group_row` because an |
| upstream layout step assigned them to the same visual line — then the |
| flag matters a great deal: |
| - `line` assembles those words into one row and checks whether *the whole |
| line* fits inside one GT box. |
| - `word` scores each word independently against GT boxes. |
| |
| ### What happens if you pass `--unit-level word` for a line-level model |
| |
| If the model itself only ever produced one box + one text string per line |
| (Surya, Chandra, DeepSeek, Qwen, most VLMs) there is no per-word geometry to |
| recover — `--unit-level word` is safe to pass (it will not error or produce |
| nonsense) but is a no-op: each CSV row already has exactly one "word" (the |
| whole line), so word mode and line mode score identically, only the |
| `summary.unit_level` label differs. You cannot get true word-level accuracy |
| out of a model that never emitted word-level boxes — normalization aside, |
| CER over the same underlying text will be the same regardless of the |
| flag. If your model *does* expose real per-word geometry, keep `group_row` |
| meaningful in the CSV (don't synthesize a unique one per word) and use |
| `--unit-level word` to get true independent-word scoring. |
| |
| ## 4. Row-to-box matching and classification |
| |
| For each `PredictedRow`, coverage against every GT box is computed |
| location-first: a word "belongs" to a box when its center lies inside the |
| box (rotation-aware, via the box's polygon). Row coverage against a box is |
| the fraction of the row's words whose centers fall inside it. |
| |
| Final row status (`box_grouping/group.py`): |
| |
| - **`exactly_one_box`**: one box contains (≥ `--coverage-threshold`, default |
| `1.0`) of the row's words, and no other box touches any word. |
| Also applied when a row touches multiple boxes but one box's `coverage` or |
| `overlap_coverage` is ≥ `0.8` (`MULTI_BOX_SINGLE_COLUMN_LOCATION_THRESHOLD` |
| / `MULTI_BOX_SINGLE_COLUMN_OVERLAP_THRESHOLD`) — this is the "one stray |
| word pulled across a column boundary by OCR" case, not treated as a real |
| multi-box error. |
| - **`multiple_boxes`**: words significantly fall into more than one box and |
| neither dominates per the threshold above. |
| - **`no_box`**: the row doesn't fit cleanly into any box. |
| - **`split_line`**: post-processing reclassifies rows that are fragments of |
| the same GT line detected as separate predicted rows (e.g. OCR split one |
| physical line into two boxes) — they get reassembled before scoring. |
| - **watermark rows**: rows matching a known scanner-watermark phrase |
| ("National Library of Armenia OCR by PortMind" and near-variants, fuzzy |
| matched up to edit distance 2) are dropped from evaluation entirely — |
| they're an artifact of the scanning pipeline, not model output. |
| |
| ## 5. CER calculation |
| |
| Implemented in `evaluation/text_metrics.py::compute_text_metrics`. Both GT |
| and predicted text go through the *same* normalization before comparison, in |
| this order: |
| |
| 1. **Unicode NFC normalization** (`unicodedata.normalize("NFC", ...)`). |
| 2. **Whitespace normalization**: any run of whitespace collapses to a single |
| space (`" ".join(text.split())`). |
| 3. **Punctuation/character canonicalization** (`normalize_punctuation_chars`) |
| — visually similar or OCR-confusable characters are mapped to one |
| canonical form so encoding differences never count as errors: |
| - Soft hyphen `֊`, em dash `—` → `-`; double hyphen `--` → `—` (applied |
| first, before the single-char pass) |
| - Combining acute accent → Armenian emphasis mark `՛` |
| - Armenian comma `՝` → grave accent `` ` `` (canonical form) |
| - One dot leader `․` → full stop `.` |
| - Horizontal ellipsis `…` → `...` |
| - `№` → `N` |
| - Every colon-like character — `։` (Armenian full stop), `:`, `˸`, `︓`, |
| `︰`, `:`, `∶`, `꞉` — all canonicalize to plain `:` |
| - Old Armenian "yev" spelling `եւ` → the ligature `և` |
| |
| ### Character Error Rate |
| |
| ``` |
| cer = char_edit_distance / gt_char_count |
| ``` |
| |
| `char_edit_distance` is Levenshtein distance over the fully-normalized |
| strings (`edit_distance`, classic O(n·m) DP, single-row space-optimized). |
| Special case: if `gt_char_count == 0`, `cer` is `0.0` when the predicted |
| string is also empty, else `1.0` (not division by zero, not undefined). |
| |
| There's a schwa-tolerant variant used for the *default* CER field |
| (`edit_distance_schwa_forgiving`): at hyphen-join points where a line was |
| reassembled by stripping a line-end hyphen (see below), inserting the |
| Armenian schwa **ը** at the join costs `0` instead of `1`. Armenian |
| line-wrapping hyphenation is ambiguous about whether the schwa at a |
| word-break belongs to the transcription or not, so this specific, |
| narrowly-scoped case is not counted as a model error. A `cer_lowercase` / |
| `char_edit_distance_lowercase` variant is also computed (same logic, both |
| strings lowercased first) for case-insensitive comparison. |
| |
| ### Line-break / hyphenation joining |
| |
| When a GT box's transcription or a predicted region spans multiple visual |
| lines, `join_box_lines_with_hyphenation` reassembles them into one string |
| before CER: a line ending in a hyphen-like character (`- ֊ ‐ ‑ ‒ – —`) |
| has that character stripped and is glued directly onto the next line's |
| first word (no space inserted) — this is what produces the hyphen-join |
| positions that get schwa-tolerant treatment above. One special case: |
| `ե` + `-` + `վ...` (a hyphen splitting the letters that make up the և |
| ligature) is rejoined as `և`, not `եվ`. |
| |
| ## 6. Multi-column / multi-region CER |
| |
| A "region" is a connected component of GT boxes, built by |
| `evaluation/reports.py::build_ocr_region_reports`: |
| |
| 1. Any predicted row that spatially touches **two or more** GT boxes creates |
| an adjacency edge between those boxes (evidence they're part of the same |
| flowing text — e.g. a headline continuing into a second column). |
| 2. Connected components of this adjacency graph become one region. An |
| isolated GT box with no such row is still its own one-box region. |
| 3. Within a region, boxes are ordered into reading order via |
| `group_items_left_to_right_top_to_bottom`: column-major — left-to-right |
| for columns, then top-to-bottom within each column. |
| 4. GT text for the region = each box's text (in that order), each box's own |
| internal line breaks de-hyphenated/joined, boxes joined with `\n`. |
| 5. Predicted text for the region = the predicted rows assigned to each box |
| in the region, assembled the same way, in the same reading order. |
| 6. CER for the region = `compute_text_metrics(region_gt_text, region_predicted_text)` |
| over the fully assembled strings — one score per region, not per box. |
|
|
| `normal_single_box_region` is a boolean on each region marking the subset |
| that is a "clean" single-box match: exactly one GT box, at least one |
| assigned row, and every assigned row's status is `exactly_one_box`. This |
| excludes merged multi-box regions, split-line rows, and rows that ended up |
| `multiple_boxes`/`no_box`. It isolates layout/column-detection quality from |
| pure recognition quality — but a `normal_single_box_region` can still have |
| high CER if recognition itself failed inside a correctly-isolated box. |
|
|
| Aggregate corpus CER (`ocr_region_cer`) is computed as |
| `(sum of char edit distances) / (sum of gt char counts)` across all regions |
| — not a simple mean of per-region CERs (that's `ocr_region_mean_cer`, also |
| reported separately). See REPORT_JSON_METRICS.md for every field. |
|
|
| ## 7. What gets excluded from evaluation |
|
|
| ### Text-level normalization (always applied, not optional) |
|
|
| - All punctuation/character canonicalization from §5 (colon variants, dash |
| variants, ellipsis, №, yev spelling) — differences here never count as |
| errors for either model. |
| - Whitespace differences (any amount/kind of whitespace is equivalent). |
| - The specific schwa-at-hyphen-join case described in §5. |
|
|
| ### Region-level filters (opt-in via `--filter`, or `--variant` in `evaluate_from_hf.py`) |
|
|
| Off by default — exclude GT boxes matching these criteria from the primary |
| `ocr_region_*` metrics (excluded boxes' text is removed from region GT text; |
| predicted words whose centers fall inside an excluded box are removed from |
| region predicted text): |
|
|
| | Filter | Excludes | |
| |---|---| |
| | `non-armenian` | GT boxes where **more than 90%** of Unicode-letter characters (category `L*`; digits/punctuation/spaces don't count toward the ratio at all) are Latin or Cyrillic script | |
| | `graphics` | boxes labeled `Graphics` | |
| | `photo` | boxes labeled `Photo` | |
| | `image` | `Photo`, `Graphics`, `SealFigure`, `FrontPicture` | |
| | `header` | `Headline`, `Kicker`, `Banner`, `Deck`, `Subhead`, `Nameplate`, `Masthead`, `FrontStory` | |
| | `image-header` | union of `image` and `header` | |
|
|
| `evaluate_from_hf.py` runs all 4 standard combinations |
| (`no_filter`, `non_armenian`, `graphics_headers_images_photos`, `all_filters`) |
| in one invocation by default; pass `--variant <name>` to run just one. |
|
|
| ### Rows dropped before scoring, unconditionally |
|
|
| - **Watermark rows** — see §4. |
| - Boxes labeled `Rule` are never treated as GT at all (decorative separator |
| lines, not text regions) — `evaluate_from_hf.py`'s adapter drops them the |
| same way the raw-JSON loader does. |
|
|
| ### Not excluded, but tracked separately |
|
|
| - **Empty predicted words inside a non-empty GT box** |
| (`missing_text_boxes`/`missing_text_box_rate`) — a detection/recognition |
| failure signal (OCR found *something* there but produced empty text), kept |
| visible rather than silently dropped. |
|
|
| ## 8. Full CLI reference |
|
|
| `evaluate_from_hf.py` (§9) is the main entry point. The lower-level scripts |
| below are only useful if you already have local ground-truth JSONs in raw |
| Label Studio export format (not the HF dataset's flattened `annotations` |
| column) — most users won't need these. |
|
|
| One page pair, one filter combination: |
|
|
| ```bash |
| python3 evaluation/measure_accuracy.py \ |
| --annotations-json path/to/page.json \ |
| --predictions-csv path/to/page.csv \ |
| --unit-level word \ |
| --filter non-armenian,graphics \ |
| --output page_report.json |
| ``` |
|
|
| All matched CSV/JSON pairs in two local directories, all 4 filter variants: |
|
|
| ```bash |
| python3 evaluation/generate_accuracy_report_variants.py \ |
| --predictions-dir path/to/evaluation_csvs \ |
| --annotations-dir path/to/annotation_jsons \ |
| --unit-level word \ |
| --output-dir results/ |
| ``` |
|
|
| ## 9. Evaluating against RLALT/ACoPPer / RLALT/ACoPDoc |
|
|
| - **`RLALT/ACoPPer`** — printed Armenian newspaper pages, the dataset this |
| evaluation pipeline was built around. |
| - **`RLALT/ACoPDoc`** — diverse-document benchmark. |
|
|
| Both are currently published with a single Hub split named `test`. |
|
|
| ### Loading |
|
|
| ```python |
| from datasets import load_dataset |
| |
| ds = load_dataset("RLALT/ACoPPer") |
| row = ds["test"][0] # column names below |
| ``` |
|
|
| Each row also carries a `split` *column* (e.g. `"pilot"`) from the source |
| manifest — that's separate from, and not necessarily the same as, the Hub's |
| own split key above. If you need a specific subset of rows, filter by that |
| column, e.g. `ds["test"].filter(lambda r: r["split"] == "pilot")` — or use |
| `evaluate_from_hf.py --dataset-split-column pilot`. Always check `ds` after |
| loading to confirm the actual Hub split key in case that changes in a future |
| release. |
|
|
| Each row has: |
|
|
| | Column | Type | Notes | |
| |---|---|---| |
| | `page_id` | string | matches the evaluation CSV filename stem, `<page_id>.csv` | |
| | `source` | string | issue/category the page comes from | |
| | `split` | string | see note above | |
| | `image` | `datasets.Image` | full-page scan, decodes to a PIL image | |
| | `image_width`, `image_height` | int | | |
| | `annotations` | list of dicts | flattened GT — `id`, `label`, `transcription`, `reading_order`, `parent_id`, `bbox` (`[x1,y1,x2,y2]`), `rotation` | |
|
|
| ### Running your model on the images |
|
|
| ```python |
| from datasets import load_dataset |
| |
| ds = load_dataset("RLALT/ACoPPer")["test"] |
| for row in ds: |
| image = row["image"] # PIL.Image, already decoded |
| image.save(f"pages/{row['page_id']}.png") |
| # ... run your model on the saved (or in-memory) image, write |
| # predictions/{row['page_id']}.json as [{"box":[x1,y1,x2,y2],"text":"..."}] |
| ``` |
|
|
| ### Scoring your predictions |
|
|
| ```bash |
| python3 convert_predictions_to_evaluation_csv.py \ |
| --predictions-dir predictions \ |
| --output-dir evaluation_csvs \ |
| --unit-level word |
| |
| python3 evaluate_from_hf.py \ |
| --dataset RLALT/ACoPPer \ |
| --predictions-dir evaluation_csvs \ |
| --output-dir results \ |
| --unit-level word |
| ``` |
|
|
| This prints one line per filter variant (`cer=... (N pages) -> path`) |
| and writes the four standard report JSONs (§6, §7) to `results/`. |
|
|
| `evaluate_from_hf.py` builds `AnnotationBox` objects directly from each row's |
| `annotations` list — the HF schema is already flattened compared to what the |
| local-JSON loader (`load_annotation_boxes`, used by the scripts in §8) |
| parses, so no intermediate JSON file is written. One caveat baked into that |
| adapter: `has_transcription` is normally *"was there a transcription field at |
| all"*, which the flattened HF schema doesn't preserve (only the resulting |
| string) — the adapter approximates it as `bool(text)`, which disagrees only |
| in the rare case of a transcription field that's present but empty. |
|
|
| Either way, PDFs are never part of either published dataset — only page |
| images and their extracted GT. |
|
|