Spaces:
Sleeping
Sleeping
Update app.py
Browse files1233456789101112131415161718192021152316171819202122232425262728293031323334353637382526272839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596303197989910010137383940414243444546474810210310410510610752535455565758596061626364651081096768697071721101111121131141151 unmodified line1171181198012012183841228612388899012492931251261279798991281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571091581591601611621151161171631641181651201211661671681699 unmodified lines1791801811371381391401821831841851861871881891901911926 unmodified lines1992002011562022031582042052062072082092102112121601611621631641651661671681691701711721731741751761771781791801811821831841852132142152162171872182191891902202211922222231941952242251971981992002012022032042052062072082092102112122132142152162172182192202212262272282292302242252262272312322292302312332342352362372382392402412422432442452462472482492502512352362522532542552562572412422432442452462472482582592602612502622632522642652662672682692582702712722732622742752762772782792802812822832682842852862872882892742902912762922932942792952962972822982993003012863023033043053063073083092903103112933122953133143152982993163173183193033043203213223233063073083093103113123133243253263273283293303311 unmodified line3333343353213223233243253363273373383393403293413423433443453463473483 unmodified lines3523533543423433443453463553563573581 unmodified line36036136236336435535636536636736836136937037137237337437537636536636736836937737837938037338138238338437737838538038138238338638738538838939038739139238939339439539639339439539739839940040140253 unmodified lines45645745845545645946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649743 unmodified lines54154254350654454554654733 unmodified lines58158258354658458558615 unmodified lines6026036045686056066076086095746106116126136146156162 unmodified lines619620621583622585623624625626590627628629593594595596597630631632633634601602603604605606607608635636637611612613638639640641642643618619644621645646647625626648649650651652629653631654655656635636657658659660661662663664665666667668669640670671672673674645646647648675676677651652653678679680681682683684685686687688655656657658689690661662691692693694665666667695696697698699700669670701702703673704705706676707708709710711712683684713714715687716717718690691692693694695696697698699700719720721722723724725726727728702729730731732733734735736737738739740705741742743744import gradio as grimport osimport yamlimport shutilimport subprocessimport sysimport queueimport threadingimport uuidfrom datetime import datetimefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom typing import Iterablefrom gradio.themes import Softfrom gradio.themes.utils import colors, fonts, sizes
# 自动安装 Playwright 浏览器(如果不存在)try: import playwright # 检查是否已经安装了浏览器,没有则下载 subprocess.run(["playwright", "install", "chromium"], check=True)except Exception as e: print(f"Playwright setup failed: {e}")
# Initialize environment pathsimport threadingimport subprocess# ==========================================# --- 🌐 异步安装 Playwright 浏览器 ---# ==========================================def setup_playwright(): """在后台静默安装 Playwright,防止阻塞 Gradio 启动导致 HF 500 超时""" try: import playwright print("⏳ [System] Downloading Playwright Chromium in background...") # 增加 --with-deps 尝试安装系统级依赖 (虽然在非 root 容器可能失效,但有备无患) subprocess.run(["playwright", "install", "chromium"], check=True) print("✅ [System] Playwright browsers ready.") except Exception as e: print(f"❌ [System] Playwright setup failed: {e}")
# 这一步非常关键:启动一个后台守护线程去下载,主进程直接往下走!threading.Thread(target=setup_playwright, daemon=True).start()
# ==========================================# --- 📁 全局目录配置 (修改为 Session 基础目录) ---# ==========================================BASE_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")ZIP_OUTPUT_PATH = os.path.join(BASE_DIR, "mineru_results.zip")SESSIONS_BASE_DIR = os.path.join(BASE_DIR, "user_sessions")os.makedirs(SESSIONS_BASE_DIR, exist_ok=True)
def get_user_dirs(session_id): """根据 Session ID 生成用户专属的隔离目录""" user_base = os.path.join(SESSIONS_BASE_DIR, session_id) papers_dir = os.path.join(user_base, "papers") output_dir = os.path.join(user_base, "mineru_outputs") zip_path = os.path.join(user_base, "mineru_results.zip") os.makedirs(papers_dir, exist_ok=True) os.makedirs(output_dir, exist_ok=True) return papers_dir, output_dir, zip_path
import time
# ==========================================# --- 🧹 垃圾回收 (后台清理过期 Session) ---# ==========================================# 设定 Session 过期时间(例如:2 小时 = 7200 秒)SESSION_MAX_AGE_SECONDS = 2 * 60 * 60# 设定清理器执行间隔(例如:每 30 分钟扫描一次 = 1800 秒)CLEANUP_INTERVAL_SECONDS = 30 * 60
def cleanup_expired_sessions(): """后台运行的垃圾回收任务""" while True: try: if os.path.exists(SESSIONS_BASE_DIR): current_time = time.time() for session_folder in os.listdir(SESSIONS_BASE_DIR): folder_path = os.path.join(SESSIONS_BASE_DIR, session_folder) # 确保只处理目录 if os.path.isdir(folder_path): # 获取文件夹的最后修改时间 folder_mtime = os.path.getmtime(folder_path) # 判断是否超过了最大存活时间 if (current_time - folder_mtime) > SESSION_MAX_AGE_SECONDS: try: shutil.rmtree(folder_path) print(f"🧹 [Garbage Collector] Deleted expired session: {session_folder}") except Exception as e: print(f"⚠️ [Garbage Collector] Failed to delete {session_folder}: {e}") except Exception as e: print(f"⚠️ [Garbage Collector] Error during cleanup scan: {e}") # 休眠到下一次扫描时间 time.sleep(CLEANUP_INTERVAL_SECONDS)
def start_garbage_collector(): """启动后台守护线程""" gc_thread = threading.Thread(target=cleanup_expired_sessions, daemon=True) gc_thread.start() print("🚀 [Garbage Collector] Background cleanup service started.")
os.makedirs(PAPERS_DIR, exist_ok=True)os.makedirs(OUTPUT_DIR, exist_ok=True)
# ==========================================# --- 🎨 Custom Purple Theme Definition ---# ==========================================colors.purple = colors.Color( name="purple", c50="#FAF5FF", c100="#F3E8FF", c200="#E9D5FF", c300="#DAB2FF", c400="#C084FC", c500="#A855F7", c600="#9333EA", c700="#7E22CE", c800="#6B21A8", c900="#581C87", c950="#3B0764", name="purple", c50="#FAF5FF", c100="#F3E8FF", c200="#E9D5FF", c300="#DAB2FF", c400="#C084FC", c500="#A855F7", c600="#9333EA", c700="#7E22CE", c800="#6B21A8", c900="#581C87", c950="#3B0764",)
class PurpleTheme(Soft): def __init__( self, *, primary_hue: colors.Color | str = colors.gray, secondary_hue: colors.Color | str = colors.purple, neutral_hue: colors.Color | str = colors.slate, text_size: sizes.Size | str = sizes.text_lg, font: fonts.Font | str | Iterable[fonts.Font | str] = ( fonts.GoogleFont("Outfit"), "Arial", "sans-serif", ), font_mono: fonts.Font | str | Iterable[fonts.Font | str] = ( fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace", ), ): def __init__(self, **kwargs): super().__init__( primary_hue=primary_hue, secondary_hue=secondary_hue, neutral_hue=neutral_hue, text_size=text_size, font=font, font_mono=font_mono, primary_hue=colors.gray, secondary_hue=colors.purple, neutral_hue=colors.slate, font=(fonts.GoogleFont("Outfit"), "Arial", "sans-serif"), font_mono=(fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace"), ) super().set( background_fill_primary="*primary_50",1 unmodified line body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)", body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)", button_primary_text_color="white", button_primary_text_color_hover="white", button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)", button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)", button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)", button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)", button_secondary_text_color="black", button_secondary_text_color_hover="white", button_secondary_background_fill="linear-gradient(90deg, *primary_300, *primary_300)", button_secondary_background_fill_hover="linear-gradient(90deg, *primary_400, *primary_400)", button_secondary_background_fill_dark="linear-gradient(90deg, *primary_500, *primary_600)", button_secondary_background_fill_hover_dark="linear-gradient(90deg, *primary_500, *primary_500)", slider_color="*secondary_500", slider_color_dark="*secondary_600", block_title_text_weight="600", block_border_width="3px", block_shadow="*shadow_drop_lg", button_primary_shadow="*shadow_drop_lg", button_large_padding="11px", color_accent_soft="*primary_100", block_label_background_fill="*primary_200", )
purple_theme = PurpleTheme()
# ==========================================# --- 🚀 HTML Progress Bar Components ---# ==========================================def empty_progress_html(text="Waiting for action..."): return f""" <div class="custom-progress-container" style="background-color: transparent; border: 2px dashed rgba(168, 85, 247, 0.4);"> <div class="custom-progress-text" style="color: #A855F7;">{text}</div> </div> """
def create_progress_html(percent, text, status="active"): """ status: "active" (紫色滚动条纹), "success" (绿色), "error" (红色) """ return f""" <div class="custom-progress-container"> <div class="custom-progress-bar {status}" style="width: {percent}%;"></div> <div class="custom-progress-text">{text} ({percent}%)</div> </div> """
# ==========================================# --- ⚙️ 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: try: items = sorted(os.listdir(current_path)) except Exception: return "" return "" if not items: return "" if not items: return "" for item in items: item_path = os.path.join(current_path, item)9 unmodified lines content = 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)def get_debug_info(session_id): papers_dir, output_dir, _ = get_user_dirs(session_id) 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;"> <div style="color: #888; margin-bottom: 8px;">Session ID: {session_id[:8]}...</div> <details open style="margin-bottom: 12px; cursor: pointer;"> <summary style="outline: none; font-size: 15px; color: #A855F7;">📁 <b>papers/</b></summary> {papers_tree}6 unmodified lines """ return html
def save_api_settings(api_key, api_base_url=None):def save_api_settings(api_key, api_base_url, session_id): if not api_key: return "❌ Key cannot be empty", get_debug_info(), False return "❌ Key cannot be empty", get_debug_info(session_id), False, "", "" success_msg = "✅ Key saved securely in session memory" if api_base_url: success_msg += ", Base URL updated" return success_msg, get_debug_info(session_id), True, api_key, api_base_url
def save_pdf(file, session_id): if file is None: return gr.update(visible=False), get_debug_info(session_id), False try: config = {} if os.path.exists(CONFIG_PATH): with open(CONFIG_PATH, "r", encoding="utf-8") as f: config = yaml.safe_load(f) or {} config.setdefault("api_keys", {})["gemini_api_key"] = api_key if api_base_url: config["api_base_url"] = api_base_url with open(CONFIG_PATH, "w", encoding="utf-8") as f: yaml.dump(config, f, allow_unicode=True) success_msg = "✅ Key saved" if api_base_url: success_msg += ", Base URL updated" # 返回成功消息和 True (表示 API 已就绪) return success_msg, get_debug_info(), True except Exception as e: return f"❌ Error: {str(e)}", get_debug_info(), False
def save_pdf(file): if file is None: return "❌ Please select a PDF first", get_debug_info(), False try: 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) papers_dir, _, _ = get_user_dirs(session_id) 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) file_path = os.path.join(PAPERS_DIR, os.path.basename(file.name)) file_path = os.path.join(papers_dir, os.path.basename(file.name)) shutil.copy(file.name, file_path) # 返回成功消息和 True (表示 PDF 已就绪) return f"✅ Saved: {os.path.basename(file.name)}", get_debug_info(), True return gr.update(value=create_progress_html(100, f"✅ PDF Uploaded: {os.path.basename(file.name)}", "success"), visible=True), get_debug_info(session_id), True except Exception as e: return f"❌ Error: {str(e)}", get_debug_info(), False return gr.update(value=create_progress_html(0, f"❌ Error: {str(e)}", "error"), visible=True), get_debug_info(session_id), False
def clear_pdf(): """清空 PDF 并锁定后续所有步骤"""def clear_pdf(session_id): try: deleted_files = [] deleted_dirs = [] pdf_names = [f for f in os.listdir(PAPERS_DIR) if f.endswith('.pdf')] 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 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(" ", "_") for item in os.listdir(OUTPUT_DIR): 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) if os.path.exists(ZIP_OUTPUT_PATH): os.remove(ZIP_OUTPUT_PATH) user_base = os.path.join(SESSIONS_BASE_DIR, session_id) if os.path.exists(user_base): shutil.rmtree(user_base) disable_btn = gr.update(interactive=False) # 返回:状态文本, debug视窗, pdf_ready=False, 以及锁定4个生成按钮 if deleted_files or deleted_dirs: return f"����️ Workspace cleared", get_debug_info(), False, disable_btn, disable_btn, disable_btn, disable_btn return "ℹ️ Workspace is already empty", get_debug_info(), False, disable_btn, disable_btn, disable_btn, disable_btn return gr.update(visible=False), gr.update(visible=False), get_debug_info(session_id), False, disable_btn, disable_btn, disable_btn, disable_btn except Exception as e: return f"❌ Error deleting file: {str(e)}", get_debug_info(), False, gr.update(), gr.update(), gr.update(), gr.update()
def run_mineru_parsing_and_dag_gen(progress=gr.Progress()): 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() env["MINERU_FORMULA_ENABLE"] = "false" env["MINERU_TABLE_ENABLE"] = "false" env["MINERU_DEVICE_MODE"] = "cpu" env["MINERU_VIRTUAL_VRAM_SIZE"] = "8" if api_key: env["GEMINI_API_KEY"] = api_key if api_base_url: env["GEMINI_API_BASE_URL"] = api_base_url env["USER_PAPERS_DIR"] = papers_dir env["USER_OUTPUT_DIR"] = output_dir return env
def run_mineru_parsing_and_dag_gen(session_id, api_key, api_base_url, progress=gr.Progress()): no_change = gr.update() disable_btn = gr.update(interactive=False) papers_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 "❌ No PDF file found", get_debug_info(), "No execution logs.", no_change, no_change, no_change, no_change 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_change return
full_log = "" try: env = os.environ.copy() env["MINERU_FORMULA_ENABLE"] = "false" env["MINERU_TABLE_ENABLE"] = "false" env["MINERU_DEVICE_MODE"] = "cpu" env["MINERU_VIRTUAL_VRAM_SIZE"] = "8"
command_mineru = ["mineru", "-p", PAPERS_DIR, "-o", OUTPUT_DIR] full_log += "--- Mineru Executing ---\n" env = build_user_env(api_key, api_base_url, papers_dir, output_dir) command_mineru = ["mineru", "-p", papers_dir, "-o", output_dir] full_log += f"--- Mineru Executing (Session: {session_id[:8]}) ---\n" # 初始化进度条 (10%) # 10% progress(0.1, desc="启动 Mineru 解析...") yield "⏳ Executing Mineru parsing...", get_debug_info(), full_log, no_change, no_change, no_change, no_change 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_change
process_mineru = subprocess.Popen( command_mineru, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1 ) # 维持在 30%,显示解析中 # 30% progress(0.3, desc="Mineru 正在解析 PDF...") for line in iter(process_mineru.stdout.readline, ''): full_log += line yield "⏳ Executing Mineru parsing...", get_debug_info(), full_log, no_change, no_change, no_change, no_change # ========================================== # 🔔 双端输出 1:Mineru 阶段 # ========================================== print(f"[Mineru | {session_id[:6]}] {line}", end="", flush=True) yield 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_change process_mineru.stdout.close() returncode_mineru = process_mineru.wait()
if returncode_mineru != 0: progress(1.0, desc="Mineru 解析失败") yield f"❌ Mineru parsing failed (Exit Code: {returncode_mineru})", get_debug_info(), full_log, disable_btn, disable_btn, disable_btn, disable_btn 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_btn return
command_dag = [sys.executable, "gen_dag.py"] full_log += "\n--- DAG Gen Executing ---\n" # Mineru 完成,进入 DAG 生成 (60%) # 60% progress(0.6, desc="执行 DAG 生成...") yield "⏳ Mineru parsing complete, executing DAG generation...", get_debug_info(), full_log, no_change, no_change, no_change, no_change 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_change process_dag = subprocess.Popen( command_dag, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1 command_dag, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1 ) # 维持在 80% # 80% progress(0.8, desc="构建图结构中...") for line in iter(process_dag.stdout.readline, ''): full_log += line yield "⏳ Executing DAG generation...", get_debug_info(), full_log, no_change, no_change, no_change, no_change # ========================================== # 🔔 双端输出 2:DAG 生成阶段 # ========================================== print(f"[DAG | {session_id[:6]}] {line}", end="", flush=True) yield 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_change process_dag.stdout.close() returncode_dag = process_dag.wait() # 解析完全成功 (100%) if returncode_dag == 0: progress(1.0, desc="解析与构建完成!") status = "✅ PDF parsing & DAG generation fully completed" enable_btn = gr.update(interactive=True) yield status, get_debug_info(), full_log, enable_btn, enable_btn, enable_btn, enable_btn 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_btn else: progress(1.0, desc="DAG 生成失败") status = f"❌ DAG generation failed (Exit Code: {returncode_dag})" yield status, get_debug_info(), full_log, disable_btn, disable_btn, disable_btn, disable_btn 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_btn
except Exception as e: progress(1.0, desc="发生异常") error_log = full_log + f"\n[Global Exception] Exception occurred:\n{str(e)}" yield "❌ Execution Exception", get_debug_info(), error_log, disable_btn, disable_btn, disable_btn, disable_btn error_log = full_log + f"\n[Global Exception]:\n{str(e)}" print(f"[Exception | {session_id[:6]}] {str(e)}", flush=True) 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_btn
def run_final_generation(task_type="all", progress=gr.Progress()): """ 使用队列和多线程实时获取子进程的流式输出,并通过 yield 推送到前端界面。 引入 progress 参数更新进度条。 """ if not os.path.exists(OUTPUT_DIR): yield "❌ Please run the parsing step first", get_debug_info(), "No output folder found.", gr.update(visible=False)def 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) return
scripts_to_run = []1 unmodified line elif task_type == "poster": scripts_to_run = ["gen_poster.py"] elif task_type == "pr": scripts_to_run = ["gen_pr.py"] elif task_type == "all": scripts_to_run = ["gen_ppt.py", "gen_poster.py", "gen_pr.py"] else: yield "❌ Unknown task type", get_debug_info(), "Invalid task_type.", gr.update(visible=False) return
full_log = f"🚀 Preparing to start {len(scripts_to_run)} tasks...\n" # 启动阶段 (10%) full_log = f"🚀 Starting {len(scripts_to_run)} tasks for session {session_id[:8]}...\n" print(f"[GEN Start | {session_id[:6]}] Starting {task_type.upper()}", flush=True) progress(0.1, desc=f"启动 {task_type.upper()} 生成任务...") yield f"⏳ Starting {task_type.upper()} generation...", get_debug_info(), full_log, gr.update(visible=False) 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 = [] env = build_user_env(api_key, api_base_url, papers_dir, output_dir) def enqueue_output(out, script_name): for line in iter(out.readline, ''):3 unmodified lines try: for script in scripts_to_run: p = subprocess.Popen( [sys.executable, script], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1 [sys.executable, script], env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1 ) processes.append((script, p)) t = threading.Thread(target=enqueue_output, args=(p.stdout, script))1 unmodified line t.start()
active_processes = len(processes) progress(0.5, desc=f"正在并行生成 {task_type.upper()}...") # 生成阶段维持在 (50%) progress(0.5, desc=f"正在并行生成 {task_type.upper()} 资产...") while active_processes > 0 or not q.empty(): try: script_name, line = q.get(timeout=0.1) full_log += f"[{script_name}] {line}" yield f"⏳ Generating {task_type.upper()}...", get_debug_info(), full_log, gr.update(visible=False) # ========================================== # 🔔 双端输出 3:生成阶段 # ========================================== print(f"[{script_name.upper()} | {session_id[:6]}] {line}", end="", flush=True) 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)
success = True for script, p in processes: if p.returncode != 0: success = False full_log += f"\n❌ [Error] {script} returned non-zero exit code (Exit Code: {p.returncode})\n" success = all(p.returncode == 0 for _, p in processes)
if not success: progress(1.0, desc="生成失败") yield f"❌ {task_type.upper()} contains failed tasks, please check logs", get_debug_info(), full_log, gr.update(visible=False) yield gr.update(value=create_progress_html(50, "❌ Tasks failed", "error"), visible=True), get_debug_info(session_id), full_log, gr.update(visible=False) return
full_log += "\n📦 Zipping output directory...\n" # 压缩阶段 (90%) progress(0.9, desc="打包压缩结果...") yield f"⏳ Zipping outputs...", get_debug_info(), full_log, gr.update(visible=False) zip_base_name = ZIP_OUTPUT_PATH.replace(".zip", "") shutil.make_archive(zip_base_name, 'zip', OUTPUT_DIR) yield gr.update(value=create_progress_html(90, "⏳ Zipping outputs...", "active"), visible=True), get_debug_info(session_id), full_log, gr.update(visible=False) full_log += "✅ All tasks and zipping completed successfully.\n" zip_base_name = zip_path.replace(".zip", "") shutil.make_archive(zip_base_name, 'zip', output_dir) # 完成阶段 (100%) full_log += "✅ All tasks completed successfully.\n" progress(1.0, desc="全部完成!") yield f"✅ {task_type.upper()} generated and zipped successfully", get_debug_info(), full_log, gr.update(value=ZIP_OUTPUT_PATH, visible=True) 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] Exception occurred:\n{str(e)}" yield "❌ Global exception during final generation", get_debug_info(), error_log, gr.update(visible=False)
error_log = full_log + f"\n[Global Exception]:\n{str(e)}" print(f"[Exception | {session_id[:6]}] {str(e)}", flush=True) 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 ---53 unmodified lines border-color: rgba(168, 85, 247, 0.3) !important; }
.gradio-group > div, .gradio-group > .form { border-radius: 12px !important; }/* ================= 进度条自定义 CSS ================= */@keyframes progress-bar-stripes { from { background-position: 1rem 0; } to { background-position: 0 0; }}.custom-progress-container { width: 100%; background-color: rgba(233, 213, 255, 0.3); border-radius: 12px; overflow: hidden; position: relative; height: 40px; border: 1px solid rgba(168, 85, 247, 0.3); box-shadow: inset 0 2px 4px rgba(0,0,0,0.05);}.custom-progress-bar { height: 100%; border-radius: 12px; transition: width 0.4s ease;}.custom-progress-bar.active { background-color: #A855F7; background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); background-size: 1rem 1rem; animation: progress-bar-stripes 1s linear infinite; box-shadow: 0 0 10px rgba(168, 85, 247, 0.5);}.custom-progress-bar.success { background-image: none; background-color: #10B981; box-shadow: 0 0 10px rgba(16, 185, 129, 0.5);}.custom-progress-bar.error { background-image: none; background-color: #EF4444; box-shadow: 0 0 10px rgba(239, 68, 68, 0.5);}.custom-progress-text { position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; font-weight: 600; color: #581C87; font-size: 14px; text-shadow: 0 0 4px rgba(255,255,255,0.8);}.dark .custom-progress-text { color: #E9D5FF; text-shadow: 0 0 4px rgba(0,0,0,0.8); }
#pdf-upload-box { border: 2px dashed rgba(192, 132, 252, 0.6) !important;43 unmodified lines margin-right: auto !important; margin-top: 10px !important; margin-bottom: 10px !important; display: block !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; 33 unmodified lines}.action-btn:active { transform: translateY(2px) scale(0.98) !important; box-shadow: 0 2px 10px rgba(147, 51, 234, 0.2) !important; }
/* ======== CSS FOR DISABLED BUTTONS ======== */.primary-action-btn:disabled, .action-btn:disabled { background: #e5e7eb !important; color: #9ca3af !important;15 unmodified lines::-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 { transition: color 0.2s ease; }details > summary:hover { color: #E9D5FF !important; }"""
with gr.Blocks(theme=purple_theme, css=custom_css) as demo: # 定义全局状态变量,用于实现依赖解锁 session_id_state = gr.State("") user_api_key_state = gr.State("") user_api_base_state = gr.State("") api_saved_state = gr.State(False) pdf_ready_state = gr.State(False)
2 unmodified lines gr.Markdown("One-click parsing of academic PDFs, DAG structuring, and multi-modal asset generation.", elem_id="subtitle") with gr.Row(): # ================= LEFT COLUMN: SETTINGS & ACTIONS ================= with gr.Column(scale=1): # 1. API Configuration with 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) 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") api_status = gr.Textbox( show_label=False, placeholder="Waiting for API configuration...", lines=1, interactive=False, elem_classes="status-text" ) api_status = gr.Textbox(show_label=False, interactive=False, elem_classes="status-text")
# 2. Document Parsing with 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" ) # 默认锁定 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", interactive=False) parse_status = gr.Textbox( show_label=False, placeholder="Waiting for document upload...", lines=1, interactive=False, elem_classes="status-text" ) # 默认隐藏进度条 parse_progress = gr.HTML(visible=False)
# 3. Asset Generation with gr.Group(elem_classes="gradio-group"): gr.Markdown("### 🎯 3. Asset Generation") gr.Markdown("Generate final formats based on DAG structure:") with gr.Row(elem_classes="action-row"): # 默认锁定 gen_ppt_btn = gr.Button("📊 Gen PPT", elem_classes="action-btn", interactive=False) gen_poster_btn = gr.Button("🖼️ Gen Poster", elem_classes="action-btn", interactive=False) gen_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)
# ================= RIGHT COLUMN: OUTPUTS & LOGS ================= with gr.Column(scale=1): # 4. Results & Downloads with gr.Group(elem_classes="gradio-group"): gr.Markdown("### 📦 Generation Results & Download") gen_status = gr.Textbox( show_label=False, placeholder="No generation task currently...", lines=2, interactive=False, elem_classes="status-text" 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;"> <span style="font-size: 32px; margin-bottom: 8px;">📦</span> <span style="font-weight: 600; font-size: 16px; margin-bottom: 4px;">Awaiting Generation</span> <span style="font-size: 13px; color: #A855F7; opacity: 0.8;">Generated assets will appear here as a downloadable ZIP archive.</span> </div> ''' ) download_file = gr.File(label="📥 Get Final Zip Archive", interactive=False, visible=False)
# 5. Debugging & Terminal # 5. Debugging with gr.Group(elem_classes="gradio-group"): gr.Markdown("### 🛠️ Developer Monitoring (Debug Only)") with gr.Tabs(): with gr.Tab("📜 Terminal Stream"): cmd_logs = gr.Textbox( label="Stdout / Stderr", placeholder="Waiting for task to start...", lines=14, interactive=False, elem_classes="log-box" ) cmd_logs = gr.Textbox(show_label=False, lines=14, interactive=False, elem_classes="log-box") with gr.Tab("🔍 System Snapshot"): refresh_btn = gr.Button("🔄 Refresh Directory Tree") debug_view = gr.HTML( value=get_debug_info() ) debug_view = gr.HTML()
# ================= LOGIC BINDINGS =================
def init_app_for_user(): new_session_id = str(uuid.uuid4()) debug_html = get_debug_info(new_session_id) return new_session_id, debug_html
demo.load(fn=init_app_for_user, inputs=None, outputs=[session_id_state, debug_view])
# ================= LOGIC BINDINGS ================= # [步骤 1] 配置 API # 成功后不仅更新 UI 文本,还会将 api_saved_state 设置为 True key_btn.click( fn=save_api_settings, inputs=[key_input, api_base_url_input], outputs=[api_status, debug_view, api_saved_state] inputs=[key_input, api_base_url_input, session_id_state], outputs=[api_status, debug_view, api_saved_state, user_api_key_state, user_api_base_state] ) # [步骤 2.1] 上传 PDF # 成功后更新文本,并将 pdf_ready_state 设置为 True pdf_input.upload(fn=save_pdf, inputs=pdf_input, outputs=[parse_status, debug_view, pdf_ready_state]) pdf_input.upload( fn=save_pdf, inputs=[pdf_input, session_id_state], outputs=[parse_progress, debug_view, pdf_ready_state] ) # [步骤 2.2] 清除 PDF # 会锁定第四步的所有生成按钮,同时将 pdf_ready_state 重置为 False pdf_input.clear( fn=clear_pdf, inputs=[session_id_state], outputs=[parse_status, debug_view, pdf_ready_state, gen_ppt_btn, gen_poster_btn, gen_pr_btn, gen_all_btn] outputs=[parse_progress, gen_progress, debug_view, pdf_ready_state, gen_ppt_btn, gen_poster_btn, gen_pr_btn, gen_all_btn] ) # [依赖检查] 当 api 状态或 pdf 状态发生变化时,检查是否解锁"开始解析"按钮 def check_parse_btn_ready(api_ready, pdf_ready): return gr.update(interactive=(api_ready and pdf_ready)) api_saved_state.change(fn=check_parse_btn_ready, inputs=[api_saved_state, pdf_ready_state], outputs=parse_btn) pdf_ready_state.change(fn=check_parse_btn_ready, inputs=[api_saved_state, pdf_ready_state], outputs=parse_btn)
# [步骤 2.3] 执行解析 # 如果完全成功,函数最后的一个 yield 会连带输出 interactive=True 给这4个生成按钮 parse_btn.click( fn=run_mineru_parsing_and_dag_gen, inputs=[session_id_state, user_api_key_state, user_api_base_state], outputs=[parse_status, debug_view, cmd_logs, gen_ppt_btn, gen_poster_btn, gen_pr_btn, gen_all_btn] outputs=[parse_progress, debug_view, cmd_logs, gen_ppt_btn, gen_poster_btn, gen_pr_btn, gen_all_btn] )
# [步骤 3] 资产生成 # 将 progress 对象注入到包装函数中 def trigger_gen_ppt(progress=gr.Progress()): yield from run_final_generation("ppt", progress) def trigger_gen_poster(progress=gr.Progress()): yield from run_final_generation("poster", progress) def trigger_gen_pr(progress=gr.Progress()): yield from run_final_generation("pr", progress) def trigger_gen_all(progress=gr.Progress()): yield from run_final_generation("all", progress)
gen_ppt_btn.click(fn=trigger_gen_ppt, outputs=[gen_status, debug_view, cmd_logs, download_file]) gen_poster_btn.click(fn=trigger_gen_poster, outputs=[gen_status, debug_view, cmd_logs, download_file]) gen_pr_btn.click(fn=trigger_gen_pr, outputs=[gen_status, debug_view, cmd_logs, download_file]) gen_all_btn.click(fn=trigger_gen_all, outputs=[gen_status, debug_view, cmd_logs, download_file]) def trigger_gen_ppt(sid, ak, ab, progress=gr.Progress()): yield from run_final_generation("ppt", sid, ak, ab, progress) def trigger_gen_poster(sid, ak, ab, progress=gr.Progress()): yield from run_final_generation("poster", sid, ak, ab, progress) def trigger_gen_pr(sid, ak, ab, progress=gr.Progress()): yield from run_final_generation("pr", sid, ak, ab, progress) def trigger_gen_all(sid, ak, ab, progress=gr.Progress()): yield from run_final_generation("all", sid, ak, ab, progress)
gen_ppt_btn.click(fn=trigger_gen_ppt, inputs=[session_id_state, user_api_key_state, user_api_base_state], outputs=[gen_progress, debug_view, cmd_logs, download_file]) gen_poster_btn.click(fn=trigger_gen_poster, inputs=[session_id_state, user_api_key_state, user_api_base_state], outputs=[gen_progress, debug_view, cmd_logs, download_file]) gen_pr_btn.click(fn=trigger_gen_pr, inputs=[session_id_state, user_api_key_state, user_api_base_state], outputs=[gen_progress, debug_view, cmd_logs, download_file]) gen_all_btn.click(fn=trigger_gen_all, inputs=[session_id_state, user_api_key_state, user_api_base_state], outputs=[gen_progress, debug_view, cmd_logs, download_file]) refresh_btn.click(fn=get_debug_info, outputs=debug_view) refresh_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( fn=toggle_empty_placeholder, inputs=[download_file], outputs=[download_placeholder] )
if __name__ == "__main__": demo.launch(debug=True) start_garbage_collector() # 并发放宽至 5 # demo.queue(default_concurrency_limit=5).launch() demo.launch(server_name="0.0.0.0", server_port=7860)app.py+314-275