Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374751 unmodified line77787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231249 unmodified lines1341351361371381391401411421431441451466 unmodified lines1531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153161 unmodified line3183193203213223233243253263273283293303313323333343353 unmodified lines3393403413423433443453463473483491 unmodified line35135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739853 unmodified lines45245345445545645745845943 unmodified lines50350450550650750850933 unmodified lines54354454554654754854915 unmodified lines5655665675685695705715725735745755765772 unmodified lines580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705import gradio as grimport osimport yamlimport shutilimport subprocessimport sysimport queueimport threadingfrom 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 pathsBASE_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")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",)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",),):super().__init__(primary_hue=primary_hue,secondary_hue=secondary_hue,neutral_hue=neutral_hue,text_size=text_size,font=font,font_mono=font_mono,)super().set(background_fill_primary="*primary_50",1 unmodified linebody_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()# ==========================================# --- โ๏ธ 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)9 unmodified linescontent = 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}6 unmodified lines"""return htmldef save_api_settings(api_key, api_base_url=None):if not api_key:return "โ Key cannot be empty", get_debug_info(), Falsetry: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_keyif api_base_url:config["api_base_url"] = api_base_urlwith 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(), Trueexcept Exception as e:return f"โ Error: {str(e)}", get_debug_info(), Falsedef save_pdf(file):if file is None: return "โ Please select a PDF first", get_debug_info(), Falsetry: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))shutil.copy(file.name, file_path)# ่ฟๅๆๅๆถๆฏๅ True (่กจ็คบ PDF ๅทฒๅฐฑ็ปช)return f"โ Saved: {os.path.basename(file.name)}", get_debug_info(), Trueexcept Exception as e:return f"โ Error: {str(e)}", get_debug_info(), Falsedef clear_pdf():"""ๆธ ็ฉบ PDF ๅนถ้ๅฎๅ็ปญๆๆๆญฅ้ชค"""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)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_btnreturn "โน๏ธ Workspace is already empty", get_debug_info(), False, disable_btn, disable_btn, disable_btn, disable_btnexcept 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()):no_change = gr.update()disable_btn = gr.update(interactive=False)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_changereturnfull_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"# ๅๅงๅ่ฟๅบฆๆก (10%)progress(0.1, desc="ๅฏๅจ Mineru ่งฃๆ...")yield "โณ Executing Mineru parsing...", get_debug_info(), 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=1)# ็ปดๆๅจ 30%๏ผๆพ็คบ่งฃๆไธญprogress(0.3, desc="Mineru ๆญฃๅจ่งฃๆ PDF...")for line in iter(process_mineru.stdout.readline, ''):full_log += lineyield "โณ Executing Mineru parsing...", get_debug_info(), 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 f"โ Mineru parsing failed (Exit Code: {returncode_mineru})", get_debug_info(), full_log, disable_btn, disable_btn, disable_btn, disable_btnreturncommand_dag = [sys.executable, "gen_dag.py"]full_log += "\n--- DAG Gen Executing ---\n"# Mineru ๅฎๆ๏ผ่ฟๅ ฅ DAG ็ๆ (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_changeprocess_dag = subprocess.Popen(command_dag, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)# ็ปดๆๅจ 80%progress(0.8, desc="ๆๅปบๅพ็ปๆไธญ...")for line in iter(process_dag.stdout.readline, ''):full_log += lineyield "โณ Executing DAG generation...", get_debug_info(), full_log, no_change, no_change, no_change, no_changeprocess_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_btnelse: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_btnexcept 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_btndef 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)returnscripts_to_run = []1 unmodified lineelif 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)returnfull_log = f"๐ Preparing to start {len(scripts_to_run)} tasks...\n"# ๅฏๅจ้ถๆฎต (10%)progress(0.1, desc=f"ๅฏๅจ {task_type.upper()} ็ๆไปปๅก...")yield f"โณ Starting {task_type.upper()} generation...", get_debug_info(), full_log, gr.update(visible=False)q = queue.Queue()processes = []def enqueue_output(out, script_name):for line in iter(out.readline, ''):3 unmodified linestry:for script in scripts_to_run:p = subprocess.Popen([sys.executable, script],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 linet.start()active_processes = len(processes)# ็ๆ้ถๆฎต็ปดๆๅจ (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)except queue.Empty:active_processes = sum(1 for _, p in processes if p.poll() is None)success = Truefor script, p in processes:if p.returncode != 0:success = Falsefull_log += f"\nโ [Error] {script} returned non-zero exit code (Exit Code: {p.returncode})\n"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)returnfull_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)full_log += "โ All tasks and zipping completed successfully.\n"# ๅฎๆ้ถๆฎต (100%)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)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)# ==========================================# --- ๐ UI Configuration & Advanced CSS ---53 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;43 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;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:# ๅฎไนๅ จๅฑ็ถๆๅ้๏ผ็จไบๅฎ็ฐไพ่ต่งฃ้api_saved_state = gr.State(False)pdf_ready_state = gr.State(False)2 unmodified linesgr.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 Configurationwith 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")api_status = gr.Textbox(show_label=False, placeholder="Waiting for API configuration...", lines=1, interactive=False, elem_classes="status-text")# 2. Document Parsingwith 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", interactive=False)parse_status = gr.Textbox(show_label=False, placeholder="Waiting for document upload...", lines=1, interactive=False, elem_classes="status-text")# 3. Asset Generationwith 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)# ================= RIGHT COLUMN: OUTPUTS & LOGS =================with gr.Column(scale=1):# 4. Results & Downloadswith 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_file = gr.File(label="๐ฅ Get Final Zip Archive", interactive=False, visible=False)# 5. Debugging & Terminalwith 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")with gr.Tab("๐ System Snapshot"):refresh_btn = gr.Button("๐ Refresh Directory Tree")debug_view = gr.HTML(value=get_debug_info())# ================= LOGIC BINDINGS =================# [ๆญฅ้ชค 1] ้ ็ฝฎ API# ๆๅๅไธไป ๆดๆฐ UI ๆๆฌ๏ผ่ฟไผๅฐ api_saved_state ่ฎพ็ฝฎไธบ Truekey_btn.click(fn=save_api_settings,inputs=[key_input, api_base_url_input],outputs=[api_status, debug_view, api_saved_state])# [ๆญฅ้ชค 2.1] ไธไผ PDF# ๆๅๅๆดๆฐๆๆฌ๏ผๅนถๅฐ pdf_ready_state ่ฎพ็ฝฎไธบ Truepdf_input.upload(fn=save_pdf, inputs=pdf_input, outputs=[parse_status, debug_view, pdf_ready_state])# [ๆญฅ้ชค 2.2] ๆธ ้ค PDF# ไผ้ๅฎ็ฌฌๅๆญฅ็ๆๆ็ๆๆ้ฎ๏ผๅๆถๅฐ pdf_ready_state ้็ฝฎไธบ Falsepdf_input.clear(fn=clear_pdf,outputs=[parse_status, 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,outputs=[parse_status, 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])refresh_btn.click(fn=get_debug_info, outputs=debug_view)if __name__ == "__main__":demo.launch(debug=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151 unmodified line1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681699 unmodified lines1791801811821831841851861871881891901911926 unmodified lines1992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303311 unmodified line3333343353363373383393403413423433443453463473483 unmodified lines3523533543553563573581 unmodified line36036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140253 unmodified lines45645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649743 unmodified lines54154254354454554654733 unmodified lines58158258358458558615 unmodified lines6026036046056066076086096106116126136146156162 unmodified lines619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744import gradio as grimport osimport 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, sizesimport threadingimport subprocess# ==========================================# --- ๐ ๅผๆญฅๅฎ่ฃ Playwright ๆต่งๅจ ---# ==========================================def setup_playwright():"""ๅจๅๅฐ้้ปๅฎ่ฃ Playwright๏ผ้ฒๆญข้ปๅก Gradio ๅฏๅจๅฏผ่ด HF 500 ่ถ ๆถ"""try:import playwrightprint("โณ [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__))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_pathimport time# ==========================================# --- ๐งน ๅๅพๅๆถ (ๅๅฐๆธ ็่ฟๆ Session) ---# ==========================================# ่ฎพๅฎ Session ่ฟๆๆถ้ด๏ผไพๅฆ๏ผ2 ๅฐๆถ = 7200 ็ง๏ผSESSION_MAX_AGE_SECONDS = 2 * 60 * 60# ่ฎพๅฎๆธ ็ๅจๆง่ก้ด้๏ผไพๅฆ๏ผๆฏ 30 ๅ้ๆซๆไธๆฌก = 1800 ็ง๏ผCLEANUP_INTERVAL_SECONDS = 30 * 60def 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.")# ==========================================# --- ๐จ 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",)class PurpleTheme(Soft):def __init__(self, **kwargs):super().__init__(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 linebody_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_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",button_secondary_text_color="black",button_secondary_background_fill="linear-gradient(90deg, *primary_300, *primary_300)",slider_color="*secondary_500",block_border_width="3px",block_shadow="*shadow_drop_lg",button_primary_shadow="*shadow_drop_lg",)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):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)9 unmodified linescontent = 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(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 htmldef save_api_settings(api_key, api_base_url, session_id):if not api_key: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_urldef 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):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))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: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)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()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_keyif api_base_url: env["GEMINI_API_BASE_URL"] = api_base_urlenv["USER_PAPERS_DIR"] = papers_direnv["USER_OUTPUT_DIR"] = output_dirreturn envdef 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 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 = ""try: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%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=1)# 30%progress(0.3, desc="Mineru ๆญฃๅจ่งฃๆ PDF...")for line in iter(process_mineru.stdout.readline, ''):full_log += line# ==========================================# ๐ ๅ็ซฏ่พๅบ 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_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"]full_log += "\n--- DAG Gen Executing ---\n"# 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=1)# 80%progress(0.8, desc="ๆๅปบๅพ็ปๆไธญ...")for line in iter(process_dag.stdout.readline, ''):full_log += line# ==========================================# ๐ ๅ็ซฏ่พๅบ 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_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)}"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_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 = []1 unmodified lineelif 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"]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 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 linestry:for script in scripts_to_run:p = subprocess.Popen([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 linet.start()active_processes = len(processes)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}"# ==========================================# ๐ ๅ็ซฏ่พๅบ 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 = all(p.returncode == 0 for _, p in processes)if 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)}"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 linesborder-color: rgba(168, 85, 247, 0.3) !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 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;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; }.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 linesgr.Markdown("One-click parsing of academic PDFs, DAG structuring, and multi-modal asset generation.", elem_id="subtitle")with gr.Row():with gr.Column(scale=1):# 1. API Configurationwith 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")api_status = gr.Textbox(show_label=False, interactive=False, elem_classes="status-text")# 2. Document Parsingwith 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", interactive=False)# ้ป่ฎค้่่ฟๅบฆๆกparse_progress = gr.HTML(visible=False)# 3. Asset Generationwith gr.Group(elem_classes="gradio-group"):gr.Markdown("### ๐ฏ 3. Asset Generation")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)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;"><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. Debuggingwith gr.Group(elem_classes="gradio-group"):gr.Markdown("### ๐ ๏ธ Developer Monitoring (Debug Only)")with gr.Tabs():with gr.Tab("๐ Terminal Stream"):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()# ================= 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_htmldemo.load(fn=init_app_for_user, inputs=None, outputs=[session_id_state, debug_view])key_btn.click(fn=save_api_settings,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])pdf_input.upload(fn=save_pdf,inputs=[pdf_input, session_id_state],outputs=[parse_progress, debug_view, pdf_ready_state])pdf_input.clear(fn=clear_pdf,inputs=[session_id_state],outputs=[parse_progress, gen_progress, debug_view, pdf_ready_state, gen_ppt_btn, gen_poster_btn, gen_pr_btn, gen_all_btn])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)parse_btn.click(fn=run_mineru_parsing_and_dag_gen,inputs=[session_id_state, user_api_key_state, user_api_base_state],outputs=[parse_progress, debug_view, cmd_logs, gen_ppt_btn, gen_poster_btn, gen_pr_btn, gen_all_btn])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, 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__":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