File size: 26,869 Bytes
9b2f298
4ac1625
ee0cb34
61279f3
ee0cb34
 
6ed5f50
4ac1625
 
 
 
225994f
6ed5f50
225994f
 
 
 
 
6ed5f50
225994f
 
 
 
 
 
6ed5f50
9b2f298
4ac1625
9b2f298
 
61279f3
9b2f298
61279f3
9b2f298
61279f3
9b2f298
61279f3
 
740bd2d
61279f3
 
9b2f298
61279f3
740bd2d
 
61279f3
740bd2d
 
 
 
 
 
 
 
 
 
 
61279f3
ee0cb34
61279f3
ee0cb34
61279f3
 
 
ee0cb34
61279f3
ee0cb34
61279f3
 
 
ee0cb34
61279f3
6ed5f50
61279f3
 
 
 
 
6ed5f50
61279f3
6ed5f50
740bd2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61279f3
4ac1625
740bd2d
 
 
 
 
 
 
 
 
 
 
 
 
4ac1625
 
9b2f298
 
225994f
6ed5f50
 
225994f
 
 
 
 
 
6ed5f50
 
225994f
6ed5f50
 
 
 
 
 
 
 
 
 
225994f
 
 
6ed5f50
 
ee0cb34
 
 
225994f
 
6ed5f50
225994f
6ed5f50
ee0cb34
225994f
 
 
6ed5f50
225994f
6ed5f50
ee0cb34
 
 
225994f
 
 
 
 
 
 
6ed5f50
225994f
 
ee0cb34
225994f
ee0cb34
 
6ed5f50
ee0cb34
 
 
 
 
 
 
225994f
ee0cb34
 
 
 
 
225994f
ee0cb34
 
 
 
225994f
 
ee0cb34
 
 
 
 
 
 
ec0ec22
 
 
 
 
 
225994f
 
ee0cb34
ec0ec22
225994f
ec0ec22
 
 
 
 
 
 
 
ee0cb34
 
 
 
 
6ed5f50
ee0cb34
 
ec0ec22
 
 
ee0cb34
 
 
 
 
 
 
 
 
ec0ec22
6ed5f50
ee0cb34
6ed5f50
 
225994f
 
206f5ac
 
ec0ec22
 
 
 
 
 
 
 
ee0cb34
ec0ec22
 
 
 
225994f
 
ec0ec22
225994f
ec0ec22
 
 
 
 
 
 
 
 
 
 
 
 
225994f
ec0ec22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee0cb34
ec0ec22
 
 
 
 
 
 
 
 
 
225994f
ec0ec22
225994f
ec0ec22
 
206f5ac
 
ec0ec22
 
 
 
 
206f5ac
ee0cb34
4ac1625
 
206f5ac
 
6ed5f50
 
 
ec0ec22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225994f
ec0ec22
206f5ac
4ac1625
 
206f5ac
4ac1625
ee0cb34
6ed5f50
206f5ac
ec0ec22
 
4ac1625
ec0ec22
225994f
4ac1625
ee0cb34
4ac1625
206f5ac
4ac1625
ec0ec22
 
4ac1625
 
 
 
 
 
 
 
 
 
ee0cb34
6ed5f50
ee0cb34
4ac1625
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206f5ac
 
 
 
 
 
4ac1625
 
 
 
 
 
 
206f5ac
4ac1625
 
 
206f5ac
4ac1625
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee0cb34
 
 
 
6ed5f50
97286e7
4ac1625
6ed5f50
ee0cb34
 
 
 
 
 
 
 
225994f
 
ee0cb34
 
 
 
97286e7
 
 
ee0cb34
 
 
 
 
6ed5f50
ee0cb34
6ed5f50
 
4ac1625
6ed5f50
ee0cb34
97286e7
 
4ac1625
97286e7
ee0cb34
 
6ed5f50
 
4ac1625
6ed5f50
ee0cb34
 
6ed5f50
4ac1625
6ed5f50
 
 
4ac1625
6ed5f50
 
61279f3
4ac1625
6ed5f50
ee0cb34
4ac1625
 
 
 
 
 
