"""Parse SDMX structural metadata (codelists, hierarchies, dataset attributes) into tables.""" from __future__ import annotations import csv import json import re from typing import Any import pandas as pd from isora_hf import config from isora_hf.config import Dataflow THOUSANDS_RE = re.compile(r"thousand|'000|\b000s\b", re.IGNORECASE) DERIVED_PREFIXES = ("337_", "398_") def _clean(text: str | None) -> str | None: if text is None: return None cleaned = re.sub(r"\s+", " ", str(text)).strip() return cleaned or None def annotations(code: dict[str, Any]) -> dict[str, str]: """Flatten SDMX annotations into {title: text}. Empty values are dropped.""" out: dict[str, str] = {} for ann in code.get("annotations", []): title = ann.get("title") value = _clean(ann.get("text") or ann.get("value")) if title and value: out[title] = value return out def load_dsd(version: str) -> dict[str, Any]: path = config.RAW_STRUCTURES_DIR / f"DSD_ISORA_PUBLISHED__{version}.json" return json.loads(path.read_text(encoding="utf-8"))["data"] def codelist(dsd: dict[str, Any], codelist_id: str) -> dict[str, Any]: matches = [cl for cl in dsd["codelists"] if cl["id"] == codelist_id] if not matches: raise KeyError(f"codelist {codelist_id} not in DSD") return matches[0] def normalize_indicator_type(dissem_scale: str | None) -> str: key = (dissem_scale or "").strip().lower() return config.INDICATOR_TYPE_MAP.get(key, key or "unspecified") def _is_derived(code_id: str, ann: dict[str, str]) -> bool: return ( code_id.startswith(DERIVED_PREFIXES) or bool(ann.get("OriginalFormula")) or bool(ann.get("Numerator")) ) def indicator_row(flow: Dataflow, cl_version: str, code: dict[str, Any]) -> dict[str, Any]: ann = annotations(code) label = _clean(code.get("name")) or code["id"] subtitle = " | ".join(s for s in (ann.get("Subtitle1"), ann.get("Subtitle2")) if s) or None return { "questionnaire_generation": flow.generation, "codelist_id": flow.indicator_codelist, "codelist_version": cl_version, "indicator_code": code["id"], "label": label, "display_label": ann.get("Display Indicator"), "description": _clean(code.get("description")), "form_code": ann.get("SubReport"), "form_name": ann.get("ReportFormDescription"), "question_ref": ann.get("Question"), "section": ann.get("Category Tab"), "report_table_index": ann.get("Table Index"), "report_table_title": ann.get("Table Title"), "subtitle": subtitle, "scope": ann.get("Report"), "indicator_type": normalize_indicator_type(ann.get("DissemScale")), "is_local_currency": ann.get("DissemCurrency") == "NC", "label_mentions_thousands": bool(THOUSANDS_RE.search(label)), "is_derived": _is_derived(code["id"], ann), "formula": ann.get("OriginalFormula"), "numerator": ann.get("Numerator"), "denominator": ann.get("Denominator"), "legend": ann.get("Legend"), "suppressed_in_source_tables": ann.get("Suppress") == "Yes", "source_last_update": ann.get("Last Update"), } def indicator_table(flow: Dataflow) -> pd.DataFrame: dsd = load_dsd(flow.dsd_version) cl = codelist(dsd, flow.indicator_codelist) rows = [indicator_row(flow, cl["version"], code) for code in cl["codes"]] return pd.DataFrame(rows) # ---------------------------------------------------------------- jurisdictions MEMBERSHIP_FLAGS = { "Member_ADB": "member_adb", "Member_CIAT": "member_ciat", "Member_IOTA": "member_iota", "Member_OECD": "member_oecd", "Member_EU": "member_eu", "Member_G20": "member_g20", "Member_G7": "member_g7", "Member_WCO": "member_wco", "Member_FTA": "member_oecd_fta", "Member_WAEMU": "member_waemu", } def _yes_no(value: str | None) -> bool | None: if value is None: return None lowered = value.strip().lower() if lowered in ("yes", "1", "true"): return True if lowered in ("no", "0", "false"): return False return None def jurisdiction_master() -> pd.DataFrame: """One row per alpha-3 jurisdiction code, from the latest CL_ISORA_ISO_COUNTRY codelist.""" dsd = load_dsd(config.DATAFLOWS[-1].dsd_version) cl = codelist(dsd, "CL_ISORA_ISO_COUNTRY") rows = [] for code in cl["codes"]: ann = annotations(code) row = { "jurisdiction_code": code["id"], "jurisdiction_name": _clean(code.get("name")), "imf_numeric_code": ann.get("Numerical Code") or ann.get("Primary Code"), "imf_region": ann.get("IMF_Region"), "imf_subregion": ann.get("IMF_SubRegion"), "imf_regional_ta_center": ann.get("IMF_RTAC"), "world_bank_region": ann.get("WB_Region"), "world_bank_income_group_fy2015": ann.get("WB_IncomeGroup_FY15"), "weo_group": ann.get("WEO_AdvancedVsDeveloping"), "fragile_state_flag": ann.get("Fragile States"), "small_developing_state_flag": ann.get("Small Developing States"), } for src, dst in MEMBERSHIP_FLAGS.items(): row[dst] = _yes_no(ann.get(src)) rows.append(row) return pd.DataFrame(rows) def numeric_to_alpha3() -> dict[str, str]: """Map IMF numeric jurisdiction codes (used by ISORA 2016/2018) to the alpha-3 codes used by the consolidated dataflow. The latest CL_JURISDICTION carries an ISO annotation.""" dsd = load_dsd(config.DATAFLOWS[-1].dsd_version) mapping: dict[str, str] = {} for code in codelist(dsd, "CL_JURISDICTION")["codes"]: iso = annotations(code).get("ISO") if iso and iso != "NULL": mapping[code["id"]] = iso # Older DSDs may know codes the latest one dropped; fill gaps without overriding. for flow in config.DATAFLOWS[:2]: for code in codelist(load_dsd(flow.dsd_version), "CL_COUNTRY")["codes"]: iso = annotations(code).get("ISO") if iso and iso != "NULL": mapping.setdefault(code["id"], iso) return mapping # ---------------------------------------------------------------- hierarchies HIERARCHY_VERSIONS = { "H_CL_INDICATORS_BY_TOPIC": "2.2.0", "H_CL_PERIODIC_INDICATORS": "2.0.0", "H_CL_DERIVED_INDICATORS": "2.0.0", "H_CL_REVIEW_INDICATORS": "2.1.0", } def _rafit_labels() -> dict[str, str]: path = config.RAW_STRUCTURES_DIR / "CL_RAFIT_LABELS__all.json" data = json.loads(path.read_text(encoding="utf-8"))["data"] labels: dict[str, str] = {} for cl in data.get("codelists", []): for code in cl["codes"]: labels[code["id"]] = _clean(code.get("name")) or code["id"] return labels def _walk(node: dict[str, Any], ancestors: list[str], labels: dict[str, str], out: list) -> None: for child in node.get("hierarchicalCodes", []): target = (child.get("code") or "").split("=")[-1] # e.g. CL_ISORA_TAX(6.0+.0).337_001 codelist_name, _, code_id = target.rpartition(").") if "CL_RAFIT_LABELS" in codelist_name: _walk(child, ancestors + [labels.get(code_id, code_id)], labels, out) else: out.append((code_id, ancestors, len(out))) _walk(child, ancestors, labels, out) def hierarchy_memberships() -> pd.DataFrame: """Long table: hierarchy -> group path -> indicator code, for the versions used by the current consolidated dataflow.""" path = config.RAW_STRUCTURES_DIR / "hierarchies__all.json" data = json.loads(path.read_text(encoding="utf-8"))["data"] labels = _rafit_labels() rows = [] for hier in data.get("hierarchies", []): if HIERARCHY_VERSIONS.get(hier["id"]) != hier["version"]: continue members: list = [] _walk(hier, [], labels, members) for code_id, ancestors, order in members: rows.append( { "hierarchy_id": hier["id"], "hierarchy_name": _clean(hier.get("name")), "group": ancestors[0] if ancestors else None, "subgroup": ancestors[1] if len(ancestors) > 1 else None, "indicator_code": code_id, "position": order, } ) return pd.DataFrame(rows) # ---------------------------------------------------------------- dataset attributes def dataset_metadata(dataflow_id: str) -> dict[str, str]: """Dataset-level attributes (license URL, citations, publication dates) from the 2.1 CSV.""" path = config.RAW_STRUCTURES_DIR / f"dataset_metadata__{dataflow_id}.csv" with path.open(encoding="utf-8", newline="") as fh: reader = csv.DictReader(fh) first = next(reader) keep = ( "DATAFLOW", "FULL_DESCRIPTION", "PUBLISHER", "DEPARTMENT", "CONTACT_POINT", "PUBLICATION_DATE", "UPDATE_DATE", "ACCESS_SHARING_LEVEL", "SECURITY_CLASSIFICATION", "SHORT_SOURCE_CITATION", "FULL_SOURCE_CITATION", "LICENSE", "SUGGESTED_CITATION", "KEYWORDS_DATASET", ) return {k: first.get(k, "") for k in keep} def dataflow_versions() -> list[dict[str, str]]: path = config.RAW_STRUCTURES_DIR / "dataflows__ISORA.json" data = json.loads(path.read_text(encoding="utf-8"))["data"] out = [] for df in data["dataflows"]: updated = next( (a.get("value") for a in df.get("annotations", []) if a.get("id") == "lastUpdatedAt"), None, ) out.append( { "dataflow_id": df["id"], "version": df["version"], "description": df.get("description"), "data_structure": df["structure"].split("=")[-1], "last_updated_at_source": updated, } ) return out # ---------------------------------------------------------------- monetary detection COUNT_LIKE_RE = re.compile(r"\b(number of|no\. of|stock of [a-z ]*cases)\b", re.IGNORECASE) def declared_monetary_codes(indicators: pd.DataFrame) -> set[str]: """Indicator codes of a 2016/2018 codelist that hold money amounts. The source types them as 'currency' (a subset of the national-currency flag). A handful of count questions are mistyped as currency; labels that read as counts are excluded unless they explicitly say 'value'.""" money = indicators[indicators["indicator_type"] == "currency"] keep = [ code for code, label in zip(money["indicator_code"], money["label"]) if "value" in label.lower() or not COUNT_LIKE_RE.search(label) ] return set(keep)