67 lines
2.9 KiB
Python
67 lines
2.9 KiB
Python
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("任务已启动,可在任务中心查看进度。")
|