File size: 26,041 Bytes
bbebfbc
 
98ef6e0
bbebfbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98ef6e0
bbebfbc
 
98ef6e0
bbebfbc
 
 
 
 
98ef6e0
bbebfbc
 
 
98ef6e0
bbebfbc
 
98ef6e0
bbebfbc
 
 
 
 
 
 
98ef6e0
bbebfbc
98ef6e0
bbebfbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98ef6e0
bbebfbc
 
 
98ef6e0
bbebfbc
98ef6e0
bbebfbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98ef6e0
bbebfbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98ef6e0
bbebfbc
 
 
98ef6e0
bbebfbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98ef6e0
bbebfbc
 
98ef6e0
bbebfbc
98ef6e0
bbebfbc
 
 
 
 
 
98ef6e0
bbebfbc
 
98ef6e0
bbebfbc
98ef6e0
bbebfbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98ef6e0
bbebfbc
 
 
 
 
 
 
98ef6e0
bbebfbc
 
 
 
98ef6e0
bbebfbc
 
 
 
 
98ef6e0
bbebfbc
 
 
 
 
 
 
98ef6e0
bbebfbc
 
 
 
 
 
98ef6e0
bbebfbc
98ef6e0
bbebfbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98ef6e0
bbebfbc
 
 
 
 
 
98ef6e0
bbebfbc
 
 
 
 
 
 
 
 
 
 
 
98ef6e0
bbebfbc
98ef6e0
bbebfbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d18863
bbebfbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98ef6e0
bbebfbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98ef6e0
bbebfbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import spaces
import json
import subprocess
import os
from llama_cpp import Llama
from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
from llama_cpp_agent.providers import LlamaCppPythonProvider
from llama_cpp_agent.chat_history import BasicChatHistory
from llama_cpp_agent.chat_history.messages import Roles
import gradio as gr
from huggingface_hub import hf_hub_download
import tempfile
from typing import List, Tuple, Optional

# PDF ์ฒ˜๋ฆฌ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์กฐ๊ฑด๋ถ€ import
try:
    from docling.document_converter import DocumentConverter
    DOCLING_AVAILABLE = True
except ImportError:
    DOCLING_AVAILABLE = False
    print("Docling not available, using alternative PDF processing")
    try:
        import PyPDF2
        import pdfplumber
    except ImportError:
        print("Warning: PDF processing libraries not fully installed")

# ํ™˜๊ฒฝ ๋ณ€์ˆ˜์—์„œ HF_TOKEN ๊ฐ€์ ธ์˜ค๊ธฐ
HF_TOKEN = os.getenv("HF_TOKEN")

# ์ „์—ญ ๋ณ€์ˆ˜ ์ดˆ๊ธฐํ™” (์ค‘์š”!)
llm = None
llm_model = None
document_context = ""  # PDF์—์„œ ์ถ”์ถœํ•œ ๋ฌธ์„œ ์ปจํ…์ŠคํŠธ ์ €์žฅ
document_filename = ""  # ํ˜„์žฌ ๋กœ๋“œ๋œ ๋ฌธ์„œ์˜ ํŒŒ์ผ๋ช…

print("์ „์—ญ ๋ณ€์ˆ˜ ์ดˆ๊ธฐํ™” ์™„๋ฃŒ")
print(f"document_context ์ดˆ๊ธฐ๊ฐ’: '{document_context}'")
print(f"document_filename ์ดˆ๊ธฐ๊ฐ’: '{document_filename}'")

# ๋ชจ๋ธ ์ด๋ฆ„๊ณผ ๊ฒฝ๋กœ๋ฅผ ์ •์˜
MISTRAL_MODEL_NAME = "Private-BitSix-Mistral-Small-3.1-24B-Instruct-2503.gguf"

# ๋ชจ๋ธ ๋‹ค์šด๋กœ๋“œ (HF_TOKEN ์‚ฌ์šฉ)
model_path = hf_hub_download(
    repo_id="ginigen/Private-BitSix-Mistral-Small-3.1-24B-Instruct-2503",
    filename=MISTRAL_MODEL_NAME,
    local_dir="./models",
    token=HF_TOKEN
)

print(f"Downloaded model path: {model_path}")

css = """
.bubble-wrap {
    padding-top: calc(var(--spacing-xl) * 3) !important;
}
.message-row {
    justify-content: space-evenly !important;
    width: 100% !important;
    max-width: 100% !important;
    margin: calc(var(--spacing-xl)) 0 !important;
    padding: 0 calc(var(--spacing-xl) * 3) !important;
}
.flex-wrap.user {
    border-bottom-right-radius: var(--radius-lg) !important;
}
.flex-wrap.bot {
    border-bottom-left-radius: var(--radius-lg) !important;
}
.message.user{
    padding: 10px;
}
.message.bot{
    text-align: right;
    width: 100%;
    padding: 10px;
    border-radius: 10px;
}
.message-bubble-border {
    border-radius: 6px !important;
}
.message-buttons {
    justify-content: flex-end !important;
}
.message-buttons-left {
    align-self: end !important;
}
.message-buttons-bot, .message-buttons-user {
    right: 10px !important;
    left: auto !important;
    bottom: 2px !important;
}
.dark.message-bubble-border {
    border-color: #343140 !important;
}
.dark.user {
    background: #1e1c26 !important;
}
.dark.assistant.dark, .dark.pending.dark {
    background: #16141c !important;
}
.upload-container {
    margin-bottom: 20px;
    padding: 15px;
    border: 2px dashed #666;
    border-radius: 10px;
    background-color: #f0f0f0;
}
.dark .upload-container {
    background-color: #292733;
    border-color: #444;
}
"""

