Spaces:
Sleeping
Sleeping
Update app.py
Browse files150 unmodified lines1511521531541551561572 unmodified lines1601611621631641651661671682 unmodified lines17117217317417517617717817913 unmodified lines1931941951961971981994 unmodified lines2042052062072082092103 unmodified lines2142152162172182192202212222232242252261 unmodified line2282292302312322332343 unmodified lines2382392402412422432442452462472482492502512522532542552562572582592602612622632642654 unmodified lines27027127227327427527621 unmodified lines2982993003013023033041 unmodified line306307308309310311312313314315316317318319320321322323324325326327328329138 unmodified lines46846947047147247347487 unmodified lines5625635645655665675685694 unmodified lines57457557657757857958058158258358458558658758868 unmodified lines657658659660661662663150 unmodified linesdef save_pdf(file, session_id):if file is None:return empty_progress_html("❌ Please select a PDF first"), get_debug_info(session_id), Falsetry:papers_dir, _, _ = get_user_dirs(session_id)for f in os.listdir(papers_dir):2 unmodified linesfile_path = os.path.join(papers_dir, os.path.basename(file.name))shutil.copy(file.name, file_path)return create_progress_html(100, f"✅ PDF Uploaded: {os.path.basename(file.name)}", "success"), get_debug_info(session_id), Trueexcept Exception as e:return create_progress_html(0, f"❌ Error: {str(e)}", "error"), get_debug_info(session_id), Falsedef clear_pdf(session_id):try:2 unmodified linesshutil.rmtree(user_base)disable_btn = gr.update(interactive=False)return empty_progress_html("🗑️ Workspace cleared"), empty_progress_html("No generation task currently..."), get_debug_info(session_id), False, disable_btn, disable_btn, disable_btn, disable_btnexcept Exception as e:return create_progress_html(0, f"❌ Clear Error: {str(e)}", "error"), gr.update(), get_debug_info(session_id), False, gr.update(), gr.update(), gr.update(), gr.update()def build_user_env(api_key, api_base_url, papers_dir, output_dir):env = os.environ.copy()13 unmodified linespapers_dir, output_dir, _ = get_user_dirs(session_id)if not os.path.exists(papers_dir) or not any(f.endswith('.pdf') for f in os.listdir(papers_dir)):yield create_progress_html(0, "❌ No PDF file found", "error"), get_debug_info(session_id), "No execution logs.", no_change, no_change, no_change, no_changereturnfull_log = ""4 unmodified lines# 10%progress(0.1, desc="启动 Mineru 解析...")yield create_progress_html(10, "⏳ Starting Mineru parsing...", "active"), get_debug_info(session_id), full_log, no_change, no_change, no_change, no_changeprocess_mineru = subprocess.Popen(command_mineru, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=13 unmodified linesprogress(0.3, desc="Mineru 正在解析 PDF...")for line in iter(process_mineru.stdout.readline, ''):full_log += lineyield create_progress_html(30, "⏳ Mineru parsing PDF...", "active"), get_debug_info(session_id), full_log, no_change, no_change, no_change, no_changeprocess_mineru.stdout.close()returncode_mineru = process_mineru.wait()if returncode_mineru != 0:progress(1.0, desc="Mineru 解析失败")yield create_progress_html(30, f"❌ Mineru failed (Code {returncode_mineru})", "error"), get_debug_info(session_id), full_log, disable_btn, disable_btn, disable_btn, disable_btnreturncommand_dag = [sys.executable, "gen_dag.py"]1 unmodified line# 60%progress(0.6, desc="执行 DAG 生成...")yield create_progress_html(60, "⏳ Executing DAG generation...", "active"), get_debug_info(session_id), full_log, no_change, no_change, no_change, no_changeprocess_dag = subprocess.Popen(command_dag, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=13 unmodified linesprogress(0.8, desc="构建图结构中...")for line in iter(process_dag.stdout.readline, ''):full_log += lineyield create_progress_html(80, "⏳ Building DAG...", "active"), get_debug_info(session_id), full_log, no_change, no_change, no_change, no_changeprocess_dag.stdout.close()returncode_dag = process_dag.wait()if returncode_dag == 0:progress(1.0, desc="解析与构建完成!")enable_btn = gr.update(interactive=True)yield create_progress_html(100, "✅ Fully completed", "success"), get_debug_info(session_id), full_log, enable_btn, enable_btn, enable_btn, enable_btnelse:progress(1.0, desc="DAG 生成失败")yield create_progress_html(80, "❌ DAG generation failed", "error"), get_debug_info(session_id), full_log, disable_btn, disable_btn, disable_btn, disable_btnexcept Exception as e:progress(1.0, desc="发生异常")error_log = full_log + f"\n[Global Exception]:\n{str(e)}"yield create_progress_html(0, "❌ Execution Exception", "error"), get_debug_info(session_id), error_log, disable_btn, disable_btn, disable_btn, disable_btndef run_final_generation(task_type, session_id, api_key, api_base_url, progress=gr.Progress()):papers_dir, output_dir, zip_path = get_user_dirs(session_id)if not os.path.exists(output_dir):yield create_progress_html(0, "❌ Please run parsing first", "error"), get_debug_info(session_id), "No output folder found.", gr.update(visible=False)returnscripts_to_run = []4 unmodified linesfull_log = f"🚀 Starting {len(scripts_to_run)} tasks for session {session_id[:8]}...\n"progress(0.1, desc=f"启动 {task_type.upper()} 生成任务...")yield create_progress_html(10, f"⏳ Starting {task_type.upper()}...", "active"), get_debug_info(session_id), full_log, gr.update(visible=False)q = queue.Queue()processes = []21 unmodified linestry:script_name, line = q.get(timeout=0.1)full_log += f"[{script_name}] {line}"yield create_progress_html(50, f"⏳ Generating {task_type.upper()}...", "active"), get_debug_info(session_id), full_log, gr.update(visible=False)except queue.Empty:active_processes = sum(1 for _, p in processes if p.poll() is None)1 unmodified lineif not success:progress(1.0, desc="生成失败")yield create_progress_html(50, "❌ Tasks failed", "error"), get_debug_info(session_id), full_log, gr.update(visible=False)returnfull_log += "\n📦 Zipping output directory...\n"progress(0.9, desc="打包压缩结果...")yield create_progress_html(90, "⏳ Zipping outputs...", "active"), get_debug_info(session_id), full_log, gr.update(visible=False)zip_base_name = zip_path.replace(".zip", "")shutil.make_archive(zip_base_name, 'zip', output_dir)full_log += "✅ All tasks completed successfully.\n"progress(1.0, desc="全部完成!")yield create_progress_html(100, f"✅ {task_type.upper()} Generated", "success"), get_debug_info(session_id), full_log, gr.update(value=zip_path, visible=True)except Exception as e:progress(1.0, desc="发生全局异常")error_log = full_log + f"\n[Global Exception]:\n{str(e)}"yield create_progress_html(0, "❌ Global exception", "error"), get_debug_info(session_id), error_log, gr.update(visible=False)# ==========================================# --- 🚀 UI Configuration & Advanced CSS ---138 unmodified linesmargin-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;87 unmodified linespdf_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", interactive=False)# 进度条替换原本的文本框parse_progress = gr.HTML(value=empty_progress_html("Waiting for document upload..."))# 3. Asset Generationwith gr.Group(elem_classes="gradio-group"):4 unmodified linesgen_pr_btn = gr.Button("📰 Gen PR", elem_classes="action-btn", interactive=False)gen_all_btn = gr.Button("✨ Generate All Assets (ALL)", elem_classes="primary-action-btn", interactive=False)# 新增进度的展示条gen_progress = gr.HTML(value=empty_progress_html("No generation task currently..."))with gr.Column(scale=1):# 4. Results & Downloadswith gr.Group(elem_classes="gradio-group"):gr.Markdown("### 📦 Generation Results & Download")# --- 新增:无输出时的美化空状态提示词 ---download_placeholder = gr.HTML('''<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 160px; border: 2px dashed rgba(192, 132, 252, 0.6); border-radius: 16px; background-color: rgba(250, 245, 255, 0.5); color: #9333EA; text-align: center; transition: all 0.3s ease;">68 unmodified linesrefresh_btn.click(fn=get_debug_info, inputs=[session_id_state], outputs=debug_view)def toggle_empty_placeholder(file_val):# 如果获取到了文件(值不为空),就隐藏占位提示词;否则保持显示return gr.update(visible=(file_val is None))download_file.change(150 unmodified lines1511521531541551561572 unmodified lines1601611621631641651661671681692 unmodified lines17217317417517617717817918018113 unmodified lines1951961971981992002014 unmodified lines2062072082092102112123 unmodified lines2162172182192202212222232242252262272281 unmodified line2302312322332342352363 unmodified lines2402412422432442452462472482492502512522532542552562572582592602612622632642652662674 unmodified lines27227327427527627727821 unmodified lines3003013023033043053061 unmodified line308309310311312313314315316317318319320321322323324325326327328329330331138 unmodified lines47047147247347447547687 unmodified lines5645655665675685695705714 unmodified lines57657757857958058158258358458558658758858968 unmodified lines658659660661662663150 unmodified linesdef save_pdf(file, session_id):if file is None:return gr.update(visible=False), get_debug_info(session_id), Falsetry:papers_dir, _, _ = get_user_dirs(session_id)for f in os.listdir(papers_dir):2 unmodified linesfile_path = os.path.join(papers_dir, os.path.basename(file.name))shutil.copy(file.name, file_path)# 上传成功后显示进度条以反馈状态return gr.update(value=create_progress_html(100, f"✅ PDF Uploaded: {os.path.basename(file.name)}", "success"), visible=True), get_debug_info(session_id), Trueexcept Exception as e:return gr.update(value=create_progress_html(0, f"❌ Error: {str(e)}", "error"), visible=True), get_debug_info(session_id), Falsedef clear_pdf(session_id):try:2 unmodified linesshutil.rmtree(user_base)disable_btn = gr.update(interactive=False)# 清除时隐藏全部进度条return gr.update(visible=False), gr.update(visible=False), get_debug_info(session_id), False, disable_btn, disable_btn, disable_btn, disable_btnexcept Exception as e:return gr.update(value=create_progress_html(0, f"❌ Clear Error: {str(e)}", "error"), visible=True), gr.update(), get_debug_info(session_id), False, gr.update(), gr.update(), gr.update(), gr.update()def build_user_env(api_key, api_base_url, papers_dir, output_dir):env = os.environ.copy()13 unmodified linespapers_dir, output_dir, _ = get_user_dirs(session_id)if not os.path.exists(papers_dir) or not any(f.endswith('.pdf') for f in os.listdir(papers_dir)):yield gr.update(value=create_progress_html(0, "❌ No PDF file found", "error"), visible=True), get_debug_info(session_id), "No execution logs.", no_change, no_change, no_change, no_changereturnfull_log = ""4 unmodified lines# 10%progress(0.1, desc="启动 Mineru 解析...")yield gr.update(value=create_progress_html(10, "⏳ Starting Mineru parsing...", "active"), visible=True), get_debug_info(session_id), full_log, no_change, no_change, no_change, no_changeprocess_mineru = subprocess.Popen(command_mineru, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=13 unmodified linesprogress(0.3, desc="Mineru 正在解析 PDF...")for line in iter(process_mineru.stdout.readline, ''):full_log += lineyield gr.update(value=create_progress_html(30, "⏳ Mineru parsing PDF...", "active"), visible=True), get_debug_info(session_id), full_log, no_change, no_change, no_change, no_changeprocess_mineru.stdout.close()returncode_mineru = process_mineru.wait()if returncode_mineru != 0:progress(1.0, desc="Mineru 解析失败")yield gr.update(value=create_progress_html(30, f"❌ Mineru failed (Code {returncode_mineru})", "error"), visible=True), get_debug_info(session_id), full_log, disable_btn, disable_btn, disable_btn, disable_btnreturncommand_dag = [sys.executable, "gen_dag.py"]1 unmodified line# 60%progress(0.6, desc="执行 DAG 生成...")yield gr.update(value=create_progress_html(60, "⏳ Executing DAG generation...", "active"), visible=True), get_debug_info(session_id), full_log, no_change, no_change, no_change, no_changeprocess_dag = subprocess.Popen(command_dag, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=13 unmodified linesprogress(0.8, desc="构建图结构中...")for line in iter(process_dag.stdout.readline, ''):full_log += lineyield gr.update(value=create_progress_html(80, "⏳ Building DAG...", "active"), visible=True), get_debug_info(session_id), full_log, no_change, no_change, no_change, no_changeprocess_dag.stdout.close()returncode_dag = process_dag.wait()if returncode_dag == 0:progress(1.0, desc="解析与构建完成!")enable_btn = gr.update(interactive=True)yield gr.update(value=create_progress_html(100, "✅ Fully completed", "success"), visible=True), get_debug_info(session_id), full_log, enable_btn, enable_btn, enable_btn, enable_btnelse:progress(1.0, desc="DAG 生成失败")yield gr.update(value=create_progress_html(80, "❌ DAG generation failed", "error"), visible=True), get_debug_info(session_id), full_log, disable_btn, disable_btn, disable_btn, disable_btnexcept Exception as e:progress(1.0, desc="发生异常")error_log = full_log + f"\n[Global Exception]:\n{str(e)}"yield gr.update(value=create_progress_html(0, "❌ Execution Exception", "error"), visible=True), get_debug_info(session_id), error_log, disable_btn, disable_btn, disable_btn, disable_btndef run_final_generation(task_type, session_id, api_key, api_base_url, progress=gr.Progress()):papers_dir, output_dir, zip_path = get_user_dirs(session_id)if not os.path.exists(output_dir):yield gr.update(value=create_progress_html(0, "❌ Please run parsing first", "error"), visible=True), get_debug_info(session_id), "No output folder found.", gr.update(visible=False)returnscripts_to_run = []4 unmodified linesfull_log = f"🚀 Starting {len(scripts_to_run)} tasks for session {session_id[:8]}...\n"progress(0.1, desc=f"启动 {task_type.upper()} 生成任务...")yield gr.update(value=create_progress_html(10, f"⏳ Starting {task_type.upper()}...", "active"), visible=True), get_debug_info(session_id), full_log, gr.update(visible=False)q = queue.Queue()processes = []21 unmodified linestry:script_name, line = q.get(timeout=0.1)full_log += f"[{script_name}] {line}"yield gr.update(value=create_progress_html(50, f"⏳ Generating {task_type.upper()}...", "active"), visible=True), get_debug_info(session_id), full_log, gr.update(visible=False)except queue.Empty:active_processes = sum(1 for _, p in processes if p.poll() is None)1 unmodified lineif not success:progress(1.0, desc="生成失败")yield gr.update(value=create_progress_html(50, "❌ Tasks failed", "error"), visible=True), get_debug_info(session_id), full_log, gr.update(visible=False)returnfull_log += "\n📦 Zipping output directory...\n"progress(0.9, desc="打包压缩结果...")yield gr.update(value=create_progress_html(90, "⏳ Zipping outputs...", "active"), visible=True), get_debug_info(session_id), full_log, gr.update(visible=False)zip_base_name = zip_path.replace(".zip", "")shutil.make_archive(zip_base_name, 'zip', output_dir)full_log += "✅ All tasks completed successfully.\n"progress(1.0, desc="全部完成!")yield gr.update(value=create_progress_html(100, f"✅ {task_type.upper()} Generated", "success"), visible=True), get_debug_info(session_id), full_log, gr.update(value=zip_path, visible=True)except Exception as e:progress(1.0, desc="发生全局异常")error_log = full_log + f"\n[Global Exception]:\n{str(e)}"yield gr.update(value=create_progress_html(0, "❌ Global exception", "error"), visible=True), get_debug_info(session_id), error_log, gr.update(visible=False)# ==========================================# --- 🚀 UI Configuration & Advanced CSS ---138 unmodified linesmargin-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;87 unmodified linespdf_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", interactive=False)# 默认隐藏进度条parse_progress = gr.HTML(visible=False)# 3. Asset Generationwith gr.Group(elem_classes="gradio-group"):4 unmodified linesgen_pr_btn = gr.Button("📰 Gen PR", elem_classes="action-btn", interactive=False)gen_all_btn = gr.Button("✨ Generate All Assets (ALL)", elem_classes="primary-action-btn", interactive=False)# 默认隐藏进度条gen_progress = gr.HTML(visible=False)with gr.Column(scale=1):# 4. Results & Downloadswith gr.Group(elem_classes="gradio-group"):gr.Markdown("### 📦 Generation Results & Download")download_placeholder = gr.HTML('''<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 160px; border: 2px dashed rgba(192, 132, 252, 0.6); border-radius: 16px; background-color: rgba(250, 245, 255, 0.5); color: #9333EA; text-align: center; transition: all 0.3s ease;">68 unmodified linesrefresh_btn.click(fn=get_debug_info, inputs=[session_id_state], outputs=debug_view)def toggle_empty_placeholder(file_val):return gr.update(visible=(file_val is None))download_file.change(
app.py+28-28