6ed5f50
206f5ac
 
 
4ac1625
 
 
 
 
 
 
 
 
9b2f298
4ac1625
 
9b2f298
740bd2d
 
 
 
 
 
 
 
 
 
 
 
 
4ac1625
 
 
740bd2d
 
9b2f298
 
4ac1625
740bd2d
9b2f298
 
4ac1625
 
740bd2d
 
4ac1625
9b2f298
740bd2d
 
 
 
 
 
 
 
 
 
4ac1625
 
 
 
 
 
740bd2d
 
 
 
 
 
 
 
 
 
 
4ac1625
7d0296f
740bd2d
 
 
 
 
 
6ed5f50
ee0cb34
740bd2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ac1625
740bd2d
 
 
4ac1625
 
 
 
740bd2d
 
 
 
 
 
4ac1625
 
740bd2d
 
 
4ac1625
 
 
740bd2d
 
4ac1625
740bd2d
a4e794b
 
740bd2d
 
 
 
3898d05
 
4ac1625
a4e794b
740bd2d
4ac1625
 
ee0cb34
4ac1625
ee0cb34
 
 
4ac1625
ee0cb34
 
 
 
4ac1625
ee0cb34
 
740bd2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ac1625
ee0cb34
740bd2d
4ac1625
97286e7
 
 
 
740bd2d
4ac1625
97286e7
 
 
4ac1625
740bd2d
4ac1625
97286e7
ee0cb34
61279f3
4ac1625
 
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
import gradio as gr
import spaces
import os
from typing import List, Dict, Any, Optional, Tuple
import hashlib
from datetime import datetime
import numpy as np
from transformers import pipeline, TextIteratorStreamer
import torch
from threading import Thread
import re

# PDF ์ฒ˜๋ฆฌ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
try:
    import fitz  # PyMuPDF
    PDF_AVAILABLE = True
except ImportError:
    PDF_AVAILABLE = False
    print("โš ๏ธ PyMuPDF not installed. Install with: pip install pymupdf")

try:
    from sentence_transformers import SentenceTransformer
    ST_AVAILABLE = True
except ImportError:
    ST_AVAILABLE = False
    print("โš ๏ธ Sentence Transformers not installed. Install with: pip install sentence-transformers")

# Custom CSS
custom_css = """
.gradio-container {
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    min-height: 100vh;
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
}

.main-container {
    background: rgba(255, 255, 255, 0.98);
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    border: 1px solid rgba(0, 0, 0, 0.05);
}

.sidebar-container {
    background: rgba(255, 255, 255, 0.98);
    border-radius: 12px;
    padding: 16px;
    box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    border: 1px solid rgba(0, 0, 0, 0.05);
    height: fit-content;
}

.pdf-status {
    padding: 10px 14px;
    border-radius: 10px;
    margin: 8px 0;
    font-size: 0.9rem;
    font-weight: 500;
}

.pdf-success {
    background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
    border: 1px solid #b1dfbb;
    color: #155724;
}

.pdf-error {
    background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
    border: 1px solid #f1aeb5;
    color: #721c24;
}

.pdf-info {
    background: linear-gradient(135deg, #d1ecf1 0%, #bee5eb 100%);
    border: 1px solid #9ec5d8;
    color: #0c5460;
}

.rag-context {
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border-left: 4px solid #f59e0b;
    padding: 10px;
    margin: 8px 0;
    border-radius: 6px;
    font-size: 0.85rem;
}

.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.85rem;
    font-weight: 600;
    margin: 4px 0;
}

.status-enabled {
    background: #10b981;
    color: white;
}

.status-disabled {
    background: #6b7280;
    color: white;
}

/* Chat interface maximization */
.chat-container {
    height: calc(100vh - 200px) !important;
    min-height: 600px;
}

/* Accordion styling */
.accordion {
    margin: 8px 0;
}
"""

