Spaces:
Sleeping
Sleeping
Update app.py
Browse files17 unmodified lines18192021222369 unmodified lines9394959697989910010110210310410510610710810911 unmodified lines121122123124125126127128129130131132133134135136131 unmodified lines26826927027127227327410 unmodified lines2852862872882892902912922932942952962972982993003013023033044 unmodified lines3093103113123133143153163173183193203213223233243253263274 unmodified lines3323333343353363373383393403413423433443453463478 unmodified lines3563573583593603613623633643653663673683693703713723733743753763773783793803813823832 unmodified lines3863873883893903913923933943953963973983994004011 unmodified line4034044054064074084094104114124132 unmodified lines4164174184194204214221 unmodified line4244254264274284299 unmodified lines4394404414424434444451 unmodified line44744844945045145245345445545645745845946010 unmodified lines47147247347447547647718 unmodified lines49649749849950050150250350450550650750850951011 unmodified lines52252352452517 unmodified linesZIP_OUTPUT_PATH = os.path.join(BASE_DIR, "mineru_results.zip")os.makedirs(PAPERS_DIR, exist_ok=True)# ==========================================# --- 🎨 Custom Purple Theme Definition ---69 unmodified lines# ==========================================# --- ⚙️ Backend Logic & Functions ---# ==========================================def get_debug_info():now = datetime.now().strftime("%H:%M:%S")files = os.listdir(PAPERS_DIR) if os.path.exists(PAPERS_DIR) else "Directory missing"output_detail = "Not generated"if os.path.exists(OUTPUT_DIR):all_output_items = []for root, dirs, files_in_out in os.walk(OUTPUT_DIR):for name in files_in_out:all_output_items.append(os.path.join(os.path.relpath(root, OUTPUT_DIR), name))output_detail = f"Found {len(all_output_items)} files: {all_output_items[:5]}..." if all_output_items else "Directory exists but is EMPTY"return f"[{now}] 📁 papers/ Content: {files}\n\n[{now}] 📂 mineru_outputs Status: {output_detail}"def save_pdf(file):if file is None: return "❌ Please select a PDF first", get_debug_info()11 unmodified linesreturn f"❌ Error: {str(e)}", get_debug_info()def clear_pdf():"""Delete PDF from the backend directory when cleared in UI"""try:deleted_files = []for f in os.listdir(PAPERS_DIR):file_to_del = os.path.join(PAPERS_DIR, f)if os.path.isfile(file_to_del):os.remove(file_to_del)deleted_files.append(f)if deleted_files:return "🗑️ File deleted from workspace", get_debug_info()return "ℹ️ Workspace is already empty", get_debug_info()except Exception as e:return f"❌ Error deleting file: {str(e)}", get_debug_info()131 unmodified linesbackground-image: linear-gradient(rgba(168, 85, 247, .1) 1px, transparent 1px), linear-gradient(90deg, rgba(168, 85, 247, .1) 1px, transparent 1px) !important;}#col-container { margin: 0 auto; max-width: 100%; padding: 20px; }#main-title { text-align: center !important; padding: 1.5rem 0 0.5rem 0; }#main-title h1 {10 unmodified lines#subtitle p { margin: 0 auto; color: #666; font-size: 1.1rem; font-weight: 500; }.dark #subtitle p { color: #DAB2FF; }/* ======== 修改:模块卡片强化圆角和内外边距 ======== */.gradio-group {background: rgba(255, 255, 255, 0.9) !important;border: 2px solid #E9D5FF !important;border-radius: 24px !important; /* 更明显的圆角 */box-shadow: 0 4px 24px rgba(168, 85, 247, 0.08) !important;backdrop-filter: blur(10px);transition: all 0.3s ease;padding: 16px 16px 16px 16px !important; /* 边缘与内层内容的间距 */overflow: visible !important;margin-bottom: 10px !important; /* 模块之间的垂直间距 */display: flex !important;flex-direction: column !important;gap: 16px !important; /* 内部组件之间的自然间距 */}.gradio-group:hover {box-shadow: 0 8px 32px rgba(168, 85, 247, 0.12) !important;4 unmodified linesborder-color: rgba(168, 85, 247, 0.3) !important;}/* 恢复 Gradio 内部组件的圆角(Gradio默认会将 group 内的元素边缘变直) */.gradio-group > div,.gradio-group > .form {border-radius: 12px !important;}/* ======== 优化:文件上传框居中与背景清理 ======== */#pdf-upload-box {border: 2px dashed rgba(192, 132, 252, 0.6) !important;border-radius: 16px !important;background-color: rgba(250, 245, 255, 0.5) !important;transition: all 0.3s ease !important;min-height: 220px !important; /* 增加高度提供居中空间 */position: relative !important;margin-top: 10px !important;}4 unmodified linesbox-shadow: 0 4px 15px rgba(168, 85, 247, 0.15) !important;}/* 隐藏原生的中/英文上传提示、图标及背景 */#pdf-upload-box .upload-container {background: transparent !important;}#pdf-upload-box .upload-container > span,#pdf-upload-box .upload-container > svg {display: none !important;}/* 使用伪元素在中央注入自定义文字和图标 */#pdf-upload-box .upload-container::before {content: "📤\\A Click here to select a PDF\\A or Drag & Drop the file here";white-space: pre-wrap;8 unmodified lineswidth: 100%;height: 100%;position: absolute;top: 0;left: 0;pointer-events: none; /* 防止遮挡拖拽事件 */}/* ======== 修改:减小按钮尺寸,保持字体一致 ======== *//* 主要操作按钮 (Start Mineru & Generate All) */.primary-action-btn {border-radius: 25px !important; /* 调小 */background: linear-gradient(135deg, #9333EA, #7E22CE) !important;color: white !important; font-weight: 700 !important; border: none !important;height: 50px !important; /* 调小:60 -> 50 */width: 80% !important;margin-left: auto !important; /* 新增:自动左边距 */margin-right: auto !important; /* 新增:自动右边距 */margin-top: 10px !important;margin-bottom: 10px !important;display: block !important; /* 新增:确保块级元素 */transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), box-shadow 0.3s ease !important;box-shadow: 0 4px 15px rgba(126, 34, 206, 0.3) !important;cursor: pointer !important;font-size: 1.15rem !important; /* 字体保持一致:略调小以配合新尺寸 */}.primary-action-btn:hover {transform: translateY(-5px) scale(1.02) !important;2 unmodified lines}.primary-action-btn:active { transform: translateY(2px) scale(0.98) !important; box-shadow: 0 2px 10px rgba(126, 34, 206, 0.2) !important; }/* 3个小按钮的样式 */.action-row { display: flex !important; justify-content: center !important; gap: 10px !important; margin-bottom: 10px !important; margin-top: 10px !important;}.action-btn {border-radius: 24px !important; /* 调小 */background: linear-gradient(135deg, #A855F7, #9333EA) !important;color: white !important; font-weight: 600 !important; border: none !important;height: 40px !important; /* 调小:55 -> 48 */width: 120px !important;flex: none !important;/*文字垂直居中*/display: flex !important;align-items: center !important;justify-content: center !important;1 unmodified linepadding: 0 !important;margin-top: 10px !important;margin-bottom: 10px !important;transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), box-shadow 0.3s ease !important;box-shadow: 0 4px 15px rgba(147, 51, 234, 0.2) !important;cursor: pointer !important; display: flex !important; align-items: center !important; justify-content: center !important;font-size: 1.05rem !important; /* 字体保持一致:显式设置 */}.action-btn:hover {transform: translateY(-5px) scale(1.03) !important;2 unmodified lines}.action-btn:active { transform: translateY(2px) scale(0.98) !important; box-shadow: 0 2px 10px rgba(147, 51, 234, 0.2) !important; }/* Terminal Log Style */.log-box textarea { font-family: 'IBM Plex Mono', monospace !important; font-size: 13px !important; background-color: #1e1e1e !important; color: #DAB2FF !important; border: 1px solid #C084FC !important; border-radius: 8px !important; }.status-text textarea { background-color: transparent !important; border: none !important; box-shadow: none !important; font-weight: 600 !important; color: #6B21A8 !important; }.dark .status-text textarea { color: #C084FC !important; }1 unmodified line::-webkit-scrollbar-track { background: rgba(168, 85, 247, 0.05); border-radius: 4px; }::-webkit-scrollbar-thumb { background: linear-gradient(135deg, #A855F7, #C084FC); border-radius: 4px; }::-webkit-scrollbar-thumb:hover { background: linear-gradient(135deg, #9333EA, #A855F7); }"""with gr.Blocks(theme=purple_theme, css=custom_css) as demo:9 unmodified lineswith gr.Group(elem_classes="gradio-group"):gr.Markdown("### ⚙️ 1. Global API Configuration")with gr.Row():key_input = gr.Textbox(label="Gemini API Key", type="password", placeholder="sk-...", scale=1)api_base_url_input = gr.Textbox(label="Base URL (Optional)", placeholder="https://api.example.com", scale=1)key_btn = gr.Button("💾 Save API Configuration")1 unmodified linewith gr.Group(elem_classes="gradio-group"):gr.Markdown("### 📄 2. Document Parsing")# 简化了 Label,因为 CSS 已经接管了内部文字渲染pdf_input = gr.File(label="Upload Document",file_types=[".pdf"],elem_id="pdf-upload-box")# 应用全新的 primary-action-btn 悬浮/圆角类parse_btn = gr.Button("🚀 Start Mineru & DAG Extraction", elem_classes="primary-action-btn")parse_status = gr.Textbox(10 unmodified linesgen_poster_btn = gr.Button("🖼️ Gen Poster", elem_classes="action-btn")gen_pr_btn = gr.Button("📰 Gen Article", elem_classes="action-btn")# 应用全新的 primary-action-btn 悬浮/圆角类gen_all_btn = gr.Button("✨ Generate All Assets (ALL)", elem_classes="primary-action-btn")# ================= RIGHT COLUMN: OUTPUTS & LOGS =================18 unmodified lineswith gr.Tab("🔍 System Snapshot"):refresh_btn = gr.Button("🔄 Refresh Directory Tree")debug_view = gr.Textbox(label="Workspace Files", lines=13, interactive=False, value=get_debug_info(), elem_classes="log-box")# ================= LOGIC BINDINGS =================key_btn.click(fn=save_api_settings, inputs=[key_input, api_base_url_input], outputs=[parse_status, debug_view])pdf_input.upload(fn=save_pdf, inputs=pdf_input, outputs=[parse_status, debug_view])# 增加清除逻辑,点击 "x" 后彻底删除后端文件pdf_input.clear(fn=clear_pdf, outputs=[parse_status, debug_view])parse_btn.click(fn=run_mineru_parsing_and_dag_gen, outputs=[parse_status, debug_view, cmd_logs])11 unmodified linesrefresh_btn.click(fn=get_debug_info, outputs=debug_view)if __name__ == "__main__":demo.launch()17 unmodified lines1819202122232469 unmodified lines94959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814911 unmodified lines161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201131 unmodified lines33333433533633733833910 unmodified lines3503513523533543553563573583593603613623633643653663673684 unmodified lines3733743753763773783793803813823833843853863874 unmodified lines3923933943953963973983994004018 unmodified lines4104114124134144154164174184194204214224234244254264274284294304314324334342 unmodified lines4374384394404414424434444454464474484494501 unmodified line4524534544554564574584594604612 unmodified lines4644654664674684691 unmodified line4714724734744754764774784794809 unmodified lines4904914924934944954961 unmodified line49849950050150250350450550650750850910 unmodified lines52052152252352452518 unmodified lines54454554654754854955055155255355455555655755855911 unmodified lines57157257357417 unmodified linesZIP_OUTPUT_PATH = os.path.join(BASE_DIR, "mineru_results.zip")os.makedirs(PAPERS_DIR, exist_ok=True)os.makedirs(OUTPUT_DIR, exist_ok=True)# ==========================================# --- 🎨 Custom Purple Theme Definition ---69 unmodified lines# ==========================================# --- ⚙️ Backend Logic & Functions ---# ==========================================def get_tree_html(dir_path):"""递归生成可折叠的 HTML 目录树"""if not os.path.exists(dir_path):return "<div style='margin-left: 15px; color: #888;'><i>Directory missing</i></div>"def build_html(current_path):html = ""try:items = sorted(os.listdir(current_path))except Exception:return ""if not items:return ""for item in items:item_path = os.path.join(current_path, item)if os.path.isdir(item_path):# 文件夹节点 (可折叠)html += f'<details style="margin-left: 15px; cursor: pointer; margin-top: 4px;"><summary style="outline: none; color: #C084FC;">📁 <b>{item}</b></summary>'inner_html = build_html(item_path)html += inner_html if inner_html else "<div style='margin-left: 20px; color: #888; font-size: 12px;'><i>Empty</i></div>"html += '</details>'else:# 文件节点html += f'<div style="margin-left: 18px; padding-left: 12px; border-left: 1px dotted #A855F7; margin-top: 4px; color: #DAB2FF;">📄 {item}</div>'return htmlcontent = build_html(dir_path)return content if content else "<div style='margin-left: 15px; color: #888;'><i>Empty directory</i></div>"def get_debug_info():"""返回渲染好的目录树 HTML 容器"""papers_tree = get_tree_html(PAPERS_DIR)output_tree = get_tree_html(OUTPUT_DIR)html = f"""<div style="font-family: 'IBM Plex Mono', monospace; font-size: 13px; background-color: #1e1e1e; border: 1px solid #C084FC; border-radius: 8px; padding: 16px; max-height: 400px; overflow-y: auto;"><details open style="margin-bottom: 12px; cursor: pointer;"><summary style="outline: none; font-size: 15px; color: #A855F7;">📁 <b>papers/</b></summary>{papers_tree}</details><details open style="cursor: pointer;"><summary style="outline: none; font-size: 15px; color: #A855F7;">📂 <b>mineru_outputs/</b></summary>{output_tree}</details></div>"""return htmldef save_pdf(file):if file is None: return "❌ Please select a PDF first", get_debug_info()11 unmodified linesreturn f"❌ Error: {str(e)}", get_debug_info()def clear_pdf():"""Delete PDF and its corresponding mineru output directory"""try:deleted_files = []deleted_dirs = []# 1. 记录要被删除的 PDF 文件名(用于匹配输出目录)pdf_names = [f for f in os.listdir(PAPERS_DIR) if f.endswith('.pdf')]# 2. 删除 papers 目录下的 PDFfor f in os.listdir(PAPERS_DIR):file_to_del = os.path.join(PAPERS_DIR, f)if os.path.isfile(file_to_del):os.remove(file_to_del)deleted_files.append(f)# 3. 删除 mineru_outputs 下的同名文件夹if os.path.exists(OUTPUT_DIR):for pdf_name in pdf_names:base_name = os.path.splitext(pdf_name)[0]base_name_us = base_name.replace(" ", "_") # 兼容 Mineru 可能会把空格转为下划线for item in os.listdir(OUTPUT_DIR):# 匹配严格同名,或者下划线名称,或者带 .pdf 后缀的文件夹if item in [base_name, base_name_us, pdf_name]:dir_to_del = os.path.join(OUTPUT_DIR, item)if os.path.isdir(dir_to_del):shutil.rmtree(dir_to_del)deleted_dirs.append(item)# 4. 删除可能遗留的打包压缩文件if os.path.exists(ZIP_OUTPUT_PATH):os.remove(ZIP_OUTPUT_PATH)if deleted_files or deleted_dirs:return f"🗑️ Workspace cleared (Deleted: {len(deleted_files)} PDF, {len(deleted_dirs)} Output Folder)", get_debug_info()return "ℹ️ Workspace is already empty", get_debug_info()except Exception as e:return f"❌ Error deleting file: {str(e)}", get_debug_info()131 unmodified linesbackground-image: linear-gradient(rgba(168, 85, 247, .1) 1px, transparent 1px), linear-gradient(90deg, rgba(168, 85, 247, .1) 1px, transparent 1px) !important;}#col-container { margin: 0 auto; max-width: 90%; padding: 20px; }#main-title { text-align: center !important; padding: 1.5rem 0 0.5rem 0; }#main-title h1 {10 unmodified lines#subtitle p { margin: 0 auto; color: #666; font-size: 1.1rem; font-weight: 500; }.dark #subtitle p { color: #DAB2FF; }.gradio-group {background: rgba(255, 255, 255, 0.9) !important;border: 2px solid #E9D5FF !important;border-radius: 24px !important;box-shadow: 0 4px 24px rgba(168, 85, 247, 0.08) !important;backdrop-filter: blur(10px);transition: all 0.3s ease;padding: 16px 16px 16px 16px !important;overflow: visible !important;margin-bottom: 10px !important;display: flex !important;flex-direction: column !important;gap: 16px !important;}.gradio-group:hover {box-shadow: 0 8px 32px rgba(168, 85, 247, 0.12) !important;4 unmodified linesborder-color: rgba(168, 85, 247, 0.3) !important;}.gradio-group > div,.gradio-group > .form { border-radius: 12px !important; }#pdf-upload-box {border: 2px dashed rgba(192, 132, 252, 0.6) !important;border-radius: 16px !important;background-color: rgba(250, 245, 255, 0.5) !important;transition: all 0.3s ease !important;min-height: 220px !important;position: relative !important;margin-top: 10px !important;}4 unmodified linesbox-shadow: 0 4px 15px rgba(168, 85, 247, 0.15) !important;}#pdf-upload-box .upload-container { background: transparent !important; }#pdf-upload-box .upload-container > span,#pdf-upload-box .upload-container > svg { display: none !important; }#pdf-upload-box .upload-container::before {content: "📤\\A Click here to select a PDF\\A or Drag & Drop the file here";white-space: pre-wrap;8 unmodified lineswidth: 100%;height: 100%;position: absolute;top: 0; left: 0;pointer-events: none;}.primary-action-btn {border-radius: 25px !important;background: linear-gradient(135deg, #9333EA, #7E22CE) !important;color: white !important; font-weight: 700 !important; border: none !important;height: 50px !important;width: 80% !important;margin-left: auto !important;margin-right: auto !important;margin-top: 10px !important;margin-bottom: 10px !important;display: block !important;transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), box-shadow 0.3s ease !important;box-shadow: 0 4px 15px rgba(126, 34, 206, 0.3) !important;cursor: pointer !important;font-size: 1.15rem !important;}.primary-action-btn:hover {transform: translateY(-5px) scale(1.02) !important;2 unmodified lines}.primary-action-btn:active { transform: translateY(2px) scale(0.98) !important; box-shadow: 0 2px 10px rgba(126, 34, 206, 0.2) !important; }.action-row { display: flex !important; justify-content: center !important; gap: 10px !important; margin-bottom: 10px !important; margin-top: 10px !important;}.action-btn {border-radius: 24px !important;background: linear-gradient(135deg, #A855F7, #9333EA) !important;color: white !important; font-weight: 600 !important; border: none !important;height: 40px !important;width: 120px !important;flex: none !important;display: flex !important;align-items: center !important;justify-content: center !important;1 unmodified linepadding: 0 !important;margin-top: 10px !important;margin-bottom: 10px !important;transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), box-shadow 0.3s ease !important;box-shadow: 0 4px 15px rgba(147, 51, 234, 0.2) !important;cursor: pointer !important;font-size: 1.05rem !important;}.action-btn:hover {transform: translateY(-5px) scale(1.03) !important;2 unmodified lines}.action-btn:active { transform: translateY(2px) scale(0.98) !important; box-shadow: 0 2px 10px rgba(147, 51, 234, 0.2) !important; }.log-box textarea { font-family: 'IBM Plex Mono', monospace !important; font-size: 13px !important; background-color: #1e1e1e !important; color: #DAB2FF !important; border: 1px solid #C084FC !important; border-radius: 8px !important; }.status-text textarea { background-color: transparent !important; border: none !important; box-shadow: none !important; font-weight: 600 !important; color: #6B21A8 !important; }.dark .status-text textarea { color: #C084FC !important; }1 unmodified line::-webkit-scrollbar-track { background: rgba(168, 85, 247, 0.05); border-radius: 4px; }::-webkit-scrollbar-thumb { background: linear-gradient(135deg, #A855F7, #C084FC); border-radius: 4px; }::-webkit-scrollbar-thumb:hover { background: linear-gradient(135deg, #9333EA, #A855F7); }/* 使折叠树中的 details 和 summary 更加平滑 */details > summary { transition: color 0.2s ease; }details > summary:hover { color: #E9D5FF !important; }"""with gr.Blocks(theme=purple_theme, css=custom_css) as demo:9 unmodified lineswith gr.Group(elem_classes="gradio-group"):gr.Markdown("### ⚙️ 1. Global API Configuration")with gr.Row():key_input = gr.Textbox(label="API Key", type="password", placeholder="sk-...", scale=1)api_base_url_input = gr.Textbox(label="Base URL (Optional)", placeholder="https://api.example.com", scale=1)key_btn = gr.Button("💾 Save API Configuration")1 unmodified linewith gr.Group(elem_classes="gradio-group"):gr.Markdown("### 📄 2. Document Parsing")pdf_input = gr.File(label="Upload Document",file_types=[".pdf"],elem_id="pdf-upload-box")parse_btn = gr.Button("🚀 Start Mineru & DAG Extraction", elem_classes="primary-action-btn")parse_status = gr.Textbox(10 unmodified linesgen_poster_btn = gr.Button("🖼️ Gen Poster", elem_classes="action-btn")gen_pr_btn = gr.Button("📰 Gen Article", elem_classes="action-btn")gen_all_btn = gr.Button("✨ Generate All Assets (ALL)", elem_classes="primary-action-btn")# ================= RIGHT COLUMN: OUTPUTS & LOGS =================18 unmodified lineswith gr.Tab("🔍 System Snapshot"):refresh_btn = gr.Button("🔄 Refresh Directory Tree")# 这里改为 HTML 组件,以便渲染我们的 details/summary 折叠树debug_view = gr.HTML(value=get_debug_info())# ================= LOGIC BINDINGS =================key_btn.click(fn=save_api_settings, inputs=[key_input, api_base_url_input], outputs=[parse_status, debug_view])pdf_input.upload(fn=save_pdf, inputs=pdf_input, outputs=[parse_status, debug_view])# 彻底清除:不仅清除 PDF,还清除 mineru output 中的对应文件夹pdf_input.clear(fn=clear_pdf, outputs=[parse_status, debug_view])parse_btn.click(fn=run_mineru_parsing_and_dag_gen, outputs=[parse_status, debug_view, cmd_logs])11 unmodified linesrefresh_btn.click(fn=get_debug_info, outputs=debug_view)if __name__ == "__main__":demo.launch(debug=True)
app.py+109-60