feat: 楼宇查询改为按轮廓 WKT 计算内部点查询
This commit is contained in:
+54
-23
@@ -1,9 +1,11 @@
|
|||||||
"""异步批量查询楼宇 WFS,由独占写入线程实时保存 CSV。独立运行。"""
|
"""异步批量查询楼宇 WFS,由独占写入线程实时保存 CSV。独立运行。
|
||||||
|
|
||||||
|
输入为楼宇轮廓 WKT;每个楼宇先计算一个保证落在轮廓内部的查询点,再按点查询。
|
||||||
|
"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
import csv
|
import csv
|
||||||
from decimal import Decimal, InvalidOperation
|
|
||||||
from itertools import islice
|
from itertools import islice
|
||||||
import json
|
import json
|
||||||
from pathlib import Path
|
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 xml.etree.ElementTree as ET
|
||||||
|
|
||||||
import aiohttp
|
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 会自动替换。
|
# 填完整 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: 前缀。
|
# 填完整 Cookie 头内容,例如 CASTGC=...;不要加 Cookie: 前缀。
|
||||||
COOKIES = "CASTGC=TGT-1071858-toWWSoGzu8ASDB-dF69kh7rTnxZHt1nWd45MsLeTt0lHrzWC8n8Hwz3BjZjGRcIxbRkmas-auth-center-7d87cd5c9d-xd94d"
|
COOKIES = "CASTGC=TGT-1071858-toWWSoGzu8ASDB-dF69kh7rTnxZHt1nWd45MsLeTt0lHrzWC8n8Hwz3BjZjGRcIxbRkmas-auth-center-7d87cd5c9d-xd94d"
|
||||||
REFERER = "https://nqi.gmcc.net:20443/pro-problem-warehouse-web/"
|
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"
|
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。
|
OUTPUT_ENCODING = "gbk" # 供 Excel/传统工具直接打开;无法编码的字符用 errors=replace。
|
||||||
ID_COLUMN = "序号"
|
ID_COLUMN = "building_id"
|
||||||
LONGITUDE_COLUMN = "经度"
|
WKT_COLUMN = "WKT" # 楼宇轮廓,MULTIPOLYGON/POLYGON WKT,经纬度 EPSG:4326。
|
||||||
LATITUDE_COLUMN = "维度" # 源文件实际写的是“维度”。
|
|
||||||
GEOMETRY_FIELD = "the_geom"
|
GEOMETRY_FIELD = "the_geom"
|
||||||
START_ROW = 1 # 从第几条数据开始,不计表头。
|
START_ROW = 1 # 从第几条数据开始,不计表头。
|
||||||
LIMIT = 1000 # 最多查询的坐标数;None 表示处理剩余全部。
|
LIMIT = 1000 # 最多查询的坐标数;None 表示处理剩余全部。
|
||||||
@@ -36,7 +40,7 @@ TIMEOUT = 30 # 每次请求超时秒数。
|
|||||||
MAX_RETRIES = 2 # 网络异常、429 或 5xx 的重试次数;空结果不重试。
|
MAX_RETRIES = 2 # 网络异常、429 或 5xx 的重试次数;空结果不重试。
|
||||||
REQUEST_INTERVAL = 0.2 # 每个查询协程两次请求之间的等待秒数。
|
REQUEST_INTERVAL = 0.2 # 每个查询协程两次请求之间的等待秒数。
|
||||||
PROGRESS_EVERY = 100
|
PROGRESS_EVERY = 100
|
||||||
QUERY_COLUMNS = ["查询序号", "查询经度", "查询纬度", "查询状态", "命中数量", "要素ID", "错误信息"]
|
QUERY_COLUMNS = ["输入行号", "查询序号", "查询经度", "查询纬度", "查询状态", "命中数量", "要素ID", "错误信息"]
|
||||||
|
|
||||||
|
|
||||||
class QueryError(Exception):
|
class QueryError(Exception):
|
||||||
@@ -47,14 +51,39 @@ class AuthenticationError(QueryError):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def coordinate(value, lower, upper):
|
def interior_point(text):
|
||||||
|
"""返回一定位于轮廓内部的 (经度, 纬度) 字符串。
|
||||||
|
|
||||||
|
不使用外包框中心或质心:凹形、L 形楼宇的这两个点都可能落在轮廓外。
|
||||||
|
主方案是 polylabel(离边界最远的内部点,天然在图形内且远离边缘);
|
||||||
|
多部件时取面积最大的部件。计算结果再用 within 校验,不通过时回退到
|
||||||
|
GEOS 的 representative_point,它同样保证在几何内部。
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
number = Decimal(str(value).strip())
|
geometry = shapely_wkt.loads(str(text or "").strip())
|
||||||
except InvalidOperation:
|
except (ShapelyError, ValueError, TypeError):
|
||||||
raise ValueError("经纬度不是有效数字") from None
|
raise ValueError("WKT 无法解析") from None
|
||||||
if not number.is_finite() or not lower <= number <= upper:
|
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("经纬度超出有效范围")
|
raise ValueError("经纬度超出有效范围")
|
||||||
return format(number, "f")
|
return f"{point.x:.8f}", f"{point.y:.8f}"
|
||||||
|
|
||||||
|
|
||||||
def query_url(longitude, latitude):
|
def query_url(longitude, latitude):
|
||||||
@@ -201,15 +230,16 @@ async def async_main(*, handle_signals=True, should_stop=None, progress=None):
|
|||||||
request_stop()
|
request_stop()
|
||||||
break
|
break
|
||||||
# 同一事件循环中读取下一行,无 await,不会并发推进 CSV 迭代器。
|
# 同一事件循环中读取下一行,无 await,不会并发推进 CSV 迭代器。
|
||||||
point = next(selected, None)
|
item = next(selected, None)
|
||||||
if point is None:
|
if item is None:
|
||||||
break
|
break
|
||||||
metadata = {"查询序号": point.get(ID_COLUMN), "查询经度": point.get(LONGITUDE_COLUMN),
|
row_number, building = item
|
||||||
"查询纬度": point.get(LATITUDE_COLUMN), "命中数量": 0, "要素ID": "", "错误信息": ""}
|
metadata = {"输入行号": row_number, "查询序号": building.get(ID_COLUMN), "查询经度": "",
|
||||||
|
"查询纬度": "", "命中数量": 0, "要素ID": "", "错误信息": ""}
|
||||||
features = []
|
features = []
|
||||||
try:
|
try:
|
||||||
lon = coordinate(point.get(LONGITUDE_COLUMN), -180, 180)
|
lon, lat = interior_point(building.get(WKT_COLUMN))
|
||||||
lat = coordinate(point.get(LATITUDE_COLUMN), -90, 90)
|
metadata.update(查询经度=lon, 查询纬度=lat)
|
||||||
features = await fetch_features(session, lon, lat)
|
features = await fetch_features(session, lon, lat)
|
||||||
if any(set(feature["properties"]) & set(QUERY_COLUMNS) for feature in features):
|
if any(set(feature["properties"]) & set(QUERY_COLUMNS) for feature in features):
|
||||||
raise QueryError("properties 字段与查询信息列重名")
|
raise QueryError("properties 字段与查询信息列重名")
|
||||||
@@ -217,7 +247,7 @@ async def async_main(*, handle_signals=True, should_stop=None, progress=None):
|
|||||||
metadata["命中数量"] = len(features)
|
metadata["命中数量"] = len(features)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
features = []
|
features = []
|
||||||
metadata.update(查询状态="坐标无效", 错误信息=str(exc))
|
metadata.update(查询状态="轮廓无效", 错误信息=str(exc))
|
||||||
except QueryError as exc:
|
except QueryError as exc:
|
||||||
features = []
|
features = []
|
||||||
metadata.update(查询状态="请求失败", 错误信息=str(exc))
|
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:
|
with input_path.open("r", encoding=INPUT_ENCODING, newline="") as source:
|
||||||
reader = csv.DictReader(source)
|
reader = csv.DictReader(source)
|
||||||
required = {ID_COLUMN, LONGITUDE_COLUMN, LATITUDE_COLUMN}
|
required = {ID_COLUMN, WKT_COLUMN}
|
||||||
if not required.issubset(reader.fieldnames or []):
|
if not required.issubset(reader.fieldnames or []):
|
||||||
raise ValueError(f"输入 CSV 必须包含列:{', '.join(sorted(required))}")
|
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
|
old_signal_handler = None
|
||||||
if handle_signals:
|
if handle_signals:
|
||||||
old_signal_handler = signal.signal(signal.SIGINT, lambda *_: loop.call_soon_threadsafe(request_stop))
|
old_signal_handler = signal.signal(signal.SIGINT, lambda *_: loop.call_soon_threadsafe(request_stop))
|
||||||
|
|||||||
@@ -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`。
|
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` 可指定起始数据行。
|
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 以扩展表头并保留已有行。
|
`CONCURRENCY = 8` 控制并发查询协程数。网络请求共用连接池,完成后进入最多缓存 `CONCURRENCY × 2` 个结果的队列。唯一的写入线程按返回顺序逐次追加 CSV 并 `flush`,因此未查完也能看到已返回的数据;用查询序号关联原坐标,输出不保证输入顺序。若后续响应新增字段,写入线程会原子替换 CSV 以扩展表头并保留已有行。
|
||||||
|
|
||||||
`REQUEST_INTERVAL` 是每个协程领取下一个坐标前的间隔。认证失败或按 Ctrl+C 时停止领取新坐标,正在处理的坐标和已入队结果会写完再退出。写文件失败会取消查询任务并报错,不会让队列永久等待。
|
`REQUEST_INTERVAL` 是每个协程领取下一个楼宇前的间隔。认证失败或按 Ctrl+C 时停止领取新楼宇,正在处理的请求和已入队结果会写完再退出。写文件失败会取消查询任务并报错,不会让队列永久等待。
|
||||||
|
|
||||||
本次取源表前 9 条及序号 `JM443411` 的坐标试跑,结果见 `output/NRBuildingsData_test10.csv`:7 条命中、3 条未命中、0 条请求失败。
|
|
||||||
|
|
||||||
## 运行方式
|
## 运行方式
|
||||||
|
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
aiohttp==3.14.3
|
aiohttp==3.14.3
|
||||||
|
shapely==2.1.2
|
||||||
|
|||||||
@@ -11,9 +11,50 @@ from unittest.mock import patch
|
|||||||
from aiohttp import web
|
from aiohttp import web
|
||||||
from aiohttp.test_utils import TestServer
|
from aiohttp.test_utils import TestServer
|
||||||
|
|
||||||
|
from shapely import wkt
|
||||||
|
from shapely.geometry import Point
|
||||||
|
|
||||||
import GetNRBuildingsData as script
|
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):
|
class AsyncBuildingsTest(unittest.IsolatedAsyncioTestCase):
|
||||||
async def asyncSetUp(self):
|
async def asyncSetUp(self):
|
||||||
self.directory = tempfile.TemporaryDirectory()
|
self.directory = tempfile.TemporaryDirectory()
|
||||||
@@ -22,8 +63,9 @@ class AsyncBuildingsTest(unittest.IsolatedAsyncioTestCase):
|
|||||||
self.output = Path(self.directory.name) / "results.csv"
|
self.output = Path(self.directory.name) / "results.csv"
|
||||||
with self.input.open("w", encoding="utf-8-sig", newline="") as destination:
|
with self.input.open("w", encoding="utf-8-sig", newline="") as destination:
|
||||||
writer = csv.writer(destination)
|
writer = csv.writer(destination)
|
||||||
writer.writerow(["序号", "经度", "维度"])
|
writer.writerow(["WKT", "building_id"])
|
||||||
writer.writerows([[str(i), str(i), "22"] for i in range(6)])
|
# 以 (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,
|
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",
|
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)
|
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):
|
async def handler(request):
|
||||||
nonlocal active, maximum
|
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
|
active += 1
|
||||||
maximum = max(maximum, active)
|
maximum = max(maximum, active)
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -50,11 +50,11 @@ class TaskIntegrationTest(unittest.TestCase):
|
|||||||
self.patch.start()
|
self.patch.start()
|
||||||
self.addCleanup(self.patch.stop)
|
self.addCleanup(self.patch.stop)
|
||||||
self.addCleanup(self.temp.cleanup)
|
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:
|
with self.input.open("w", encoding="utf-8-sig", newline="") as output:
|
||||||
writer = csv.writer(output)
|
writer = csv.writer(output)
|
||||||
writer.writerow(["序号", "经度", "维度"])
|
writer.writerow(["WKT", "building_id"])
|
||||||
writer.writerows((i, 112+i/1000, 22) for i in range(30))
|
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,
|
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}
|
"LIMIT": 30, "CONCURRENCY": 2, "TIMEOUT": 5, "MAX_RETRIES": 0, "REQUEST_INTERVAL": 0}
|
||||||
|
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ def validate(kind, params):
|
|||||||
raise ValueError("查询参数无效。")
|
raise ValueError("查询参数无效。")
|
||||||
with Path(params["INPUT_CSV"]).open(encoding=params["INPUT_ENCODING"], newline="") as source:
|
with Path(params["INPUT_CSV"]).open(encoding=params["INPUT_ENCODING"], newline="") as source:
|
||||||
reader = csv.DictReader(source)
|
reader = csv.DictReader(source)
|
||||||
if not {"序号", "经度", "维度"} <= set(reader.fieldnames or []):
|
if not {"WKT", "building_id"} <= set(reader.fieldnames or []):
|
||||||
raise ValueError("坐标 CSV 必须包含:序号、经度、维度。")
|
raise ValueError("楼宇轮廓 CSV 必须包含:WKT、building_id。")
|
||||||
else:
|
else:
|
||||||
raise ValueError("未知工具。")
|
raise ValueError("未知工具。")
|
||||||
|
|||||||
+4
-3
@@ -6,13 +6,14 @@ from .task_panel import show_started, task_panel
|
|||||||
|
|
||||||
def render():
|
def render():
|
||||||
st.markdown("## 楼宇数据查询")
|
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"):
|
with st.form("building_run"):
|
||||||
c1, c2, c3 = st.columns(3)
|
c1, c2, c3 = st.columns(3)
|
||||||
start = c1.number_input("起始行", 1, value=1)
|
start = c1.number_input("起始行", 1, value=1)
|
||||||
limit = c2.number_input("查询数量(0 表示全部)", 0, value=1000)
|
limit = c2.number_input("查询数量(0 表示全部)", 0, value=1000)
|
||||||
concurrency = c3.number_input("并发数", 1, 32, 8)
|
concurrency = c3.number_input("并发数", 1, 32, 8)
|
||||||
encoding = st.selectbox("文件编码", ["gb18030", "utf-8-sig"])
|
encoding = st.selectbox("文件编码", ["utf-8-sig", "gb18030"])
|
||||||
st.markdown("**连接信息**(留空则使用脚本内默认配置)")
|
st.markdown("**连接信息**(留空则使用脚本内默认配置)")
|
||||||
url = st.text_input("服务地址", type="password", placeholder="https://...wfs?...ak=...&sig=...")
|
url = st.text_input("服务地址", type="password", placeholder="https://...wfs?...ak=...&sig=...")
|
||||||
cookies = st.text_input("登录信息", type="password", placeholder="CASTGC=...")
|
cookies = st.text_input("登录信息", type="password", placeholder="CASTGC=...")
|
||||||
@@ -25,7 +26,7 @@ def render():
|
|||||||
if submitted:
|
if submitted:
|
||||||
try:
|
try:
|
||||||
if not source:
|
if not source:
|
||||||
raise ValueError("请先导入坐标文件。")
|
raise ValueError("请先导入楼宇轮廓文件。")
|
||||||
override = bool(url.strip() or cookies.strip())
|
override = bool(url.strip() or cookies.strip())
|
||||||
if override and (not url.strip().startswith(("http://", "https://")) or not cookies.strip()):
|
if override and (not url.strip().startswith(("http://", "https://")) or not cookies.strip()):
|
||||||
raise ValueError("服务地址和登录信息需同时填写,且地址以 http(s):// 开头。")
|
raise ValueError("服务地址和登录信息需同时填写,且地址以 http(s):// 开头。")
|
||||||
|
|||||||
Reference in New Issue
Block a user