File size: 30,239 Bytes
15e0bb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78d3f12
15e0bb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
"""
ๅคš็ญ–็•ฅ RAG ๆ–‡ไปถๅ•็ญ”็ณป็ตฑ v2 โ€” ChromaDB + PDF/DOCX ็‰ˆๆœฌ๏ผˆๅซ Telegram ๆŽจ้€๏ผ‰

ๅฎ‰่ฃไพ่ณด๏ผš
    pip install gradio groq pypdf python-docx sentence-transformers numpy chromadb scikit-learn requests
"""

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
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 ๆŽจ้€่จญๅฎš
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
DEFAULT_TELEGRAM_CHAT_ID = "8699604284"
TELEGRAM_MAX_LEN = 4000  # Telegram ่จŠๆฏ้•ทๅบฆ้™ๅˆถ (4096)๏ผŒ็•™ไธ€ไบ›็ทฉ่ก


def send_telegram_message(text: str, chat_id: str, token: str) -> dict:
    """ๅฐ‡ๆ–‡ๅญ—่จŠๆฏ้€ๅˆฐ Telegramใ€‚่‹ฅๆ–‡ๅญ—้Ž้•ทๆœƒ่‡ชๅ‹•ๅˆ†ๆฎตๅ‚ณ้€ใ€‚"""
    if not token:
        return {"ok": False, "error": "ๅฐšๆœชๆไพ› Bot Token"}
    if not chat_id:
        return {"ok": False, "error": "ๅฐšๆœชๆไพ› Chat ID"}
    if not text:
        return {"ok": False, "error": "empty text"}

    url = f"https://api.telegram.org/bot{token}/sendMessage"
    results = []
    for i in range(0, len(text), TELEGRAM_MAX_LEN):
        chunk = text[i:i + TELEGRAM_MAX_LEN]
        try:
            r = requests.post(url, data={"chat_id": chat_id, "text": chunk}, timeout=30)
            results.append(r.json())
        except Exception as exc:
            results.append({"ok": False, "error": f"{type(exc).__name__}: {exc}"})
    return results[-1] if results else {"ok": False, "error": "no chunks sent"}


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
#  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",
    ):
        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 "โœ— ่ผ‰ๅ…ฅๅคฑๆ•—๏ผšๆ–‡ไปถๆฒ’ๆœ‰ๅฏๆ“ทๅ–ๆ–‡ๅญ—๏ผŒๅฏ่ƒฝๆ˜ฏๆŽƒๆๅœ–็‰‡ๆช”๏ผŒ้œ€ๅ…ˆ 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 01ใ€่ผธๅ…ฅๆ‚จ็š„ 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",       "ๅ…ˆ็”Ÿๆˆๅ‡่จญ็ญ”ๆกˆๅ†่ชžๆ„ๆœๅฐ‹"),
]

# ้กฏ็คบ็”จ label -> ๅ…ง้ƒจ key ๅฐ็…ง่กจ
STRATEGY_LABEL_TO_KEY = {label: key for key, label, _ in STRATEGY_INFO}
STRATEGY_CHOICES = [label for _, label, _ in STRATEGY_INFO]
STRATEGY_DESC_HTML = "<br>".join(f"<b>{label}</b> โ€” {desc}" for _, label, desc in STRATEGY_INFO)

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;
}

/* Telegram ๅ€ๅกŠ */
#telegram-box {
    background: #eef6ff;
    border: 1.5px solid #8ec4f0;
    border-radius: 10px;
    padding: 12px 14px;
    margin-bottom: 8px;
}

/* ็ญ–็•ฅ้ธๆ“‡ๅ€ๅกŠ */
#strategy-box {
    background:#fff;
    border:1.5px solid #e5e0d8;
    border-radius:10px;
    padding:10px 12px;
    margin-bottom: 8px;
}
#strategy-box .wrap { gap:6px !important; }
#strategy-box label {
    border:1.5px solid #e5e0d8 !important;
    border-radius:8px !important;
    padding:8px 10px !important;
    margin:0 !important;
    transition: border-color .15s, background .15s;
}
#strategy-box label:hover { border-color:#2d6a4f !important; }
#strategy-desc { font-size:11px; color:#7a6e67; line-height:1.6; margin-top:6px; }

.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; }
#send-tg-btn { background:#0088cc !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 ๆชข็ดข็ญ–็•ฅ๏ผŒไธฆๅฏๅฐ‡็ตๆžœๆŽจ้€่‡ณ 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">โ–ธ Telegram</span>
  </div>