class SimpleTextSplitter:
    """ํ…์ŠคํŠธ ๋ถ„ํ• ๊ธฐ"""
    def __init__(self, chunk_size=800, chunk_overlap=100):
        self.chunk_size = chunk_size
        self.chunk_overlap = chunk_overlap
    
    def split_text(self, text: str) -> List[str]:
        """ํ…์ŠคํŠธ๋ฅผ ์ฒญํฌ๋กœ ๋ถ„ํ• """
        chunks = []
        sentences = text.split('. ')
        current_chunk = ""
        
        for sentence in sentences:
            if len(current_chunk) + len(sentence) < self.chunk_size:
                current_chunk += sentence + ". "
            else:
                if current_chunk:
                    chunks.append(current_chunk.strip())
                current_chunk = sentence + ". "
        
        if current_chunk:
            chunks.append(current_chunk.strip())
        
        return chunks

class PDFRAGSystem:
    """PDF ๊ธฐ๋ฐ˜ RAG ์‹œ์Šคํ…œ"""
    
    def __init__(self):
        self.documents = {}
        self.document_chunks = {}
        self.embeddings_store = {}
        self.text_splitter = SimpleTextSplitter(chunk_size=800, chunk_overlap=100)
        
        # ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ์ดˆ๊ธฐํ™”
        self.embedder = None
        if ST_AVAILABLE:
            try:
                self.embedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
                print("โœ… ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ๋กœ๋“œ ์„ฑ๊ณต")
            except Exception as e:
                print(f"โš ๏ธ ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ๋กœ๋“œ ์‹คํŒจ: {e}")
    
    def extract_text_from_pdf(self, pdf_path: str) -> Dict[str, Any]:
        """PDF์—์„œ ํ…์ŠคํŠธ ์ถ”์ถœ"""
        if not PDF_AVAILABLE:
            return {
                "metadata": {
                    "title": "PDF Reader Not Available",
                    "file_name": os.path.basename(pdf_path),
                    "pages": 0
                },
                "full_text": "PDF ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•ด 'pip install pymupdf'๋ฅผ ์‹คํ–‰ํ•ด์ฃผ์„ธ์š”."
            }
        
        try:
            doc = fitz.open(pdf_path)
            text_content = []
            metadata = {
                "title": doc.metadata.get("title", os.path.basename(pdf_path)),
                "pages": len(doc),
                "file_name": os.path.basename(pdf_path)
            }
            
            for page_num, page in enumerate(doc):
                text = page.get_text()
                if text.strip():
                    text_content.append(text)
            
            doc.close()
            
            return {
                "metadata": metadata,
                "full_text": "\n\n".join(text_content)
            }
        except Exception as e:
            raise Exception(f"PDF ์ฒ˜๋ฆฌ ์˜ค๋ฅ˜: {str(e)}")
    
    def process_and_store_pdf(self, pdf_path: str, doc_id: str) -> Dict[str, Any]:
        """PDF ์ฒ˜๋ฆฌ ๋ฐ ์ €์žฅ"""
        try:
            # PDF ํ…์ŠคํŠธ ์ถ”์ถœ
            pdf_data = self.extract_text_from_pdf(pdf_path)
            
            # ํ…์ŠคํŠธ๋ฅผ ์ฒญํฌ๋กœ ๋ถ„ํ• 
            chunks = self.text_splitter.split_text(pdf_data["full_text"])
            
            if not chunks:
                print("Warning: No chunks created from PDF")
                return {"success": False, "error": "No text content found in PDF"}
            
            print(f"Created {len(chunks)} chunks from PDF")
            
            # ์ฒญํฌ ์ €์žฅ
            self.document_chunks[doc_id] = chunks
            
            # ์ž„๋ฒ ๋”ฉ ์ƒ์„ฑ (์„ ํƒ์ )
            if self.embedder:
                try:
                    print("Generating embeddings...")
                    embeddings = self.embedder.encode(chunks)
                    self.embeddings_store[doc_id] = embeddings
                    print(f"Generated {len(embeddings)} embeddings")
                except Exception as e:
                    print(f"Warning: Failed to generate embeddings: {e}")
                    # ์ž„๋ฒ ๋”ฉ ์‹คํŒจํ•ด๋„ ๊ณ„์† ์ง„ํ–‰
            
            # ๋ฌธ์„œ ์ •๋ณด ์ €์žฅ
            self.documents[doc_id] = {
                "metadata": pdf_data["metadata"],
                "chunk_count": len(chunks),
                "upload_time": datetime.now().isoformat()
            }
            
            # ๋””๋ฒ„๊ทธ: ์ฒซ ๋ฒˆ์งธ ์ฒญํฌ ์ถœ๋ ฅ
            print(f"First chunk preview: {chunks[0][:200]}...")
            
            return {
                "success": True,
                "doc_id": doc_id,
                "chunks": len(chunks),
                "pages": pdf_data["metadata"]["pages"],
                "title": pdf_data["metadata"]["title"]
            }
            
        except Exception as e:
            print(f"Error processing PDF: {e}")
            return {"success": False, "error": str(e)}
    
    def search_relevant_chunks(self, query: str, doc_ids: List[str], top_k: int = 3) -> List[Dict]:
        """๊ด€๋ จ ์ฒญํฌ ๊ฒ€์ƒ‰"""
        all_relevant_chunks = []
        
        print(f"Searching chunks for query: '{query[:50]}...' in {len(doc_ids)} documents")
        
        # ๋จผ์ € ๋ฌธ์„œ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธ
        for doc_id in doc_ids:
            if doc_id not in self.document_chunks:
                print(f"Warning: Document {doc_id} not found in chunks")
                continue
                
            chunks = self.document_chunks[doc_id]
            print(f"Document {doc_id} has {len(chunks)} chunks")
            
            # ์ž„๋ฒ ๋”ฉ ๊ธฐ๋ฐ˜ ๊ฒ€์ƒ‰ ์‹œ๋„
            if self.embedder and doc_id in self.embeddings_store:
                try:
                    query_embedding = self.embedder.encode([query])[0]
                    doc_embeddings = self.embeddings_store[doc_id]
                    
                    # ์ฝ”์‚ฌ์ธ ์œ ์‚ฌ๋„ ๊ณ„์‚ฐ (์•ˆ์ „ํ•˜๊ฒŒ)
                    similarities = []
                    for i, emb in enumerate(doc_embeddings):
                        try:
                            query_norm = np.linalg.norm(query_embedding)
                            emb_norm = np.linalg.norm(emb)
                            
                            if query_norm > 0 and emb_norm > 0:
                                sim = np.dot(query_embedding, emb) / (query_norm * emb_norm)
                                similarities.append(sim)
                            else:
                                similarities.append(0.0)
                        except Exception as e:
                            print(f"Error calculating similarity for chunk {i}: {e}")
                            similarities.append(0.0)
                    
                    # ์ƒ์œ„ ์ฒญํฌ ์„ ํƒ
                    if similarities:
                        top_indices = np.argsort(similarities)[-min(top_k, len(similarities)):][::-1]
                        
                        for idx in top_indices:
                            if idx < len(chunks):  # ์ธ๋ฑ์Šค ๋ฒ”์œ„ ํ™•์ธ
                                all_relevant_chunks.append({
                                    "content": chunks[idx],
                                    "doc_name": self.documents[doc_id]["metadata"]["file_name"],
                                    "similarity": similarities[idx]
                                })
                                print(f"Added chunk {idx} with similarity: {similarities[idx]:.3f}")
                except Exception as e:
                    print(f"Error in embedding search: {e}")
                    # ์ž„๋ฒ ๋”ฉ ์‹คํŒจ์‹œ ํด๋ฐฑ
            
            # ์ž„๋ฒ ๋”ฉ์ด ์—†๊ฑฐ๋‚˜ ์‹คํŒจํ•œ ๊ฒฝ์šฐ - ๊ฐ„๋‹จํžˆ ์ฒ˜์Œ N๊ฐœ ์ฒญํฌ ๋ฐ˜ํ™˜
            if not all_relevant_chunks:
                print(f"Falling back to simple chunk selection for {doc_id}")
                for i in range(min(top_k, len(chunks))):
                    all_relevant_chunks.append({
                        "content": chunks[i],
                        "doc_name": self.documents[doc_id]["metadata"]["file_name"],
                        "similarity": 1.0 - (i * 0.1)  # ์ˆœ์„œ๋Œ€๋กœ ๊ฐ€์ค‘์น˜
                    })
                    print(f"Added chunk {i} (fallback)")
        
        # ์œ ์‚ฌ๋„ ๊ธฐ์ค€ ์ •๋ ฌ
        all_relevant_chunks.sort(key=lambda x: x.get('similarity', 0), reverse=True)
        
        # ์ƒ์œ„ K๊ฐœ ์„ ํƒ
        result = all_relevant_chunks[:top_k]
        print(f"Returning {len(result)} chunks")
        
        # ๋””๋ฒ„๊ทธ: ์ฒซ ๋ฒˆ์งธ ์ฒญํฌ ๋‚ด์šฉ ์ผ๋ถ€ ์ถœ๋ ฅ
        if result:
            print(f"First chunk preview: {result[0]['content'][:100]}...")
        
        return result
    
    def create_rag_prompt(self, query: str, doc_ids: List[str], top_k: int = 3) -> tuple:
        """RAG ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ - ์ฟผ๋ฆฌ์™€ ์ปจํ…์ŠคํŠธ๋ฅผ ๋ถ„๋ฆฌํ•˜์—ฌ ๋ฐ˜ํ™˜"""
        print(f"Creating RAG prompt for query: '{query[:50]}...' with docs: {doc_ids}")
        
        relevant_chunks = self.search_relevant_chunks(query, doc_ids, top_k)
        
        if not relevant_chunks:
            print("No relevant chunks found - checking if documents exist")
            # ๋ฌธ์„œ๊ฐ€ ์žˆ๋Š”๋ฐ ์ฒญํฌ๋ฅผ ๋ชป ์ฐพ์€ ๊ฒฝ์šฐ, ์ฒซ ๋ฒˆ์งธ ์ฒญํฌ๋ผ๋„ ์‚ฌ์šฉ
            for doc_id in doc_ids:
                if doc_id in self.document_chunks and self.document_chunks[doc_id]:
                    print(f"Using first chunk from {doc_id} as fallback")
                    relevant_chunks = [{
                        "content": self.document_chunks[doc_id][0],
                        "doc_name": self.documents[doc_id]["metadata"]["file_name"],
                        "similarity": 0.5
                    }]
                    break
            
            if not relevant_chunks:
                print("No documents or chunks available")
                return query, ""
        
        print(f"Using {len(relevant_chunks)} chunks for context")
        
        # ์ปจํ…์ŠคํŠธ ๊ตฌ์„ฑ
        context_parts = []
        context_parts.append("Based on the following document context, please answer the question below:")
        context_parts.append("=" * 40)
        
        for i, chunk in enumerate(relevant_chunks, 1):
            context_parts.append(f"\n[Document Reference {i} - {chunk['doc_name']}]")
            # ์ฒญํฌ ํฌ๊ธฐ ์ฆ๊ฐ€
            content = chunk['content'][:1000] if len(chunk['content']) > 1000 else chunk['content']
            context_parts.append(content)
            print(f"Added chunk {i} ({len(content)} chars) with similarity: {chunk.get('similarity', 0):.3f}")
        
        context_parts.append("\n" + "=" * 40)
        
        context = "\n".join(context_parts)
        enhanced_query = f"{context}\n\nQuestion: {query}\n\nAnswer based on the document context provided above:"
        
        print(f"Enhanced query length: {len(enhanced_query)} chars (original: {len(query)} chars)")
        
        return enhanced_query, context

