Skip to content

country

src.utils.normalization.country

Shared country normalization helpers.

Provides consistent conversion between human-friendly country names and ISO 3166-1 alpha-2 codes across the pipeline.

iso2_to_country_name(country_code: str) -> str | None

Convert ISO alpha-2 code to a canonical country display name.

Source code in src/utils/normalization/country.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def iso2_to_country_name(country_code: str) -> str | None:
    """Convert ISO alpha-2 code to a canonical country display name."""
    code = (country_code or "").strip().upper()
    if not code:
        return None

    override = ISO2_TO_DISPLAY_OVERRIDES.get(code)
    if override:
        return override

    rec = pycountry.countries.get(alpha_2=code)
    if rec is None:
        return None
    name = getattr(rec, "name", None)
    return name if isinstance(name, str) else None

country_name_to_iso2(country_name: str) -> str | None

Convert a country display/official name to ISO alpha-2 code.

Source code in src/utils/normalization/country.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def country_name_to_iso2(country_name: str) -> str | None:
    """Convert a country display/official name to ISO alpha-2 code."""
    name = (country_name or "").strip()
    if not name:
        return None

    override = DISPLAY_TO_ISO2_OVERRIDES.get(name)
    if override:
        return override

    try:
        rec = pycountry.countries.lookup(name)
    except LookupError:
        return None

    code = getattr(rec, "alpha_2", None)
    return code if isinstance(code, str) else None