#!/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 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()