File size: 47,004 Bytes
4a98f26 b12512e 4a98f26 b12512e 4a98f26 b12512e 4a98f26 b12512e 4a98f26 b12512e 4a98f26 b12512e 4a98f26 b12512e 4a98f26 b12512e 5243fd2 b12512e 5243fd2 b12512e 4a98f26 52a2853 4a98f26 52a2853 4a98f26 52a2853 4a98f26 52a2853 4a98f26 b12512e 4a98f26 52a2853 4a98f26 b12512e 52a2853 b12512e 52a2853 b12512e 52a2853 b12512e 4a98f26 52a2853 4a98f26 a76f77b 4a98f26 a76f77b 4a98f26 a76f77b 4a98f26 a76f77b 4a98f26 a76f77b 4a98f26 a76f77b 4a98f26 a76f77b b12512e 4a98f26 a76f77b 4a98f26 a76f77b 4a98f26 a76f77b 4a98f26 b12512e 4a98f26 78df87c 4a98f26 66409a3 4a98f26 b12512e 4a98f26 78df87c 4a98f26 78df87c 4a98f26 b12512e 4a98f26 b12512e 4a98f26 66409a3 52a2853 66409a3 52a2853 66409a3 a76f77b 66409a3 52a2853 a76f77b 66409a3 a76f77b 52a2853 66409a3 52a2853 b12512e 66409a3 52a2853 66409a3 a76f77b 66409a3 52a2853 a76f77b 4a98f26 b12512e 4a98f26 ceaab21 4a98f26 ceaab21 67649a2 ceaab21 67649a2 ceaab21 67649a2 ceaab21 67649a2 ceaab21 67649a2 ceaab21 67649a2 ceaab21 67649a2 ceaab21 67649a2 ceaab21 67649a2 ceaab21 67649a2 4a98f26 b2f5fac 4a98f26 ceaab21 4a98f26 ceaab21 4a98f26 78df87c ceaab21 4a98f26 ceaab21 4a98f26 ceaab21 4a98f26 a76f77b 4a98f26 |
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 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 |
"""
์์ฑ์ธ์ ๊ธฐ๋ฅ์ด ์ถ๊ฐ๋ RAG ์ฑ๋ด ์ฑ
"""
import os
import time
import tempfile
from typing import List, Dict, Tuple, Any, Optional
import hashlib
import pickle
import json
# ๊ธฐ์กด ์ํฌํธ
from config import (
PDF_DIRECTORY, CHUNK_SIZE, CHUNK_OVERLAP, LLM_MODEL,
STT_LANGUAGE, IS_HUGGINGFACE, OPENAI_API_KEY, USE_OPENAI
)
from optimized_document_processor import OptimizedDocumentProcessor
from vector_store import VectorStore
from langchain.schema import Document
# ํด๋ก๋ฐ STT ๋ชจ๋ ์ํฌํธ
from clova_stt import ClovaSTT
# ์์ ํ ์ํฌํธ
try:
print("RAG ์ฒด์ธ ๋ชจ๋ ๋ก๋ ์๋...")
from rag_chain import RAGChain
# RAGChain ํด๋์ค๊ฐ ์ ๋๋ก ์ํฌํธ๋์๋์ง ํ์ธ
RAG_CHAIN_AVAILABLE = True
print("์ธ๋ถ RAG ์ฒด์ธ ๋ชจ๋ ๋ก๋ ์ฑ๊ณต")
except Exception as e:
print(f"์ธ๋ถ RAG ์ฒด์ธ ๋ก๋ ์คํจ: {e}")
print("๋ด์ฅ RAG ์ฒด์ธ์ ์ฌ์ฉํฉ๋๋ค.")
# ๋ด์ฅ RAG ์ฒด์ธ ๊ตฌํ ์ฌ์ฉ
RAG_CHAIN_AVAILABLE = True
# ํ์ํ langchain ์ํฌํธ
try:
from langchain_openai import ChatOpenAI
from langchain_community.chat_models import ChatOllama
from langchain.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
# SimpleRAGChain ๋ด์ฅ ํด๋์ค ์ ์
class RAGChain:
"""์ฑ์ ๋ด์ฅ๋ ๊ฐ๋จํ RAG ์ฒด์ธ"""
def __init__(self, vector_store):
print("๋ด์ฅ RAG ์ฒด์ธ ์ด๊ธฐํ ์ค...")
self.vector_store = vector_store
# ํ๊ฒฝ ์ค์ ์ํฌํธ
from config import OPENAI_API_KEY, LLM_MODEL, USE_OPENAI, TOP_K_RETRIEVAL, IS_HUGGINGFACE
# OLLAMA_HOST๋ HuggingFace ํ๊ฒฝ์์๋ ์ ์๋์ง ์์ผ๋ฏ๋ก ์กฐ๊ฑด๋ถ ๊ฐ์ ธ์ค๊ธฐ
OLLAMA_HOST = "http://localhost:11434" # ๊ธฐ๋ณธ๊ฐ
if not IS_HUGGINGFACE and not USE_OPENAI:
try:
from config import OLLAMA_HOST
print(f"Ollama ํธ์คํธ: {OLLAMA_HOST}")
except ImportError:
print("OLLAMA_HOST ์ค์ ์ ์ฐพ์ ์ ์์ด ๊ธฐ๋ณธ๊ฐ ์ฌ์ฉ")
try:
# LLM ์ด๊ธฐํ
if USE_OPENAI or IS_HUGGINGFACE:
self.llm = ChatOpenAI(
model_name=LLM_MODEL,
temperature=0.2,
api_key=OPENAI_API_KEY,
)
print(f"OpenAI ๋ชจ๋ธ ์ด๊ธฐํ: {LLM_MODEL}")
else:
try:
self.llm = ChatOllama(
model=LLM_MODEL,
temperature=0.2,
base_url=OLLAMA_HOST,
)
print(f"Ollama ๋ชจ๋ธ ์ด๊ธฐํ: {LLM_MODEL}")
except Exception as e:
print(f"Ollama ์ด๊ธฐํ ์คํจ: {e}, OpenAI ๋ชจ๋ธ๋ก ๋์ฒด")
self.llm = ChatOpenAI(
model_name="gpt-3.5-turbo",
temperature=0.2,
api_key=OPENAI_API_KEY,
)
# ํ๋กฌํํธ ํ
ํ๋ฆฟ
template = """
๋ค์ ์ ๋ณด๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ์ง๋ฌธ์ ์ ํํ๊ฒ ๋ต๋ณํด์ฃผ์ธ์.
์ง๋ฌธ: {question}
์ฐธ๊ณ ์ ๋ณด:
{context}
์ฐธ๊ณ ์ ๋ณด์ ๋ต์ด ์๋ ๊ฒฝ์ฐ "์ ๊ณต๋ ๋ฌธ์์์ ํด๋น ์ ๋ณด๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."๋ผ๊ณ ๋ต๋ณํ์ธ์.
๋ต๋ณ์ ์ ํํ๊ณ ๊ฐ๊ฒฐํ๊ฒ ์ ๊ณตํ๋, ์ฐธ๊ณ ์ ๋ณด์์ ๊ทผ๊ฑฐ๋ฅผ ์ฐพ์ ์ค๋ช
ํด์ฃผ์ธ์.
์ฐธ๊ณ ์ ๋ณด์ ์ถ์ฒ๋ ํจ๊ป ์๋ ค์ฃผ์ธ์.
"""
self.prompt = PromptTemplate.from_template(template)
# ์ฒด์ธ ๊ตฌ์ฑ
self.chain = (
{"context": self._retrieve, "question": RunnablePassthrough()}
| self.prompt
| self.llm
| StrOutputParser()
)
print("๋ด์ฅ RAG ์ฒด์ธ ์ด๊ธฐํ ์๋ฃ")
except Exception as e:
print(f"LLM ์ด๊ธฐํ ์คํจ: {e}")
import traceback
traceback.print_exc()
raise
def _retrieve(self, query):
"""๋ฌธ์ ๊ฒ์"""
try:
from config import TOP_K_RETRIEVAL
docs = self.vector_store.similarity_search(query, k=TOP_K_RETRIEVAL)
# ๊ฒ์ ๊ฒฐ๊ณผ ์ปจํ
์คํธ ๊ตฌ์ฑ
context_parts = []
for i, doc in enumerate(docs, 1):
source = doc.metadata.get("source", "์ ์ ์๋ ์ถ์ฒ")
page = doc.metadata.get("page", "")
source_info = f"{source}"
if page:
source_info += f" (ํ์ด์ง: {page})"
context_parts.append(f"[์ฐธ๊ณ ์๋ฃ {i}] - ์ถ์ฒ: {source_info}\n{doc.page_content}\n")
return "\n".join(context_parts)
except Exception as e:
print(f"๊ฒ์ ์ค ์ค๋ฅ: {e}")
import traceback
traceback.print_exc()
return "๋ฌธ์ ๊ฒ์ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค."
def run(self, query):
"""์ฟผ๋ฆฌ ์ฒ๋ฆฌ"""
try:
return self.chain.invoke(query)
except Exception as e:
print(f"RAG ์ฒด์ธ ์คํ ์ค๋ฅ: {e}")
import traceback
traceback.print_exc()
return f"์ค๋ฅ ๋ฐ์: {str(e)}"
except Exception as inner_e:
print(f"๋ด์ฅ RAG ์ฒด์ธ ์ ์ ์คํจ: {inner_e}")
import traceback
traceback.print_exc()
RAG_CHAIN_AVAILABLE = False
class AutoRAGChatApp:
"""
documents ํด๋์ PDF ํ์ผ์ ์๋์ผ๋ก ์ฒ๋ฆฌํ๊ณ ์์ฑ์ธ์ ๊ธฐ๋ฅ์ ์ ๊ณตํ๋ RAG ์ฑ๋ด
"""
def __init__(self):
"""
RAG ์ฑ๋ด ์ ํ๋ฆฌ์ผ์ด์
์ด๊ธฐํ
"""
print("=" * 50)
print("์์ฑ์ธ์ RAG ์ฑ๋ด ์ ํ๋ฆฌ์ผ์ด์
์ด๊ธฐํ ์์")
print("=" * 50)
# ๋ฐ์ดํฐ ๋๋ ํ ๋ฆฌ ์ ์
self.pdf_directory = PDF_DIRECTORY
self.cache_directory = "cached_data"
self.index_file = os.path.join(self.cache_directory, "file_index.json")
self.chunks_dir = os.path.join(self.cache_directory, "chunks")
self.vector_index_dir = os.path.join(self.cache_directory, "vector_index")
# ๋๋ ํ ๋ฆฌ ์์ฑ
os.makedirs(self.pdf_directory, exist_ok=True)
os.makedirs(self.cache_directory, exist_ok=True)
os.makedirs(self.chunks_dir, exist_ok=True)
os.makedirs(self.vector_index_dir, exist_ok=True)
print(f"PDF ๋ฌธ์ ๋๋ ํ ๋ฆฌ: '{self.pdf_directory}'")
print(f"์บ์ ๋๋ ํ ๋ฆฌ: '{self.cache_directory}'")
# ์ปดํฌ๋ํธ ์ด๊ธฐํ
self.document_processor = OptimizedDocumentProcessor(
chunk_size=CHUNK_SIZE,
chunk_overlap=CHUNK_OVERLAP
)
# ๋ฒกํฐ ์ ์ฅ์ ์ด๊ธฐํ
self.vector_store = VectorStore(use_milvus=False)
# ๋ฌธ์ ์ธ๋ฑ์ค ๋ก๋
self.file_index = self._load_file_index()
# ๊ธฐ๋ณธ ๋ณ์ ์ด๊ธฐํ
self.documents = []
self.processed_files = []
self.is_initialized = False
self.rag_chain = None
# ํด๋ก๋ฐ STT ํด๋ผ์ด์ธํธ ์ด๊ธฐํ
self.stt_client = ClovaSTT()
print("์์ฑ์ธ์(STT) ๊ธฐ๋ฅ์ด ์ด๊ธฐํ๋์์ต๋๋ค.")
# RAG ์ฒด์ธ ์ฌ์ฉ ๊ฐ๋ฅ์ฑ ํ์ธ
print(f"RAG ์ฒด์ธ ์ฌ์ฉ ๊ฐ๋ฅ: {RAG_CHAIN_AVAILABLE}")
# ์์ ์ ์๋์ผ๋ก ๋ฌธ์ ๋ก๋ ๋ฐ ์ฒ๋ฆฌ
print("๋ฌธ์ ์๋ ๋ก๋ ๋ฐ ์ฒ๋ฆฌ ์์...")
result = self.auto_process_documents()
print(f"์ด๊ธฐํ ์๋ฃ ์ํ: {self.is_initialized}")
print("=" * 50)
def _fallback_response(self, query: str) -> str:
"""
RAG ์ฒด์ธ ์ด๊ธฐํ ์คํจ ์ ๊ธฐ๋ณธ ์๋ต ์์ฑ
Args:
query: ์ฌ์ฉ์ ์ง๋ฌธ
Returns:
๊ธฐ๋ณธ ์๋ต ํ
์คํธ
"""
try:
# ๋ฒกํฐ ๊ฒ์์ด๋ผ๋ ์คํ
if self.vector_store and self.vector_store.vector_store:
try:
docs = self.vector_store.similarity_search(query, k=3)
if docs:
context = "\n\n".join([doc.page_content for doc in docs])
response = f"""
์ง๋ฌธ์ ๋ํ ์๋ต์ ์์ฑํ ์ ์์ต๋๋ค. RAG ์ฒด์ธ์ด ์ด๊ธฐํ๋์ง ์์์ต๋๋ค.
๊ทธ๋ฌ๋ ๋ฌธ์์์ ๊ด๋ จ ์ ๋ณด๋ฅผ ์ฐพ์์ต๋๋ค:
{context}
RAG ์ฒด์ธ ์ด๊ธฐํ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ ค๋ฉด ๋ก๊ทธ๋ฅผ ํ์ธํ์ธ์.
"""
return response.strip()
except Exception as e:
print(f"๋ฒกํฐ ๊ฒ์ ์คํจ: {e}")
# ๊ธฐ๋ณธ ์๋ต
return "์ฃ์กํฉ๋๋ค. RAG ์ฒด์ธ์ด ์ด๊ธฐํ๋์ง ์์ ์ง๋ฌธ์ ์๋ตํ ์ ์์ต๋๋ค. ๊ธฐ์ ์ ์ธ ๋ฌธ์ ๋ฅผ ํด๊ฒฐ ์ค์
๋๋ค."
except Exception as e:
print(f"๊ธฐ๋ณธ ์๋ต ์์ฑ ์คํจ: {e}")
return "์์คํ
์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. ๊ด๋ฆฌ์์๊ฒ ๋ฌธ์ํ์ธ์."
def _process_pdf_file(self, file_path: str) -> List[Document]:
"""
PDF ํ์ผ ์ฒ๋ฆฌ - docling ์คํจ ์ PyPDFLoader ์ฌ์ฉ
Args:
file_path: ์ฒ๋ฆฌํ PDF ํ์ผ ๊ฒฝ๋ก
Returns:
์ฒ๋ฆฌ๋ ๋ฌธ์ ์ฒญํฌ ๋ฆฌ์คํธ
"""
try:
print(f"docling์ผ๋ก ์ฒ๋ฆฌ ์๋: {file_path}")
# docling ์ฌ์ฉ ์๋
try:
# 10์ด ํ์์์ ์ค์ (์ต์
)
import signal
def timeout_handler(signum, frame):
raise TimeoutError("docling ์ฒ๋ฆฌ ์๊ฐ ์ด๊ณผ")
# ๋ฆฌ๋
์ค/๋งฅ์์๋ง ์๋ (์๋์ฐ์์๋ ๋ฌด์๋จ)
try:
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(60) # 60์ด ํ์์์
except:
pass
# docling์ผ๋ก ์ฒ๋ฆฌ ์๋
chunks = self.document_processor.process_pdf(file_path, use_docling=True)
# ํ์์์ ์ทจ์
try:
signal.alarm(0)
except:
pass
return chunks
except Exception as e:
# docling ์ค๋ฅ ํ์ธ
error_str = str(e)
if "Invalid code point" in error_str or "RuntimeError" in error_str:
print(f"docling ์ฒ๋ฆฌ ์ค๋ฅ (์ฝ๋ ํฌ์ธํธ ๋ฌธ์ ): {error_str}")
print("PyPDFLoader๋ก ๋์ฒดํฉ๋๋ค.")
else:
print(f"docling ์ฒ๋ฆฌ ์ค๋ฅ: {error_str}")
print("PyPDFLoader๋ก ๋์ฒดํฉ๋๋ค.")
# PyPDFLoader๋ก ๋์ฒด
try:
return self.document_processor.process_pdf(file_path, use_docling=False)
except Exception as inner_e:
print(f"PyPDFLoader ์ฒ๋ฆฌ ์ค๋ฅ: {inner_e}")
raise # ๋ ๋ฐฉ๋ฒ ๋ชจ๋ ์คํจํ๋ฉด ์์ธ ๋ฐ์
except Exception as e:
print(f"PDF ์ฒ๋ฆฌ ์ค ์ฌ๊ฐํ ์ค๋ฅ: {e}")
# ๋น ์ฒญํฌ๋ผ๋ ๋ฐํํ์ฌ ์ ์ฒด ์ฒ๋ฆฌ๊ฐ ์ค๋จ๋์ง ์๋๋ก ํจ
return []
def _load_file_index(self) -> Dict[str, Dict[str, Any]]:
"""
ํ์ผ ์ธ๋ฑ์ค ๋ก๋
Returns:
ํ์ผ ๊ฒฝ๋ก -> ๋ฉํ๋ฐ์ดํฐ ๋งคํ
"""
if os.path.exists(self.index_file):
try:
with open(self.index_file, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
print(f"์ธ๋ฑ์ค ํ์ผ ๋ก๋ ์คํจ: {e}")
return {}
return {}
def _save_file_index(self) -> None:
"""
ํ์ผ ์ธ๋ฑ์ค ์ ์ฅ
"""
with open(self.index_file, 'w', encoding='utf-8') as f:
json.dump(self.file_index, f, ensure_ascii=False, indent=2)
def _calculate_file_hash(self, file_path: str) -> str:
"""
ํ์ผ ํด์ ๊ณ์ฐ
Args:
file_path: ํ์ผ ๊ฒฝ๋ก
Returns:
MD5 ํด์๊ฐ
"""
hasher = hashlib.md5()
with open(file_path, 'rb') as f:
buf = f.read(65536)
while len(buf) > 0:
hasher.update(buf)
buf = f.read(65536)
return hasher.hexdigest()
def _is_file_processed(self, file_path: str) -> bool:
"""
ํ์ผ์ด ์ด๋ฏธ ์ฒ๋ฆฌ๋์๊ณ ๋ณ๊ฒฝ๋์ง ์์๋์ง ํ์ธ
Args:
file_path: ํ์ผ ๊ฒฝ๋ก
Returns:
์ฒ๋ฆฌ ์ฌ๋ถ
"""
if file_path not in self.file_index:
return False
# ํ์ฌ ํด์๊ฐ ๊ณ์ฐ
current_hash = self._calculate_file_hash(file_path)
# ์ ์ฅ๋ ํด์๊ฐ๊ณผ ๋น๊ต
if self.file_index[file_path]['hash'] != current_hash:
print(f"ํ์ผ ๋ณ๊ฒฝ ๊ฐ์ง: {file_path}")
return False
# ์ฒญํฌ ํ์ผ ์กด์ฌ ํ์ธ
chunks_path = self.file_index[file_path]['chunks_path']
if not os.path.exists(chunks_path):
return False
return True
def _get_chunks_path(self, file_hash: str) -> str:
"""
์ฒญํฌ ํ์ผ ๊ฒฝ๋ก ์์ฑ
Args:
file_hash: ํ์ผ ํด์๊ฐ
Returns:
์ฒญํฌ ํ์ผ ๊ฒฝ๋ก
"""
return os.path.join(self.chunks_dir, f"{file_hash}.pkl")
def _save_chunks(self, file_path: str, chunks: List[Document]) -> None:
"""
์ฒญํฌ ๋ฐ์ดํฐ ์ ์ฅ
Args:
file_path: ์๋ณธ ํ์ผ ๊ฒฝ๋ก
chunks: ๋ฌธ์ ์ฒญํฌ ๋ฆฌ์คํธ
"""
# ํด์ ๊ณ์ฐ
file_hash = self._calculate_file_hash(file_path)
# ์ฒญํฌ ํ์ผ ๊ฒฝ๋ก
chunks_path = self._get_chunks_path(file_hash)
# ์ฒญํฌ ๋ฐ์ดํฐ ์ ์ฅ
with open(chunks_path, 'wb') as f:
pickle.dump(chunks, f)
# ์ธ๋ฑ์ค ์
๋ฐ์ดํธ
self.file_index[file_path] = {
'hash': file_hash,
'chunks_path': chunks_path,
'last_processed': time.time(),
'chunks_count': len(chunks)
}
# ์ธ๋ฑ์ค ์ ์ฅ
self._save_file_index()
print(f"์ฒญํฌ ์ ์ฅ ์๋ฃ: {file_path} ({len(chunks)}๊ฐ ์ฒญํฌ)")
def _load_chunks(self, file_path: str) -> List[Document]:
"""
์ ์ฅ๋ ์ฒญํฌ ๋ฐ์ดํฐ ๋ก๋
Args:
file_path: ํ์ผ ๊ฒฝ๋ก
Returns:
๋ฌธ์ ์ฒญํฌ ๋ฆฌ์คํธ
"""
chunks_path = self.file_index[file_path]['chunks_path']
with open(chunks_path, 'rb') as f:
chunks = pickle.load(f)
print(f"์ฒญํฌ ๋ก๋ ์๋ฃ: {file_path} ({len(chunks)}๊ฐ ์ฒญํฌ)")
return chunks
def auto_process_documents(self) -> str:
"""
documents ํด๋์ PDF ํ์ผ ์๋ ์ฒ๋ฆฌ
Returns:
์ฒ๋ฆฌ ๊ฒฐ๊ณผ ๋ฉ์์ง
"""
try:
start_time = time.time()
# PDF ํ์ผ ๋ชฉ๋ก ์์ง
pdf_files = []
for filename in os.listdir(self.pdf_directory):
if filename.lower().endswith('.pdf'):
pdf_files.append(os.path.join(self.pdf_directory, filename))
if not pdf_files:
print(f"'{self.pdf_directory}' ํด๋์ PDF ํ์ผ์ด ์์ต๋๋ค.")
return f"'{self.pdf_directory}' ํด๋์ PDF ํ์ผ์ด ์์ต๋๋ค."
print(f"๋ฐ๊ฒฌ๋ PDF ํ์ผ: {len(pdf_files)}๊ฐ")
# ํด๋ ๋ด PDF ํ์ผ ์ฒ๋ฆฌ
new_files = []
updated_files = []
cached_files = []
failed_files = []
all_chunks = []
for file_path in pdf_files:
if self._is_file_processed(file_path):
# ์บ์์์ ์ฒญํฌ ๋ก๋
chunks = self._load_chunks(file_path)
all_chunks.extend(chunks)
cached_files.append(file_path)
self.processed_files.append(os.path.basename(file_path))
else:
# ์ ํ์ผ ๋๋ ๋ณ๊ฒฝ๋ ํ์ผ ์ฒ๋ฆฌ
print(f"์ฒ๋ฆฌ ์ค: {file_path}")
try:
# ๊ฐ์ ๋ PDF ์ฒ๋ฆฌ ๋ฉ์๋ ์ฌ์ฉ
chunks = self._process_pdf_file(file_path)
if chunks: # ์ฒญํฌ๊ฐ ์๋ ๊ฒฝ์ฐ์๋ง ์ ์ฅ
# ์ฒญํฌ ์ ์ฅ
self._save_chunks(file_path, chunks)
all_chunks.extend(chunks)
if file_path in self.file_index:
updated_files.append(file_path)
else:
new_files.append(file_path)
self.processed_files.append(os.path.basename(file_path))
else:
print(f"'{file_path}' ์ฒ๋ฆฌ ์คํจ: ์ถ์ถ๋ ์ฒญํฌ ์์")
failed_files.append(file_path)
except Exception as e:
print(f"'{file_path}' ์ฒ๋ฆฌ ์ค ์ค๋ฅ: {e}")
failed_files.append(file_path)
# ๋ชจ๋ ์ฒญํฌ ์ ์ฅ
self.documents = all_chunks
processing_time = time.time() - start_time
print(f"๋ฌธ์ ์ฒ๋ฆฌ ์๋ฃ: {len(all_chunks)}๊ฐ ์ฒญํฌ, {processing_time:.2f}์ด")
# ๋ฒกํฐ ์ธ๋ฑ์ค ์ ์ฅ ๊ฒฝ๋ก ํ์ธ
if os.path.exists(self.vector_index_dir) and any(os.listdir(self.vector_index_dir)):
# ๊ธฐ์กด ๋ฒกํฐ ์ธ๋ฑ์ค ๋ก๋
try:
print("์ ์ฅ๋ ๋ฒกํฐ ์ธ๋ฑ์ค ๋ก๋ ์ค...")
vector_store_loaded = self.vector_store.load_local(self.vector_index_dir)
# ์ธ๋ฑ์ค ๋ก๋ ์ฑ๊ณต ํ์ธ
if self.vector_store.vector_store is not None:
# ์ ๋ฌธ์๋ ๋ณ๊ฒฝ๋ ๋ฌธ์๊ฐ ์์ผ๋ฉด ์ธ๋ฑ์ค ์
๋ฐ์ดํธ
if new_files or updated_files:
print("๋ฒกํฐ ์ธ๋ฑ์ค ์
๋ฐ์ดํธ ์ค...")
self.vector_store.add_documents(self.documents)
print("๋ฒกํฐ ์ธ๋ฑ์ค ๋ก๋ ์๋ฃ")
else:
print("๋ฒกํฐ ์ธ๋ฑ์ค๋ฅผ ๋ก๋ํ์ผ๋ ์ ํจํ์ง ์์, ์๋ก ์์ฑํฉ๋๋ค.")
self.vector_store.create_or_load(self.documents)
except Exception as e:
print(f"๋ฒกํฐ ์ธ๋ฑ์ค ๋ก๋ ์คํจ, ์๋ก ์์ฑํฉ๋๋ค: {e}")
# ์ค๋ฅ ์์ธ ์ ๋ณด ์ถ๋ ฅ
import traceback
traceback.print_exc()
# ์ ๋ฒกํฐ ์ธ๋ฑ์ค ์์ฑ
self.vector_store.create_or_load(self.documents)
else:
# ์ ๋ฒกํฐ ์ธ๋ฑ์ค ์์ฑ
print("์ ๋ฒกํฐ ์ธ๋ฑ์ค ์์ฑ ์ค...")
self.vector_store.create_or_load(self.documents)
# ๋ฒกํฐ ์ธ๋ฑ์ค ์ ์ฅ
if self.vector_store and self.vector_store.vector_store is not None:
try:
print(f"๋ฒกํฐ ์ธ๋ฑ์ค ์ ์ฅ ์ค: {self.vector_index_dir}")
save_result = self.vector_store.save_local(self.vector_index_dir)
print(f"๋ฒกํฐ ์ธ๋ฑ์ค ์ ์ฅ ์๋ฃ: {self.vector_index_dir}")
except Exception as e:
print(f"๋ฒกํฐ ์ธ๋ฑ์ค ์ ์ฅ ์คํจ: {e}")
# ์ค๋ฅ ์์ธ ์ ๋ณด ์ถ๋ ฅ
import traceback
traceback.print_exc()
else:
print("๋ฒกํฐ ์ธ๋ฑ์ค๊ฐ ์ด๊ธฐํ๋์ง ์์ ์ ์ฅํ์ง ์์ต๋๋ค.")
# RAG ์ฒด์ธ ์ด๊ธฐํ
try:
print("RAG ์ฒด์ธ ์ด๊ธฐํ ์๋...")
if RAG_CHAIN_AVAILABLE:
print("RAG_CHAIN_AVAILABLE=True, ์ด๊ธฐํ ์งํ")
# ์ง์ RAG ์ฒด์ธ ํด๋์ค๋ฅผ ์ฌ์ฉํ์ฌ ์ด๊ธฐํ
self.rag_chain = RAGChain(self.vector_store)
print("RAG ์ฒด์ธ ๊ฐ์ฒด ์์ฑ ์๋ฃ")
# ํ
์คํธ ์ฟผ๋ฆฌ ์คํํ์ฌ ์ฒด์ธ์ด ์๋ํ๋์ง ํ์ธ
try:
test_response = self.rag_chain.run("ํ
์คํธ ์ฟผ๋ฆฌ์
๋๋ค.")
print(f"RAG ์ฒด์ธ ํ
์คํธ ์ฑ๊ณต: ์๋ต ๊ธธ์ด {len(test_response)}")
self.is_initialized = True
except Exception as test_e:
print(f"RAG ์ฒด์ธ ํ
์คํธ ์คํจ: {test_e}")
import traceback
traceback.print_exc()
self.is_initialized = False
return f"RAG ์ฒด์ธ ํ
์คํธ ์คํจ: {test_e}"
else:
print("RAG_CHAIN_AVAILABLE=False, ์ด๊ธฐํ ๋ถ๊ฐ")
self.is_initialized = False
return "RAG ์ฒด์ธ ๋ชจ๋์ ์ฌ์ฉํ ์ ์์ต๋๋ค."
# ์ต์ข
์ํ ํ์ธ ๋ฐ ๋ก๊ทธ
print(f"RAG ์ฒด์ธ ์ด๊ธฐํ ๊ฒฐ๊ณผ: is_initialized={self.is_initialized}")
if self.is_initialized:
print("RAG ์ฒด์ธ ์ด๊ธฐํ ์ฑ๊ณต!")
else:
print("RAG ์ฒด์ธ ์ด๊ธฐํ ์คํจํ์ง๋ง ์์ธ๋ ๋ฐ์ํ์ง ์์.")
return "RAG ์ฒด์ธ ์ด๊ธฐํ ์คํจ: ์์ธ ๋ถ๋ช
"
except Exception as e:
print(f"RAG ์ฒด์ธ ์ด๊ธฐํ ์ค ์์ธ ๋ฐ์: {e}")
import traceback
traceback.print_exc()
self.is_initialized = False
return f"RAG ์ฒด์ธ ์ด๊ธฐํ ์คํจ: {e}"
total_time = time.time() - start_time
status_message = (
f"๋ฌธ์ ์ฒ๋ฆฌ ์๋ฃ!\n"
f"- ์ฒ๋ฆฌ๋ ํ์ผ: {len(self.processed_files)}๊ฐ\n"
f"- ์บ์๋ ํ์ผ: {len(cached_files)}๊ฐ\n"
f"- ์ ํ์ผ: {len(new_files)}๊ฐ\n"
f"- ์
๋ฐ์ดํธ๋ ํ์ผ: {len(updated_files)}๊ฐ\n"
f"- ์คํจํ ํ์ผ: {len(failed_files)}๊ฐ\n"
f"- ์ด ์ฒญํฌ ์: {len(self.documents)}๊ฐ\n"
f"- ์ฒ๋ฆฌ ์๊ฐ: {total_time:.2f}์ด\n"
f"- RAG ์ฒด์ธ ์ด๊ธฐํ: {'์ฑ๊ณต' if self.is_initialized else '์คํจ'}\n"
f"์ด์ ์ง๋ฌธํ ์ค๋น๊ฐ ๋์์ต๋๋ค!"
)
print(status_message)
return status_message
except Exception as e:
self.is_initialized = False
error_message = f"๋ฌธ์ ์ฒ๋ฆฌ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
print(error_message)
import traceback
traceback.print_exc()
return error_message
def reset_cache(self) -> str:
"""
์บ์ ์ด๊ธฐํ
Returns:
๊ฒฐ๊ณผ ๋ฉ์์ง
"""
try:
# ์ฒญํฌ ํ์ผ ์ญ์
for filename in os.listdir(self.chunks_dir):
file_path = os.path.join(self.chunks_dir, filename)
if os.path.isfile(file_path):
os.remove(file_path)
# ์ธ๋ฑ์ค ์ด๊ธฐํ
self.file_index = {}
self._save_file_index()
# ๋ฒกํฐ ์ธ๋ฑ์ค ์ญ์
for filename in os.listdir(self.vector_index_dir):
file_path = os.path.join(self.vector_index_dir, filename)
if os.path.isfile(file_path):
os.remove(file_path)
self.documents = []
self.processed_files = []
self.is_initialized = False
return "์บ์๊ฐ ์ด๊ธฐํ๋์์ต๋๋ค. ๋ค์ ์คํ ์ ๋ชจ๋ ๋ฌธ์๊ฐ ๋ค์ ์ฒ๋ฆฌ๋ฉ๋๋ค."
except Exception as e:
return f"์บ์ ์ด๊ธฐํ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
def process_query(self, query: str, chat_history: List[List[str]]) -> Tuple[str, List[List[str]]]:
"""
์ฌ์ฉ์ ์ฟผ๋ฆฌ ์ฒ๋ฆฌ
Args:
query: ์ฌ์ฉ์ ์ง๋ฌธ
chat_history: ๋ํ ๊ธฐ๋ก (๋ฆฌ์คํธ ํ์)
Returns:
์๋ต ๋ฐ ์
๋ฐ์ดํธ๋ ๋ํ ๊ธฐ๋ก
"""
if not query: # ๋น์ด์๋ ์ฟผ๋ฆฌ ์ฒ๋ฆฌ
return "", chat_history
if not self.is_initialized or self.rag_chain is None:
print("ํ
์คํธ ์ฟผ๋ฆฌ ์ฒ๋ฆฌ: ๋ฌธ์ ๋ก๋ ์ด๊ธฐํ๊ฐ ํ์ํฉ๋๋ค.")
response = "๋ฌธ์ ๋ก๋๊ฐ ์ด๊ธฐํ๋์ง ์์์ต๋๋ค. ์๋ ๋ก๋๋ฅผ ์๋ํฉ๋๋ค."
new_history = list(chat_history)
new_history.append([query, response])
# ์๋ ๋ก๋ ์๋
try:
init_result = self.auto_process_documents()
print(f"[DEBUG] ์๋ ๋ก๋ ํ is_initialized = {self.is_initialized}, RAG ์ฒด์ธ ์กด์ฌ = {self.rag_chain is not None}")
if not self.is_initialized or self.rag_chain is None:
response = f"๋ฌธ์๋ฅผ ๋ก๋ํ ์ ์์ต๋๋ค. 'documents' ํด๋์ PDF ํ์ผ์ด ์๋์ง ํ์ธํ์ธ์.\n์ค๋ฅ ์ ๋ณด: {init_result}"
new_history = list(chat_history)
new_history.append([query, response])
return "", new_history
except Exception as e:
response = f"๋ฌธ์ ๋ก๋ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
new_history = list(chat_history)
new_history.append([query, response])
return "", new_history
else:
print("ํ
์คํธ ์ฟผ๋ฆฌ ์ฒ๋ฆฌ: ๋ฌธ์๊ฐ ์ด๋ฏธ ๋ก๋๋์ด ์์ต๋๋ค.")
try:
# RAG ์ฒด์ธ ์คํ ๋ฐ ์๋ต ์์ฑ
start_time = time.time()
print(f"RAG ์ฒด์ธ ์คํ ์ค: ์ฟผ๋ฆฌ = '{query}'")
if self.is_initialized and self.rag_chain is not None:
response = self.rag_chain.run(query)
else:
print("RAG ์ฒด์ธ์ด ์ด๊ธฐํ๋์ง ์์: ๊ธฐ๋ณธ ์๋ต ์ฌ์ฉ")
response = self._fallback_response(query)
end_time = time.time()
query_time = end_time - start_time
print(f"์ฟผ๋ฆฌ ์ฒ๋ฆฌ ์๊ฐ: {query_time:.2f}์ด")
print(f"์๋ต: {response[:100]}..." if len(response) > 100 else f"์๋ต: {response}")
# ๋ฉ์์ง ํ์์ ๋ง๊ฒ ์ถ๊ฐ
new_history = list(chat_history)
new_history.append([query, response])
return "", new_history
except Exception as e:
error_msg = f"์ค๋ฅ ๋ฐ์: {str(e)}"
print(f"RAG ์ฒด์ธ ์คํ ์ค ์ค๋ฅ: {error_msg}")
import traceback
traceback.print_exc()
new_history = list(chat_history)
new_history.append([query, error_msg])
return "", new_history
def process_voice_query(self, audio, chat_history: List[List[str]]) -> List[List[str]]:
"""
์์ฑ ์ฟผ๋ฆฌ ์ฒ๋ฆฌ
Args:
audio: ๋
น์๋ ์ค๋์ค ๋ฐ์ดํฐ (numpy ๋ฐฐ์ด: (์ํ, ์ฑ๋))
chat_history: ๋ํ ๊ธฐ๋ก
Returns:
์
๋ฐ์ดํธ๋ ๋ํ ๊ธฐ๋ก
"""
if audio is None:
return chat_history
try:
import numpy as np
import scipy.io.wavfile as wav
# numpy ๋ฐฐ์ด์ WAV ํ์ผ๋ก ์ ์ฅ
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
temp_path = temp_file.name
# ์ํ๋ง ๋ ์ดํธ์ ์ค๋์ค ๋ฐ์ดํฐ๋ฅผ WAV ํ์ผ๋ก ์ ์ฅ
sr, data = audio
# 16๋นํธ PCM ํ์์ผ๋ก ๋ณํ
wav.write(temp_path, sr, data.astype(np.int16))
print(f"[STT] ์์ ์ค๋์ค ํ์ผ ์์ฑ: {temp_path}")
# config.py์์ ์ค์ ํ ์ธ์ด ์ฝ๋๋ก STT ์คํ
result = self.stt_client.recognize_file(temp_path, language=STT_LANGUAGE)
# ์์ ํ์ผ ์ญ์
try:
os.unlink(temp_path)
print("[STT] ์์ ์ค๋์ค ํ์ผ ์ญ์ ๋จ")
except Exception as e:
print(f"[STT] ์์ ํ์ผ ์ญ์ ์คํจ: {e}")
# STT ๊ฒฐ๊ณผ ์ฒ๋ฆฌ
if "error" in result:
error_msg = f"์์ฑ์ธ์ ์ค๋ฅ: {result.get('error')}"
print(f"[STT] {error_msg}")
new_history = list(chat_history)
new_history.append(["์์ฑ ๋ฉ์์ง", error_msg])
return new_history
# ์ธ์๋ ํ
์คํธ ์ถ์ถ
recognized_text = result.get("text", "")
if not recognized_text:
error_msg = "์์ฑ์ ์ธ์ํ ์ ์์ต๋๋ค. ๋ค์ ์๋ํด์ฃผ์ธ์."
print("[STT] ์ธ์๋ ํ
์คํธ ์์")
new_history = list(chat_history)
new_history.append(["์์ฑ ๋ฉ์์ง", error_msg])
return new_history
print(f"[STT] ์ธ์๋ ํ
์คํธ: {recognized_text}")
# ์ธ์๋ ํ
์คํธ๋ก ์ฟผ๋ฆฌ ์ฒ๋ฆฌ (์์ฑ ๋ฉ์์ง ์ ๋์ด ์ถ๊ฐ)
query = f"๐ค {recognized_text}"
print(f"[DEBUG] is_initialized = {self.is_initialized}, RAG ์ฒด์ธ ์กด์ฌ = {self.rag_chain is not None}")
# RAG ์ฒด์ธ ์คํ ๋ฐ ์๋ต ์์ฑ
if not self.is_initialized or self.rag_chain is None:
print("์์ฑ ์ฟผ๋ฆฌ ์ฒ๋ฆฌ: ๋ฌธ์ ๋ก๋ ์ด๊ธฐํ๊ฐ ํ์ํฉ๋๋ค.")
response = "๋ฌธ์ ๋ก๋๊ฐ ์ด๊ธฐํ๋์ง ์์์ต๋๋ค. ์๋ ๋ก๋๋ฅผ ์๋ํฉ๋๋ค."
new_history = list(chat_history)
new_history.append([query, response])
# ์๋ ๋ก๋ ์๋
try:
init_result = self.auto_process_documents()
print(f"[DEBUG] ์๋ ๋ก๋ ํ is_initialized = {self.is_initialized}, RAG ์ฒด์ธ ์กด์ฌ = {self.rag_chain is not None}")
if not self.is_initialized or self.rag_chain is None:
response = f"๋ฌธ์๋ฅผ ๋ก๋ํ ์ ์์ต๋๋ค. 'documents' ํด๋์ PDF ํ์ผ์ด ์๋์ง ํ์ธํ์ธ์.\n์ค๋ฅ ์ ๋ณด: {init_result}"
new_history = list(chat_history)
new_history.append([query, response])
return new_history
except Exception as e:
response = f"๋ฌธ์ ๋ก๋ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
new_history = list(chat_history)
new_history.append([query, response])
return new_history
else:
print("์์ฑ ์ฟผ๋ฆฌ ์ฒ๋ฆฌ: ๋ฌธ์๊ฐ ์ด๋ฏธ ๋ก๋๋์ด ์์ต๋๋ค.")
try:
# RAG ์ฒด์ธ ์คํ ๋ฐ ์๋ต ์์ฑ
start_time = time.time()
print(f"RAG ์ฒด์ธ ์คํ ์ค: ์ฟผ๋ฆฌ = '{query}'")
if self.is_initialized and self.rag_chain is not None:
response = self.rag_chain.run(query)
else:
print("RAG ์ฒด์ธ์ด ์ด๊ธฐํ๋์ง ์์: ๊ธฐ๋ณธ ์๋ต ์ฌ์ฉ")
response = self._fallback_response(query)
end_time = time.time()
query_time = end_time - start_time
print(f"์ฟผ๋ฆฌ ์ฒ๋ฆฌ ์๊ฐ: {query_time:.2f}์ด")
print(f"์๋ต: {response[:100]}..." if len(response) > 100 else f"์๋ต: {response}")
# ๋ฉ์์ง ํ์์ ๋ง๊ฒ ์ถ๊ฐ
new_history = list(chat_history) # ๊ธฐ์กด ๋ฆฌ์คํธ๋ฅผ ๋ณต์ฌ
new_history.append([query, response]) # ๋ฆฌ์คํธ ํ์์ผ๋ก ์ถ๊ฐ
return new_history
except Exception as e:
error_msg = f"์ค๋ฅ ๋ฐ์: {str(e)}"
print(f"RAG ์ฒด์ธ ์คํ ์ค ์ค๋ฅ: {error_msg}")
import traceback
traceback.print_exc()
# ๋ฉ์์ง ํ์์ ๋ง๊ฒ ์ถ๊ฐ
new_history = list(chat_history) # ๊ธฐ์กด ๋ฆฌ์คํธ๋ฅผ ๋ณต์ฌ
new_history.append([query, error_msg]) # ๋ฆฌ์คํธ ํ์์ผ๋ก ์ถ๊ฐ
return new_history
except Exception as e:
error_msg = f"์์ฑ ์ฒ๋ฆฌ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
print(f"[STT] {error_msg}")
import traceback
traceback.print_exc()
new_history = list(chat_history)
new_history.append(["์์ฑ ๋ฉ์์ง", error_msg])
return new_history
def launch_app(self) -> None:
"""
์์ฑ์ธ์ ๊ธฐ๋ฅ์ด ์ถ๊ฐ๋ Gradio ์ฑ ์คํ (์๋ ์์ฑ์ฒ๋ฆฌ ๊ฐ์ )
"""
import gradio as gr
import time
# ์์ฑ ์ธ์ ํ ์๋ ์ฒ๋ฆฌ ํจ์
def process_audio_auto(audio, chat_history):
"""๋
น์ ์๋ฃ ์ ์๋์ผ๋ก STT ์ฒ๋ฆฌ ํ ์ง์ ์ฒ๋ฆฌ"""
if audio is None:
return chat_history, gr.update(interactive=True), "๋
น์ ํ ์๋์ผ๋ก ์ฒ๋ฆฌ๋ฉ๋๋ค", ""
# ์ฒ๋ฆฌ ์ค ์ํ ๋ฉ์์ง
processing_msg = "์์ฑ ์ฒ๋ฆฌ ์ค..."
try:
import numpy as np
import scipy.io.wavfile as wav
# ์ํ ์
๋ฐ์ดํธ
yield chat_history, gr.update(interactive=False), processing_msg, "์์ฑ์ ํ
์คํธ๋ก ๋ณํ ์ค..."
# numpy ๋ฐฐ์ด์ WAV ํ์ผ๋ก ์ ์ฅ
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
temp_path = temp_file.name
# ์ํ๋ง ๋ ์ดํธ์ ์ค๋์ค ๋ฐ์ดํฐ๋ฅผ WAV ํ์ผ๋ก ์ ์ฅ
sr, data = audio
# 16๋นํธ PCM ํ์์ผ๋ก ๋ณํ
wav.write(temp_path, sr, data.astype(np.int16))
print(f"[STT] ์์ ์ค๋์ค ํ์ผ ์์ฑ: {temp_path}")
# config.py์์ ์ค์ ํ ์ธ์ด ์ฝ๋๋ก STT ์คํ
result = self.stt_client.recognize_file(temp_path, language=STT_LANGUAGE)
# ์์ ํ์ผ ์ญ์
try:
os.unlink(temp_path)
print("[STT] ์์ ์ค๋์ค ํ์ผ ์ญ์ ๋จ")
except Exception as e:
print(f"[STT] ์์ ํ์ผ ์ญ์ ์คํจ: {e}")
# STT ๊ฒฐ๊ณผ ์ฒ๋ฆฌ
if "error" in result:
error_msg = f"์์ฑ์ธ์ ์ค๋ฅ: {result.get('error')}"
print(f"[STT] {error_msg}")
new_history = list(chat_history)
new_history.append(["์์ฑ ๋ฉ์์ง", error_msg])
yield new_history, gr.update(interactive=True), error_msg, ""
return
# ์ธ์๋ ํ
์คํธ ์ถ์ถ
recognized_text = result.get("text", "")
if not recognized_text:
error_msg = "์์ฑ์ ์ธ์ํ ์ ์์ต๋๋ค. ๋ค์ ์๋ํด์ฃผ์ธ์."
print("[STT] ์ธ์๋ ํ
์คํธ ์์")
new_history = list(chat_history)
new_history.append(["์์ฑ ๋ฉ์์ง", error_msg])
yield new_history, gr.update(interactive=True), error_msg, ""
return
print(f"[STT] ์ธ์๋ ํ
์คํธ: {recognized_text}")
# ์ํ ์
๋ฐ์ดํธ
yield chat_history, gr.update(
interactive=False), f"์ธ์๋ ํ
์คํธ: {recognized_text}\n\n์๋ต ์์ฑ ์ค...", "์๋ต ์์ฑ ์ค..."
# ์ธ์๋ ํ
์คํธ๋ก ์ฟผ๋ฆฌ ์ฒ๋ฆฌ (์์ฑ ๋ฉ์์ง ์ ๋์ด ์ถ๊ฐ)
query = f"๐ค {recognized_text}"
print(f"[DEBUG] is_initialized = {self.is_initialized}, RAG ์ฒด์ธ ์กด์ฌ = {self.rag_chain is not None}")
# RAG ์ฒด์ธ ์คํ ๋ฐ ์๋ต ์์ฑ
if not self.is_initialized or self.rag_chain is None:
print("์์ฑ ์ฟผ๋ฆฌ ์ฒ๋ฆฌ: ๋ฌธ์ ๋ก๋ ์ด๊ธฐํ๊ฐ ํ์ํฉ๋๋ค.")
response = "๋ฌธ์ ๋ก๋๊ฐ ์ด๊ธฐํ๋์ง ์์์ต๋๋ค. ์๋ ๋ก๋๋ฅผ ์๋ํฉ๋๋ค."
new_history = list(chat_history)
new_history.append([query, response])
# ์๋ ๋ก๋ ์๋
try:
init_result = self.auto_process_documents()
print(
f"[DEBUG] ์๋ ๋ก๋ ํ is_initialized = {self.is_initialized}, RAG ์ฒด์ธ ์กด์ฌ = {self.rag_chain is not None}")
if not self.is_initialized or self.rag_chain is None:
response = f"๋ฌธ์๋ฅผ ๋ก๋ํ ์ ์์ต๋๋ค. 'documents' ํด๋์ PDF ํ์ผ์ด ์๋์ง ํ์ธํ์ธ์.\n์ค๋ฅ ์ ๋ณด: {init_result}"
new_history = list(chat_history)
new_history.append([query, response])
yield new_history, gr.update(interactive=True), response, ""
return
except Exception as e:
response = f"๋ฌธ์ ๋ก๋ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
new_history = list(chat_history)
new_history.append([query, response])
yield new_history, gr.update(interactive=True), response, ""
return
else:
print("์์ฑ ์ฟผ๋ฆฌ ์ฒ๋ฆฌ: ๋ฌธ์๊ฐ ์ด๋ฏธ ๋ก๋๋์ด ์์ต๋๋ค.")
try:
# RAG ์ฒด์ธ ์คํ ๋ฐ ์๋ต ์์ฑ
start_time = time.time()
print(f"RAG ์ฒด์ธ ์คํ ์ค: ์ฟผ๋ฆฌ = '{query}'")
if self.is_initialized and self.rag_chain is not None:
response = self.rag_chain.run(query)
else:
print("RAG ์ฒด์ธ์ด ์ด๊ธฐํ๋์ง ์์: ๊ธฐ๋ณธ ์๋ต ์ฌ์ฉ")
response = self._fallback_response(query)
end_time = time.time()
query_time = end_time - start_time
print(f"์ฟผ๋ฆฌ ์ฒ๋ฆฌ ์๊ฐ: {query_time:.2f}์ด")
print(f"์๋ต: {response[:100]}..." if len(response) > 100 else f"์๋ต: {response}")
# ๋ฉ์์ง ํ์์ ๋ง๊ฒ ์ถ๊ฐ
new_history = list(chat_history) # ๊ธฐ์กด ๋ฆฌ์คํธ๋ฅผ ๋ณต์ฌ
new_history.append([query, response]) # ๋ฆฌ์คํธ ํ์์ผ๋ก ์ถ๊ฐ
# ์ต์ข
์ํ ์
๋ฐ์ดํธ
yield new_history, gr.update(interactive=True), f"์ฒ๋ฆฌ ์๋ฃ: {recognized_text}", ""
except Exception as e:
error_msg = f"์ค๋ฅ ๋ฐ์: {str(e)}"
print(f"RAG ์ฒด์ธ ์คํ ์ค ์ค๋ฅ: {error_msg}")
import traceback
traceback.print_exc()
# ๋ฉ์์ง ํ์์ ๋ง๊ฒ ์ถ๊ฐ
new_history = list(chat_history) # ๊ธฐ์กด ๋ฆฌ์คํธ๋ฅผ ๋ณต์ฌ
new_history.append([query, error_msg]) # ๋ฆฌ์คํธ ํ์์ผ๋ก ์ถ๊ฐ
yield new_history, gr.update(interactive=True), error_msg, ""
except Exception as e:
error_msg = f"์์ฑ ์ฒ๋ฆฌ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
print(f"[STT] {error_msg}")
import traceback
traceback.print_exc()
new_history = list(chat_history)
new_history.append(["์์ฑ ๋ฉ์์ง", error_msg])
yield new_history, gr.update(interactive=True), error_msg, ""
with gr.Blocks(title="์์ฑ์ธ์ ๊ธฐ๋ฅ์ด ์ถ๊ฐ๋ PDF ๋ฌธ์ ๊ธฐ๋ฐ RAG ์ฑ๋ด") as app:
gr.Markdown("# ์์ฑ์ธ์ ๊ธฐ๋ฅ์ด ์ถ๊ฐ๋ PDF ๋ฌธ์ ๊ธฐ๋ฐ RAG ์ฑ๋ด")
gr.Markdown(f"* ์ฌ์ฉ ์ค์ธ LLM ๋ชจ๋ธ: **{LLM_MODEL}**")
gr.Markdown(f"* PDF ๋ฌธ์ ํด๋: **{self.pdf_directory}**")
gr.Markdown("* ๋ค์ด๋ฒ ํด๋ก๋ฐ ์์ฑ์ธ์ API ํตํฉ")
with gr.Row():
with gr.Column(scale=1):
# ๋ฌธ์ ์ํ ์น์
status_box = gr.Textbox(
label="๋ฌธ์ ์ฒ๋ฆฌ ์ํ",
value=f"์ฒ๋ฆฌ๋ ๋ฌธ์ ({len(self.processed_files)}๊ฐ): {', '.join(self.processed_files)}",
lines=5,
interactive=False
)
# ์บ์ ๊ด๋ฆฌ ๋ฒํผ
refresh_button = gr.Button("๋ฌธ์ ์๋ก ์ฝ๊ธฐ", variant="primary")
reset_button = gr.Button("์บ์ ์ด๊ธฐํ", variant="stop")
# ์ฒ๋ฆฌ๋ ํ์ผ ์ ๋ณด
with gr.Accordion("์บ์ ์ธ๋ถ ์ ๋ณด", open=False):
file_info = ""
for file_path, info in self.file_index.items():
file_info += f"- {os.path.basename(file_path)}: {info['chunks_count']}๊ฐ ์ฒญํฌ\n"
cache_info = gr.Textbox(
label="์บ์๋ ํ์ผ ์ ๋ณด",
value=file_info or "์บ์๋ ํ์ผ์ด ์์ต๋๋ค.",
lines=5,
interactive=False
)
with gr.Column(scale=2):
# ์ฑํ
์ธํฐํ์ด์ค
chatbot = gr.Chatbot(
label="๋ํ ๋ด์ฉ",
height=500,
show_copy_button=True
)
with gr.Tabs() as input_tabs:
# ํ
์คํธ ์
๋ ฅ ํญ
with gr.Tab("ํ
์คํธ ์
๋ ฅ"):
# ํ
์คํธ ์
๋ ฅ๊ณผ ์ ์ก ๋ฒํผ์ ์ํ์ผ๋ก ๋ฐฐ์น
with gr.Row():
query_box = gr.Textbox(
label="์ง๋ฌธ",
placeholder="์ฒ๋ฆฌ๋ ๋ฌธ์ ๋ด์ฉ์ ๋ํด ์ง๋ฌธํ์ธ์...",
lines=2,
scale=4
)
submit_btn = gr.Button("์ ์ก", variant="primary", scale=1)
# ์์ฑ ์
๋ ฅ ํญ (์๋ ์ฒ๋ฆฌ ๋ฐฉ์์ผ๋ก ๊ฐ์ )
with gr.Tab("์์ฑ ์
๋ ฅ"):
# ์ํ ํ์
processing_status = gr.Textbox(
label="์ฒ๋ฆฌ ์ํ",
placeholder="๋
น์ ํ ์๋์ผ๋ก ์ฒ๋ฆฌ๋ฉ๋๋ค",
lines=3,
interactive=False,
visible=True
)
# ํ๋ก๊ทธ๋ ์ค ๋ฐ ์ถ๊ฐ
progress_bar = gr.Textbox(
label="์งํ ์ํฉ",
value="",
visible=True
)
# ์๋ ์ฒ๋ฆฌ ์ค๋์ค ์ปดํฌ๋ํธ
audio_input_auto = gr.Audio(
label="๋ง์ดํฌ ์
๋ ฅ (๋
น์ ํ ์๋ ์ฒ๋ฆฌ)",
sources=["microphone"],
type="numpy",
format="wav",
streaming=False
)
# ๋ํ ์ด๊ธฐํ ๋ฒํผ
clear_chat_button = gr.Button("๋ํ ์ด๊ธฐํ")
# ์ด๋ฒคํธ ํธ๋ค๋ฌ ์ค์
refresh_button.click(
fn=self.auto_process_documents,
inputs=[],
outputs=[status_box]
)
reset_button.click(
fn=lambda: (self.reset_cache(), self.auto_process_documents()),
inputs=[],
outputs=[status_box]
)
# ํ
์คํธ ์ ์ก ๋ฒํผ ํด๋ฆญ ์ด๋ฒคํธ
submit_btn.click(
fn=self.process_query,
inputs=[query_box, chatbot],
outputs=[query_box, chatbot]
)
# ์ํฐํค ์
๋ ฅ ์ด๋ฒคํธ
query_box.submit(
fn=self.process_query,
inputs=[query_box, chatbot],
outputs=[query_box, chatbot]
)
# ์๋ ์์ฑ์ฒ๋ฆฌ ์ด๋ฒคํธ (๋
น์์ด ๋๋๋ฉด ์๋์ผ๋ก ์ฒ๋ฆฌ ์์)
audio_input_auto.stop_recording(
fn=process_audio_auto,
inputs=[audio_input_auto, chatbot],
outputs=[chatbot, audio_input_auto, processing_status, progress_bar]
)
# ๋ํ ์ด๊ธฐํ ๋ฒํผ
clear_chat_button.click(
fn=lambda: [], # ๋น ๋ฆฌ์คํธ ๋ฐํ
outputs=[chatbot]
)
# ์ฑ ์คํ
app.launch(share=False)
if __name__ == "__main__":
app = AutoRAGChatApp()
app.launch_app() |