# Initialize model and RAG system
model_id = "openai/gpt-oss-20b"
pipe = pipeline(
    "text-generation",
    model=model_id,
    torch_dtype="auto",
    device_map="auto",
)

rag_system = PDFRAGSystem()

# Global state for RAG
rag_enabled = False
selected_docs = []
top_k_chunks = 3
last_context = ""

def format_conversation_history(chat_history):
    """Format conversation history for the model"""
    messages = []
    for item in chat_history:
        role = item["role"]
        content = item["content"]
        if isinstance(content, list):
            content = content[0]["text"] if content and "text" in content[0] else str(content)
        messages.append({"role": role, "content": content})
    return messages

@spaces.GPU()
def generate_response(input_data, chat_history, max_new_tokens, system_prompt, temperature, top_p, top_k, repetition_penalty):
    """Generate response with optional RAG enhancement"""
    global last_context, rag_enabled, selected_docs, top_k_chunks
    
    # Debug logging
    print(f"RAG Enabled: {rag_enabled}")
    print(f"Selected Docs: {selected_docs}")
    print(f"Available Docs: {list(rag_system.documents.keys())}")
    
    # Apply RAG if enabled
    if rag_enabled and selected_docs:
        doc_ids = [doc.split(":")[0] for doc in selected_docs]
        enhanced_input, context = rag_system.create_rag_prompt(input_data, doc_ids, top_k_chunks)
        last_context = context
        actual_input = enhanced_input
        print(f"RAG Applied - Original: {len(input_data)} chars, Enhanced: {len(enhanced_input)} chars")
    else:
        actual_input = input_data
        last_context = ""
        print("RAG Not Applied")
    
    # Prepare messages
    new_message = {"role": "user", "content": actual_input}
    system_message = [{"role": "system", "content": system_prompt}] if system_prompt else []
    processed_history = format_conversation_history(chat_history)
    messages = system_message + processed_history + [new_message]
    
    # Setup streaming
    streamer = TextIteratorStreamer(pipe.tokenizer, skip_prompt=True, skip_special_tokens=True)
    generation_kwargs = {
        "max_new_tokens": max_new_tokens,
        "do_sample": True,
        "temperature": temperature,
        "top_p": top_p,
        "top_k": top_k,
        "repetition_penalty": repetition_penalty,
        "streamer": streamer
    }
    
    thread = Thread(target=pipe, args=(messages,), kwargs=generation_kwargs)
    thread.start()
    
    # Process streaming output
    thinking = ""
    final = ""
    started_final = False
    
    for chunk in streamer:
        if not started_final:
            if "assistantfinal" in chunk.lower():
                split_parts = re.split(r'assistantfinal', chunk, maxsplit=1)
                thinking += split_parts[0]
                final += split_parts[1]
                started_final = True
            else:
                thinking += chunk
        else:
            final += chunk
        
        clean_thinking = re.sub(r'^analysis\s*', '', thinking).strip()
        clean_final = final.strip()
        
        # Add RAG context indicator if used
        rag_indicator = ""
        if rag_enabled and selected_docs and last_context:
            rag_indicator = "<div class='rag-context'>๐Ÿ“š RAG Context Applied</div>\n\n"
        
        formatted = f"{rag_indicator}<details open><summary>Click to view Thinking Process</summary>\n\n{clean_thinking}\n\n</details>\n\n{clean_final}"
        yield formatted

