File size: 11,623 Bytes
4e28f7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcb24ca
4e28f7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcb24ca
4e28f7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
"""Constrói uma base SQLite de geografia administrativa a partir da Malha Municipal do IBGE.

Uso local:
    python scripts/build_ibge_sqlite.py --download

Uso com arquivos já baixados:
    python scripts/build_ibge_sqlite.py --municipios reference/downloads/BR_Municipios_2025.zip --ufs reference/downloads/BR_UF_2025.zip --pais reference/downloads/BR_Pais_2025.zip

Saída padrão:
    reference/ibge_geography.sqlite

Dependência: pyshp (pacote PyPI: pyshp; import: shapefile).
A base usa geometria serializada em JSON e índice por bounding box para validação rápida sem PostGIS.
"""

from __future__ import annotations

import argparse
import json
import re
import sqlite3
import tempfile
import unicodedata
import urllib.request
import zipfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

try:
    import shapefile  # type: ignore
except ImportError as exc:  # pragma: no cover
    raise SystemExit("Instale a dependência pyshp: pip install pyshp") from exc

IBGE_YEAR = "2025"
IBGE_BASE = "https://geoftp.ibge.gov.br/organizacao_do_territorio/malhas_territoriais/malhas_municipais/municipio_2025/Brasil"
DEFAULT_MUNICIPIOS_URL = f"{IBGE_BASE}/BR_Municipios_{IBGE_YEAR}.zip"
DEFAULT_UFS_URL = f"{IBGE_BASE}/BR_UF_{IBGE_YEAR}.zip"
DEFAULT_PAIS_URL = f"{IBGE_BASE}/BR_Pais_{IBGE_YEAR}.zip"

UF_NAMES = {
    "AC": "Acre", "AL": "Alagoas", "AP": "Amapá", "AM": "Amazonas", "BA": "Bahia",
    "CE": "Ceará", "DF": "Distrito Federal", "ES": "Espírito Santo", "GO": "Goiás",
    "MA": "Maranhão", "MT": "Mato Grosso", "MS": "Mato Grosso do Sul", "MG": "Minas Gerais",
    "PA": "Pará", "PB": "Paraíba", "PR": "Paraná", "PE": "Pernambuco", "PI": "Piauí",
    "RJ": "Rio de Janeiro", "RN": "Rio Grande do Norte", "RS": "Rio Grande do Sul",
    "RO": "Rondônia", "RR": "Roraima", "SC": "Santa Catarina", "SP": "São Paulo",
    "SE": "Sergipe", "TO": "Tocantins",
}

UF_CODES = {
    "11": "RO", "12": "AC", "13": "AM", "14": "RR", "15": "PA", "16": "AP", "17": "TO",
    "21": "MA", "22": "PI", "23": "CE", "24": "RN", "25": "PB", "26": "PE", "27": "AL", "28": "SE", "29": "BA",
    "31": "MG", "32": "ES", "33": "RJ", "35": "SP",
    "41": "PR", "42": "SC", "43": "RS",
    "50": "MS", "51": "MT", "52": "GO", "53": "DF",
}

COUNTRY_ALIASES = {"brasil", "brazil", "br", "brasilia?"}


def norm(value: Any) -> str:
    text = "" if value is None else str(value)
    text = unicodedata.normalize("NFKD", text)
    text = "".join(ch for ch in text if not unicodedata.combining(ch))
    text = text.lower().strip()
    text = re.sub(r"[^a-z0-9]+", " ", text)
    return re.sub(r"\s+", " ", text).strip()


def download(url: str, output: Path) -> Path:
    output.parent.mkdir(parents=True, exist_ok=True)
    print(f"Baixando: {url}")
    urllib.request.urlretrieve(url, output)
    return output


def extract_zip(archive: Path, outdir: Path) -> Path:
    print(f"Extraindo: {archive}")
    outdir.mkdir(parents=True, exist_ok=True)
    with zipfile.ZipFile(archive) as zf:
        zf.extractall(outdir)
    return outdir


def find_shp(path: Path) -> Path:
    shps = sorted(path.rglob("*.shp"))
    if not shps:
        raise FileNotFoundError(f"Nenhum .shp encontrado em {path}")
    # Preferir arquivo principal; evitar xml/auxiliares não se aplica a .shp, mas mantemos determinístico.
    return shps[0]


