# app.py import os import time import re from typing import List, Dict import gradio as gr import numpy as np import pandas as pd from sentence_transformers import SentenceTransformer # =============== 啟動時載入資料 =============== # 1. 載入你在 Colab 事先存好的資料 # - cases.parquet:從評議彙整.xlsx 轉來 # - embeddings.npy:對應每列 retrieve_text 的向量 CASES_PATH = "cases.parquet" EMB_PATH = "embeddings.npy" df = pd.read_parquet(CASES_PATH).fillna("") emb = np.load(EMB_PATH).astype("float32") # shape = (N, D) cases = df.to_dict(orient="records") # 與你 Colab 相同的檢索欄位與模型 RETRIEVE_FIELDS = [ "爭議類型","本件爭點","判斷理由","主文", "程序事項","申請人之主張","相對人之主張","兩造不爭執之事實" ] model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2') # =============== 檢索相關函式(沿用你原本邏輯) =============== def maybe_filter(df: pd.DataFrame, query: str) -> List[int]: """ 簡單條件/關鍵詞過濾:在 產業別/子產業別/主文/申請人主張/相對人主張 中做字串包含 """ mask = None pattern = "|".join([re.escape(w) for w in re.findall(r"[\u4e00-\u9fa5A-Za-z]+", query)]) for col in ["產業別","子產業別","主文","申請人之主張","相對人之主張"]: contains = df[col].astype(str).str.contains(pattern, case=False, na=False) mask = contains if mask is None else (mask | contains) candidate_idx = df[mask].index.tolist() if mask is not None and mask.any() else list(range(len(df))) return candidate_idx def mmr(relevance: np.ndarray, pairwise_sim: np.ndarray, k: int, lambda_mult: float = 0.5): """ Maximal Marginal Relevance:選出同時「跟查詢相關」且「彼此多樣」的一組案例 """ n = relevance.shape[0] if n == 0: return [] if n == 1 or k <= 1: return [int(np.argmax(relevance))] selected = [] candidates = list(range(n)) first = int(np.argmax(relevance)) selected.append(first) candidates.remove(first) while len(selected) < min(k, n) and candidates: cand_rels = relevance[candidates] submat = pairwise_sim[np.ix_(candidates, selected)] submat = np.nan_to_num(submat, nan=0.0) redund = submat.max(axis=1) if submat.ndim == 2 else np.zeros_like(cand_rels) scores = lambda_mult * cand_rels - (1.0 - lambda_mult) * redund pick_local = int(np.argmax(scores)) pick = candidates[pick_local] selected.append(pick) candidates.remove(pick) return selected def retrieve(query: str, top_k: int = 20, mmr_k: int = 5) -> List[Dict]: """ 給 query,回傳擬似度排序後、經 MMR 篩選過的案例(list of dict) """ candidate_idx = maybe_filter(df, query) if len(candidate_idx) == 0: candidate_idx = list(range(len(df))) qv = model.encode([query], normalize_embeddings=True).astype("float32") sub_emb = emb[candidate_idx] sims = np.dot(sub_emb, qv.T).ravel() if sims.size == 0: return [] top_idx_local = np.argsort(-sims)[:min(top_k, sims.size)] sub_emb_top = sub_emb[top_idx_local] rel_top = sims[top_idx_local] pairwise_top = np.dot(sub_emb_top, sub_emb_top.T) pick_local = mmr(rel_top, pairwise_top, k=min(mmr_k, len(top_idx_local)), lambda_mult=0.5) final_local = [top_idx_local[i] for i in pick_local] final_idx = [candidate_idx[i] for i in final_local] return [cases[i] for i in final_idx] # =============== Gemini:勝負 & 關鍵論述摘要 =============== from google import genai from google.genai import types GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY") # 請在 Space 的「Settings → Variables」設定 if not GEMINI_API_KEY: print("⚠️ 未設定 GEMINI_API_KEY 環境變數,Gemini 功能將無法使用。") client = genai.Client(api_key=GEMINI_API_KEY) if GEMINI_API_KEY else None def rate_limited_iter(iterable, max_per_min=10): """ 簡單限流:每 10 筆請求為一批,批與批之間至少空 60 秒 """ start = time.time() count = 0 for item in iterable: if count and (count % max_per_min == 0): elapsed = time.time() - start if elapsed < 60: time.sleep(60 - elapsed) start = time.time() count += 1 yield item def summarize_case_with_gemini(row: Dict) -> str: """ 使用 Gemini 閱讀整案重點欄位,生成勝負與關鍵論述摘要 輸出格式: --- 勝負結果:XXX 關鍵論述摘要:YYY --- """ if client is None: return "⚠️ 未設定 GEMINI_API_KEY,無法產生摘要。" prompt = f""" 你是一位熟悉保險評議制度的專業助理。請根據以下資料,分析評議委員最終的判定理由,並回答: 1️⃣ 最終勝負結果(申請人勝 / 相對人勝 / 相對人部分勝與申請人部分勝 / 申請人部分勝 / 不受理 / 不確定)。 2️⃣ 評議委員判定誰勝出的關鍵理由摘要(50-100字內)。 【評議決定】: {row.get('評議決定','')} 【主文】: {row.get('主文','')} 【申請人之主張】: {row.get('申請人之主張','')} 【相對人之主張】: {row.get('相對人之主張','')} 【判斷理由】: {row.get('判斷理由','')} 請以簡潔、專業中文輸出: --- 勝負結果:XXX 關鍵論述摘要:YYY --- """ try: response = client.models.generate_content( model="gemini-2.5-flash", contents=prompt, config=types.GenerateContentConfig( thinking_config=types.ThinkingConfig(thinking_budget=0) ), ) return (response.text or "").strip() except Exception as e: return f"⚠️ Gemini 摘要失敗:{e}" # =============== 主流程:查詢 → Gemini 摘要 → 產生 Excel 檔路徑 =============== def search_and_build_excel(query: str, top_k: int) -> str: """ Gradio 用的函式: - 用向量檢索找到前 top_k 個案例 - 對每個案例呼叫 Gemini 生成摘要 - 產生一個 Excel 檔(沿用你原本的格式) - 回傳該檔案的路徑,讓 Gradio File 元件提供下載 """ query = (query or "").strip() if not query: raise gr.Error("請先輸入查詢關鍵字。") if client is None: raise gr.Error("伺服器尚未設定 GEMINI_API_KEY,無法產生 Gemini 摘要。") rows = retrieve(query, top_k=int(top_k)*2, mmr_k=int(top_k)) if not rows: raise gr.Error("查無相似評議案例,請改用其他關鍵字或描述。") summaries = [] for i, r in enumerate(rate_limited_iter(rows, max_per_min=10), 1): print(f"[Gemini] ({i}/{len(rows)}) 處理評議字號:{r.get('評議字號','')}") summary = summarize_case_with_gemini(r) summaries.append({ "評議字號": r.get("評議字號",""), "評議決定": r.get("評議決定",""), "主文": r.get("主文",""), "Gemini摘要結果": summary, }) summary_df = pd.DataFrame(summaries) # 沿用原本檔名,可依需要加上 query out_path = f"Gemini勝負摘要.xlsx" summary_df.to_excel(out_path, index=False) return out_path # =============== Gradio 介面:只提供輸入 & 下載 Excel,不顯示表格 =============== with gr.Blocks() as demo: gr.Markdown("## 保險評議案例檢索摘要Excel 下載(資料來源:金融消費評議中心109/1~114/10,僅供學習使用。請勿轉載重製)") with gr.Row(): query_in = gr.Textbox( label="請輸入病名或治療關鍵字", placeholder="例如:牙周翻瓣手術", lines=2, ) topk_in = gr.Slider( minimum=5, maximum=50, value=20, step=1, label="最多產生幾筆案例摘要(top_k)" ) run_btn = gr.Button("搜尋並產生 Excel 摘要") result_file = gr.File(label="下載 Excel 檔案") def _run_and_return_file(q, k): path = search_and_build_excel(q, k) return path run_btn.click( fn=_run_and_return_file, inputs=[query_in, topk_in], outputs=[result_file] ) demo.launch(ssr_mode=False)