Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,6 @@ from typing import List, Dict, Any, Optional, Tuple
|
|
| 4 |
import hashlib
|
| 5 |
from datetime import datetime
|
| 6 |
import numpy as np
|
| 7 |
-
from gradio_client import Client
|
| 8 |
|
| 9 |
# PDF 처리 라이브러리
|
| 10 |
try:
|
|
@@ -38,11 +37,6 @@ custom_css = """
|
|
| 38 |
margin: 12px;
|
| 39 |
}
|
| 40 |
|
| 41 |
-
.main-container:hover {
|
| 42 |
-
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
|
| 43 |
-
transition: all 0.3s ease;
|
| 44 |
-
}
|
| 45 |
-
|
| 46 |
/* Status messages styling */
|
| 47 |
.pdf-status {
|
| 48 |
padding: 12px 16px;
|
|
@@ -50,7 +44,6 @@ custom_css = """
|
|
| 50 |
margin: 12px 0;
|
| 51 |
font-size: 0.95rem;
|
| 52 |
font-weight: 500;
|
| 53 |
-
backdrop-filter: blur(10px);
|
| 54 |
}
|
| 55 |
|
| 56 |
.pdf-success {
|
|
@@ -71,40 +64,14 @@ custom_css = """
|
|
| 71 |
color: #0c5460;
|
| 72 |
}
|
| 73 |
|
| 74 |
-
.pdf-warning {
|
| 75 |
-
background: linear-gradient(135deg, #fff3cd 0%, #ffeeba 100%);
|
| 76 |
-
border: 1px solid #ffeaa7;
|
| 77 |
-
color: #856404;
|
| 78 |
-
}
|
| 79 |
-
|
| 80 |
-
/* RAG context display */
|
| 81 |
.rag-context {
|
| 82 |
background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
|
| 83 |
border-left: 4px solid #f59e0b;
|
| 84 |
-
padding:
|
| 85 |
-
margin:
|
| 86 |
border-radius: 8px;
|
| 87 |
font-size: 0.9rem;
|
| 88 |
}
|
| 89 |
-
|
| 90 |
-
/* Chat message styling */
|
| 91 |
-
.message {
|
| 92 |
-
padding: 12px 16px;
|
| 93 |
-
margin: 8px 4px;
|
| 94 |
-
border-radius: 12px;
|
| 95 |
-
max-width: 80%;
|
| 96 |
-
}
|
| 97 |
-
|
| 98 |
-
.user-message {
|
| 99 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 100 |
-
color: white;
|
| 101 |
-
margin-left: auto;
|
| 102 |
-
}
|
| 103 |
-
|
| 104 |
-
.bot-message {
|
| 105 |
-
background: #f3f4f6;
|
| 106 |
-
color: #1f2937;
|
| 107 |
-
}
|
| 108 |
"""
|
| 109 |
|
| 110 |
class SimpleTextSplitter:
|
|
@@ -256,7 +223,7 @@ class PDFRAGSystem:
|
|
| 256 |
for doc_id in doc_ids:
|
| 257 |
if doc_id in self.document_chunks:
|
| 258 |
chunks = self.document_chunks[doc_id]
|
| 259 |
-
for chunk in chunks[:
|
| 260 |
chunk_lower = chunk.lower()
|
| 261 |
score = sum(1 for keyword in query_keywords if keyword in chunk_lower)
|
| 262 |
if score > 0:
|
|
@@ -279,33 +246,33 @@ class PDFRAGSystem:
|
|
| 279 |
|
| 280 |
# 프롬프트 구성
|
| 281 |
prompt_parts = []
|
| 282 |
-
prompt_parts.append("
|
| 283 |
-
prompt_parts.append("=" *
|
| 284 |
|
| 285 |
for i, chunk in enumerate(relevant_chunks, 1):
|
| 286 |
-
prompt_parts.append(f"\n[
|
| 287 |
-
content = chunk['content'][:
|
| 288 |
prompt_parts.append(content)
|
| 289 |
-
prompt_parts.append("")
|
| 290 |
|
| 291 |
-
prompt_parts.append("=" *
|
| 292 |
prompt_parts.append(f"\n질문: {query}")
|
| 293 |
-
prompt_parts.append("\n위 참고문서의 내용을 바탕으로 정확하고 상세하게 답변해주세요:")
|
| 294 |
|
| 295 |
return "\n".join(prompt_parts)
|
| 296 |
|
| 297 |
# RAG 시스템 인스턴스 생성
|
| 298 |
rag_system = PDFRAGSystem()
|
| 299 |
|
| 300 |
-
# State
|
| 301 |
current_model = gr.State("openai/gpt-oss-120b")
|
| 302 |
-
|
|
|
|
|
|
|
| 303 |
|
| 304 |
def upload_pdf(file):
|
| 305 |
"""PDF 파일 업로드 처리"""
|
| 306 |
if file is None:
|
| 307 |
return (
|
| 308 |
-
gr.update(value="<div class='pdf-status pdf-
|
| 309 |
gr.update(choices=[]),
|
| 310 |
gr.update(value=False)
|
| 311 |
)
|
|
@@ -323,10 +290,9 @@ def upload_pdf(file):
|
|
| 323 |
if result["success"]:
|
| 324 |
status_html = f"""
|
| 325 |
<div class="pdf-status pdf-success">
|
| 326 |
-
✅ PDF 업로드
|
| 327 |
-
📄
|
| 328 |
-
📑
|
| 329 |
-
🔍 청크: {result['chunks']}개 생성
|
| 330 |
</div>
|
| 331 |
"""
|
| 332 |
|
|
@@ -340,12 +306,11 @@ def upload_pdf(file):
|
|
| 340 |
gr.update(value=True)
|
| 341 |
)
|
| 342 |
else:
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
return status_html, gr.update(), gr.update(value=False)
|
| 349 |
|
| 350 |
except Exception as e:
|
| 351 |
return (
|
|
@@ -368,55 +333,32 @@ def clear_documents():
|
|
| 368 |
|
| 369 |
def switch_model(model_choice):
|
| 370 |
"""Function to switch between models"""
|
| 371 |
-
|
| 372 |
-
return gr.update(visible=True), gr.update(visible=False), model_choice
|
| 373 |
-
else:
|
| 374 |
-
return gr.update(visible=False), gr.update(visible=True), model_choice
|
| 375 |
|
| 376 |
-
def
|
| 377 |
-
"""RAG
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
if enable_rag and selected_docs:
|
| 384 |
-
doc_ids = [doc.split(":")[0] for doc in selected_docs]
|
| 385 |
-
enhanced_message = rag_system.create_rag_prompt(message, doc_ids, top_k)
|
| 386 |
-
|
| 387 |
-
# 디버그: RAG 적용 확인
|
| 388 |
-
print(f"RAG 적용됨 - 원본: {len(message)}자, 강화: {len(enhanced_message)}자")
|
| 389 |
-
else:
|
| 390 |
-
enhanced_message = message
|
| 391 |
-
|
| 392 |
-
try:
|
| 393 |
-
# 여기서 실제 모델 API를 호출해야 합니다
|
| 394 |
-
# 임시로 모의 응답 생성
|
| 395 |
-
if enable_rag and selected_docs:
|
| 396 |
-
response = f"""📚 [RAG 기반 답변]
|
| 397 |
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
{enhanced_message[:500]}...
|
| 401 |
-
|
| 402 |
-
[참고: 실제 모델 API 연결 필요]
|
| 403 |
-
"""
|
| 404 |
-
else:
|
| 405 |
-
response = f"""💬 [일반 답변]
|
| 406 |
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
|
| 419 |
-
return
|
| 420 |
|
| 421 |
# Main interface with soft theme
|
| 422 |
with gr.Blocks(fill_height=True, theme=gr.themes.Soft(), css=custom_css) as demo:
|
|
@@ -425,50 +367,50 @@ with gr.Blocks(fill_height=True, theme=gr.themes.Soft(), css=custom_css) as demo
|
|
| 425 |
# Sidebar
|
| 426 |
with gr.Column(scale=1):
|
| 427 |
with gr.Group(elem_classes="main-container"):
|
| 428 |
-
gr.Markdown("#
|
| 429 |
gr.Markdown(
|
| 430 |
-
"OpenAI GPT-OSS
|
|
|
|
| 431 |
)
|
| 432 |
|
| 433 |
-
# Login button
|
| 434 |
-
login_button = gr.LoginButton("🔐 Hugging Face 로그인", size="lg")
|
| 435 |
-
|
| 436 |
# Model selection
|
| 437 |
model_dropdown = gr.Dropdown(
|
| 438 |
choices=["openai/gpt-oss-120b", "openai/gpt-oss-20b"],
|
| 439 |
value="openai/gpt-oss-120b",
|
| 440 |
-
label="📊
|
| 441 |
-
info="
|
| 442 |
)
|
| 443 |
|
|
|
|
|
|
|
|
|
|
| 444 |
# Reload button to apply model change
|
| 445 |
-
reload_btn = gr.Button("🔄
|
| 446 |
|
| 447 |
# RAG Settings
|
| 448 |
-
with gr.Accordion("📚 PDF RAG
|
| 449 |
pdf_upload = gr.File(
|
| 450 |
-
label="
|
| 451 |
file_types=[".pdf"],
|
| 452 |
type="filepath"
|
| 453 |
)
|
| 454 |
|
| 455 |
upload_status = gr.HTML(
|
| 456 |
-
value="<div class='pdf-status pdf-info'
|
| 457 |
)
|
| 458 |
|
| 459 |
document_list = gr.CheckboxGroup(
|
| 460 |
choices=[],
|
| 461 |
-
label="📄
|
| 462 |
-
info="
|
| 463 |
)
|
| 464 |
|
| 465 |
-
|
| 466 |
-
clear_btn = gr.Button("🗑️ 모든 문서 삭제", size="sm", variant="secondary")
|
| 467 |
|
| 468 |
enable_rag = gr.Checkbox(
|
| 469 |
-
label="✨ RAG
|
| 470 |
value=False,
|
| 471 |
-
info="
|
| 472 |
)
|
| 473 |
|
| 474 |
top_k_chunks = gr.Slider(
|
|
@@ -476,27 +418,26 @@ with gr.Blocks(fill_height=True, theme=gr.themes.Soft(), css=custom_css) as demo
|
|
| 476 |
maximum=5,
|
| 477 |
value=3,
|
| 478 |
step=1,
|
| 479 |
-
label="
|
| 480 |
-
info="
|
| 481 |
)
|
| 482 |
|
| 483 |
# Additional options
|
| 484 |
-
with gr.Accordion("
|
|
|
|
| 485 |
temperature = gr.Slider(
|
| 486 |
minimum=0,
|
| 487 |
maximum=2,
|
| 488 |
value=0.7,
|
| 489 |
step=0.1,
|
| 490 |
-
label="Temperature"
|
| 491 |
-
info="낮을수록 일관성 있고, 높을수록 창의적입니다"
|
| 492 |
)
|
| 493 |
max_tokens = gr.Slider(
|
| 494 |
minimum=1,
|
| 495 |
maximum=4096,
|
| 496 |
value=512,
|
| 497 |
step=1,
|
| 498 |
-
label="Max Tokens"
|
| 499 |
-
info="생성할 최대 토큰 수"
|
| 500 |
)
|
| 501 |
|
| 502 |
# Main chat area
|
|
@@ -504,187 +445,114 @@ with gr.Blocks(fill_height=True, theme=gr.themes.Soft(), css=custom_css) as demo
|
|
| 504 |
with gr.Group(elem_classes="main-container"):
|
| 505 |
gr.Markdown("## 💬 Chat Interface")
|
| 506 |
|
| 507 |
-
# RAG
|
| 508 |
rag_status = gr.HTML(
|
| 509 |
-
value="<div class='pdf-status pdf-info'>🔍 RAG: <strong
|
| 510 |
)
|
| 511 |
|
| 512 |
-
#
|
|
|
|
|
|
|
|
|
|
| 513 |
with gr.Column(visible=True) as model_120b_container:
|
| 514 |
-
gr.Markdown("###
|
| 515 |
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
|
|
|
| 520 |
)
|
| 521 |
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
placeholder="메시지를 입력하세요... (Enter로 전송)",
|
| 525 |
-
show_label=False,
|
| 526 |
-
scale=4,
|
| 527 |
-
container=False
|
| 528 |
-
)
|
| 529 |
-
send_btn_120b = gr.Button("📤 전송", variant="primary", scale=1)
|
| 530 |
-
|
| 531 |
-
with gr.Row():
|
| 532 |
-
clear_btn_120b = gr.Button("🗑️ 대화 ��기화", variant="secondary", size="sm")
|
| 533 |
-
|
| 534 |
-
# 예제 질문들
|
| 535 |
-
gr.Examples(
|
| 536 |
-
examples=[
|
| 537 |
-
"문서의 주요 내용을 요약해주세요",
|
| 538 |
-
"이 문서에서 가장 중요한 포인트는 무엇인가요?",
|
| 539 |
-
"문서에 언급된 날짜와 일정을 알려주세요"
|
| 540 |
-
],
|
| 541 |
-
inputs=msg_120b
|
| 542 |
-
)
|
| 543 |
|
| 544 |
with gr.Column(visible=False) as model_20b_container:
|
| 545 |
-
gr.Markdown("###
|
| 546 |
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
|
|
|
| 551 |
)
|
| 552 |
-
|
| 553 |
-
with gr.Row():
|
| 554 |
-
msg_20b = gr.Textbox(
|
| 555 |
-
placeholder="메시지를 입력하세요... (Enter로 전송)",
|
| 556 |
-
show_label=False,
|
| 557 |
-
scale=4,
|
| 558 |
-
container=False
|
| 559 |
-
)
|
| 560 |
-
send_btn_20b = gr.Button("📤 전송", variant="primary", scale=1)
|
| 561 |
-
|
| 562 |
-
with gr.Row():
|
| 563 |
-
clear_btn_20b = gr.Button("🗑️ 대화 초기화", variant="secondary", size="sm")
|
| 564 |
-
|
| 565 |
-
# 예제 질문들
|
| 566 |
-
gr.Examples(
|
| 567 |
-
examples=[
|
| 568 |
-
"문서의 주요 내용을 요약해주세요",
|
| 569 |
-
"이 문서에서 가장 중요한 포인트는 무엇인가요?",
|
| 570 |
-
"문서에 언급된 날짜와 일정을 알려주세요"
|
| 571 |
-
],
|
| 572 |
-
inputs=msg_20b
|
| 573 |
-
)
|
| 574 |
|
| 575 |
# Event Handlers
|
| 576 |
|
| 577 |
-
# PDF
|
| 578 |
pdf_upload.upload(
|
| 579 |
fn=upload_pdf,
|
| 580 |
inputs=[pdf_upload],
|
| 581 |
outputs=[upload_status, document_list, enable_rag]
|
| 582 |
)
|
| 583 |
|
| 584 |
-
#
|
| 585 |
clear_btn.click(
|
| 586 |
fn=clear_documents,
|
| 587 |
outputs=[upload_status, document_list, enable_rag]
|
| 588 |
)
|
| 589 |
|
| 590 |
-
# RAG
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 591 |
enable_rag.change(
|
| 592 |
-
fn=
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 597 |
)
|
| 598 |
|
| 599 |
-
#
|
| 600 |
reload_btn.click(
|
| 601 |
fn=switch_model,
|
| 602 |
inputs=[model_dropdown],
|
| 603 |
outputs=[model_120b_container, model_20b_container, current_model]
|
| 604 |
).then(
|
| 605 |
-
fn=lambda: gr.Info("
|
| 606 |
inputs=[],
|
| 607 |
outputs=[]
|
| 608 |
)
|
| 609 |
|
| 610 |
-
#
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
),
|
| 617 |
-
inputs=[msg_120b, chatbot_120b],
|
| 618 |
-
outputs=[chatbot_120b]
|
| 619 |
-
).then(
|
| 620 |
-
fn=lambda: "",
|
| 621 |
-
outputs=[msg_120b]
|
| 622 |
-
)
|
| 623 |
-
|
| 624 |
-
send_btn_120b.click(
|
| 625 |
-
fn=lambda msg, hist: chat_with_rag(
|
| 626 |
-
msg, hist, "openai/gpt-oss-120b",
|
| 627 |
-
enable_rag.value, document_list.value, top_k_chunks.value,
|
| 628 |
-
temperature.value, max_tokens.value
|
| 629 |
-
),
|
| 630 |
-
inputs=[msg_120b, chatbot_120b],
|
| 631 |
-
outputs=[chatbot_120b]
|
| 632 |
-
).then(
|
| 633 |
-
fn=lambda: "",
|
| 634 |
-
outputs=[msg_120b]
|
| 635 |
-
)
|
| 636 |
-
|
| 637 |
-
clear_btn_120b.click(
|
| 638 |
-
fn=lambda: [],
|
| 639 |
-
outputs=[chatbot_120b]
|
| 640 |
-
)
|
| 641 |
-
|
| 642 |
-
# 20b 모델 채팅 이벤트
|
| 643 |
-
msg_20b.submit(
|
| 644 |
-
fn=lambda msg, hist: chat_with_rag(
|
| 645 |
-
msg, hist, "openai/gpt-oss-20b",
|
| 646 |
-
enable_rag.value, document_list.value, top_k_chunks.value,
|
| 647 |
-
temperature.value, max_tokens.value
|
| 648 |
-
),
|
| 649 |
-
inputs=[msg_20b, chatbot_20b],
|
| 650 |
-
outputs=[chatbot_20b]
|
| 651 |
-
).then(
|
| 652 |
-
fn=lambda: "",
|
| 653 |
-
outputs=[msg_20b]
|
| 654 |
-
)
|
| 655 |
-
|
| 656 |
-
send_btn_20b.click(
|
| 657 |
-
fn=lambda msg, hist: chat_with_rag(
|
| 658 |
-
msg, hist, "openai/gpt-oss-20b",
|
| 659 |
-
enable_rag.value, document_list.value, top_k_chunks.value,
|
| 660 |
-
temperature.value, max_tokens.value
|
| 661 |
-
),
|
| 662 |
-
inputs=[msg_20b, chatbot_20b],
|
| 663 |
-
outputs=[chatbot_20b]
|
| 664 |
-
).then(
|
| 665 |
-
fn=lambda: "",
|
| 666 |
-
outputs=[msg_20b]
|
| 667 |
-
)
|
| 668 |
|
| 669 |
-
|
| 670 |
-
fn=
|
| 671 |
-
|
|
|
|
| 672 |
)
|
| 673 |
-
|
| 674 |
-
# 실제 모델 API 연결을 위한 함수 (구현 필요)
|
| 675 |
-
def connect_to_model_api(model_name, message, temperature, max_tokens):
|
| 676 |
-
"""
|
| 677 |
-
실제 모델 API에 연결하는 함수
|
| 678 |
-
TODO: 여기에 실제 API 호출 코드를 구현해야 합니다
|
| 679 |
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
- Custom model endpoint
|
| 684 |
-
"""
|
| 685 |
-
# client = Client(f"models/{model_name}")
|
| 686 |
-
# response = client.predict(message, temperature=temperature, max_tokens=max_tokens)
|
| 687 |
-
# return response
|
| 688 |
-
pass
|
| 689 |
|
| 690 |
demo.launch()
|
|
|
|
| 4 |
import hashlib
|
| 5 |
from datetime import datetime
|
| 6 |
import numpy as np
|
|
|
|
| 7 |
|
| 8 |
# PDF 처리 라이브러리
|
| 9 |
try:
|
|
|
|
| 37 |
margin: 12px;
|
| 38 |
}
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
/* Status messages styling */
|
| 41 |
.pdf-status {
|
| 42 |
padding: 12px 16px;
|
|
|
|
| 44 |
margin: 12px 0;
|
| 45 |
font-size: 0.95rem;
|
| 46 |
font-weight: 500;
|
|
|
|
| 47 |
}
|
| 48 |
|
| 49 |
.pdf-success {
|
|
|
|
| 64 |
color: #0c5460;
|
| 65 |
}
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
.rag-context {
|
| 68 |
background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
|
| 69 |
border-left: 4px solid #f59e0b;
|
| 70 |
+
padding: 12px;
|
| 71 |
+
margin: 12px 0;
|
| 72 |
border-radius: 8px;
|
| 73 |
font-size: 0.9rem;
|
| 74 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
"""
|
| 76 |
|
| 77 |
class SimpleTextSplitter:
|
|
|
|
| 223 |
for doc_id in doc_ids:
|
| 224 |
if doc_id in self.document_chunks:
|
| 225 |
chunks = self.document_chunks[doc_id]
|
| 226 |
+
for i, chunk in enumerate(chunks[:5]): # 처음 5개만
|
| 227 |
chunk_lower = chunk.lower()
|
| 228 |
score = sum(1 for keyword in query_keywords if keyword in chunk_lower)
|
| 229 |
if score > 0:
|
|
|
|
| 246 |
|
| 247 |
# 프롬프트 구성
|
| 248 |
prompt_parts = []
|
| 249 |
+
prompt_parts.append("다음 문서 내용을 참고하여 답변해주세요:\n")
|
| 250 |
+
prompt_parts.append("=" * 40)
|
| 251 |
|
| 252 |
for i, chunk in enumerate(relevant_chunks, 1):
|
| 253 |
+
prompt_parts.append(f"\n[참고 {i} - {chunk['doc_name']}]")
|
| 254 |
+
content = chunk['content'][:300] if len(chunk['content']) > 300 else chunk['content']
|
| 255 |
prompt_parts.append(content)
|
|
|
|
| 256 |
|
| 257 |
+
prompt_parts.append("\n" + "=" * 40)
|
| 258 |
prompt_parts.append(f"\n질문: {query}")
|
|
|
|
| 259 |
|
| 260 |
return "\n".join(prompt_parts)
|
| 261 |
|
| 262 |
# RAG 시스템 인스턴스 생성
|
| 263 |
rag_system = PDFRAGSystem()
|
| 264 |
|
| 265 |
+
# State variable to track current model and RAG settings
|
| 266 |
current_model = gr.State("openai/gpt-oss-120b")
|
| 267 |
+
rag_enabled_state = gr.State(False)
|
| 268 |
+
selected_docs_state = gr.State([])
|
| 269 |
+
top_k_state = gr.State(3)
|
| 270 |
|
| 271 |
def upload_pdf(file):
|
| 272 |
"""PDF 파일 업로드 처리"""
|
| 273 |
if file is None:
|
| 274 |
return (
|
| 275 |
+
gr.update(value="<div class='pdf-status pdf-info'>📁 파일을 선택해주세요</div>"),
|
| 276 |
gr.update(choices=[]),
|
| 277 |
gr.update(value=False)
|
| 278 |
)
|
|
|
|
| 290 |
if result["success"]:
|
| 291 |
status_html = f"""
|
| 292 |
<div class="pdf-status pdf-success">
|
| 293 |
+
✅ PDF 업로드 완료!<br>
|
| 294 |
+
📄 {result['title']}<br>
|
| 295 |
+
📑 {result['pages']} 페이지 | 🔍 {result['chunks']} 청크
|
|
|
|
| 296 |
</div>
|
| 297 |
"""
|
| 298 |
|
|
|
|
| 306 |
gr.update(value=True)
|
| 307 |
)
|
| 308 |
else:
|
| 309 |
+
return (
|
| 310 |
+
f"<div class='pdf-status pdf-error'>❌ 오류: {result['error']}</div>",
|
| 311 |
+
gr.update(),
|
| 312 |
+
gr.update(value=False)
|
| 313 |
+
)
|
|
|
|
| 314 |
|
| 315 |
except Exception as e:
|
| 316 |
return (
|
|
|
|
| 333 |
|
| 334 |
def switch_model(model_choice):
|
| 335 |
"""Function to switch between models"""
|
| 336 |
+
return gr.update(visible=False), gr.update(visible=True), model_choice
|
|
|
|
|
|
|
|
|
|
| 337 |
|
| 338 |
+
def create_rag_wrapper(original_fn, model_name):
|
| 339 |
+
"""원본 모델 함수를 RAG로 감싸는 래퍼 생성"""
|
| 340 |
+
def wrapped_fn(message, history=None):
|
| 341 |
+
# RAG 설정 가져오기
|
| 342 |
+
if rag_enabled_state.value and selected_docs_state.value:
|
| 343 |
+
doc_ids = [doc.split(":")[0] for doc in selected_docs_state.value]
|
| 344 |
+
enhanced_message = rag_system.create_rag_prompt(message, doc_ids, top_k_state.value)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
|
| 346 |
+
# RAG 적용 알림
|
| 347 |
+
print(f"🔍 RAG 적용: {len(message)}자 → {len(enhanced_message)}자")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
+
# 원본 모델에 강화된 메시지 전달
|
| 350 |
+
if history is not None:
|
| 351 |
+
return original_fn(enhanced_message, history)
|
| 352 |
+
else:
|
| 353 |
+
return original_fn(enhanced_message)
|
| 354 |
+
else:
|
| 355 |
+
# RAG 미적용시 원본 메시지 그대로 전달
|
| 356 |
+
if history is not None:
|
| 357 |
+
return original_fn(message, history)
|
| 358 |
+
else:
|
| 359 |
+
return original_fn(message)
|
| 360 |
|
| 361 |
+
return wrapped_fn
|
| 362 |
|
| 363 |
# Main interface with soft theme
|
| 364 |
with gr.Blocks(fill_height=True, theme=gr.themes.Soft(), css=custom_css) as demo:
|
|
|
|
| 367 |
# Sidebar
|
| 368 |
with gr.Column(scale=1):
|
| 369 |
with gr.Group(elem_classes="main-container"):
|
| 370 |
+
gr.Markdown("# 🚀 Inference Provider + RAG")
|
| 371 |
gr.Markdown(
|
| 372 |
+
"OpenAI GPT-OSS models served by Cerebras API. "
|
| 373 |
+
"Upload PDF documents for context-aware responses."
|
| 374 |
)
|
| 375 |
|
|
|
|
|
|
|
|
|
|
| 376 |
# Model selection
|
| 377 |
model_dropdown = gr.Dropdown(
|
| 378 |
choices=["openai/gpt-oss-120b", "openai/gpt-oss-20b"],
|
| 379 |
value="openai/gpt-oss-120b",
|
| 380 |
+
label="📊 Select Model",
|
| 381 |
+
info="Choose between different model sizes"
|
| 382 |
)
|
| 383 |
|
| 384 |
+
# Login button
|
| 385 |
+
login_button = gr.LoginButton("Sign in with Hugging Face", size="lg")
|
| 386 |
+
|
| 387 |
# Reload button to apply model change
|
| 388 |
+
reload_btn = gr.Button("🔄 Apply Model Change", variant="primary", size="lg")
|
| 389 |
|
| 390 |
# RAG Settings
|
| 391 |
+
with gr.Accordion("📚 PDF RAG Settings", open=True):
|
| 392 |
pdf_upload = gr.File(
|
| 393 |
+
label="Upload PDF",
|
| 394 |
file_types=[".pdf"],
|
| 395 |
type="filepath"
|
| 396 |
)
|
| 397 |
|
| 398 |
upload_status = gr.HTML(
|
| 399 |
+
value="<div class='pdf-status pdf-info'>📤 Upload a PDF to enable document-based answers</div>"
|
| 400 |
)
|
| 401 |
|
| 402 |
document_list = gr.CheckboxGroup(
|
| 403 |
choices=[],
|
| 404 |
+
label="📄 Uploaded Documents",
|
| 405 |
+
info="Select documents to use as context"
|
| 406 |
)
|
| 407 |
|
| 408 |
+
clear_btn = gr.Button("🗑️ Clear All Documents", size="sm", variant="secondary")
|
|
|
|
| 409 |
|
| 410 |
enable_rag = gr.Checkbox(
|
| 411 |
+
label="✨ Enable RAG",
|
| 412 |
value=False,
|
| 413 |
+
info="Use documents for context-aware responses"
|
| 414 |
)
|
| 415 |
|
| 416 |
top_k_chunks = gr.Slider(
|
|
|
|
| 418 |
maximum=5,
|
| 419 |
value=3,
|
| 420 |
step=1,
|
| 421 |
+
label="Context Chunks",
|
| 422 |
+
info="Number of document chunks to use"
|
| 423 |
)
|
| 424 |
|
| 425 |
# Additional options
|
| 426 |
+
with gr.Accordion("⚙️ Advanced Options", open=False):
|
| 427 |
+
gr.Markdown("*These options will be available after model implementation*")
|
| 428 |
temperature = gr.Slider(
|
| 429 |
minimum=0,
|
| 430 |
maximum=2,
|
| 431 |
value=0.7,
|
| 432 |
step=0.1,
|
| 433 |
+
label="Temperature"
|
|
|
|
| 434 |
)
|
| 435 |
max_tokens = gr.Slider(
|
| 436 |
minimum=1,
|
| 437 |
maximum=4096,
|
| 438 |
value=512,
|
| 439 |
step=1,
|
| 440 |
+
label="Max Tokens"
|
|
|
|
| 441 |
)
|
| 442 |
|
| 443 |
# Main chat area
|
|
|
|
| 445 |
with gr.Group(elem_classes="main-container"):
|
| 446 |
gr.Markdown("## 💬 Chat Interface")
|
| 447 |
|
| 448 |
+
# RAG status
|
| 449 |
rag_status = gr.HTML(
|
| 450 |
+
value="<div class='pdf-status pdf-info'>🔍 RAG: <strong>Disabled</strong></div>"
|
| 451 |
)
|
| 452 |
|
| 453 |
+
# RAG context preview
|
| 454 |
+
context_preview = gr.HTML(value="", visible=False)
|
| 455 |
+
|
| 456 |
+
# Container for model interfaces
|
| 457 |
with gr.Column(visible=True) as model_120b_container:
|
| 458 |
+
gr.Markdown("### Model: openai/gpt-oss-120b")
|
| 459 |
|
| 460 |
+
# Load the original model and wrap it with RAG
|
| 461 |
+
original_interface_120b = gr.load(
|
| 462 |
+
"models/openai/gpt-oss-120b",
|
| 463 |
+
accept_token=login_button,
|
| 464 |
+
provider="fireworks-ai"
|
| 465 |
)
|
| 466 |
|
| 467 |
+
# Note: The loaded interface will have its own chat components
|
| 468 |
+
# We'll intercept the messages through our wrapper function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 469 |
|
| 470 |
with gr.Column(visible=False) as model_20b_container:
|
| 471 |
+
gr.Markdown("### Model: openai/gpt-oss-20b")
|
| 472 |
|
| 473 |
+
# Load the original model
|
| 474 |
+
original_interface_20b = gr.load(
|
| 475 |
+
"models/openai/gpt-oss-20b",
|
| 476 |
+
accept_token=login_button,
|
| 477 |
+
provider="fireworks-ai"
|
| 478 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 479 |
|
| 480 |
# Event Handlers
|
| 481 |
|
| 482 |
+
# PDF upload
|
| 483 |
pdf_upload.upload(
|
| 484 |
fn=upload_pdf,
|
| 485 |
inputs=[pdf_upload],
|
| 486 |
outputs=[upload_status, document_list, enable_rag]
|
| 487 |
)
|
| 488 |
|
| 489 |
+
# Clear documents
|
| 490 |
clear_btn.click(
|
| 491 |
fn=clear_documents,
|
| 492 |
outputs=[upload_status, document_list, enable_rag]
|
| 493 |
)
|
| 494 |
|
| 495 |
+
# Update RAG state when settings change
|
| 496 |
+
def update_rag_state(enabled, docs, k):
|
| 497 |
+
rag_enabled_state.value = enabled
|
| 498 |
+
selected_docs_state.value = docs if docs else []
|
| 499 |
+
top_k_state.value = k
|
| 500 |
+
|
| 501 |
+
status = "✅ Enabled" if enabled and docs else "⭕ Disabled"
|
| 502 |
+
status_html = f"<div class='pdf-status pdf-info'>🔍 RAG: <strong>{status}</strong></div>"
|
| 503 |
+
|
| 504 |
+
# Show context preview if RAG is enabled
|
| 505 |
+
if enabled and docs:
|
| 506 |
+
preview = f"<div class='rag-context'>📚 Using {len(docs)} document(s) with {k} chunks per query</div>"
|
| 507 |
+
return gr.update(value=status_html), gr.update(value=preview, visible=True)
|
| 508 |
+
else:
|
| 509 |
+
return gr.update(value=status_html), gr.update(value="", visible=False)
|
| 510 |
+
|
| 511 |
+
# Connect RAG state updates
|
| 512 |
enable_rag.change(
|
| 513 |
+
fn=update_rag_state,
|
| 514 |
+
inputs=[enable_rag, document_list, top_k_chunks],
|
| 515 |
+
outputs=[rag_status, context_preview]
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
document_list.change(
|
| 519 |
+
fn=update_rag_state,
|
| 520 |
+
inputs=[enable_rag, document_list, top_k_chunks],
|
| 521 |
+
outputs=[rag_status, context_preview]
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
top_k_chunks.change(
|
| 525 |
+
fn=update_rag_state,
|
| 526 |
+
inputs=[enable_rag, document_list, top_k_chunks],
|
| 527 |
+
outputs=[rag_status, context_preview]
|
| 528 |
)
|
| 529 |
|
| 530 |
+
# Handle model switching
|
| 531 |
reload_btn.click(
|
| 532 |
fn=switch_model,
|
| 533 |
inputs=[model_dropdown],
|
| 534 |
outputs=[model_120b_container, model_20b_container, current_model]
|
| 535 |
).then(
|
| 536 |
+
fn=lambda: gr.Info("Model switched successfully!"),
|
| 537 |
inputs=[],
|
| 538 |
outputs=[]
|
| 539 |
)
|
| 540 |
|
| 541 |
+
# Update visibility based on dropdown selection
|
| 542 |
+
def update_visibility(model_choice):
|
| 543 |
+
if model_choice == "openai/gpt-oss-120b":
|
| 544 |
+
return gr.update(visible=True), gr.update(visible=False)
|
| 545 |
+
else:
|
| 546 |
+
return gr.update(visible=False), gr.update(visible=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 547 |
|
| 548 |
+
model_dropdown.change(
|
| 549 |
+
fn=update_visibility,
|
| 550 |
+
inputs=[model_dropdown],
|
| 551 |
+
outputs=[model_120b_container, model_20b_container]
|
| 552 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 553 |
|
| 554 |
+
# Monkey-patch the loaded interfaces to add RAG support
|
| 555 |
+
# This is done after the interface is loaded
|
| 556 |
+
demo.load = lambda: print("📚 RAG System Ready!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 557 |
|
| 558 |
demo.launch()
|