def fields(reader: Any) -> list[str]:
    return [f[0] for f in reader.fields[1:]]


def rec_get(record: dict[str, Any], candidates: list[str]) -> Any:
    lowered = {k.lower(): k for k in record.keys()}
    for cand in candidates:
        key = lowered.get(cand.lower())
        if key is not None:
            return record.get(key)
    return None


def shape_to_rings(shape: Any) -> list[list[list[float]]]:
    pts = shape.points
    parts = list(shape.parts) + [len(pts)]
    rings: list[list[list[float]]] = []
    for i in range(len(parts) - 1):
        start, end = parts[i], parts[i + 1]
        ring = [[float(x), float(y)] for x, y in pts[start:end]]
        if len(ring) >= 4:
            rings.append(ring)
    return rings


def init_db(db_path: Path) -> sqlite3.Connection:
    db_path.parent.mkdir(parents=True, exist_ok=True)
    if db_path.exists():
        db_path.unlink()
    con = sqlite3.connect(db_path)
    con.execute("PRAGMA journal_mode=OFF")
    con.execute("PRAGMA synchronous=OFF")
    con.execute("PRAGMA temp_store=MEMORY")
    con.executescript(
        """
        CREATE TABLE reference_metadata (
            key TEXT PRIMARY KEY,
            value TEXT
        );

        CREATE TABLE ibge_admin (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            level TEXT NOT NULL,
            code TEXT,
            name TEXT NOT NULL,
            norm_name TEXT NOT NULL,
            uf_code TEXT,
            uf_sigla TEXT,
            uf_name TEXT,
            norm_uf_name TEXT,
            min_lon REAL NOT NULL,
            min_lat REAL NOT NULL,
            max_lon REAL NOT NULL,
            max_lat REAL NOT NULL,
            geom_json TEXT NOT NULL
        );

        CREATE INDEX idx_ibge_admin_level_name ON ibge_admin(level, norm_name);
        CREATE INDEX idx_ibge_admin_level_uf ON ibge_admin(level, uf_sigla, norm_name);
        CREATE INDEX idx_ibge_admin_bbox ON ibge_admin(level, min_lon, max_lon, min_lat, max_lat);

        CREATE TABLE ibge_state_alias (
            alias TEXT PRIMARY KEY,
            uf_sigla TEXT NOT NULL,
            uf_name TEXT NOT NULL,
            uf_code TEXT
        );
        """
    )
    return con


def insert_metadata(con: sqlite3.Connection, **items: Any) -> None:
    for key, value in items.items():
        con.execute(
            "INSERT OR REPLACE INTO reference_metadata(key, value) VALUES (?, ?)",
            (key, str(value) if value is not None else None),
        )


def insert_state_aliases(con: sqlite3.Connection) -> None:
    for uf, name in UF_NAMES.items():
        code = next((c for c, sigla in UF_CODES.items() if sigla == uf), None)
        aliases = {uf, uf.lower(), name, norm(name)}
        for alias in aliases:
            con.execute(
                "INSERT OR REPLACE INTO ibge_state_alias(alias, uf_sigla, uf_name, uf_code) VALUES (?, ?, ?, ?)",
                (norm(alias), uf, name, code),
            )