def get_messages_formatter_type(model_name):
    if "Mistral" in model_name or "BitSix" in model_name:
        return MessagesFormatterType.MISTRAL  # CHATML ๋Œ€์‹  MISTRAL ํ˜•์‹ ์‚ฌ์šฉ
    else:
        raise ValueError(f"Unsupported model: {model_name}")

@spaces.GPU
def convert_pdf_to_markdown(file):
    """PDF ํŒŒ์ผ์„ Markdown์œผ๋กœ ๋ณ€ํ™˜"""
    global document_context, document_filename
    
    if file is None:
        return "ํŒŒ์ผ์ด ์—…๋กœ๋“œ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.", {}
    
    try:
        print(f"\n=== PDF ๋ณ€ํ™˜ ์‹œ์ž‘ ===")
        print(f"ํŒŒ์ผ ๊ฒฝ๋กœ: {file.name}")
        
        # DocumentConverter ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
        converter = DocumentConverter()
        
        # ํŒŒ์ผ ๋ณ€ํ™˜
        result = converter.convert(file.name)
        
        # Markdown์œผ๋กœ ๋‚ด๋ณด๋‚ด๊ธฐ
        markdown_content = result.document.export_to_markdown()
        
        # ๋ฌธ์„œ ์ปจํ…์ŠคํŠธ ์—…๋ฐ์ดํŠธ (์ค‘์š”!)
        document_context = markdown_content
        document_filename = os.path.basename(file.name)
        
        # ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ ์ถ”์ถœ
        metadata = {
            "filename": document_filename,
            "conversion_status": "success",
            "content_length": len(markdown_content),
            "preview": markdown_content[:500] + "..." if len(markdown_content) > 500 else markdown_content
        }
        
        print(f"โœ… PDF ๋ณ€ํ™˜ ์„ฑ๊ณต!")
        print(f"๐Ÿ“„ ํŒŒ์ผ๋ช…: {document_filename}")
        print(f"๐Ÿ“ ๋ฌธ์„œ ๊ธธ์ด: {len(markdown_content)} ๋ฌธ์ž")
        print(f"๐Ÿ“ ๋ฌธ์„œ ์‹œ์ž‘ 300์ž:\n{markdown_content[:300]}...")
        print(f"=== PDF ๋ณ€ํ™˜ ์™„๋ฃŒ ===\n")
        
        # ์ „์—ญ ๋ณ€์ˆ˜ ํ™•์ธ ๋ฐ ๊ฐ•์ œ ์„ค์ •
        print(f"\n=== ์ „์—ญ ๋ณ€์ˆ˜ ์„ค์ • ์ „ ===")
        print(f"global document_context ๊ธธ์ด: {len(document_context)}")
        print(f"global document_filename: {document_filename}")
        
        # globals() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ฐ•์ œ๋กœ ์ „์—ญ ๋ณ€์ˆ˜ ์„ค์ •
        globals()['document_context'] = markdown_content
        globals()['document_filename'] = document_filename
        
        print(f"\n=== ์ „์—ญ ๋ณ€์ˆ˜ ์„ค์ • ํ›„ ===")
        print(f"global document_context ๊ธธ์ด: {len(globals()['document_context'])}")
        print(f"global document_filename: {globals()['document_filename']}")
        
        return markdown_content, metadata
        
    except Exception as e:
        error_msg = f"PDF ๋ณ€ํ™˜ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"
        print(f"โŒ {error_msg}")
        document_context = ""
        document_filename = ""
        return error_msg, {"error": str(e)}

def find_relevant_chunks(document, query, chunk_size=1500, overlap=300):
    """๋ฌธ์„œ์—์„œ ์งˆ๋ฌธ๊ณผ ๊ด€๋ จ๋œ ์ฒญํฌ ์ฐพ๊ธฐ"""
    if not document:
        return ""
    
    print(f"๊ด€๋ จ ์ฒญํฌ ์ฐพ๊ธฐ ์‹œ์ž‘ - ์ฟผ๋ฆฌ: {query}")
    
    # ๊ฐ„๋‹จํ•œ ํ‚ค์›Œ๋“œ ๊ธฐ๋ฐ˜ ๊ฒ€์ƒ‰
    query_words = query.lower().split()
    chunks = []
    
    # ๋ฌธ์„œ๋ฅผ ์ฒญํฌ๋กœ ๋‚˜๋ˆ„๊ธฐ
    for i in range(0, len(document), chunk_size - overlap):
        chunk = document[i:i + chunk_size]
        chunks.append((i, chunk))
    
    print(f"์ด {len(chunks)}๊ฐœ์˜ ์ฒญํฌ๋กœ ๋ถ„ํ• ๋จ")
    
    # ๊ฐ ์ฒญํฌ์˜ ๊ด€๋ จ์„ฑ ์ ์ˆ˜ ๊ณ„์‚ฐ
    scored_chunks = []
    for idx, chunk in chunks:
        chunk_lower = chunk.lower()
        score = sum(1 for word in query_words if word in chunk_lower)
        if score > 0:
            scored_chunks.append((score, idx, chunk))
    
    # ์ƒ์œ„ 2๊ฐœ ์ฒญํฌ ์„ ํƒ (๋ฉ”๋ชจ๋ฆฌ ์ ˆ์•ฝ)
    scored_chunks.sort(reverse=True, key=lambda x: x[0])
    relevant_chunks = scored_chunks[:2]
    
    if relevant_chunks:
        result = ""
        for score, idx, chunk in relevant_chunks:
            result += f"\n[๋ฌธ์„œ์˜ {idx}๋ฒˆ์งธ ์œ„์น˜์—์„œ ๋ฐœ์ทŒ - ๊ด€๋ จ๋„: {score}]\n{chunk}\n"
        print(f"{len(relevant_chunks)}๊ฐœ์˜ ๊ด€๋ จ ์ฒญํฌ ์ฐพ์Œ")
        return result
    else:
        # ๊ด€๋ จ ์ฒญํฌ๋ฅผ ์ฐพ์ง€ ๋ชปํ•œ ๊ฒฝ์šฐ ๋ฌธ์„œ ์‹œ์ž‘ ๋ถ€๋ถ„ ๋ฐ˜ํ™˜
        print("๊ด€๋ จ ์ฒญํฌ๋ฅผ ์ฐพ์ง€ ๋ชปํ•จ, ๋ฌธ์„œ ์‹œ์ž‘ ๋ถ€๋ถ„ ๋ฐ˜ํ™˜")
        return document[:2000]

