SMedDV / tools /write_docs.py
hahouari's picture
Add SMedDV v5 package file: tools/write_docs.py
7682125 verified
Raw History Blame Contribute Delete
30.6 kB
#!/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()