Spaces:
Sleeping
Sleeping
File size: 26,913 Bytes
a615373 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 | """
ๅค็ญ็ฅ RAG ๆไปถๅ็ญ็ณป็ตฑ v2 โ ChromaDB + PDF/DOCX ็ๆฌ๏ผๅชๅ็๏ผ
ๅฎ่ฃไพ่ณด๏ผ
pip install gradio groq pypdf python-docx sentence-transformers numpy chromadb scikit-learn
ๅท่ก๏ผ
python multistrategy_rag_chromadb_docx_v2.py
"""
from __future__ import annotations
import os
import re
import time
from pathlib import Path
from typing import Any
import chromadb
import gradio as gr
import numpy as np
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
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# RAG ๆ ธๅฟ้่ผฏ๏ผๅชๅ็๏ผ
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
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",
):
# API client ๆน็บ None๏ผ็ฑไฝฟ็จ่
้้ UI ่ผธๅ
ฅๅพๅๆ
ๅปบ็ซ
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:
"""ๅๆ
่จญๅฎ Groq API Key๏ผๅปบ็ซๆๆดๆฐ clientใ"""
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 "โ ่ผๅ
ฅๅคฑๆ๏ผๆไปถๆฒๆๅฏๆทๅๆๅญ๏ผๅฏ่ฝๆฏๆๆๅ็ๆช๏ผ้ๅ
OCR"
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ใ\n"
"่ซๅจๅทฆๆฌใStep 00ใ่ผธๅ
ฅๆจ็ Groq API Key ไธฆ้ปๆใๅฅ็จใๅพๅๆๅใ\n\n"
"๏ผๆชข็ดขๅทฒๅฎๆ๏ผๅฏๅจไธๆนใๆฅ็ๆชข็ดขๅฐ็ๆๆฌ็ๆฎตใ็ขบ่ช็ตๆ๏ผ",
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"็ๆๅคฑๆ๏ผ{type(exc).__name__}: {exc}", source_preview
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Gradio UI
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
STRATEGY_INFO = [
("semantic", "่ชๆๆๅฐ", "ChromaDB ๅ้็ธไผผๅบฆ๏ผๆ้็จ", "๐"),
("tfidf", "TF-IDF", "ๅญๅ
n-gram ้้ต่ฉ็ตฑ่จ", "๐"),
("hybrid", "ๆททๅๆๅฐ", "่ชๆ + TF-IDF ็ตๆๅไฝตๅป้", "โก"),
("rerank", "้ๆฐๆๅบ", "LLM ๅฐๅ้ธ็ๆฎตไบๆฌก่ฉๅ", "๐ฏ"),
("multi_query", "ๅคๆฅ่ฉขๆดๅฑ", "่ชๅ็ๆๅค่งๅบฆๅ้ก่ฏๅๆๅฐ", "๐"),
("compress", "ไธไธๆๅฃ็ธฎ", "LLM ๆๅๆ็ธ้ๅฅๅญ็ฒพ็ฐกไธไธๆ", "โ๏ธ"),
("parent_child", "็ถๅญๆๆช", "ๅฐ็ๆฎตๅฎไฝ โ ๅๅณๅฐๆๅคง็ๆฎต", "๐"),
("hyde", "HyDE", "ๅ
็ๆๅ่จญ็ญๆกๅ่ชๆๆๅฐ", "๐ก"),
]
CSS = """
body, .gradio-container { background:#f5f4f1 !important; }
#hdr {
background:#fff;
border:1px solid #e5e0d8;
border-radius:14px;
padding:28px 36px;
margin-bottom:20px;
border-top: 4px solid #2d6a4f;
}
.hdr-eyebrow { font-size:11px; letter-spacing:2.5px; color:#2d6a4f; text-transform:uppercase; margin-bottom:6px; }
.hdr-title { font-size:26px; font-weight:700; color:#1a1714; margin:0 0 6px; }
.hdr-sub { font-size:14px; color:#6b5e56; }
.pill { display:inline-block; margin:10px 5px 0 0; padding:3px 10px; border-radius:16px;
font-size:11px; background:#e8f4f0; color:#2d6a4f; border:1px solid rgba(45,106,79,.2); }
.pill-amber { background:#fdf4e3; color:#b87a1a; border-color:rgba(184,122,26,.25); }
/* API Key ๅๅก */
#apikey-box {
background: #fffbf2;
border: 1.5px solid #f0c96a;
border-radius: 10px;
padding: 12px 14px;
margin-bottom: 8px;
}
.strat-grid { display:grid; grid-template-columns:repeat(4,1fr); gap:10px; margin:10px 0 16px; }
.strat-card {
background:#fff;
border:1.5px solid #e5e0d8;
border-radius:10px;
padding:10px 12px;
cursor:pointer;
transition:border-color .15s, box-shadow .15s;
text-align:left;
width:100%;
}
.strat-card:hover { border-color:#2d6a4f; box-shadow:0 2px 8px rgba(45,106,79,.12); }
.strat-card.active { border-color:#2d6a4f; background:#f0f9f5; box-shadow:0 2px 10px rgba(45,106,79,.18); }
.strat-icon { font-size:20px; margin-bottom:4px; }
.strat-name { font-size:13px; font-weight:700; color:#1a1714; margin:0 0 2px; }
.strat-desc { font-size:11px; color:#7a6e67; line-height:1.4; }
.sec-label { font-size:11px; letter-spacing:1.5px; text-transform:uppercase;
color:#7a6e67; font-weight:700; margin:16px 0 8px; }
.card-box { background:#fff !important; border:1px solid #e5e0d8 !important;
border-radius:12px !important; padding:16px !important; }
#ask-btn { background:#2d6a4f !important; color:#fff !important; border:0 !important; border-radius:8px !important; }
#apply-key-btn { background:#b87a1a !important; color:#fff !important; border:0 !important; border-radius:8px !important; }
"""
HEADER_HTML = """
<div id="hdr">
<div class="hdr-eyebrow">Intelligent Document Analysis ยท v2</div>
<div class="hdr-title">ๅค็ญ็ฅ RAG ๆไปถๅ็ญ็ณป็ตฑ</div>
<div class="hdr-sub">ๆฏๆด PDF / DOCX ไธๅณ๏ผๆก็จ ChromaDB ๆไน
ๅๅ้่ณๆๅบซ่ 8 ็จฎ RAG ๆชข็ดข็ญ็ฅ</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>
</div>
</div>
"""
def build_strategy_menu(selected: str = "semantic") -> str:
cards = []
for key, name, desc, icon in STRATEGY_INFO:
active_cls = "active" if key == selected else ""
cards.append(
f"""<button class="strat-card {active_cls}" onclick="selectStrategy('{key}', this)" type="button">
<div class="strat-icon">{icon}</div>
<div class="strat-name">{name}</div>
<div class="strat-desc">{desc}</div>
</button>"""
)
return f'<div class="strat-grid">{"".join(cards)}</div>'
STRATEGY_MENU_JS = """
<script>
function selectStrategy(key, el) {
document.querySelectorAll('.strat-card').forEach(c => c.classList.remove('active'));
el.classList.add('active');
const inp = document.getElementById('strategy-hidden');
if (inp) { inp.value = key; inp.dispatchEvent(new Event('input')); }
}
</script>
"""
EXAMPLE_QS = [
["้ไปฝๆไปถ็ไธป่ฆๅ
งๅฎนๆฏไป้บผ๏ผ"],
["ๆไปถไธญๆๅฐๅชไบ้่ฆๆฆๅฟตๆๅฎ็พฉ๏ผ"],
["ๆๅชไบ้้ตๆธๆใ็ตฑ่จ่ณๆๆๆกไพ๏ผ"],
["ๆไปถ็็ต่ซๆๅปบ่ญฐๆฏไป้บผ๏ผ"],
["ๆไปถๆๅๅชไบๆฝๅจ้ขจ้ชๆๆๆฐ๏ผ"],
]
def create_interface():
# ๅๅๆๅ่ฉฆๅพ็ฐๅข่ฎๆธ่ฎๅ๏ผๅฏ็็ฉบ๏ผ
env_key = os.getenv("GROQ_API_KEY", "").strip()
rag = MultiStrategyRAG(chroma_path="./chroma_db")
if env_key:
rag.set_api_key(env_key)
current_strategy = {"key": "semantic"}
def apply_api_key(api_key: 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 upload_document(file):
if file is None:
return "โ ่ซ้ธๆ PDF ๆ DOCX ๆชๆก"
return rag.load_document(file.name)
def set_strategy(key: str):
current_strategy["key"] = key
return f"โ ๅทฒ้ธๆ็ญ็ฅ๏ผ{dict((k, n) for k, n, *_ in STRATEGY_INFO).get(key, key)}"
def ask(query, top_k):
return rag.generate_answer(query, current_strategy["key"], int(top_k))
with gr.Blocks(
title="ๅค็ญ็ฅ RAG ๆไปถๅ็ญ v2",
css=CSS,
theme=gr.themes.Base(
primary_hue=gr.themes.colors.green,
neutral_hue=gr.themes.colors.stone,
),
) 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๏ผ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๏ผไธๅณๆไปถ
gr.HTML("<div class='sec-label'>Step 01 ยท ไธๅณๆไปถ</div>")
file_input = gr.File(label="PDF / DOCX", file_types=[".pdf", ".docx"])
load_btn = gr.Button("โ ่ผๅ
ฅๆไปถ")
status = gr.Textbox(label="็ๆ
", interactive=False, lines=3)
# Step 02๏ผRAG ็ญ็ฅ
gr.HTML("<div class='sec-label'>Step 02 ยท ้ธๆ RAG ็ญ็ฅ</div>")
gr.HTML(build_strategy_menu("semantic"))
strategy_input = gr.Textbox(
value="semantic",
elem_id="strategy-hidden",
label="",
visible=False,
)
strategy_status = gr.Textbox(
value="โ ๅทฒ้ธๆ็ญ็ฅ๏ผ่ชๆๆๅฐ",
interactive=False,
lines=1,
label="็ฎๅ็ญ็ฅ",
)
gr.HTML(STRATEGY_MENU_JS)
# Step 03๏ผๅๆธ
gr.HTML("<div class='sec-label'>Step 03 ยท ๆๅฐๅๆธ</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 04 ยท ่ผธๅ
ฅๅ้ก</div>")
qin = gr.Textbox(
label="",
placeholder="ไพๅฆ๏ผ้ไปฝๆไปถ็ๆ ธๅฟ่ซ้ปๆฏไป้บผ๏ผ",
lines=4,
)
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)
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])
load_btn.click(fn=upload_document, inputs=[file_input], outputs=[status])
strategy_input.change(fn=set_strategy, inputs=[strategy_input], outputs=[strategy_status])
ask_btn.click(fn=ask, inputs=[qin, topk], outputs=[ans, src])
qin.submit(fn=ask, inputs=[qin, topk], outputs=[ans, src])
return demo
if __name__ == "__main__":
demo = create_interface()
demo.launch(share=False, server_name="0.0.0.0") |