@spaces.GPU(duration=120)
def respond(
    message,
    history: list[dict],
    system_message,
    max_tokens,
    temperature,
    top_p,
    top_k,
    repeat_penalty,
):
    global llm, llm_model
    
    # globals()๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ „์—ญ ๋ณ€์ˆ˜์— ์ ‘๊ทผ
    document_context = globals().get('document_context', '')
    document_filename = globals().get('document_filename', '')
    
    # ๋””๋ฒ„๊น…์„ ์œ„ํ•œ ์ƒ์„ธ ๋กœ๊ทธ
    print(f"\n=== RESPOND ํ•จ์ˆ˜ ์‹œ์ž‘ ===")
    print(f"์‚ฌ์šฉ์ž ๋ฉ”์‹œ์ง€: {message}")
    print(f"๋ฌธ์„œ ์ปจํ…์ŠคํŠธ ์กด์žฌ ์—ฌ๋ถ€: {bool(document_context)}")
    if document_context:
        print(f"๋ฌธ์„œ ๊ธธ์ด: {len(document_context)}")
        print(f"๋ฌธ์„œ ํŒŒ์ผ๋ช…: {document_filename}")
        print(f"๋ฌธ์„œ ์‹œ์ž‘ 100์ž: {document_context[:100]}...")
    else:
        print("โš ๏ธ document_context๊ฐ€ ๋น„์–ด์žˆ์Šต๋‹ˆ๋‹ค!")
        print(f"globals()์˜ ํ‚ค๋“ค: {list(globals().keys())[:20]}...")  # ์ฒ˜์Œ 20๊ฐœ ํ‚ค๋งŒ
    
    chat_template = get_messages_formatter_type(MISTRAL_MODEL_NAME)
    
    # ๋ชจ๋ธ ํŒŒ์ผ ๊ฒฝ๋กœ ํ™•์ธ
    model_path_local = os.path.join("./models", MISTRAL_MODEL_NAME)
    
    if llm is None or llm_model != MISTRAL_MODEL_NAME:
        print("LLM ๋ชจ๋ธ ๋กœ๋”ฉ ์ค‘...")
        llm = Llama(
            model_path=model_path_local,
            flash_attn=True,
            n_gpu_layers=81,
            n_batch=1024,
            n_ctx=16384,  # ์ปจํ…์ŠคํŠธ ํฌ๊ธฐ
            verbose=True  # ๋””๋ฒ„๊น…์„ ์œ„ํ•œ ์ƒ์„ธ ๋กœ๊ทธ
        )
        llm_model = MISTRAL_MODEL_NAME
        print("LLM ๋ชจ๋ธ ๋กœ๋”ฉ ์™„๋ฃŒ!")
    
    provider = LlamaCppPythonProvider(llm)
    
    # ํ•œ๊ตญ์–ด ๋‹ต๋ณ€์„ ์œ„ํ•œ ๊ธฐ๋ณธ ์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€
    korean_system_message = system_message  # ์‚ฌ์šฉ์ž๊ฐ€ ์„ค์ •ํ•œ ์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€ ์‚ฌ์šฉ
    
    # ๋ฌธ์„œ ์ปจํ…์ŠคํŠธ๊ฐ€ ์žˆ์œผ๋ฉด ์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€์™€ ์‚ฌ์šฉ์ž ๋ฉ”์‹œ์ง€ ๋ชจ๋‘์— ํฌํ•จ
    if document_context and len(document_context) > 0:
        doc_length = len(document_context)
        print(f"๐Ÿ“„ ๋ฌธ์„œ ์ปจํ…์ŠคํŠธ๋ฅผ ๋ฉ”์‹œ์ง€์— ํฌํ•จํ•ฉ๋‹ˆ๋‹ค: {doc_length} ๋ฌธ์ž")
        
        # ์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€์—๋„ ๋ฌธ์„œ ์ •๋ณด ์ถ”๊ฐ€
        korean_system_message += f"\n\nํ˜„์žฌ '{document_filename}' PDF ๋ฌธ์„œ๊ฐ€ ๋กœ๋“œ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ์‚ฌ์šฉ์ž์˜ ๋ชจ๋“  ์งˆ๋ฌธ์— ๋Œ€ํ•ด ์ด ๋ฌธ์„œ์˜ ๋‚ด์šฉ์„ ๋ฐ˜๋“œ์‹œ ์ฐธ์กฐํ•˜์—ฌ ๋‹ต๋ณ€ํ•˜์„ธ์š”."
        
        # ๋ฌธ์„œ ๋‚ด์šฉ์„ ์ ์ ˆํ•œ ํฌ๊ธฐ๋กœ ์ œํ•œ
        max_doc_length = 4000  # ์ตœ๋Œ€ 4000์ž๋กœ ์ œํ•œ
        if doc_length > max_doc_length:
            # ๋ฌธ์„œ๊ฐ€ ๋„ˆ๋ฌด ๊ธด ๊ฒฝ์šฐ ์ฒ˜์Œ๊ณผ ๋ ๋ถ€๋ถ„๋งŒ ํฌํ•จ
            doc_snippet = document_context[:2000] + "\n\n[... ์ค‘๊ฐ„ ๋‚ด์šฉ ์ƒ๋žต ...]\n\n" + document_context[-1500:]
            enhanced_message = f"""์—…๋กœ๋“œ๋œ PDF ๋ฌธ์„œ ์ •๋ณด:
- ํŒŒ์ผ๋ช…: {document_filename}
- ๋ฌธ์„œ ๊ธธ์ด: {doc_length} ๋ฌธ์ž

๋ฌธ์„œ ๋‚ด์šฉ (์ผ๋ถ€):
{doc_snippet}

์‚ฌ์šฉ์ž ์งˆ๋ฌธ: {message}

์œ„ ๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ ํ•œ๊ตญ์–ด๋กœ ๋‹ต๋ณ€ํ•ด์ฃผ์„ธ์š”."""
        else:
            # ์งง์€ ๋ฌธ์„œ๋Š” ์ „์ฒด ํฌํ•จ
            enhanced_message = f"""์—…๋กœ๋“œ๋œ PDF ๋ฌธ์„œ ์ •๋ณด:
- ํŒŒ์ผ๋ช…: {document_filename}
- ๋ฌธ์„œ ๊ธธ์ด: {doc_length} ๋ฌธ์ž

๋ฌธ์„œ ๋‚ด์šฉ:
{document_context}

์‚ฌ์šฉ์ž ์งˆ๋ฌธ: {message}

์œ„ ๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ ํ•˜์—ฌ ํ•œ๊ตญ์–ด๋กœ ๋‹ต๋ณ€ํ•ด์ฃผ์„ธ์š”."""
        
        print(f"๊ฐ•ํ™”๋œ ๋ฉ”์‹œ์ง€ ๊ธธ์ด: {len(enhanced_message)}")
        print(f"๋ฉ”์‹œ์ง€ ๋ฏธ๋ฆฌ๋ณด๊ธฐ (์ฒ˜์Œ 300์ž):\n{enhanced_message[:300]}...")
        
        # ๋””๋ฒ„๊ทธ: ์ตœ์ข… ๋ฉ”์‹œ์ง€ ํŒŒ์ผ๋กœ ์ €์žฅ (ํ™•์ธ์šฉ)
        with open("debug_last_message.txt", "w", encoding="utf-8") as f:
            f.write(f"=== ๋””๋ฒ„๊ทธ ์ •๋ณด ===\n")
            f.write(f"๋ฌธ์„œ ๊ธธ์ด: {len(document_context)}\n")
            f.write(f"ํŒŒ์ผ๋ช…: {document_filename}\n")
            f.write(f"์‚ฌ์šฉ์ž ์งˆ๋ฌธ: {message}\n")
            f.write(f"\n=== ์ „์†ก๋  ๋ฉ”์‹œ์ง€ ===\n")
            f.write(enhanced_message)
    else:
        # ๋ฌธ์„œ๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ
        enhanced_message = message
        if any(keyword in message.lower() for keyword in ["๋ฌธ์„œ", "pdf", "์—…๋กœ๋“œ", "ํŒŒ์ผ", "๋‚ด์šฉ", "์š”์•ฝ"]):
            enhanced_message = f"{message}\n\n[์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€: ํ˜„์žฌ ์—…๋กœ๋“œ๋œ PDF ๋ฌธ์„œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. PDF ํŒŒ์ผ์„ ๋จผ์ € ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”.]"
            print("๋ฌธ์„œ ๊ด€๋ จ ์งˆ๋ฌธ์ด์ง€๋งŒ ๋ฌธ์„œ๊ฐ€ ์—†์Œ")
        
        # ๋””๋ฒ„๊ทธ ๋ฉ”์‹œ์ง€
        print("โš ๏ธ ๊ฒฝ๊ณ : document_context๊ฐ€ ๋น„์–ด์žˆ์Šต๋‹ˆ๋‹ค!")
        print(f"document_context ํƒ€์ž…: {type(document_context)}")
        print(f"document_context ๊ฐ’: {repr(document_context)}")
        print(f"document_filename: {document_filename}")

    settings = provider.get_provider_default_settings()
    settings.temperature = temperature
    settings.top_k = top_k
    settings.top_p = top_p
    settings.max_tokens = max_tokens
    settings.repeat_penalty = repeat_penalty
    settings.stream = True

    # ์‹œ์Šคํ…œ ํ”„๋กฌํ”„ํŠธ์— ๋ฌธ์„œ ๋‚ด์šฉ ์ง์ ‘ ํฌํ•จ (๋ฌธ์„œ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ)
    if document_context and len(document_context) > 0:
        doc_snippet = document_context[:3000]  # ์ฒ˜์Œ 3000์ž๋งŒ ์‚ฌ์šฉ
        enhanced_system_prompt = f"""{korean_system_message}

ํ˜„์žฌ ๋กœ๋“œ๋œ PDF ๋ฌธ์„œ:
ํŒŒ์ผ๋ช…: {document_filename}
๋ฌธ์„œ ๋‚ด์šฉ:
{doc_snippet}
{'' if len(document_context) <= 3000 else '... (์ดํ•˜ ์ƒ๋žต)'}

์œ„ ๋ฌธ์„œ์˜ ๋‚ด์šฉ์„ ๋ฐ”ํƒ•์œผ๋กœ ์‚ฌ์šฉ์ž์˜ ์งˆ๋ฌธ์— ๋‹ต๋ณ€ํ•˜์„ธ์š”."""
        
        # ์‚ฌ์šฉ์ž ๋ฉ”์‹œ์ง€๋Š” ๋‹จ์ˆœํ•˜๊ฒŒ
        final_message = message
    else:
        enhanced_system_prompt = korean_system_message
        final_message = enhanced_message

    agent = LlamaCppAgent(
        provider,
        system_prompt=enhanced_system_prompt,
        predefined_messages_formatter_type=chat_template,
        debug_output=True
    )

    messages = BasicChatHistory()

    # ์ด์ „ ๋Œ€ํ™” ๊ธฐ๋ก ์ถ”๊ฐ€ (์ˆ˜์ •๋จ)
    for i in range(0, len(history)):
        # ํ˜„์žฌ ๋ฉ”์‹œ์ง€๋Š” ์ œ์™ธ
        if i < len(history) - 1 and history[i][1] is not None:
            # ์‚ฌ์šฉ์ž ๋ฉ”์‹œ์ง€
            messages.add_message({
                'role': Roles.user,
                'content': history[i][0]
            })
            # ์–ด์‹œ์Šคํ„ดํŠธ ๋ฉ”์‹œ์ง€
            messages.add_message({
                'role': Roles.assistant,
                'content': history[i][1]
            })
    
    print(f"์ตœ์ข… ๋ฉ”์‹œ์ง€ ์ „์†ก ์ค‘: {final_message}")
    
    # ์ŠคํŠธ๋ฆผ ์‘๋‹ต ์ƒ์„ฑ
    try:
        stream = agent.get_chat_response(
            final_message,  # ๋‹จ์ˆœํ•œ ๋ฉ”์‹œ์ง€ ์‚ฌ์šฉ
            llm_sampling_settings=settings,
            chat_history=messages,
            returns_streaming_generator=True,
            print_output=False
        )
        
        outputs = ""
        for output in stream:
            outputs += output
            yield outputs
    except Exception as e:
        print(f"์ŠคํŠธ๋ฆผ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜: {e}")
        yield "์ฃ„์†กํ•ฉ๋‹ˆ๋‹ค. ์‘๋‹ต ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์‹œ๋„ํ•ด์ฃผ์„ธ์š”."

