File size: 3,827 Bytes
49765fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/env python3
"""
extract_countries.py — Extract unique country names from a CSV.

Assumptions:
- Preferred source is a column named 'country' if present.
- Otherwise, parses a 'location' column formatted roughly as 'city, country'.
- Trims whitespace and canonicalizes common country synonyms (via csv_repair).

Output formats:
- text (default): one country per line to stdout or file
- json: JSON array of countries
- csv: single-column CSV with header 'country'

Usage examples:
  python extract_countries.py -i data.csv
  python extract_countries.py -i data.csv --format json > countries.json
  python extract_countries.py -i data.csv --format csv -o countries.csv
  python extract_countries.py -i data.csv --column location --sep ';' --encoding latin-1
"""

from __future__ import annotations

import argparse
import json
import sys
from typing import List, Optional

import numpy as np
import pandas as pd

try:
    # Reuse robust CSV reading and parsing helpers from csv_repair
    from csv_repair import try_read_csv, parse_location, canonical_country
except Exception as e:  # pragma: no cover
    print("This script expects csv_repair.py in the same directory.", file=sys.stderr)
    raise


def extract_countries(
    df: pd.DataFrame,
    column: str = "location",
    prefer_country_col: bool = True,
    dropna: bool = True,
) -> List[str]:
    if prefer_country_col and "country" in df.columns:
        s = df["country"].astype(str).str.strip().replace({"": np.nan})
    elif column in df.columns:
        # Parse from location
        _, country = parse_location(df[column])
        s = country
    else:
        raise ValueError(f"Column '{column}' not found and no 'country' column present")

    # Canonicalize and clean
    s = s.apply(canonical_country)
    if dropna:
        s = s.dropna()

    # Unique sorted list (case-insensitive sort, stable)
    uniq = pd.Series(s.unique(), dtype=object).dropna().astype(str)
    countries = sorted(uniq.tolist(), key=lambda x: x.casefold())
    return countries


def main(argv: Optional[List[str]] = None) -> int:
    p = argparse.ArgumentParser(description="Extract unique country names from a CSV")
    p.add_argument("-i", "--input", required=True, help="Path to input CSV")
    p.add_argument("--encoding", default=None, help="Optional file encoding (auto if omitted)")
    p.add_argument("--sep", default=None, help="CSV delimiter; if omitted, inferred by pandas")
    p.add_argument("--column", default="location", help="Column to parse when 'country' not present")
    p.add_argument(
        "--format", choices=["text", "json", "csv"], default="text", help="Output format"
    )
    p.add_argument("-o", "--output", default=None, help="Optional output file; default stdout")
    p.add_argument("--keep-nulls", action="store_true", help="Include empty/NA countries in output")
    args = p.parse_args(argv)

    # Read CSV robustly
    df = try_read_csv(args.input, encoding=args.encoding, sep=args.sep)

    try:
        countries = extract_countries(df, column=args.column, dropna=not args.keep_nulls)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        return 2

    out = None
    if args.format == "text":
        out = "\n".join(countries) + ("\n" if countries else "")
    elif args.format == "json":
        out = json.dumps(countries, ensure_ascii=False, indent=2)
    elif args.format == "csv":
        # Build a simple CSV; avoid pandas roundtrip to keep deps minimal here
        lines = ["country"] + [c.replace("\"", "\"") for c in countries]
        out = "\n".join(lines) + "\n"

    if args.output:
        with open(args.output, "w", encoding="utf-8") as f:
            f.write(out)
    else:
        sys.stdout.write(out)

    return 0


if __name__ == "__main__":
    raise SystemExit(main())