"""楼宇查询结果清洗、轮廓回填和 GeoPackage 生成。""" import csv import sqlite3 from pathlib import Path from shapely import wkt, to_wkb DROP_COLUMNS = {"输入行号", "查询状态", "错误信息"} LAYER_NAME = "NRBuildingsData" GEOM_COLUMN = "geom" def _encoding(path): for enc in ("gbk", "utf-8-sig", "utf-8"): try: with Path(path).open(encoding=enc, newline="") as f: next(csv.reader(f)) return enc except (UnicodeDecodeError, StopIteration): continue raise ValueError("无法识别楼宇结果 CSV 编码") def _gpkg_blob(geometry): return b"GP" + bytes((0, 1, 0, 0, 0, 0, 0, 0)) + to_wkb(geometry) def build_gpkg(data_csv, polygon_csv, output_path): data_csv, polygon_csv, output_path = map(Path, (data_csv, polygon_csv, output_path)) polygons = {} with polygon_csv.open(encoding=_encoding(polygon_csv), newline="") as f: for row in csv.DictReader(f): try: geometry = wkt.loads(row["WKT"]) except Exception: continue if not geometry.is_empty and geometry.is_valid: polygons.setdefault(str(row["building_id"]), geometry) data_encoding = _encoding(data_csv) with data_csv.open(encoding=data_encoding, newline="") as f: reader = csv.DictReader(f) fields = [x for x in (reader.fieldnames or []) if x not in DROP_COLUMNS] if "building_id" not in fields: raise ValueError("楼宇结果 CSV 缺少 building_id 字段") fields.append("WKT") rows=[] for row in reader: geometry=polygons.get(str(row.get("building_id", "")).strip()) if not geometry or (row.get("查询状态", "").strip() and row.get("查询状态", "").strip() not in {"成功", "命中"}): continue clean={x:row.get(x, "") for x in fields if x != "WKT"}; clean["WKT"]=geometry.wkt; rows.append((clean,geometry)) # 先原子回写清洗后的 CSV,避免中途失败破坏原文件。 temporary_csv = data_csv.with_name(f".{data_csv.name}.tmp") with temporary_csv.open("w", encoding=data_encoding, newline="") as f: writer = csv.DictWriter(f, fieldnames=fields) writer.writeheader() writer.writerows(clean for clean, _ in rows) temporary_csv.replace(data_csv) output_path.parent.mkdir(parents=True, exist_ok=True) if output_path.exists(): output_path.unlink() conn=sqlite3.connect(output_path) try: conn.executescript("""CREATE TABLE gpkg_spatial_ref_sys (srs_name TEXT NOT NULL, srs_id INTEGER PRIMARY KEY, organization TEXT NOT NULL, organization_coordsys_id INTEGER NOT NULL, definition TEXT NOT NULL, description TEXT); INSERT INTO gpkg_spatial_ref_sys VALUES ('WGS 84 geodetic',4326,'EPSG',4326,'GEOGCS[\"WGS 84\"]',''); CREATE TABLE gpkg_contents (table_name TEXT PRIMARY KEY, data_type TEXT NOT NULL, identifier TEXT UNIQUE, description TEXT DEFAULT '', last_change DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), min_x DOUBLE, min_y DOUBLE, max_x DOUBLE, max_y DOUBLE, srs_id INTEGER); CREATE TABLE gpkg_geometry_columns (table_name TEXT PRIMARY KEY, column_name TEXT NOT NULL, geometry_type_name TEXT NOT NULL, srs_id INTEGER NOT NULL, z TINYINT NOT NULL, m TINYINT NOT NULL);""") esc=lambda x:'"'+x.replace('"','""')+'"' conn.execute(f'CREATE TABLE {esc(LAYER_NAME)} (fid INTEGER PRIMARY KEY AUTOINCREMENT, '+', '.join(esc(x)+' TEXT' for x in fields)+f', {esc(GEOM_COLUMN)} BLOB NOT NULL)') conn.execute('CREATE VIRTUAL TABLE rtree_NRBuildingsData_geom USING rtree(id,minx,maxx,miny,maxy)') conn.execute('INSERT INTO gpkg_contents(table_name,data_type,identifier,srs_id) VALUES (?,?,?,?)',(LAYER_NAME,'features',LAYER_NAME,4326)) conn.execute('INSERT INTO gpkg_geometry_columns VALUES (?,?,?,?,?,?)',(LAYER_NAME,GEOM_COLUMN,'MULTIPOLYGON',4326,0,0)) cols=','.join(esc(x) for x in fields) for clean,geometry in rows: vals=[clean[x] for x in fields]+[_gpkg_blob(geometry)]; cur=conn.execute(f'INSERT INTO {esc(LAYER_NAME)} ({cols},{esc(GEOM_COLUMN)}) VALUES ({",".join("?" for _ in vals)})',vals); fid=cur.lastrowid; x1,y1,x2,y2=geometry.bounds; conn.execute('INSERT INTO rtree_NRBuildingsData_geom VALUES (?,?,?,?,?)',(fid,x1,x2,y1,y2)) conn.commit() finally: conn.close() return {"output":str(output_path),"feature_count":len(rows)}