def clear_document_context():
    """๋ฌธ์„œ ์ปจํ…์ŠคํŠธ ์ดˆ๊ธฐํ™”"""
    global document_context, document_filename
    document_context = ""
    document_filename = ""
    return "๐Ÿ“ญ ๋ฌธ์„œ ์ปจํ…์ŠคํŠธ๊ฐ€ ์ดˆ๊ธฐํ™”๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ƒˆ๋กœ์šด PDF๋ฅผ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."

def check_document_status():
    """ํ˜„์žฌ ๋ฌธ์„œ ์ƒํƒœ ํ™•์ธ"""
    global document_context, document_filename
    print(f"\n=== ๋ฌธ์„œ ์ƒํƒœ ํ™•์ธ ===")
    print(f"document_context ํƒ€์ž…: {type(document_context)}")
    print(f"document_context ๊ธธ์ด: {len(document_context) if document_context else 0}")
    print(f"document_filename: '{document_filename}'")
    
    if document_context and len(document_context) > 0:
        status = f"โœ… ๋ฌธ์„œ๊ฐ€ ๋กœ๋“œ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.\n๐Ÿ“„ ํŒŒ์ผ๋ช…: {document_filename}\n๐Ÿ“ ๋ฌธ์„œ ๊ธธ์ด: {len(document_context):,} ๋ฌธ์ž"
        print(f"๋ฌธ์„œ ์ฒซ 100์ž: {document_context[:100]}")
        return status
    else:
        return "๐Ÿ“ญ ๋กœ๋“œ๋œ ๋ฌธ์„œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. PDF ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."

