File size: 19,018 Bytes
d0af001
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Streamlit + Groq API - 8็จฎ RAG ็ญ–็•ฅ PDF ๅ•็ญ”็ณป็ตฑ
ๅฎ‰่ฃไพ่ณด๏ผšpip install streamlit groq pypdf sentence-transformers numpy faiss-cpu scikit-learn
ๅŸท่กŒๆ–นๅผ๏ผšstreamlit run rag_streamlit.py
"""

import streamlit as st
from groq import Groq
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss
from pypdf import PdfReader
import re
from sklearn.feature_extraction.text import TfidfVectorizer
import tempfile
import os

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ้ ้ข่จญๅฎš
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
st.set_page_config(
    page_title="ๅคš็ญ–็•ฅ RAG PDF ๅ•็ญ”็ณป็ตฑ",
    page_icon="๐Ÿค–",
    layout="wide",
    initial_sidebar_state="expanded",
)

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ่‡ช่จ‚ๆจฃๅผ
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
st.markdown("""
<style>
    /* ๅ…จๅŸŸๅญ—้ซ” & ่ƒŒๆ™ฏ */
    html, body, [class*="css"] {
        font-family: 'Segoe UI', sans-serif;
    }
    .main { background-color: #f8f9fb; }

    /* ๆจ™้กŒๅก็‰‡ */
    .hero {
        background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
        border-radius: 16px;
        padding: 2rem 2.5rem;
        color: white;
        margin-bottom: 1.5rem;
    }
    .hero h1 { margin: 0; font-size: 2rem; letter-spacing: -0.5px; }
    .hero p  { margin: 0.5rem 0 0; opacity: 0.75; font-size: 1rem; }

    /* ๅ€ๅกŠๅก็‰‡ */
    .card {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        box-shadow: 0 2px 12px rgba(0,0,0,0.06);
        margin-bottom: 1.2rem;
    }

    /* ็ญ”ๆกˆๅ€ */
    .answer-box {
        background: #f0f7ff;
        border-left: 4px solid #2563eb;
        border-radius: 8px;
        padding: 1.2rem 1.5rem;
        white-space: pre-wrap;
        line-height: 1.75;
        font-size: 0.95rem;
    }

    /* ็ญ–็•ฅๅพฝ็ซ  */
    .badge {
        display: inline-block;
        background: #e0e7ff;
        color: #3730a3;
        border-radius: 6px;
        padding: 2px 10px;
        font-size: 0.82rem;
        font-weight: 600;
        margin-bottom: 0.5rem;
    }

    /* ไพ†ๆบๆ–‡ๆœฌ */
    .source-chunk {
        background: #fafafa;
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        padding: 0.9rem 1.1rem;
        margin-bottom: 0.8rem;
        font-size: 0.85rem;
        line-height: 1.65;
        color: #374151;
    }
    .chunk-label {
        font-weight: 700;
        color: #6b7280;
        font-size: 0.75rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 4px;
    }

    /* ็‹€ๆ…‹ๆฌ„ */
    .status-ok   { color: #16a34a; font-weight: 600; }
    .status-err  { color: #dc2626; font-weight: 600; }
    .status-warn { color: #d97706; font-weight: 600; }

    div[data-testid="stExpander"] { border-radius: 10px; }
</style>
""", unsafe_allow_html=True)


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# RAG ๆ ธๅฟƒ้กžๅˆฅ
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
class MultiStrategyRAG:
    def __init__(self, api_key: str):
        self.client = Groq(api_key=api_key)
        self.embedding_model = SentenceTransformer(
            'sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2'
        )
        self.chunks: list[str] = []
        self.embeddings = None
        self.index = None
        self.tfidf_vectorizer = None
        self.tfidf_matrix = None

    # โ”€โ”€ ่ผ‰ๅ…ฅ PDF โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    def load_pdf(self, pdf_path: str) -> str:
        try:
            reader = PdfReader(pdf_path)
            full_text = "\n".join(
                (page.extract_text() or "") for page in reader.pages
            )

            self.chunks = self._split_text(full_text, chunk_size=800, overlap=150)

            self.embeddings = self.embedding_model.encode(
                self.chunks, convert_to_numpy=True, show_progress_bar=False
            )

            dim = self.embeddings.shape[1]
            self.index = faiss.IndexFlatL2(dim)
            self.index.add(self.embeddings.astype("float32"))

            self.tfidf_vectorizer = TfidfVectorizer(max_features=1000)
            self.tfidf_matrix = self.tfidf_vectorizer.fit_transform(self.chunks)

            return (
                f"โœ… ๆˆๅŠŸ่ผ‰ๅ…ฅ๏ผๅ…ฑ **{len(reader.pages)}** ้ ๏ผŒ"
                f"ๅˆ†ๅ‰ฒ็‚บ **{len(self.chunks)}** ๅ€‹็‰‡ๆฎตใ€‚"
            )
        except Exception as e:
            return f"โŒ ่ผ‰ๅ…ฅๅคฑๆ•—๏ผš{e}"

    def _split_text(self, text: str, chunk_size: int, overlap: int) -> list[str]:
        chunks, start = [], 0
        while start < len(text):
            chunk = re.sub(r'\s+', ' ', text[start:start + chunk_size]).strip()
            if chunk:
                chunks.append(chunk)
            start += chunk_size - overlap
        return chunks

    # โ”€โ”€ 8 ็จฎ็ญ–็•ฅ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    def strategy_1_basic_similarity(self, query: str, top_k: int = 3):
        """็ญ–็•ฅ1: ๅŸบ็คŽ่ชžๆ„็›ธไผผๅบฆๆœๅฐ‹"""
        qv = self.embedding_model.encode([query]).astype("float32")
        _, idxs = self.index.search(qv, top_k)
        return [self.chunks[i] for i in idxs[0]]

    def strategy_2_tfidf(self, query: str, top_k: int = 3):
        """็ญ–็•ฅ2: TF-IDF ้—œ้ต่ฉžๆœๅฐ‹"""
        qv = self.tfidf_vectorizer.transform([query])
        scores = (self.tfidf_matrix * qv.T).toarray().flatten()
        return [self.chunks[i] for i in scores.argsort()[-top_k:][::-1]]

    def strategy_3_hybrid(self, query: str, top_k: int = 3):
        """็ญ–็•ฅ3: ๆททๅˆๆœๅฐ‹๏ผˆ่ชžๆ„ + TF-IDF๏ผ‰"""
        qv = self.embedding_model.encode([query]).astype("float32")
        _, sem_idxs = self.index.search(qv, top_k * 2)

        qv_tfidf = self.tfidf_vectorizer.transform([query])
        tfidf_scores = (self.tfidf_matrix * qv_tfidf.T).toarray().flatten()
        tfidf_idxs = tfidf_scores.argsort()[-top_k * 2:][::-1]

        combined = list(set(sem_idxs[0].tolist() + tfidf_idxs.tolist()))
        return [self.chunks[i] for i in combined[:top_k]]

    def strategy_4_reranking(self, query: str, top_k: int = 3):
        """็ญ–็•ฅ4: ้‡ๆ–ฐๆŽ’ๅบ๏ผˆLLM ่ฉ•ๅˆ†๏ผ‰"""
        candidates = self.strategy_1_basic_similarity(query, top_k=top_k * 2)
        scored = []
        for chunk in candidates:
            prompt = (
                f"ๅ•้กŒ๏ผš{query}\n\nๆ–‡ๆœฌ๏ผš{chunk[:200]}...\n\n"
                f"้€™ๆฎตๆ–‡ๆœฌ่ˆ‡ๅ•้กŒ็š„็›ธ้—œๅบฆ(0-10)๏ผŒๅชๅ›ž่ฆ†ๆ•ธๅญ—๏ผš"
            )
            try:
                resp = self.client.chat.completions.create(
                    model="llama-3.1-8b-instant",
                    messages=[{"role": "user", "content": prompt}],
                    max_tokens=10,
                    temperature=0,
                )
                raw = resp.choices[0].message.content.strip()
                nums = re.findall(r'\d+', raw)
                score = float(nums[0]) if nums else 0
            except Exception:
                score = 0
            scored.append((chunk, score))
        scored.sort(key=lambda x: x[1], reverse=True)
        return [c for c, _ in scored[:top_k]]

    def strategy_5_multi_query(self, query: str, top_k: int = 3):
        """็ญ–็•ฅ5: ๅคšๆŸฅ่ฉขๆ“ดๅฑ•"""
        expand_prompt = (
            f"ๅฐ‡ไปฅไธ‹ๅ•้กŒๆ”นๅฏซๆˆ3ๅ€‹็›ธ้—œไฝ†ไธๅŒ่ง’ๅบฆ็š„ๅ•้กŒ๏ผŒ็”จๆ›่กŒๅˆ†้š”๏ผš\n{query}"
        )
        try:
            resp = self.client.chat.completions.create(
                model="llama-3.1-8b-instant",
                messages=[{"role": "user", "content": expand_prompt}],
                max_tokens=200,
                temperature=0.7,
            )
            queries = [query] + resp.choices[0].message.content.strip().split('\n')[:3]
        except Exception:
            queries = [query]

        all_chunks = []
        for q in queries:
            all_chunks.extend(self.strategy_1_basic_similarity(q, top_k=2))
        return list(dict.fromkeys(all_chunks))[:top_k]

    def strategy_6_contextual_compression(self, query: str, top_k: int = 3):
        """็ญ–็•ฅ6: ไธŠไธ‹ๆ–‡ๅฃ“็ธฎ"""
        chunks = self.strategy_1_basic_similarity(query, top_k=top_k)
        compressed = []
        for chunk in chunks:
            prompt = (
                f"ๅพžไปฅไธ‹ๆ–‡ๆœฌไธญๆๅ–่ˆ‡ๅ•้กŒใ€Œ{query}ใ€ๆœ€็›ธ้—œ็š„1-2ๅฅ่ฉฑ๏ผš\n\n{chunk}"
            )
            try:
                resp = self.client.chat.completions.create(
                    model="llama-3.1-8b-instant",
                    messages=[{"role": "user", "content": prompt}],
                    max_tokens=150,
                    temperature=0,
                )
                compressed.append(resp.choices[0].message.content.strip())
            except Exception:
                compressed.append(chunk[:300])
        return compressed

    def strategy_7_parent_child(self, query: str, top_k: int = 3):
        """็ญ–็•ฅ7: ็ˆถๅญๆ–‡ๆช”"""
        full_text = ' '.join(self.chunks)
        small_chunks = self._split_text(full_text, chunk_size=300, overlap=50)
        small_emb = self.embedding_model.encode(
            small_chunks, convert_to_numpy=True, show_progress_bar=False
        ).astype("float32")

        small_index = faiss.IndexFlatL2(small_emb.shape[1])
        small_index.add(small_emb)

        qv = self.embedding_model.encode([query]).astype("float32")
        _, idxs = small_index.search(qv, top_k)

        results = []
        for idx in idxs[0]:
            snippet = small_chunks[idx]
            for big in self.chunks:
                if snippet in big:
                    results.append(big)
                    break
        return list(dict.fromkeys(results))[:top_k]

    def strategy_8_hypothetical_answer(self, query: str, top_k: int = 3):
        """็ญ–็•ฅ8: ๅ‡่จญๆ€ง็ญ”ๆกˆ๏ผˆHyDE๏ผ‰"""
        hyde_prompt = (
            f"่ซ‹ๅฐไปฅไธ‹ๅ•้กŒ็ตฆๅ‡บไธ€ๅ€‹ๅ‡่จญๆ€ง็š„็ญ”ๆกˆ๏ผˆๅณไฝฟไธ็ขบๅฎš๏ผ‰๏ผš\n{query}"
        )
        try:
            resp = self.client.chat.completions.create(
                model="llama-3.1-8b-instant",
                messages=[{"role": "user", "content": hyde_prompt}],
                max_tokens=200,
                temperature=0.7,
            )
            hypothetical = resp.choices[0].message.content
        except Exception:
            hypothetical = query

        qv = self.embedding_model.encode([hypothetical]).astype("float32")
        _, idxs = self.index.search(qv, top_k)
        return [self.chunks[i] for i in idxs[0]]

    # โ”€โ”€ ไธปๅ•็ญ”ๅ…ฅๅฃ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    STRATEGIES = {
        "1. ๅŸบ็คŽ่ชžๆ„ๆœๅฐ‹":        "strategy_1_basic_similarity",
        "2. TF-IDF ้—œ้ต่ฉž":      "strategy_2_tfidf",
        "3. ๆททๅˆๆœๅฐ‹":            "strategy_3_hybrid",
        "4. ้‡ๆ–ฐๆŽ’ๅบ":            "strategy_4_reranking",
        "5. ๅคšๆŸฅ่ฉขๆ“ดๅฑ•":          "strategy_5_multi_query",
        "6. ไธŠไธ‹ๆ–‡ๅฃ“็ธฎ":          "strategy_6_contextual_compression",
        "7. ็ˆถๅญๆ–‡ๆช”":            "strategy_7_parent_child",
        "8. ๅ‡่จญๆ€ง็ญ”ๆกˆ (HyDE)":   "strategy_8_hypothetical_answer",
    }

    def generate_answer(self, query: str, strategy: str, top_k: int = 3):
        if not self.chunks:
            return "โŒ ่ซ‹ๅ…ˆไธŠๅ‚ณ PDF ๆช”ๆกˆ๏ผ", []

        method = getattr(self, self.STRATEGIES.get(strategy, "strategy_1_basic_similarity"))
        relevant_chunks = method(query, top_k)
        context = "\n\n---\n\n".join(relevant_chunks)

        prompt = (
            f"่ซ‹ๆ นๆ“šไปฅไธ‹ไธŠไธ‹ๆ–‡ๅ›ž็ญ”ๅ•้กŒใ€‚ๅฆ‚ๆžœไธŠไธ‹ๆ–‡ไธญๆฒ’ๆœ‰็›ธ้—œ่ณ‡่จŠ๏ผŒ่ซ‹่ชชๆ˜Ž็„กๆณ•ๅ›ž็ญ”ใ€‚\n\n"
            f"ไธŠไธ‹ๆ–‡๏ผš\n{context}\n\nๅ•้กŒ๏ผš{query}\n\n่ซ‹็”จ็น้ซ”ไธญๆ–‡่ฉณ็ดฐๅ›ž็ญ”๏ผš"
        )
        try:
            resp = self.client.chat.completions.create(
                model="llama-3.1-8b-instant",
                messages=[
                    {"role": "system", "content": "ไฝ ๆ˜ฏๅฐˆๆฅญ็š„ๆ–‡ไปถๅˆ†ๆžๅŠฉๆ‰‹ใ€‚"},
                    {"role": "user", "content": prompt},
                ],
                max_tokens=1024,
                temperature=0.3,
            )
            return resp.choices[0].message.content, relevant_chunks
        except Exception as e:
            return f"โŒ ็”Ÿๆˆ็ญ”ๆกˆๅคฑๆ•—๏ผš{e}", []


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Session State ๅˆๅง‹ๅŒ–
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
if "rag" not in st.session_state:
    st.session_state.rag = None
if "pdf_loaded" not in st.session_state:
    st.session_state.pdf_loaded = False
if "load_msg" not in st.session_state:
    st.session_state.load_msg = ""
if "answer" not in st.session_state:
    st.session_state.answer = ""
if "sources" not in st.session_state:
    st.session_state.sources = []
if "last_strategy" not in st.session_state:
    st.session_state.last_strategy = ""


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# Sidebar โ€” ่จญๅฎš
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
with st.sidebar:
    st.markdown("## โš™๏ธ ็ณป็ตฑ่จญๅฎš")

    api_key = st.text_input(
        "Groq API Key",
        type="password",
        placeholder="gsk_...",
        help="ๅ‰ๅพ€ https://console.groq.com ๅ–ๅพ—ๅ…่ฒป API Key",
    )

    st.markdown("---")
    st.markdown("## ๐Ÿ“ค ไธŠๅ‚ณ PDF")
    uploaded_file = st.file_uploader("้ธๆ“‡ PDF ๆช”ๆกˆ", type=["pdf"])

    if st.button("๐Ÿš€ ่ผ‰ๅ…ฅๆ–‡ไปถ", use_container_width=True, type="primary"):
        if not api_key:
            st.error("่ซ‹ๅ…ˆ่ผธๅ…ฅ Groq API Key")
        elif uploaded_file is None:
            st.warning("่ซ‹ๅ…ˆ้ธๆ“‡ PDF ๆช”ๆกˆ")
        else:
            with st.spinner("ๆญฃๅœจ่งฃๆž PDF ไธฆๅปบ็ซ‹็ดขๅผ•โ€ฆ"):
                # ๅฏซๅ…ฅ่‡จๆ™‚ๆช”
                with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
                    tmp.write(uploaded_file.read())
                    tmp_path = tmp.name
                try:
                    rag = MultiStrategyRAG(api_key=api_key)
                    msg = rag.load_pdf(tmp_path)
                    if msg.startswith("โœ…"):
                        st.session_state.rag = rag
                        st.session_state.pdf_loaded = True
                    st.session_state.load_msg = msg
                finally:
                    os.unlink(tmp_path)

    if st.session_state.load_msg:
        if "โœ…" in st.session_state.load_msg:
            st.success(st.session_state.load_msg)
        else:
            st.error(st.session_state.load_msg)

    st.markdown("---")
    st.markdown("## ๐ŸŽฏ RAG ็ญ–็•ฅ")
    strategy = st.selectbox(
        "้ธๆ“‡็ญ–็•ฅ",
        list(MultiStrategyRAG.STRATEGIES.keys()),
        index=0,
    )

    top_k = st.slider("ๆชข็ดข็‰‡ๆฎตๆ•ธ้‡ (Top-K)", min_value=1, max_value=10, value=3)

    st.markdown("---")
    st.markdown("""
### ๐Ÿ“– ็ญ–็•ฅ่ชชๆ˜Ž
| # | ๅ็จฑ | ๆ–นๆณ• |
|---|------|------|
| 1 | ๅŸบ็คŽ่ชžๆ„ | ๅ‘้‡็›ธไผผๅบฆ |
| 2 | TF-IDF | ่ฉž้ ป็ตฑ่จˆ |
| 3 | ๆททๅˆๆœๅฐ‹ | ่ชžๆ„๏ผ‹้—œ้ต่ฉž |
| 4 | ้‡ๆ–ฐๆŽ’ๅบ | LLM ่ฉ•ๅˆ† |
| 5 | ๅคšๆŸฅ่ฉข | ็”Ÿๆˆๅคš่ง’ๅบฆๅ•้กŒ |
| 6 | ไธŠไธ‹ๆ–‡ๅฃ“็ธฎ | LLM ๆๅ–ๆ‘˜่ฆ |
| 7 | ็ˆถๅญๆ–‡ๆช” | ๅฐโ†’ๅคงไธŠไธ‹ๆ–‡ |
| 8 | HyDE | ๅ…ˆ็”Ÿๆˆๅ‡่จญ็ญ”ๆกˆ |
""")


# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# ไธป้ ้ข
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
st.markdown("""
<div class="hero">
  <h1>๐Ÿค– ๅคš็ญ–็•ฅ RAG PDF ๅ•็ญ”็ณป็ตฑ</h1>
  <p>8 ็จฎๆชข็ดข็ญ–็•ฅ ร— Groq Llama 3.1 ร— ่ชžๆ„ๅ‘้‡ๆœๅฐ‹ โ€” ๆ™บ่ƒฝ่งฃๆžๆ‚จ็š„ๆ–‡ไปถ</p>
</div>
""", unsafe_allow_html=True)

# ๅ•้กŒ่ผธๅ…ฅๅ€
st.markdown("### ๐Ÿ’ฌ ๆๅ•")
col_q, col_btn = st.columns([5, 1])
with col_q:
    question = st.text_area(
        "่ผธๅ…ฅๆ‚จ็š„ๅ•้กŒ",
        placeholder="ไพ‹ๅฆ‚๏ผš้€™ไปฝๆ–‡ไปถ็š„ไธป่ฆๅ…งๅฎนๆ˜ฏไป€้บผ๏ผŸ",
        height=100,
        label_visibility="collapsed",
    )
with col_btn:
    st.markdown("<br>", unsafe_allow_html=True)
    ask_clicked = st.button("๐Ÿ” ๆๅ•", use_container_width=True, type="primary")

# ็ฏ„ไพ‹ๅ•้กŒ
st.markdown("**็ฏ„ไพ‹ๅ•้กŒ๏ผš**")
examples = [
    "้€™ไปฝๆ–‡ไปถ็š„ไธป่ฆๅ…งๅฎนๆ˜ฏไป€้บผ๏ผŸ",
    "ๆ–‡ไปถไธญๆๅˆฐๅ“ชไบ›้‡่ฆๆฆ‚ๅฟต๏ผŸ",
    "ๆœ‰ๅ“ชไบ›้—œ้ตๆ•ธๆ“šๆˆ–็ตฑ่จˆ่ณ‡ๆ–™๏ผŸ",
    "ๆ–‡ไปถ็š„็ต่ซ–ๆ˜ฏไป€้บผ๏ผŸ",
]
ex_cols = st.columns(len(examples))
for col, ex in zip(ex_cols, examples):
    if col.button(ex, use_container_width=True):
        question = ex
        ask_clicked = True

st.markdown("---")

# ๅŸท่กŒๅ•็ญ”
if ask_clicked:
    if not question.strip():
        st.warning("โš ๏ธ ่ซ‹่ผธๅ…ฅๅ•้กŒ")
    elif not st.session_state.pdf_loaded or st.session_state.rag is None:
        st.error("โŒ ่ซ‹ๅ…ˆๅœจๅทฆๅดไธŠๅ‚ณไธฆ่ผ‰ๅ…ฅ PDF ๆ–‡ไปถ")
    else:
        with st.spinner(f"ไฝฟ็”จใ€Œ{strategy}ใ€็ญ–็•ฅๆœๅฐ‹ไธญโ€ฆ"):
            answer, sources = st.session_state.rag.generate_answer(
                question, strategy, top_k
            )
        st.session_state.answer = answer
        st.session_state.sources = sources
        st.session_state.last_strategy = strategy

# ้กฏ็คบ็ญ”ๆกˆ
if st.session_state.answer:
    st.markdown("### ๐Ÿ’ก AI ๅ›ž็ญ”")
    st.markdown(
        f'<span class="badge">็ญ–็•ฅ๏ผš{st.session_state.last_strategy}</span>',
        unsafe_allow_html=True,
    )
    st.markdown(
        f'<div class="answer-box">{st.session_state.answer}</div>',
        unsafe_allow_html=True,
    )

    # ไพ†ๆบ็‰‡ๆฎต
    if st.session_state.sources:
        with st.expander(
            f"๐Ÿ“š ๆŸฅ็œ‹ๆชข็ดขๅˆฐ็š„ {len(st.session_state.sources)} ๅ€‹ๆ–‡ๆœฌ็‰‡ๆฎต", expanded=False
        ):
            for i, chunk in enumerate(st.session_state.sources, 1):
                st.markdown(
                    f'<div class="source-chunk">'
                    f'<div class="chunk-label">็‰‡ๆฎต {i}</div>'
                    f'{chunk}'
                    f'</div>',
                    unsafe_allow_html=True,
                )