</div>
"""

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"}
    # ๆšซๅญ˜ๆœ€่ฟ‘ไธ€ๆฌกๅ›ž็ญ” / ไพ†ๆบ็‰‡ๆฎต๏ผŒไพ› Telegram ๆŽจ้€ไฝฟ็”จ
    last_result = {"answer": "", "source": ""}

    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(label: str):
        key = STRATEGY_LABEL_TO_KEY.get(label, "semantic")
        current_strategy["key"] = key
        return f"โœ“ ๅทฒ้ธๆ“‡็ญ–็•ฅ๏ผš{label}"

    def ask(query, top_k):
        answer, source = rag.generate_answer(query, current_strategy["key"], int(top_k))
        last_result["answer"] = answer or ""
        last_result["source"] = source or ""
        return answer, source

    def push_to_telegram(include_source: bool, chat_id_input: str, token_input: str):
        if not last_result["answer"]:
            return "โš  ๅฐš็„กๅฏๆŽจ้€็š„ๅ›ž็ญ”๏ผŒ่ซ‹ๅ…ˆๆๅ•ใ€‚"

        token = (token_input or "").strip()
        if not token:
            return "โš  ่ซ‹ๅ…ˆ่ผธๅ…ฅ Telegram Bot Token"

        chat_id = (chat_id_input or "").strip() or DEFAULT_TELEGRAM_CHAT_ID

        text = f"๐Ÿ“„ ๆ–‡ไปถ๏ผš{rag.source_name or 'ๆœช็Ÿฅ'}\n"
        text += f"โ“ ็ญ–็•ฅ๏ผš{rag.STRATEGY_MAP.get(current_strategy['key'], current_strategy['key'])}\n\n"
        text += f"๐Ÿ’ฌ ๅ›ž็ญ”๏ผš\n{last_result['answer']}"

        if include_source:
            text += f"\n\nโ€” ๆชข็ดข็‰‡ๆฎต โ€”\n{last_result['source']}"

        result = send_telegram_message(text, chat_id=chat_id, token=token)
        if result.get("ok"):
            return "โœ“ ๅทฒๆˆๅŠŸๆŽจ้€่‡ณ Telegram"
        return f"โœ— ๆŽจ้€ๅคฑๆ•—๏ผš{result.get('description') or result.get('error') or result}"

    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 ยท Telegram ๆŽจ้€๏ผˆ็งป่‡ณๆœ€ไธŠๆ–น๏ผŒ้ฟๅ…ๆ‰พไธๅˆฐ๏ผ‰
                gr.HTML("<div class='sec-label'>Step 00 ยท Telegram ๆŽจ้€</div>")
                with gr.Group(elem_id="telegram-box"):
                    tg_token = gr.Textbox(
                        label="Bot Token",
                        placeholder="ไพ‹ๅฆ‚๏ผš123456789:AAAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                        type="password",
                        lines=1,
                    )
                    tg_chat_id = gr.Textbox(
                        label="Chat ID",
                        placeholder=f"้ ่จญ๏ผš{DEFAULT_TELEGRAM_CHAT_ID}๏ผˆ็•™็ฉบไฝฟ็”จๆญค้ ่จญๅ€ผ๏ผ‰",
                        lines=1,
                    )
                    tg_include_source = gr.Checkbox(
                        label="ๅŒๆ™‚ๆŽจ้€ๆชข็ดข็‰‡ๆฎตๅ…งๅฎน", value=False
                    )
                    send_tg_btn = gr.Button(
                        "๐Ÿ“จ ๆŽจ้€ๅ›ž็ญ”ๅˆฐ Telegram", elem_id="send-tg-btn"
                    )
                    tg_status = gr.Textbox(
                        label="ๆŽจ้€็‹€ๆ…‹", interactive=False, lines=1
                    )

                # Step 01๏ผšGroq API Key
                gr.HTML("<div class='sec-label'>Step 01 ยท 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 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("โ†‘ ่ผ‰ๅ…ฅๆ–‡ไปถ")
                status = gr.Textbox(label="็‹€ๆ…‹", interactive=False, lines=3)

                # Step 03๏ผšRAG ็ญ–็•ฅ๏ผˆๆ”น็”จ Radio๏ผŒๅฏๆญฃๅธธ้ปž้ธ๏ผ‰
                gr.HTML("<div class='sec-label'>Step 03 ยท ้ธๆ“‡ RAG ็ญ–็•ฅ</div>")
                with gr.Group(elem_id="strategy-box"):
                    strategy_radio = gr.Radio(
                        choices=STRATEGY_CHOICES,
                        value=STRATEGY_CHOICES[0],
                        label="",
                        show_label=False,
                    )
                    gr.HTML(f"<div id='strategy-desc'>{STRATEGY_DESC_HTML}</div>")
                strategy_status = gr.Textbox(
                    value=f"โœ“ ๅทฒ้ธๆ“‡็ญ–็•ฅ๏ผš{STRATEGY_CHOICES[0]}",
                    interactive=False,
                    lines=1,
                    label="็›ฎๅ‰็ญ–็•ฅ",
                )

                # 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,
                )
                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_radio.change(fn=set_strategy, inputs=[strategy_radio], outputs=[strategy_status])
        ask_btn.click(fn=ask, inputs=[qin, topk], outputs=[ans, src])
        qin.submit(fn=ask, inputs=[qin, topk], outputs=[ans, src])
        send_tg_btn.click(
            fn=push_to_telegram,
            inputs=[tg_include_source, tg_chat_id, tg_token],
            outputs=[tg_status],
        )

    return demo


if __name__ == "__main__":
    demo = create_interface()
    demo.launch(share=False, server_name="0.0.0.0")