Datasets:
File size: 30,555 Bytes
7682125 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 | #!/usr/bin/env python3
"""Generate release documentation from measured v5 metadata and source manifests."""
from __future__ import annotations
import argparse
import csv
import csv
import hashlib
import json
from pathlib import Path
import re
from typing import Any
import yaml
LANGUAGE_NAMES = {
"af": "Afrikaans",
"ar": "Arabic",
"az": "Azerbaijani",
"bs": "Bosnian",
"ca": "Catalan",
"ckb": "Central Kurdish (Sorani)",
"cs": "Czech",
"cy": "Welsh",
"da": "Danish",
"de": "German",
"en": "English",
"es": "Spanish",
"et": "Estonian",
"eu": "Basque",
"fa": "Persian",
"fi": "Finnish",
"fil": "Filipino",
"fr": "French",
"ga": "Irish",
"gl": "Galician",
"he": "Hebrew",
"hr": "Croatian",
"hu": "Hungarian",
"id": "Indonesian",
"is": "Icelandic",
"it": "Italian",
"ku": "Kurdish (Kurmanji)",
"la": "Latin",
"lb": "Luxembourgish",
"lt": "Lithuanian",
"lv": "Latvian",
"mi": "Māori",
"mrz": "Machine-readable zone (not a language)",
"ms": "Malay",
"mt": "Maltese",
"nl": "Dutch",
"no": "Norwegian",
"oc": "Occitan",
"pl": "Polish",
"ps": "Pashto",
"pt": "Portuguese",
"qu": "Quechua",
"rm": "Romansh",
"ro": "Romanian",
"sk": "Slovak",
"sl": "Slovenian",
"sq": "Albanian",
"sr-Latn": "Serbian (Latin script)",
"sv": "Swedish",
"sw": "Swahili",
"tr": "Turkish",
"ur": "Urdu",
"uz": "Uzbek",
"vi": "Vietnamese",
}
def read_json(path: Path) -> dict[str, Any]:
return json.loads(path.read_text(encoding="utf-8"))
def sha256(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for block in iter(lambda: f.read(1024 * 1024), b""):
h.update(block)
return h.hexdigest()
def percent(n: int, total: int) -> str:
return f"{100*n/total:.2f}%"
def font_rows(root: Path) -> tuple[list[dict[str, Any]], list[str]]:
fonts: dict[str, list[dict[str, Any]]] = {}
problems: list[str] = []
for config in (root / "synth/fonts.yaml", root / "synth/fonts_v5.yaml"):
data = yaml.safe_load(config.read_text(encoding="utf-8"))
for entry in data["fonts"]:
fonts.setdefault(entry["name"], []).append(entry)
rows = []
for family, entries in sorted(fonts.items()):
licenses = sorted({str(e.get("license", "UNVERIFIED")) for e in entries})
sources = sorted({str(e.get("source", "UNVERIFIED")) for e in entries})
files = []
license_files = []
for entry in entries:
path = root / entry["path"]
if not path.is_file():
problems.append(f"missing font binary: {entry['path']}")
elif entry.get("sha256") and sha256(path) != entry["sha256"]:
problems.append(f"font binary SHA-256 mismatch: {entry['path']}")
files.append(Path(entry["path"]).name)
license = str(entry.get("license", ""))
if "Bitstream Vera" in license:
license_files.append("LICENSES/Bitstream-Vera.txt")
elif "RFN" in license:
license_files.append("LICENSES/Liberation-OFL-1.1-RFN.txt")
else:
source = str(entry.get("source", ""))
slug = source.rstrip("/").split("/")[-1].lower()
matches = [
p.name for p in (root / "release/v5_hf/LICENSES/fonts").glob("*-OFL.txt")
if p.stem.lower().removesuffix("-ofl") == slug
]
if not matches and family == "OCR-B":
matches = ["OCR-B-OFL.txt"]
if not matches:
problems.append(f"no OFL text mapped for font family: {family} ({slug})")
else:
license_files.extend(f"LICENSES/fonts/{name}" for name in matches)
rows.append(
{
"family": family,
"licenses": licenses,
"sources": sources,
"files": sorted(set(files)),
"license_files": sorted(set(license_files)),
}
)
return rows, problems
def make_readme(root: Path, inv: dict[str, Any], extra: dict[str, Any], stats: dict[str, Any]) -> str:
languages = sorted(set(inv["languages"]) - {"mrz"})
# Hugging Face language metadata accepts lowercase 2- or 3-character tags;
# the dataset's internal CLDR code sr-Latn is represented by the broader sr tag.
hf_languages = sorted({"sr" if code == "sr-Latn" else code for code in languages})
# Quote every tag so YAML 1.1 parsers do not coerce the valid code `no` to
# boolean false.
lang_yaml = "\n".join(f" - \"{code}\"" for code in hf_languages)
language_lines = []
for code in sorted(inv["languages"]):
tr = inv["split_languages"]["train"].get(code, 0)
va = inv["split_languages"]["val"].get(code, 0)
name = LANGUAGE_NAMES.get(code, "UNVERIFIED")
language_lines.append(f"| `{code}` | {name} | {tr:,} | {va:,} | {tr+va:,} |")
category_lines = []
for category, total in sorted(inv["categories"].items(), key=lambda x: (-x[1], x[0])):
tr = inv["split_categories"]["train"].get(category, 0)
va = inv["split_categories"]["val"].get(category, 0)
category_lines.append(f"| {category} | {tr:,} | {va:,} | {total:,} | {percent(total, inv['rows'])} |")
length_lines = []
for key, count in inv["text_length_bins"].items():
length_lines.append(f"| {key} | {count:,} | {percent(count, inv['rows'])} |")
bg = stats["counts"]
bg_groups = {
"Flat": bg.get("background:flat", 0),
"Gradients": sum(v for k, v in bg.items() if k.startswith("background:gradient:")),
"Procedural guilloche": bg.get("background:guilloche", 0),
"Noise": bg.get("background:noise", 0),
"CC0 security patterns": sum(v for k, v in bg.items() if k in {"background:cc0_security", "background:cc0_guilloche", "background:cc0_rosette"}),
"ambientCG material textures": sum(v for k, v in bg.items() if k.startswith("background:material:")),
}
bg_lines = [f"| {name} | {count:,} | {percent(count, inv['rows'])} |" for name, count in bg_groups.items()]
tiers = extra["degradation_tiers"]
tier_lines = [
f"| {tier} | {v['rows']:,} | {percent(v['rows'], inv['rows'])} |"
for tier, v in tiers.items() if tier in {"clean", "light", "medium", "heavy"}
]
overlap = inv["validation_text_reuse"]
val_pct = percent(overlap["validation_rows_matching_train"], inv["validation_rows"])
roundtrip = read_json(root / "data/synth/v5/stats/export_qa.json")["roundtrip"]
build_manifest_path = root / "release/v5_hf/data/build_manifest.json"
build = read_json(build_manifest_path) if build_manifest_path.is_file() else None
shard_summary = (
f"{len(build['shards'])} shards ({sum(s['path'].startswith('train/') for s in build['shards'])} train, "
f"{sum(s['path'].startswith('validation/') for s in build['shards'])} validation; "
f"largest {max(s['size_bytes'] for s in build['shards']):,} bytes)"
if build else "Parquet shards; see build manifest"
)
return f'''---
license: cc-by-sa-4.0
task_categories:
- image-to-text
language:
{lang_yaml}
tags:
- OCR
- synthetic-data
- multilingual
- Arabic
- Hebrew
- right-to-left
size_categories:
- 1M<n<10M
configs:
- config_name: default
data_files:
- split: train
path: data/train/*.parquet
- split: validation
path: data/validation/*.parquet
---
# SMedDV: Synthetic Mediterranean Document Validation (v5)
SMedDV v5 is a synthetic, multilingual **text-line OCR** dataset: each row contains a rendered WebP line and its transcription. It contains no photographs of people, real identity documents, or real personal identifiers.
## At a glance
| Measure | Value |
|---|---:|
| Rows | {inv['rows']:,} |
| Train / validation | {inv['train_rows']:,} / {inv['validation_rows']:,} ({inv['manifest_exact_fraction']*100:.2f}% validation) |
| Languages | {inv['language_count_excluding_mrz']} language IDs, plus MRZ |
| Image | WebP, q85, method 6; 48 px high; proportional width |
| Parquet | {shard_summary} |
| Width | {inv['dimensions_from_labels']['width_min']}–{inv['dimensions_from_labels']['width_max']} px; mean {inv['dimensions_from_labels']['width_mean']:.2f} px |
| Encoded image bytes | {inv['image_inventory']['encoded_bytes_from_stat']:,} ({inv['image_inventory']['encoded_bytes_from_stat']/1e9:.2f} GB) |
| Character dictionary | {inv['dictionary_chars']} characters; space is represented separately |
| Maximum label length | {inv['max_text_length']} Unicode code points |
| Font families | {extra['font_families']['family_count']} |
| Degradation | clean/light/medium/heavy tiers; see table below |
The validation membership is fixed by [`splits/validation_indices.json`](splits/validation_indices.json) and reproduced exactly in the Parquet split. The manifest contains {inv['manifest_rows']:,} validation indices.
## Data fields and reading order
Each Parquet row has `image`, `text`, `text_visual`, `index`, `lang`, `script`, `category`, `font`, `font_style`, `font_weight`, `width`, `height`, `background_mode`, `degradation_tier`, `seed`, `aug`, `long_text`, `hard_negative`, `line_idx`, `mrz_format`, `coverage_char`, `coverage_mode`, and `base_dir`.
- `text` is the canonical **logical Unicode order** transcription.
- `text_visual` is the left-to-right **visual order** string used by the Paddle recognition lists. For RTL samples, do not silently substitute one representation for the other. Consumers training a recognizer should select the label order expected by that model and document the choice.
- `image` stores the original WebP bytes; images are not re-encoded during packaging.
- The preserved lists under [`paddle/`](paddle/README.md) retain visual-order labels, but their original image paths refer to the source loose-image layout. Use `tools/export_paddle.py` to materialize a Paddle-ready tree from Parquet.
## Composition
### Rows by category
| Category | Train | Validation | Total | Share |
|---|---:|---:|---:|---:|
{chr(10).join(category_lines)}
### Rows by language and split
MRZ is listed as its own code, not as a natural language.
| Code | Language | Train | Validation | Total |
|---|---|---:|---:|---:|
{chr(10).join(language_lines)}
### Logical label length
Lengths count Unicode code points in `text`, including spaces.
| Length | Rows | Share |
|---|---:|---:|
{chr(10).join(length_lines)}
There are {extra['row_flags'].get('long_text', 0):,} `long_text` rows ({percent(extra['row_flags'].get('long_text',0), inv['rows'])}) and {extra['row_flags'].get('hard_negative',0):,} `hard_negative` rows ({percent(extra['row_flags'].get('hard_negative',0), inv['rows'])}). See [`docs/statistics.md`](docs/statistics.md) and [`docs/character-frequency.csv`](docs/character-frequency.csv) for more breakdowns.
### Backgrounds and degradation
| Background group | Rows | Share |
|---|---:|---:|
{chr(10).join(bg_lines)}
| Degradation tier | Rows | Share |
|---|---:|---:|
{chr(10).join(tier_lines)}
The additional `contrast_clamped` flag is present on {extra['row_flags'].get('degradation_clamped',0)} rows; it is not a fifth degradation tier.
### Character coverage
The dictionary has {inv['dictionary_chars']} characters. The least frequent character appears {inv['minimum_character_occurrences_all']} times overall, at least {inv['minimum_character_occurrences_train']} times in training and {inv['minimum_character_occurrences_val']} times in validation. Full per-character totals are in [`docs/character-frequency.csv`](docs/character-frequency.csv).
## Intended use
- Develop and compare text-line OCR recognizers across scripts, languages, categories, fonts, and rendering conditions.
- Regression-test RTL reading order, digit recognition, dictionaries, and OCR data pipelines.
- Analyze synthetic rendering and degradation sensitivity; teach or demonstrate line-recognition workflows.
This is **not** a real-document benchmark, an ID-card detector dataset, or evidence of performance on photographs or real identity documents. Validation comes from the same synthetic generation family and is not an independent real-world test set.
## Limitations and known issues
- The validation text is not unique to the validation split: {overlap['validation_rows_matching_train']:,} of {inv['validation_rows']:,} validation rows ({val_pct}) have a logical label string that also occurs in training. This is expected rendering-level reuse; no source index is shared across splits. The distinct-string overlap is {overlap['unique_validation_strings_matching_train']:,} of {overlap['unique_validation_strings']:,} ({percent(overlap['unique_validation_strings_matching_train'], overlap['unique_validation_strings'])}). Do not treat the split as text-disjoint.
- A stored 10,000-sample RTL round-trip QA had {roundtrip['exact']:,} exact results ({roundtrip['checked']-roundtrip['exact']} mismatches, {100*(1-roundtrip['exact_rate']):.2f}%). The mismatches were Arabic generic lines with digit ranges or punctuation, where round-tripping can reverse a number span; inspect `docs/VALIDATION.md` before using it as a strict RTL evaluation set.
- Synthetic text sources and rendering choices create source, language, vocabulary, font, and style biases. Category and language proportions are not population estimates for real identity documents.
- Some identifier-like strings are format-generated synthetic values; they are not guaranteed to pass a government issuer's unpublished check-digit rules.
## Licence and citation
The release is licensed **CC BY-SA 4.0**. Commercial use is allowed. Share-alike applies when redistributing an adaptation; see [`LICENSE`](LICENSE), [`LICENSES/`](LICENSES/), and [`ATTRIBUTION.md`](ATTRIBUTION.md).
| Use | Summary |
|---|---|
| Commercial use | Allowed |
| Train privately | Allowed; citation is welcome, not required for private use |
| Redistribute all or part | Credit the dataset and preserve applicable licence notices; adaptations of CC BY-SA material must use CC BY-SA or a permitted later version |
Citation is welcome, not a condition of private use. `CITATION.cff` is included. BibTeX:
```bibtex
@dataset{{SMedDV_v5,
author = {{SMedDV dataset team}},
title = {{SMedDV: Synthetic Mediterranean Document Validation}},
version = {{v5}},
year = {{2026}},
url = {{https://huggingface.co/datasets/hahouari/SMedDV}}
}}
```
## Reproducibility and files
The package contains `data/train/` and `data/validation/` Parquet shards, source-layout `paddle/` lists plus the Parquet-to-Paddle materializer, the exact `splits/validation_indices.json` manifest, `metadata/` coverage plans and skip records, licence notices, and documentation.
See [`docs/generation-recipe.md`](docs/generation-recipe.md), [`docs/statistics.md`](docs/statistics.md), [`docs/VALIDATION.md`](docs/VALIDATION.md), and [`docs/reproducibility.json`](docs/reproducibility.json). Per-shard checksums and the whole-package checksum are listed in `checksums/`.
'''
def make_attribution(root: Path, inv: dict[str, Any], extra: dict[str, Any]) -> str:
fonts, problems = font_rows(root)
if problems:
raise ValueError("font source verification failed:\n" + "\n".join(problems))
font_lines = []
for row in fonts:
license_text = ", ".join(f"[`{p.split('/')[-1]}`]({p})" for p in row["license_files"])
font_lines.append(
f"| {row['family']} | {', '.join(row['licenses'])} | "
f"{', '.join(row['sources'])} | {license_text} | {', '.join(row['files'])} |"
)
manifest = read_json(root / "synth/sources/ambientcg/manifest.json")
texture_lines = []
for asset in manifest["assets"]:
texture_lines.append(
f"| {asset['asset']} | [ambientCG]({asset['source']}) | CC0 1.0 Universal | "
f"{asset['archive_bytes']:,} | `{asset['archive_sha256']}` |"
)
bg_script = (root / "synth/fetch_background_assets.py").read_text(encoding="utf-8")
patterns = re.findall(r'"filename": "([^"]+)".*?"url": "([^"]+)".*?"sha256": "([0-9a-f]{64})"', bg_script, re.S)
pattern_lines = [f"| `{name}` | {url} | CC0 1.0 / public domain as recorded in source manifest | `{digest}` |" for name,url,digest in patterns]
repro = inv["source_file_sha256"]
repro_line = f"Source manifest SHA-256: `{repro.get('validation_indices.json','UNVERIFIED')}` for `validation_indices.json`."
return f'''# Attribution and upstream licences
SMedDV v5 is synthetic. Its text values and rendering inputs have the following upstream provenance. Licence texts and source notices are provided under [`LICENSES/`](LICENSES/). Source-level attribution is used where the generation pipeline did not retain finer provenance; see the Wikipedia note below.
## Text and character sources
| Source | Contribution | Licence / credit |
|---|---|---|
| Wikimedia Wikipedia, Hugging Face dataset `wikimedia/wikipedia`, `20231101` | Normalized, filtered 1–6-word spans; selected per-language source shards are recorded in `synth/wikipedia_shards.yaml` | CC BY-SA 3.0 and GFDL are listed by the upstream dataset. This release relies on the CC BY-SA 3.0 option and uses CC BY-SA 4.0 for the release adaptation. Credit: Wikimedia Wikipedia contributors; [source dataset](https://huggingface.co/datasets/wikimedia/wikipedia); see `LICENSES/CC-BY-SA-3.0.txt` and `LICENSES/CC-BY-SA-4.0.txt`. |
| GeoNames Gazetteer | Global/local place names, administrative names, roads, and alternate names | CC BY 4.0; credit GeoNames and link [GeoNames](https://www.geonames.org/) and the [licence](https://creativecommons.org/licenses/by/4.0/); see `LICENSES/CC-BY-4.0.txt`. |
| Wikidata Query Service | Given/family-name labels and selected country-linked name labels only | CC0; [Wikidata](https://www.wikidata.org/); see `LICENSES/CC0-1.0.txt`. |
| `wadiemendja/algeria-communes-wilayas` | Algerian commune names and administrative places | MIT; copyright wadiemendja (2026); see `LICENSES/MIT-communes.txt`. |
| Unicode CLDR 48.2.3 | Language exemplars and character sets, not label sentences | Unicode License V3; see `LICENSES/Unicode-3.0.txt`. |
| Project-curated document terms and format tokens | Short identity-document headings and synthetic format symbols | Project-curated; no external text corpus claimed. |
### Wikipedia provenance limitation
The source extractor reads the `text` column and the generator stores the sampled strings, not the source article title, URL, or author list. This package therefore gives concise dataset/shard-level credit instead of an article list. The raw Parquet source schema has `id`, `url`, and `title`, so article provenance may be reconstructable, but it was not retained in the generated labels. The sufficiency of this aggregate attribution under CC BY-SA 3.0 is **UNVERIFIED**; this is a provenance limitation, not a claim that attribution is unnecessary.
## Fonts
Each family below contributed glyph renderings. Font binaries are not included in the dataset release; the output contains raster images. Font checksums and licence files are retained in the table and `LICENSES/fonts/`.
**Font notice discrepancy:** the downloaded Google Fonts OFL notice for Noto Sans Hebrew says Copyright 2022, while the used font binary's embedded name table says Copyright 2024. Both identify The Noto Project Authors and the font is marked SIL OFL 1.1; the exact matching upstream notice version is **UNVERIFIED**. The upstream OFL file is preserved verbatim.
| Family | Licence | Upstream | Verbatim licence notice | Font files used |
|---|---|---|---|---|
{chr(10).join(font_lines)}
## Background assets
### ambientCG materials
Color/diffuse maps were used as low-opacity synthetic background textures. The exact archive hashes below come from `synth/sources/ambientcg/manifest.json`.
| Asset | Source | Licence | Archive bytes | Archive SHA-256 |
|---|---|---|---:|---|
{chr(10).join(texture_lines)}
### Security-pattern overlays
These pattern-only assets were used as faint procedural background motifs, not as identity documents.
| Asset | Source | Licence | SHA-256 |
|---|---|---|---|
{chr(10).join(pattern_lines)}
## Code, models, and algorithms
No upstream model generated any text, labels, or images. The dataset was generated by this project's code. The MRZ formatting/check-digit structure follows ICAO Doc 9303 (references are listed in `synth/SOURCES.md`); other identifier formats and verification limits are documented in the generation recipe. Runtime libraries used for rendering are dependencies of the project and are not bundled as executable code in this dataset.
## Dataset release licence
The SMedDV release contribution/compilation is licensed under CC BY-SA 4.0; upstream components retain their own licences and attribution notices above. The root `LICENSE` and `LICENSES/CC-BY-SA-4.0.txt` contain the release licence text. This notice is not legal advice.
'''
def write_statistics(release: Path, inv: dict[str, Any], extra: dict[str, Any], stats: dict[str, Any]) -> None:
total = inv["rows"]
lang_rows = ["| Code | Language | Train | Validation | Total | Share |"]
lang_rows.append("|---|---|---:|---:|---:|---:|")
for code in sorted(inv["languages"]):
tr = inv["split_languages"]["train"].get(code, 0)
va = inv["split_languages"]["val"].get(code, 0)
lang_rows.append(f"| `{code}` | {LANGUAGE_NAMES.get(code, 'UNVERIFIED')} | {tr:,} | {va:,} | {tr+va:,} | {percent(tr+va,total)} |")
category_rows = ["| Category | Train | Validation | Total | Share |", "|---|---:|---:|---:|---:|"]
for name, count in sorted(inv["categories"].items(), key=lambda x: (-x[1], x[0])):
tr=inv["split_categories"]["train"].get(name,0); va=inv["split_categories"]["val"].get(name,0)
category_rows.append(f"| {name} | {tr:,} | {va:,} | {count:,} | {percent(count,total)} |")
length_rows = ["| Length | Rows | Share |", "|---|---:|---:|"]
for name,count in inv["text_length_bins"].items():
length_rows.append(f"| {name} | {count:,} | {percent(count,total)} |")
tier_rows=[]
for name,data in extra["degradation_tiers"].items():
if name in {"clean","light","medium","heavy"}:
tier_rows.append(f"| {name} | {data['rows']:,} | {percent(data['rows'],total)} |")
bg=stats["counts"]
bg_groups={
"flat":bg.get("background:flat",0),
"gradient variants":sum(v for k,v in bg.items() if k.startswith("background:gradient:")),
"procedural guilloche":bg.get("background:guilloche",0),
"noise":bg.get("background:noise",0),
"CC0 pattern overlays":sum(v for k,v in bg.items() if k in {"background:cc0_security","background:cc0_guilloche","background:cc0_rosette"}),
"ambientCG material textures":sum(v for k,v in bg.items() if k.startswith("background:material:")),
}
bg_rows=[f"| {name} | {count:,} | {percent(count,total)} |" for name,count in bg_groups.items()]
font_rows=["| Family | Rows | Share |","|---|---:|---:|"]
for family,count in sorted(extra["font_families"]["family_rows"].items(),key=lambda x:(-x[1],x[0])):
font_rows.append(f"| {family} | {count:,} | {percent(count,total)} |")
overlap=inv["validation_text_reuse"]
md=f'''# v5 statistics
Counts are measured from `data/synth/v5/labels.jsonl` and cross-checked against the fixed validation manifest. Rows in the category and language tables sum to {total:,}.
## Language IDs and split
There are {inv['language_count_excluding_mrz']} language IDs plus MRZ (`mrz`). The HF `language:` metadata uses the valid `sr` tag for the dataset's internal Latin-script Serbian code `sr-Latn`; the row table retains `sr-Latn`.
{chr(10).join(lang_rows)}
## Sample categories
{chr(10).join(category_rows)}
## Logical text lengths
Unicode code points in `text`, spaces included.
{chr(10).join(length_rows)}
`long_text`: {extra['row_flags'].get('long_text',0):,} rows ({percent(extra['row_flags'].get('long_text',0),total)}). `hard_negative`: {extra['row_flags'].get('hard_negative',0):,} rows ({percent(extra['row_flags'].get('hard_negative',0),total)}).
## Background groups
{chr(10).join(["| Group | Rows | Share |", "|---|---:|---:|"]+bg_rows)}
## Font families
{chr(10).join(font_rows)}
## Degradation tiers
| Tier | Rows | Share |
|---|---:|---:|
{chr(10).join(tier_rows)}
The separate `contrast_clamped` flag occurs on {extra['row_flags'].get('degradation_clamped',0)} rows; it is not a fifth tier.
## Character coverage and split reuse
- Dictionary characters: {inv['dictionary_chars']} (spaces omitted from `dict.txt`).
- Least frequent code point: {inv['minimum_character_occurrences_all']} total; {inv['minimum_character_occurrences_train']} train; {inv['minimum_character_occurrences_val']} validation.
- Every one of the {inv['dictionary_chars']} non-space dictionary characters is present in the labels.
- Character totals are in [`character-frequency.csv`](character-frequency.csv).
- {overlap['validation_rows_matching_train']:,}/{inv['validation_rows']:,} validation rows ({percent(overlap['validation_rows_matching_train'],inv['validation_rows'])}) have text found in training. Unique strings: {overlap['unique_validation_strings_matching_train']:,}/{overlap['unique_validation_strings']:,} ({percent(overlap['unique_validation_strings_matching_train'],overlap['unique_validation_strings'])}). This is expected; the split is not text-disjoint.
'''
(release/"docs/statistics.md").write_text(md,encoding="utf-8")
with (release/"docs/character-frequency.csv").open("w",encoding="utf-8",newline="") as f:
writer=csv.writer(f)
writer.writerow(["character","codepoint","count_total"])
for char,count in sorted(inv["character_frequency"].items(),key=lambda x:ord(x[0])):
writer.writerow([char,f"U+{ord(char):04X}",count])
def write_reproducibility(release: Path, root: Path, inv: dict[str, Any], source_code_hashes: Path) -> None:
source_code_text = source_code_hashes.read_text(encoding="utf-8")
(release / "docs/source-code.sha256").write_text(source_code_text, encoding="utf-8")
run_a = root / "runs/v5_20261026_01"
run_b = root / "runs/v5_20261027_800coverage"
commands = {
"initial_generation": (run_a / "generation_command.txt").read_text().strip(),
"coverage_supplement_plan": (run_b / "supplement_plan_command.txt").read_text().strip(),
"coverage_supplement_generation": (run_b / "supplement_generation_command.txt").read_text().strip(),
"validation_manifest": (run_b / "validation_plan_command.txt").read_text().strip(),
"final_source_export": (run_b / "export_command.txt").read_text().strip(),
"parquet_packaging": "PYTHONHASHSEED=0 .venv/bin/python release/v5_hf/tools/build_parquet.py --source data/synth/v5 --out release/v5_hf/data --target-bytes 650000000 --row-group-size 2048",
}
build_manifest_path = release / "data/build_manifest.json"
build_manifest = read_json(build_manifest_path) if build_manifest_path.exists() else None
license_paths = [release / "LICENSE", *sorted((release / "LICENSES").rglob("*"))]
license_hashes = {
p.relative_to(release).as_posix(): sha256(p)
for p in license_paths if p.is_file()
}
release_tools = {
p.relative_to(release).as_posix(): sha256(p)
for p in sorted((release / "tools").glob("*.py"))
if p.is_file()
}
result = {
"dataset": "SMedDV",
"version": "v5",
"source_dataset_path": "data/synth/v5",
"generation": {
"base_commit_at_generation": "879b491",
"relevant_uncommitted_code_committed_as": "9e0e8d99f23c89203166a33751cd03a67a403e14",
"global_seed": 0,
"workers": 12,
"chunk_rows": 10000,
"requested_indices_final": 3528113,
"rendered_rows": 3527958,
"explicit_missing_source_rows": 155,
"image_format": "WebP",
"quality": 85,
"method": 6,
"height_px": 48,
"max_text_length": 64,
},
"source_file_sha256": inv["source_file_sha256"],
"source_image_path_size_inventory_sha256": inv["image_inventory"]["path_size_inventory_sha256"],
"source_image_content_tree_sha256": build_manifest["source_image_tree_sha256"] if build_manifest else None,
"source_image_bytes_read": build_manifest["source_image_bytes"] if build_manifest else None,
"source_code_sha256_file": "docs/source-code.sha256",
"release_tool_sha256": release_tools,
"license_file_sha256": license_hashes,
"generation_and_packaging_commands": commands,
"package_build": {
"format": "Parquet",
"target_source_image_bytes_per_shard": 650000000,
"row_group_size": 2048,
"parallelism": 1,
"build_manifest": "data/build_manifest.json",
},
}
(release / "docs/reproducibility.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path("."))
parser.add_argument("--inventory", type=Path, required=True)
parser.add_argument("--font-counts", type=Path, required=True)
parser.add_argument("--source-code-hashes", type=Path, required=True)
args = parser.parse_args()
root = args.root.resolve()
release = root / "release/v5_hf"
inv = read_json(args.inventory)
extra = read_json(args.font_counts)
stats = read_json(root / "data/synth/v5/stats.json")
export_qa = read_json(root / "data/synth/v5/stats/export_qa.json")
release.joinpath("README.md").write_text(make_readme(root, inv, extra, stats), encoding="utf-8")
release.joinpath("ATTRIBUTION.md").write_text(make_attribution(root, inv, extra), encoding="utf-8")
write_statistics(release, inv, extra, stats)
write_reproducibility(release, root, inv, args.source_code_hashes)
print(json.dumps({"readme": "written", "attribution": "written", "export_qa_roundtrip": export_qa["roundtrip"]}, ensure_ascii=False))
if __name__ == "__main__":
main()
|