""" 文档管理组件 """ import streamlit as st from services import get_document_service, get_vector_store_service, get_cached_user_stats from utils.config import config def show_document_manager(user_id: int): """显示文档管理界面""" st.title("📁 知识库管理") # 显示 Embedding 模型加载状态 _show_embedding_model_status() doc_service = get_document_service() # 显示统计信息 _show_statistics(user_id, doc_service) st.markdown("---") # 文档上传区域 _show_upload_section(user_id, doc_service) st.markdown("---") # 文档列表 _show_document_list(user_id, doc_service) def _show_embedding_model_status(): """显示 Embedding 模型加载状态""" vector_service = get_vector_store_service() status = vector_service.get_embeddings_loading_status() if status['ready']: st.success(f"✅ Embedding 模型已就绪: {status['model_name']}") elif status['loading']: st.info(f"⏳ 正在后台加载 Embedding 模型: {status['model_name']},请稍候...") st.caption("💡 模型加载完成后即可使用向量检索功能") else: st.warning(f"⚠️ Embedding 模型未加载: {status['model_name']}") @st.cache_data(ttl=120) # 缓存120秒 def _get_cached_documents(user_id: int): """缓存文档列表""" doc_service = get_document_service() return doc_service.get_user_documents(user_id) def _show_statistics(user_id: int, doc_service): """显示统计信息""" try: # 使用缓存的统计数据,避免频繁查询 stats = get_cached_user_stats(user_id) col1, col2, col3 = st.columns(3) with col1: st.metric("📄 文档数量", stats['document_count']) with col2: st.metric("🧩 向量块数", stats['vector_count']) with col3: st.metric("💾 存储空间", stats['storage_used_formatted']) except ConnectionError as e: # 数据库连接失败,显示友好的错误提示 st.error("⚠️ 无法连接到数据库") error_msg = str(e) # 检查是否是 DNS 解析失败 if "DNS 解析失败" in error_msg or "nodename nor servname" in error_msg: st.warning(""" **网络连接问题** 无法连接到 Supabase PostgreSQL 数据库。这可能是由于: - 网络连接不稳定 - DNS 解析失败 - 防火墙阻止了连接 **解决方案:** 1. 检查网络连接 2. 确认 `DATABASE_URL` 配置正确 3. 如果问题持续,可以暂时切换到本地模式: - 在 `.env` 文件中设置 `DATABASE_MODE=local` - 重启应用 """) else: st.warning(f"数据库连接错误:{error_msg}") # 显示默认统计值 col1, col2, col3 = st.columns(3) with col1: st.metric("📄 文档数量", "N/A") with col2: st.metric("🧩 向量块数", "N/A") with col3: st.metric("💾 存储空间", "N/A") except Exception as e: st.error(f"获取统计信息失败: {str(e)}") # 显示默认统计值 col1, col2, col3 = st.columns(3) with col1: st.metric("📄 文档数量", "N/A") with col2: st.metric("🧩 向量块数", "N/A") with col3: st.metric("💾 存储空间", "N/A") def _show_upload_section(user_id: int, doc_service): """显示上传区域""" st.subheader("📤 上传文档") # 使用 session_state 管理文件上传器的 key if 'uploader_key' not in st.session_state: st.session_state.uploader_key = 0 # 动态获取最大文件大小(MB) max_size_mb = config.MAX_FILE_SIZE / (1024 * 1024) uploaded_file = st.file_uploader( "选择文件", type=['pdf', 'txt', 'md', 'docx'], help=f"支持 PDF、TXT、Markdown、Word 文档,最大 {max_size_mb:.0f}MB", key=f"file_uploader_{st.session_state.uploader_key}" ) if uploaded_file: st.info(f"📄 已选择: {uploaded_file.name} ({uploaded_file.size // 1024} KB)") col1, col2 = st.columns([1, 4]) with col1: if st.button("🚀 开始上传", use_container_width=True): with st.spinner("正在处理文档..."): success, message = doc_service.upload_document(user_id, uploaded_file) if success: st.success(f"✅ {message}") # 精确清除文档相关缓存 get_cached_user_stats.clear() _get_cached_documents.clear() # 上传成功后,更新 key 以清空文件选择器 st.session_state.uploader_key += 1 st.rerun() else: st.error(f"❌ {message}") with col2: st.caption("上传后将自动解析、分块并生成向量索引") def _show_document_list(user_id: int, doc_service): """显示文档列表""" # 使用更紧凑的标题样式 st.markdown("
{icon} {doc['original_filename']}
", unsafe_allow_html=True) # 文件信息 info_parts = [] info_parts.append(f"📏 {doc['file_size_formatted']}") if doc.get('page_count'): info_parts.append(f"📄 {doc['page_count']} 页") info_parts.append(f"🧩 {doc['chunk_count']} 块") info_parts.append(f"🕐 {doc['upload_at'][:16]}") st.markdown(f"{' • '.join(info_parts)}
", unsafe_allow_html=True) with col2: # 三点菜单 with st.popover("⋮", use_container_width=True): st.markdown(f"**操作菜单**") st.caption(doc['original_filename']) st.markdown("---") # 预览按钮 if st.button("👁️ 预览文档", key=f"preview_{doc['doc_id']}", use_container_width=True): _show_document_preview(user_id, doc['doc_id'], doc['original_filename'], doc_service) # 删除按钮 if st.button("🗑️ 删除文档", key=f"delete_{doc['doc_id']}", use_container_width=True): _confirm_delete_document(user_id, doc['doc_id'], doc['original_filename'], doc_service) # 使用更紧凑的分隔线 st.markdown("{}