def import_admin(con: sqlite3.Connection, zip_path: Path, level: str) -> int:
    with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
        extract_dir = extract_zip(zip_path, Path(tmp) / level)
        shp = find_shp(extract_dir)
        print(f"Lendo {level}: {shp.name}")
        reader = shapefile.Reader(str(shp), encoding="utf-8")
        names = fields(reader)
        total = 0
        for sr in reader.iterShapeRecords():
            record = dict(zip(names, list(sr.record)))
            shape = sr.shape
            rings = shape_to_rings(shape)
            if not rings:
                continue
            min_lon, min_lat, max_lon, max_lat = [float(v) for v in shape.bbox]

            if level == "municipality":
                code = rec_get(record, ["CD_MUN", "CD_GEOCMU", "GEOCODIGO", "CD_GEOCODI"])
                name = rec_get(record, ["NM_MUN", "NM_MUNICIP", "NOME", "NM_NOME"])
                uf_sigla = rec_get(record, ["SIGLA_UF", "UF", "NM_UF_SIGLA"])
                uf_code = rec_get(record, ["CD_UF", "GEOCUF"])
                if not uf_sigla and code:
                    uf_sigla = UF_CODES.get(str(code)[:2])
                if not uf_sigla and uf_code:
                    uf_sigla = UF_CODES.get(str(uf_code).zfill(2))
                uf_sigla = str(uf_sigla).upper() if uf_sigla else None
                uf_name = UF_NAMES.get(uf_sigla or "")
            elif level == "state":
                code = rec_get(record, ["CD_UF", "GEOCODIGO", "CD_GEOCUF"])
                name = rec_get(record, ["NM_UF", "NOME", "NM_NOME"])
                uf_sigla = rec_get(record, ["SIGLA_UF", "UF"])
                if not uf_sigla and code:
                    uf_sigla = UF_CODES.get(str(code).zfill(2))
                uf_sigla = str(uf_sigla).upper() if uf_sigla else None
                uf_name = str(name) if name else UF_NAMES.get(uf_sigla or "")
                code = str(code).zfill(2) if code is not None else None
            else:  # country
                code = rec_get(record, ["CD_PAIS", "CD_GEOCODI", "GEOCODIGO"])
                name = rec_get(record, ["NM_PAIS", "NOME", "NM_NOME"])
                uf_sigla = None
                uf_code = None
                uf_name = None

            if not name:
                continue

            con.execute(
                """
                INSERT INTO ibge_admin(
                    level, code, name, norm_name, uf_code, uf_sigla, uf_name, norm_uf_name,
                    min_lon, min_lat, max_lon, max_lat, geom_json
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                """,
                (
                    level,
                    str(code) if code is not None else None,
                    str(name),
                    norm(name),
                    str(locals().get("uf_code")).zfill(2) if locals().get("uf_code") is not None and str(locals().get("uf_code")).strip() else None,
                    uf_sigla,
                    uf_name,
                    norm(uf_name),
                    min_lon,
                    min_lat,
                    max_lon,
                    max_lat,
                    json.dumps(rings, ensure_ascii=False, separators=(",", ":")),
                ),
            )
            total += 1
            if total % 500 == 0:
                con.commit()
                print(f"  {level}: {total}")
        con.commit()
        return total


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--download", action="store_true")
    parser.add_argument("--municipios", type=Path)
    parser.add_argument("--ufs", type=Path)
    parser.add_argument("--pais", type=Path)
    parser.add_argument("--output", type=Path, default=Path("reference/ibge_geography.sqlite"))
    parser.add_argument("--year", default=IBGE_YEAR)
    args = parser.parse_args()

    downloads = Path("reference/downloads")
    if args.download:
        municipios = download(DEFAULT_MUNICIPIOS_URL, downloads / f"BR_Municipios_{IBGE_YEAR}.zip")
        ufs = download(DEFAULT_UFS_URL, downloads / f"BR_UF_{IBGE_YEAR}.zip")
        pais = download(DEFAULT_PAIS_URL, downloads / f"BR_Pais_{IBGE_YEAR}.zip")
    else:
        if not args.municipios or not args.ufs:
            raise SystemExit("Informe --download ou --municipios e --ufs")
        municipios = args.municipios
        ufs = args.ufs
        pais = args.pais

    con = init_db(args.output)
    insert_state_aliases(con)

    muni_total = import_admin(con, municipios, "municipality")
    state_total = import_admin(con, ufs, "state")
    country_total = import_admin(con, pais, "country") if pais and pais.exists() else 0

    insert_metadata(
        con,
        geography_mode="ibge_sqlite",
        source="IBGE Malha Municipal Digital",
        source_url=DEFAULT_MUNICIPIOS_URL,
        source_version=args.year,
        created_at_utc=datetime.now(timezone.utc).isoformat(),
        municipality_count=muni_total,
        state_count=state_total,
        country_count=country_total,
    )
    con.commit()
    con.close()

    print(f"SQLite criado: {args.output}")
    print(f"Municípios/áreas municipais: {muni_total}")
    print(f"UFs: {state_total}")
    print(f"País: {country_total}")


if __name__ == "__main__":
    main()