Files
MarketGrid/api/app.py
T

529 lines
18 KiB
Python

"""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 marketgrid import layer_edit
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
class LayerWrite(BaseModel):
path: str
wkt: str = ""
values: dict = {}
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/layer")
def layer_document(path: str = ""):
return layer_edit.read_layer(resolve_path(path))
@app.post("/api/layer/clear")
def layer_clear(body: LayerWrite):
return layer_edit.clear_features(resolve_path(body.path))
@app.post("/api/layer/features")
def layer_create(body: LayerWrite):
return layer_edit.create_feature(resolve_path(body.path), body.values, body.wkt)
@app.put("/api/layer/features/{fid}")
def layer_update(fid: int, body: LayerWrite):
return layer_edit.update_feature(resolve_path(body.path), fid, body.values, body.wkt)
@app.delete("/api/layer/features/{fid}")
def layer_remove(fid: int, path: str = ""):
return layer_edit.delete_feature(resolve_path(path), fid)
@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}