address-service/address/fias_archive.py

161 lines
5.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import re
import zipfile
from collections.abc import Iterator
from pathlib import Path
from xml.etree import ElementTree
from django.core.management.base import CommandError
KIND_ADDRESSES = "addresses"
KIND_HOUSES = "houses"
KIND_HIERARCHY = "hierarchy"
KIND_MUN_HIERARCHY = "mun_hierarchy"
KIND_ADDR_PARAMS = "addr_params"
KIND_HOUSE_PARAMS = "house_params"
_FIAS_XML_PATTERNS = {
KIND_ADDRESSES: re.compile(
r"(?:^|/)(?P<region>\d{2})/AS_ADDR_OBJ_\d{8}_[^/]+\.XML$",
re.IGNORECASE,
),
KIND_HOUSES: re.compile(
r"(?:^|/)(?P<region>\d{2})/AS_HOUSES_\d{8}_[^/]+\.XML$",
re.IGNORECASE,
),
KIND_HIERARCHY: re.compile(
r"(?:^|/)(?P<region>\d{2})/AS_ADM_HIERARCHY_\d{8}_[^/]+\.XML$",
re.IGNORECASE,
),
KIND_MUN_HIERARCHY: re.compile(
r"(?:^|/)(?P<region>\d{2})/AS_MUN_HIERARCHY_\d{8}_[^/]+\.XML$",
re.IGNORECASE,
),
KIND_ADDR_PARAMS: re.compile(
r"(?:^|/)(?P<region>\d{2})/AS_ADDR_OBJ_PARAMS_\d{8}_[^/]+\.XML$",
re.IGNORECASE,
),
KIND_HOUSE_PARAMS: re.compile(
r"(?:^|/)(?P<region>\d{2})/AS_HOUSES_PARAMS_\d{8}_[^/]+\.XML$",
re.IGNORECASE,
),
}
_KIND_TITLES = {
KIND_ADDRESSES: "AS_ADDR_OBJ",
KIND_HOUSES: "AS_HOUSES",
KIND_HIERARCHY: "AS_ADM_HIERARCHY",
KIND_MUN_HIERARCHY: "AS_MUN_HIERARCHY",
KIND_ADDR_PARAMS: "AS_ADDR_OBJ_PARAMS",
KIND_HOUSE_PARAMS: "AS_HOUSES_PARAMS",
}
def infer_region_code(path: Path | str) -> str | None:
"""Infer the FIAS region code from a directory in the XML path."""
parts = Path(str(path).replace("\\", "/")).parts
return next(
(part for part in reversed(parts[:-1]) if len(part) == 2 and part.isdigit()),
None,
)
def is_zip_archive(path: Path) -> bool:
return path.suffix.lower() == ".zip" or zipfile.is_zipfile(path)
def normalize_region_code(region_code: str | int | None) -> str | None:
if region_code is None or region_code == "":
return None
value = str(region_code)
if len(value) > 2 or not value.isdigit():
raise CommandError(
"Не удалось определить код региона. Передайте его через --region-code"
)
return f"{int(value):02d}"
def require_region_code(region_code: str | int | None) -> str:
normalized = normalize_region_code(region_code)
if normalized is None:
raise CommandError(
"Не удалось определить код региона. Передайте его через --region-code"
)
return normalized
def list_fias_members(
names: list[str],
kind: str,
region_code: str | None = None,
) -> list[tuple[str, str]]:
pattern = _FIAS_XML_PATTERNS[kind]
wanted = normalize_region_code(region_code)
found: list[tuple[str, str]] = []
for name in names:
match = pattern.search(name.replace("\\", "/"))
if match is None:
continue
region = match.group("region")
if wanted is not None and region != wanted:
continue
found.append((region, name))
found.sort(key=lambda item: (item[0], item[1]))
return found
def iter_fias_xml(
path: Path,
kind: str,
region_code: str | None = None,
*,
require_region: bool = True,
optional: bool = False,
) -> Iterator[tuple[str, str | None, Path | zipfile.ZipExtFile]]:
"""Yield `(label, region_code, source)` for a loose XML file or ZIP members.
ZIP members are streamed without extracting the archive. The returned
file object is only valid until the next iteration.
"""
if not path.is_file():
raise CommandError(f"Файл не найден: {path}")
if is_zip_archive(path):
yield from _iter_zip_xml(path, kind, region_code, optional=optional)
return
inferred = region_code or infer_region_code(path)
region = require_region_code(inferred) if require_region else normalize_region_code(inferred)
yield str(path), region, path
def _iter_zip_xml(
path: Path,
kind: str,
region_code: str | None,
*,
optional: bool = False,
) -> Iterator[tuple[str, str, zipfile.ZipExtFile]]:
try:
archive = zipfile.ZipFile(path)
except zipfile.BadZipFile as error:
raise CommandError(f"Не удалось открыть архив {path}: {error}") from error
with archive:
members = list_fias_members(archive.namelist(), kind, region_code)
if not members:
if optional:
return
title = _KIND_TITLES[kind]
if region_code:
raise CommandError(
f"В архиве нет файлов {title} для региона {require_region_code(region_code)}"
)
raise CommandError(f"В архиве нет файлов {title}")
for region, name in members:
with archive.open(name) as stream:
yield name, region, stream
def iterparse_xml(source: Path | zipfile.ZipExtFile):
return ElementTree.iterparse(source, events=("end",))