def upload_pdf(file):
    """PDF ํŒŒ์ผ ์—…๋กœ๋“œ ์ฒ˜๋ฆฌ"""
    if file is None:
        return (
            gr.update(value="<div class='pdf-status pdf-info'>๐Ÿ“ ํŒŒ์ผ์„ ์„ ํƒํ•ด์ฃผ์„ธ์š”</div>"),
            gr.update(choices=[])
        )
    
    try:
        # ํŒŒ์ผ ํ•ด์‹œ๋ฅผ ID๋กœ ์‚ฌ์šฉ
        with open(file.name, 'rb') as f:
            file_hash = hashlib.md5(f.read()).hexdigest()[:8]
        
        doc_id = f"doc_{file_hash}"
        
        # PDF ์ฒ˜๋ฆฌ ๋ฐ ์ €์žฅ
        result = rag_system.process_and_store_pdf(file.name, doc_id)
        
        if result["success"]:
            status_html = f"""
            <div class="pdf-status pdf-success">
                โœ… PDF ์—…๋กœ๋“œ ์™„๋ฃŒ!<br>
                ๐Ÿ“„ {result['title']}<br>
                ๐Ÿ“‘ {result['pages']} ํŽ˜์ด์ง€ | ๐Ÿ” {result['chunks']} ์ฒญํฌ
            </div>
            """
            
            # ๋ฌธ์„œ ๋ชฉ๋ก ์—…๋ฐ์ดํŠธ
            doc_choices = [f"{doc_id}: {rag_system.documents[doc_id]['metadata']['file_name']}" 
                          for doc_id in rag_system.documents.keys()]
            
            return (
                status_html,
                gr.update(choices=doc_choices, value=doc_choices)
            )
        else:
            return (
                f"<div class='pdf-status pdf-error'>โŒ ์˜ค๋ฅ˜: {result['error']}</div>",
                gr.update()
            )
            
    except Exception as e:
        return (
            f"<div class='pdf-status pdf-error'>โŒ ์˜ค๋ฅ˜: {str(e)}</div>",
            gr.update()
        )

