feat: 新增 Vue 工具箱供对比
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
.venv/
|
||||
.venv-ui/
|
||||
.venv-web/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
node_modules/
|
||||
web/dist/
|
||||
|
||||
# Local data artifacts
|
||||
source/*
|
||||
|
||||
@@ -29,6 +29,18 @@ python -m streamlit run app.py
|
||||
|
||||
界面导入 `source/江门市AOI级报表.csv` 后,按 AOI 与市场网格的最大接触面积自动写入 `source/AOI级报表_市场网格匹配.gpkg` 的 `所属市场网格`。只贴边、没有正面积的不归属。用户量和 4G 流程仍停用。
|
||||
|
||||
## Vue 对比界面
|
||||
|
||||
现有 Streamlit 工具箱保持不变,仍用 `start-ui.cmd` 打开 `http://127.0.0.1:8501`。本节是同一仓库里的另一套界面,用来对照体验,不替换 `ui/`。两套可以同时开着,端口互不占用。
|
||||
|
||||
Windows 双击 `start-web.cmd`,或在项目目录运行 `./start-web.ps1`。脚本会先结束本项目已有的 Vue 界面和接口进程,再用独立的 `.venv-web` 安装 `requirements-web.txt`,并在 `web/` 安装前端依赖。接口只监听 `http://127.0.0.1:8765`,页面是 `http://127.0.0.1:5173`(开发服务把 `/api` 代理到接口)。控制台打印这两个地址并打开浏览器。关闭窗口会停止页面和接口。
|
||||
|
||||
五个页面与 Streamlit 对齐:工具箱首页、市场网格出图、楼宇数据查询、任务中心、成果浏览。出图和查询仍由原来的 Python 任务进程执行,同一时间只运行一个任务。连接信息仍写在 `output/toolbox/nr_connection.json`,只经任务进程的标准输入传递,不写入任务配置或日志。成果按文件下载;超过 128 MB 的文件请从本地目录复制。
|
||||
|
||||
几何编辑和规则引擎这次没有做。
|
||||
|
||||
接口测试:`.venv-web/Scripts/python.exe -m unittest tests.test_web_api -v`。前端构建:在 `web/` 执行 `npm run build`。
|
||||
|
||||
## 代码结构
|
||||
|
||||
`main.py` 保留为命令行入口;默认配置位于 `marketgrid/config.py`。
|
||||
@@ -42,6 +54,7 @@ python -m streamlit run app.py
|
||||
| `marketgrid/legacy_user_count.py`、`metrics.py` | 保留的历史用户量与指标算法 |
|
||||
| `toolbox/` | 输入验证、独立任务进程、任务记录和成果读取 |
|
||||
| `ui/` | 页面和通用文件导入、任务进度组件 |
|
||||
| `api/`、`web/` | Vue 对比界面的本地接口和页面;Streamlit 的 `ui/` 仍保留 |
|
||||
| `GetNRBuildingsData.py` | 可独立运行的异步楼宇查询 |
|
||||
|
||||
测试:`.venv-ui/Scripts/python.exe -m unittest discover -s tests -v`。
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Vue 对比界面的本地接口包。"""
|
||||
@@ -0,0 +1,9 @@
|
||||
import uvicorn
|
||||
|
||||
|
||||
def main():
|
||||
uvicorn.run("api.app:app", host="127.0.0.1", port=8765, log_level="info")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+496
@@ -0,0 +1,496 @@
|
||||
"""Vue 对比界面的本地接口。只绑定 127.0.0.1,计算仍交给 toolbox 任务进程。"""
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
import uuid
|
||||
import zipfile
|
||||
|
||||
from fastapi import FastAPI, HTTPException, UploadFile
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from toolbox import tasks
|
||||
from toolbox.tasks import ACTIVE, KINDS, LABELS, ROOT
|
||||
from toolbox.validation import SOURCES, market_options, validate
|
||||
|
||||
MAX_INLINE_DOWNLOAD = 128 * 1024**2
|
||||
CONNECTION_KEYS = ("URL", "COOKIES", "REFERER")
|
||||
CONNECTION_FILE = ROOT / "output" / "toolbox" / "nr_connection.json"
|
||||
SECRET_KEYS = {"URL", "COOKIES", "REFERER", "PASSWORD", "TOKEN", "SECRET"}
|
||||
IMPORT_SUFFIXES = {".gpkg", ".csv", ".qgz"}
|
||||
POLYGON_CSV = ROOT / "source" / "NRBuildPolygon.csv"
|
||||
BUILDINGS_GPKG = ROOT / "source" / "NRBuildingsData.gpkg"
|
||||
|
||||
app = FastAPI(title="MarketGrid", docs_url=None, redoc_url=None, openapi_url=None)
|
||||
|
||||
|
||||
class TaskRequest(BaseModel):
|
||||
kind: str
|
||||
params: dict = {}
|
||||
credentials: dict | None = None
|
||||
|
||||
|
||||
def resolve_path(value):
|
||||
text = str(value or "").strip().strip('"')
|
||||
if not text:
|
||||
return ""
|
||||
path = Path(text).expanduser()
|
||||
if not path.is_absolute():
|
||||
path = ROOT / path
|
||||
return str(path.resolve())
|
||||
|
||||
|
||||
def require_int(params, key, low, high, label):
|
||||
value = params.get(key)
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ValueError(f"{label}必须为整数。")
|
||||
if not low <= value <= high:
|
||||
raise ValueError(f"{label}超出范围。")
|
||||
return value
|
||||
|
||||
|
||||
def require_float(params, key, low, high, label):
|
||||
value = params.get(key)
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise ValueError(f"{label}必须为数字。")
|
||||
if not low <= float(value) <= high:
|
||||
raise ValueError(f"{label}超出范围。")
|
||||
return float(value)
|
||||
|
||||
|
||||
def script_defaults():
|
||||
import GetNRBuildingsData as script
|
||||
return {key: str(getattr(script, key, "") or "") for key in CONNECTION_KEYS}
|
||||
|
||||
|
||||
def load_connection():
|
||||
defaults = script_defaults()
|
||||
try:
|
||||
data = json.loads(CONNECTION_FILE.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return defaults
|
||||
if not isinstance(data, dict):
|
||||
return defaults
|
||||
return {key: str(data.get(key, "") or "") or defaults[key] for key in CONNECTION_KEYS}
|
||||
|
||||
|
||||
def save_connection(values):
|
||||
if values is None:
|
||||
CONNECTION_FILE.unlink(missing_ok=True)
|
||||
return
|
||||
CONNECTION_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
CONNECTION_FILE.write_text(json.dumps(values, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def public_task(state):
|
||||
params = state.get("params") if isinstance(state.get("params"), dict) else {}
|
||||
safe_params = {key: value for key, value in params.items() if str(key).upper() not in SECRET_KEYS}
|
||||
status = state.get("status") or ""
|
||||
kind = state.get("kind") or ""
|
||||
return {
|
||||
"id": state.get("id") or "",
|
||||
"kind": kind,
|
||||
"kind_label": KINDS.get(kind, kind),
|
||||
"status": status,
|
||||
"status_label": LABELS.get(status, status),
|
||||
"active": status in ACTIVE,
|
||||
"created": state.get("created"),
|
||||
"finished": state.get("finished"),
|
||||
"message": state.get("message") or "",
|
||||
"done": state.get("done") or 0,
|
||||
"total": state.get("total") or 0,
|
||||
"counts": state.get("counts"),
|
||||
"output": state.get("output") or "",
|
||||
"stop_requested": bool(state.get("stop_requested")),
|
||||
"params": safe_params,
|
||||
}
|
||||
|
||||
|
||||
def archive_count(task_list):
|
||||
total = 0
|
||||
for task in task_list:
|
||||
directory = Path(task.get("output") or "")
|
||||
if not directory.is_dir():
|
||||
continue
|
||||
total += sum(1 for path in directory.glob("*.zip") if path.is_file())
|
||||
return total
|
||||
|
||||
|
||||
def source_rows():
|
||||
rows = []
|
||||
for label, relative, _extension in SOURCES.values():
|
||||
path = ROOT / relative
|
||||
ready = path.is_file()
|
||||
size = round(path.stat().st_size / 1024**2, 1) if ready else 0
|
||||
rows.append({
|
||||
"label": label,
|
||||
"file": relative,
|
||||
"status": "已就绪" if ready else "缺失",
|
||||
"ready": ready,
|
||||
"size_mb": size,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def safe_task_dir(task_id):
|
||||
if not task_id or task_id in {".", ".."} or any(part in task_id for part in ("/", "\\", ":")):
|
||||
raise HTTPException(status_code=404, detail="任务不存在。")
|
||||
root = tasks.TASKS.resolve()
|
||||
directory = (root / task_id).resolve()
|
||||
if directory.parent != root:
|
||||
raise HTTPException(status_code=404, detail="任务不存在。")
|
||||
return directory
|
||||
|
||||
|
||||
def require_task(task_id):
|
||||
directory = safe_task_dir(task_id)
|
||||
if not (directory / "state.json").is_file():
|
||||
raise HTTPException(status_code=404, detail="任务不存在。")
|
||||
state = tasks.read_task(directory)
|
||||
return directory, state
|
||||
|
||||
|
||||
def result_root(task_id):
|
||||
directory, state = require_task(task_id)
|
||||
root = Path(state.get("output") or "").resolve()
|
||||
if root != directory and directory not in root.parents:
|
||||
raise HTTPException(status_code=404, detail="成果目录不存在。")
|
||||
return state, root
|
||||
|
||||
|
||||
def result_file(task_id, name):
|
||||
if not name or name != Path(name).name or name.startswith("."):
|
||||
raise HTTPException(status_code=404, detail="文件不存在。")
|
||||
state, root = result_root(task_id)
|
||||
target = (root / name).resolve()
|
||||
if target.parent != root or not target.is_file():
|
||||
raise HTTPException(status_code=404, detail="文件不存在。")
|
||||
return state, target
|
||||
|
||||
|
||||
def file_chunks(path, size=1024 * 1024):
|
||||
with path.open("rb") as source:
|
||||
while True:
|
||||
block = source.read(size)
|
||||
if not block:
|
||||
break
|
||||
yield block
|
||||
|
||||
|
||||
def prepare_market(raw):
|
||||
params = dict(raw or {})
|
||||
for key in SOURCES:
|
||||
if params.get(key) in (None, ""):
|
||||
raise ValueError("请完成所需数据的导入。")
|
||||
params[key] = resolve_path(params[key])
|
||||
chosen = params.get("SELECTED_MARKET_IDS")
|
||||
if not isinstance(chosen, list) or not chosen:
|
||||
raise ValueError("请至少选择一个市场网格。")
|
||||
ids = []
|
||||
for item in chosen:
|
||||
if isinstance(item, bool) or not isinstance(item, int):
|
||||
raise ValueError("市场选择无效。")
|
||||
ids.append(item)
|
||||
params["SELECTED_MARKET_IDS"] = ids
|
||||
params["MAX_WORKERS"] = require_int(params, "MAX_WORKERS", 1, 16, "并行进程数")
|
||||
params["SCALE"] = require_float(params, "SCALE", 0.1, 20, "分辨率倍数")
|
||||
params["MAX_RASTER_PIXELS"] = require_int(params, "MAX_RASTER_PIXELS", 1_000_000, 100_000_000, "单市场像元上限")
|
||||
params["SUMMARY_MAX_RASTER_PIXELS"] = require_int(
|
||||
params, "SUMMARY_MAX_RASTER_PIXELS", 1_000_000, 200_000_000, "汇总像元上限")
|
||||
params["PROJECT_EXTENT_PADDING_RATIO"] = require_float(
|
||||
params, "PROJECT_EXTENT_PADDING_RATIO", 0, 1, "地图留白比例")
|
||||
if params.get("CLIP_MODE") not in {"intersects", "center"}:
|
||||
raise ValueError("网格纳入方式无效。")
|
||||
if not isinstance(params.get("SUMMARY_OUTPUT_ENABLED"), bool):
|
||||
raise ValueError("生成全量汇总包参数无效。")
|
||||
for key, (label, _, _) in SOURCES.items():
|
||||
if not Path(params[key]).is_file():
|
||||
raise ValueError(f"{label}文件不存在:{params[key]}")
|
||||
data_csv = resolve_path(params.get("NR_BUILDINGS_DATA_CSV") or "")
|
||||
if not data_csv or not Path(data_csv).is_file() or not POLYGON_CSV.is_file():
|
||||
raise ValueError("缺少 source/NRBuildingsData.csv 或 source/NRBuildPolygon.csv。")
|
||||
data_csv_path = Path(data_csv)
|
||||
if (not BUILDINGS_GPKG.exists()
|
||||
or BUILDINGS_GPKG.stat().st_mtime < max(data_csv_path.stat().st_mtime, POLYGON_CSV.stat().st_mtime)):
|
||||
from marketgrid.nrdata import build_gpkg
|
||||
build_gpkg(data_csv_path, POLYGON_CSV, BUILDINGS_GPKG)
|
||||
params["NR_BUILDINGS_DATA_GPKG"] = str(BUILDINGS_GPKG)
|
||||
params.pop("NR_BUILDINGS_DATA_CSV", None)
|
||||
return params
|
||||
|
||||
|
||||
def prepare_buildings(raw, credentials):
|
||||
params = dict(raw or {})
|
||||
params["START_ROW"] = require_int(params, "START_ROW", 1, 10**9, "起始行")
|
||||
limit = params.get("LIMIT")
|
||||
if limit in (0, None):
|
||||
params["LIMIT"] = None
|
||||
else:
|
||||
params["LIMIT"] = require_int(params, "LIMIT", 1, 10**9, "查询数量")
|
||||
params["CONCURRENCY"] = require_int(params, "CONCURRENCY", 1, 32, "并发数")
|
||||
params["TIMEOUT"] = require_int(params, "TIMEOUT", 1, 300, "超时")
|
||||
params["MAX_RETRIES"] = require_int(params, "MAX_RETRIES", 0, 10, "失败重试")
|
||||
params["REQUEST_INTERVAL"] = require_float(params, "REQUEST_INTERVAL", 0, 60, "请求间隔")
|
||||
if params.get("INPUT_ENCODING") not in {"gbk", "utf-8-sig"}:
|
||||
raise ValueError("文件编码无效。")
|
||||
source = resolve_path(params.get("INPUT_CSV") or "")
|
||||
if not source:
|
||||
raise ValueError("请先导入楼宇轮廓文件。")
|
||||
if not Path(source).is_file():
|
||||
raise ValueError(f"楼宇轮廓文件不存在:{source}")
|
||||
params["INPUT_CSV"] = source
|
||||
incoming = credentials or {}
|
||||
url = str(incoming.get("URL") or "").strip()
|
||||
cookies = str(incoming.get("COOKIES") or "").strip()
|
||||
referer = str(incoming.get("REFERER") or "").strip()
|
||||
override = bool(url or cookies)
|
||||
if override and (not url.startswith(("http://", "https://")) or not cookies):
|
||||
raise ValueError("服务地址和登录信息需同时填写,且地址以 http(s):// 开头。")
|
||||
validate("buildings", params)
|
||||
payload = {"URL": url, "COOKIES": cookies, "REFERER": referer} if override else None
|
||||
save_connection(payload)
|
||||
return params, payload
|
||||
|
||||
|
||||
def content_disposition(name):
|
||||
fallback = "".join(ch if ch.isascii() and ch not in '"\\;' else "_" for ch in name) or "download"
|
||||
return f"attachment; filename=\"{fallback}\"; filename*=UTF-8''{quote(name)}"
|
||||
|
||||
|
||||
@app.exception_handler(ValueError)
|
||||
async def value_error(_, exc):
|
||||
return JSONResponse(status_code=400, content={"detail": str(exc)})
|
||||
|
||||
|
||||
@app.exception_handler(OSError)
|
||||
async def os_error(_, exc):
|
||||
return JSONResponse(status_code=400, content={"detail": str(exc)})
|
||||
|
||||
|
||||
@app.exception_handler(sqlite3.Error)
|
||||
async def sqlite_error(_, exc):
|
||||
return JSONResponse(status_code=400, content={"detail": str(exc)})
|
||||
|
||||
|
||||
@app.exception_handler(zipfile.BadZipFile)
|
||||
async def zip_error(_, exc):
|
||||
return JSONResponse(status_code=400, content={"detail": str(exc)})
|
||||
|
||||
|
||||
@app.exception_handler(UnicodeError)
|
||||
async def unicode_error(_, exc):
|
||||
return JSONResponse(status_code=400, content={"detail": str(exc)})
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def health():
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.get("/api/home")
|
||||
def home():
|
||||
task_list = tasks.list_tasks()
|
||||
return {
|
||||
"running": sum(task["status"] in ACTIVE for task in task_list),
|
||||
"tasks": len(task_list),
|
||||
"archives": archive_count(task_list),
|
||||
"sources": source_rows(),
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/catalog")
|
||||
def catalog():
|
||||
sources = [{
|
||||
"key": key,
|
||||
"label": label,
|
||||
"path": str((ROOT / relative).resolve()),
|
||||
"relative": relative,
|
||||
"extension": extension,
|
||||
} for key, (label, relative, extension) in SOURCES.items()]
|
||||
return {
|
||||
"sources": sources,
|
||||
"nr_csv": {
|
||||
"key": "NR_BUILDINGS_DATA_CSV",
|
||||
"label": "楼宇查询结果",
|
||||
"path": str((ROOT / "source" / "NRBuildingsData.csv").resolve()),
|
||||
"extension": "csv",
|
||||
},
|
||||
"building_csv": {
|
||||
"key": "INPUT_CSV",
|
||||
"label": "楼宇轮廓清单",
|
||||
"path": str((ROOT / "source" / "NRBuildPolygon.csv").resolve()),
|
||||
"extension": "csv",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/files/stat")
|
||||
def file_stat(path: str = ""):
|
||||
resolved = resolve_path(path)
|
||||
target = Path(resolved) if resolved else None
|
||||
if target is None or not target.is_file():
|
||||
return {"path": resolved, "exists": False, "size": 0}
|
||||
return {"path": str(target), "exists": True, "size": target.stat().st_size}
|
||||
|
||||
|
||||
@app.get("/api/markets")
|
||||
def market_list(path: str = ""):
|
||||
resolved = resolve_path(path)
|
||||
if not resolved or not Path(resolved).is_file():
|
||||
raise ValueError("请先导入可用的市场边界。")
|
||||
try:
|
||||
options = market_options(resolved)
|
||||
except (OSError, sqlite3.Error, ValueError) as error:
|
||||
raise ValueError(f"市场边界不可用:{error}") from error
|
||||
return {"options": [{"id": fid, "name": name} for fid, name in options]}
|
||||
|
||||
|
||||
@app.get("/api/connection")
|
||||
def connection():
|
||||
return JSONResponse(content=load_connection(), headers={"Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@app.post("/api/imports")
|
||||
async def import_file(file: UploadFile):
|
||||
name = Path(file.filename or "").name
|
||||
suffix = Path(name).suffix.lower()
|
||||
if not name or name.startswith(".") or suffix not in IMPORT_SUFFIXES:
|
||||
raise ValueError("请选择 gpkg、csv 或 qgz 文件。")
|
||||
folder = ROOT / "output" / "toolbox" / "imports" / uuid.uuid4().hex
|
||||
folder.mkdir(parents=True)
|
||||
target = folder / name
|
||||
size = 0
|
||||
try:
|
||||
with target.open("wb") as output:
|
||||
while True:
|
||||
chunk = await file.read(8 * 1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
output.write(chunk)
|
||||
size += len(chunk)
|
||||
except Exception:
|
||||
target.unlink(missing_ok=True)
|
||||
raise
|
||||
finally:
|
||||
await file.close()
|
||||
if size <= 0:
|
||||
target.unlink(missing_ok=True)
|
||||
raise ValueError("文件是空的。")
|
||||
return {"path": str(target.resolve()), "name": name, "size": size}
|
||||
|
||||
|
||||
@app.get("/api/tasks")
|
||||
def list_task_view():
|
||||
return {"tasks": [public_task(task) for task in tasks.list_tasks()]}
|
||||
|
||||
|
||||
@app.get("/api/tasks/{task_id}")
|
||||
def task_view(task_id: str):
|
||||
_, state = require_task(task_id)
|
||||
return public_task(state)
|
||||
|
||||
|
||||
@app.get("/api/tasks/{task_id}/log")
|
||||
def task_log(task_id: str):
|
||||
directory, _state = require_task(task_id)
|
||||
return {"text": tasks.tail_log(directory)}
|
||||
|
||||
|
||||
@app.post("/api/tasks")
|
||||
def create_task(body: TaskRequest):
|
||||
if body.kind == "market":
|
||||
params = prepare_market(body.params)
|
||||
task_id = tasks.start_task("market", params)
|
||||
elif body.kind == "buildings":
|
||||
params, credentials = prepare_buildings(body.params, body.credentials)
|
||||
task_id = tasks.start_task("buildings", params, credentials)
|
||||
else:
|
||||
raise ValueError("未知工具。")
|
||||
return {"id": task_id}
|
||||
|
||||
|
||||
@app.post("/api/tasks/{task_id}/stop")
|
||||
def stop(task_id: str):
|
||||
require_task(task_id)
|
||||
tasks.stop_task(task_id)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.delete("/api/tasks/{task_id}")
|
||||
def remove(task_id: str):
|
||||
require_task(task_id)
|
||||
tasks.delete_task(task_id)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/api/tasks/clear")
|
||||
def clear():
|
||||
deleted, skipped = tasks.clear_tasks()
|
||||
message = f"已删除 {deleted} 个任务。"
|
||||
if skipped:
|
||||
message += f" {skipped} 个运行中的任务已跳过。"
|
||||
return {"deleted": deleted, "skipped": skipped, "message": message}
|
||||
|
||||
|
||||
@app.get("/api/results")
|
||||
def results():
|
||||
rows = []
|
||||
for task in tasks.list_tasks():
|
||||
view = public_task(task)
|
||||
rows.append({
|
||||
"id": view["id"],
|
||||
"label": f"{view['id']} · {view['kind_label']} · {view['status_label']}",
|
||||
"output": view["output"],
|
||||
"kind": view["kind"],
|
||||
"status": view["status"],
|
||||
})
|
||||
return {"tasks": rows}
|
||||
|
||||
|
||||
@app.get("/api/results/{task_id}/files")
|
||||
def result_files(task_id: str):
|
||||
_state, root = result_root(task_id)
|
||||
if not root.is_dir():
|
||||
return {"directory": str(root), "files": []}
|
||||
files = sorted(
|
||||
(path for path in root.iterdir() if path.is_file() and not path.name.startswith(".")),
|
||||
key=lambda path: path.name.lower(),
|
||||
)
|
||||
return {
|
||||
"directory": str(root),
|
||||
"files": [{
|
||||
"name": path.name,
|
||||
"size": path.stat().st_size,
|
||||
"too_large": path.stat().st_size > MAX_INLINE_DOWNLOAD,
|
||||
} for path in files],
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/results/{task_id}/files/{name}")
|
||||
def download_result(task_id: str, name: str):
|
||||
_state, target = result_file(task_id, name)
|
||||
size = target.stat().st_size
|
||||
if size > MAX_INLINE_DOWNLOAD:
|
||||
return JSONResponse(status_code=413, content={
|
||||
"detail": "文件较大,请从本地目录复制。",
|
||||
"path": str(target),
|
||||
"directory": str(target.parent),
|
||||
})
|
||||
headers = {
|
||||
"Content-Disposition": content_disposition(target.name),
|
||||
"Content-Length": str(size),
|
||||
}
|
||||
return StreamingResponse(file_chunks(target), media_type="application/octet-stream", headers=headers)
|
||||
|
||||
|
||||
@app.post("/api/results/{task_id}/open")
|
||||
def open_result(task_id: str):
|
||||
_state, root = result_root(task_id)
|
||||
if not root.is_dir():
|
||||
raise ValueError("成果目录不存在。")
|
||||
if os.name != "nt":
|
||||
raise ValueError(f"请从本地目录复制:{root}")
|
||||
os.startfile(root)
|
||||
return {"ok": True}
|
||||
@@ -0,0 +1,5 @@
|
||||
-r requirements-ui.txt
|
||||
fastapi==0.143.0
|
||||
uvicorn==0.54.0
|
||||
python-multipart==0.0.32
|
||||
httpx==0.28.1
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0start-web.ps1"
|
||||
if errorlevel 1 pause
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location -LiteralPath $PSScriptRoot
|
||||
$env:PYTHONIOENCODING = 'utf-8'
|
||||
$env:PYTHONUTF8 = '1'
|
||||
$ApiHost = '127.0.0.1'
|
||||
$ApiPort = 8765
|
||||
$WebPort = 5173
|
||||
$PageUrl = "http://${ApiHost}:${WebPort}"
|
||||
$ApiUrl = "http://${ApiHost}:${ApiPort}"
|
||||
$Python = Join-Path $PSScriptRoot '.venv-web\Scripts\python.exe'
|
||||
$WebDir = Join-Path $PSScriptRoot 'web'
|
||||
|
||||
function Test-Listening([int] $Port) {
|
||||
$pattern = ":$Port\s+"
|
||||
netstat -ano | Where-Object { $_ -match $pattern -and $_ -match 'LISTENING' }
|
||||
}
|
||||
|
||||
function Stop-Tree($Proc) {
|
||||
if (-not $Proc) { return }
|
||||
$children = @(Get-CimInstance Win32_Process -Filter "ParentProcessId=$($Proc.Id)" -ErrorAction SilentlyContinue)
|
||||
foreach ($child in $children) {
|
||||
$childProc = Get-Process -Id $child.ProcessId -ErrorAction SilentlyContinue
|
||||
if ($childProc) { Stop-Tree $childProc }
|
||||
}
|
||||
if (-not $Proc.HasExited) {
|
||||
Stop-Process -Id $Proc.Id -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
|
||||
function Stop-ListenerIfOurs([int] $Port, [scriptblock] $Belongs) {
|
||||
foreach ($line in @(Test-Listening $Port)) {
|
||||
if ($line -notmatch '\s(\d+)\s*$') { continue }
|
||||
$procId = [int]$Matches[1]
|
||||
if ($procId -le 0) { continue }
|
||||
$owner = Get-CimInstance Win32_Process -Filter "ProcessId=$procId" -ErrorAction SilentlyContinue
|
||||
$cmd = if ($owner) { $owner.CommandLine } else { '' }
|
||||
if (-not $cmd -or -not (& $Belongs $cmd)) {
|
||||
throw "端口 $Port 被其他程序占用,无法启动。"
|
||||
}
|
||||
Stop-Process -Id $procId -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
|
||||
function Stop-ExistingWeb {
|
||||
$root = $PSScriptRoot
|
||||
$web = Join-Path $root 'web'
|
||||
Get-CimInstance Win32_Process | Where-Object {
|
||||
$_.CommandLine -and $_.ProcessId -ne $PID -and (
|
||||
($_.Name -match 'python' -and $_.CommandLine -match 'api\.app' -and $_.CommandLine -match [regex]::Escape($root)) -or
|
||||
($_.Name -match 'node' -and $_.CommandLine -match 'vite' -and $_.CommandLine -match [regex]::Escape($web))
|
||||
)
|
||||
} | ForEach-Object {
|
||||
Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Stop-ListenerIfOurs $ApiPort { param($cmd) $cmd -match 'api\.app' -and $cmd -match [regex]::Escape($PSScriptRoot) }
|
||||
Stop-ListenerIfOurs $WebPort { param($cmd) $cmd -match 'vite' -and $cmd -match [regex]::Escape($WebDir) }
|
||||
$deadline = (Get-Date).AddSeconds(10)
|
||||
do {
|
||||
if (-not (Test-Listening $ApiPort) -and -not (Test-Listening $WebPort)) { return }
|
||||
Start-Sleep -Milliseconds 200
|
||||
} while ((Get-Date) -lt $deadline)
|
||||
throw "端口 $ApiPort 或 $WebPort 仍被占用,无法启动。"
|
||||
}
|
||||
|
||||
function Wait-Port([int] $Port, $Proc, [string] $Name) {
|
||||
$deadline = (Get-Date).AddSeconds(90)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
if ($Proc.HasExited) { throw "$Name 进程已退出,启动失败。" }
|
||||
if (Test-Listening $Port) { return }
|
||||
Start-Sleep -Milliseconds 300
|
||||
}
|
||||
throw "等待${Name}启动超时。"
|
||||
}
|
||||
|
||||
function Start-Tool([string] $File, [string] $Arguments, [string] $Workdir) {
|
||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
||||
$psi.FileName = $File
|
||||
$psi.Arguments = $Arguments
|
||||
$psi.WorkingDirectory = $Workdir
|
||||
$psi.UseShellExecute = $false
|
||||
return [System.Diagnostics.Process]::Start($psi)
|
||||
}
|
||||
|
||||
function Ensure-WebEnvironment {
|
||||
if (Get-Command uv -ErrorAction SilentlyContinue) {
|
||||
if (-not (Test-Path -LiteralPath $Python)) {
|
||||
uv venv .venv-web --python 3.13
|
||||
if ($LASTEXITCODE -ne 0) { throw '创建 Python 环境失败。' }
|
||||
}
|
||||
uv pip install --python $Python -r requirements-web.txt
|
||||
if ($LASTEXITCODE -ne 0) { throw '安装 Python 依赖失败。' }
|
||||
return
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $Python)) {
|
||||
python -m venv .venv-web
|
||||
if ($LASTEXITCODE -ne 0) { throw '创建 Python 环境失败。' }
|
||||
}
|
||||
& $Python -m pip install -r requirements-web.txt
|
||||
if ($LASTEXITCODE -ne 0) { throw '安装 Python 依赖失败。' }
|
||||
}
|
||||
|
||||
if (-not (Get-Command node -ErrorAction SilentlyContinue) -or -not (Get-Command npm.cmd -ErrorAction SilentlyContinue)) {
|
||||
throw '未找到 Node.js 或 npm,无法启动 Vue 界面。请先安装 Node.js 后再运行 start-web。'
|
||||
}
|
||||
|
||||
Stop-ExistingWeb
|
||||
Ensure-WebEnvironment
|
||||
Push-Location -LiteralPath $WebDir
|
||||
try {
|
||||
& npm.cmd install --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { throw '安装前端依赖失败。' }
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
Write-Host ''
|
||||
Write-Host '正在启动 MarketGrid Vue 对比界面'
|
||||
Write-Host "页面:$PageUrl"
|
||||
Write-Host "接口:$ApiUrl"
|
||||
Write-Host 'Streamlit 工具箱仍使用 start-ui.cmd(http://127.0.0.1:8501)'
|
||||
Write-Host '关闭本窗口会停止页面和接口。'
|
||||
Write-Host ''
|
||||
|
||||
$npm = (Get-Command npm.cmd).Source
|
||||
$api = Start-Tool $Python '-m uvicorn api.app:app --host 127.0.0.1 --port 8765 --log-level info' $PSScriptRoot
|
||||
try {
|
||||
Wait-Port $ApiPort $api '接口'
|
||||
$web = Start-Tool $npm 'run dev' $WebDir
|
||||
try {
|
||||
Wait-Port $WebPort $web '页面'
|
||||
Write-Host "已启动:$PageUrl"
|
||||
Start-Process $PageUrl
|
||||
while (-not $api.HasExited -and -not $web.HasExited) {
|
||||
Start-Sleep -Milliseconds 400
|
||||
}
|
||||
if ($api.HasExited) { $code = $api.ExitCode } else { $code = $web.ExitCode }
|
||||
exit $code
|
||||
} finally {
|
||||
Stop-Tree $web
|
||||
}
|
||||
} finally {
|
||||
Stop-Tree $api
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Vue 接口测试。不启动真实出图,不打开 Grid 大文件。"""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from toolbox import tasks
|
||||
from toolbox.tasks import ROOT
|
||||
|
||||
FASTAPI_READY = importlib.util.find_spec("fastapi") is not None and importlib.util.find_spec("httpx") is not None
|
||||
|
||||
|
||||
def _stamp(path):
|
||||
if not path.exists():
|
||||
return None
|
||||
stat = path.stat()
|
||||
return (stat.st_mtime_ns, stat.st_size)
|
||||
|
||||
|
||||
@unittest.skipUnless(FASTAPI_READY, "未安装 FastAPI,跳过 Vue 接口测试")
|
||||
class WebApiTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
from fastapi.testclient import TestClient
|
||||
from api.app import CONNECTION_FILE, app
|
||||
|
||||
self.connection_file = CONNECTION_FILE
|
||||
self.real_connection = _stamp(ROOT / "output" / "toolbox" / "nr_connection.json")
|
||||
self.temp = tempfile.TemporaryDirectory(prefix="webapi_")
|
||||
self.root = Path(self.temp.name)
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.tasks_patch = patch("toolbox.tasks.TASKS", self.root / "tasks")
|
||||
self.connection_patch = patch("api.app.CONNECTION_FILE", self.root / "nr_connection.json")
|
||||
self.tasks_patch.start()
|
||||
self.connection_patch.start()
|
||||
self.addCleanup(self.tasks_patch.stop)
|
||||
self.addCleanup(self.connection_patch.stop)
|
||||
self.client = TestClient(app)
|
||||
self.addCleanup(self.client.close)
|
||||
|
||||
def tearDown(self):
|
||||
self.assertEqual(_stamp(ROOT / "output" / "toolbox" / "nr_connection.json"), self.real_connection)
|
||||
|
||||
def add_task(self, name, files):
|
||||
folder = tasks.TASKS / name
|
||||
results = folder / "results"
|
||||
results.mkdir(parents=True)
|
||||
for filename, payload in files.items():
|
||||
(results / filename).write_bytes(payload)
|
||||
tasks.write_json(folder / "state.json", {
|
||||
"id": name, "kind": "market", "status": "success", "created": 1700000000,
|
||||
"output": str(results), "directory": str(folder),
|
||||
"params": {"COOKIES": "should-not-appear", "MAX_WORKERS": 4},
|
||||
"done": 1, "total": 2, "message": "处理完成",
|
||||
})
|
||||
return results
|
||||
|
||||
def test_list_tasks(self):
|
||||
marker = b"UNIQUE-BYTES-NOT-IN-TASK-LIST"
|
||||
self.add_task("done-1", {"成果.zip": marker})
|
||||
with patch.object(Path, "read_bytes", side_effect=AssertionError("不应整文件读入")):
|
||||
response = self.client.get("/api/tasks")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertNotIn(marker, response.content)
|
||||
self.assertNotIn("should-not-appear", response.text)
|
||||
body = response.json()
|
||||
self.assertEqual(len(body["tasks"]), 1)
|
||||
task = body["tasks"][0]
|
||||
self.assertEqual(task["id"], "done-1")
|
||||
self.assertEqual(task["status_label"], "已完成")
|
||||
self.assertEqual(task["params"], {"MAX_WORKERS": 4})
|
||||
self.assertNotIn("content", task)
|
||||
cleared = self.client.post("/api/tasks/clear")
|
||||
self.assertEqual(cleared.status_code, 200)
|
||||
self.assertEqual(cleared.json()["deleted"], 1)
|
||||
self.assertFalse((tasks.TASKS / "done-1").exists())
|
||||
|
||||
def test_start_validation_failure(self):
|
||||
market = {
|
||||
"kind": "market",
|
||||
"params": {
|
||||
"MARKET_GPKG": str(self.root / "missing.gpkg"),
|
||||
"GRID_5G_GPKG": str(self.root / "missing-grid.gpkg"),
|
||||
"BUILDING_INFO_GPKG": str(self.root / "missing-building.gpkg"),
|
||||
"AOI_CSV": str(self.root / "missing.csv"),
|
||||
"GIS_PROJECT_SOURCE": str(self.root / "missing.qgz"),
|
||||
"NR_BUILDINGS_DATA_CSV": str(self.root / "missing-nr.csv"),
|
||||
"SELECTED_MARKET_IDS": [1],
|
||||
"MAX_WORKERS": 4,
|
||||
"SCALE": 5,
|
||||
"SUMMARY_OUTPUT_ENABLED": True,
|
||||
"MAX_RASTER_PIXELS": 25_000_000,
|
||||
"SUMMARY_MAX_RASTER_PIXELS": 100_000_000,
|
||||
"CLIP_MODE": "intersects",
|
||||
"PROJECT_EXTENT_PADDING_RATIO": 0.05,
|
||||
},
|
||||
}
|
||||
buildings = {
|
||||
"kind": "buildings",
|
||||
"params": {
|
||||
"INPUT_CSV": str(self.root / "missing.csv"),
|
||||
"INPUT_ENCODING": "gbk",
|
||||
"START_ROW": 0,
|
||||
"LIMIT": 1,
|
||||
"CONCURRENCY": 1,
|
||||
"TIMEOUT": 5,
|
||||
"MAX_RETRIES": 0,
|
||||
"REQUEST_INTERVAL": 0,
|
||||
},
|
||||
"credentials": {
|
||||
"URL": "http://127.0.0.1/wfs",
|
||||
"COOKIES": "private-cookie-should-not-leak",
|
||||
"REFERER": "",
|
||||
},
|
||||
}
|
||||
with patch("marketgrid.nrdata.build_gpkg", side_effect=AssertionError("不应整理楼宇")), \
|
||||
patch("api.app.tasks.start_task", side_effect=AssertionError("不应启动任务")):
|
||||
market_response = self.client.post("/api/tasks", json=market)
|
||||
buildings_response = self.client.post("/api/tasks", json=buildings)
|
||||
self.assertEqual(market_response.status_code, 400)
|
||||
self.assertIn("不存在", market_response.json()["detail"])
|
||||
self.assertEqual(buildings_response.status_code, 400)
|
||||
self.assertIn("起始行", buildings_response.json()["detail"])
|
||||
self.assertNotIn("private-cookie-should-not-leak", buildings_response.text)
|
||||
self.assertFalse((self.root / "nr_connection.json").exists())
|
||||
self.assertFalse(tasks.TASKS.exists() and any(tasks.TASKS.glob("*/state.json")))
|
||||
|
||||
def test_building_credentials_stay_out_of_task_response(self):
|
||||
source = self.root / "楼宇轮廓.csv"
|
||||
source.write_text("WKT,building_id\n", encoding="gbk")
|
||||
cookie = "private-cookie-should-not-leak"
|
||||
with patch("api.app.tasks.start_task", return_value="task-1") as start:
|
||||
response = self.client.post("/api/tasks", json={
|
||||
"kind": "buildings",
|
||||
"params": {
|
||||
"INPUT_CSV": str(source),
|
||||
"INPUT_ENCODING": "gbk",
|
||||
"START_ROW": 1,
|
||||
"LIMIT": 1,
|
||||
"CONCURRENCY": 1,
|
||||
"TIMEOUT": 5,
|
||||
"MAX_RETRIES": 0,
|
||||
"REQUEST_INTERVAL": 0,
|
||||
},
|
||||
"credentials": {"URL": "http://127.0.0.1/wfs", "COOKIES": cookie, "REFERER": ""},
|
||||
})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), {"id": "task-1"})
|
||||
self.assertNotIn(cookie, response.text)
|
||||
kind, params, credentials = start.call_args.args
|
||||
self.assertEqual(kind, "buildings")
|
||||
self.assertNotIn("COOKIES", params)
|
||||
self.assertNotIn("URL", params)
|
||||
self.assertEqual(credentials["COOKIES"], cookie)
|
||||
saved = json.loads((self.root / "nr_connection.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(saved["COOKIES"], cookie)
|
||||
self.assertNotIn(cookie, json.dumps(params, ensure_ascii=False))
|
||||
|
||||
def test_result_list_and_download_do_not_inline_file(self):
|
||||
small = "成果内容".encode()
|
||||
large = b"UNIQUE-BYTES-NOT-IN-JSON"
|
||||
self.add_task("pack-1", {"成果.zip": small, "large.bin": large})
|
||||
with patch("api.app.MAX_INLINE_DOWNLOAD", len(small)), \
|
||||
patch.object(Path, "read_bytes", side_effect=AssertionError("不应整文件读入")):
|
||||
listed = self.client.get("/api/results/pack-1/files")
|
||||
downloaded = self.client.get("/api/results/pack-1/files/" + "成果.zip")
|
||||
refused = self.client.get("/api/results/pack-1/files/large.bin")
|
||||
self.assertEqual(listed.status_code, 200)
|
||||
self.assertNotIn(large, listed.content)
|
||||
self.assertNotIn(small, listed.content)
|
||||
files = {item["name"]: item for item in listed.json()["files"]}
|
||||
self.assertEqual(set(files), {"成果.zip", "large.bin"})
|
||||
self.assertFalse(files["成果.zip"]["too_large"])
|
||||
self.assertTrue(files["large.bin"]["too_large"])
|
||||
self.assertNotIn("content", files["成果.zip"])
|
||||
self.assertEqual(downloaded.status_code, 200)
|
||||
self.assertEqual(downloaded.content, small)
|
||||
self.assertIn("filename*=UTF-8''", downloaded.headers["content-disposition"])
|
||||
self.assertEqual(refused.status_code, 413)
|
||||
self.assertNotIn(large, refused.content)
|
||||
self.assertIn("本地目录", refused.json()["detail"])
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>MarketGrid 工具箱</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+1752
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "marketgrid-web",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview --host 127.0.0.1 --port 5173 --strictPort"
|
||||
},
|
||||
"dependencies": {
|
||||
"naive-ui": "2.45.3",
|
||||
"vue": "3.5.44",
|
||||
"vue-router": "5.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "6.0.10",
|
||||
"vite": "8.3.4"
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
<script setup>
|
||||
import { dateZhCN, zhCN } from 'naive-ui'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const names = new Set(['home', 'market', 'buildings', 'tasks', 'results'])
|
||||
const menuOptions = [
|
||||
{
|
||||
type: 'group',
|
||||
label: '工具',
|
||||
key: 'tools',
|
||||
children: [
|
||||
{ label: '工具箱首页', key: 'home' },
|
||||
{ label: '市场网格出图', key: 'market' },
|
||||
{ label: '楼宇数据查询', key: 'buildings' },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'group',
|
||||
label: '工作记录',
|
||||
key: 'records',
|
||||
children: [
|
||||
{ label: '任务中心', key: 'tasks' },
|
||||
{ label: '成果浏览', key: 'results' },
|
||||
],
|
||||
},
|
||||
]
|
||||
const themeOverrides = {
|
||||
common: {
|
||||
primaryColor: '#1F6F8B',
|
||||
primaryColorHover: '#2B86A4',
|
||||
primaryColorPressed: '#18596F',
|
||||
primaryColorSuppl: '#1F6F8B',
|
||||
borderRadius: '6px',
|
||||
fontSize: '13px',
|
||||
fontSizeMedium: '13px',
|
||||
heightMedium: '32px',
|
||||
fontFamily: '"Segoe UI", "Microsoft YaHei", sans-serif',
|
||||
},
|
||||
Form: {
|
||||
blankHeightMedium: '8px',
|
||||
feedbackHeightMedium: '14px',
|
||||
labelFontSizeLeftMedium: '13px',
|
||||
labelPaddingHorizontal: '0 8px 0 0',
|
||||
},
|
||||
Menu: {
|
||||
itemHeight: '34px',
|
||||
},
|
||||
}
|
||||
|
||||
function go(key) {
|
||||
if (names.has(key)) router.push({ name: key })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<n-config-provider :locale="zhCN" :date-locale="dateZhCN" :theme-overrides="themeOverrides">
|
||||
<n-layout has-sider class="shell">
|
||||
<n-layout-sider bordered :width="216" content-style="display:flex;flex-direction:column;">
|
||||
<div class="brand">
|
||||
<strong>MarketGrid</strong>
|
||||
<span>空间数据工具箱</span>
|
||||
</div>
|
||||
<n-menu :value="route.name" :options="menuOptions" :indent="16" @update:value="go" />
|
||||
</n-layout-sider>
|
||||
<div class="main-column">
|
||||
<header class="topbar">
|
||||
<h1>{{ route.meta.title }}</h1>
|
||||
<div id="page-actions"></div>
|
||||
</header>
|
||||
<div class="page-body">
|
||||
<router-view />
|
||||
</div>
|
||||
</div>
|
||||
</n-layout>
|
||||
</n-config-provider>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.shell { height: 100vh; overflow: hidden; }
|
||||
.main-column { flex: 1; min-width: 0; height: 100vh; display: flex; flex-direction: column; }
|
||||
.brand { padding: 12px 16px 2px; }
|
||||
.brand strong { display: block; font-size: 18px; }
|
||||
.brand span { display: block; margin-top: 2px; color: #66788a; font-size: 12px; }
|
||||
.topbar {
|
||||
flex: none;
|
||||
height: 48px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 0 16px;
|
||||
background: #fff;
|
||||
border-bottom: 1px solid #e4ebf1;
|
||||
z-index: 2;
|
||||
}
|
||||
.topbar h1 { margin: 0; font-size: 16px; font-weight: 600; }
|
||||
.page-body { flex: 1; min-height: 0; overflow: auto; padding: 12px 16px 16px; background: #f5f7f9; }
|
||||
</style>
|
||||
@@ -0,0 +1,75 @@
|
||||
export class ApiError extends Error {}
|
||||
|
||||
function errorMessage(data) {
|
||||
const detail = data && data.detail
|
||||
if (typeof detail === 'string' && detail) return detail
|
||||
if (Array.isArray(detail)) {
|
||||
const text = detail.map((item) => item.msg || '').filter(Boolean).join(';')
|
||||
if (text) return text
|
||||
}
|
||||
return '请求失败'
|
||||
}
|
||||
|
||||
export async function request(path, options = {}) {
|
||||
const headers = { ...(options.headers || {}) }
|
||||
if (options.body && !(options.body instanceof FormData) && !headers['Content-Type']) {
|
||||
headers['Content-Type'] = 'application/json'
|
||||
}
|
||||
let response
|
||||
try {
|
||||
response = await fetch(path, { ...options, headers })
|
||||
} catch {
|
||||
throw new ApiError('无法连接接口。请确认已运行 start-web。')
|
||||
}
|
||||
const text = await response.text()
|
||||
let data = null
|
||||
if (text) {
|
||||
try {
|
||||
data = JSON.parse(text)
|
||||
} catch {
|
||||
data = { detail: text }
|
||||
}
|
||||
}
|
||||
if (!response.ok) throw new ApiError(errorMessage(data))
|
||||
return data
|
||||
}
|
||||
|
||||
export function getJSON(path) {
|
||||
return request(path)
|
||||
}
|
||||
|
||||
export function postJSON(path, body) {
|
||||
return request(path, { method: 'POST', body: JSON.stringify(body) })
|
||||
}
|
||||
|
||||
export function del(path) {
|
||||
return request(path, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
export function uploadFile(file) {
|
||||
const body = new FormData()
|
||||
body.append('file', file)
|
||||
return request('/api/imports', { method: 'POST', body })
|
||||
}
|
||||
|
||||
export function statFile(path) {
|
||||
return getJSON(`/api/files/stat?path=${encodeURIComponent(path)}`)
|
||||
}
|
||||
|
||||
export function downloadHref(taskId, name) {
|
||||
return `/api/results/${encodeURIComponent(taskId)}/files/${encodeURIComponent(name)}`
|
||||
}
|
||||
|
||||
export function formatTime(ts) {
|
||||
if (!ts) return ''
|
||||
const date = new Date(ts * 1000)
|
||||
const pad = (value) => String(value).padStart(2, '0')
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
|
||||
}
|
||||
|
||||
export function formatMb(bytes, digits = 2) {
|
||||
return `${(bytes / 1024 / 1024).toLocaleString('zh-CN', {
|
||||
minimumFractionDigits: digits,
|
||||
maximumFractionDigits: digits,
|
||||
})} MB`
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
<script setup>
|
||||
import { ref, watch } from 'vue'
|
||||
import { statFile, uploadFile, formatMb } from '../api'
|
||||
|
||||
const props = defineProps({
|
||||
label: { type: String, required: true },
|
||||
extension: { type: String, required: true },
|
||||
hint: { type: String, default: '' },
|
||||
modelValue: { type: String, default: '' },
|
||||
})
|
||||
const emit = defineEmits(['update:modelValue'])
|
||||
|
||||
const mode = ref('path')
|
||||
const savedPath = ref(props.modelValue || '')
|
||||
const status = ref('')
|
||||
const busy = ref(false)
|
||||
let ticket = 0
|
||||
let timer = 0
|
||||
|
||||
watch(() => props.modelValue, (value) => {
|
||||
if (mode.value === 'path' && value) savedPath.value = value
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(() => refresh(value), value ? 250 : 0)
|
||||
}, { immediate: true })
|
||||
|
||||
function setMode(next) {
|
||||
mode.value = next
|
||||
if (next === 'upload') emit('update:modelValue', '')
|
||||
else emit('update:modelValue', savedPath.value)
|
||||
}
|
||||
|
||||
async function refresh(path) {
|
||||
const current = ++ticket
|
||||
if (!path) {
|
||||
status.value = mode.value === 'upload' ? `请选择 .${props.extension} 文件` : '文件不存在'
|
||||
return
|
||||
}
|
||||
try {
|
||||
const info = await statFile(path)
|
||||
if (current !== ticket) return
|
||||
status.value = info.exists ? `已就绪 · ${formatMb(info.size, 1)}` : '文件不存在'
|
||||
} catch {
|
||||
if (current === ticket) status.value = '文件不存在'
|
||||
}
|
||||
}
|
||||
|
||||
async function customRequest({ file, onFinish, onError, onProgress }) {
|
||||
if (!file.file) {
|
||||
onError()
|
||||
return
|
||||
}
|
||||
busy.value = true
|
||||
status.value = '正在导入…'
|
||||
try {
|
||||
onProgress({ percent: 30 })
|
||||
const result = await uploadFile(file.file)
|
||||
savedPath.value = result.path
|
||||
emit('update:modelValue', result.path)
|
||||
onProgress({ percent: 100 })
|
||||
onFinish()
|
||||
} catch (error) {
|
||||
status.value = error.message || '导入失败'
|
||||
onError()
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="file-field panel">
|
||||
<div class="file-title">
|
||||
<n-tooltip v-if="hint">
|
||||
<template #trigger>
|
||||
<span class="hint">{{ label }}</span>
|
||||
</template>
|
||||
{{ hint }}
|
||||
</n-tooltip>
|
||||
<span v-else>{{ label }}</span>
|
||||
</div>
|
||||
<n-radio-group :value="mode" size="small" @update:value="setMode">
|
||||
<n-radio-button value="path">本地路径</n-radio-button>
|
||||
<n-radio-button value="upload">拖拽上传</n-radio-button>
|
||||
</n-radio-group>
|
||||
<n-input
|
||||
v-if="mode === 'path'"
|
||||
:value="modelValue"
|
||||
placeholder="文件路径"
|
||||
clearable
|
||||
@update:value="emit('update:modelValue', ($event || '').trim())"
|
||||
/>
|
||||
<n-upload
|
||||
v-else
|
||||
:accept="`.${extension}`"
|
||||
:max="1"
|
||||
:show-file-list="false"
|
||||
:custom-request="customRequest"
|
||||
:disabled="busy"
|
||||
>
|
||||
<n-button size="small" :loading="busy">选择 .{{ extension }} 文件</n-button>
|
||||
</n-upload>
|
||||
<p class="muted">{{ status }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.file-field { display: flex; flex-direction: column; gap: 8px; }
|
||||
.file-title { font-weight: 600; }
|
||||
.hint { border-bottom: 1px dashed #b7c2cc; cursor: help; }
|
||||
</style>
|
||||
@@ -0,0 +1,143 @@
|
||||
<script setup>
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { del, formatTime, getJSON, postJSON } from '../api'
|
||||
|
||||
const props = defineProps({
|
||||
task: { type: Object, required: true },
|
||||
logOpen: { type: Boolean, default: false },
|
||||
})
|
||||
const emit = defineEmits(['changed'])
|
||||
|
||||
const error = ref('')
|
||||
const confirming = ref(false)
|
||||
const removing = ref(false)
|
||||
const log = ref('')
|
||||
const logError = ref('')
|
||||
const expanded = ref(props.logOpen)
|
||||
let ticket = 0
|
||||
|
||||
const percent = computed(() => {
|
||||
if (!props.task.total) return 0
|
||||
return Math.min(100, Math.round((props.task.done || 0) / props.task.total * 100))
|
||||
})
|
||||
const countText = computed(() => {
|
||||
const counts = props.task.counts
|
||||
if (!counts || typeof counts !== 'object') return ''
|
||||
return Object.entries(counts).map(([key, value]) => `${key} ${value}`).join(',')
|
||||
})
|
||||
|
||||
watch(() => [props.task.message, props.task.done, props.task.status], () => {
|
||||
if (expanded.value) loadLog()
|
||||
})
|
||||
|
||||
function onExpand(names) {
|
||||
expanded.value = names.includes('log')
|
||||
if (expanded.value) loadLog()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (props.logOpen) loadLog()
|
||||
})
|
||||
|
||||
async function loadLog() {
|
||||
const current = ++ticket
|
||||
try {
|
||||
const data = await getJSON(`/api/tasks/${encodeURIComponent(props.task.id)}/log`)
|
||||
if (current === ticket) {
|
||||
log.value = data.text || ''
|
||||
logError.value = ''
|
||||
}
|
||||
} catch (reason) {
|
||||
if (current === ticket) logError.value = reason.message
|
||||
}
|
||||
}
|
||||
|
||||
async function stop() {
|
||||
error.value = ''
|
||||
try {
|
||||
await postJSON(`/api/tasks/${encodeURIComponent(props.task.id)}/stop`, {})
|
||||
emit('changed')
|
||||
} catch (reason) {
|
||||
error.value = reason.message
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
removing.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await del(`/api/tasks/${encodeURIComponent(props.task.id)}`)
|
||||
confirming.value = false
|
||||
emit('changed')
|
||||
} catch (reason) {
|
||||
error.value = reason.message
|
||||
} finally {
|
||||
removing.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="task-card panel">
|
||||
<header>
|
||||
<strong>{{ task.kind_label }} · {{ task.status_label }}</strong>
|
||||
<span>{{ task.id }} · {{ formatTime(task.created) }}</span>
|
||||
</header>
|
||||
<p class="message">{{ task.message }}</p>
|
||||
<n-alert v-if="error" type="error">{{ error }}</n-alert>
|
||||
<n-progress v-if="task.total" type="line" :percentage="percent" :show-indicator="false" />
|
||||
<p v-if="task.total" class="muted">{{ task.done }} / {{ task.total }}</p>
|
||||
<p v-else-if="task.done" class="muted">已处理 {{ task.done }} 条</p>
|
||||
<p v-if="countText" class="muted">{{ countText }}</p>
|
||||
<n-alert v-if="task.active && task.stop_requested" type="info">正在停止,请稍候。</n-alert>
|
||||
<div class="actions">
|
||||
<n-button v-if="task.active && !task.stop_requested" size="small" @click="stop">停止任务</n-button>
|
||||
<n-button v-if="!task.active" size="small" @click="confirming = true">删除任务</n-button>
|
||||
</div>
|
||||
<p class="muted">成果目录:{{ task.output }}</p>
|
||||
<n-collapse :default-expanded-names="logOpen ? ['log'] : []" @update:expanded-names="onExpand">
|
||||
<n-collapse-item title="运行日志" name="log">
|
||||
<n-alert v-if="logError" type="error">{{ logError }}</n-alert>
|
||||
<div class="log-box"><pre>{{ log || '等待任务输出……' }}</pre></div>
|
||||
</n-collapse-item>
|
||||
</n-collapse>
|
||||
<n-modal
|
||||
v-model:show="confirming"
|
||||
preset="card"
|
||||
title="删除任务"
|
||||
style="width: 420px"
|
||||
:segmented="{ content: true, footer: 'soft' }"
|
||||
:content-style="{ maxHeight: '180px', overflow: 'auto' }"
|
||||
>
|
||||
<p>将删除该任务记录及其成果目录,不可恢复。</p>
|
||||
<template #footer>
|
||||
<n-space justify="end">
|
||||
<n-button @click="confirming = false">取消</n-button>
|
||||
<n-button type="primary" :loading="removing" @click="remove">确认删除</n-button>
|
||||
</n-space>
|
||||
</template>
|
||||
</n-modal>
|
||||
</article>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.task-card { display: flex; flex-direction: column; gap: 6px; }
|
||||
header { display: flex; flex-direction: column; gap: 2px; }
|
||||
header span, .message { margin: 0; }
|
||||
.message { white-space: pre-wrap; }
|
||||
.actions { display: flex; gap: 8px; }
|
||||
.log-box {
|
||||
max-height: 180px;
|
||||
overflow: auto;
|
||||
background: #f7f9fb;
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
}
|
||||
pre {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font-family: Consolas, "Microsoft YaHei", monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,24 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import naive from 'naive-ui'
|
||||
import App from './App.vue'
|
||||
import './styles.css'
|
||||
import Home from './views/Home.vue'
|
||||
import Market from './views/Market.vue'
|
||||
import Buildings from './views/Buildings.vue'
|
||||
import Tasks from './views/Tasks.vue'
|
||||
import Results from './views/Results.vue'
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes: [
|
||||
{ path: '/', name: 'home', component: Home, meta: { title: '工具箱首页' } },
|
||||
{ path: '/market', name: 'market', component: Market, meta: { title: '市场网格出图' } },
|
||||
{ path: '/buildings', name: 'buildings', component: Buildings, meta: { title: '楼宇数据查询' } },
|
||||
{ path: '/tasks', name: 'tasks', component: Tasks, meta: { title: '任务中心' } },
|
||||
{ path: '/results', name: 'results', component: Results, meta: { title: '成果浏览' } },
|
||||
{ path: '/:pathMatch(.*)*', redirect: '/' },
|
||||
],
|
||||
})
|
||||
|
||||
createApp(App).use(router).use(naive).mount('#app')
|
||||
@@ -0,0 +1,64 @@
|
||||
html, body, #app {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
body {
|
||||
color: #1f2a33;
|
||||
background: #f5f7f9;
|
||||
font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
|
||||
.page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
max-width: 1120px;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
margin: 4px 0 0;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.two-col,
|
||||
.three-col,
|
||||
.metrics {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.two-col { grid-template-columns: 1fr 1fr; }
|
||||
.three-col,
|
||||
.metrics { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
|
||||
.panel {
|
||||
border: 1px solid #e4ebf1;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.muted {
|
||||
margin: 0;
|
||||
color: #66788a;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.scroll-box {
|
||||
max-height: 280px;
|
||||
overflow: auto;
|
||||
border: 1px solid #e4ebf1;
|
||||
border-radius: 6px;
|
||||
padding: 6px 10px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
@media (max-width: 860px) {
|
||||
.two-col,
|
||||
.three-col,
|
||||
.metrics { grid-template-columns: 1fr; }
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
<script setup>
|
||||
import { onMounted, onUnmounted, reactive, ref } from 'vue'
|
||||
import FileField from '../components/FileField.vue'
|
||||
import TaskCard from '../components/TaskCard.vue'
|
||||
import { getJSON, postJSON } from '../api'
|
||||
|
||||
const draft = reactive({
|
||||
ready: false,
|
||||
path: '',
|
||||
extension: 'csv',
|
||||
url: '',
|
||||
cookies: '',
|
||||
referer: '',
|
||||
start: 1,
|
||||
limit: 1000,
|
||||
concurrency: 8,
|
||||
encoding: 'gbk',
|
||||
timeout: 30,
|
||||
retries: 2,
|
||||
interval: 0.2,
|
||||
lastTaskId: '',
|
||||
})
|
||||
const error = ref('')
|
||||
const success = ref('')
|
||||
const submitting = ref(false)
|
||||
const lastTask = ref(null)
|
||||
let pollTimer = 0
|
||||
const encodings = [
|
||||
{ label: 'gbk', value: 'gbk' },
|
||||
{ label: 'utf-8-sig', value: 'utf-8-sig' },
|
||||
]
|
||||
|
||||
async function ensureDefaults() {
|
||||
if (draft.ready) return
|
||||
const [catalog, connection] = await Promise.all([
|
||||
getJSON('/api/catalog'),
|
||||
getJSON('/api/connection'),
|
||||
])
|
||||
if (!draft.path) draft.path = catalog.building_csv.path
|
||||
draft.extension = catalog.building_csv.extension || 'csv'
|
||||
draft.url = connection.URL || ''
|
||||
draft.cookies = connection.COOKIES || ''
|
||||
draft.referer = connection.REFERER || ''
|
||||
draft.ready = true
|
||||
}
|
||||
|
||||
async function refreshTask() {
|
||||
if (!draft.lastTaskId) return
|
||||
try {
|
||||
lastTask.value = await getJSON(`/api/tasks/${encodeURIComponent(draft.lastTaskId)}`)
|
||||
} catch {
|
||||
// 轮询失败时保留上一帧。
|
||||
}
|
||||
}
|
||||
|
||||
function numbersReady() {
|
||||
return [draft.start, draft.limit, draft.concurrency, draft.timeout, draft.retries, draft.interval]
|
||||
.every((value) => typeof value === 'number')
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
error.value = ''
|
||||
success.value = ''
|
||||
if (!draft.path) {
|
||||
error.value = '请先导入楼宇轮廓文件。'
|
||||
return
|
||||
}
|
||||
if (!numbersReady()) {
|
||||
error.value = '请填写完整参数。'
|
||||
return
|
||||
}
|
||||
const url = draft.url.trim()
|
||||
const cookies = draft.cookies.trim()
|
||||
const urlOk = url.startsWith('http://') || url.startsWith('https://')
|
||||
if ((url || cookies) && (!urlOk || !cookies)) {
|
||||
error.value = '服务地址和登录信息需同时填写,且地址以 http(s):// 开头。'
|
||||
return
|
||||
}
|
||||
submitting.value = true
|
||||
try {
|
||||
const result = await postJSON('/api/tasks', {
|
||||
kind: 'buildings',
|
||||
params: {
|
||||
INPUT_CSV: draft.path,
|
||||
INPUT_ENCODING: draft.encoding,
|
||||
START_ROW: draft.start,
|
||||
LIMIT: draft.limit || null,
|
||||
CONCURRENCY: draft.concurrency,
|
||||
TIMEOUT: draft.timeout,
|
||||
MAX_RETRIES: draft.retries,
|
||||
REQUEST_INTERVAL: draft.interval,
|
||||
},
|
||||
credentials: { URL: url, COOKIES: cookies, REFERER: draft.referer.trim() },
|
||||
})
|
||||
draft.lastTaskId = result.id
|
||||
success.value = '任务已启动,可在任务中心查看进度。'
|
||||
await refreshTask()
|
||||
} catch (reason) {
|
||||
error.value = reason.message
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await ensureDefaults()
|
||||
} catch (reason) {
|
||||
error.value = reason.message
|
||||
}
|
||||
await refreshTask()
|
||||
pollTimer = setInterval(refreshTask, 2000)
|
||||
})
|
||||
|
||||
onUnmounted(() => clearInterval(pollTimer))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<teleport to="#page-actions">
|
||||
<n-button type="primary" :loading="submitting" :disabled="!draft.ready" @click="submit">开始查询</n-button>
|
||||
</teleport>
|
||||
<p class="muted">按楼宇轮廓(WKT)查询:先计算落在轮廓内部的点,再按该点查询。</p>
|
||||
<n-alert v-if="error" type="error">{{ error }}</n-alert>
|
||||
<n-alert v-if="success" type="success">{{ success }}</n-alert>
|
||||
<FileField v-model="draft.path" label="楼宇轮廓清单" :extension="draft.extension" hint="默认 source/NRBuildPolygon.csv" />
|
||||
<n-form label-placement="left" label-width="168" @submit.prevent="submit">
|
||||
<n-form-item label-placement="top">
|
||||
<template #label>
|
||||
<n-tooltip>
|
||||
<template #trigger><span class="tip">连接信息</span></template>
|
||||
默认显示脚本内配置或上次保存值。开始查询时写入本机,不进入任务记录。
|
||||
</n-tooltip>
|
||||
</template>
|
||||
<div class="stack">
|
||||
<n-form-item label="服务地址" :show-feedback="false">
|
||||
<n-input v-model:value="draft.url" clearable placeholder="https://...wfs?..." />
|
||||
</n-form-item>
|
||||
<n-form-item label="登录信息(Cookies)" :show-feedback="false">
|
||||
<n-input v-model:value="draft.cookies" type="password" show-password-on="click" clearable placeholder="CASTGC=..." />
|
||||
</n-form-item>
|
||||
<n-form-item label="来源页(可留空)" :show-feedback="false">
|
||||
<n-input v-model:value="draft.referer" clearable placeholder="可留空" />
|
||||
</n-form-item>
|
||||
</div>
|
||||
</n-form-item>
|
||||
<div class="three-col">
|
||||
<n-form-item label="起始行">
|
||||
<n-input-number v-model:value="draft.start" :min="1" :precision="0" style="width: 100%" />
|
||||
</n-form-item>
|
||||
<n-form-item>
|
||||
<template #label>
|
||||
<n-tooltip><template #trigger><span class="tip">查询数量</span></template>0 表示全部</n-tooltip>
|
||||
</template>
|
||||
<n-input-number v-model:value="draft.limit" :min="0" :precision="0" style="width: 100%" />
|
||||
</n-form-item>
|
||||
<n-form-item label="并发数">
|
||||
<n-input-number v-model:value="draft.concurrency" :min="1" :max="32" :precision="0" style="width: 100%" />
|
||||
</n-form-item>
|
||||
</div>
|
||||
<n-form-item>
|
||||
<template #label>
|
||||
<n-tooltip>
|
||||
<template #trigger><span class="tip">文件编码</span></template>
|
||||
按内容自动识别,识别不出时按此项
|
||||
</n-tooltip>
|
||||
</template>
|
||||
<n-select v-model:value="draft.encoding" :options="encodings" />
|
||||
</n-form-item>
|
||||
<n-collapse>
|
||||
<n-collapse-item title="高级参数" name="advanced">
|
||||
<div class="three-col">
|
||||
<n-form-item label="超时(秒)">
|
||||
<n-input-number v-model:value="draft.timeout" :min="1" :max="300" :precision="0" style="width: 100%" />
|
||||
</n-form-item>
|
||||
<n-form-item label="失败重试">
|
||||
<n-input-number v-model:value="draft.retries" :min="0" :max="10" :precision="0" style="width: 100%" />
|
||||
</n-form-item>
|
||||
<n-form-item label="请求间隔(秒)">
|
||||
<n-input-number v-model:value="draft.interval" :min="0" :max="60" :step="0.1" style="width: 100%" />
|
||||
</n-form-item>
|
||||
</div>
|
||||
</n-collapse-item>
|
||||
</n-collapse>
|
||||
</n-form>
|
||||
<TaskCard v-if="lastTask" :task="lastTask" log-open @changed="refreshTask" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.stack { display: flex; flex-direction: column; gap: 8px; width: 100%; }
|
||||
.tip { border-bottom: 1px dashed #b7c2cc; cursor: help; }
|
||||
</style>
|
||||
@@ -0,0 +1,75 @@
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { getJSON } from '../api'
|
||||
|
||||
const router = useRouter()
|
||||
const error = ref('')
|
||||
const loading = ref(false)
|
||||
const home = ref({ running: 0, tasks: 0, archives: 0, sources: [] })
|
||||
const columns = [
|
||||
{ title: '数据源', key: 'label', width: 140 },
|
||||
{ title: '状态', key: 'status', width: 90 },
|
||||
{ title: '文件', key: 'file', ellipsis: { tooltip: true } },
|
||||
{ title: '大小 MB', key: 'size_mb', width: 100 },
|
||||
]
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
home.value = await getJSON('/api/home')
|
||||
} catch (reason) {
|
||||
error.value = reason.message
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<teleport to="#page-actions">
|
||||
<n-button :loading="loading" @click="load">刷新</n-button>
|
||||
</teleport>
|
||||
<n-alert type="info">
|
||||
这是供对比的 Vue 界面,Streamlit 仍从 start-ui.cmd 进入。几何编辑和规则引擎是后续能力,当前未提供。
|
||||
</n-alert>
|
||||
<n-alert v-if="error" type="error">{{ error }}</n-alert>
|
||||
<div class="metrics">
|
||||
<div class="panel metric"><span>正在运行</span><strong>{{ home.running }}</strong></div>
|
||||
<div class="panel metric"><span>任务记录</span><strong>{{ home.tasks }}</strong></div>
|
||||
<div class="panel metric"><span>成果包</span><strong>{{ home.archives }}</strong></div>
|
||||
</div>
|
||||
<h2 class="section-title">选择工具</h2>
|
||||
<div class="two-col">
|
||||
<div class="panel tool">
|
||||
<strong>市场网格出图</strong>
|
||||
<p class="muted">按市场生成信号图和成果包。</p>
|
||||
<n-button type="primary" @click="router.push({ name: 'market' })">开始出图</n-button>
|
||||
</div>
|
||||
<div class="panel tool">
|
||||
<strong>楼宇数据查询</strong>
|
||||
<p class="muted">按坐标批量查询楼宇信息。</p>
|
||||
<n-button type="primary" @click="router.push({ name: 'buildings' })">开始查询</n-button>
|
||||
</div>
|
||||
</div>
|
||||
<h2 class="section-title">默认数据源</h2>
|
||||
<n-data-table
|
||||
size="small"
|
||||
:columns="columns"
|
||||
:data="home.sources"
|
||||
:bordered="true"
|
||||
:max-height="320"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.tool { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; }
|
||||
.metric { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
|
||||
.metric span { color: #66788a; }
|
||||
.metric strong { font-size: 22px; line-height: 1; }
|
||||
</style>
|
||||
@@ -0,0 +1,252 @@
|
||||
<script setup>
|
||||
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
|
||||
import FileField from '../components/FileField.vue'
|
||||
import TaskCard from '../components/TaskCard.vue'
|
||||
import { getJSON, postJSON } from '../api'
|
||||
|
||||
const hints = {
|
||||
MARKET_GPKG: '市场边界,默认 source/GridMap.gpkg',
|
||||
GRID_5G_GPKG: '大文件请填本地路径,不要上传',
|
||||
BUILDING_INFO_GPKG: '建筑信息',
|
||||
AOI_CSV: 'AOI 报表',
|
||||
GIS_PROJECT_SOURCE: 'QGIS 工程模板',
|
||||
NR_BUILDINGS_DATA_CSV: '楼宇查询结果。开始生成时如有需要会整理边界图层',
|
||||
}
|
||||
const draft = reactive({
|
||||
ready: false,
|
||||
paths: {},
|
||||
allMarkets: true,
|
||||
chosen: [],
|
||||
maxWorkers: 4,
|
||||
scale: 5,
|
||||
summary: true,
|
||||
maxRaster: 25,
|
||||
summaryRaster: 100,
|
||||
clipMode: 'intersects',
|
||||
padding: 0.05,
|
||||
lastTaskId: '',
|
||||
})
|
||||
const sources = ref([])
|
||||
const nr = ref(null)
|
||||
const options = ref([])
|
||||
const marketError = ref('')
|
||||
const error = ref('')
|
||||
const success = ref('')
|
||||
const submitting = ref(false)
|
||||
const loadingMarkets = ref(false)
|
||||
const lastTask = ref(null)
|
||||
let marketTicket = 0
|
||||
let marketTimer = 0
|
||||
let pollTimer = 0
|
||||
|
||||
const fileItems = computed(() => {
|
||||
const items = sources.value.map((item) => ({ ...item, hint: hints[item.key] || '' }))
|
||||
if (nr.value) items.push({ ...nr.value, hint: hints[nr.value.key] || '' })
|
||||
return items
|
||||
})
|
||||
const canStart = computed(() => draft.ready && options.value.length > 0 && !submitting.value)
|
||||
const clipOptions = [
|
||||
{ label: '与市场相交', value: 'intersects' },
|
||||
{ label: '中心点在市场内', value: 'center' },
|
||||
]
|
||||
|
||||
async function ensureCatalog() {
|
||||
const data = await getJSON('/api/catalog')
|
||||
sources.value = data.sources
|
||||
nr.value = data.nr_csv
|
||||
if (!draft.ready) {
|
||||
for (const item of data.sources) draft.paths[item.key] = item.path
|
||||
draft.paths[data.nr_csv.key] = data.nr_csv.path
|
||||
draft.ready = true
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMarkets(path) {
|
||||
const current = ++marketTicket
|
||||
loadingMarkets.value = true
|
||||
try {
|
||||
if (!path) {
|
||||
options.value = []
|
||||
marketError.value = '请先导入可用的市场边界。'
|
||||
return
|
||||
}
|
||||
const data = await getJSON(`/api/markets?path=${encodeURIComponent(path)}`)
|
||||
if (current !== marketTicket) return
|
||||
options.value = data.options || []
|
||||
draft.chosen = draft.chosen.filter((id) => options.value.some((item) => item.id === id))
|
||||
marketError.value = options.value.length ? '' : '请先导入可用的市场边界。'
|
||||
} catch (reason) {
|
||||
if (current !== marketTicket) return
|
||||
options.value = []
|
||||
marketError.value = reason.message
|
||||
} finally {
|
||||
if (current === marketTicket) loadingMarkets.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshTask() {
|
||||
if (!draft.lastTaskId) return
|
||||
try {
|
||||
lastTask.value = await getJSON(`/api/tasks/${encodeURIComponent(draft.lastTaskId)}`)
|
||||
} catch {
|
||||
// 轮询失败时保留上一帧。
|
||||
}
|
||||
}
|
||||
|
||||
function numbersReady() {
|
||||
return [draft.maxWorkers, draft.scale, draft.maxRaster, draft.summaryRaster, draft.padding]
|
||||
.every((value) => typeof value === 'number')
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
error.value = ''
|
||||
success.value = ''
|
||||
if (!canStart.value) return
|
||||
if (!numbersReady()) {
|
||||
error.value = '请填写完整参数。'
|
||||
return
|
||||
}
|
||||
const ids = draft.allMarkets ? options.value.map((item) => item.id) : [...draft.chosen]
|
||||
if (!ids.length) {
|
||||
error.value = '请至少选择一个市场网格。'
|
||||
return
|
||||
}
|
||||
for (const item of fileItems.value) {
|
||||
if (!draft.paths[item.key]) {
|
||||
error.value = '请完成所需数据的导入。'
|
||||
return
|
||||
}
|
||||
}
|
||||
submitting.value = true
|
||||
try {
|
||||
const result = await postJSON('/api/tasks', {
|
||||
kind: 'market',
|
||||
params: {
|
||||
...draft.paths,
|
||||
SELECTED_MARKET_IDS: ids,
|
||||
MAX_WORKERS: draft.maxWorkers,
|
||||
SCALE: draft.scale,
|
||||
SUMMARY_OUTPUT_ENABLED: draft.summary,
|
||||
MAX_RASTER_PIXELS: Math.round(draft.maxRaster * 1_000_000),
|
||||
SUMMARY_MAX_RASTER_PIXELS: Math.round(draft.summaryRaster * 1_000_000),
|
||||
CLIP_MODE: draft.clipMode,
|
||||
PROJECT_EXTENT_PADDING_RATIO: draft.padding,
|
||||
},
|
||||
})
|
||||
draft.lastTaskId = result.id
|
||||
success.value = '任务已启动,可在任务中心查看进度。'
|
||||
await refreshTask()
|
||||
} catch (reason) {
|
||||
error.value = reason.message
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => draft.paths.MARKET_GPKG, (path) => {
|
||||
clearTimeout(marketTimer)
|
||||
marketTimer = setTimeout(() => loadMarkets(path), 300)
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await ensureCatalog()
|
||||
await loadMarkets(draft.paths.MARKET_GPKG)
|
||||
} catch (reason) {
|
||||
error.value = reason.message
|
||||
}
|
||||
await refreshTask()
|
||||
pollTimer = setInterval(refreshTask, 2000)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
clearInterval(pollTimer)
|
||||
clearTimeout(marketTimer)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<teleport to="#page-actions">
|
||||
<n-button type="primary" :disabled="!canStart" :loading="submitting" @click="submit">开始生成</n-button>
|
||||
</teleport>
|
||||
<n-alert v-if="error" type="error">{{ error }}</n-alert>
|
||||
<n-alert v-if="success" type="success">{{ success }}</n-alert>
|
||||
<h2 class="section-title">1 · 导入数据</h2>
|
||||
<div class="two-col">
|
||||
<FileField
|
||||
v-for="item in fileItems"
|
||||
:key="item.key"
|
||||
v-model="draft.paths[item.key]"
|
||||
:label="item.label"
|
||||
:extension="item.extension"
|
||||
:hint="item.hint"
|
||||
/>
|
||||
</div>
|
||||
<h2 class="section-title">2 · 选择市场与参数</h2>
|
||||
<n-alert v-if="marketError" type="warning">{{ marketError }}</n-alert>
|
||||
<n-spin :show="loadingMarkets" size="small">
|
||||
<div class="panel market-box">
|
||||
<n-tooltip>
|
||||
<template #trigger>
|
||||
<n-checkbox v-model:checked="draft.allMarkets" :disabled="!options.length">处理全部市场</n-checkbox>
|
||||
</template>
|
||||
取消后可在下方指定市场
|
||||
</n-tooltip>
|
||||
<div v-if="options.length && !draft.allMarkets" class="scroll-box">
|
||||
<n-checkbox-group v-model:value="draft.chosen">
|
||||
<div v-for="item in options" :key="item.id" class="pick">
|
||||
<n-checkbox :value="item.id" :label="`${item.id} · ${item.name}`" />
|
||||
</div>
|
||||
</n-checkbox-group>
|
||||
</div>
|
||||
<p v-else-if="options.length" class="muted">将处理全部 {{ options.length }} 个市场</p>
|
||||
<p v-else class="muted">请先导入可用的市场边界。</p>
|
||||
</div>
|
||||
</n-spin>
|
||||
<n-form label-placement="left" label-width="176" @submit.prevent="submit">
|
||||
<div class="three-col">
|
||||
<n-form-item>
|
||||
<template #label>
|
||||
<n-tooltip><template #trigger><span class="tip">并行进程数</span></template>1 到 16,默认 4</n-tooltip>
|
||||
</template>
|
||||
<n-input-number v-model:value="draft.maxWorkers" :min="1" :max="16" :precision="0" style="width: 100%" />
|
||||
</n-form-item>
|
||||
<n-form-item>
|
||||
<template #label>
|
||||
<n-tooltip><template #trigger><span class="tip">分辨率倍数</span></template>放大查看更清晰,默认 5</n-tooltip>
|
||||
</template>
|
||||
<n-input-number v-model:value="draft.scale" :min="0.1" :max="20" :step="0.5" style="width: 100%" />
|
||||
</n-form-item>
|
||||
<n-form-item label="全量汇总包">
|
||||
<n-checkbox v-model:checked="draft.summary">生成全量汇总包</n-checkbox>
|
||||
</n-form-item>
|
||||
</div>
|
||||
<n-collapse>
|
||||
<n-collapse-item title="更多参数" name="more">
|
||||
<div class="two-col">
|
||||
<n-form-item label="单市场像元上限(百万)">
|
||||
<n-input-number v-model:value="draft.maxRaster" :min="1" :max="100" :precision="0" style="width: 100%" />
|
||||
</n-form-item>
|
||||
<n-form-item label="汇总像元上限(百万)">
|
||||
<n-input-number v-model:value="draft.summaryRaster" :min="1" :max="200" :precision="0" style="width: 100%" />
|
||||
</n-form-item>
|
||||
<n-form-item label="网格纳入方式">
|
||||
<n-select v-model:value="draft.clipMode" :options="clipOptions" />
|
||||
</n-form-item>
|
||||
<n-form-item label="地图留白比例">
|
||||
<n-input-number v-model:value="draft.padding" :min="0" :max="1" :step="0.01" style="width: 100%" />
|
||||
</n-form-item>
|
||||
</div>
|
||||
</n-collapse-item>
|
||||
</n-collapse>
|
||||
</n-form>
|
||||
<TaskCard v-if="lastTask" :task="lastTask" log-open @changed="refreshTask" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.market-box { display: flex; flex-direction: column; gap: 8px; }
|
||||
.pick { padding: 2px 0; }
|
||||
.tip { border-bottom: 1px dashed #b7c2cc; cursor: help; }
|
||||
</style>
|
||||
@@ -0,0 +1,124 @@
|
||||
<script setup>
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { downloadHref, formatMb, getJSON, postJSON } from '../api'
|
||||
|
||||
const tasks = ref([])
|
||||
const selectedId = ref(null)
|
||||
const directory = ref('')
|
||||
const files = ref([])
|
||||
const error = ref('')
|
||||
const notice = ref('')
|
||||
const opening = ref(false)
|
||||
|
||||
const options = computed(() => tasks.value.map((task) => ({ label: task.label, value: task.id })))
|
||||
|
||||
async function loadTasks() {
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await getJSON('/api/results')
|
||||
tasks.value = data.tasks || []
|
||||
if (!tasks.value.length) {
|
||||
selectedId.value = null
|
||||
files.value = []
|
||||
directory.value = ''
|
||||
return
|
||||
}
|
||||
if (!tasks.value.some((task) => task.id === selectedId.value)) selectedId.value = tasks.value[0].id
|
||||
} catch (reason) {
|
||||
error.value = reason.message
|
||||
}
|
||||
}
|
||||
|
||||
async function loadFiles(id) {
|
||||
notice.value = ''
|
||||
if (!id) {
|
||||
files.value = []
|
||||
directory.value = ''
|
||||
return
|
||||
}
|
||||
try {
|
||||
const data = await getJSON(`/api/results/${encodeURIComponent(id)}/files`)
|
||||
directory.value = data.directory || ''
|
||||
files.value = data.files || []
|
||||
error.value = ''
|
||||
} catch (reason) {
|
||||
files.value = []
|
||||
error.value = reason.message
|
||||
}
|
||||
}
|
||||
|
||||
async function openDirectory() {
|
||||
if (!selectedId.value) return
|
||||
opening.value = true
|
||||
notice.value = ''
|
||||
try {
|
||||
await postJSON(`/api/results/${encodeURIComponent(selectedId.value)}/open`, {})
|
||||
} catch (reason) {
|
||||
error.value = reason.message
|
||||
} finally {
|
||||
opening.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function showLarge(file) {
|
||||
notice.value = `${file.name}(${formatMb(file.size)})较大,请从本地目录复制:${directory.value}`
|
||||
}
|
||||
|
||||
watch(selectedId, loadFiles)
|
||||
onMounted(loadTasks)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<teleport to="#page-actions">
|
||||
<n-button :disabled="!selectedId" :loading="opening" @click="openDirectory">打开目录</n-button>
|
||||
</teleport>
|
||||
<n-alert v-if="error" type="error">{{ error }}</n-alert>
|
||||
<n-alert v-if="notice" type="info">{{ notice }}</n-alert>
|
||||
<n-empty v-if="!tasks.length" description="暂无成果。完成出图或查询后会显示在这里。" />
|
||||
<template v-else>
|
||||
<n-form label-placement="left" label-width="88">
|
||||
<n-form-item label="成果清单">
|
||||
<n-select v-model:value="selectedId" :options="options" />
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<p class="muted">{{ directory }}</p>
|
||||
<n-empty v-if="!files.length" description="该任务暂无文件。" />
|
||||
<div v-else class="file-list">
|
||||
<div v-for="file in files" :key="file.name" class="file-row">
|
||||
<span class="file-name" :title="file.name">{{ file.name }}</span>
|
||||
<span class="muted size">{{ formatMb(file.size) }}</span>
|
||||
<a v-if="!file.too_large" class="download" :href="downloadHref(selectedId, file.name)" :download="file.name">下载</a>
|
||||
<n-button v-else text type="primary" @click="showLarge(file)">从本地目录复制</n-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.file-list {
|
||||
max-height: 420px;
|
||||
overflow: auto;
|
||||
border: 1px solid #e4ebf1;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
}
|
||||
.file-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 110px 128px;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
padding: 7px 10px;
|
||||
border-bottom: 1px solid #f0f3f6;
|
||||
}
|
||||
.file-row:last-child { border-bottom: 0; }
|
||||
.file-name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-family: Consolas, "Microsoft YaHei", monospace;
|
||||
}
|
||||
.size { text-align: right; }
|
||||
.download { justify-self: end; color: #1f6f8b; }
|
||||
</style>
|
||||
@@ -0,0 +1,86 @@
|
||||
<script setup>
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import TaskCard from '../components/TaskCard.vue'
|
||||
import { getJSON, postJSON } from '../api'
|
||||
|
||||
const tasks = ref([])
|
||||
const error = ref('')
|
||||
const success = ref('')
|
||||
const confirming = ref(false)
|
||||
const clearing = ref(false)
|
||||
let pollTimer = 0
|
||||
|
||||
const finishedCount = computed(() => tasks.value.filter((task) => !task.active).length)
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const data = await getJSON('/api/tasks')
|
||||
tasks.value = data.tasks || []
|
||||
error.value = ''
|
||||
} catch (reason) {
|
||||
error.value = reason.message
|
||||
}
|
||||
}
|
||||
|
||||
async function clearAll() {
|
||||
clearing.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const result = await postJSON('/api/tasks/clear', {})
|
||||
success.value = result.message
|
||||
confirming.value = false
|
||||
await load()
|
||||
} catch (reason) {
|
||||
error.value = reason.message
|
||||
} finally {
|
||||
clearing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
load()
|
||||
pollTimer = setInterval(load, 2000)
|
||||
})
|
||||
onUnmounted(() => clearInterval(pollTimer))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<teleport to="#page-actions">
|
||||
<n-button :disabled="!finishedCount || confirming" @click="confirming = true">清空全部任务</n-button>
|
||||
</teleport>
|
||||
<n-alert v-if="error" type="error">{{ error }}</n-alert>
|
||||
<n-alert v-if="success" type="success">{{ success }}</n-alert>
|
||||
<n-empty v-if="!tasks.length" description="暂无任务。" />
|
||||
<div v-else class="task-list">
|
||||
<TaskCard v-for="task in tasks" :key="task.id" :task="task" @changed="load" />
|
||||
</div>
|
||||
<n-modal
|
||||
v-model:show="confirming"
|
||||
preset="card"
|
||||
title="清空全部任务"
|
||||
style="width: 440px"
|
||||
:segmented="{ content: true, footer: 'soft' }"
|
||||
:content-style="{ maxHeight: '200px', overflow: 'auto' }"
|
||||
>
|
||||
<p>将删除 {{ finishedCount }} 个已结束任务的记录和成果目录,不可恢复。运行中的任务不会删除。</p>
|
||||
<template #footer>
|
||||
<n-space justify="end">
|
||||
<n-button @click="confirming = false">取消</n-button>
|
||||
<n-button type="primary" :loading="clearing" @click="clearAll">确认清空</n-button>
|
||||
</n-space>
|
||||
</template>
|
||||
</n-modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.task-list {
|
||||
max-height: calc(100vh - 150px);
|
||||
overflow: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding-right: 2px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,22 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: {
|
||||
host: '127.0.0.1',
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://127.0.0.1:8765',
|
||||
changeOrigin: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
preview: {
|
||||
host: '127.0.0.1',
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user