feat: 新增模块化Streamlit本地工具箱
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""本地工具箱任务与成果服务。"""
|
||||
@@ -0,0 +1,87 @@
|
||||
"""按需读取成果;大栅格通过磁盘映射降采样预览。"""
|
||||
from contextlib import contextmanager
|
||||
import csv
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
import shapely
|
||||
import tifffile
|
||||
from marketgrid import gpkg
|
||||
|
||||
|
||||
def csv_preview(path, encoding="utf-8-sig", limit=500):
|
||||
with Path(path).open(encoding=encoding, newline="") as source:
|
||||
reader = csv.DictReader(source)
|
||||
rows = []
|
||||
for index, row in enumerate(reader):
|
||||
if index >= limit:
|
||||
return rows, True
|
||||
rows.append(row)
|
||||
return rows, False
|
||||
|
||||
|
||||
def qgis_layers(path):
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
projects = [n for n in archive.namelist() if n.lower().endswith(".qgs")]
|
||||
if len(projects) != 1:
|
||||
raise ValueError("QGZ 必须包含一个 .qgs 工程。")
|
||||
name = projects[0]
|
||||
root = ET.fromstring(archive.read(name))
|
||||
checked = {n.get("id"): n.get("checked") for n in root.findall(".//layer-tree-layer")}
|
||||
return [{"图层": layer.findtext("layername"), "类型": layer.get("type"),
|
||||
"默认显示": checked.get(layer.findtext("id")) == "Qt::Checked"}
|
||||
for layer in root.findall("./projectlayers/maplayer")]
|
||||
|
||||
|
||||
def raster_preview(path, max_side=1400):
|
||||
with tifffile.TiffFile(path) as source:
|
||||
page = source.pages[0]
|
||||
height, width = page.shape[:2]
|
||||
metadata = {"宽": width, "高": height, "数据类型": str(page.dtype), "通道": page.samplesperpixel}
|
||||
for name in ("ModelPixelScaleTag", "ModelTiepointTag", "GeoKeyDirectoryTag"):
|
||||
if name in page.tags:
|
||||
metadata[name] = list(page.tags[name].value)
|
||||
# 当前生成的 TIFF 未压缩,可以直接 memmap,不把原图完整载入内存。
|
||||
data = tifffile.memmap(path, mode="r")
|
||||
step = max(1, int(np.ceil(max(height, width) / max_side)))
|
||||
image = Image.fromarray(np.array(data[::step, ::step]))
|
||||
del data
|
||||
return image, metadata
|
||||
|
||||
|
||||
def gpkg_preview(path, limit=300):
|
||||
with gpkg.open_read_connection(Path(path)) as conn:
|
||||
layer = gpkg.resolve_feature_layer(conn)
|
||||
table = gpkg.quote_identifier(layer.table_name)
|
||||
total = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
|
||||
columns = gpkg.table_columns(conn, layer.table_name)
|
||||
rows = conn.execute(f"SELECT * FROM {table} LIMIT ?", (limit,)).fetchall()
|
||||
records, features = [], []
|
||||
for row in rows:
|
||||
record = dict(zip(columns, row))
|
||||
blob = record.pop(layer.geom_col)
|
||||
records.append({k: str(v) if isinstance(v, bytes) else v for k, v in record.items()})
|
||||
if blob:
|
||||
geometry = shapely.from_wkb(gpkg.gpkg_blob_to_wkb(blob))
|
||||
if not geometry.is_empty:
|
||||
features.append({"type": "Feature", "geometry": json.loads(shapely.to_geojson(geometry)),
|
||||
"properties": {"名称": str(record.get("name", record.get("AOI名称", record.get("Name", ""))))}})
|
||||
return records, features, {"图层": layer.table_name, "总要素": total, "坐标系": layer.srs_id, "预览上限": limit}
|
||||
|
||||
|
||||
@contextmanager
|
||||
def zip_member(path, member):
|
||||
with zipfile.ZipFile(path) as archive, tempfile.TemporaryDirectory(prefix="marketgrid_preview_") as temp:
|
||||
info = archive.getinfo(member)
|
||||
if info.file_size > 1024**3:
|
||||
raise ValueError("该成员超过 1 GB,请下载后使用 QGIS 查看。")
|
||||
target = Path(temp) / Path(member).name
|
||||
with archive.open(info) as source, target.open("wb") as output:
|
||||
shutil.copyfileobj(source, output, length=8 * 1024 * 1024)
|
||||
yield target
|
||||
@@ -0,0 +1,122 @@
|
||||
"""文件持久化任务记录;任务进程独立于浏览器会话。"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from filelock import FileLock
|
||||
import psutil
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TASKS = ROOT / "output" / "toolbox" / "tasks"
|
||||
ACTIVE = {"queued", "running"}
|
||||
LABELS = {"queued": "启动中", "running": "运行中", "success": "已完成",
|
||||
"failed": "失败", "cancelled": "已停止", "interrupted": "意外中断"}
|
||||
KINDS = {"market": "市场网格出图", "buildings": "楼宇数据查询"}
|
||||
|
||||
|
||||
def write_json(path, value):
|
||||
path = Path(path)
|
||||
temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
|
||||
try:
|
||||
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
for attempt in range(20):
|
||||
try:
|
||||
temporary.replace(path)
|
||||
break
|
||||
except PermissionError:
|
||||
if attempt == 19:
|
||||
raise
|
||||
time.sleep(0.05)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def alive(state):
|
||||
try:
|
||||
process = psutil.Process(state["pid"])
|
||||
return (abs(process.create_time() - state["process_created"]) < 0.1
|
||||
and process.is_running() and process.status() != psutil.STATUS_ZOMBIE)
|
||||
except (KeyError, ValueError, psutil.Error):
|
||||
return False
|
||||
|
||||
|
||||
def read_task(directory):
|
||||
directory = Path(directory)
|
||||
state = json.loads((directory / "state.json").read_text(encoding="utf-8"))
|
||||
if state["status"] in ACTIVE and not alive(state):
|
||||
if time.time() - state["created"] > 15:
|
||||
# 不写回,避免与刚完成的 worker 原子更新发生竞争。
|
||||
state = {**state, "status": "interrupted", "message": "任务进程已退出,已完成文件保留。"}
|
||||
state["stop_requested"] = (directory / "stop").exists()
|
||||
return state
|
||||
|
||||
|
||||
def list_tasks():
|
||||
if not TASKS.exists():
|
||||
return []
|
||||
return [read_task(p.parent) for p in sorted(TASKS.glob("*/state.json"), reverse=True)]
|
||||
|
||||
|
||||
def start_task(kind, params, credentials=None):
|
||||
from .validation import validate
|
||||
validate(kind, params)
|
||||
TASKS.mkdir(parents=True, exist_ok=True)
|
||||
with FileLock(str(TASKS / ".launch.lock"), timeout=10):
|
||||
if any(t["status"] in ACTIVE for t in list_tasks()):
|
||||
raise ValueError("已有任务正在运行,请等待完成或到任务中心停止它。")
|
||||
task_id = time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]
|
||||
directory = TASKS / task_id
|
||||
directory.mkdir()
|
||||
output = directory / "results"
|
||||
output.mkdir()
|
||||
state = {"id": task_id, "kind": kind, "status": "queued", "created": time.time(),
|
||||
"output": str(output), "params": params, "done": 0, "total": 0,
|
||||
"message": "正在启动", "directory": str(directory)}
|
||||
write_json(directory / "state.json", state)
|
||||
process = None
|
||||
try:
|
||||
env = {**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"}
|
||||
flags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
|
||||
with (directory / "task.log").open("wb") as log:
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, "-u", "-m", "toolbox.worker", str(directory)],
|
||||
cwd=ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT,
|
||||
env=env, creationflags=flags,
|
||||
)
|
||||
state.update(pid=process.pid, process_created=psutil.Process(process.pid).create_time())
|
||||
write_json(directory / "state.json", state)
|
||||
# 凭据只经标准输入传给独立任务进程,不写配置文件或命令行。
|
||||
process.stdin.write(json.dumps(credentials or {}).encode("utf-8"))
|
||||
process.stdin.close()
|
||||
threading.Thread(target=process.wait, daemon=True, name=f"wait-{task_id}").start()
|
||||
except Exception:
|
||||
if process is not None:
|
||||
if process.stdin and not process.stdin.closed:
|
||||
process.stdin.close()
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(timeout=10)
|
||||
state.update(status="failed", message="任务进程启动失败", finished=time.time())
|
||||
write_json(directory / "state.json", state)
|
||||
raise
|
||||
return task_id
|
||||
|
||||
|
||||
def stop_task(task_id):
|
||||
directory = TASKS / task_id
|
||||
if read_task(directory)["status"] in ACTIVE:
|
||||
(directory / "stop").touch()
|
||||
|
||||
|
||||
def tail_log(directory, max_bytes=24000):
|
||||
path = Path(directory) / "task.log"
|
||||
if not path.exists():
|
||||
return "等待任务输出……"
|
||||
with path.open("rb") as source:
|
||||
source.seek(max(0, path.stat().st_size - max_bytes))
|
||||
return source.read().decode("utf-8", errors="replace")
|
||||
@@ -0,0 +1,70 @@
|
||||
"""界面启动前验证输入,避免无效任务覆盖现有数据。"""
|
||||
import csv
|
||||
from pathlib import Path
|
||||
import zipfile
|
||||
|
||||
from marketgrid import config, gpkg
|
||||
|
||||
SOURCES = {
|
||||
"MARKET_GPKG": ("市场边界", "source/GridMap.gpkg", "gpkg"),
|
||||
"GRID_5G_GPKG": ("5G Grid", "source/Grid_5G.gpkg", "gpkg"),
|
||||
"BUILDING_INFO_GPKG": ("建筑信息", "source/BuildingInfo.gpkg", "gpkg"),
|
||||
"AOI_GPKG": ("已匹配市场的 AOI", "output/AOI级报表_市场网格匹配.gpkg", "gpkg"),
|
||||
"CELL_DATA_GPKG": ("小区数据(汇总包使用)", "source/CellData.gpkg", "gpkg"),
|
||||
"GIS_PROJECT_SOURCE": ("QGIS 工程模板", "source/GIS.qgz", "qgz"),
|
||||
}
|
||||
|
||||
|
||||
def market_options(path):
|
||||
with gpkg.open_read_connection(Path(path)) as conn:
|
||||
layer = gpkg.resolve_feature_layer(conn)
|
||||
gpkg.require_columns(conn, layer.table_name, [config.MARKET_CODE_FIELD, config.MARKET_NAME_FIELD])
|
||||
return [(int(row[0]), str(row[1])) for row in conn.execute(
|
||||
f'SELECT "fid", "Name" FROM {gpkg.quote_identifier(layer.table_name)} ORDER BY "fid"')]
|
||||
|
||||
|
||||
def validate(kind, params):
|
||||
if kind == "market":
|
||||
for key, (label, _, suffix) in SOURCES.items():
|
||||
if key == "CELL_DATA_GPKG" and not params["SUMMARY_OUTPUT_ENABLED"]:
|
||||
continue
|
||||
path = Path(params[key])
|
||||
if not path.is_file():
|
||||
raise ValueError(f"{label}文件不存在:{path}")
|
||||
if suffix == "gpkg":
|
||||
with gpkg.open_read_connection(path) as conn:
|
||||
layer = gpkg.resolve_feature_layer(conn, config.AOI_LAYER if key == "AOI_GPKG" else None)
|
||||
if key != "CELL_DATA_GPKG":
|
||||
allowed = config.BUILDING_INFO_ALLOWED_SRS_IDS if key == "BUILDING_INFO_GPKG" else (4326,)
|
||||
if layer.srs_id not in allowed:
|
||||
raise ValueError(f"{label}坐标系不支持:{layer.srs_id}")
|
||||
if key in {"GRID_5G_GPKG", "BUILDING_INFO_GPKG", "AOI_GPKG"}:
|
||||
gpkg.rtree_name(conn, layer)
|
||||
fields = {
|
||||
"MARKET_GPKG": ["fid", "Name"], "BUILDING_INFO_GPKG": ["name"],
|
||||
"AOI_GPKG": [config.AOI_MARKET_FIELD, "AOI唯一标签", "AOI名称"],
|
||||
"GRID_5G_GPKG": [*config.CSV_SOURCE_FIELDS, config.MOBILE_TOTAL_FIELD, config.MOBILE_WEAK_COVER_FIELD],
|
||||
}.get(key, [])
|
||||
gpkg.require_columns(conn, layer.table_name, fields)
|
||||
else:
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
if len([n for n in archive.namelist() if n.lower().endswith(".qgs")]) != 1:
|
||||
raise ValueError("QGIS 模板必须包含一个 .qgs 工程。")
|
||||
if not params.get("SELECTED_MARKET_IDS"):
|
||||
raise ValueError("请至少选择一个市场网格。")
|
||||
if not set(params["SELECTED_MARKET_IDS"]) <= {i for i, _ in market_options(params["MARKET_GPKG"])}:
|
||||
raise ValueError("市场选择已过期,请重新选择。")
|
||||
for key in ("SCALE", "MAX_WORKERS", "MAX_RASTER_PIXELS", "SUMMARY_MAX_RASTER_PIXELS"):
|
||||
if params[key] <= 0:
|
||||
raise ValueError(f"{key} 必须大于零。")
|
||||
elif kind == "buildings":
|
||||
if params["START_ROW"] < 1 or (params["LIMIT"] is not None and params["LIMIT"] < 1):
|
||||
raise ValueError("起始行和查询数量必须大于零。")
|
||||
if params["CONCURRENCY"] < 1 or params["TIMEOUT"] <= 0 or params["MAX_RETRIES"] < 0 or params["REQUEST_INTERVAL"] < 0:
|
||||
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 必须包含:序号、经度、维度。")
|
||||
else:
|
||||
raise ValueError("未知工具。")
|
||||
@@ -0,0 +1,78 @@
|
||||
"""独立任务入口。刷新界面或切换页面不会重新启动计算。"""
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
from .tasks import write_json
|
||||
from marketgrid.config import TaskCancelled
|
||||
|
||||
|
||||
def run(directory, credentials):
|
||||
directory = Path(directory)
|
||||
path = directory / "state.json"
|
||||
state = json.loads(path.read_text(encoding="utf-8"))
|
||||
state.update(status="running", message="开始处理", started=time.time())
|
||||
write_json(path, state)
|
||||
def progress(done, total, message, **extra):
|
||||
state.update(done=done, total=total, message=message, **extra)
|
||||
write_json(path, state)
|
||||
def stopping():
|
||||
return (directory / "stop").exists()
|
||||
try:
|
||||
if stopping():
|
||||
raise TaskCancelled("启动前已停止。")
|
||||
if state["kind"] == "market":
|
||||
from marketgrid.pipeline import main
|
||||
settings = {**state["params"], "OUTPUT_DIR": state["output"],
|
||||
"STOP_FILE": str(directory / "stop"), "OVERWRITE": True, "LIMIT": None}
|
||||
main(settings, progress)
|
||||
else:
|
||||
import GetNRBuildingsData as query
|
||||
for key, value in state["params"].items():
|
||||
setattr(query, key, value)
|
||||
for key in ("URL", "COOKIES", "REFERER"):
|
||||
if key in credentials:
|
||||
setattr(query, key, credentials[key])
|
||||
query.OUTPUT_CSV = Path(state["output"]) / "NRBuildingsData.csv"
|
||||
last = 0
|
||||
def report(counts):
|
||||
nonlocal last
|
||||
now = time.monotonic()
|
||||
state["counts"] = counts
|
||||
state["done"] = counts["查询坐标"]
|
||||
if now - last >= 0.5:
|
||||
progress(counts["查询坐标"], query.LIMIT or 0, "正在查询楼宇", counts=counts)
|
||||
last = now
|
||||
result = asyncio.run(query.async_main(handle_signals=False, should_stop=stopping, progress=report))
|
||||
if stopping():
|
||||
raise TaskCancelled("已停止领取新坐标,进行中的查询和写入已完成。")
|
||||
if result:
|
||||
raise ValueError("部分查询失败或认证失效,已保存返回结果,请查看日志和 CSV 状态列。")
|
||||
state["total"] = state["done"]
|
||||
state.update(status="success", message="处理完成")
|
||||
except TaskCancelled as error:
|
||||
state.update(status="cancelled", message=str(error))
|
||||
except Exception as error:
|
||||
# 不输出堆栈局部变量;外部输入中的凭据也不进入日志。
|
||||
chain = []
|
||||
current = error
|
||||
while current is not None:
|
||||
chain.append(str(current))
|
||||
current = current.__cause__
|
||||
message = ":".join(chain)
|
||||
for value in credentials.values():
|
||||
if value:
|
||||
message = message.replace(value, "[已隐藏]")
|
||||
print(f"任务失败:{message}", flush=True)
|
||||
state.update(status="failed", message=message)
|
||||
finally:
|
||||
state["finished"] = time.time()
|
||||
write_json(path, state)
|
||||
return 0 if state["status"] in {"success", "cancelled"} else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
credentials = json.loads(sys.stdin.buffer.read().decode("utf-8"))
|
||||
raise SystemExit(run(sys.argv[1], credentials))
|
||||
Reference in New Issue
Block a user