feat: 对话区域文件上传(粘贴/拖拽) + XLSX支持 + 会话切换无限循环修复
- 对话区域: st.file_uploader + 全局 paste/drop 事件监听 + sessionStorage 桥接 - 文件预览芯片: 上传后显示在对话区域,可逐文件移除 - OCR 双层解析全面接入: file_parser(文字) + ocr_extractor(字段提取) - XLSX 解析: openpyxl 逐工作表/逐行读取 - 修复: create_session 强制写入 agent_state.session_id - 修复: load_session_node 不再从磁盘覆盖 session_id - 修复: 切换会话 _last_switched_to 哨兵防止无限 rerun Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -21,6 +21,7 @@ import time
|
||||
from pathlib import Path
|
||||
|
||||
import streamlit as st
|
||||
import streamlit.components.v1 as components
|
||||
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
@@ -117,6 +118,10 @@ if "graph" not in st.session_state:
|
||||
st.session_state.graph = build_graph()
|
||||
if "pending_action" not in st.session_state:
|
||||
st.session_state.pending_action = None
|
||||
if "chat_attached_files" not in st.session_state:
|
||||
st.session_state.chat_attached_files = [] # [{name, text, type, path}]
|
||||
if "_paste_processed_ts" not in st.session_state:
|
||||
st.session_state._paste_processed_ts = 0
|
||||
|
||||
if "agent_state" not in st.session_state:
|
||||
if url_session_id:
|
||||
@@ -402,16 +407,21 @@ with st.sidebar:
|
||||
|
||||
if selected and session_options.get(selected) != current_session_id:
|
||||
new_sid = session_options[selected]
|
||||
data = load_session(new_sid)
|
||||
if data and data.get("agent_state"):
|
||||
_app_log.info(
|
||||
"切换会话",
|
||||
extra={"from_session": current_session_id, "to_session": new_sid},
|
||||
)
|
||||
data["agent_state"]["session_id"] = new_sid
|
||||
st.session_state.agent_state = data["agent_state"]
|
||||
st.session_state.messages = []
|
||||
st.rerun()
|
||||
if st.session_state.get("_last_switched_to") == new_sid:
|
||||
# 防止同一会话重复切换导致的无限 rerun 循环
|
||||
st.session_state._last_switched_to = ""
|
||||
else:
|
||||
data = load_session(new_sid)
|
||||
if data and data.get("agent_state"):
|
||||
_app_log.info(
|
||||
"切换会话",
|
||||
extra={"from_session": current_session_id, "to_session": new_sid},
|
||||
)
|
||||
data["agent_state"]["session_id"] = new_sid
|
||||
st.session_state.agent_state = data["agent_state"]
|
||||
st.session_state.messages = []
|
||||
st.session_state._last_switched_to = new_sid
|
||||
st.rerun()
|
||||
|
||||
col1, col2 = st.columns(2)
|
||||
with col1:
|
||||
@@ -481,7 +491,7 @@ with st.sidebar:
|
||||
|
||||
uploaded = st.file_uploader(
|
||||
"选择文件",
|
||||
type=["png", "jpg", "jpeg", "bmp", "webp", "pdf", "docx", "txt", "csv", "json", "xml"],
|
||||
type=["png", "jpg", "jpeg", "bmp", "webp", "pdf", "docx", "xlsx", "txt", "csv", "json", "xml"],
|
||||
accept_multiple_files=True,
|
||||
key="file_uploader",
|
||||
label_visibility="collapsed",
|
||||
@@ -614,6 +624,95 @@ with st.sidebar:
|
||||
key=f"dl_v{i}",
|
||||
)
|
||||
|
||||
# ---- 文件粘贴/拖拽全局处理器 ----
|
||||
st.html("""
|
||||
<script>
|
||||
(function() {
|
||||
if (window.__jrxml_drop_paste) return;
|
||||
window.__jrxml_drop_paste = true;
|
||||
var MAX_SIZE = 20 * 1024 * 1024;
|
||||
function handleFiles(files) {
|
||||
var fd = []; var n = 0; var total = Math.min(files.length, 10);
|
||||
for (var i = 0; i < total; i++) {
|
||||
var f = files[i];
|
||||
if (f.size > MAX_SIZE) { n++; continue; }
|
||||
var reader = new FileReader();
|
||||
reader.onload = (function(file) {
|
||||
return function(e) {
|
||||
fd.push({name: file.name, size: file.size, data: e.target.result});
|
||||
n++;
|
||||
if (n === total && fd.length) {
|
||||
sessionStorage.setItem('_jrxml_paste', JSON.stringify({ts: Date.now(), files: fd}));
|
||||
}
|
||||
};
|
||||
})(f);
|
||||
reader.readAsDataURL(f);
|
||||
}
|
||||
}
|
||||
document.addEventListener('paste', function(e) {
|
||||
var fs = e.clipboardData && e.clipboardData.files;
|
||||
if (fs && fs.length) { e.preventDefault(); handleFiles(fs); }
|
||||
});
|
||||
document.addEventListener('dragover', function(e) {
|
||||
e.preventDefault(); e.dataTransfer.dropEffect = 'copy';
|
||||
});
|
||||
document.addEventListener('drop', function(e) {
|
||||
var fs = e.dataTransfer && e.dataTransfer.files;
|
||||
if (fs && fs.length) { e.preventDefault(); handleFiles(fs); }
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
""")
|
||||
|
||||
# ---- 粘贴桥接组件 ----
|
||||
paste_data = components.html("""
|
||||
<script>
|
||||
(function poll() {
|
||||
var raw = sessionStorage.getItem('_jrxml_paste');
|
||||
if (raw) {
|
||||
try { sessionStorage.removeItem('_jrxml_paste'); Streamlit.setComponentValue(JSON.parse(raw)); return; }
|
||||
catch(e) {}
|
||||
}
|
||||
setTimeout(poll, 800);
|
||||
})();
|
||||
</script>
|
||||
""", height=0, default=0)
|
||||
|
||||
if paste_data and paste_data != 0:
|
||||
pts = paste_data.get("ts", 0)
|
||||
if pts > st.session_state._paste_processed_ts:
|
||||
st.session_state._paste_processed_ts = pts
|
||||
import base64, tempfile
|
||||
from backend.file_parser import parse_file
|
||||
from backend.layout_analyzer import analyze_layout
|
||||
for fi in paste_data.get("files", []):
|
||||
if not any(f["name"] == fi["name"] for f in st.session_state.chat_attached_files):
|
||||
header, b64 = fi["data"].split(",", 1)
|
||||
raw = base64.b64decode(b64)
|
||||
suffix = Path(fi["name"]).suffix.lower()
|
||||
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
|
||||
tmp.write(raw)
|
||||
tmp_path = tmp.name
|
||||
result = parse_file(tmp_path, suffix)
|
||||
text = result["text"]
|
||||
file_type = result["file_type"]
|
||||
img_suffixes = (".png", ".jpg", ".jpeg", ".bmp", ".webp")
|
||||
if suffix in img_suffixes and result.get("method") not in ("metadata_only", None):
|
||||
try:
|
||||
layout = analyze_layout(tmp_path)
|
||||
tt = layout.get("template_type", "unknown")
|
||||
if tt == "full_a4":
|
||||
text = layout["description"]
|
||||
file_type = "a4_template"
|
||||
elif tt == "partial_rows":
|
||||
file_type = "a4_partial"
|
||||
except Exception:
|
||||
pass
|
||||
st.session_state.chat_attached_files.append({
|
||||
"name": fi["name"], "text": text, "type": file_type, "path": tmp_path
|
||||
})
|
||||
st.rerun()
|
||||
|
||||
# ---- 标题 ----
|
||||
st.title("📝 JRXML 报表生成器")
|
||||
st.caption("用自然语言描述您的报表需求,我将逐步生成可用的 JRXML 模板。")
|
||||
@@ -633,29 +732,122 @@ for msg in st.session_state.messages:
|
||||
else:
|
||||
st.markdown(msg["content"])
|
||||
|
||||
# ---- 已附加文件预览 ----
|
||||
if st.session_state.chat_attached_files:
|
||||
n_files = len(st.session_state.chat_attached_files)
|
||||
chip_cols = st.columns(min(n_files, 4))
|
||||
files_to_remove = []
|
||||
for i, f in enumerate(st.session_state.chat_attached_files):
|
||||
with chip_cols[i % len(chip_cols)]:
|
||||
c1, c2 = st.columns([5, 1])
|
||||
with c1:
|
||||
name = f["name"]
|
||||
short_name = name[:16] + ("…" if len(name) > 16 else "")
|
||||
emoji_map = {"a4_template": "📷", "image": "🖼", "pdf": "📄", "docx": "📝", "xlsx": "📊"}
|
||||
emoji = emoji_map.get(f["type"], "📎")
|
||||
st.caption(f"{emoji} {short_name}")
|
||||
with c2:
|
||||
if st.button("✕", key=f"rm_chip_{i}"):
|
||||
files_to_remove.append(i)
|
||||
if files_to_remove:
|
||||
for i in sorted(files_to_remove, reverse=True):
|
||||
try:
|
||||
Path(st.session_state.chat_attached_files[i]["path"]).unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
st.session_state.chat_attached_files.pop(i)
|
||||
st.rerun()
|
||||
|
||||
# ---- 对话区域文件上传 ----
|
||||
col_fu, col_hint = st.columns([5, 1])
|
||||
with col_fu:
|
||||
chat_uploads = st.file_uploader(
|
||||
"附加文件",
|
||||
type=["png", "jpg", "jpeg", "bmp", "webp", "pdf", "docx", "xlsx", "txt", "csv", "json", "xml"],
|
||||
accept_multiple_files=True,
|
||||
key="chat_file_uploader",
|
||||
label_visibility="visible",
|
||||
)
|
||||
with col_hint:
|
||||
st.caption("Ctrl+V 粘贴\n或拖拽到页面")
|
||||
|
||||
if chat_uploads:
|
||||
newly_added = False
|
||||
import tempfile
|
||||
from backend.file_parser import parse_file
|
||||
from backend.layout_analyzer import analyze_layout
|
||||
for uf in chat_uploads:
|
||||
if not any(f["name"] == uf.name for f in st.session_state.chat_attached_files):
|
||||
suffix = Path(uf.name).suffix.lower()
|
||||
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
|
||||
tmp.write(uf.getvalue())
|
||||
tmp_path = tmp.name
|
||||
result = parse_file(tmp_path, suffix)
|
||||
text = result["text"]
|
||||
file_type = result["file_type"]
|
||||
img_suffixes = (".png", ".jpg", ".jpeg", ".bmp", ".webp")
|
||||
if suffix in img_suffixes and result.get("method") not in ("metadata_only", None):
|
||||
try:
|
||||
layout = analyze_layout(tmp_path)
|
||||
tt = layout.get("template_type", "unknown")
|
||||
if tt == "full_a4":
|
||||
text = layout["description"]
|
||||
file_type = "a4_template"
|
||||
elif tt == "partial_rows":
|
||||
file_type = "a4_partial"
|
||||
except Exception:
|
||||
pass
|
||||
st.session_state.chat_attached_files.append({
|
||||
"name": uf.name, "text": text, "type": file_type, "path": tmp_path
|
||||
})
|
||||
newly_added = True
|
||||
if newly_added:
|
||||
st.session_state.chat_file_uploader = []
|
||||
st.rerun()
|
||||
|
||||
# ---- 聊天输入 ----
|
||||
if prompt := st.chat_input("描述您的报表需求..."):
|
||||
# 拼接上传文件的文本
|
||||
uploaded_texts = []
|
||||
uploaded_files_info = []
|
||||
# 拼接对话区域附加文件的文本
|
||||
file_texts = []
|
||||
attached_info = []
|
||||
for f in st.session_state.chat_attached_files:
|
||||
file_texts.append(f"[附加文件: {f['name']} ({f['type']})]\n{f['text']}")
|
||||
attached_info.append({"name": f["name"], "type": f["type"], "length": len(f["text"])})
|
||||
|
||||
# 同时拼接侧边栏上传的文件(向后兼容)
|
||||
if st.session_state.get("uploaded_files"):
|
||||
for f in st.session_state.uploaded_files:
|
||||
uploaded_texts.append(f"[上传文件: {f['name']}]\n{f['text']}")
|
||||
uploaded_files_info.append({"name": f["name"], "type": f["type"], "length": len(f["text"])})
|
||||
if uploaded_texts:
|
||||
full_prompt = "\n\n".join(uploaded_texts) + "\n\n---\n用户需求:\n" + prompt
|
||||
st.session_state.uploaded_files = [] # 用后即清
|
||||
file_texts.append(f"[上传文件: {f['name']}]\n{f['text']}")
|
||||
attached_info.append({"name": f["name"], "type": f["type"], "length": len(f["text"])})
|
||||
|
||||
if file_texts:
|
||||
full_prompt = "\n\n".join(file_texts) + "\n\n---\n用户需求:\n" + prompt
|
||||
else:
|
||||
full_prompt = prompt
|
||||
|
||||
# 将第一个图片文件的路径传给 agent,供 OCR 字段精确提取
|
||||
for f in st.session_state.chat_attached_files:
|
||||
if f["type"] in ("image", "a4_template", "a4_partial"):
|
||||
st.session_state.agent_state["uploaded_file_path"] = f["path"]
|
||||
break
|
||||
|
||||
# 清理临时文件和状态
|
||||
st.session_state.uploaded_files = []
|
||||
for f in st.session_state.chat_attached_files:
|
||||
try:
|
||||
Path(f["path"]).unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
st.session_state.chat_attached_files = []
|
||||
|
||||
_app_log.info(
|
||||
"收到用户输入",
|
||||
extra={
|
||||
"session_id": current_session_id,
|
||||
"prompt_preview": prompt[:200],
|
||||
"prompt_length": len(prompt),
|
||||
"has_uploaded_files": bool(uploaded_files_info),
|
||||
"uploaded_files": uploaded_files_info,
|
||||
"has_uploaded_files": bool(attached_info),
|
||||
"uploaded_files": attached_info,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user