Files
MarketGrid/ui/results_page.py
T

75 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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("文件较大,请点击上方“打开目录”后直接复制。")