wangsungwen commited on
Commit
2a76d64
·
1 Parent(s): 2b6eb12

Fix Gradio review input and add model detection uploads

Browse files
Files changed (1) hide show
  1. app.py +101 -3
app.py CHANGED
@@ -17,6 +17,7 @@ from pathlib import Path
17
  from typing import Iterable
18
 
19
  import gradio as gr
 
20
 
21
  try:
22
  import spaces
@@ -147,7 +148,18 @@ def _temporary_config(config: dict) -> str:
147
 
148
  def _reviewers_from_table(rows) -> list[ReviewerAgent]:
149
  reviewers = []
150
- for row in rows or []:
 
 
 
 
 
 
 
 
 
 
 
151
  values = list(row) + ["", "", "", ""]
152
  name, expertise, focus, style = [str(value or "").strip() for value in values[:4]]
153
  if name:
@@ -157,6 +169,73 @@ def _reviewers_from_table(rows) -> list[ReviewerAgent]:
157
  return reviewers
158
 
159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  def _round_markdown(title: str, entries: dict) -> str:
161
  parts = [f"## {title}"]
162
  for name, content in entries.items():
@@ -283,9 +362,22 @@ with gr.Blocks(title=APP_TITLE) as demo:
283
  with gr.Accordion("⚙️ 推論與知識設定", open=True):
284
  with gr.Row():
285
  provider = gr.Radio(["Gemini", "OpenAI 相容 API", "模擬模式"], value="Gemini", label="推論服務")
286
- model_name = gr.Textbox(value="gemini-2.5-flash", label="模型名稱")
 
 
 
 
287
  api_key = gr.Textbox(label="API Key", type="password", placeholder="不會寫入儲存庫或永久磁碟")
288
- api_url = gr.Textbox(value="https://api.openai.com/v1/chat/completions", label="OpenAI 相容 API Endpoint")
 
 
 
 
 
 
 
 
 
289
  with gr.Row():
290
  enable_rag = gr.Checkbox(value=True, label="Arxiv 最新文獻")
291
  enable_web = gr.Checkbox(value=False, label="聯網搜尋")
@@ -338,7 +430,13 @@ with gr.Blocks(title=APP_TITLE) as demo:
338
  )
339
 
340
  with gr.Tab("🔍 AI 文字偵測"):
 
 
 
 
 
341
  detector_text = gr.Textbox(label="待分析文字", lines=16)
 
342
  with gr.Row():
343
  detector_mode = gr.Radio(["ZeroGPU 模型", "GPTZero API", "模擬偵測"], value="模擬偵測", label="偵測方式")
344
  detector_key = gr.Textbox(label="GPTZero API Key", type="password")
 
17
  from typing import Iterable
18
 
19
  import gradio as gr
20
+ import requests
21
 
22
  try:
23
  import spaces
 
148
 
149
  def _reviewers_from_table(rows) -> list[ReviewerAgent]:
150
  reviewers = []
151
+ # Gradio 6 returns a pandas.DataFrame. Evaluating a DataFrame as a bool
152
+ # (``rows or []``) raises: "The truth value of a DataFrame is ambiguous".
153
+ if rows is None:
154
+ normalized_rows = []
155
+ elif hasattr(rows, "itertuples"):
156
+ normalized_rows = rows.fillna("").itertuples(index=False, name=None)
157
+ elif isinstance(rows, dict):
158
+ normalized_rows = zip(*rows.values()) if rows else []
159
+ else:
160
+ normalized_rows = rows
161
+
162
+ for row in normalized_rows:
163
  values = list(row) + ["", "", "", ""]
164
  name, expertise, focus, style = [str(value or "").strip() for value in values[:4]]
165
  if name:
 
169
  return reviewers
170
 
171
 