# Gradio ์ธํ„ฐํŽ˜์ด์Šค ๊ตฌ์„ฑ
with gr.Blocks(theme=gr.themes.Soft(
        primary_hue="blue",
        secondary_hue="cyan",
        neutral_hue="gray",
        font=[gr.themes.GoogleFont("Exo"), "ui-sans-serif", "system-ui", "sans-serif"]
    ).set(
        body_background_fill="#f8f9fa",
        block_background_fill="#ffffff",
        block_border_width="1px",
        block_title_background_fill="#e9ecef",
        input_background_fill="#ffffff",
        button_secondary_background_fill="#e9ecef",
        border_color_accent="#dee2e6",
        border_color_primary="#ced4da",
        background_fill_secondary="#f8f9fa",
        color_accent_soft="transparent",
        code_background_fill="#f1f3f5",
    ), css=css) as demo:
    
    gr.Markdown("# ์˜จํ”„๋ ˆ๋ฏธ์Šค ์ตœ์ ํ™” 'LLM+RAG ๋ชจ๋ธ' ์„œ๋น„์Šค by VIDraft")
    gr.Markdown("๐Ÿ“„ PDF ๋ฌธ์„œ๋ฅผ ์—…๋กœ๋“œํ•˜๋ฉด AI๊ฐ€ ๋ฌธ์„œ ๋‚ด์šฉ์„ ๋ถ„์„ํ•˜์—ฌ ์งˆ๋ฌธ์— ๋‹ต๋ณ€ํ•ฉ๋‹ˆ๋‹ค.")
    gr.Markdown("๐Ÿ’ก ์‚ฌ์šฉ๋ฒ•: 1) ์•„๋ž˜์—์„œ PDF ์—…๋กœ๋“œ โ†’ 2) ๋ฌธ์„œ์— ๋Œ€ํ•œ ์งˆ๋ฌธ ์ž…๋ ฅ โ†’ 3) AI๊ฐ€ ํ•œ๊ตญ์–ด๋กœ ๋‹ต๋ณ€")
    
    # ์ฑ„ํŒ… ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์œ„์ชฝ์— ๋ฐฐ์น˜
    with gr.Row():
        with gr.Column():
            # ์ฑ„ํŒ… ์ธํ„ฐํŽ˜์ด์Šค
            chatbot = gr.Chatbot(elem_id="chatbot", height=500)
            msg = gr.Textbox(
                label="๋ฉ”์‹œ์ง€ ์ž…๋ ฅ",
                placeholder="์งˆ๋ฌธ์„ ์ž…๋ ฅํ•˜์„ธ์š”... (PDF๋ฅผ ์—…๋กœ๋“œํ•˜๋ฉด ๋ฌธ์„œ ๋‚ด์šฉ์— ๋Œ€ํ•ด ์งˆ๋ฌธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค)",
                lines=2
            )
            with gr.Row():
                submit = gr.Button("์ „์†ก", variant="primary")
                clear_chat = gr.Button("๋Œ€ํ™” ์ดˆ๊ธฐํ™”")
    
    # ์˜ˆ์ œ๋ฅผ ์ค‘๊ฐ„์— ๋ฐฐ์น˜
    gr.Examples(
        examples=[
            ["์ด ๋ฌธ์„œ๋Š” ๋ฌด์—‡์— ๊ด€ํ•œ ๋‚ด์šฉ์ธ๊ฐ€์š”?"],
            ["์—…๋กœ๋“œํ•œ PDF ๋ฌธ์„œ์˜ ์ฃผ์š” ๋‚ด์šฉ์„ ํ•œ๊ตญ์–ด๋กœ ์š”์•ฝํ•ด์ฃผ์„ธ์š”."],
            ["๋ฌธ์„œ์— ๋‚˜์˜จ ์ผ์ •์„ ์•Œ๋ ค์ฃผ์„ธ์š”."],
            ["๋ฌธ์„œ์—์„œ ๊ฐ€์žฅ ์ค‘์š”ํ•œ 3๊ฐ€์ง€ ํ•ต์‹ฌ ํฌ์ธํŠธ๋Š” ๋ฌด์—‡์ธ๊ฐ€์š”?"],
            ["์ด ํ–‰์‚ฌ์˜ ๊ฐœ์š”๋ฅผ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”."]
        ],
        inputs=msg
    )
    
    # PDF ์—…๋กœ๋“œ ์„น์…˜์„ ์•„๋ž˜์ชฝ์— ๋ฐฐ์น˜
    with gr.Accordion("๐Ÿ“„ PDF ๋ฌธ์„œ ์—…๋กœ๋“œ", open=True):
        with gr.Row():
            with gr.Column(scale=1):
                file_input = gr.File(
                    label="PDF ๋ฌธ์„œ ์„ ํƒ",
                    file_types=[".pdf"],
                    type="filepath"
                )
                with gr.Row():
                    convert_button = gr.Button("๋ฌธ์„œ ๋ณ€ํ™˜", variant="primary")
                    clear_button = gr.Button("๋ฌธ์„œ ์ดˆ๊ธฐํ™”", variant="secondary")
                    test_button = gr.Button("๋ฌธ์„œ ํ…Œ์ŠคํŠธ", variant="secondary")
                
                status_text = gr.Textbox(
                    label="๋ฌธ์„œ ์ƒํƒœ", 
                    interactive=False,
                    value=check_document_status(),
                    lines=3
                )
            
            with gr.Column(scale=1):
                with gr.Accordion("๋ณ€ํ™˜๋œ ๋ฌธ์„œ ๋ฏธ๋ฆฌ๋ณด๊ธฐ", open=False):
                    converted_text = gr.Textbox(
                        label="Markdown ๋ณ€ํ™˜ ๊ฒฐ๊ณผ",
                        lines=10,
                        max_lines=20,
                        interactive=False
                    )
                    metadata_output = gr.JSON(label="๋ฉ”ํƒ€๋ฐ์ดํ„ฐ")
    
    # ๊ณ ๊ธ‰ ์„ค์ •์„ ๊ฐ€์žฅ ์•„๋ž˜์— ๋ฐฐ์น˜
    with gr.Accordion("โš™๏ธ ๊ณ ๊ธ‰ ์„ค์ •", open=False):
        system_message = gr.Textbox(
            value="๋‹น์‹ ์€ ํ•œ๊ตญ์–ด๋กœ ๋‹ต๋ณ€ํ•˜๋Š” AI ์–ด์‹œ์Šคํ„ดํŠธ์ž…๋‹ˆ๋‹ค. PDF ๋ฌธ์„œ๊ฐ€ ์ œ๊ณต๋˜๋ฉด ๊ทธ ๋‚ด์šฉ์„ ์ •ํ™•ํžˆ ๋ถ„์„ํ•˜์—ฌ ๋‹ต๋ณ€ํ•ฉ๋‹ˆ๋‹ค.",
            label="์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€",
            lines=3
        )
        max_tokens = gr.Slider(minimum=1, maximum=4096, value=2048, step=1, label="์ตœ๋Œ€ ํ† ํฐ ์ˆ˜")
        temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.3, step=0.1, label="Temperature (๋‚ฎ์„์ˆ˜๋ก ์ผ๊ด€์„ฑ ์žˆ์Œ)")
        top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.90, step=0.05, label="Top-p")
        top_k = gr.Slider(minimum=0, maximum=100, value=40, step=1, label="Top-k")
        repeat_penalty = gr.Slider(minimum=0.0, maximum=2.0, value=1.1, step=0.1, label="Repetition penalty")
    
    # ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ
    def user_submit(message, history):
        return "", history + [[message, None]]
    
    def bot_response(history, system_msg, max_tok, temp, top_p_val, top_k_val, rep_pen):
        if history and history[-1][1] is None:
            user_message = history[-1][0]
            
            # ๋””๋ฒ„๊น…: ๋ฌธ์„œ ์ปจํ…์ŠคํŠธ ์ƒํƒœ ํ™•์ธ
            global document_context, document_filename
            print(f"\n=== BOT RESPONSE ์‹œ์ž‘ ===")
            print(f"์‚ฌ์šฉ์ž ๋ฉ”์‹œ์ง€: {user_message}")
            if document_context:
                print(f"๐Ÿ“„ ๋ฌธ์„œ ์ปจํ…์ŠคํŠธ ํ™œ์„ฑ: {document_filename} ({len(document_context)} ๋ฌธ์ž)")
                print(f"๋ฌธ์„œ ์ฒซ 200์ž: {document_context[:200]}...")
            else:
                print("๐Ÿ“ญ ๋ฌธ์„œ ์ปจํ…์ŠคํŠธ ์—†์Œ")
            
            # ๋‹จ์ˆœํ•œ ํ˜•์‹ ์‚ฌ์šฉ - [user_message, assistant_message]
            previous_history = []
            for i in range(len(history) - 1):
                if history[i][1] is not None:
                    previous_history.append({
                        "user": history[i][0],
                        "assistant": history[i][1]
                    })
            
            print(f"์ด์ „ ๋Œ€ํ™” ์ˆ˜: {len(previous_history)}")
            
            # ๋ฌธ์„œ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ ํŠน๋ณ„ ์ฒ˜๋ฆฌ
            if document_context and len(document_context) > 0:
                print(f"๐Ÿ“„ ๋ฌธ์„œ ๊ธฐ๋ฐ˜ ์‘๋‹ต ์ƒ์„ฑ ์ค‘... (๋ฌธ์„œ ๊ธธ์ด: {len(document_context)})")
            
            bot_message = ""
            try:
                for token in respond(
                    user_message,
                    previous_history,
                    system_msg,
                    max_tok,
                    temp,
                    top_p_val,
                    top_k_val,
                    rep_pen
                ):
                    bot_message = token
                    history[-1][1] = bot_message
                    yield history
            except Exception as e:
                print(f"โŒ ์‘๋‹ต ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜: {e}")
                import traceback
                traceback.print_exc()
                history[-1][1] = "์ฃ„์†กํ•ฉ๋‹ˆ๋‹ค. ์‘๋‹ต ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์‹œ๋„ํ•ด์ฃผ์„ธ์š”."
                yield history
    
    # PDF ๋ณ€ํ™˜ ์ด๋ฒคํŠธ
    def on_pdf_convert(file):
        """PDF ๋ณ€ํ™˜ ๋ฐ ์ƒํƒœ ์—…๋ฐ์ดํŠธ"""
        global document_context, document_filename
        
        if file is None:
            return "", {}, "โŒ ํŒŒ์ผ์ด ์„ ํƒ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค."
        
        markdown_content, metadata = convert_pdf_to_markdown(file)
        
        if "error" in metadata:
            status = f"โŒ ๋ณ€ํ™˜ ์‹คํŒจ: {metadata['error']}"
        else:
            # ์ „์—ญ ๋ณ€์ˆ˜ ๋‹ค์‹œ ํ•œ๋ฒˆ ํ™•์ธ ๋ฐ ์„ค์ • (globals() ์‚ฌ์šฉ)
            globals()['document_context'] = markdown_content
            globals()['document_filename'] = metadata['filename']
            
            status = f"โœ… PDF ๋ฌธ์„œ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๋ณ€ํ™˜๋˜์—ˆ์Šต๋‹ˆ๋‹ค!\n๐Ÿ“„ ํŒŒ์ผ๋ช…: {metadata['filename']}\n๐Ÿ“ ๋ฌธ์„œ ๊ธธ์ด: {metadata['content_length']:,} ๋ฌธ์ž\n\n์ด์ œ ๋ฌธ์„œ ๋‚ด์šฉ์— ๋Œ€ํ•ด ํ•œ๊ตญ์–ด๋กœ ์งˆ๋ฌธํ•˜์‹ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.\n\n์˜ˆ์‹œ ์งˆ๋ฌธ:\n- ์ด ๋ฌธ์„œ์˜ ์ฃผ์š” ๋‚ด์šฉ์„ ์š”์•ฝํ•ด์ฃผ์„ธ์š”\n- ๋ฌธ์„œ์— ๋‚˜์˜จ ํ•ต์‹ฌ ๊ฐœ๋…์„ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”"
            
            print(f"\nโœ… ๋ฌธ์„œ ๋กœ๋“œ ์™„๋ฃŒ ํ™•์ธ:")
            print(f"- globals()['document_context'] ๊ธธ์ด: {len(globals()['document_context'])}")
            print(f"- globals()['document_filename']: {globals()['document_filename']}")
            
            # ์ตœ์ข… ํ™•์ธ
            if len(globals()['document_context']) > 0:
                print("โœ… ๋ฌธ์„œ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ์ „์—ญ ๋ณ€์ˆ˜์— ์ €์žฅ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!")
            else:
                print("โŒ ๊ฒฝ๊ณ : ๋ฌธ์„œ๊ฐ€ ์ „์—ญ ๋ณ€์ˆ˜์— ์ €์žฅ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค!")
        
        return markdown_content, metadata, status
    
    # ํŒŒ์ผ ์—…๋กœ๋“œ ์‹œ ์ž๋™ ๋ณ€ํ™˜
    file_input.change(
        fn=on_pdf_convert,
        inputs=[file_input],
        outputs=[converted_text, metadata_output, status_text]
    )
    
    # ์ˆ˜๋™ ๋ณ€ํ™˜ ๋ฒ„ํŠผ
    convert_button.click(
        fn=on_pdf_convert,
        inputs=[file_input],
        outputs=[converted_text, metadata_output, status_text]
    )
    
    # ๋ฌธ์„œ ํ…Œ์ŠคํŠธ ํ•จ์ˆ˜
    def test_document():
        """ํ˜„์žฌ ๋กœ๋“œ๋œ ๋ฌธ์„œ ํ…Œ์ŠคํŠธ"""
        global document_context, document_filename
        if document_context:
            test_msg = f"โœ… ๋ฌธ์„œ ํ…Œ์ŠคํŠธ ๊ฒฐ๊ณผ:\n"
            test_msg += f"๐Ÿ“„ ํŒŒ์ผ๋ช…: {document_filename}\n"
            test_msg += f"๐Ÿ“ ์ „์ฒด ๊ธธ์ด: {len(document_context):,} ๋ฌธ์ž\n"
            test_msg += f"๐Ÿ“ ์ฒซ 500์ž:\n{document_context[:500]}..."
            return test_msg
        else:
            return "โŒ ํ˜„์žฌ ๋กœ๋“œ๋œ ๋ฌธ์„œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."
    
    test_button.click(
        fn=test_document,
        outputs=[status_text]
    )
    
    clear_button.click(
        fn=clear_document_context,
        outputs=[status_text]
    ).then(
        fn=lambda: ("", {}, check_document_status()),
        outputs=[converted_text, metadata_output, status_text]
    )
    
    # ์ฑ„ํŒ… ์ด๋ฒคํŠธ
    msg.submit(user_submit, [msg, chatbot], [msg, chatbot]).then(
        bot_response, 
        [chatbot, system_message, max_tokens, temperature, top_p, top_k, repeat_penalty], 
        chatbot
    )
    
    submit.click(user_submit, [msg, chatbot], [msg, chatbot]).then(
        bot_response, 
        [chatbot, system_message, max_tokens, temperature, top_p, top_k, repeat_penalty], 
        chatbot
    )
    
    clear_chat.click(lambda: [], None, chatbot)

if __name__ == "__main__":
    # ํ•„์š”ํ•œ ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ
    os.makedirs("./models", exist_ok=True)
    
    # ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ํ™•์ธ
    if not HF_TOKEN:
        print("โš ๏ธ  ๊ฒฝ๊ณ : HF_TOKEN์ด ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ๋ชจ๋ธ ๋‹ค์šด๋กœ๋“œ์— ์ œํ•œ์ด ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")
        print("ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์„ค์ •ํ•˜๋ ค๋ฉด: export HF_TOKEN='your_huggingface_token'")
    
    demo.launch(
        server_name="0.0.0.0",  # ๋กœ์ปฌ ๋„คํŠธ์›Œํฌ์—์„œ ์ ‘๊ทผ ๊ฐ€๋Šฅ
        server_port=7860,
        share=False  # ์˜จํ”„๋ ˆ๋ฏธ์Šค ํ™˜๊ฒฝ์ด๋ฏ€๋กœ ๊ณต์œ  ๋น„ํ™œ์„ฑํ™”
    )