From 48e68469adc11605cdfc27fb8c00e3dc9f33a13d Mon Sep 17 00:00:00 2001 From: nixevol Date: Thu, 17 Sep 2026 09:22:53 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=A5=BC=E5=AE=87=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E6=8C=89=E8=BD=AE=E5=BB=93=20WKT=20=E8=AE=A1?= =?UTF-8?q?=E7=AE=97=E5=86=85=E9=83=A8=E7=82=B9=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- GetNRBuildingsData.py | 77 ++++++++++++++++++++++++----------- README.md | 14 +++---- requirements-nr-buildings.txt | 1 + tests/test_nr_buildings.py | 48 ++++++++++++++++++++-- tests/test_toolbox.py | 6 +-- toolbox/validation.py | 4 +- ui/building_page.py | 7 ++-- 7 files changed, 116 insertions(+), 41 deletions(-) diff --git a/GetNRBuildingsData.py b/GetNRBuildingsData.py index 60a0037..3bbdf27 100644 --- a/GetNRBuildingsData.py +++ b/GetNRBuildingsData.py @@ -1,9 +1,11 @@ -"""异步批量查询楼宇 WFS,由独占写入线程实时保存 CSV。独立运行。""" +"""异步批量查询楼宇 WFS,由独占写入线程实时保存 CSV。独立运行。 + +输入为楼宇轮廓 WKT;每个楼宇先计算一个保证落在轮廓内部的查询点,再按点查询。 +""" import asyncio from concurrent.futures import ThreadPoolExecutor import csv -from decimal import Decimal, InvalidOperation from itertools import islice import json from pathlib import Path @@ -13,6 +15,9 @@ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit, quote import xml.etree.ElementTree as ET import aiohttp +from shapely import make_valid, wkt as shapely_wkt +from shapely.errors import ShapelyError +from shapely.ops import polylabel # 填完整 WFS URL(包含 ak、sig 等参数);原 CQL_FILTER 会自动替换。 @@ -21,13 +26,12 @@ URL = "https://nqi.gmcc.net:20443/pro-gis-tenant/gmcc-wyzc/prod-api/api/HRvjYUm1 # 填完整 Cookie 头内容,例如 CASTGC=...;不要加 Cookie: 前缀。 COOKIES = "CASTGC=TGT-1071858-toWWSoGzu8ASDB-dF69kh7rTnxZHt1nWd45MsLeTt0lHrzWC8n8Hwz3BjZjGRcIxbRkmas-auth-center-7d87cd5c9d-xd94d" REFERER = "https://nqi.gmcc.net:20443/pro-problem-warehouse-web/" -INPUT_CSV = Path(__file__).resolve().parent / "source" / "NRBuildingsPoint.csv" +INPUT_CSV = Path(__file__).resolve().parent / "source" / "NRBuildPolygon.csv" OUTPUT_CSV = Path(__file__).resolve().parent / "output" / "NRBuildingsData.csv" -INPUT_ENCODING = "gb18030" # 当前源文件为 GBK;UTF-8 文件可改为 utf-8-sig。 +INPUT_ENCODING = "utf-8-sig" # 当前源文件为 UTF-8 BOM;GBK 文件可改为 gb18030。 OUTPUT_ENCODING = "gbk" # 供 Excel/传统工具直接打开;无法编码的字符用 errors=replace。 -ID_COLUMN = "序号" -LONGITUDE_COLUMN = "经度" -LATITUDE_COLUMN = "维度" # 源文件实际写的是“维度”。 +ID_COLUMN = "building_id" +WKT_COLUMN = "WKT" # 楼宇轮廓,MULTIPOLYGON/POLYGON WKT,经纬度 EPSG:4326。 GEOMETRY_FIELD = "the_geom" START_ROW = 1 # 从第几条数据开始,不计表头。 LIMIT = 1000 # 最多查询的坐标数;None 表示处理剩余全部。 @@ -36,7 +40,7 @@ TIMEOUT = 30 # 每次请求超时秒数。 MAX_RETRIES = 2 # 网络异常、429 或 5xx 的重试次数;空结果不重试。 REQUEST_INTERVAL = 0.2 # 每个查询协程两次请求之间的等待秒数。 PROGRESS_EVERY = 100 -QUERY_COLUMNS = ["查询序号", "查询经度", "查询纬度", "查询状态", "命中数量", "要素ID", "错误信息"] +QUERY_COLUMNS = ["输入行号", "查询序号", "查询经度", "查询纬度", "查询状态", "命中数量", "要素ID", "错误信息"] class QueryError(Exception): @@ -47,14 +51,39 @@ class AuthenticationError(QueryError): pass -def coordinate(value, lower, upper): +def interior_point(text): + """返回一定位于轮廓内部的 (经度, 纬度) 字符串。 + + 不使用外包框中心或质心:凹形、L 形楼宇的这两个点都可能落在轮廓外。 + 主方案是 polylabel(离边界最远的内部点,天然在图形内且远离边缘); + 多部件时取面积最大的部件。计算结果再用 within 校验,不通过时回退到 + GEOS 的 representative_point,它同样保证在几何内部。 + """ try: - number = Decimal(str(value).strip()) - except InvalidOperation: - raise ValueError("经纬度不是有效数字") from None - if not number.is_finite() or not lower <= number <= upper: + geometry = shapely_wkt.loads(str(text or "").strip()) + except (ShapelyError, ValueError, TypeError): + raise ValueError("WKT 无法解析") from None + if geometry.is_empty or geometry.geom_type not in ("Polygon", "MultiPolygon"): + raise ValueError("WKT 不是多边形或为空") + if not geometry.is_valid: + geometry = make_valid(geometry) + parts = [part for part in getattr(geometry, "geoms", [geometry]) if part.geom_type == "Polygon" and part.area > 0] + if not parts: + raise ValueError("轮廓没有有效面积") + largest = max(parts, key=lambda part: part.area) + x1, y1, x2, y2 = largest.bounds + point = None + try: + point = polylabel(largest, tolerance=max(max(x2 - x1, y2 - y1) / 100, 1e-9)) + except (ShapelyError, ValueError): + point = None + if point is None or not point.within(geometry): + point = largest.representative_point() + if not point.within(geometry): + raise ValueError("无法计算轮廓内部点") + if not (-180 <= point.x <= 180 and -90 <= point.y <= 90): raise ValueError("经纬度超出有效范围") - return format(number, "f") + return f"{point.x:.8f}", f"{point.y:.8f}" def query_url(longitude, latitude): @@ -201,15 +230,16 @@ async def async_main(*, handle_signals=True, should_stop=None, progress=None): request_stop() break # 同一事件循环中读取下一行,无 await,不会并发推进 CSV 迭代器。 - point = next(selected, None) - if point is None: + item = next(selected, None) + if item is None: break - metadata = {"查询序号": point.get(ID_COLUMN), "查询经度": point.get(LONGITUDE_COLUMN), - "查询纬度": point.get(LATITUDE_COLUMN), "命中数量": 0, "要素ID": "", "错误信息": ""} + row_number, building = item + metadata = {"输入行号": row_number, "查询序号": building.get(ID_COLUMN), "查询经度": "", + "查询纬度": "", "命中数量": 0, "要素ID": "", "错误信息": ""} features = [] try: - lon = coordinate(point.get(LONGITUDE_COLUMN), -180, 180) - lat = coordinate(point.get(LATITUDE_COLUMN), -90, 90) + lon, lat = interior_point(building.get(WKT_COLUMN)) + metadata.update(查询经度=lon, 查询纬度=lat) features = await fetch_features(session, lon, lat) if any(set(feature["properties"]) & set(QUERY_COLUMNS) for feature in features): raise QueryError("properties 字段与查询信息列重名") @@ -217,7 +247,7 @@ async def async_main(*, handle_signals=True, should_stop=None, progress=None): metadata["命中数量"] = len(features) except ValueError as exc: features = [] - metadata.update(查询状态="坐标无效", 错误信息=str(exc)) + metadata.update(查询状态="轮廓无效", 错误信息=str(exc)) except QueryError as exc: features = [] metadata.update(查询状态="请求失败", 错误信息=str(exc)) @@ -253,10 +283,11 @@ async def async_main(*, handle_signals=True, should_stop=None, progress=None): with input_path.open("r", encoding=INPUT_ENCODING, newline="") as source: reader = csv.DictReader(source) - required = {ID_COLUMN, LONGITUDE_COLUMN, LATITUDE_COLUMN} + required = {ID_COLUMN, WKT_COLUMN} if not required.issubset(reader.fieldnames or []): raise ValueError(f"输入 CSV 必须包含列:{', '.join(sorted(required))}") - selected = islice(reader, START_ROW - 1, None if LIMIT is None else START_ROW - 1 + LIMIT) + # 输入行号从 1 计(不含表头),便于按行号断点重跑和区分重复 building_id。 + selected = islice(enumerate(reader, 1), START_ROW - 1, None if LIMIT is None else START_ROW - 1 + LIMIT) old_signal_handler = None if handle_signals: old_signal_handler = signal.signal(signal.SIGINT, lambda *_: loop.call_soon_threadsafe(request_stop)) diff --git a/README.md b/README.md index 5986603..e902eb4 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ python -m streamlit run app.py - **工具箱首页**:数据状态与任务概况。 - **市场网格出图**:导入数据后生成市场成果包。 -- **楼宇数据查询**:导入坐标清单后批量查询楼宇。 +- **楼宇数据查询**:导入楼宇轮廓清单后按轮廓内部点批量查询楼宇。 - **任务中心**:查看进度并停止任务。 - **成果浏览**:查看成果清单,按文件下载。 @@ -48,19 +48,19 @@ AOI 最大重叠面积匹配的预处理不在当前仓库内,界面直接使 ## 独立楼宇批量查询 -`GetNRBuildingsData.py` 独立运行,不调用 `main.py`。先运行 `python -m pip install -r requirements-nr-buildings.txt` 安装异步请求依赖 `aiohttp`。 +`GetNRBuildingsData.py` 独立运行,不调用 `main.py`。先运行 `python -m pip install -r requirements-nr-buildings.txt` 安装依赖 `aiohttp` 和 `shapely`。 1. 在脚本顶部填写完整 WFS `URL`(含 `ak`、`sig` 等原参数)和 `COOKIES`。 -2. 默认读取 `source/NRBuildingsPoint.csv`,使用 `序号`、`经度`、`维度` 三列,输入编码为 GBK/GB18030。 +2. 默认读取 `source/NRBuildPolygon.csv`,使用 `WKT`(楼宇轮廓,`MULTIPOLYGON`/`POLYGON`,EPSG:4326)和 `building_id` 两列,输入编码为 UTF-8 BOM(GBK 文件可改 `INPUT_ENCODING`)。 3. 运行 `python GetNRBuildingsData.py`,当前 `LIMIT = 1000`,输出 `output/NRBuildingsData.csv`(GBK 编码)。将 `LIMIT` 改为 `None` 可查询剩余全部;`START_ROW` 可指定起始数据行。 -脚本自动把 URL 中的 `CQL_FILTER` 替换成 `POINT(经度 纬度)` 点查询,坐标之间使用空格。输出表头包含查询坐标、状态以及所有返回 `properties` 字段;一个坐标命中多个楼宇时输出多行,未命中或失败时保留状态行。脚本顶部保存现有本地连接配置;界面可覆盖本次连接参数,覆盖值不写入任务配置或日志。 +每个楼宇先计算一个**保证落在轮廓内部**的查询点:不用外包框中心或质心(凹形、L 形楼宇这两个点都可能落在轮廓外),而是用 `polylabel`(离边界最远的内部点,天然远离边缘);多部件轮廓取面积最大的部件,结果再用 `within` 校验,不通过时回退到 GEOS `representative_point`。无效 WKT 记为 `轮廓无效` 状态行。全量 435327 条轮廓校验:计算点全部落在轮廓内,单条约 0.25 ms。 + +脚本自动把 URL 中的 `CQL_FILTER` 替换成 `POINT(经度 纬度)` 点查询,坐标之间使用空格。输出表头包含 `输入行号`、`查询序号`(building_id)、查询点坐标、状态以及所有返回 `properties` 字段;一个楼宇命中多个要素时输出多行,未命中或失败时保留状态行。源表存在重复 `building_id`,用 `输入行号` 区分。脚本顶部保存现有本地连接配置;界面可覆盖本次连接参数,覆盖值不写入任务配置或日志。 `CONCURRENCY = 8` 控制并发查询协程数。网络请求共用连接池,完成后进入最多缓存 `CONCURRENCY × 2` 个结果的队列。唯一的写入线程按返回顺序逐次追加 CSV 并 `flush`,因此未查完也能看到已返回的数据;用查询序号关联原坐标,输出不保证输入顺序。若后续响应新增字段,写入线程会原子替换 CSV 以扩展表头并保留已有行。 -`REQUEST_INTERVAL` 是每个协程领取下一个坐标前的间隔。认证失败或按 Ctrl+C 时停止领取新坐标,正在处理的坐标和已入队结果会写完再退出。写文件失败会取消查询任务并报错,不会让队列永久等待。 - -本次取源表前 9 条及序号 `JM443411` 的坐标试跑,结果见 `output/NRBuildingsData_test10.csv`:7 条命中、3 条未命中、0 条请求失败。 +`REQUEST_INTERVAL` 是每个协程领取下一个楼宇前的间隔。认证失败或按 Ctrl+C 时停止领取新楼宇,正在处理的请求和已入队结果会写完再退出。写文件失败会取消查询任务并报错,不会让队列永久等待。 ## 运行方式 diff --git a/requirements-nr-buildings.txt b/requirements-nr-buildings.txt index 94b9fc9..5bc1343 100644 --- a/requirements-nr-buildings.txt +++ b/requirements-nr-buildings.txt @@ -1 +1,2 @@ aiohttp==3.14.3 +shapely==2.1.2 diff --git a/tests/test_nr_buildings.py b/tests/test_nr_buildings.py index 96a1c45..50bfc2f 100644 --- a/tests/test_nr_buildings.py +++ b/tests/test_nr_buildings.py @@ -11,9 +11,50 @@ from unittest.mock import patch from aiohttp import web from aiohttp.test_utils import TestServer +from shapely import wkt +from shapely.geometry import Point + import GetNRBuildingsData as script +def square(x, y, half=0.001): + return (f"MULTIPOLYGON ((({x - half} {y - half},{x + half} {y - half}," + f"{x + half} {y + half},{x - half} {y + half},{x - half} {y - half})))") + + +class InteriorPointTest(unittest.TestCase): + def test_point_lies_inside_concave_shapes_where_centroid_and_bbox_center_do_not(self): + # U 形:外包框中心与质心都落在缺口里。 + u_shape = ("POLYGON ((0 0, 10 0, 10 10, 7 10, 7 3, 3 3, 3 10, 0 10, 0 0))") + # L 形:外包框中心落在外面。 + l_shape = ("POLYGON ((0 0, 10 0, 10 2, 2 2, 2 10, 0 10, 0 0))") + for text in (u_shape, l_shape): + geometry = wkt.loads(text) + x1, y1, x2, y2 = geometry.bounds + self.assertFalse(Point((x1 + x2) / 2, (y1 + y2) / 2).within(geometry), text) + lon, lat = script.interior_point(text) + self.assertTrue(Point(float(lon), float(lat)).within(geometry), text) + + def test_multipolygon_uses_largest_part_and_invalid_input_is_rejected(self): + text = ("MULTIPOLYGON (((0 0, 1 0, 1 1, 0 1, 0 0)), ((5 5, 9 5, 9 9, 5 9, 5 5)))") + lon, lat = script.interior_point(text) + self.assertTrue(Point(float(lon), float(lat)).within(wkt.loads("POLYGON ((5 5, 9 5, 9 9, 5 9, 5 5))"))) + for bad in ("", "not wkt", "POINT (1 1)", "POLYGON EMPTY", None): + with self.assertRaises(ValueError): + script.interior_point(bad) + + def test_real_sample_rows_from_source_file(self): + path = Path(script.INPUT_CSV) + if not path.is_file(): + self.skipTest("源文件不存在") + with path.open(encoding=script.INPUT_ENCODING, newline="") as source: + reader = csv.DictReader(source) + for _, row in zip(range(200), reader): + geometry = wkt.loads(row["WKT"]) + lon, lat = script.interior_point(row["WKT"]) + self.assertTrue(Point(float(lon), float(lat)).within(geometry), row["building_id"]) + + class AsyncBuildingsTest(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): self.directory = tempfile.TemporaryDirectory() @@ -22,8 +63,9 @@ class AsyncBuildingsTest(unittest.IsolatedAsyncioTestCase): self.output = Path(self.directory.name) / "results.csv" with self.input.open("w", encoding="utf-8-sig", newline="") as destination: writer = csv.writer(destination) - writer.writerow(["序号", "经度", "维度"]) - writer.writerows([[str(i), str(i), "22"] for i in range(6)]) + writer.writerow(["WKT", "building_id"]) + # 以 (i, 22) 为中心的正方形,内部点应为 POINT(i 22)。 + writer.writerows([[square(i, 22), str(i)] for i in range(6)]) settings = patch.multiple(script, INPUT_CSV=self.input, OUTPUT_CSV=self.output, INPUT_ENCODING="utf-8-sig", URL="http://127.0.0.1/wfs", COOKIES="test-session", START_ROW=1, LIMIT=6, CONCURRENCY=3, REQUEST_INTERVAL=0, MAX_RETRIES=0) @@ -50,7 +92,7 @@ class AsyncBuildingsTest(unittest.IsolatedAsyncioTestCase): async def handler(request): nonlocal active, maximum - identifier = int(re.search(r"POINT\((\d+) 22\)", request.query["CQL_FILTER"]).group(1)) + identifier = round(float(re.search(r"POINT\(([-\d.]+) ([-\d.]+)\)", request.query["CQL_FILTER"]).group(1))) active += 1 maximum = max(maximum, active) try: diff --git a/tests/test_toolbox.py b/tests/test_toolbox.py index f22cab4..36dab03 100644 --- a/tests/test_toolbox.py +++ b/tests/test_toolbox.py @@ -50,11 +50,11 @@ class TaskIntegrationTest(unittest.TestCase): self.patch.start() self.addCleanup(self.patch.stop) self.addCleanup(self.temp.cleanup) - self.input = self.root / "坐标.csv" + self.input = self.root / "楼宇轮廓.csv" with self.input.open("w", encoding="utf-8-sig", newline="") as output: writer = csv.writer(output) - writer.writerow(["序号", "经度", "维度"]) - writer.writerows((i, 112+i/1000, 22) for i in range(30)) + writer.writerow(["WKT", "building_id"]) + writer.writerows((box(112 + i / 1000, 22, 112 + i / 1000 + 0.0005, 22.0005).wkt, f"JM{i}") for i in range(30)) self.params = {"INPUT_CSV": str(self.input), "INPUT_ENCODING": "utf-8-sig", "START_ROW": 1, "LIMIT": 30, "CONCURRENCY": 2, "TIMEOUT": 5, "MAX_RETRIES": 0, "REQUEST_INTERVAL": 0} diff --git a/toolbox/validation.py b/toolbox/validation.py index f2d9abc..5e551c4 100644 --- a/toolbox/validation.py +++ b/toolbox/validation.py @@ -64,7 +64,7 @@ def validate(kind, params): raise ValueError("查询参数无效。") with Path(params["INPUT_CSV"]).open(encoding=params["INPUT_ENCODING"], newline="") as source: reader = csv.DictReader(source) - if not {"序号", "经度", "维度"} <= set(reader.fieldnames or []): - raise ValueError("坐标 CSV 必须包含:序号、经度、维度。") + if not {"WKT", "building_id"} <= set(reader.fieldnames or []): + raise ValueError("楼宇轮廓 CSV 必须包含:WKT、building_id。") else: raise ValueError("未知工具。") diff --git a/ui/building_page.py b/ui/building_page.py index dd79916..f50e86c 100644 --- a/ui/building_page.py +++ b/ui/building_page.py @@ -6,13 +6,14 @@ from .task_panel import show_started, task_panel def render(): st.markdown("## 楼宇数据查询") - source = file_input("坐标清单", "source/NRBuildingsPoint.csv", "csv", "building_csv") + st.caption("按楼宇轮廓(WKT)查询:先计算落在轮廓内部的点,再按该点查询。") + source = file_input("楼宇轮廓清单", "source/NRBuildPolygon.csv", "csv", "building_csv") with st.form("building_run"): c1, c2, c3 = st.columns(3) start = c1.number_input("起始行", 1, value=1) limit = c2.number_input("查询数量(0 表示全部)", 0, value=1000) concurrency = c3.number_input("并发数", 1, 32, 8) - encoding = st.selectbox("文件编码", ["gb18030", "utf-8-sig"]) + encoding = st.selectbox("文件编码", ["utf-8-sig", "gb18030"]) st.markdown("**连接信息**(留空则使用脚本内默认配置)") url = st.text_input("服务地址", type="password", placeholder="https://...wfs?...ak=...&sig=...") cookies = st.text_input("登录信息", type="password", placeholder="CASTGC=...") @@ -25,7 +26,7 @@ def render(): if submitted: try: if not source: - raise ValueError("请先导入坐标文件。") + raise ValueError("请先导入楼宇轮廓文件。") override = bool(url.strip() or cookies.strip()) if override and (not url.strip().startswith(("http://", "https://")) or not cookies.strip()): raise ValueError("服务地址和登录信息需同时填写,且地址以 http(s):// 开头。")