"""Render the Hugging Face dataset card from card_template.md and the build summary.""" from __future__ import annotations import argparse import json from string import Template import pandas as pd from isora_hf import config TEMPLATE = config.PROJECT_ROOT / "card_template.md" OUTPUT = config.OUT_DIR / "README.md" SUMMARY = config.OUT_DIR / "metadata" / "build_summary.json" def fmt(n: float) -> str: return f"{int(n):,}" def generation_table(summary: dict) -> str: rows = [ "| Questionnaire generation | Source dataflow | Fiscal years | Rows | Jurisdictions | Indicator codes |", "|---|---|---|---|---|---|", ] for flow in summary["dataflows_used"]: g = summary["observations"]["by_generation"][flow["generation"]] years = f"FY{g['fiscal_years'][0]}–FY{g['fiscal_years'][-1]}" rows.append( f"| {flow['generation']} | `{flow['id']}` v{flow['version']} | {years} | {fmt(g['rows'])} | {g['jurisdictions']} | {fmt(g['indicators'])} |" ) return "\n".join(rows) def fiscal_year_table(summary: dict) -> str: rows = [ "| Fiscal year | Collected in | Jurisdictions | Indicator codes | Rows |", "|---|---|---|---|---|", ] for year, r in summary["observations"]["by_fiscal_year"].items(): rnd = config.FISCAL_YEAR_TO_ROUND[int(year)] rows.append( f"| {year} | {rnd} | {r['jurisdictions']} | {r['indicators']} | {fmt(r['rows'])} |" ) return "\n".join(rows) def status_table(summary: dict) -> str: counts = summary["observations"]["value_status"] total = sum(counts.values()) meaning = { "value": "a numeric or text answer is present", "not_available": "the administration answered `D` (data not available) to a numeric question", "not_applicable": "the administration answered *Not Applicable*", "empty": "the cell was published empty", "unrecognized_code": "the published value is the undocumented code `P` (ISORA 2016 only)", } rows = ["| `value_status` | Rows | Share | Meaning |", "|---|---|---|---|"] for k in ("value", "not_available", "not_applicable", "empty", "unrecognized_code"): n = counts.get(k, 0) rows.append(f"| `{k}` | {fmt(n)} | {100 * n / total:.1f}% | {meaning[k]} |") return "\n".join(rows) def dataflow_versions_table(summary: dict) -> str: rows = [ "| Dataflow | Version | Data structure | Last updated at source | Used here |", "|---|---|---|---|---|", ] used = {(f["id"], f["version"]) for f in summary["dataflows_used"]} vint = {("ISORA_LATEST_DATA_PUB", v) for v, _, _ in config.VINTAGES} for d in sorted( summary["dataflow_versions_at_source"], key=lambda x: (x["dataflow_id"], x["version"]) ): key = (d["dataflow_id"], d["version"]) use = "observations" if key in used else ("revisions" if key in vint else "no") rows.append( f"| `{d['dataflow_id']}` | {d['version']} | `{d['data_structure']}` | {d['last_updated_at_source'] or '—'} | {use} |" ) return "\n".join(rows) def kind_table(summary: dict) -> str: counts = summary["observations"]["indicator_value_kind"] meaning = { "numeric": "every published answer is a number", "binary": "answers are Yes / No", "categorical": "answers come from a closed list (≤ 25 distinct values)", "free_text": "more than 25 distinct text answers", "mixed": "numbers and text both occur (usually a category plus a numeric ‘other’)", "no_values": "only `D`, empty or not-applicable cells were published", } rows = ["| `indicator_value_kind` | Rows | What it means |", "|---|---|---|"] for k, n in sorted(counts.items(), key=lambda kv: -kv[1]): rows.append(f"| `{k}` | {fmt(n)} | {meaning.get(k, '')} |") return "\n".join(rows) def panel_table() -> str: """Markdown table of the consolidated panel columns, from panel_dictionary.parquet.""" d = pd.read_parquet(config.OUT_DIR / "data" / "panel_dictionary.parquet") rows = [ "| Column | Unit | Description | Source code by generation (2016 / 2018 / 2020+) | Non-null rows |", "|---|---|---|---|---|", ] for col, grp in d.groupby("column", sort=False): codes = {g: c for g, c in zip(grp["questionnaire_generation"], grp["indicator_code"])} src = " / ".join( f"`{codes[g]}`" if g in codes else "—" for g in ("ISORA 2016", "ISORA 2018", "ISORA 2020+") ) first = grp.iloc[0] rows.append( f"| `{col}` | {first['unit']} | {first['description']} | {src} | {fmt(first['n_non_null_in_panel'])} |" ) return "\n".join(rows) def build_context(summary: dict, repo_id: str) -> dict[str, str]: obs, hist, rev = summary["observations"], summary["indicator_history"], summary["revisions"] ct = rev["change_types"] return { "repo_id": repo_id, "retrieved_at": summary["retrieved_at_utc"], "retrieved_date": summary["retrieved_at_utc"][:10], "obs_rows": fmt(obs["rows"]), "n_jur": str(obs["jurisdictions"]), "n_codes": fmt(obs["indicator_codes"]), "fy_min": str(obs["fiscal_years"][0]), "fy_max": str(obs["fiscal_years"][-1]), "n_ind_rows": fmt(summary["indicators"]["rows"]), "n_hist_rows": fmt(hist["indicator_codes"]), "n_cov_rows": fmt(summary["coverage"]["rows"]), "n_jur_rows": str(summary["jurisdictions"]["rows"]), "hist_all_three": fmt(hist["in_all_three_generations"]), "hist_two": fmt(hist["in_two_generations"]), "hist_single": fmt(hist["single_generation"]), "hist_label_changed": fmt(hist["comparability_flag"].get("label_changed", 0)), "hist_label_stable": fmt(hist["comparability_flag"].get("label_stable", 0)), "hist_changed_16_18": fmt(hist["label_changed_2016_to_2018"]), "hist_changed_18_20": fmt(hist["label_changed_2018_to_2020plus"]), "rev_keys_compared": fmt(rev["keys_compared"]), "rev_keys_changed": fmt(rev["keys_with_changes"]), "rev_value_revised": fmt(ct.get("value_revised", 0)), "rev_text_revised": fmt(ct.get("text_revised", 0)), "rev_scale": fmt(ct.get("scale_convention_change", 0)), "rev_added": fmt(ct.get("added_in_later_release", 0)), "rev_removed": fmt(ct.get("removed_in_later_release", 0)), "not_available_rows": fmt(obs["value_status"].get("not_available", 0)), "unrecognized_rows": fmt(obs["value_status"].get("unrecognized_code", 0)), "monetary_thousands_rows": fmt(obs["monetary_unit"].get("thousands of local currency", 0)), "monetary_units_rows": fmt(obs["monetary_unit"].get("local currency units", 0)), "mojibake_values": fmt(obs["encoding_repairs"]["values"]), "generation_table": generation_table(summary), "fiscal_year_table": fiscal_year_table(summary), "status_table": status_table(summary), "dataflow_versions_table": dataflow_versions_table(summary), "kind_table": kind_table(summary), "panel_table": panel_table(), "panel_rows": fmt(summary["panel"]["rows"]), "panel_columns": str(summary["panel"]["indicator_columns"]), "panel_income_matched": fmt(summary["panel"]["income_group_by_year_matched"]), "panel_income_total": fmt(summary["panel"]["income_group_by_year_total"]), "wb_matched": str(summary["jurisdictions"]["world_bank"]["jurisdictions_matched"]), "wb_unmatched": ", ".join( f"`{c}`" for c in summary["jurisdictions"]["world_bank"]["jurisdictions_unmatched"] ), } def render(repo_id: str) -> None: summary = json.loads(SUMMARY.read_text(encoding="utf-8")) text = Template(TEMPLATE.read_text(encoding="utf-8")).substitute( build_context(summary, repo_id) ) OUTPUT.write_text(text, encoding="utf-8") print(f"wrote {OUTPUT} ({len(text.splitlines())} lines)") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--repo-id", default="FrenchCastle/isora-tax-administration") render(parser.parse_args().repo_id)