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")