94 lines
4.9 KiB
Python
94 lines
4.9 KiB
Python
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sqlite3
|
|
import zipfile
|
|
|
|
import pydeck as pdk
|
|
import streamlit as st
|
|
from toolbox import artifacts
|
|
from toolbox.tasks import ROOT, KINDS, LABELS, list_tasks
|
|
|
|
|
|
def preview(path):
|
|
suffix = path.suffix.lower()
|
|
if suffix == ".csv":
|
|
encoding = st.selectbox("预览编码", ["utf-8-sig", "gb18030"], key="preview_encoding")
|
|
rows, truncated = artifacts.csv_preview(path, encoding)
|
|
st.dataframe(rows, width="stretch", hide_index=True)
|
|
st.caption("仅显示前 500 行。" if truncated else f"共 {len(rows)} 行。")
|
|
elif suffix == ".json":
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
if isinstance(data, dict) and data.get("market_timings"):
|
|
st.subheader("市场处理耗时(秒)")
|
|
st.bar_chart([{"市场": item["market_code"], "耗时秒": item["elapsed_seconds"]}
|
|
for item in data["market_timings"]], x="市场", y="耗时秒")
|
|
st.json(data, expanded=False)
|
|
elif suffix == ".qgz":
|
|
st.dataframe(artifacts.qgis_layers(path), hide_index=True, width="stretch")
|
|
elif suffix in {".tif", ".tiff"}:
|
|
image, metadata = artifacts.raster_preview(path)
|
|
st.image(image, caption="按比例降采样预览;完整地理信息保留在原始 TIFF 中。")
|
|
st.json(metadata, expanded=False)
|
|
elif suffix == ".gpkg":
|
|
rows, features, metadata = artifacts.gpkg_preview(path)
|
|
st.write(metadata)
|
|
st.dataframe(rows, hide_index=True, width="stretch")
|
|
if features and metadata["坐标系"] in {4326, 100000}:
|
|
import shapely
|
|
geometry = shapely.from_geojson(json.dumps({"type": "FeatureCollection", "features": features}))
|
|
minx, miny, maxx, maxy = geometry.bounds
|
|
st.pydeck_chart(pdk.Deck(
|
|
map_style=None,
|
|
initial_view_state=pdk.ViewState(longitude=(minx+maxx)/2, latitude=(miny+maxy)/2, zoom=10),
|
|
layers=[pdk.Layer("GeoJsonLayer", {"type": "FeatureCollection", "features": features},
|
|
get_fill_color=[13, 130, 122, 60], get_line_color=[13, 130, 122, 255],
|
|
line_width_min_pixels=1, pickable=True)],
|
|
tooltip={"text": "{名称}"},
|
|
))
|
|
st.caption("离线几何预览,仅显示上述抽样要素;可拖动和缩放。完整地图请打开成果中的 QGIS 工程。")
|
|
else:
|
|
st.info("此文件可下载或在本地打开。")
|
|
|
|
|
|
def render():
|
|
st.markdown("## 成果浏览")
|
|
st.write("查看既有成果或新任务结果,预览数据表、空间图层、QGIS 图层配置和专题栅格。")
|
|
tasks = list_tasks()
|
|
roots = {"现有正式成果": ROOT / "output"}
|
|
roots.update({f"{t['id']} · {KINDS[t['kind']]} · {LABELS[t['status']]}": Path(t["output"]) for t in tasks})
|
|
selected = st.selectbox("成果来源", list(roots))
|
|
directory = roots[selected]
|
|
st.caption(str(directory))
|
|
if os.name == "nt" and st.button("在资源管理器中打开目录"):
|
|
os.startfile(directory)
|
|
files = sorted(p for p in directory.iterdir() if p.is_file() and not p.name.startswith(".")) if directory.exists() else []
|
|
if not files:
|
|
st.info("该任务尚未生成文件,稍后可刷新页面。")
|
|
return
|
|
st.dataframe([{"文件": p.name, "大小 MB": round(p.stat().st_size/1024**2, 2)} for p in files],
|
|
hide_index=True, width="stretch")
|
|
name = st.selectbox("选择文件", [p.name for p in files])
|
|
path = directory / name
|
|
# 下载按需加载,避免首次进入页面把所有大 ZIP 都读进内存。
|
|
if path.stat().st_size <= 128 * 1024**2:
|
|
if st.checkbox("准备下载所选文件", key=f"download_{path}"):
|
|
with path.open("rb") as source:
|
|
st.download_button("下载文件", source, file_name=path.name)
|
|
else:
|
|
st.caption("文件大于 128 MB,请使用上方本地目录直接复制,避免浏览器占用大量内存。")
|
|
try:
|
|
if path.suffix.lower() == ".zip":
|
|
with zipfile.ZipFile(path) as archive:
|
|
entries = [info for info in archive.infolist() if not info.is_dir()]
|
|
st.dataframe([{"成员": e.filename, "原始大小 MB": round(e.file_size/1024**2, 2)} for e in entries],
|
|
hide_index=True, width="stretch")
|
|
member = st.selectbox("包内文件", [e.filename for e in entries])
|
|
if st.checkbox("加载包内预览", key=f"preview_{path}_{member}"):
|
|
with st.spinner("读取成果预览……"), artifacts.zip_member(path, member) as target:
|
|
preview(target)
|
|
elif st.checkbox("加载文件预览", key=f"preview_{path}"):
|
|
preview(path)
|
|
except (OSError, ValueError, sqlite3.Error, zipfile.BadZipFile, KeyError) as error:
|
|
st.error(f"无法预览此文件:{error}")
|