Datasets:
Formats:
parquet
Languages:
English
Size:
100K - 1M
Tags:
isora
international-survey-on-revenue-administration
tax-administration
revenue-administration
tax-authority
taxation
License:
v1.1.0: consolidated panel + panel_dictionary, isora.py loader, World Bank income groups (current + per fiscal year), thousands flag on derived expenditure aggregates
9f0fcd7 verified Download pipeline/src/isora_hf/build.py from FrenchCastle/isora-tax-administration: direct link, hf CLI and curl.
- Browser
- Download file 13.5 kB
-
https://huggingface.co/datasets/FrenchCastle/isora-tax-administration/resolve/main/pipeline/src/isora_hf/build.py
- Command line
-
hf download hf://datasets/FrenchCastle/isora-tax-administration/pipeline/src/isora_hf/build.py
-
curl -L -o build.py https://huggingface.co/datasets/FrenchCastle/isora-tax-administration/resolve/main/pipeline/src/isora_hf/build.py
13.5 kB
| """Orchestrate the build: raw SDMX artifacts -> clean Parquet/CSV tables + metadata for the card.""" | |
| from __future__ import annotations | |
| import gzip | |
| import json | |
| import logging | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| from isora_hf import config, structures, worldbank | |
| from isora_hf.crosswalk import build_indicator_history | |
| from isora_hf.observations import MAX_CATEGORIES, OBSERVATION_COLUMNS, clean_observations | |
| from isora_hf.panel import build_panel | |
| from isora_hf.revisions import build_revisions | |
| log = logging.getLogger(__name__) | |
| LATEST = config.DATAFLOWS[-1] | |
| FILE_SLUG = { | |
| "ISORA 2016": "isora_2016", | |
| "ISORA 2018": "isora_2018", | |
| "ISORA 2020+": "isora_2020plus", | |
| } | |
| def _years(series: pd.Series) -> list[int]: | |
| return sorted({int(y) for y in series}) | |
| def _as_list(value) -> list: | |
| """groupby().agg may hand back numpy arrays or NaN for list-valued aggregations.""" | |
| if isinstance(value, list): | |
| return value | |
| if isinstance(value, np.ndarray): | |
| return value.tolist() | |
| return [] | |
| def _answer_categories(series: pd.Series) -> list[str]: | |
| """Distinct categorical answers, most frequent first, or empty when the indicator is numeric | |
| or free text (more than MAX_CATEGORIES distinct answers).""" | |
| counts = series.dropna().value_counts() | |
| if counts.empty or len(counts) > MAX_CATEGORIES: | |
| return [] | |
| return [str(v) for v in counts.index] | |
| def build_indicators(observations: pd.DataFrame) -> pd.DataFrame: | |
| frames = [structures.indicator_table(flow) for flow in config.DATAFLOWS] | |
| indicators = pd.concat(frames, ignore_index=True) | |
| members = structures.hierarchy_memberships() | |
| topic = members[members["hierarchy_id"] == "H_CL_INDICATORS_BY_TOPIC"].drop_duplicates( | |
| "indicator_code" | |
| ) | |
| topic = topic.set_index("indicator_code") | |
| sets = { | |
| h: set(members.loc[members["hierarchy_id"] == h, "indicator_code"]) | |
| for h in members["hierarchy_id"].unique() | |
| } | |
| latest = indicators["questionnaire_generation"] == LATEST.generation | |
| codes = indicators["indicator_code"] | |
| indicators["topic_group"] = codes.map(topic["group"]).where(latest) | |
| indicators["topic_subgroup"] = codes.map(topic["subgroup"]).where(latest) | |
| indicators["is_periodic"] = ( | |
| codes.isin(sets.get("H_CL_PERIODIC_INDICATORS", set())) & latest | |
| ).where(latest) | |
| indicators["is_review_indicator"] = ( | |
| codes.isin(sets.get("H_CL_REVIEW_INDICATORS", set())) & latest | |
| ).where(latest) | |
| indicators["in_derived_indicators_hierarchy"] = ( | |
| codes.isin(sets.get("H_CL_DERIVED_INDICATORS", set())) & latest | |
| ).where(latest) | |
| key = ["questionnaire_generation", "indicator_code"] | |
| stats = observations.groupby(key).agg( | |
| n_observations=("value_raw", "size"), | |
| n_observations_with_value=("value_status", lambda s: int((s == "value").sum())), | |
| n_jurisdictions=("jurisdiction_code", "nunique"), | |
| fiscal_years_with_data=("fiscal_year", _years), | |
| observed_value_kind=("indicator_value_kind", "first"), | |
| is_monetary=("monetary_unit", lambda s: bool(s.notna().any())), | |
| answer_categories=("value_text", _answer_categories), | |
| ) | |
| indicators = indicators.merge(stats, left_on=key, right_index=True, how="left") | |
| indicators["n_observations"] = indicators["n_observations"].fillna(0).astype(int) | |
| indicators["n_observations_with_value"] = ( | |
| indicators["n_observations_with_value"].fillna(0).astype(int) | |
| ) | |
| indicators["n_jurisdictions"] = indicators["n_jurisdictions"].fillna(0).astype(int) | |
| for col in ("fiscal_years_with_data", "answer_categories"): | |
| indicators[col] = indicators[col].apply(_as_list) | |
| indicators["observed_value_kind"] = indicators["observed_value_kind"].fillna("no_observations") | |
| indicators["is_monetary"] = indicators["is_monetary"].fillna(False).astype(bool) | |
| indicators["has_observations"] = indicators["n_observations"] > 0 | |
| return indicators.sort_values(key).reset_index(drop=True) | |
| def build_jurisdictions(observations: pd.DataFrame) -> pd.DataFrame: | |
| master = structures.jurisdiction_master() | |
| stats = observations.groupby("jurisdiction_code").agg( | |
| fiscal_years_with_data=("fiscal_year", _years), | |
| survey_rounds_with_data=("survey_round", lambda s: sorted(set(s))), | |
| n_observations=("value_raw", "size"), | |
| in_isora_2016=("questionnaire_generation", lambda s: bool((s == "ISORA 2016").any())), | |
| in_isora_2018=("questionnaire_generation", lambda s: bool((s == "ISORA 2018").any())), | |
| in_isora_2020plus=("questionnaire_generation", lambda s: bool((s == "ISORA 2020+").any())), | |
| ) | |
| out = master.merge(stats, left_on="jurisdiction_code", right_index=True, how="inner") | |
| for col in ("fiscal_years_with_data", "survey_rounds_with_data"): | |
| out[col] = out[col].apply(_as_list) | |
| missing = set(stats.index) - set(master["jurisdiction_code"]) | |
| if missing: | |
| raise ValueError(f"jurisdictions in data but not in master codelist: {sorted(missing)}") | |
| return out.sort_values("jurisdiction_code").reset_index(drop=True) | |
| def build_coverage(observations: pd.DataFrame) -> pd.DataFrame: | |
| key = ["questionnaire_generation", "indicator_code", "fiscal_year"] | |
| counts = observations.pivot_table( | |
| index=key, columns="value_status", values="value_raw", aggfunc="size", fill_value=0 | |
| ) | |
| counts.columns = [f"n_{c}" for c in counts.columns] | |
| counts["n_jurisdictions_reporting"] = counts.sum(axis=1) | |
| return counts.reset_index().sort_values(key).reset_index(drop=True) | |
| def write_table(frame: pd.DataFrame, path: Path, csv_dir: Path | None = None) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| table = pa.Table.from_pandas(frame, preserve_index=False) | |
| pq.write_table(table, path, compression="zstd") | |
| log.info( | |
| "wrote %s (%d rows, %d cols)", | |
| path.relative_to(config.OUT_DIR), | |
| len(frame), | |
| len(frame.columns), | |
| ) | |
| if csv_dir is not None: | |
| csv_dir.mkdir(parents=True, exist_ok=True) | |
| flat = frame.copy() | |
| for col in flat.columns: | |
| if flat[col].map(lambda v: isinstance(v, list)).any(): | |
| flat[col] = flat[col].map( | |
| lambda v: ";".join(str(x) for x in v) if isinstance(v, list) else v | |
| ) | |
| with gzip.open(csv_dir / (path.stem + ".csv.gz"), "wt", encoding="utf-8", newline="") as fh: | |
| flat.to_csv(fh, index=False) | |
| def observation_summary(obs: pd.DataFrame) -> dict: | |
| per_gen = {} | |
| for gen, part in obs.groupby("questionnaire_generation"): | |
| per_gen[gen] = { | |
| "rows": len(part), | |
| "jurisdictions": int(part["jurisdiction_code"].nunique()), | |
| "indicators": int(part["indicator_code"].nunique()), | |
| "fiscal_years": _years(part["fiscal_year"]), | |
| "value_status": {k: int(v) for k, v in part["value_status"].value_counts().items()}, | |
| "numeric_values": int(part["value_numeric"].notna().sum()), | |
| "footnotes": int(part["footnote"].notna().sum()), | |
| } | |
| per_year = obs.groupby("fiscal_year").agg( | |
| jurisdictions=("jurisdiction_code", "nunique"), | |
| indicators=("indicator_code", "nunique"), | |
| rows=("value_raw", "size"), | |
| ) | |
| return { | |
| "rows": len(obs), | |
| "jurisdictions": int(obs["jurisdiction_code"].nunique()), | |
| "indicator_codes": int(obs["indicator_code"].nunique()), | |
| "fiscal_years": _years(obs["fiscal_year"]), | |
| "by_generation": per_gen, | |
| "by_fiscal_year": { | |
| int(y): {k: int(v) for k, v in r.items()} for y, r in per_year.iterrows() | |
| }, | |
| "value_status": {k: int(v) for k, v in obs["value_status"].value_counts().items()}, | |
| "unit_multiplier": { | |
| int(k): int(v) for k, v in obs["unit_multiplier"].value_counts().items() | |
| }, | |
| "monetary_unit": {str(k): int(v) for k, v in obs["monetary_unit"].value_counts().items()}, | |
| "indicator_value_kind": { | |
| k: int(v) for k, v in obs["indicator_value_kind"].value_counts().items() | |
| }, | |
| "encoding_repairs": { | |
| "values": int(obs["value_raw"].str.contains("Ã|â€", regex=True).sum()), | |
| "footnotes_with_turkiye_or_quotes": int( | |
| obs["footnote"].fillna("").str.contains("‘|’|Türkiye", regex=True).sum() | |
| ), | |
| }, | |
| } | |
| def panel_summary(panel: pd.DataFrame, dictionary: pd.DataFrame, income_by_year: pd.Series) -> dict: | |
| coverage = { | |
| row["column"]: int(row["n_non_null_in_panel"]) | |
| for _, row in dictionary.drop_duplicates("column").iterrows() | |
| } | |
| return { | |
| "rows": len(panel), | |
| "jurisdictions": int(panel["jurisdiction_code"].nunique()), | |
| "indicator_columns": int(dictionary["column"].nunique()), | |
| "dictionary_rows": len(dictionary), | |
| "income_group_by_year_matched": int(income_by_year.notna().sum()), | |
| "income_group_by_year_total": len(income_by_year), | |
| "non_null_by_column": coverage, | |
| } | |
| def history_summary(hist: pd.DataFrame) -> dict: | |
| return { | |
| "indicator_codes": len(hist), | |
| "in_all_three_generations": int((hist["n_generations"] == 3).sum()), | |
| "in_two_generations": int((hist["n_generations"] == 2).sum()), | |
| "single_generation": int((hist["n_generations"] == 1).sum()), | |
| "comparability_flag": { | |
| k: int(v) for k, v in hist["comparability_flag"].value_counts().items() | |
| }, | |
| "label_changed_2016_to_2018": int((hist["label_changed_2016_to_2018"] == True).sum()), | |
| "label_changed_2018_to_2020plus": int( | |
| (hist["label_changed_2018_to_2020plus"] == True).sum() | |
| ), | |
| } | |
| def run() -> dict: | |
| out = config.OUT_DIR | |
| data_dir, csv_dir = out / "data", out / "csv" | |
| n2a = structures.numeric_to_alpha3() | |
| master = structures.jurisdiction_master() | |
| names = dict(zip(master["jurisdiction_code"], master["jurisdiction_name"])) | |
| base_indicators = pd.concat( | |
| [structures.indicator_table(f) for f in config.DATAFLOWS], ignore_index=True | |
| ) | |
| parts = [] | |
| for flow in config.DATAFLOWS: | |
| ind = base_indicators[base_indicators["questionnaire_generation"] == flow.generation] | |
| monetary = set() if flow is LATEST else structures.declared_monetary_codes(ind) | |
| part = clean_observations(flow, ind, n2a, names, monetary)[OBSERVATION_COLUMNS] | |
| write_table( | |
| part, data_dir / "observations" / f"{FILE_SLUG[flow.generation]}.parquet", csv_dir | |
| ) | |
| parts.append(part) | |
| observations = pd.concat(parts, ignore_index=True) | |
| indicators = build_indicators(observations) | |
| write_table(indicators, data_dir / "indicators.parquet", csv_dir) | |
| history = build_indicator_history(indicators, observations) | |
| write_table(history, data_dir / "indicator_history.parquet", csv_dir) | |
| jurisdictions, wb_meta = worldbank.enrich_jurisdictions(build_jurisdictions(observations)) | |
| write_table(jurisdictions, data_dir / "jurisdictions.parquet", csv_dir) | |
| wb_history = worldbank.load_history() | |
| keys = ( | |
| observations[["jurisdiction_code", "fiscal_year"]].drop_duplicates().reset_index(drop=True) | |
| ) | |
| income_by_year = pd.Series( | |
| worldbank.income_group_for_years(wb_history, keys).to_numpy(), | |
| index=pd.MultiIndex.from_frame(keys), | |
| ) | |
| panel, panel_dictionary = build_panel(observations, jurisdictions, income_by_year) | |
| write_table(panel, data_dir / "panel.parquet", csv_dir) | |
| write_table(panel_dictionary, data_dir / "panel_dictionary.parquet", csv_dir) | |
| coverage = build_coverage(observations) | |
| write_table(coverage, data_dir / "coverage.parquet", csv_dir) | |
| revisions, rev_summary = build_revisions() | |
| write_table(revisions, data_dir / "revisions.parquet", csv_dir) | |
| summary = { | |
| "retrieved_at_utc": (config.RAW_DIR / "RETRIEVED_AT.txt").read_text().strip(), | |
| "dataflows_used": [ | |
| { | |
| "id": f.id, | |
| "version": f.version, | |
| "dsd_version": f.dsd_version, | |
| "generation": f.generation, | |
| } | |
| for f in config.DATAFLOWS | |
| ], | |
| "dataflow_versions_at_source": structures.dataflow_versions(), | |
| "dataset_attributes": {f.id: structures.dataset_metadata(f.id) for f in config.DATAFLOWS}, | |
| "hierarchy_versions": structures.HIERARCHY_VERSIONS, | |
| "observations": observation_summary(observations), | |
| "indicators": { | |
| "rows": len(indicators), | |
| "by_generation": { | |
| k: int(v) for k, v in indicators["questionnaire_generation"].value_counts().items() | |
| }, | |
| }, | |
| "indicator_history": history_summary(history), | |
| "jurisdictions": {"rows": len(jurisdictions), "world_bank": wb_meta}, | |
| "panel": panel_summary(panel, panel_dictionary, income_by_year), | |
| "coverage": {"rows": len(coverage)}, | |
| "revisions": rev_summary, | |
| } | |
| (out / "metadata").mkdir(parents=True, exist_ok=True) | |
| (out / "metadata" / "build_summary.json").write_text( | |
| json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8" | |
| ) | |
| log.info("build complete") | |
| return summary | |
| if __name__ == "__main__": | |
| logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s") | |
| run() | |