172
+ def _openai_models_url(api_url: str) -> str:
173
+ """Convert a chat-completions endpoint to its OpenAI-compatible models URL."""
174
+ url = (api_url or "https://api.openai.com/v1/chat/completions").strip().rstrip("/")
175
+ for suffix in ("/chat/completions", "/responses", "/completions"):
176
+ if url.endswith(suffix):
177
+ return url[: -len(suffix)] + "/models"
178
+ return url if url.endswith("/models") else url + "/models"
179
+
180
+
181
+ def provider_defaults(provider: str):
182
+ if provider == "Gemini":
183
+ choices = ["gemini-2.5-flash", "gemini-2.5-pro", "gemini-2.0-flash"]
184
+ return gr.Dropdown(choices=choices, value=choices[0], allow_custom_value=True), gr.Textbox(value="https://api.openai.com/v1/chat/completions", visible=False)
185
+ if provider == "OpenAI 相容 API":
186
+ choices = ["gpt-4o-mini", "gpt-4o", "gpt-4.1-mini"]
187
+ return gr.Dropdown(choices=choices, value=choices[0], allow_custom_value=True), gr.Textbox(value="https://api.openai.com/v1/chat/completions", visible=True)
188
+ return gr.Dropdown(choices=["mock"], value="mock", allow_custom_value=True), gr.Textbox(value="https://api.openai.com/v1/chat/completions", visible=False)
189
+
190
+
191
+ def detect_available_models(provider: str, api_key: str, api_url: str):
192
+ """Validate the API key and populate the model dropdown."""
193
+ if provider == "模擬模式":
194
+ return gr.Dropdown(choices=["mock"], value="mock", allow_custom_value=True), "✅ 模擬模式不需要 API Key。"
195
+ if not (api_key or "").strip():
196
+ raise gr.Error("請先輸入 API Key。")
197
+
198
+ try:
199
+ if provider == "Gemini":
200
+ response = requests.get(
201
+ "https://generativelanguage.googleapis.com/v1beta/models",
202
+ params={"key": api_key.strip(), "pageSize": 1000},
203
+ timeout=20,
204
+ )
205
+ response.raise_for_status()
206
+ models = []
207
+ for item in response.json().get("models", []):
208
+ methods = item.get("supportedGenerationMethods", [])
209
+ if "generateContent" in methods:
210
+ models.append(item.get("name", "").removeprefix("models/"))
211
+ else:
212
+ response = requests.get(
213
+ _openai_models_url(api_url),
214
+ headers={"Authorization": f"Bearer {api_key.strip()}"},
215
+ timeout=20,
216
+ )
217
+ response.raise_for_status()
218
+ models = [str(item.get("id", "")).strip() for item in response.json().get("data", [])]
219
+
220
+ models = sorted({model for model in models if model}, key=str.lower)
221
+ if not models:
222
+ raise ValueError("API 回應成功,但沒有可用模型。您仍可手動輸入模型名稱。")
223
+ preferred = next((m for m in models if "flash" in m.lower()), models[0])
224
+ return (
225
+ gr.Dropdown(choices=models, value=preferred, allow_custom_value=True),
226
+ f"✅ API Key 驗證成功,共找到 {len(models)} 個可用模型。",
227
+ )
228
+ except requests.HTTPError as exc:
229
+ detail = ""
230
+ try:
231
+ detail = exc.response.json().get("error", {}).get("message", "")
232
+ except Exception:
233
+ detail = exc.response.text[:300] if exc.response is not None else ""
234
+ raise gr.Error(f"模型偵測失敗(HTTP {exc.response.status_code}):{detail or exc}") from exc
235
+ except Exception as exc:
236
+ raise gr.Error(f"模型偵測失敗:{exc}") from exc
237
+
238
+
239
  def _round_markdown(title: str, entries: dict) -> str:
240
  parts = [f"## {title}"]
241
  for name, content in entries.items():
 
362
  with gr.Accordion("⚙️ 推論與知識設定", open=True):
363
  with gr.Row():
364
  provider = gr.Radio(["Gemini", "OpenAI 相容 API", "模擬模式"], value="Gemini", label="推論服務")
365
+ model_name = gr.Dropdown(
366
+ choices=["gemini-2.5-flash", "gemini-2.5-pro", "gemini-2.0-flash"],
367
+ value="gemini-2.5-flash", allow_custom_value=True,
368
+ label="模型名稱(可從偵測結果選擇或自行輸入)",
369
+ )
370
  api_key = gr.Textbox(label="API Key", type="password", placeholder="不會寫入儲存庫或永久磁碟")
371
+ with gr.Row():
372
+ detect_models_button = gr.Button("🔍 驗證 API Key 並偵測可用模型")
373
+ model_detection_status = gr.Markdown("輸入 API Key 後可自動取得模型清單。")
374
+ api_url = gr.Textbox(value="https://api.openai.com/v1/chat/completions", label="OpenAI 相容 API Endpoint", visible=False)
375
+ provider.change(provider_defaults, provider, [model_name, api_url])
376
+ detect_models_button.click(
377
+ detect_available_models,
378
+ [provider, api_key, api_url],
379
+ [model_name, model_detection_status],
380
+ )
381
  with gr.Row():
382
  enable_rag = gr.Checkbox(value=True, label="Arxiv 最新文獻")
383
  enable_web = gr.Checkbox(value=False, label="聯網搜尋")
 
430
  )
431
 
432
  with gr.Tab("🔍 AI 文字偵測"):
433
+ detector_file = gr.File(
434
+ label="上傳待偵測論文(TXT / PDF / DOCX)",
435
+ file_types=[".txt", ".pdf", ".docx"], type="filepath",
436
+ )
437
+ detector_file_status = gr.Markdown("可上傳論文,或直接在下方貼上文字。")
438
  detector_text = gr.Textbox(label="待分析文字", lines=16)
439
+ detector_file.change(parse_paper_file, detector_file, [detector_text, detector_file_status])
440
  with gr.Row():
441
  detector_mode = gr.Radio(["ZeroGPU 模型", "GPTZero API", "模擬偵測"], value="模擬偵測", label="偵測方式")
442
  detector_key = gr.Textbox(label="GPTZero API Key", type="password")