NayanaOCRBench / make_cards.py
AdithyaSK's picture
AdithyaSK HF Staff
NayanaOCRBench explorer: leaderboard, page explorer with diffs, model comparison, language view
141bfc8 verified
Raw History Blame Contribute Delete
11.4 kB
"""Write dataset cards for Cognitive-Lab/NayanaOCRBench_{Natural,Synthetic}: keep the auto-generated dataset_info /
configs YAML, add card metadata (license, languages, tags) and a body with description, leaderboard and links.
python make_cards.py --index <bucket_mirror>/index --cards <dir with <name>/README.md downloads> [--upload]
"""
import argparse, os, re
import polars as pl
from huggingface_hub import HfApi
LANGS = ["en", "hi", "bn", "mr", "gu", "pa", "or", "kn", "ta", "te", "ml", "sa", "zh", "ja", "ko", "de", "fr", "es", "it", "ru", "ar", "th"]
NAME = {"en": "English", "zh": "Chinese", "hi": "Hindi", "bn": "Bengali", "mr": "Marathi", "gu": "Gujarati", "pa": "Punjabi", "or": "Odia", "kn": "Kannada", "ta": "Tamil",
"te": "Telugu", "ml": "Malayalam", "sa": "Sanskrit", "ja": "Japanese", "ko": "Korean", "de": "German", "fr": "French", "es": "Spanish", "it": "Italian", "ru": "Russian",
"ar": "Arabic", "th": "Thai"}
GROUPS = {"Indic": ["hi", "bn", "mr", "gu", "pa", "or", "kn", "ta", "te", "ml", "sa"], "East Asian": ["zh", "ja", "ko"], "European": ["en", "de", "fr", "es", "it", "ru"], "Other": ["ar", "th"]}
SPACE = "https://huggingface.co/spaces/Cognitive-Lab/NayanaOCRBench"
BUCKET = "https://huggingface.co/buckets/Cognitive-Lab/nayanaocrbench-evals"
META = """license: cc-by-nc-4.0
pretty_name: {pretty}
language:
{langs}
task_categories:
- image-to-text
- image-text-to-text
tags:
- ocr
- document-ai
- multilingual
- indic
- benchmark
- nayana
size_categories:
- {size}
"""
CITATION = """```bibtex
@inproceedings{kolavi2025nayanaocr,
title = {Nayana {OCR}: A Scalable Framework for Document {OCR} in Low-Resource Languages},
author = {Kolavi, Adithya S. and Samarth, P. and Jain, Vyoman},
booktitle = {Proceedings of the 1st Workshop on Language Models for Underserved Communities (LM4UC), NAACL},
year = {2025}, pages = {86--103}, url = {https://aclanthology.org/2025.lm4uc-1.11/}
}
@inproceedings{kolavi2025nayana,
title = {Nayana: A Foundation for Document-Centric Vision-Language Models via Multi-Task, Multimodal, and Multilingual Data Synthesis},
author = {Kolavi, Adithya S. and Samarth, P. and Jain, Vyoman},
booktitle = {ICCV Workshops (CV4DC)}, year = {2025}, pages = {1678--1687}
}
```"""
def leaderboard(runs: pl.DataFrame, split: str, exclude=()):
df = runs.filter(pl.col("split") == split)
langs = [l for l in LANGS if l in df["lang"].unique().to_list() and l not in exclude]
wide = df.pivot(on="lang", index="model_short", values="accuracy")
for l in langs:
if l not in wide.columns:
wide = wide.with_columns(pl.lit(None).cast(pl.Float64).alias(l))
wide = wide.with_columns(pl.mean_horizontal([pl.col(l).fill_null(0.0) for l in langs]).alias("avg_all"),
pl.mean_horizontal([pl.col(l) for l in langs]).alias("avg_eval"),
pl.sum_horizontal([pl.col(l).is_not_null().cast(pl.Int32) for l in langs]).alias("n"))
for g, gl in GROUPS.items():
gl = [l for l in gl if l in langs]
wide = wide.with_columns(pl.mean_horizontal([pl.col(l) for l in gl]).alias(g) if gl else pl.lit(None).alias(g))
wide = wide.sort("avg_all", descending=True)
f = lambda v: "—" if v is None else f"{v:.1f}"
grp = ["| Model | Langs | Avg (all, missing = 0) | Avg (evaluated) | " + " | ".join(GROUPS) + " |", "|---|---:|---:|---:|" + "---:|" * len(GROUPS)]
for r in wide.iter_rows(named=True):
grp.append(f"| {r['model_short']} | {r['n']}/{len(langs)} | {f(r['avg_all'])} | {f(r['avg_eval'])} | " + " | ".join(f(r[g]) for g in GROUPS) + " |")
full = ["| Model | " + " | ".join(langs) + " |", "|---|" + "---:|" * len(langs)]
for r in wide.iter_rows(named=True):
full.append(f"| {r['model_short']} | " + " | ".join(f(r[l]) for l in langs) + " |")
return "\n".join(grp), "\n".join(full), langs
def body_natural(runs, gt_counts):
grp, full, langs = leaderboard(runs, "natural")
counts = " · ".join(f"{NAME[l]} {gt_counts.get(l, 0)}" for l in LANGS if l in gt_counts)
return f"""
# NayanaOCRBench · Natural
**Human-verified OCR benchmark on real documents in 22 languages.** {sum(gt_counts.values()):,} pages of scanned, photographed and
born-digital documents (government gazettes, newspapers, forms, books, reports) whose layout and text were machine-proposed and then
corrected by human annotators, in OmniDocBench format.
👁️ **Browse every model output on every page:** [{SPACE}]({SPACE})
## What is in a row
| Column | Type | Meaning |
|---|---|---|
| `image` | Image | the document page |
| `id` | string | page id, e.g. `kn_pdf_0003_page_00226` |
| `omnidocbench` / `omnidocbench_original` / `omnidocbench_norm1000` | struct | OmniDocBench JSON: layout blocks with category, polygon, reading order and text (original pixels and 1000×1000 normalised) |
| `md_norm1000` / `html_norm1000` | string | full-page ground truth in reading order, Markdown and HTML |
| `layout_norm1000` | list | `{{type, bbox}}` per block on a 1000×1000 grid |
| `layout_content_norm1000` | list | `{{type, bbox, content}}` per block |
One config per language: {counts}.
## How it was built
1. Real pages collected per language and de-duplicated.
2. Layout proposed with MinerU, then corrected by annotators (block classes, boxes, reading order).
3. Text extracted per block by frontier VLMs, then reviewed line by line by human annotators.
4. Exported to OmniDocBench format so existing evaluation tooling works unchanged.
## Zero-shot results (character accuracy = 100 − CER)
13 open vision-language and OCR models, one shared prompt, full-page plain-text OCR. Per-page predictions, scores and the evaluation
harness are public in [{BUCKET}]({BUCKET}); the [explorer Space]({SPACE}) shows the page, ground truth and each model's output side by side.
{grp}
<details><summary>Per-language accuracy</summary>
{full}
</details>
Grey / missing cells: the model card does not claim the language, so it was not run. "Avg (all)" counts those as 0, which is what a
user of a general multilingual model experiences; "Avg (evaluated)" averages only the languages that were run.
**Finding.** Latin, Cyrillic and CJK are largely solved. Kannada, Odia, Malayalam and Telugu are not: the strongest general-purpose
family scores above 90% on European scripts and under 20% on those four at every model size. The gap is a data gap, which is what
the [NayanaOCR corpora](https://huggingface.co/datasets/Cognitive-Lab/NayanaOCR_Corpus_2025) exist to close.
## Related
- Companion held-out synthetic set: [Cognitive-Lab/NayanaOCRBench_Synthetic](https://huggingface.co/datasets/Cognitive-Lab/NayanaOCRBench_Synthetic)
- Training corpus (public, 1M pages): [Cognitive-Lab/NayanaOCR_Corpus_2025](https://huggingface.co/datasets/Cognitive-Lab/NayanaOCR_Corpus_2025)
- Retrieval benchmark: [Nayana-IR Bench](https://huggingface.co/collections/Cognitive-Lab/nayanair-bench)
## License and citation
CC BY-NC 4.0. Free for research and education with attribution; commercial use: contact@cognitivelab.in.
{CITATION}
Part of the Nayana initiative by [Cognitive Lab](https://cognitivelab.in), a 2025 Meta Llama Impact Grant recipient.
"""
def body_synthetic(runs, gt_counts):
grp, full, langs = leaderboard(runs, "synthetic", exclude=("en",))
return f"""
# NayanaOCRBench · Synthetic
**Held-out evaluation split of the NayanaOCR 2026 pipeline, 22 languages, ~{sum(gt_counts.values()) // len(gt_counts) if gt_counts else 770} pages per language.**
Every page is the same source document re-typeset in each language with the layout preserved, so the set is parallel across languages
and carries the full annotation stack of the training corpus: layout, reading-order OCR ground truth, translated tables, VQA pairs.
👁️ **Browse every model output on every page:** [{SPACE}]({SPACE})
## What is in a row
Same 14 columns as the page-level NayanaOCR corpus: `image`, `font_used`, `page_size`, `original_id` (shared across all 22 language
configs), `rendered_layout` (per region: type, coordinates, original and translated text, fit ratio), `translated_tables` (HTML),
`vqa_translated`, `omnidocbench` / `omnidocbench_original` / `omnidocbench_norm1000`, `html_norm1000`, `md_norm1000`,
`layout_content_norm1000`, `layout_norm1000`.
## Zero-shot results (character accuracy = 100 − CER)
Same protocol and models as the [Natural benchmark](https://huggingface.co/datasets/Cognitive-Lab/NayanaOCRBench_Natural).
**English is excluded from the tables below** while its ground truth is being revised (text leaked into the `latex` field on some
text blocks); all other languages are unaffected. Predictions and scores: [{BUCKET}]({BUCKET}).
{grp}
<details><summary>Per-language accuracy</summary>
{full}
</details>
Synthetic pages are typeset with a wide rotation of fonts per script and are, on average, harder for current models than the
natural pages; use the two sets together.
## Related
- Human-verified benchmark on real documents: [Cognitive-Lab/NayanaOCRBench_Natural](https://huggingface.co/datasets/Cognitive-Lab/NayanaOCRBench_Natural)
- Training corpus (public, 1M pages): [Cognitive-Lab/NayanaOCR_Corpus_2025](https://huggingface.co/datasets/Cognitive-Lab/NayanaOCR_Corpus_2025)
## License and citation
CC BY-NC 4.0. Free for research and education with attribution; commercial use: contact@cognitivelab.in.
{CITATION}
Part of the Nayana initiative by [Cognitive Lab](https://cognitivelab.in), a 2025 Meta Llama Impact Grant recipient.
"""
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--index", required=True)
ap.add_argument("--cards", required=True)
ap.add_argument("--upload", action="store_true")
a = ap.parse_args()
runs = pl.read_parquet(os.path.join(a.index, "runs.parquet"))
gt = pl.read_parquet(os.path.join(a.index, "gt.parquet"))
counts = {s: dict(gt.filter(pl.col("split") == s).group_by("lang").len().rows()) for s in ("natural", "synthetic")}
api = HfApi()
for name, split, body_fn, size in [("NayanaOCRBench_Natural", "natural", body_natural, "10K<n<100K"), ("NayanaOCRBench_Synthetic", "synthetic", body_synthetic, "10K<n<100K")]:
path = os.path.join(a.cards, name, "README.md")
text = open(path, encoding="utf-8").read()
m = re.match(r"^---\n(.*?)\n---\n?(.*)$", text, re.S)
fm, _old_body = (m.group(1), m.group(2)) if m else ("", text)
# drop any previous copies of the keys we set
fm = re.sub(r"^(license|pretty_name|language|task_categories|tags|size_categories):.*?(?=^\w|\Z)", "", fm, flags=re.S | re.M)
meta = META.format(pretty=name.replace("_", " · "), langs="\n".join(f"- {l}" for l in LANGS), size=size)
new = f"---\n{meta}{fm.strip()}\n---\n{body_fn(runs, counts[split])}"
out = os.path.join(a.cards, f"{name}_README_new.md")
open(out, "w", encoding="utf-8").write(new)
print(f"{name}: {len(new):,} chars -> {out}")
if a.upload:
api.upload_file(path_or_fileobj=out, path_in_repo="README.md", repo_id=f"Cognitive-Lab/{name}", repo_type="dataset",
commit_message="Add dataset card: description, zero-shot leaderboard, explorer Space link")
print(" uploaded")
if __name__ == "__main__":
main()