def clear_documents():
    """๋ฌธ์„œ ์ดˆ๊ธฐํ™”"""
    global selected_docs
    rag_system.documents = {}
    rag_system.document_chunks = {}
    rag_system.embeddings_store = {}
    selected_docs = []
    
    return (
        gr.update(value="<div class='pdf-status pdf-info'>๐Ÿ—‘๏ธ ๋ชจ๋“  ๋ฌธ์„œ๊ฐ€ ์‚ญ์ œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค</div>"),
        gr.update(choices=[], value=[])
    )

def update_rag_settings(enable, docs, k):
    """Update RAG settings"""
    global rag_enabled, selected_docs, top_k_chunks
    rag_enabled = enable
    selected_docs = docs if docs else []
    top_k_chunks = k
    
    # Debug logging
    print(f"RAG Settings Updated - Enabled: {rag_enabled}, Docs: {selected_docs}, Top-K: {top_k_chunks}")
    
    status = "โœ… Enabled" if enable and docs else "โญ• Disabled"
    status_html = f"<div class='pdf-status pdf-info'>๐Ÿ” RAG: <strong>{status}</strong></div>"
    
    # Show context preview if RAG is enabled
    if enable and docs:
        preview = f"<div class='rag-context'>๐Ÿ“š Using {len(docs)} document(s) with {k} chunks per query</div>"
        return gr.update(value=status_html), gr.update(value=preview, visible=True)
    else:
        return gr.update(value=status_html), gr.update(value="", visible=False)

