Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line2345671 unmodified line910111213141 unmodified line1617181920212 unmodified lines2425262728293028 unmodified lines5960616263644 unmodified lines6970717273747576777879808182832 unmodified lines86878889909192939495969798991001011021031041051061071081091101111121131141151161171181191 unmodified lineimport osimport yamlimport shutilimport sysfrom datetime import datetime1 unmodified lineBASE_DIR = os.path.dirname(os.path.abspath(__file__))PAPERS_DIR = os.path.join(BASE_DIR, "papers")CONFIG_PATH = os.path.join(BASE_DIR, "config.yaml")os.makedirs(PAPERS_DIR, exist_ok=True)def get_debug_info():1 unmodified linenow = datetime.now().strftime("%H:%M:%S")files = os.listdir(PAPERS_DIR) if os.path.exists(PAPERS_DIR) else "Directory missing"config_content = "Not found"if os.path.exists(CONFIG_PATH):try:2 unmodified linesexcept Exception:config_content = "Error reading config"return f"[{now}] 📁 papers/ 文件夹下的文件:\n{files}\n\n[{now}] 📄 config.yaml 完整内容:\n{config_content}"def save_pdf(file):if file is None:28 unmodified linesexcept Exception as e:return f"❌ 保存 Key 出错: {str(e)}", get_debug_info()# --- 构建单页 UI ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# 📑 PDF 助手管理后台")4 unmodified lines# 第一部分:API 配置with gr.Group():gr.Markdown("### 1. 密钥配置")key_input = gr.Textbox(label="Gemini API Key",type="password",placeholder="在此输入您的 API Key...")key_btn = gr.Button("保存配置", variant="primary")key_status = gr.Textbox(label="配置状态", interactive=False)gr.Markdown("---") # 分割线# 第二部分:PDF 上传with gr.Group():2 unmodified linespdf_btn = gr.Button("保存到 papers 文件夹", variant="primary")pdf_status = gr.Textbox(label="上传状态", interactive=False)# 右侧调试监控区with gr.Column(scale=1):gr.Markdown("### 🔍 实时系统监控")debug_view = gr.Textbox(label="服务器文件状态 (每操作一次即自动更新)",value=get_debug_info(),lines=20,interactive=False)refresh_btn = gr.Button("🔄 手动刷新状态")# 绑定事件逻辑key_btn.click(fn=save_api_key,inputs=key_input,outputs=[key_status, debug_view])pdf_btn.click(fn=save_pdf,inputs=pdf_input,outputs=[pdf_status, debug_view])refresh_btn.click(fn=get_debug_info,outputs=debug_view)if __name__ == "__main__":demo.launch()1 unmodified line23456781 unmodified line10111213141516171 unmodified line1920212223242526272829302 unmodified lines3334353637383928 unmodified lines68697071727374757677787980818283848586878889909192939495969798991001011021034 unmodified lines1081091101111121131141151161171182 unmodified lines1211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511 unmodified lineimport osimport yamlimport shutilimport subprocessimport sysfrom datetime import datetime1 unmodified lineBASE_DIR = os.path.dirname(os.path.abspath(__file__))PAPERS_DIR = os.path.join(BASE_DIR, "papers")CONFIG_PATH = os.path.join(BASE_DIR, "config.yaml")OUTPUT_DIR = os.path.join(BASE_DIR, "mineru_outputs")os.makedirs(PAPERS_DIR, exist_ok=True)def get_debug_info():1 unmodified linenow = datetime.now().strftime("%H:%M:%S")files = os.listdir(PAPERS_DIR) if os.path.exists(PAPERS_DIR) else "Directory missing"# 检查输出目录是否存在output_status = "Not generated"if os.path.exists(OUTPUT_DIR):out_files = os.listdir(OUTPUT_DIR)output_status = f"Exists ({len(out_files)} items)"config_content = "Not found"if os.path.exists(CONFIG_PATH):try:2 unmodified linesexcept Exception:config_content = "Error reading config"return f"[{now}] 📁 papers/ 文件夹:\n{files}\n\n[{now}] 📂 mineru_outputs:\n{output_status}\n\n[{now}] 📄 config.yaml 内容:\n{config_content}"def save_pdf(file):if file is None:28 unmodified linesexcept Exception as e:return f"❌ 保存 Key 出错: {str(e)}", get_debug_info()def run_mineru_parsing():"""执行 PDF 解析逻辑"""# 1. 判断是否上传了 PDF (检查 papers 文件夹是否为空)if not os.path.exists(PAPERS_DIR) or not any(f.endswith('.pdf') for f in os.listdir(PAPERS_DIR)):return "❌ 未发现已上传的 PDF 文件,请先执行步骤 2。", get_debug_info()try:# 2. 设置环境变量env = os.environ.copy()env["MINERU_FORMULA_ENABLE"] = "false"env["MINERU_TABLE_ENABLE"] = "false"# 3. 执行 Mineru 命令# 使用 list 形式传递参数更安全command = ["mineru", "-p", "papers", "-o", "mineru_outputs"]# 提示开始执行print(f"Executing: {' '.join(command)}", file=sys.stderr, flush=True)# 执行并等待结束result = subprocess.run(command, env=env, capture_output=True, text=True)if result.returncode == 0:return "✅ PDF解析完成", get_debug_info()else:return f"❌ 解析过程中出错: {result.stderr}", get_debug_info()except Exception as e:return f"❌ 执行命令时发生异常: {str(e)}", get_debug_info()# --- 构建单页 UI ---with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# 📑 PDF 助手管理后台")4 unmodified lines# 第一部分:API 配置with gr.Group():gr.Markdown("### 1. 密钥配置")key_input = gr.Textbox(label="Gemini API Key", type="password")key_btn = gr.Button("保存配置", variant="primary")key_status = gr.Textbox(label="配置状态", interactive=False)gr.Markdown("---")# 第二部分:PDF 上传with gr.Group():2 unmodified linespdf_btn = gr.Button("保存到 papers 文件夹", variant="primary")pdf_status = gr.Textbox(label="上传状态", interactive=False)gr.Markdown("---")# 第三部分:解析步骤with gr.Group():gr.Markdown("### 3. 解析 PDF")gr.Markdown("<small>说明:禁用公式与表格提取以加快速度</small>")parse_btn = gr.Button("🚀 开始解析 (Run Mineru)", variant="secondary")parse_status = gr.Textbox(label="解析进度/结果", interactive=False)# 右侧调试监控区with gr.Column(scale=1):gr.Markdown("### 🔍 实时系统监控")debug_view = gr.Textbox(label="服务器文件状态",value=get_debug_info(),lines=25,interactive=False)refresh_btn = gr.Button("🔄 手动刷新状态")# 绑定事件逻辑key_btn.click(fn=save_api_key, inputs=key_input, outputs=[key_status, debug_view])pdf_btn.click(fn=save_pdf, inputs=pdf_input, outputs=[pdf_status, debug_view])parse_btn.click(fn=run_mineru_parsing, outputs=[parse_status, debug_view])refresh_btn.click(fn=get_debug_info, outputs=debug_view)if __name__ == "__main__":demo.launch()
app.py+57-25