"""Gradio UI for the multi-agent paper review system. The application keeps API keys in per-request temporary configuration files and never writes them to the repository configuration. The former Streamlit UI is kept in ``streamlit_app.py`` for local backwards compatibility. """ from __future__ import annotations import asyncio import copy import html import json import os import tempfile from pathlib import Path from typing import Iterable import gradio as gr import requests try: import spaces gpu_task = spaces.GPU(duration=120) except (ImportError, RuntimeError): def gpu_task(function): return function from core.orchestrator import PaperReviewOrchestrator from llm.interface import LLMInterface from models.paper import Paper from models.reviewer import ReviewerAgent from services import config_service from services.file_service import apply_text_filters, extract_text_from_file APP_TITLE = "多代理人論文審查系統" DEFAULT_REVIEWERS = [ ["Dr. Alan", "電腦視覺與深度學習", "輕量化神經網路架構", "嚴格,要求完整數據驗證"], ["Prof. Lin", "嵌入式與邊緣運算", "微控制器整合與邊緣 AI", "務實且具建設性,重視落地性"], ] class UploadedFileAdapter: """Give a Gradio filepath the small file API expected by file_service.""" def __init__(self, path: str): self.path = path self.name = Path(path).name self._handle = open(path, "rb") def seek(self, offset: int): return self._handle.seek(offset) def read(self, size: int = -1): return self._handle.read(size) def getvalue(self): position = self._handle.tell() self._handle.seek(0) data = self._handle.read() self._handle.seek(position) return data def close(self): self._handle.close() def _extract_path(path: str | None) -> str: if not path: return "" adapter = UploadedFileAdapter(path) try: return extract_text_from_file(adapter) finally: adapter.close() def parse_paper_file(path: str | None): if not path: return "", "尚未上傳檔案。" try: content = _extract_path(path) return content, f"✅ 已解析 **{Path(path).name}**,共 {len(content):,} 個字元。" except Exception as exc: return "", f"❌ {exc}" def parse_reference_files(paths: Iterable[str] | None): paths = list(paths or []) if not paths: return "", "未加入參考文獻。" blocks, errors = [], [] for path in paths: try: blocks.append(f"【{Path(path).name}】\n{_extract_path(path)}") except Exception as exc: errors.append(f"{Path(path).name}: {exc}") status = f"✅ 已解析 {len(blocks)} 份參考文獻。" if errors: status += "\n\n⚠️ " + ";".join(errors) return "\n\n".join(blocks), status def _build_config( provider: str, api_key: str, model_name: str, api_url: str, detector_mode: str, detector_key: str, detector_url: str, enable_rag: bool, enable_web: bool, enable_references: bool, tavily_key: str, ) -> dict: config = copy.deepcopy(config_service.DEFAULT_CONFIG) provider_code = { "Gemini": "gemini", "OpenAI 相容 API": "openai", "Ollama 遠端服務": "ollama", "模擬模式": "mock", }[provider] if provider_code == "ollama": config["llm_mode"] = "ollama" else: config["llm_mode"] = "mock" if provider_code == "mock" else "cloud" config["cloud"].update({ "provider": provider_code, "api_key": (api_key or "").strip(), "model_name": (model_name or "").strip(), "api_url": (api_url or "").strip(), }) config["ollama"].update({ "host": (api_url or "").strip().rstrip("/"), "base_url": (api_url or "").strip().rstrip("/"), "model_name": (model_name or "").strip(), "api_key": (api_key or "").strip(), "max_tokens": 4096, "keep_alive": "30m", "timeout": 300, }) config["ai_detector"].update({ # Cloud mode without a key intentionally falls back to the deterministic # mock report without importing/downloading the Hugging Face model. "mode": {"ZeroGPU 模型": "hf_model", "GPTZero API": "cloud", "模擬偵測": "cloud"}[detector_mode], "api_key": (detector_key or "").strip(), "api_url": (detector_url or "").strip(), "force_cpu": False, }) config["knowledge_update"].update({ "enable_rag": bool(enable_rag), "enable_web_search": bool(enable_web), "enable_reference_upload": bool(enable_references), "tavily_api_key": (tavily_key or "").strip(), }) return config def _temporary_config(config: dict) -> str: return config_service.write_temp_user_config(config) def _reviewers_from_table(rows) -> list[ReviewerAgent]: reviewers = [] # Gradio 6 returns a pandas.DataFrame. Evaluating a DataFrame as a bool # (``rows or []``) raises: "The truth value of a DataFrame is ambiguous". if rows is None: normalized_rows = [] elif hasattr(rows, "itertuples"): normalized_rows = rows.fillna("").itertuples(index=False, name=None) elif isinstance(rows, dict): normalized_rows = zip(*rows.values()) if rows else [] else: normalized_rows = rows for row in normalized_rows: values = list(row) + ["", "", "", ""] name, expertise, focus, style = [str(value or "").strip() for value in values[:4]] if name: reviewers.append(ReviewerAgent(name, expertise, focus, style)) if not reviewers: raise gr.Error("請至少設定一位審查委員。") return reviewers def _openai_models_url(api_url: str) -> str: """Convert a chat-completions endpoint to its OpenAI-compatible models URL.""" url = (api_url or "https://api.openai.com/v1/chat/completions").strip().rstrip("/") for suffix in ("/chat/completions", "/responses", "/completions"): if url.endswith(suffix): return url[: -len(suffix)] + "/models" return url if url.endswith("/models") else url + "/models" def _ollama_api_url(base_url: str, path: str) -> str: """Build an Ollama native API URL from a public HTTPS base URL.""" base = (base_url or "").strip().rstrip("/") if base.endswith("/api"): base = base[:-4] return f"{base}/api/{path.lstrip('/')}" def _auth_headers(api_key: str) -> dict: token = (api_key or "").strip() return {"Authorization": f"Bearer {token}"} if token else {} def provider_defaults(provider: str): if provider == "Gemini": choices = ["gemini-2.5-flash", "gemini-2.5-pro", "gemini-2.0-flash"] return gr.Dropdown(choices=choices, value=choices[0], allow_custom_value=True), gr.Textbox(value="https://api.openai.com/v1/chat/completions", visible=False) if provider == "OpenAI 相容 API": choices = ["gpt-4o-mini", "gpt-4o", "gpt-4.1-mini"] return gr.Dropdown(choices=choices, value=choices[0], allow_custom_value=True), gr.Textbox(value="https://api.openai.com/v1/chat/completions", visible=True) if provider == "Ollama 遠端服務": choices = ["gemma3:latest", "llama3.1:latest", "qwen3:latest"] return gr.Dropdown(choices=choices, value=choices[0], allow_custom_value=True), gr.Textbox(value="https://your-ollama.example.com", visible=True) return gr.Dropdown(choices=["mock"], value="mock", allow_custom_value=True), gr.Textbox(value="https://api.openai.com/v1/chat/completions", visible=False) def provider_help(provider: str) -> str: if provider == "Ollama 遠端服務": return ( "請填入可從網際網路存取的 Ollama HTTPS Base URL,然後按下方按鈕。" "系統會測試 `/api/tags`、顯示模型明細,並更新模型下拉選單。" ) if provider == "模擬模式": return "模擬模式不需要 API Key 或遠端模型。" return "輸入 API Key 後可自動取得模型清單。" def detect_available_models(provider: str, api_key: str, api_url: str): """Validate the API key and populate the model dropdown.""" if provider == "模擬模式": return gr.Dropdown(choices=["mock"], value="mock", allow_custom_value=True), "✅ 模擬模式不需要 API Key。" if provider != "Ollama 遠端服務" and not (api_key or "").strip(): raise gr.Error("請先輸入 API Key。") try: model_details = [] if provider == "Gemini": response = requests.get( "https://generativelanguage.googleapis.com/v1beta/models", params={"key": api_key.strip(), "pageSize": 1000}, timeout=20, ) response.raise_for_status() models = [] for item in response.json().get("models", []): methods = item.get("supportedGenerationMethods", []) if "generateContent" in methods: models.append(item.get("name", "").removeprefix("models/")) elif provider == "OpenAI 相容 API": response = requests.get( _openai_models_url(api_url), headers={"Authorization": f"Bearer {api_key.strip()}"}, timeout=20, ) response.raise_for_status() models = [str(item.get("id", "")).strip() for item in response.json().get("data", [])] else: if not (api_url or "").strip().lower().startswith("https://"): raise ValueError("Hugging Face Space 請使用 HTTPS Ollama URL;localhost 與 11434 無法由雲端直接存取。") if "your-ollama.example.com" in (api_url or "").lower(): raise ValueError("目前仍是範例網址。請改填 Cloudflare Tunnel 或反向代理實際產生的 HTTPS URL。") response = requests.get( _ollama_api_url(api_url, "tags"), headers=_auth_headers(api_key), timeout=20, ) response.raise_for_status() ollama_models = response.json().get("models", []) models = [str(item.get("name", "")).strip() for item in ollama_models] for item in ollama_models: details = item.get("details", {}) or {} size = int(item.get("size", 0) or 0) model_details.append({ "name": str(item.get("name", "")).strip(), "size": f"{size / (1024 ** 3):.2f} GB" if size else "未知", "family": details.get("family") or details.get("format") or "未知", "quantization": details.get("quantization_level") or "未知", }) models = sorted({model for model in models if model}, key=str.lower) if not models: raise ValueError("API 回應成功,但沒有可用模型。您仍可手動輸入模型名稱。") preferred = next((m for m in models if "flash" in m.lower()), models[0]) if provider == "Ollama 遠端服務": rows = ["| 模型 | 大小 | 家族/格式 | 量化 |", "|---|---:|---|---|"] for detail in model_details: rows.append( f"| `{detail['name']}` | {detail['size']} | {detail['family']} | {detail['quantization']} |" ) status = ( f"✅ Ollama 連線成功:`{(api_url or '').rstrip('/')}` " f"\n共找到 **{len(models)}** 個可用模型。\n\n" + "\n".join(rows) ) else: status = f"✅ API Key 驗證成功,共找到 {len(models)} 個可用模型。" return gr.Dropdown(choices=models, value=preferred, allow_custom_value=True), status except requests.HTTPError as exc: detail = "" try: detail = exc.response.json().get("error", {}).get("message", "") except Exception: detail = exc.response.text[:300] if exc.response is not None else "" raise gr.Error(f"模型偵測失敗(HTTP {exc.response.status_code}):{detail or exc}") from exc except Exception as exc: raise gr.Error(f"模型偵測失敗:{exc}") from exc def _round_markdown(title: str, entries: dict) -> str: parts = [f"## {title}"] for name, content in entries.items(): parts.append(f"### {name}\n\n{content}") return "\n\n".join(parts) def _report_file(title: str, history: dict, stats: dict) -> str: safe_title = "".join(c for c in title if c.isalnum() or c in "-_ ").strip() or "paper_review" fd, path = tempfile.mkstemp(prefix="paper_review_", suffix=".md") with os.fdopen(fd, "w", encoding="utf-8") as file: file.write(f"# {safe_title}:多代理人審查報告\n\n") file.write("## 評分\n\n") file.write(json.dumps(stats, ensure_ascii=False, indent=2)) for key, label in (("round_1", "第一輪:獨立審查"), ("round_2", "第二輪:交叉辯論"), ("round_3", "第三輪:最終裁決")): file.write("\n\n" + _round_markdown(label, history.get(key, {}))) return path def run_review( title, field, content, references, exclude_quotes, exclusion_keywords, manual_exclusions, reviewer_rows, provider, api_key, model_name, api_url, enable_rag, enable_web, enable_references, tavily_key, ): if not (title or "").strip(): raise gr.Error("請輸入論文標題。") filtered = apply_text_filters( content or "", manual_exclusions=[line for line in (manual_exclusions or "").splitlines() if line.strip()], exclude_quotes=bool(exclude_quotes), exclusion_keywords=exclusion_keywords or "", ) if not filtered.strip(): raise gr.Error("請上傳論文或貼上論文內容。") config = _build_config( provider, api_key, model_name, api_url, "模擬偵測", "", "", enable_rag, enable_web, enable_references, tavily_key, ) if config["llm_mode"] == "cloud" and not config["cloud"]["api_key"]: raise gr.Error("請輸入所選推論服務的 API Key。") if config["llm_mode"] == "ollama" and not config["ollama"]["host"].lower().startswith("https://"): raise gr.Error("雲端 Space 只能連線至 HTTPS Ollama URL,不能使用 localhost:11434。") config_path = _temporary_config(config) try: paper = Paper(title.strip(), (field or "").strip(), filtered, references or "") llm = LLMInterface(config_path=config_path) orchestrator = PaperReviewOrchestrator( paper, _reviewers_from_table(reviewer_rows), llm, knowledge_config=config["knowledge_update"], ) yield "⏳ 第一輪:獨立深度審查與外部知識檢索…", {}, "", "", "", None round_1 = asyncio.run(orchestrator.run_round_1()) yield "⏳ 第二輪:審查委員交叉辯論…", {}, _round_markdown("第一輪:獨立審查", round_1), "", "", None round_2 = asyncio.run(orchestrator.run_round_2()) yield "⏳ 第三輪:主席整合與最終裁決…", {}, _round_markdown("第一輪:獨立審查", round_1), _round_markdown("第二輪:交叉辯論", round_2), "", None round_3 = asyncio.run(orchestrator.run_round_3()) history, stats = orchestrator.history, orchestrator.review_stats yield ( "✅ 審查完成。", stats, _round_markdown("第一輪:獨立審查", round_1), _round_markdown("第二輪:交叉辯論", round_2), _round_markdown("第三輪:最終裁決", round_3), _report_file(title, history, stats), ) except gr.Error: raise except Exception as exc: raise gr.Error(f"審查執行失敗:{exc}") from exc finally: try: os.remove(config_path) except OSError: pass def _segments_html(report: dict) -> str: blocks = [] for segment in report.get("segments", []): text = html.escape(str(segment.get("text", ""))) color = segment.get("color", "transparent") reason = html.escape(str(segment.get("reason", segment.get("type", "")))) blocks.append(f'{text}') return '