Spaces:
Sleeping
Sleeping
Download app.py from Arthur0126/RAG_Telegram: direct link, hf CLI and curl.
- Browser
- Download file 39.5 kB
-
https://huggingface.co/spaces/Arthur0126/RAG_Telegram/resolve/main/app.py
- Command line
-
hf download hf://spaces/Arthur0126/RAG_Telegram/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Arthur0126/RAG_Telegram/resolve/main/app.py
39.5 kB
| from __future__ import annotations | |
| # ── 自動安裝缺少的套件 ──────────────────────────────────── | |
| import subprocess, sys | |
| _REQUIRED = [ | |
| "gradio", "groq", "pypdf", "python-docx", | |
| "sentence-transformers", "numpy", "chromadb", | |
| "scikit-learn", "requests", | |
| ] | |
| for _pkg in _REQUIRED: | |
| try: | |
| __import__(_pkg.replace("-", "_").split("[")[0]) | |
| except ImportError: | |
| print(f"Installing {_pkg}...") | |
| subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", _pkg]) | |
| # ── 強制 UTF-8,相容 Colab OutStream(無 .buffer)──────────── | |
| import io, os | |
| os.environ.setdefault("PYTHONIOENCODING", "utf-8") | |
| # 只在有 .buffer 的環境(本機終端)才換包,Colab 直接跳過 | |
| try: | |
| if hasattr(sys.stdout, "buffer"): | |
| sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace") | |
| if hasattr(sys.stderr, "buffer"): | |
| sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace") | |
| except Exception: | |
| pass | |
| # ── Telegram 設定(優先讀取環境變數以利 HF Spaces 安全部署,無則 Fallback 至預設值)── | |
| TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "123456789:ABCdefGhIJKlmNoPQRstUVwxyZ") | |
| TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", "987654321") | |
| import os | |
| import re | |
| import time | |
| from pathlib import Path | |
| from typing import Any | |
| import chromadb | |
| import gradio as gr | |
| import numpy as np | |
| import requests | |
| from docx import Document | |
| from docx.oxml.table import CT_Tbl | |
| from docx.oxml.text.paragraph import CT_P | |
| from docx.table import Table | |
| from docx.text.paragraph import Paragraph | |
| from groq import Groq | |
| from pypdf import PdfReader | |
| from sentence_transformers import SentenceTransformer | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| # ══════════════════════════════════════════════════════════ | |
| # Telegram 推送模組 | |
| # ══════════════════════════════════════════════════════════ | |
| class TelegramNotifier: | |
| """單一職責:透過 Bot API 推送訊息至指定 Chat。""" | |
| MAX_LENGTH = 4096 # Telegram 單則訊息字元上限 | |
| def __init__(self, token: str = "", chat_id: str = "", api_url: str = "https://api.telegram.org"): | |
| self.token = token.strip() | |
| self.chat_id = chat_id.strip() | |
| self.api_url = api_url.strip() or "https://api.telegram.org" | |
| def configure(self, token: str, chat_id: str, api_url: str = "") -> str: | |
| """更新 Token、Chat ID 與 API URL,並驗證 Bot 是否可用。""" | |
| self.token = token.strip() | |
| self.chat_id = chat_id.strip() | |
| if api_url: | |
| self.api_url = api_url.strip() | |
| if not self.token or not self.chat_id: | |
| return "⚠ Token 或 Chat ID 未填寫" | |
| # 用 getMe 驗證 token 是否有效,增加 timeout 解決網路超時問題 | |
| try: | |
| url = f"{self.api_url.rstrip('/')}/bot{self.token}/getMe" | |
| resp = requests.get(url, timeout=12) | |
| data = resp.json() | |
| if not data.get("ok"): | |
| return f"✗ Token 無效:{data.get('description', '未知錯誤')}" | |
| bot_name = data["result"].get("username", "unknown") | |
| return f"✓ Telegram 已連線:@{bot_name} → Chat ID: {self.chat_id}" | |
| except requests.RequestException as exc: | |
| return f"✗ 網路錯誤:{exc}" | |
| def send(self, text: str, parse_mode: str = "Markdown") -> tuple[bool, str]: | |
| """ | |
| 推送文字訊息,自動分段處理超過 4096 字元的內容。 | |
| 回傳 (成功與否, 狀態說明)。 | |
| """ | |
| if not self.token or not self.chat_id: | |
| return False, "⚠ Telegram 尚未設定(Token / Chat ID 為空)" | |
| url = f"{self.api_url.rstrip('/')}/bot{self.token}/sendMessage" | |
| # 切分長文,避免超過 Telegram 單則上限 | |
| segments = self._split_message(text) | |
| errors: list[str] = [] | |
| for segment in segments: | |
| try: | |
| resp = requests.post( | |
| url, | |
| json={ | |
| "chat_id": self.chat_id, | |
| "text": segment, | |
| "parse_mode": parse_mode, | |
| }, | |
| timeout=15, | |
| ) | |
| data = resp.json() | |
| if not data.get("ok"): | |
| # 若 Markdown 解析失敗,降級為純文字重試 | |
| if "can't parse" in data.get("description", ""): | |
| resp2 = requests.post( | |
| url, | |
| json={"chat_id": self.chat_id, "text": segment}, | |
| timeout=15, | |
| ) | |
| data2 = resp2.json() | |
| if not data2.get("ok"): | |
| errors.append(data2.get("description", "未知")) | |
| else: | |
| errors.append(data.get("description", "未知")) | |
| except requests.RequestException as exc: | |
| errors.append(str(exc)) | |
| if errors: | |
| return False, f"✗ 推送失敗:{'; '.join(errors)}" | |
| return True, f"✓ 已推送 {len(segments)} 則訊息至 Telegram" | |
| def _split_message(self, text: str) -> list[str]: | |
| """將長文依 MAX_LENGTH 切分。""" | |
| if len(text) <= self.MAX_LENGTH: | |
| return [text] | |
| segments = [] | |
| while text: | |
| segments.append(text[: self.MAX_LENGTH]) | |
| text = text[self.MAX_LENGTH :] | |
| return segments | |
| # ══════════════════════════════════════════════════════════ | |
| # RAG 核心邏輯(與 v2 相同,保持不動) | |
| # ══════════════════════════════════════════════════════════ | |
| class MultiStrategyRAG: | |
| STRATEGY_MAP = { | |
| "semantic": "1 ChromaDB 語意搜尋", | |
| "tfidf": "2 TF-IDF 關鍵詞", | |
| "hybrid": "3 混合搜尋", | |
| "rerank": "4 重新排序", | |
| "multi_query": "5 多查詢擴展", | |
| "compress": "6 上下文壓縮", | |
| "parent_child": "7 父子文檔", | |
| "hyde": "8 假設性答案 HyDE", | |
| } | |
| def __init__( | |
| self, | |
| chroma_path: str = "./chroma_db", | |
| collection_name: str = "audit_rag_chunks", | |
| child_collection_name: str = "audit_rag_child_chunks", | |
| ): | |
| self.client: Groq | None = None | |
| self.embedding_model = SentenceTransformer( | |
| "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2" | |
| ) | |
| self.chroma_client = chromadb.PersistentClient(path=chroma_path) | |
| self.collection = self.chroma_client.get_or_create_collection( | |
| name=collection_name, | |
| metadata={"hnsw:space": "cosine"}, | |
| ) | |
| self.child_collection = self.chroma_client.get_or_create_collection( | |
| name=child_collection_name, | |
| metadata={"hnsw:space": "cosine"}, | |
| ) | |
| self.session_id: str | None = None | |
| self.source_name: str = "" | |
| self.file_type: str = "" | |
| self.chunks: list[str] = [] | |
| self.child_chunks: list[str] = [] | |
| self.tfidf_vectorizer: TfidfVectorizer | None = None | |
| self.tfidf_matrix = None | |
| # ── API Key 管理 ───────────────────────────────────── | |
| def set_api_key(self, api_key: str) -> None: | |
| key = (api_key or "").strip() | |
| self.client = Groq(api_key=key) if key else None | |
| # ── 文件載入 ───────────────────────────────────────── | |
| def load_document(self, file_path: str) -> str: | |
| try: | |
| path = Path(file_path) | |
| if not path.exists(): | |
| return "✗ 載入失敗:找不到檔案" | |
| suffix = path.suffix.lower() | |
| if suffix not in (".pdf", ".docx"): | |
| return "✗ 目前僅支援 PDF 與 DOCX 檔案" | |
| self.source_name = path.name | |
| self.file_type = suffix.lstrip(".") | |
| self.session_id = ( | |
| f"{int(time.time())}_{re.sub(r'[^a-zA-Z0-9]+', '_', path.stem)[:40]}" | |
| ) | |
| if suffix == ".pdf": | |
| full_text, stats = self._extract_pdf(path) | |
| else: | |
| full_text, stats = self._extract_docx(path) | |
| if not full_text.strip(): | |
| return "✗ 載入失敗:文件沒有可擷取文字" | |
| self.chunks = self._split(full_text, chunk_size=800, overlap=150) | |
| if not self.chunks: | |
| return "✗ 載入失敗:切段後沒有有效內容" | |
| self._build_chroma_index() | |
| self._build_tfidf_index() | |
| self._build_child_index() | |
| return ( | |
| f"✓ 成功載入 {self.source_name}\n" | |
| f"類型:{suffix.upper().lstrip('.')} · {stats}\n" | |
| f"{len(self.chunks)} 個主片段 · ChromaDB Session:{self.session_id}" | |
| ) | |
| except Exception as exc: | |
| return f"✗ 載入失敗:{type(exc).__name__}: {exc}" | |
| # ── 文字擷取 ───────────────────────────────────────── | |
| def _extract_pdf(self, path: Path) -> tuple[str, str]: | |
| reader = PdfReader(str(path)) | |
| parts = [] | |
| for idx, page in enumerate(reader.pages, 1): | |
| text = page.extract_text() or "" | |
| if text.strip(): | |
| parts.append(f"\n[PDF 第 {idx} 頁]\n{text}") | |
| return "\n".join(parts), f"{len(reader.pages)} 頁" | |
| def _extract_docx(self, path: Path) -> tuple[str, str]: | |
| doc = Document(str(path)) | |
| blocks: list[str] = [] | |
| para_count = table_count = 0 | |
| for child in doc.element.body.iterchildren(): | |
| if isinstance(child, CT_P): | |
| text = Paragraph(child, doc).text.strip() | |
| if text: | |
| para_count += 1 | |
| blocks.append(text) | |
| elif isinstance(child, CT_Tbl): | |
| table_count += 1 | |
| tbl_text = self._table_to_text(Table(child, doc)) | |
| if tbl_text.strip(): | |
| blocks.append(f"\n[DOCX 表格 {table_count}]\n{tbl_text}") | |
| return "\n\n".join(blocks), f"{para_count} 段落 / {table_count} 表格" | |
| def _table_to_text(self, table: Table) -> str: | |
| rows = [] | |
| for row in table.rows: | |
| cells = [re.sub(r"\s+", " ", c.text).strip() for c in row.cells if c.text.strip()] | |
| if cells: | |
| rows.append(" | ".join(cells)) | |
| return "\n".join(rows) | |
| def _split(self, text: str, chunk_size: int, overlap: int) -> list[str]: | |
| clean = re.sub(r"\s+", " ", text).strip() | |
| step = max(1, chunk_size - overlap) | |
| return [ | |
| c for start in range(0, len(clean), step) | |
| if (c := clean[start: start + chunk_size].strip()) | |
| ] | |
| # ── Index 建立 ─────────────────────────────────────── | |
| def _encode(self, texts: list[str]) -> list[list[float]]: | |
| return ( | |
| self.embedding_model | |
| .encode(texts, convert_to_numpy=True, normalize_embeddings=True, show_progress_bar=False) | |
| .astype("float32") | |
| .tolist() | |
| ) | |
| def _build_chroma_index(self) -> None: | |
| sid = self.session_id | |
| ids = [f"{sid}_chunk_{i:05d}" for i in range(len(self.chunks))] | |
| metas = [ | |
| {"session_id": sid, "source": self.source_name, | |
| "file_type": self.file_type, "chunk_index": i} | |
| for i in range(len(self.chunks)) | |
| ] | |
| self.collection.add(ids=ids, documents=self.chunks, | |
| metadatas=metas, embeddings=self._encode(self.chunks)) | |
| def _build_tfidf_index(self) -> None: | |
| self.tfidf_vectorizer = TfidfVectorizer(analyzer="char", ngram_range=(2, 4), max_features=3000) | |
| self.tfidf_matrix = self.tfidf_vectorizer.fit_transform(self.chunks) | |
| def _build_child_index(self) -> None: | |
| sid = self.session_id | |
| child_docs, child_ids, child_metas = [], [], [] | |
| for pidx, parent in enumerate(self.chunks): | |
| for cidx, child in enumerate(self._split(parent, chunk_size=300, overlap=50)): | |
| child_docs.append(child) | |
| child_ids.append(f"{sid}_parent_{pidx:05d}_child_{cidx:03d}") | |
| child_metas.append({"session_id": sid, "source": self.source_name, | |
| "file_type": self.file_type, | |
| "parent_index": pidx, "child_index": cidx}) | |
| self.child_chunks = child_docs | |
| if child_docs: | |
| self.child_collection.add(ids=child_ids, documents=child_docs, | |
| metadatas=child_metas, embeddings=self._encode(child_docs)) | |
| # ── 工具函式 ───────────────────────────────────────── | |
| def _where(self) -> dict[str, str]: | |
| return {"session_id": self.session_id or ""} | |
| def _chroma_search(self, query: str, k: int, child: bool = False) -> list[dict[str, Any]]: | |
| if not self.session_id: | |
| return [] | |
| col = self.child_collection if child else self.collection | |
| results = col.query( | |
| query_embeddings=self._encode([query]), | |
| n_results=max(1, k), | |
| where=self._where(), | |
| include=["documents", "metadatas", "distances"], | |
| ) | |
| docs = results.get("documents", [[]])[0] or [] | |
| metas = results.get("metadatas", [[]])[0] or [] | |
| dists = results.get("distances", [[]])[0] or [] | |
| return [{"text": d, "metadata": m or {}, "distance": dist} | |
| for d, m, dist in zip(docs, metas, dists)] | |
| def _dedupe(self, chunks: list[str], k: int) -> list[str]: | |
| seen: set[str] = set() | |
| out: list[str] = [] | |
| for c in chunks: | |
| key = c[:120] | |
| if key not in seen: | |
| seen.add(key) | |
| out.append(c) | |
| if len(out) >= k: | |
| break | |
| return out | |
| def _llm(self, prompt: str, max_tokens: int = 300, temperature: float = 0.3) -> str | None: | |
| if not self.client: | |
| return None | |
| try: | |
| r = self.client.chat.completions.create( | |
| model="llama-3.1-8b-instant", | |
| messages=[{"role": "user", "content": prompt}], | |
| max_tokens=max_tokens, | |
| temperature=temperature, | |
| ) | |
| return r.choices[0].message.content | |
| except Exception: | |
| return None | |
| # ── 8 種策略 ────────────────────────────────────────── | |
| def s_semantic(self, query: str, k: int = 3) -> list[str]: | |
| return [r["text"] for r in self._chroma_search(query, k)] | |
| def s_tfidf(self, query: str, k: int = 3) -> list[str]: | |
| if self.tfidf_vectorizer is None or self.tfidf_matrix is None: | |
| return [] | |
| qv = self.tfidf_vectorizer.transform([query]) | |
| scores = (self.tfidf_matrix * qv.T).toarray().flatten() | |
| return [self.chunks[i] for i in scores.argsort()[-k:][::-1]] | |
| def s_hybrid(self, query: str, k: int = 3) -> list[str]: | |
| return self._dedupe( | |
| self.s_semantic(query, k * 2) + self.s_tfidf(query, k * 2), k | |
| ) | |
| def s_rerank(self, query: str, k: int = 3) -> list[str]: | |
| candidates = self.s_semantic(query, k * 2) | |
| if not self.client: | |
| return candidates[:k] | |
| scored: list[tuple[str, float]] = [] | |
| for chunk in candidates: | |
| prompt = (f"問題:{query}\n\n文本:{chunk[:500]}\n\n" | |
| f"請只輸出 0 到 10 的相關度分數(僅數字):") | |
| resp = self._llm(prompt, max_tokens=10, temperature=0) | |
| nums = re.findall(r"\d+(?:\.\d+)?", resp or "") | |
| scored.append((chunk, float(nums[0]) if nums else 0.0)) | |
| scored.sort(key=lambda x: x[1], reverse=True) | |
| return [c for c, _ in scored[:k]] | |
| def s_multi_query(self, query: str, k: int = 3) -> list[str]: | |
| queries = [query] | |
| prompt = f"將以下問題改寫成 3 個角度不同的繁體中文問題,每行一題,不加編號:\n{query}" | |
| resp = self._llm(prompt, max_tokens=200, temperature=0.7) | |
| if resp: | |
| extras = [ln.strip("-• 1234567890.、 ") for ln in resp.splitlines() if ln.strip()] | |
| queries += extras[:3] | |
| chunks: list[str] = [] | |
| for q in queries: | |
| chunks.extend(self.s_semantic(q, 2)) | |
| return self._dedupe(chunks, k) | |
| def s_compress(self, query: str, k: int = 3) -> list[str]: | |
| chunks = self.s_semantic(query, k) | |
| if not self.client: | |
| return chunks | |
| compressed = [] | |
| for chunk in chunks: | |
| prompt = (f"從以下文本中,提取與問題「{query}」最相關的 1-2 句," | |
| f"保留繁體中文,不要添加任何解釋:\n\n{chunk}") | |
| resp = self._llm(prompt, max_tokens=180, temperature=0) | |
| compressed.append((resp or "").strip() or chunk[:350]) | |
| return compressed | |
| def s_parent_child(self, query: str, k: int = 3) -> list[str]: | |
| hits = self._chroma_search(query, k * 3, child=True) | |
| seen_parents: list[int] = [] | |
| for h in hits: | |
| pidx = h.get("metadata", {}).get("parent_index") | |
| if isinstance(pidx, int) and pidx not in seen_parents: | |
| seen_parents.append(pidx) | |
| if len(seen_parents) >= k: | |
| break | |
| return [self.chunks[i] for i in seen_parents if 0 <= i < len(self.chunks)] | |
| def s_hyde(self, query: str, k: int = 3) -> list[str]: | |
| prompt = f"請對以下問題給出一段假設性簡短答案(繁體中文):\n{query}" | |
| hypo = self._llm(prompt, max_tokens=250, temperature=0.7) or query | |
| return self.s_semantic(hypo, k) | |
| # ── 策略路由 ────────────────────────────────────────── | |
| _FN = { | |
| "semantic": s_semantic, | |
| "tfidf": s_tfidf, | |
| "hybrid": s_hybrid, | |
| "rerank": s_rerank, | |
| "multi_query": s_multi_query, | |
| "compress": s_compress, | |
| "parent_child": s_parent_child, | |
| "hyde": s_hyde, | |
| } | |
| def generate_answer(self, query: str, strategy_key: str, top_k: int): | |
| if not self.chunks: | |
| return "請先上傳並載入 PDF 或 DOCX 文件。", "" | |
| if not query.strip(): | |
| return "請輸入問題。", "" | |
| fn = self._FN.get(strategy_key, self.s_semantic) | |
| chunks = fn(self, query, int(top_k)) | |
| context = "\n\n—\n\n".join(chunks) | |
| strategy_label = self.STRATEGY_MAP.get(strategy_key, strategy_key) | |
| source_preview = ( | |
| f"文件:{self.source_name}\n" | |
| f"策略:{strategy_label} · 片段數:{len(chunks)}\n" | |
| f"ChromaDB Session:{self.session_id}\n\n" | |
| f"{'─' * 56}\n\n{context}" | |
| ) | |
| if not self.client: | |
| return ( | |
| "⚠ 尚未設定 Groq API Key。", | |
| source_preview, | |
| ) | |
| prompt = f"""請根據以下上下文回答問題。若上下文無相關資訊,請明確說明無法從文件回答,不要自行編造。 | |
| 上下文: | |
| {context} | |
| 問題:{query} | |
| 請用繁體中文詳細回答,並以條列方式整理重點:""" | |
| try: | |
| r = self.client.chat.completions.create( | |
| model="llama-3.1-8b-instant", | |
| messages=[ | |
| {"role": "system", "content": "你是專業的文件分析與 RAG 問答助手。"}, | |
| {"role": "user", "content": prompt}, | |
| ], | |
| max_tokens=1024, | |
| temperature=0.3, | |
| ) | |
| return r.choices[0].message.content, source_preview | |
| except Exception as exc: | |
| return f"Error [{type(exc).__name__}]: {exc}", source_preview | |
| # ══════════════════════════════════════════════════════════ | |
| # Gradio UI - Nordic Dark (北歐極簡暗黑風格) | |
| # ══════════════════════════════════════════════════════════ | |
| STRATEGY_INFO = [ | |
| ("semantic", "語意搜尋", "ChromaDB 向量相似度,最通用", "🔍"), | |
| ("tfidf", "TF-IDF", "字元 n-gram 關鍵詞統計", "📊"), | |
| ("hybrid", "混合搜尋", "語意 + TF-IDF 結果合併去重", "⚡"), | |
| ("rerank", "重新排序", "LLM 對候選片段二次評分", "🎯"), | |
| ("multi_query", "多查詢擴展", "自動生成多角度問題聯合搜尋", "🔄"), | |
| ("compress", "上下文壓縮", "LLM 提取最相關句子精簡上下文", "✂️"), | |
| ("parent_child", "父子文檔", "小片段定位 → 回傳對應大片段", "📂"), | |
| ("hyde", "HyDE", "先生成假設答案再語意搜尋", "💡"), | |
| ] | |
| # 整合並套用 sky (極光藍) 與 slate (板岩灰) 主題變數,強制一般與 dark 模式顏色相同 | |
| NORDIC_DARK_THEME = gr.themes.Soft( | |
| primary_hue=gr.themes.colors.sky, | |
| neutral_hue=gr.themes.colors.slate, | |
| font=[gr.themes.GoogleFont("Outfit"), "Inter", "sans-serif"], | |
| ).set( | |
| # 全域背景與文字 | |
| body_background_fill="#0f172a", # slate-900 深藍黑背景 | |
| body_background_fill_dark="#0f172a", | |
| block_background_fill="#1e293b", # slate-800 元件卡片背景 | |
| block_background_fill_dark="#1e293b", | |
| body_text_color="#f8fafc", # slate-50 冰白文字 | |
| body_text_color_dark="#f8fafc", | |
| body_text_color_subdued="#94a3b8", # slate-400 冷灰文字 | |
| body_text_color_subdued_dark="#94a3b8", | |
| # 邊框線條 | |
| block_border_color="#334155", # slate-700 | |
| block_border_color_dark="#334155", | |
| border_color_primary="#334155", | |
| border_color_primary_dark="#334155", | |
| # Slider 控制條與按鈕基本配色 | |
| slider_color="#38bdf8", # sky-400 | |
| slider_color_dark="#38bdf8", | |
| button_primary_background_fill="#38bdf8", # sky-400 極光藍 | |
| button_primary_background_fill_dark="#38bdf8", | |
| button_primary_text_color="#0f172a", # 深藍黑字,保證可見度 | |
| button_primary_text_color_dark="#0f172a", | |
| button_primary_border_color="#38bdf8", | |
| button_primary_border_color_dark="#38bdf8", | |
| button_primary_background_fill_hover="#7dd3fc", # sky-300 | |
| button_primary_background_fill_hover_dark="#7dd3fc", | |
| button_secondary_background_fill="#334155", # slate-700 | |
| button_secondary_background_fill_dark="#334155", | |
| button_secondary_text_color="#f8fafc", | |
| button_secondary_text_color_dark="#f8fafc", | |
| ) | |
| # 自訂細節 CSS,強制鎖定 input 與 textarea 背景色與文字色以防止不可見問題 | |
| CSS = """ | |
| :root, body, .gradio-container { | |
| background-color: #0f172a !important; | |
| font-family: 'Outfit', 'Inter', system-ui, -apple-system, sans-serif; | |
| -webkit-font-smoothing: antialiased; | |
| } | |
| /* 強制輸入框與文字區域在任何狀態下的背景色與文字對比度 */ | |
| .gradio-container textarea, | |
| .gradio-container input[type=text], | |
| .gradio-container input[type=password], | |
| .gradio-container textarea:focus, | |
| .gradio-container input[type=text]:focus, | |
| .gradio-container input[type=password]:focus { | |
| background-color: #0f172a !important; | |
| color: #f8fafc !important; | |
| border: 1px solid #334155 !important; | |
| } | |
| /* 頂部 Header — 霧面玻璃質感 */ | |
| #hdr { | |
| background: rgba(30, 41, 59, 0.7); | |
| border: 1px solid #334155; | |
| border-radius: 16px; | |
| padding: 24px 32px; | |
| margin-bottom: 24px; | |
| border-top: 4px solid #38bdf8; | |
| backdrop-filter: blur(12px); | |
| box-shadow: 0 4px 20px rgba(0, 0, 0, 0.25); | |
| } | |
| .hdr-eyebrow { | |
| font-size: 11px; | |
| font-weight: 700; | |
| letter-spacing: 2px; | |
| color: #38bdf8; | |
| text-transform: uppercase; | |
| margin-bottom: 8px; | |
| } | |
| .hdr-title { | |
| font-size: 28px; | |
| font-weight: 800; | |
| color: #f8fafc; | |
| margin: 0 0 8px; | |
| } | |
| .hdr-sub { | |
| font-size: 14px; | |
| color: #94a3b8; | |
| } | |
| /* 標籤藥丸 (Pills) */ | |
| .pill { | |
| display: inline-block; | |
| margin: 8px 6px 0 0; | |
| padding: 4px 12px; | |
| border-radius: 20px; | |
| font-size: 11px; | |
| font-weight: 600; | |
| background: rgba(56, 189, 248, 0.1); | |
| color: #38bdf8; | |
| border: 1px solid rgba(56, 189, 248, 0.25); | |
| transition: all 0.2s ease; | |
| } | |
| .pill:hover { | |
| background: rgba(56, 189, 248, 0.18); | |
| } | |
| .pill-amber { | |
| background: rgba(245, 158, 11, 0.1); | |
| color: #f59e0b; | |
| border-color: rgba(245, 158, 11, 0.25); | |
| } | |
| .pill-amber:hover { | |
| background: rgba(245, 158, 11, 0.18); | |
| } | |
| .pill-blue { | |
| background: rgba(139, 92, 246, 0.1); | |
| color: #a78bfa; | |
| border-color: rgba(139, 92, 246, 0.25); | |
| } | |
| .pill-blue:hover { | |
| background: rgba(139, 92, 246, 0.18); | |
| } | |
| /* 設定區塊 — 科技感半透明框線 */ | |
| #apikey-box, #tgbox { | |
| background: rgba(30, 41, 59, 0.4) !important; | |
| border: 1px solid rgba(56, 189, 248, 0.2) !important; | |
| border-radius: 12px; | |
| padding: 16px; | |
| margin-bottom: 12px; | |
| box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.2); | |
| } | |
| #tgbox { | |
| border-color: rgba(139, 92, 246, 0.2) !important; | |
| } | |
| /* 輸入框 Focus 狀態邊框 */ | |
| .gradio-container textarea:focus, .gradio-container input[type=text]:focus { | |
| border-color: #38bdf8 !important; | |
| box-shadow: 0 0 0 2px rgba(56, 189, 248, 0.2) !important; | |
| } | |
| /* Radio 選擇器網格與選中樣式優化 */ | |
| #strategy-radio .wrap { | |
| display: grid !important; | |
| grid-template-columns: repeat(2, 1fr) !important; | |
| gap: 8px !important; | |
| } | |
| #strategy-radio label { | |
| background: #1e293b !important; | |
| border: 1px solid #334155 !important; | |
| border-radius: 10px !important; | |
| padding: 12px !important; | |
| cursor: pointer !important; | |
| transition: all 0.2s ease !important; | |
| color: #94a3b8 !important; | |
| } | |
| #strategy-radio label:hover { | |
| border-color: #38bdf8 !important; | |
| color: #f8fafc !important; | |
| background: #243146 !important; | |
| } | |
| /* 強制透過 checked 狀態與 has 選擇器匹配選中樣式,避免 Gradio 改版 class 遺失 */ | |
| #strategy-radio label.selected, | |
| #strategy-radio label:has(input[type=radio]:checked) { | |
| border-color: #38bdf8 !important; | |
| background: rgba(56, 189, 248, 0.08) !important; | |
| color: #38bdf8 !important; | |
| box-shadow: 0 0 0 1px #38bdf8 !important; | |
| } | |
| #strategy-radio input[type=radio]:checked + span { | |
| color: #38bdf8 !important; | |
| font-weight: 700 !important; | |
| } | |
| /* 左/右欄板塊背景與陰影 */ | |
| .card-box { | |
| background: #1e293b !important; | |
| border: 1px solid #334155 !important; | |
| border-radius: 16px !important; | |
| padding: 24px !important; | |
| box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -4px rgba(0, 0, 0, 0.3); | |
| } | |
| /* 分區標籤 */ | |
| .sec-label { | |
| font-size: 11px; | |
| font-weight: 700; | |
| letter-spacing: 1.5px; | |
| text-transform: uppercase; | |
| color: #64748b !important; | |
| margin: 20px 0 10px; | |
| border-left: 3px solid #38bdf8; | |
| padding-left: 8px; | |
| } | |
| /* 按鈕微動效 */ | |
| #ask-btn, #apply-key-btn, #apply-tg-btn { | |
| transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1) !important; | |
| } | |
| #ask-btn:hover { | |
| transform: translateY(-1px); | |
| box-shadow: 0 4px 12px rgba(56, 189, 248, 0.3) !important; | |
| } | |
| /* 確保 Accordion 內容展開時也是暗色底 */ | |
| .accordion { | |
| background: #1e293b !important; | |
| border: 1px solid #334155 !important; | |
| } | |
| """ | |
| HEADER_HTML = """ | |
| <div id="hdr"> | |
| <div class="hdr-eyebrow">Intelligent Document Analysis · v3</div> | |
| <div class="hdr-title">多策略 RAG 文件問答系統</div> | |
| <div class="hdr-sub">支援 PDF / DOCX 上傳,採用 ChromaDB 持久化向量資料庫、8 種 RAG 策略,並可推送答案至 Telegram</div> | |
| <div> | |
| <span class="pill">▸ Groq API</span> | |
| <span class="pill">▸ llama-3.1-8b-instant</span> | |
| <span class="pill pill-amber">▸ ChromaDB</span> | |
| <span class="pill pill-amber">▸ PDF / DOCX</span> | |
| <span class="pill">▸ SentenceTransformers</span> | |
| <span class="pill pill-blue">▸ Telegram Bot</span> | |
| </div> | |
| </div> | |
| """ | |
| EXAMPLE_QS = [ | |
| ["這份文件的主要內容是什麼?"], | |
| ["文件中提到哪些重要概念或定義?"], | |
| ["有哪些關鍵數據、統計資料或案例?"], | |
| ["文件的結論或建議是什麼?"], | |
| ["文件提及哪些潛在風險或挑戰?"], | |
| ] | |
| def is_hf_spaces() -> bool: | |
| """偵測是否在 Hugging Face Spaces 容器中執行""" | |
| return "SPACE_ID" in os.environ or "SPACES_CONTAINER" in os.environ | |
| def create_interface(): | |
| env_key = os.getenv("GROQ_API_KEY", "").strip() | |
| # Hugging Face Spaces 上絕對不使用硬編碼預設 Token,僅從環境變數讀取;本機端則保留示範值方便調試 | |
| if is_hf_spaces(): | |
| env_tg_token = os.getenv("TELEGRAM_BOT_TOKEN", "").strip() | |
| env_tg_chat = os.getenv("TELEGRAM_CHAT_ID", "").strip() | |
| env_tg_url = os.getenv("TELEGRAM_API_URL", "https://api.telegram.org").strip() | |
| else: | |
| env_tg_token = os.getenv("TELEGRAM_BOT_TOKEN", TELEGRAM_BOT_TOKEN).strip() | |
| env_tg_chat = os.getenv("TELEGRAM_CHAT_ID", TELEGRAM_CHAT_ID).strip() | |
| env_tg_url = os.getenv("TELEGRAM_API_URL", "https://api.telegram.org").strip() | |
| rag = MultiStrategyRAG(chroma_path="./chroma_db") | |
| tg = TelegramNotifier(token=env_tg_token, chat_id=env_tg_chat, api_url=env_tg_url) | |
| if env_key: | |
| rag.set_api_key(env_key) | |
| # ── 事件函式 ────────────────────────────────────────── | |
| def apply_api_key(api_key: str) -> str: | |
| key = (api_key or "").strip() | |
| rag.set_api_key(key) | |
| if key: | |
| masked = key[:8] + "****" + key[-4:] if len(key) > 12 else "****" | |
| return f"✓ API Key 已套用({masked})" | |
| return "⚠ API Key 已清除,無法呼叫 LLM" | |
| def apply_telegram(token: str, chat_id: str, api_url: str) -> str: | |
| """套用並驗證 Telegram 設定。""" | |
| return tg.configure(token, chat_id, api_url) | |
| def upload_document(file) -> str: | |
| if file is None: | |
| return "⚠ 請選擇 PDF 或 DOCX 檔案" | |
| return rag.load_document(file.name) | |
| def ask_and_push(query: str, strategy_key: str, top_k: int, send_to_tg: bool) -> tuple[str, str, str]: | |
| """ | |
| 提問 → 取得答案 → 若勾選則推送至 Telegram。 | |
| strategy_key 直接來自 gr.Radio,不依賴 closure dict。 | |
| """ | |
| sk = strategy_key or "semantic" | |
| answer, source_preview = rag.generate_answer(query, sk, int(top_k)) | |
| push_status = "(未推送)" | |
| if send_to_tg: | |
| strategy_name = dict( | |
| (k, n) for k, n, *_ in STRATEGY_INFO | |
| ).get(sk, sk) | |
| tg_message = ( | |
| f"📄 *文件問答結果*\n" | |
| f"文件:{rag.source_name or 'N/A'}\n" | |
| f"策略:{strategy_name}\n\n" | |
| f"❓ *問題*\n{query}\n\n" | |
| f"💬 *答案*\n{answer}" | |
| ) | |
| ok, push_status = tg.send(tg_message) | |
| return answer, source_preview, push_status | |
| # ── UI 佈局 ─────────────────────────────────────────── | |
| with gr.Blocks( | |
| title="多策略 RAG 文件問答 v3", | |
| css=CSS, | |
| theme=NORDIC_DARK_THEME, # 套用全新的北歐極簡暗黑主題 | |
| ) as demo: | |
| gr.HTML(HEADER_HTML) | |
| with gr.Row(equal_height=False): | |
| # ── 左欄 ────────────────────────────────── | |
| with gr.Column(scale=1, min_width=320, elem_classes="card-box"): | |
| # Step 00:Groq API Key | |
| gr.HTML("<div class='sec-label'>Step 00 · Groq API Key</div>") | |
| with gr.Group(elem_id="apikey-box"): | |
| api_key_input = gr.Textbox( | |
| label="", | |
| placeholder="gsk_xxxxxxxxxxxxxxxxxxxxxxxx", | |
| value=env_key, | |
| type="password", | |
| lines=1, | |
| show_label=False, | |
| ) | |
| apply_key_btn = gr.Button("套用 API Key", size="sm", elem_id="apply-key-btn") | |
| api_key_status = gr.Textbox( | |
| value="✓ API Key 已從環境變數載入" if env_key else "⚠ 尚未設定 API Key", | |
| interactive=False, | |
| lines=1, | |
| label="", | |
| show_label=False, | |
| ) | |
| # Step 01:Telegram 設定 | |
| gr.HTML("<div class='sec-label'>Step 01 · Telegram 設定</div>") | |
| with gr.Group(elem_id="tgbox"): | |
| tg_token_input = gr.Textbox( | |
| label="Bot Token", | |
| placeholder="123456789:ABCdefGhIJKlmNoPQRstUVwxyZ", | |
| value=env_tg_token, | |
| type="password", | |
| lines=1, | |
| ) | |
| tg_chat_input = gr.Textbox( | |
| label="Chat ID", | |
| placeholder="987654321", | |
| value=env_tg_chat, | |
| lines=1, | |
| ) | |
| tg_url_input = gr.Textbox( | |
| label="Telegram API 代理 (選填,連線超時可使用)", | |
| placeholder="https://api.telegram.org", | |
| value=env_tg_url, | |
| lines=1, | |
| ) | |
| apply_tg_btn = gr.Button("連線驗證", size="sm", elem_id="apply-tg-btn") | |
| tg_status = gr.Textbox( | |
| value="✓ Telegram 已從環境變數載入" if (env_tg_token and env_tg_chat) else "⚠ 尚未設定 Telegram", | |
| interactive=False, | |
| lines=1, | |
| label="", | |
| show_label=False, | |
| ) | |
| # Step 02:上傳文件 | |
| gr.HTML("<div class='sec-label'>Step 02 · 上傳文件</div>") | |
| file_input = gr.File(label="PDF / DOCX", file_types=[".pdf", ".docx"]) | |
| load_btn = gr.Button("↑ 載入文件") | |
| doc_status = gr.Textbox(label="狀態", interactive=False, lines=3) | |
| # Step 03:RAG 策略 (Radio) | |
| gr.HTML("<div class='sec-label'>Step 03 · 選擇 RAG 策略</div>") | |
| strategy_radio = gr.Radio( | |
| choices=[ | |
| ("🔍 語意搜尋 — ChromaDB 向量相似度", "semantic"), | |
| ("📊 TF-IDF — 字元 n-gram 關鍵詞", "tfidf"), | |
| ("⚡ 混合搜尋 — 語意 + TF-IDF 合併", "hybrid"), | |
| ("🎯 重新排序 — LLM 二次評分", "rerank"), | |
| ("🔄 多查詢擴展 — 自動生成多角度問題", "multi_query"), | |
| ("✂️ 上下文壓縮 — LLM 提取關鍵句", "compress"), | |
| ("📂 父子文檔 — 小片段定位大片段", "parent_child"), | |
| ("💡 HyDE — 先生成假設答案再搜尋", "hyde"), | |
| ], | |
| value="semantic", | |
| label="", | |
| elem_id="strategy-radio", | |
| ) | |
| # Step 04:參數 | |
| gr.HTML("<div class='sec-label'>Step 04 · 搜尋參數</div>") | |
| topk = gr.Slider(minimum=1, maximum=10, value=3, step=1, label="Top-K 片段數量") | |
| # ── 右欄:問答 ──────────────────────────── | |
| with gr.Column(scale=2, elem_classes="card-box"): | |
| gr.HTML("<div class='sec-label'>Step 05 · 輸入問題</div>") | |
| qin = gr.Textbox( | |
| label="", | |
| placeholder="例如:這份文件的核心論點是什麼?", | |
| lines=4, | |
| ) | |
| # Telegram 推送選項 | |
| send_tg_checkbox = gr.Checkbox( | |
| label="📤 提問後自動推送答案至 Telegram", | |
| value=False, | |
| ) | |
| ask_btn = gr.Button("提問", variant="primary", size="lg", elem_id="ask-btn") | |
| gr.HTML("<div class='sec-label'>AI 回答</div>") | |
| ans = gr.Textbox(label="", lines=12, interactive=False) | |
| # Telegram 推送狀態 | |
| push_status_box = gr.Textbox( | |
| label="Telegram 推送狀態", | |
| interactive=False, | |
| lines=1, | |
| ) | |
| with gr.Accordion("▸ 查看檢索到的文本片段", open=False): | |
| src = gr.Textbox(label="", lines=10, interactive=False) | |
| gr.Examples(examples=EXAMPLE_QS, inputs=qin, label="範例問題") | |
| # ── 事件綁定 ────────────────────────────────── | |
| apply_key_btn.click(fn=apply_api_key, inputs=[api_key_input], outputs=[api_key_status]) | |
| api_key_input.submit(fn=apply_api_key, inputs=[api_key_input], outputs=[api_key_status]) | |
| apply_tg_btn.click(fn=apply_telegram, inputs=[tg_token_input, tg_chat_input, tg_url_input], outputs=[tg_status]) | |
| load_btn.click(fn=upload_document, inputs=[file_input], outputs=[doc_status]) | |
| ask_btn.click( | |
| fn=ask_and_push, | |
| inputs=[qin, strategy_radio, topk, send_tg_checkbox], | |
| outputs=[ans, src, push_status_box], | |
| ) | |
| qin.submit( | |
| fn=ask_and_push, | |
| inputs=[qin, strategy_radio, topk, send_tg_checkbox], | |
| outputs=[ans, src, push_status_box], | |
| ) | |
| return demo | |
| if __name__ == "__main__": | |
| demo = create_interface() | |
| demo.launch(share=False, server_name="0.0.0.0") | |