"""从区域表里读取栅格 ID。""" from __future__ import annotations import csv import io from pathlib import Path from app.shared.ids import normalize_id _ID_COLUMN_MESSAGE = "请把编号列的表头写成 20米栅格ID 或 50米栅格ID" _EXACT_HEADERS = { "栅格id": None, "20米栅格id": 20, "50米栅格id": 50, "grid20id": 20, "grid50id": 50, "gridid": None, "栅格": None, "栅格编号": None, } def _column_meter(name: str) -> tuple[bool, int | None]: raw = name.strip().lower().replace(" ", "").replace("\u3000", "") key = raw.replace("_", "") if key in _EXACT_HEADERS: return True, _EXACT_HEADERS[key] if "栅格" in name and "id" in raw: if "20" in key: return True, 20 if "50" in key: return True, 50 return True, None return False, None def _expected_meter(grid_size: str | None) -> int | None: if grid_size is None: return None if grid_size == "GRID20": return 20 if grid_size == "GRID50": return 50 raise ValueError("栅格只支持 20米或50米") def parse_table(rows: list[list], grid_size: str | None = None) -> tuple[list[str], int]: if not rows: return [], 0 header = ["" if cell is None else str(cell).strip() for cell in rows[0]] index: int | None = None meter: int | None = None for position, name in enumerate(header): matched, found = _column_meter(name) if matched: index = position meter = found break if index is None: filled = [cell for cell in header if cell] if len(filled) > 1: raise ValueError(_ID_COLUMN_MESSAGE) index = 0 start = 0 if normalize_id(header[0] if header else "") else 1 else: start = 1 expected = _expected_meter(grid_size) if meter is not None and expected is not None and meter != expected: raise ValueError(f"表头是{meter}米栅格,与所选的{expected}米不一致") found: list[str] = [] seen: set[str] = set() duplicates = 0 for row in rows[start:]: if index >= len(row): continue grid_id = normalize_id(row[index]) if not grid_id: continue if grid_id in seen: duplicates += 1 continue seen.add(grid_id) found.append(grid_id) return found, duplicates def _decode_csv(raw: bytes) -> str: for encoding in ("utf-8-sig", "utf-8", "gbk"): try: return raw.decode(encoding) except UnicodeDecodeError: continue return raw.decode("utf-8", "replace") def parse_upload(path: Path, grid_size: str | None = None) -> tuple[list[str], int]: if path.suffix.lower() != ".csv": raise ValueError("区域表只支持 CSV") text = _decode_csv(path.read_bytes()) sample = text[:4096] try: dialect = csv.Sniffer().sniff(sample, delimiters=",\t;") except csv.Error: dialect = csv.excel reader = csv.reader(io.StringIO(text), dialect) rows = [list(row) for row in reader if any(str(cell).strip() for cell in row)] return parse_table(rows, grid_size)