"""按数据源独立选择本地文件或拖拽上传。""" 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())