84 lines
2.2 KiB
Python
84 lines
2.2 KiB
Python
"""从区域表里读取栅格 ID。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import csv
|
|
import io
|
|
from pathlib import Path
|
|
|
|
from app.shared.ids import normalize_id
|
|
|
|
_HEADER_KEYS = {
|
|
"栅格id",
|
|
"20米栅格id",
|
|
"grid20_id",
|
|
"grid50_id",
|
|
"grid_id",
|
|
"栅格",
|
|
"栅格编号",
|
|
"20米栅格id",
|
|
"50米栅格id",
|
|
}
|
|
|
|
|
|
def _header_index(header: list[str]) -> int | None:
|
|
for index, name in enumerate(header):
|
|
key = name.strip().lower().replace(" ", "").replace("_", "")
|
|
raw = name.strip().lower().replace(" ", "")
|
|
if raw in _HEADER_KEYS or key in {"栅格id", "20米栅格id", "50米栅格id", "grid20id", "grid50id", "gridid"}:
|
|
return index
|
|
if "栅格" in name and "id" in raw:
|
|
return index
|
|
return None
|
|
|
|
|
|
def parse_table(rows: list[list]) -> tuple[list[str], int]:
|
|
if not rows:
|
|
return [], 0
|
|
header = ["" if cell is None else str(cell).strip() for cell in rows[0]]
|
|
column = _header_index(header)
|
|
start = 0
|
|
if column is None:
|
|
column = 0
|
|
if not normalize_id(header[0] if header else ""):
|
|
start = 1
|
|
else:
|
|
start = 1
|
|
found: list[str] = []
|
|
seen: set[str] = set()
|
|
duplicates = 0
|
|
for row in rows[start:]:
|
|
if column >= len(row):
|
|
continue
|
|
grid_id = normalize_id(row[column])
|
|
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) -> list[str]:
|
|
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)
|
|
return parse_table([list(row) for row in reader if any(str(cell).strip() for cell in row)])
|