# Build the interface
with gr.Blocks(theme=gr.themes.Soft(), css=custom_css, fill_height=True) as demo:
    with gr.Row():
        # Compact sidebar
        with gr.Column(scale=1, min_width=300):
            gr.Markdown("## ๐Ÿš€ GPT-OSS-20B + RAG")
            
            # RAG Status Badge
            with gr.Group(elem_classes="sidebar-container"):
                rag_status = gr.HTML(
                    value="<div class='status-badge status-disabled'>RAG: Disabled</div>"
                )
                context_preview = gr.HTML(value="", visible=False)
            
            # PDF Upload Section
            with gr.Accordion("๐Ÿ“„ PDF Documents", open=True, elem_classes="accordion"):
                pdf_upload = gr.File(
                    label="Upload PDF",
                    file_types=[".pdf"],
                    type="filepath",
                    elem_classes="compact-upload"
                )
                
                upload_status = gr.HTML(
                    value="<div style='font-size: 0.85rem; color: #6b7280;'>No documents uploaded</div>"
                )
                
                document_list = gr.CheckboxGroup(
                    choices=[],
                    label="Select Documents",
                    elem_classes="compact-checkbox"
                )
                
                with gr.Row():
                    enable_rag = gr.Checkbox(
                        label="Enable RAG",
                        value=False,
                        scale=2
                    )
                    clear_btn = gr.Button("Clear", size="sm", variant="secondary", scale=1)
            
            # RAG Settings
            with gr.Accordion("โš™๏ธ RAG Settings", open=False, elem_classes="accordion"):
                top_k_slider = gr.Slider(
                    minimum=1,
                    maximum=5,
                    value=3,
                    step=1,
                    label="Context Chunks",
                    info="Number of chunks to use"
                )
            
            # Model Settings
            with gr.Accordion("๐Ÿ”ง Model Settings", open=False, elem_classes="accordion"):
                max_tokens = gr.Slider(
                    label="Max tokens",
                    minimum=64,
                    maximum=4096,
                    step=1,
                    value=2048
                )
                
                temperature = gr.Slider(
                    label="Temperature",
                    minimum=0.1,
                    maximum=2.0,
                    step=0.1,
                    value=0.7
                )
                
                with gr.Row():
                    top_p = gr.Slider(
                        label="Top-p",
                        minimum=0.05,
                        maximum=1.0,
                        step=0.05,
                        value=0.9
                    )
                    
                    top_k = gr.Slider(
                        label="Top-k",
                        minimum=1,
                        maximum=100,
                        step=1,
                        value=50
                    )
                
                repetition_penalty = gr.Slider(
                    label="Repetition Penalty",
                    minimum=1.0,
                    maximum=2.0,
                    step=0.05,
                    value=1.0
                )
            
            # System Prompt
            with gr.Accordion("๐Ÿ’ฌ System Prompt", open=False, elem_classes="accordion"):
                system_prompt = gr.Textbox(
                    label="System Prompt",
                    value="You are a helpful assistant. Reasoning: medium",
                    lines=3,
                    placeholder="Customize the system prompt..."
                )
        
        # Main chat area - maximized
        with gr.Column(scale=4):
            with gr.Group(elem_classes="main-container chat-container"):
                # Create ChatInterface with custom function
                chat_interface = gr.ChatInterface(
                    fn=generate_response,
                    additional_inputs=[
                        max_tokens,
                        system_prompt,
                        temperature,
                        top_p,
                        top_k,
                        repetition_penalty
                    ],
                    examples=[
                        [{"text": "Summarize the document"}],
                        [{"text": "What are the key points mentioned?"}],
                        [{"text": "Explain the main concept"}],
                    ],
                    cache_examples=False,
                    type="messages",
                    title=None,
                    description=None,
                    textbox=gr.Textbox(
                        placeholder="Ask anything... (RAG will be applied if enabled)",
                        container=False,
                        scale=7
                    ),
                    chatbot=gr.Chatbot(
                        height=550,
                        show_copy_button=True,
                        render_markdown=True,
                        type="messages"
                    ),
                    submit_btn="Send",
                    stop_btn="Stop",
                    multimodal=False
                )
    
    # Event handlers
    pdf_upload.upload(
        fn=upload_pdf,
        inputs=[pdf_upload],
        outputs=[upload_status, document_list]
    )
    
    clear_btn.click(
        fn=clear_documents,
        outputs=[upload_status, document_list]
    )
    
    # Simplified RAG status update
    def update_rag_status_simple(enable, docs, k):
        """Simplified RAG status update"""
        global rag_enabled, selected_docs, top_k_chunks
        rag_enabled = enable
        selected_docs = docs if docs else []
        top_k_chunks = k
        
        if enable and docs:
            status_html = "<div class='status-badge status-enabled'>RAG: Active</div>"
            preview = f"<div style='font-size: 0.85rem; color: #10b981;'>๐Ÿ“š {len(docs)} doc(s) | {k} chunks</div>"
            return gr.update(value=status_html), gr.update(value=preview, visible=True)
        else:
            status_html = "<div class='status-badge status-disabled'>RAG: Disabled</div>"
            return gr.update(value=status_html), gr.update(value="", visible=False)
    
    # Update RAG settings when changed
    enable_rag.change(
        fn=update_rag_status_simple,
        inputs=[enable_rag, document_list, top_k_slider],
        outputs=[rag_status, context_preview]
    )
    
    document_list.change(
        fn=update_rag_status_simple,
        inputs=[enable_rag, document_list, top_k_slider],
        outputs=[rag_status, context_preview]
    )
    
    top_k_slider.change(
        fn=update_rag_status_simple,
        inputs=[enable_rag, document_list, top_k_slider],
        outputs=[rag_status, context_preview]
    )

if __name__ == "__main__":
    demo.launch(share=True)