From e96eed0f6c38c28c8a85eb89ad7ade47c0001c01 Mon Sep 17 00:00:00 2001 From: nixevol Date: Thu, 17 Sep 2026 09:38:22 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=A5=BC=E5=AE=87=E8=BD=AE=E5=BB=93=20?= =?UTF-8?q?CSV=20=E6=8C=89=E5=86=85=E5=AE=B9=E8=87=AA=E5=8A=A8=E8=AF=86?= =?UTF-8?q?=E5=88=AB=E7=BC=96=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- GetNRBuildingsData.py | 46 ++++++++++++++++++++++++++++++++++---- README.md | 2 +- tests/test_nr_buildings.py | 27 +++++++++++++++++++++- toolbox/validation.py | 12 +++------- ui/building_page.py | 2 +- 5 files changed, 73 insertions(+), 16 deletions(-) diff --git a/GetNRBuildingsData.py b/GetNRBuildingsData.py index 69f5e86..5b69bed 100644 --- a/GetNRBuildingsData.py +++ b/GetNRBuildingsData.py @@ -51,6 +51,44 @@ class AuthenticationError(QueryError): pass +ENCODING_CANDIDATES = ("gbk", "utf-8-sig") + + +def detect_encoding(path, preferred=None, required=(ID_COLUMN, WKT_COLUMN)): + """按文件内容自动判定编码,返回能读出必需表头的编码。 + + GBK 对 UTF-8 字节流很宽容,会“成功”解出乱码,所以不能只靠解码是否报错: + 样本含非 ASCII 且能通过严格 UTF-8 解码就判为 UTF-8,否则判为 GBK; + 纯 ASCII 样本两种编码等价,沿用首选编码。判定结果读不出表头时再试其余候选。 + """ + path = Path(path) + with path.open("rb") as raw: + head = raw.read(1024 * 1024) + # 只按最后一个换行截断,避免样本末尾切断多字节字符造成误判。 + sample = head[:head.rfind(b"\n") + 1] or head + order = [] + if head.startswith(b"\xef\xbb\xbf"): + order.append("utf-8-sig") + elif not sample.isascii(): + try: + sample.decode("utf-8") + order.append("utf-8-sig") + except UnicodeDecodeError: + order.append("gbk") + if preferred and preferred not in order: + order.append(preferred) + order.extend(candidate for candidate in ENCODING_CANDIDATES if candidate not in order) + for encoding in order: + try: + text = sample.decode(encoding) + except (UnicodeDecodeError, LookupError): + continue + fieldnames = next(csv.reader(text.splitlines()[:1]), []) + if set(required) <= set(fieldnames): + return encoding + raise ValueError(f"无法按 {'/'.join(order)} 读取表头,输入 CSV 必须包含列:{', '.join(required)}") + + def interior_point(text): """返回一定位于轮廓内部的 (经度, 纬度) 字符串。 @@ -281,11 +319,11 @@ async def async_main(*, handle_signals=True, should_stop=None, progress=None): finally: await loop.run_in_executor(executor, writer.close) - with input_path.open("r", encoding=INPUT_ENCODING, newline="") as source: + encoding = detect_encoding(input_path, INPUT_ENCODING) + if encoding != INPUT_ENCODING: + print(f"输入文件按 {encoding} 读取(首选 {INPUT_ENCODING} 无法识别表头)", flush=True) + with input_path.open("r", encoding=encoding, newline="") as source: reader = csv.DictReader(source) - required = {ID_COLUMN, WKT_COLUMN} - if not required.issubset(reader.fieldnames or []): - raise ValueError(f"输入 CSV 必须包含列:{', '.join(sorted(required))}") # 输入行号从 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 diff --git a/README.md b/README.md index 0985a92..25864e6 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ AOI 最大重叠面积匹配的预处理不在当前仓库内,界面直接使 `GetNRBuildingsData.py` 独立运行,不调用 `main.py`。先运行 `python -m pip install -r requirements-nr-buildings.txt` 安装依赖 `aiohttp` 和 `shapely`。 1. 在脚本顶部填写完整 WFS `URL`(含 `ak`、`sig` 等原参数)和 `COOKIES`。 -2. 默认读取 `source/NRBuildPolygon.csv`,使用 `WKT`(楼宇轮廓,`MULTIPOLYGON`/`POLYGON`,EPSG:4326)和 `building_id` 两列,输入编码默认 GBK(UTF-8 BOM 文件把 `INPUT_ENCODING` 或界面“文件编码”改为 `utf-8-sig`)。 +2. 默认读取 `source/NRBuildPolygon.csv`,使用 `WKT`(楼宇轮廓,`MULTIPOLYGON`/`POLYGON`,EPSG:4326)和 `building_id` 两列,输入编码按内容自动判定(含 BOM 或能通过严格 UTF-8 解码即 UTF-8,否则 GBK;纯 ASCII 沿用默认 GBK),读不出 `WKT`/`building_id` 表头才报错。 3. 运行 `python GetNRBuildingsData.py`,当前 `LIMIT = 1000`,输出 `output/NRBuildingsData.csv`(GBK 编码)。将 `LIMIT` 改为 `None` 可查询剩余全部;`START_ROW` 可指定起始数据行。 每个楼宇先计算一个**保证落在轮廓内部**的查询点:不用外包框中心或质心(凹形、L 形楼宇这两个点都可能落在轮廓外),而是用 `polylabel`(离边界最远的内部点,天然远离边缘);多部件轮廓取面积最大的部件,结果再用 `within` 校验,不通过时回退到 GEOS `representative_point`。无效 WKT 记为 `轮廓无效` 状态行。全量 435327 条轮廓校验:计算点全部落在轮廓内,单条约 0.25 ms。 diff --git a/tests/test_nr_buildings.py b/tests/test_nr_buildings.py index c527a9b..de2af03 100644 --- a/tests/test_nr_buildings.py +++ b/tests/test_nr_buildings.py @@ -43,11 +43,36 @@ class InteriorPointTest(unittest.TestCase): with self.assertRaises(ValueError): script.interior_point(bad) + def test_detect_encoding_falls_back_between_gbk_and_utf8(self): + with tempfile.TemporaryDirectory() as directory: + row = "WKT,building_id\n\"POLYGON ((0 0,1 0,1 1,0 0))\",甲楼\n" + utf8_bom = Path(directory) / "utf8_bom.csv" + utf8_bom.write_text(row, encoding="utf-8-sig") + utf8 = Path(directory) / "utf8.csv" + utf8.write_text(row, encoding="utf-8") + gbk = Path(directory) / "gbk.csv" + gbk.write_text(row, encoding="gbk") + ascii_only = Path(directory) / "ascii.csv" + ascii_only.write_text("WKT,building_id\n\"POLYGON ((0 0,1 0,1 1,0 0))\",JM1\n", encoding="ascii") + other = Path(directory) / "other.csv" + other.write_text("序号,经度\n1,2\n", encoding="gbk") + # 首选 gbk 但内容是 UTF-8(含/不含 BOM)时自动切换,反之亦然。 + self.assertEqual(script.detect_encoding(utf8_bom, "gbk"), "utf-8-sig") + self.assertEqual(script.detect_encoding(utf8, "gbk"), "utf-8-sig") + self.assertEqual(script.detect_encoding(gbk, "utf-8-sig"), "gbk") + self.assertEqual(script.detect_encoding(gbk, "gbk"), "gbk") + self.assertEqual(script.detect_encoding(ascii_only, "gbk"), "gbk") + self.assertEqual(script.detect_encoding(ascii_only, "utf-8-sig"), "utf-8-sig") + with self.assertRaisesRegex(ValueError, "building_id"): + script.detect_encoding(other, "gbk") + with utf8.open(encoding=script.detect_encoding(utf8, "gbk"), newline="") as source: + self.assertEqual(list(csv.DictReader(source))[0]["building_id"], "甲楼") + 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="utf-8-sig", newline="") as source: # 当前源文件为 UTF-8 BOM + with path.open(encoding=script.detect_encoding(path, script.INPUT_ENCODING), newline="") as source: reader = csv.DictReader(source) for _, row in zip(range(200), reader): geometry = wkt.loads(row["WKT"]) diff --git a/toolbox/validation.py b/toolbox/validation.py index 815c575..b6a9d25 100644 --- a/toolbox/validation.py +++ b/toolbox/validation.py @@ -1,5 +1,4 @@ """界面启动前验证输入,避免无效任务覆盖现有数据。""" -import csv from pathlib import Path import zipfile @@ -62,13 +61,8 @@ def validate(kind, params): raise ValueError("起始行和查询数量必须大于零。") if params["CONCURRENCY"] < 1 or params["TIMEOUT"] <= 0 or params["MAX_RETRIES"] < 0 or params["REQUEST_INTERVAL"] < 0: raise ValueError("查询参数无效。") - try: - with Path(params["INPUT_CSV"]).open(encoding=params["INPUT_ENCODING"], newline="") as source: - reader = csv.DictReader(source) - header = set(reader.fieldnames or []) - except UnicodeDecodeError: - raise ValueError(f"文件不是 {params['INPUT_ENCODING']} 编码,请切换文件编码。") from None - if not {"WKT", "building_id"} <= header: - raise ValueError("楼宇轮廓 CSV 必须包含:WKT、building_id;若表头显示乱码请切换文件编码。") + from GetNRBuildingsData import detect_encoding + # 首选编码读不出表头时自动切换;两种都不行才报错。实际编码写回参数供任务进程使用。 + params["INPUT_ENCODING"] = detect_encoding(params["INPUT_CSV"], params["INPUT_ENCODING"]) else: raise ValueError("未知工具。") diff --git a/ui/building_page.py b/ui/building_page.py index 4f4483d..6638400 100644 --- a/ui/building_page.py +++ b/ui/building_page.py @@ -35,7 +35,7 @@ def render(): 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("文件编码", ["gbk", "utf-8-sig"]) + encoding = st.selectbox("文件编码(按内容自动识别,识别不出时按此项)", ["gbk", "utf-8-sig"]) st.markdown("**连接信息**(填写后保存到本地,下次自动读取;留空则使用脚本内默认配置)") url = st.text_input("服务地址", value=saved["URL"], placeholder="https://...wfs?...ak=...&sig=...") cookies = st.text_input("登录信息(Cookies)", value=saved["COOKIES"], placeholder="CASTGC=...")