chore: 去掉 Streamlit,只保留一套界面和环境
工具箱只留 Vue 3 + Naive UI,启动改为 start.cmd;依赖合并进 requirements.txt, Python 环境只保留 .venv。
This commit is contained in:
@@ -1,6 +1,4 @@
|
|||||||
.venv/
|
.venv/
|
||||||
.venv-ui/
|
|
||||||
.venv-web/
|
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
node_modules/
|
node_modules/
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
[server]
|
|
||||||
address = "127.0.0.1"
|
|
||||||
maxUploadSize = 4096
|
|
||||||
runOnSave = true
|
|
||||||
|
|
||||||
[browser]
|
|
||||||
gatherUsageStats = false
|
|
||||||
|
|
||||||
[client]
|
|
||||||
toolbarMode = "minimal"
|
|
||||||
|
|
||||||
[theme]
|
|
||||||
primaryColor = "#0D827A"
|
|
||||||
backgroundColor = "#F7F9FC"
|
|
||||||
secondaryBackgroundColor = "#EDF2F7"
|
|
||||||
textColor = "#163047"
|
|
||||||
font = "sans serif"
|
|
||||||
@@ -2,20 +2,23 @@
|
|||||||
|
|
||||||
本项目按 `source/GridMap.gpkg` 中的市场网格切分 Grid 和 BuildingInfo 数据,并为每个市场网格生成一个 zip 结果包。
|
本项目按 `source/GridMap.gpkg` 中的市场网格切分 Grid 和 BuildingInfo 数据,并为每个市场网格生成一个 zip 结果包。
|
||||||
|
|
||||||
## 本地工具箱界面
|
## 工具箱界面
|
||||||
|
|
||||||
Windows 双击 `start-ui.cmd`,或在项目目录运行 `./start-ui.ps1`。启动时会先结束已有的工具箱界面进程,再使用独立的 `.venv-ui` 环境启动 Streamlit;控制台会打印入口地址(默认 `http://127.0.0.1:8501`)并打开浏览器。支持 Python 3.13;安装了 uv 时自动使用 uv 创建环境,否则使用系统 Python。原 `.venv` 不会被覆盖。
|
界面是 Vue 3 + Naive UI。Windows 双击 `start.cmd`,或在项目目录运行 `./start.ps1`。脚本会先结束本项目已有的页面和接口进程,再用 `.venv` 安装 `requirements.txt`,并在 `web/` 安装前端依赖。接口只监听 `http://127.0.0.1:8765`,页面是 `http://127.0.0.1:5173`(开发服务把 `/api` 代理到接口)。控制台打印这两个地址并打开浏览器。关闭窗口会停止页面和接口。支持 Python 3.13;安装了 uv 时自动使用 uv 创建环境,否则使用系统 Python。
|
||||||
|
|
||||||
手动启动(包括 Linux):
|
手动启动(包括 Linux):
|
||||||
|
|
||||||
```text
|
```text
|
||||||
python -m venv .venv-ui
|
python -m venv .venv
|
||||||
# 激活 .venv-ui 后执行
|
# 激活 .venv 后执行
|
||||||
python -m pip install -r requirements-ui.txt
|
python -m pip install -r requirements.txt
|
||||||
python -m streamlit run app.py
|
python -m uvicorn api.app:app --host 127.0.0.1 --port 8765
|
||||||
|
# 另一个终端,在 web/ 目录
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
界面包含五个可用页面:
|
界面包含五个页面:
|
||||||
|
|
||||||
- **工具箱首页**:数据状态与任务概况。
|
- **工具箱首页**:数据状态与任务概况。
|
||||||
- **市场网格出图**:导入数据后生成市场成果包。
|
- **市场网格出图**:导入数据后生成市场成果包。
|
||||||
@@ -23,23 +26,15 @@ python -m streamlit run app.py
|
|||||||
- **任务中心**:查看进度、停止任务;已结束任务可单个删除或一键清空(连同成果目录,需二次确认,运行中的任务不会删除)。
|
- **任务中心**:查看进度、停止任务;已结束任务可单个删除或一键清空(连同成果目录,需二次确认,运行中的任务不会删除)。
|
||||||
- **成果浏览**:查看成果清单,按文件下载。
|
- **成果浏览**:查看成果清单,按文件下载。
|
||||||
|
|
||||||
每次任务使用 `output/toolbox/tasks/<任务ID>/results/`。历史正式成果已导入为任务 `20260815-a0000001`,界面只按任务清单浏览和下载,不再单独区分“现有正式成果”。任务配置、状态和日志持久保存,连接参数只通过标准输入传递,不进入任务历史。上传副本放在 `output/toolbox/imports/`。大文件推荐使用本地路径;Streamlit 上传会占用额外内存,单文件上限 4 GB。超过 128 MB 的成果请从本地目录复制,避免下载占用服务内存。
|
每次任务使用 `output/toolbox/tasks/<任务ID>/results/`。历史正式成果已导入为任务 `20260815-a0000001`,界面只按任务清单浏览和下载,不再单独区分“现有正式成果”。任务配置、状态和日志持久保存,连接参数只通过标准输入传递,不进入任务历史。选择的文件会复制到 `output/toolbox/imports/`;大文件可以直接填写本地路径。超过 128 MB 的成果请从本地目录复制,避免下载占用服务内存。
|
||||||
|
|
||||||
同一时间只运行一个工具箱任务。任务由独立 Python 进程执行,刷新、切页或关闭浏览器不会重启或中断计算。出图停止在几何批处理边界生效,当前文件写入/打包可能需要等待;楼宇查询停止领取新坐标,正在处理的请求和结果写完后退出。已完成文件保留,失败和停止不标为成功;重启后意外退出的进程标为中断。**起始行只控制输入跳过,不是自动断点续传**,重试会创建新任务成果。
|
同一时间只运行一个工具箱任务。任务由独立 Python 进程执行,刷新、切页或关闭浏览器不会重启或中断计算。出图停止在几何批处理边界生效,当前文件写入/打包可能需要等待;楼宇查询停止领取新坐标,正在处理的请求和结果写完后退出。已完成文件保留,失败和停止不标为成功;重启后意外退出的进程标为中断。**起始行只控制输入跳过,不是自动断点续传**,重试会创建新任务成果。
|
||||||
|
|
||||||
界面导入 `source/江门市AOI级报表.csv` 后,按 AOI 与市场网格的最大接触面积自动写入 `source/AOI级报表_市场网格匹配.gpkg` 的 `所属市场网格`。只贴边、没有正面积的不归属。用户量仍停用。4G Grid 可以在导入区选择,当前出图不读取,留给后续 4G+5G 采样点统计。
|
界面导入 `source/江门市AOI级报表.csv` 后,按 AOI 与市场网格的最大接触面积自动写入 `source/AOI级报表_市场网格匹配.gpkg` 的 `所属市场网格`。只贴边、没有正面积的不归属。用户量仍停用。4G Grid 可以在导入区选择,当前出图不读取,留给后续 4G+5G 采样点统计。
|
||||||
|
|
||||||
## Vue 工具箱
|
|
||||||
|
|
||||||
Streamlit 工具箱仍用 `start-ui.cmd` 打开 `http://127.0.0.1:8501`。Vue 工具箱与它共用任务进程、任务记录和成果目录,两套可以同时开着,端口互不占用。
|
|
||||||
|
|
||||||
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 的文件请从本地目录复制。
|
|
||||||
|
|
||||||
市场网格出图页的导入区一行一个文件:标题、路径、选择文件。「市场边界」行的「操作」菜单可以编辑图层,增删改面和字段;「QGIS 工程模板」行可以增删改模板图层的名称、勾选、数据源和顺序。并行进程数、分辨率倍数和其他出图参数在「设置」弹窗里。规则引擎仍未做。
|
市场网格出图页的导入区一行一个文件:标题、路径、选择文件。「市场边界」行的「操作」菜单可以编辑图层,增删改面和字段;「QGIS 工程模板」行可以增删改模板图层的名称、勾选、数据源和顺序。并行进程数、分辨率倍数和其他出图参数在「设置」弹窗里。规则引擎仍未做。
|
||||||
|
|
||||||
接口测试:`.venv-web/Scripts/python.exe -m unittest tests.test_web_api -v`。前端构建:在 `web/` 执行 `npm run build`。
|
接口测试:`.venv/Scripts/python.exe -m unittest tests.test_web_api -v`。前端构建:在 `web/` 执行 `npm run build`。
|
||||||
|
|
||||||
## 代码结构
|
## 代码结构
|
||||||
|
|
||||||
@@ -56,16 +51,15 @@ Windows 双击 `start-web.cmd`,或在项目目录运行 `./start-web.ps1`。
|
|||||||
| `marketgrid/legacy_user_count.py`、`metrics.py` | 保留的历史用户量与指标算法 |
|
| `marketgrid/legacy_user_count.py`、`metrics.py` | 保留的历史用户量与指标算法 |
|
||||||
| `marketgrid/styles/` | 写进成果和工程的 QML、图层模板与默认勾选 |
|
| `marketgrid/styles/` | 写进成果和工程的 QML、图层模板与默认勾选 |
|
||||||
| `toolbox/` | 输入验证、独立任务进程、任务记录和成果读取 |
|
| `toolbox/` | 输入验证、独立任务进程、任务记录和成果读取 |
|
||||||
| `ui/` | Streamlit 页面和通用文件导入、任务进度组件 |
|
| `api/`、`web/` | Vue 3 + Naive UI 工具箱的本地接口和页面 |
|
||||||
| `api/`、`web/` | Vue 工具箱的本地接口和页面 |
|
|
||||||
| `xyzserver/` | online 统计底图服务(Go),说明见 `xyzserver/README.md` |
|
| `xyzserver/` | online 统计底图服务(Go),说明见 `xyzserver/README.md` |
|
||||||
| `GetNRBuildingsData.py` | 可独立运行的异步楼宇查询 |
|
| `GetNRBuildingsData.py` | 可独立运行的异步楼宇查询 |
|
||||||
|
|
||||||
测试:`.venv-ui/Scripts/python.exe -m unittest discover -s tests -v`。
|
测试:`.venv/Scripts/python.exe -m unittest discover -s tests -v`。
|
||||||
|
|
||||||
## 独立楼宇批量查询
|
## 独立楼宇批量查询
|
||||||
|
|
||||||
`GetNRBuildingsData.py` 独立运行,不调用 `main.py`。先运行 `python -m pip install -r requirements-nr-buildings.txt` 安装依赖 `aiohttp` 和 `shapely`。
|
`GetNRBuildingsData.py` 独立运行,不调用 `main.py`。依赖已包含在 `requirements.txt` 中。
|
||||||
|
|
||||||
1. 在脚本顶部填写完整 WFS `URL`(含 `ak`、`sig` 等原参数)和 `COOKIES`。
|
1. 在脚本顶部填写完整 WFS `URL`(含 `ak`、`sig` 等原参数)和 `COOKIES`。
|
||||||
2. 默认读取 `source/NRBuildPolygon.csv`,使用 `WKT`(楼宇轮廓,`MULTIPOLYGON`/`POLYGON`,EPSG:4326)和 `building_id` 两列,输入编码按内容自动判定(含 BOM 或能通过严格 UTF-8 解码即 UTF-8,否则 GBK;纯 ASCII 沿用默认 GBK),读不出 `WKT`/`building_id` 表头才报错。
|
2. 默认读取 `source/NRBuildPolygon.csv`,使用 `WKT`(楼宇轮廓,`MULTIPOLYGON`/`POLYGON`,EPSG:4326)和 `building_id` 两列,输入编码按内容自动判定(含 BOM 或能通过严格 UTF-8 解码即 UTF-8,否则 GBK;纯 ASCII 沿用默认 GBK),读不出 `WKT`/`building_id` 表头才报错。
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
"""本地工具箱入口:streamlit run app.py。"""
|
|
||||||
import streamlit as st
|
|
||||||
from ui import home_page, market_page, building_page, tasks_page, results_page
|
|
||||||
from ui.layout import apply_compact_layout
|
|
||||||
|
|
||||||
st.set_page_config(page_title="MarketGrid 工具箱", page_icon="🗺️", layout="wide")
|
|
||||||
apply_compact_layout()
|
|
||||||
pages = {
|
|
||||||
"home": st.Page(home_page.render, title="工具箱首页", icon="🏠", default=True),
|
|
||||||
"market": st.Page(market_page.render, title="市场网格出图", icon="🗺️", url_path="market"),
|
|
||||||
"buildings": st.Page(building_page.render, title="楼宇数据查询", icon="🏢", url_path="buildings"),
|
|
||||||
"tasks": st.Page(tasks_page.render, title="任务中心", icon="⏳", url_path="tasks"),
|
|
||||||
"results": st.Page(results_page.render, title="成果浏览", icon="📦", url_path="results"),
|
|
||||||
}
|
|
||||||
st.session_state["pages"] = pages
|
|
||||||
nav = st.navigation(
|
|
||||||
{"工具": [pages["home"], pages["market"], pages["buildings"]],
|
|
||||||
"工作记录": [pages["tasks"], pages["results"]]},
|
|
||||||
position="hidden",
|
|
||||||
)
|
|
||||||
with st.sidebar:
|
|
||||||
st.markdown("## MarketGrid")
|
|
||||||
st.caption("空间数据工具箱")
|
|
||||||
st.markdown("**工具**")
|
|
||||||
st.page_link(pages["home"], label="工具箱首页", icon="🏠", use_container_width=True)
|
|
||||||
st.page_link(pages["market"], label="市场网格出图", icon="🗺️", use_container_width=True)
|
|
||||||
st.page_link(pages["buildings"], label="楼宇数据查询", icon="🏢", use_container_width=True)
|
|
||||||
st.markdown("**工作记录**")
|
|
||||||
st.page_link(pages["tasks"], label="任务中心", icon="⏳", use_container_width=True)
|
|
||||||
st.page_link(pages["results"], label="成果浏览", icon="📦", use_container_width=True)
|
|
||||||
nav.run()
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
aiohttp==3.14.3
|
|
||||||
shapely==2.1.2
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
-r requirements.txt
|
|
||||||
-r requirements-nr-buildings.txt
|
|
||||||
streamlit==1.64.0
|
|
||||||
filelock==3.32.7
|
|
||||||
psutil==7.2.2
|
|
||||||
Pillow==12.3.0
|
|
||||||
openpyxl==3.1.5
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
-r requirements-ui.txt
|
|
||||||
fastapi==0.143.0
|
|
||||||
uvicorn==0.54.0
|
|
||||||
python-multipart==0.0.32
|
|
||||||
httpx==0.28.1
|
|
||||||
@@ -1,3 +1,12 @@
|
|||||||
numpy==2.5.1
|
numpy==2.5.1
|
||||||
shapely==2.1.2
|
shapely==2.1.2
|
||||||
tifffile==2026.6.1
|
tifffile==2026.6.1
|
||||||
|
aiohttp==3.14.3
|
||||||
|
filelock==3.32.7
|
||||||
|
psutil==7.2.2
|
||||||
|
Pillow==12.3.0
|
||||||
|
openpyxl==3.1.5
|
||||||
|
fastapi==0.143.0
|
||||||
|
uvicorn==0.54.0
|
||||||
|
python-multipart==0.0.32
|
||||||
|
httpx==0.28.1
|
||||||
|
|||||||
-106
@@ -1,106 +0,0 @@
|
|||||||
$ErrorActionPreference = 'Stop'
|
|
||||||
Set-Location -LiteralPath $PSScriptRoot
|
|
||||||
$env:PYTHONIOENCODING = 'utf-8'
|
|
||||||
$HostAddress = '127.0.0.1'
|
|
||||||
$Port = 8501
|
|
||||||
$EntryUrl = "http://${HostAddress}:${Port}"
|
|
||||||
$Python = Join-Path $PSScriptRoot '.venv-ui\Scripts\python.exe'
|
|
||||||
|
|
||||||
function Test-PortInUse {
|
|
||||||
$pattern = ":$Port\s+"
|
|
||||||
netstat -ano | Where-Object { $_ -match $pattern -and $_ -match 'LISTENING' }
|
|
||||||
}
|
|
||||||
|
|
||||||
function Stop-ExistingUi {
|
|
||||||
$root = $PSScriptRoot
|
|
||||||
$ids = @{}
|
|
||||||
Get-CimInstance Win32_Process | Where-Object {
|
|
||||||
$_.Name -match '^python(\.exe)?$' -and $_.CommandLine -and ($_.CommandLine -match 'streamlit')
|
|
||||||
} | ForEach-Object {
|
|
||||||
$cmd = $_.CommandLine
|
|
||||||
$fromProject = $cmd.IndexOf($root, [StringComparison]::OrdinalIgnoreCase) -ge 0
|
|
||||||
$genericApp = $cmd -match 'streamlit.*run.*app\.py'
|
|
||||||
if ($fromProject -or $genericApp) {
|
|
||||||
$ids[[int]$_.ProcessId] = $true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Test-PortInUse | ForEach-Object {
|
|
||||||
if ($_ -match '\s(\d+)\s*$') {
|
|
||||||
$ids[[int]$Matches[1]] = $true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
foreach ($id in @($ids.Keys)) {
|
|
||||||
if ($id -gt 0) {
|
|
||||||
Stop-Process -Id $id -Force -ErrorAction SilentlyContinue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$deadline = (Get-Date).AddSeconds(10)
|
|
||||||
do {
|
|
||||||
if (-not (Test-PortInUse)) { return }
|
|
||||||
Start-Sleep -Milliseconds 200
|
|
||||||
} while ((Get-Date) -lt $deadline)
|
|
||||||
throw "端口 $Port 仍被占用,无法启动。"
|
|
||||||
}
|
|
||||||
|
|
||||||
function Wait-UiReady {
|
|
||||||
param($Process)
|
|
||||||
$deadline = (Get-Date).AddSeconds(90)
|
|
||||||
while ((Get-Date) -lt $deadline) {
|
|
||||||
if ($Process.HasExited) {
|
|
||||||
throw 'Streamlit 进程已退出,启动失败。'
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
$client = New-Object System.Net.Sockets.TcpClient
|
|
||||||
$client.Connect($HostAddress, $Port)
|
|
||||||
$client.Close()
|
|
||||||
return
|
|
||||||
} catch {
|
|
||||||
Start-Sleep -Milliseconds 300
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw "等待界面启动超时:$EntryUrl"
|
|
||||||
}
|
|
||||||
|
|
||||||
function Ensure-UiEnvironment {
|
|
||||||
if (Get-Command uv -ErrorAction SilentlyContinue) {
|
|
||||||
if (-not (Test-Path $Python)) {
|
|
||||||
uv venv .venv-ui --python 3.13
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw '创建 Python 环境失败。' }
|
|
||||||
}
|
|
||||||
uv pip install --python $Python -r requirements-ui.txt
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw '安装依赖失败。' }
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (-not (Test-Path $Python)) {
|
|
||||||
python -m venv .venv-ui
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw '创建 Python 环境失败。' }
|
|
||||||
}
|
|
||||||
& $Python -m pip install -r requirements-ui.txt
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw '安装依赖失败。' }
|
|
||||||
}
|
|
||||||
|
|
||||||
Stop-ExistingUi
|
|
||||||
Ensure-UiEnvironment
|
|
||||||
|
|
||||||
Write-Host ''
|
|
||||||
Write-Host "正在启动 MarketGrid 工具箱"
|
|
||||||
Write-Host "入口地址:$EntryUrl"
|
|
||||||
Write-Host ''
|
|
||||||
|
|
||||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
||||||
$psi.FileName = $Python
|
|
||||||
$psi.Arguments = "-m streamlit run `"$PSScriptRoot\app.py`" --server.headless true --server.address $HostAddress --server.port $Port --browser.serverAddress $HostAddress --browser.gatherUsageStats false"
|
|
||||||
$psi.WorkingDirectory = $PSScriptRoot
|
|
||||||
$psi.UseShellExecute = $false
|
|
||||||
$ui = [System.Diagnostics.Process]::Start($psi)
|
|
||||||
try {
|
|
||||||
Wait-UiReady -Process $ui
|
|
||||||
Write-Host "已启动:$EntryUrl"
|
|
||||||
Start-Process $EntryUrl
|
|
||||||
$ui.WaitForExit()
|
|
||||||
exit $ui.ExitCode
|
|
||||||
} finally {
|
|
||||||
if (-not $ui.HasExited) {
|
|
||||||
Stop-Process -Id $ui.Id -Force -ErrorAction SilentlyContinue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
@echo off
|
|
||||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0start-web.ps1"
|
|
||||||
if errorlevel 1 pause
|
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
@echo off
|
@echo off
|
||||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0start-ui.ps1"
|
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0start.ps1"
|
||||||
if errorlevel 1 pause
|
if errorlevel 1 pause
|
||||||
@@ -7,7 +7,7 @@ $ApiPort = 8765
|
|||||||
$WebPort = 5173
|
$WebPort = 5173
|
||||||
$PageUrl = "http://${ApiHost}:${WebPort}"
|
$PageUrl = "http://${ApiHost}:${WebPort}"
|
||||||
$ApiUrl = "http://${ApiHost}:${ApiPort}"
|
$ApiUrl = "http://${ApiHost}:${ApiPort}"
|
||||||
$Python = Join-Path $PSScriptRoot '.venv-web\Scripts\python.exe'
|
$Python = Join-Path $PSScriptRoot '.venv\Scripts\python.exe'
|
||||||
$WebDir = Join-Path $PSScriptRoot 'web'
|
$WebDir = Join-Path $PSScriptRoot 'web'
|
||||||
|
|
||||||
function Test-Listening([int] $Port) {
|
function Test-Listening([int] $Port) {
|
||||||
@@ -84,23 +84,23 @@ function Start-Tool([string] $File, [string] $Arguments, [string] $Workdir) {
|
|||||||
function Ensure-WebEnvironment {
|
function Ensure-WebEnvironment {
|
||||||
if (Get-Command uv -ErrorAction SilentlyContinue) {
|
if (Get-Command uv -ErrorAction SilentlyContinue) {
|
||||||
if (-not (Test-Path -LiteralPath $Python)) {
|
if (-not (Test-Path -LiteralPath $Python)) {
|
||||||
uv venv .venv-web --python 3.13
|
uv venv .venv --python 3.13
|
||||||
if ($LASTEXITCODE -ne 0) { throw '创建 Python 环境失败。' }
|
if ($LASTEXITCODE -ne 0) { throw '创建 Python 环境失败。' }
|
||||||
}
|
}
|
||||||
uv pip install --python $Python -r requirements-web.txt
|
uv pip install --python $Python -r requirements.txt
|
||||||
if ($LASTEXITCODE -ne 0) { throw '安装 Python 依赖失败。' }
|
if ($LASTEXITCODE -ne 0) { throw '安装 Python 依赖失败。' }
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (-not (Test-Path -LiteralPath $Python)) {
|
if (-not (Test-Path -LiteralPath $Python)) {
|
||||||
python -m venv .venv-web
|
python -m venv .venv
|
||||||
if ($LASTEXITCODE -ne 0) { throw '创建 Python 环境失败。' }
|
if ($LASTEXITCODE -ne 0) { throw '创建 Python 环境失败。' }
|
||||||
}
|
}
|
||||||
& $Python -m pip install -r requirements-web.txt
|
& $Python -m pip install -r requirements.txt
|
||||||
if ($LASTEXITCODE -ne 0) { throw '安装 Python 依赖失败。' }
|
if ($LASTEXITCODE -ne 0) { throw '安装 Python 依赖失败。' }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not (Get-Command node -ErrorAction SilentlyContinue) -or -not (Get-Command npm.cmd -ErrorAction SilentlyContinue)) {
|
if (-not (Get-Command node -ErrorAction SilentlyContinue) -or -not (Get-Command npm.cmd -ErrorAction SilentlyContinue)) {
|
||||||
throw '未找到 Node.js 或 npm,无法启动 Vue 界面。请先安装 Node.js 后再运行 start-web。'
|
throw '未找到 Node.js 或 npm,无法启动界面。请先安装 Node.js 后再运行 start。'
|
||||||
}
|
}
|
||||||
|
|
||||||
Stop-ExistingWeb
|
Stop-ExistingWeb
|
||||||
@@ -117,7 +117,6 @@ Write-Host ''
|
|||||||
Write-Host '正在启动 MarketGrid Vue 工具箱'
|
Write-Host '正在启动 MarketGrid Vue 工具箱'
|
||||||
Write-Host "页面:$PageUrl"
|
Write-Host "页面:$PageUrl"
|
||||||
Write-Host "接口:$ApiUrl"
|
Write-Host "接口:$ApiUrl"
|
||||||
Write-Host 'Streamlit 工具箱仍使用 start-ui.cmd(http://127.0.0.1:8501)'
|
|
||||||
Write-Host '关闭本窗口会停止页面和接口。'
|
Write-Host '关闭本窗口会停止页面和接口。'
|
||||||
Write-Host ''
|
Write-Host ''
|
||||||
|
|
||||||
@@ -241,55 +241,5 @@ class TaskIntegrationTest(unittest.TestCase):
|
|||||||
self.assertTrue(any(l.findtext('layername') == '移动C端采样点比例_AOI' for l in xml.findall('projectlayers/maplayer')))
|
self.assertTrue(any(l.findtext('layername') == '移动C端采样点比例_AOI' for l in xml.findall('projectlayers/maplayer')))
|
||||||
|
|
||||||
|
|
||||||
class PageTest(unittest.TestCase):
|
|
||||||
def test_result_file_list_is_sorted(self):
|
|
||||||
with tempfile.TemporaryDirectory() as directory:
|
|
||||||
root = Path(directory)
|
|
||||||
(root / "b.zip").write_bytes(b"b")
|
|
||||||
(root / "a.csv").write_text("x\n", encoding="utf-8")
|
|
||||||
(root / ".hidden").write_text("x", encoding="utf-8")
|
|
||||||
from ui.results_page import _file_rows, _task_label
|
|
||||||
names = [path.name for path in _file_rows(root)]
|
|
||||||
self.assertEqual(names, ["a.csv", "b.zip"])
|
|
||||||
self.assertIn("市场网格出图", _task_label({
|
|
||||||
"id": "20260815-a0000001", "kind": "market", "status": "success"
|
|
||||||
}))
|
|
||||||
|
|
||||||
def test_global_css_survives_streamlit_sanitizer(self):
|
|
||||||
# st.html 经 DOMPurify 清洗,样式里出现 "<"(如内联 SVG)会让整段 <style> 被丢弃。
|
|
||||||
from ui.layout import COMPACT_CSS
|
|
||||||
self.assertNotIn("<", COMPACT_CSS)
|
|
||||||
self.assertIn('[data-testid="InputInstructions"]', COMPACT_CSS)
|
|
||||||
|
|
||||||
def test_uploaded_file_is_stored_once_with_exact_bytes(self):
|
|
||||||
from streamlit.testing.v1 import AppTest
|
|
||||||
from ui import inputs
|
|
||||||
content = b"id,longitude,latitude\n1,112,22\n"
|
|
||||||
uploaded = io.BytesIO(content)
|
|
||||||
uploaded.name, uploaded.size, uploaded.file_id = "坐标.csv", len(content), "test-upload"
|
|
||||||
with tempfile.TemporaryDirectory() as directory, patch.object(inputs, "ROOT", Path(directory)), \
|
|
||||||
patch("streamlit.file_uploader", return_value=uploaded):
|
|
||||||
at = AppTest.from_string(
|
|
||||||
"from ui.inputs import file_input\n"
|
|
||||||
"file_input('坐标', 'missing.csv', 'csv', 'test')"
|
|
||||||
).run()
|
|
||||||
at.radio[0].set_value("拖拽上传").run()
|
|
||||||
self.assertFalse(at.exception)
|
|
||||||
saved = list(Path(directory).rglob("坐标.csv"))
|
|
||||||
self.assertEqual(len(saved), 1)
|
|
||||||
self.assertEqual(saved[0].read_bytes(), content)
|
|
||||||
at.run()
|
|
||||||
self.assertEqual(len(list(Path(directory).rglob("坐标.csv"))), 1)
|
|
||||||
|
|
||||||
def test_home_and_each_functional_page_render(self):
|
|
||||||
from streamlit.testing.v1 import AppTest
|
|
||||||
at = AppTest.from_file(str(tasks.ROOT / "app.py")).run(timeout=30)
|
|
||||||
self.assertFalse(at.exception, at.exception)
|
|
||||||
for module in ("market_page", "building_page", "tasks_page", "results_page"):
|
|
||||||
with self.subTest(page=module):
|
|
||||||
at = AppTest.from_string(f"from ui.{module} import render\nrender()").run(timeout=30)
|
|
||||||
self.assertFalse(at.exception, at.exception)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
"""Streamlit 页面与交互组件。"""
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
import json
|
|
||||||
import streamlit as st
|
|
||||||
from toolbox.tasks import ROOT, start_task
|
|
||||||
from .inputs import file_input
|
|
||||||
from .task_panel import show_started, task_panel
|
|
||||||
|
|
||||||
# 上次填写的服务地址/登录信息保存在本地 output 目录(已被 .gitignore 忽略),下次自动读取。
|
|
||||||
CONNECTION_FILE = ROOT / "output" / "toolbox" / "nr_connection.json"
|
|
||||||
CONNECTION_KEYS = ("URL", "COOKIES", "REFERER")
|
|
||||||
|
|
||||||
|
|
||||||
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
|
|
||||||
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 connection_input(label, key, placeholder=None):
|
|
||||||
"""type=search 的输入框在框内右侧自带 ✕ 清除按钮(样式见 layout.py)。"""
|
|
||||||
return st.text_input(label, key=f"conn_{key}", placeholder=placeholder, type="search")
|
|
||||||
|
|
||||||
|
|
||||||
def render():
|
|
||||||
st.markdown("## 楼宇数据查询")
|
|
||||||
st.caption("按楼宇轮廓(WKT)查询:先计算落在轮廓内部的点,再按该点查询。")
|
|
||||||
source = file_input("楼宇轮廓清单", "source/NRBuildPolygon.csv", "csv", "building_csv")
|
|
||||||
if "conn_URL" not in st.session_state:
|
|
||||||
for key, value in load_connection().items():
|
|
||||||
st.session_state[f"conn_{key}"] = value
|
|
||||||
st.markdown("**连接信息**(默认显示脚本内配置或上次保存值;修改后保存到本地,下次自动读取)")
|
|
||||||
url = connection_input("服务地址", "URL", "https://...wfs?...ak=...&sig=...")
|
|
||||||
cookies = connection_input("登录信息(Cookies)", "COOKIES", "CASTGC=...")
|
|
||||||
referer = connection_input("来源页(可留空)", "REFERER", "可留空")
|
|
||||||
with st.form("building_run"):
|
|
||||||
c1, c2, c3 = st.columns(3)
|
|
||||||
start = c1.number_input("起始行", 1, value=1)
|
|
||||||
limit = c2.number_input("查询数量(0 表示全部)", 0, value=1000)
|
|
||||||
concurrency = c3.number_input("并发数", 1, 32, 8)
|
|
||||||
encoding = st.selectbox("文件编码(按内容自动识别,识别不出时按此项)", ["gbk", "utf-8-sig"])
|
|
||||||
with st.expander("高级参数"):
|
|
||||||
timeout = st.number_input("超时(秒)", 1, 300, 30)
|
|
||||||
retries = st.number_input("失败重试", 0, 10, 2)
|
|
||||||
interval = st.number_input("请求间隔(秒)", 0.0, 60.0, 0.2, 0.1)
|
|
||||||
submitted = st.form_submit_button("开始查询", type="primary")
|
|
||||||
if submitted:
|
|
||||||
try:
|
|
||||||
if not source:
|
|
||||||
raise ValueError("请先导入楼宇轮廓文件。")
|
|
||||||
url, cookies, referer = url.strip(), cookies.strip(), referer.strip()
|
|
||||||
override = bool(url or cookies)
|
|
||||||
if override and (not url.startswith(("http://", "https://")) or not cookies):
|
|
||||||
raise ValueError("服务地址和登录信息需同时填写,且地址以 http(s):// 开头。")
|
|
||||||
params = {"INPUT_CSV": source, "INPUT_ENCODING": encoding, "START_ROW": start,
|
|
||||||
"LIMIT": limit or None, "CONCURRENCY": concurrency, "TIMEOUT": timeout,
|
|
||||||
"MAX_RETRIES": retries, "REQUEST_INTERVAL": interval}
|
|
||||||
credentials = {"URL": url, "COOKIES": cookies, "REFERER": referer} if override else None
|
|
||||||
save_connection(credentials)
|
|
||||||
show_started(start_task("buildings", params, credentials))
|
|
||||||
except (OSError, ValueError, UnicodeError) as error:
|
|
||||||
st.error(str(error))
|
|
||||||
if st.session_state.get("last_task"):
|
|
||||||
task_panel(st.session_state["last_task"])
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
from pathlib import Path
|
|
||||||
import streamlit as st
|
|
||||||
from toolbox.tasks import ROOT, list_tasks, ACTIVE
|
|
||||||
from toolbox.validation import SOURCES
|
|
||||||
|
|
||||||
|
|
||||||
def _result_zip_count(tasks):
|
|
||||||
total = 0
|
|
||||||
for task in tasks:
|
|
||||||
directory = Path(task["output"])
|
|
||||||
if not directory.exists():
|
|
||||||
continue
|
|
||||||
total += sum(1 for path in directory.glob("*.zip") if path.is_file())
|
|
||||||
return total
|
|
||||||
|
|
||||||
|
|
||||||
def render():
|
|
||||||
st.markdown("## MarketGrid 工具箱")
|
|
||||||
tasks = list_tasks()
|
|
||||||
cols = st.columns(3)
|
|
||||||
cols[0].metric("正在运行", sum(t["status"] in ACTIVE for t in tasks))
|
|
||||||
cols[1].metric("任务记录", len(tasks))
|
|
||||||
cols[2].metric("成果包", _result_zip_count(tasks))
|
|
||||||
st.markdown("#### 选择工具")
|
|
||||||
left, right = st.columns(2)
|
|
||||||
with left, st.container(border=True):
|
|
||||||
st.markdown("##### 🗺️ 市场网格出图")
|
|
||||||
st.write("按市场生成信号图和成果包。")
|
|
||||||
st.page_link(st.session_state["pages"]["market"], label="开始出图", icon="➡️")
|
|
||||||
with right, st.container(border=True):
|
|
||||||
st.markdown("##### 🏢 楼宇数据查询")
|
|
||||||
st.write("按坐标批量查询楼宇信息。")
|
|
||||||
st.page_link(st.session_state["pages"]["buildings"], label="开始查询", icon="➡️")
|
|
||||||
st.markdown("#### 默认数据源")
|
|
||||||
st.dataframe([{"数据源": label, "状态": "已就绪" if (ROOT / file).is_file() else "缺失",
|
|
||||||
"文件": file, "大小 MB": round((ROOT / file).stat().st_size / 1024**2, 1) if (ROOT / file).is_file() else 0}
|
|
||||||
for label, file, _ in SOURCES.values()], hide_index=True, width="stretch")
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
"""按数据源独立选择本地文件或拖拽上传。"""
|
|
||||||
from pathlib import Path
|
|
||||||
import uuid
|
|
||||||
import streamlit as st
|
|
||||||
from toolbox.tasks import ROOT
|
|
||||||
|
|
||||||
|
|
||||||
def file_input(label, default, extension, key):
|
|
||||||
with st.container(border=True):
|
|
||||||
st.markdown(f"**{label}**")
|
|
||||||
mode = st.radio("导入方式", ["本地路径", "拖拽上传"], horizontal=True,
|
|
||||||
key=f"{key}_mode", label_visibility="collapsed")
|
|
||||||
if mode == "本地路径":
|
|
||||||
value = st.text_input("文件路径", str(ROOT / default), key=f"{key}_path")
|
|
||||||
value = value.strip().strip('"')
|
|
||||||
path = Path(value).expanduser()
|
|
||||||
if not path.is_absolute():
|
|
||||||
path = ROOT / path
|
|
||||||
else:
|
|
||||||
uploaded = st.file_uploader("拖拽文件到这里,或点击选择", type=[extension], key=f"{key}_upload")
|
|
||||||
if uploaded is None:
|
|
||||||
st.caption(f"请选择 .{extension} 文件")
|
|
||||||
return None
|
|
||||||
identity = (uploaded.file_id, uploaded.size)
|
|
||||||
cached = st.session_state.get(f"{key}_stored")
|
|
||||||
if cached and cached[0] == identity and Path(cached[1]).exists():
|
|
||||||
path = Path(cached[1])
|
|
||||||
else:
|
|
||||||
folder = ROOT / "output" / "toolbox" / "imports" / uuid.uuid4().hex
|
|
||||||
folder.mkdir(parents=True)
|
|
||||||
path = folder / Path(uploaded.name).name
|
|
||||||
uploaded.seek(0)
|
|
||||||
with path.open("wb") as target:
|
|
||||||
while chunk := uploaded.read(8 * 1024 * 1024):
|
|
||||||
target.write(chunk)
|
|
||||||
st.session_state[f"{key}_stored"] = (identity, str(path))
|
|
||||||
if path.is_file():
|
|
||||||
st.caption(f"已就绪 · {path.stat().st_size / 1024 / 1024:,.1f} MB")
|
|
||||||
else:
|
|
||||||
st.caption("文件不存在")
|
|
||||||
return str(path.resolve())
|
|
||||||
-141
@@ -1,141 +0,0 @@
|
|||||||
"""共享界面布局样式。"""
|
|
||||||
import streamlit as st
|
|
||||||
|
|
||||||
COMPACT_CSS = """
|
|
||||||
header[data-testid="stHeader"] {
|
|
||||||
background: transparent;
|
|
||||||
height: 2.25rem;
|
|
||||||
}
|
|
||||||
div[data-testid="stDecoration"] {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
.block-container {
|
|
||||||
padding-top: 0.85rem !important;
|
|
||||||
padding-bottom: 1rem !important;
|
|
||||||
padding-left: 1.75rem !important;
|
|
||||||
padding-right: 1.75rem !important;
|
|
||||||
max-width: 1200px;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 允许折叠按钮溢出到侧栏外侧 */
|
|
||||||
div[data-testid="stApp"],
|
|
||||||
div[data-testid="stAppViewContainer"],
|
|
||||||
section[data-testid="stSidebar"],
|
|
||||||
section[data-testid="stSidebar"] > div,
|
|
||||||
section[data-testid="stSidebar"] [data-testid="stSidebarContent"] {
|
|
||||||
overflow: visible !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
section[data-testid="stSidebar"] [data-testid="stSidebarUserContent"] {
|
|
||||||
padding-top: 0.45rem !important;
|
|
||||||
padding-bottom: 0.75rem !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 顶部 header 行高度清零,标题贴顶 */
|
|
||||||
section[data-testid="stSidebar"] [data-testid="stSidebarHeader"] {
|
|
||||||
height: 0 !important;
|
|
||||||
min-height: 0 !important;
|
|
||||||
margin: 0 !important;
|
|
||||||
padding: 0 !important;
|
|
||||||
border: 0 !important;
|
|
||||||
overflow: visible !important;
|
|
||||||
position: relative !important;
|
|
||||||
background: transparent !important;
|
|
||||||
}
|
|
||||||
section[data-testid="stSidebar"] [data-testid="stLogo"] {
|
|
||||||
display: none !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 折叠按钮固定显示在侧栏右缘外侧 */
|
|
||||||
section[data-testid="stSidebar"] [data-testid="stSidebarCollapseButton"],
|
|
||||||
section[data-testid="stSidebar"] [data-testid="stSidebarCollapseButton"] * {
|
|
||||||
visibility: visible !important;
|
|
||||||
opacity: 1 !important;
|
|
||||||
}
|
|
||||||
section[data-testid="stSidebar"] [data-testid="stSidebarCollapseButton"] {
|
|
||||||
position: absolute !important;
|
|
||||||
top: 0.45rem !important;
|
|
||||||
right: 0 !important;
|
|
||||||
transform: translateX(70%) !important;
|
|
||||||
z-index: 1000000 !important;
|
|
||||||
width: auto !important;
|
|
||||||
margin: 0 !important;
|
|
||||||
padding: 0 !important;
|
|
||||||
pointer-events: auto !important;
|
|
||||||
}
|
|
||||||
section[data-testid="stSidebar"] [data-testid="stSidebarCollapseButton"] button {
|
|
||||||
background: #FFFFFF !important;
|
|
||||||
border: 1px solid #D5DEE8 !important;
|
|
||||||
border-radius: 999px !important;
|
|
||||||
box-shadow: 0 1px 3px rgba(22, 48, 71, 0.14) !important;
|
|
||||||
width: 1.7rem !important;
|
|
||||||
height: 1.7rem !important;
|
|
||||||
min-height: 1.7rem !important;
|
|
||||||
padding: 0 !important;
|
|
||||||
}
|
|
||||||
section[data-testid="stSidebar"] [data-testid="stSidebarCollapseButton"] span {
|
|
||||||
font-size: 1.05rem !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 品牌与导航贴顶、间距收紧 */
|
|
||||||
section[data-testid="stSidebar"] [data-testid="stMarkdownContainer"] h1,
|
|
||||||
section[data-testid="stSidebar"] [data-testid="stMarkdownContainer"] h2,
|
|
||||||
section[data-testid="stSidebar"] [data-testid="stMarkdownContainer"] h3 {
|
|
||||||
margin: 0 0 0.15rem 0 !important;
|
|
||||||
padding: 0 !important;
|
|
||||||
line-height: 1.2 !important;
|
|
||||||
}
|
|
||||||
section[data-testid="stSidebar"] [data-testid="stCaptionContainer"] {
|
|
||||||
margin-top: 0 !important;
|
|
||||||
margin-bottom: 0.4rem !important;
|
|
||||||
}
|
|
||||||
section[data-testid="stSidebar"] a[data-testid="stPageLink-NavLink"] {
|
|
||||||
padding-top: 0.3rem !important;
|
|
||||||
padding-bottom: 0.3rem !important;
|
|
||||||
margin: 0.02rem 0 !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
div[data-testid="stVerticalBlock"] {
|
|
||||||
gap: 0.5rem !important;
|
|
||||||
}
|
|
||||||
div[data-testid="stHorizontalBlock"] {
|
|
||||||
gap: 0.7rem !important;
|
|
||||||
}
|
|
||||||
[data-testid="stMetric"] {
|
|
||||||
background: #EDF2F7;
|
|
||||||
border-radius: 0.55rem;
|
|
||||||
padding: 0.5rem 0.75rem;
|
|
||||||
}
|
|
||||||
[data-testid="stMetricValue"] {
|
|
||||||
font-size: 1.5rem !important;
|
|
||||||
}
|
|
||||||
h1 {
|
|
||||||
font-size: 1.6rem !important;
|
|
||||||
margin-bottom: 0.15rem !important;
|
|
||||||
}
|
|
||||||
h2, h3 {
|
|
||||||
margin-top: 0.3rem !important;
|
|
||||||
margin-bottom: 0.2rem !important;
|
|
||||||
}
|
|
||||||
hr {
|
|
||||||
margin: 0.35rem 0 !important;
|
|
||||||
}
|
|
||||||
/* 去掉输入框右下角 “Press Enter to submit form / apply” 提示 */
|
|
||||||
[data-testid="InputInstructions"] {
|
|
||||||
display: none !important;
|
|
||||||
}
|
|
||||||
/* type=search 输入框自带框内右侧 ✕ 清除按钮;隐藏左侧放大镜图标 */
|
|
||||||
[data-testid="stTextInputRootElement"]:has(input[type="search"]) [data-testid="stTextInputIcon"] {
|
|
||||||
display: none !important;
|
|
||||||
}
|
|
||||||
[data-testid="stTextInputRootElement"]:has(input[type="search"]) {
|
|
||||||
padding-left: 0 !important;
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
def apply_compact_layout():
|
|
||||||
# st.html 比 markdown 更稳定地注入样式,避免侧栏折叠按钮样式被忽略。
|
|
||||||
# 注意:内容经 DOMPurify 清洗,CSS 中不能出现 "<"(例如内联 SVG data URL),否则整段样式会被丢弃。
|
|
||||||
assert "<" not in COMPACT_CSS, "COMPACT_CSS 不能包含 '<'"
|
|
||||||
st.html(f"<style>{COMPACT_CSS}</style>")
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
"""完整市场出图流程页面。"""
|
|
||||||
import sqlite3
|
|
||||||
import zipfile
|
|
||||||
import streamlit as st
|
|
||||||
from pathlib import Path
|
|
||||||
from toolbox.tasks import start_task
|
|
||||||
from toolbox.validation import SOURCES, market_options
|
|
||||||
from marketgrid.nrdata import build_gpkg
|
|
||||||
from .inputs import file_input
|
|
||||||
from .task_panel import show_started, task_panel
|
|
||||||
|
|
||||||
|
|
||||||
def render():
|
|
||||||
st.markdown("## 市场网格出图")
|
|
||||||
st.markdown("#### 1 · 导入数据")
|
|
||||||
params = {}
|
|
||||||
columns = st.columns(2)
|
|
||||||
for index, (key, (label, default, extension)) in enumerate(SOURCES.items()):
|
|
||||||
with columns[index % 2]:
|
|
||||||
params[key] = file_input(label, default, extension, key)
|
|
||||||
with columns[len(SOURCES) % 2]:
|
|
||||||
params["NR_BUILDINGS_DATA_CSV"] = file_input(
|
|
||||||
"楼宇查询结果",
|
|
||||||
"source/NRBuildingsData.csv",
|
|
||||||
"csv",
|
|
||||||
"nr_buildings_csv",
|
|
||||||
)
|
|
||||||
options = []
|
|
||||||
if params["MARKET_GPKG"]:
|
|
||||||
try:
|
|
||||||
options = market_options(params["MARKET_GPKG"])
|
|
||||||
except (OSError, sqlite3.Error, ValueError) as error:
|
|
||||||
st.warning(f"市场边界不可用:{error}")
|
|
||||||
st.markdown("#### 2 · 选择市场与参数")
|
|
||||||
# 勾选交互放在 form 外;用复选框列表代替 multiselect,避免下拉被页面样式挡住。
|
|
||||||
all_markets = st.checkbox("处理全部市场", value=True, disabled=not options, key="market_all")
|
|
||||||
chosen = []
|
|
||||||
if options and not all_markets:
|
|
||||||
st.caption("指定市场")
|
|
||||||
with st.container(height=280, border=True):
|
|
||||||
for fid, name in options:
|
|
||||||
if st.checkbox(f"{fid} · {name}", key=f"market_pick_{fid}"):
|
|
||||||
chosen.append(fid)
|
|
||||||
elif options:
|
|
||||||
st.caption(f"将处理全部 {len(options)} 个市场")
|
|
||||||
else:
|
|
||||||
st.caption("请先导入可用的市场边界。")
|
|
||||||
|
|
||||||
with st.form("market_run"):
|
|
||||||
c1, c2, c3 = st.columns(3)
|
|
||||||
params["MAX_WORKERS"] = c1.number_input("并行进程数", 1, 16, 4)
|
|
||||||
params["SCALE"] = c2.number_input("分辨率倍数", 0.1, 20.0, 5.0, 0.5)
|
|
||||||
params["SUMMARY_OUTPUT_ENABLED"] = c3.checkbox("生成全量汇总包", value=True)
|
|
||||||
with st.expander("更多参数"):
|
|
||||||
params["MAX_RASTER_PIXELS"] = int(st.number_input("单市场像元上限(百万)", 1, 100, 25) * 1_000_000)
|
|
||||||
params["SUMMARY_MAX_RASTER_PIXELS"] = int(st.number_input("汇总像元上限(百万)", 1, 200, 100) * 1_000_000)
|
|
||||||
params["CLIP_MODE"] = st.selectbox(
|
|
||||||
"网格纳入方式",
|
|
||||||
["intersects", "center"],
|
|
||||||
format_func=lambda v: {"intersects": "与市场相交", "center": "中心点在市场内"}[v],
|
|
||||||
)
|
|
||||||
params["PROJECT_EXTENT_PADDING_RATIO"] = st.number_input("地图留白比例", 0.0, 1.0, 0.05, 0.01)
|
|
||||||
submitted = st.form_submit_button("开始生成", type="primary", disabled=not options)
|
|
||||||
if submitted:
|
|
||||||
params["SELECTED_MARKET_IDS"] = [fid for fid, _ in options] if all_markets else chosen
|
|
||||||
try:
|
|
||||||
data_csv = Path(params["NR_BUILDINGS_DATA_CSV"] or "")
|
|
||||||
polygon_csv = Path("source/NRBuildPolygon.csv")
|
|
||||||
data_gpkg = Path("source/NRBuildingsData.gpkg")
|
|
||||||
if not data_csv.is_file() or not polygon_csv.is_file():
|
|
||||||
raise ValueError("缺少 source/NRBuildingsData.csv 或 source/NRBuildPolygon.csv。")
|
|
||||||
if not data_gpkg.exists() or data_gpkg.stat().st_mtime < max(data_csv.stat().st_mtime, polygon_csv.stat().st_mtime):
|
|
||||||
st.info("正在整理楼宇结果并生成边界图层,请稍候……")
|
|
||||||
build_gpkg(data_csv, polygon_csv, data_gpkg)
|
|
||||||
params["NR_BUILDINGS_DATA_GPKG"] = str(data_gpkg)
|
|
||||||
# 这是页面导入控件的临时参数,不属于后台 pipeline 配置,不能传入任务进程。
|
|
||||||
params.pop("NR_BUILDINGS_DATA_CSV", None)
|
|
||||||
if any(value is None for key, value in params.items() if key in SOURCES):
|
|
||||||
raise ValueError("请完成所需数据的导入。")
|
|
||||||
show_started(start_task("market", params))
|
|
||||||
except (OSError, sqlite3.Error, ValueError, zipfile.BadZipFile) as error:
|
|
||||||
st.error(str(error))
|
|
||||||
if st.session_state.get("last_task"):
|
|
||||||
task_panel(st.session_state["last_task"])
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
import os
|
|
||||||
from pathlib import Path
|
|
||||||
import streamlit as st
|
|
||||||
from toolbox.tasks import KINDS, LABELS, list_tasks
|
|
||||||
|
|
||||||
MAX_INLINE_DOWNLOAD = 128 * 1024**2
|
|
||||||
LIST_HEIGHT = 420
|
|
||||||
|
|
||||||
|
|
||||||
def _file_rows(directory):
|
|
||||||
if not directory.exists():
|
|
||||||
return []
|
|
||||||
return sorted(
|
|
||||||
(path for path in directory.iterdir() if path.is_file() and not path.name.startswith(".")),
|
|
||||||
key=lambda path: path.name.lower(),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _task_label(task):
|
|
||||||
return f"{task['id']} · {KINDS.get(task['kind'], task['kind'])} · {LABELS.get(task['status'], task['status'])}"
|
|
||||||
|
|
||||||
|
|
||||||
def render():
|
|
||||||
st.markdown("## 成果浏览")
|
|
||||||
tasks = list_tasks()
|
|
||||||
if not tasks:
|
|
||||||
st.info("暂无成果。完成出图或查询后会显示在这里。")
|
|
||||||
return
|
|
||||||
|
|
||||||
labels = {_task_label(task): Path(task["output"]) for task in tasks}
|
|
||||||
selected = st.selectbox("成果清单", list(labels))
|
|
||||||
directory = labels[selected]
|
|
||||||
cols = st.columns([4, 1])
|
|
||||||
cols[0].caption(str(directory))
|
|
||||||
if os.name == "nt" and cols[1].button("打开目录", use_container_width=True):
|
|
||||||
os.startfile(directory)
|
|
||||||
|
|
||||||
files = _file_rows(directory)
|
|
||||||
if not files:
|
|
||||||
st.info("该任务暂无文件。")
|
|
||||||
return
|
|
||||||
|
|
||||||
download_key = f"pending_download::{selected}"
|
|
||||||
pending_name = st.session_state.get(download_key)
|
|
||||||
|
|
||||||
st.markdown("#### 文件列表")
|
|
||||||
with st.container(height=LIST_HEIGHT, border=True):
|
|
||||||
for path in files:
|
|
||||||
row = st.columns([6, 2, 2])
|
|
||||||
row[0].markdown(f"`{path.name}`")
|
|
||||||
row[1].write(f"{path.stat().st_size / 1024**2:,.2f} MB")
|
|
||||||
if row[2].button("下载", key=f"pick_{selected}_{path.name}", use_container_width=True):
|
|
||||||
st.session_state[download_key] = path.name
|
|
||||||
pending_name = path.name
|
|
||||||
|
|
||||||
if pending_name:
|
|
||||||
target = directory / pending_name
|
|
||||||
if not target.is_file():
|
|
||||||
st.session_state.pop(download_key, None)
|
|
||||||
st.warning("文件已不存在,请重新选择。")
|
|
||||||
return
|
|
||||||
size = target.stat().st_size
|
|
||||||
st.markdown(f"已选择:**{pending_name}**({size / 1024**2:,.2f} MB)")
|
|
||||||
if size <= MAX_INLINE_DOWNLOAD:
|
|
||||||
st.download_button(
|
|
||||||
"保存到本地",
|
|
||||||
data=target.read_bytes(),
|
|
||||||
file_name=target.name,
|
|
||||||
mime="application/octet-stream",
|
|
||||||
key=f"save_{selected}_{pending_name}",
|
|
||||||
type="primary",
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
st.info("文件较大,请点击上方“打开目录”后直接复制。")
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
from datetime import datetime
|
|
||||||
import streamlit as st
|
|
||||||
from toolbox.tasks import ACTIVE, KINDS, LABELS, delete_task, list_tasks, stop_task, tail_log
|
|
||||||
|
|
||||||
|
|
||||||
def _delete_controls(task):
|
|
||||||
"""两步确认删除;状态存 session_state,fragment 定时刷新时不会丢失。"""
|
|
||||||
confirm_key = f"confirm_delete_{task['id']}"
|
|
||||||
if st.session_state.get(confirm_key):
|
|
||||||
st.warning("将删除该任务记录及其成果目录,不可恢复。")
|
|
||||||
c1, c2 = st.columns(2)
|
|
||||||
if c1.button("确认删除", key=f"delete_yes_{task['id']}", type="primary", use_container_width=True):
|
|
||||||
st.session_state.pop(confirm_key, None)
|
|
||||||
try:
|
|
||||||
delete_task(task["id"])
|
|
||||||
except (OSError, ValueError) as error:
|
|
||||||
st.session_state["task_delete_error"] = str(error)
|
|
||||||
st.rerun()
|
|
||||||
if c2.button("取消", key=f"delete_no_{task['id']}", use_container_width=True):
|
|
||||||
st.session_state.pop(confirm_key, None)
|
|
||||||
st.rerun(scope="fragment")
|
|
||||||
elif st.button("删除任务", key=f"delete_{task['id']}"):
|
|
||||||
st.session_state[confirm_key] = True
|
|
||||||
st.rerun(scope="fragment")
|
|
||||||
|
|
||||||
|
|
||||||
@st.fragment(run_every="2s")
|
|
||||||
def task_panel(task_id=None, recent=False):
|
|
||||||
if error := st.session_state.pop("task_delete_error", None):
|
|
||||||
st.error(f"删除失败:{error}")
|
|
||||||
tasks = list_tasks()
|
|
||||||
if task_id:
|
|
||||||
tasks = [task for task in tasks if task["id"] == task_id]
|
|
||||||
elif recent:
|
|
||||||
tasks = tasks[:1]
|
|
||||||
if not tasks:
|
|
||||||
st.info("暂无任务。")
|
|
||||||
return
|
|
||||||
for task in tasks:
|
|
||||||
with st.container(border=True):
|
|
||||||
st.markdown(f"**{KINDS[task['kind']]} · {LABELS[task['status']]}**")
|
|
||||||
st.caption(f"{task['id']} · {datetime.fromtimestamp(task['created']):%Y-%m-%d %H:%M:%S}")
|
|
||||||
st.write(task["message"])
|
|
||||||
if task.get("total"):
|
|
||||||
ratio = min(task.get("done", 0) / task["total"], 1.0)
|
|
||||||
st.progress(ratio, text=f"{task.get('done', 0)} / {task['total']}")
|
|
||||||
elif task.get("done"):
|
|
||||||
st.write(f"已处理 {task['done']} 条")
|
|
||||||
if task.get("counts"):
|
|
||||||
st.write(task["counts"])
|
|
||||||
if task["status"] in ACTIVE:
|
|
||||||
if task["stop_requested"]:
|
|
||||||
st.info("正在停止,请稍候。")
|
|
||||||
elif st.button("停止任务", key=f"stop_{task['id']}"):
|
|
||||||
stop_task(task["id"])
|
|
||||||
st.rerun(scope="fragment")
|
|
||||||
st.caption(f"成果目录:{task['output']}")
|
|
||||||
with st.expander("运行日志", expanded=bool(task_id)):
|
|
||||||
st.code(tail_log(task["directory"]), language="text")
|
|
||||||
if task["status"] not in ACTIVE:
|
|
||||||
_delete_controls(task)
|
|
||||||
|
|
||||||
|
|
||||||
def show_started(task_id):
|
|
||||||
st.session_state["last_task"] = task_id
|
|
||||||
st.success("任务已启动,可在任务中心查看进度。")
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
import streamlit as st
|
|
||||||
from toolbox.tasks import ACTIVE, clear_tasks, list_tasks
|
|
||||||
from .task_panel import task_panel
|
|
||||||
|
|
||||||
|
|
||||||
def render():
|
|
||||||
finished = [task for task in list_tasks() if task["status"] not in ACTIVE]
|
|
||||||
confirming = st.session_state.get("confirm_clear_tasks", False)
|
|
||||||
left, right = st.columns([5, 2])
|
|
||||||
left.markdown("## 任务中心")
|
|
||||||
if right.button("清空全部任务", disabled=not finished or confirming, use_container_width=True):
|
|
||||||
st.session_state["confirm_clear_tasks"] = True
|
|
||||||
st.rerun()
|
|
||||||
if confirming:
|
|
||||||
st.warning(f"将删除 {len(finished)} 个已结束任务的记录和成果目录,不可恢复;运行中的任务不会删除。")
|
|
||||||
c1, c2, _ = st.columns([1, 1, 4])
|
|
||||||
if c1.button("确认清空", type="primary", use_container_width=True):
|
|
||||||
st.session_state.pop("confirm_clear_tasks", None)
|
|
||||||
try:
|
|
||||||
st.session_state["clear_tasks_result"] = clear_tasks()
|
|
||||||
except OSError as error:
|
|
||||||
st.session_state["task_delete_error"] = str(error)
|
|
||||||
st.rerun()
|
|
||||||
if c2.button("取消", use_container_width=True):
|
|
||||||
st.session_state.pop("confirm_clear_tasks", None)
|
|
||||||
st.rerun()
|
|
||||||
if result := st.session_state.pop("clear_tasks_result", None):
|
|
||||||
deleted, skipped = result
|
|
||||||
message = f"已删除 {deleted} 个任务。"
|
|
||||||
if skipped:
|
|
||||||
message += f" {skipped} 个运行中的任务已跳过。"
|
|
||||||
st.success(message)
|
|
||||||
task_panel()
|
|
||||||
+1
-1
@@ -19,7 +19,7 @@ export async function request(path, options = {}) {
|
|||||||
try {
|
try {
|
||||||
response = await fetch(path, { ...options, headers })
|
response = await fetch(path, { ...options, headers })
|
||||||
} catch {
|
} catch {
|
||||||
throw new ApiError('无法连接接口。请确认已运行 start-web。')
|
throw new ApiError('无法连接接口。请确认已运行 start。')
|
||||||
}
|
}
|
||||||
const text = await response.text()
|
const text = await response.text()
|
||||||
let data = null
|
let data = null
|
||||||
|
|||||||
Reference in New Issue
Block a user