Spaces:
Paused
Paused
File size: 65,847 Bytes
14586a6 b4a2320 14586a6 cd49bcd 14586a6 26d4b34 14586a6 15e251d 14586a6 cd49bcd 14586a6 cd49bcd 14586a6 cd49bcd 14586a6 cd49bcd 14586a6 |
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 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 |
"""
๋๋ฒ๊น
์ ์ํ ์ฝ๋ ์ถ๊ฐ - ๊ฒฝ๋ก ๊ด๋ จ ๋ฌธ์ ํด๊ฒฐ
"""
import os
import time
import hashlib
import pickle
import json
import logging
import glob
from typing import List, Dict, Tuple, Any, Optional
from logging.handlers import RotatingFileHandler
from pathlib import Path
from langchain.schema import Document
from config import (
PDF_DIRECTORY, CACHE_DIRECTORY, CHUNK_SIZE, CHUNK_OVERLAP,
LLM_MODEL, LOG_LEVEL, LOG_FILE, print_config, validate_config
)
from optimized_document_processor import OptimizedDocumentProcessor
from vector_store import VectorStore
import sys
print("===== Script starting =====")
sys.stdout.flush() # ์ฆ์ ์ถ๋ ฅ ๊ฐ์
# ์ฃผ์ ํจ์/๋ฉ์๋ ํธ์ถ ์ ํ์๋ ๋๋ฒ๊น
์ถ๋ ฅ ์ถ๊ฐ
print("Loading config...")
sys.stdout.flush()
# from config import ... ๋ฑ์ ์ฝ๋
print("Config loaded!")
sys.stdout.flush()
# ๋ก๊น
์ค์ ๊ฐ์
def setup_logging():
"""์ ํ๋ฆฌ์ผ์ด์
๋ก๊น
์ค์ """
# ๋ก๊ทธ ๋ ๋ฒจ ์ค์
log_level = getattr(logging, LOG_LEVEL.upper(), logging.INFO)
# ๋ก๊ทธ ํฌ๋งท ์ค์
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
formatter = logging.Formatter(log_format)
# ๋ฃจํธ ๋ก๊ฑฐ ์ค์
root_logger = logging.getLogger()
root_logger.setLevel(log_level)
# ํธ๋ค๋ฌ ์ด๊ธฐํ
# ์ฝ์ ํธ๋ค๋ฌ
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
root_logger.addHandler(console_handler)
# ํ์ผ ํธ๋ค๋ฌ (ํ์ ์)
try:
file_handler = RotatingFileHandler(
LOG_FILE,
maxBytes=10*1024*1024, # 10 MB
backupCount=5
)
file_handler.setFormatter(formatter)
root_logger.addHandler(file_handler)
except Exception as e:
console_handler.warning(f"๋ก๊ทธ ํ์ผ ์ค์ ์คํจ: {e}, ์ฝ์ ๋ก๊น
๋ง ์ฌ์ฉํฉ๋๋ค.")
return logging.getLogger("AutoRAG")
# ๋ก๊ฑฐ ์ค์
logger = setup_logging()
# ํ์ฌ ์์
๋๋ ํ ๋ฆฌ ํ์ธ์ ์ํ ๋๋ฒ๊น
์ฝ๋
current_dir = os.getcwd()
logger.info(f"ํ์ฌ ์์
๋๋ ํ ๋ฆฌ: {current_dir}")
# ์ค์ ๋ PDF ๋๋ ํ ๋ฆฌ ํ์ธ
abs_pdf_dir = os.path.abspath(PDF_DIRECTORY)
logger.info(f"์ค์ ๋ PDF ๋๋ ํ ๋ฆฌ: {PDF_DIRECTORY}")
logger.info(f"์ ๋ ๊ฒฝ๋ก๋ก ๋ณํ๋ PDF ๋๋ ํ ๋ฆฌ: {abs_pdf_dir}")
# PDF ๋๋ ํ ๋ฆฌ ์กด์ฌ ํ์ธ
if os.path.exists(abs_pdf_dir):
logger.info(f"PDF ๋๋ ํ ๋ฆฌ๊ฐ ์กด์ฌํฉ๋๋ค: {abs_pdf_dir}")
# ๋๋ ํ ๋ฆฌ ๋ด์ฉ ํ์ธ
pdf_files = glob.glob(os.path.join(abs_pdf_dir, "*.pdf"))
logger.info(f"๋๋ ํ ๋ฆฌ ๋ด PDF ํ์ผ ๋ชฉ๋ก: {pdf_files}")
else:
logger.error(f"PDF ๋๋ ํ ๋ฆฌ๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค: {abs_pdf_dir}")
# ์์ ๋๋ ํ ๋ฆฌ ๋ด์ฉ ํ์ธ
parent_dir = os.path.dirname(abs_pdf_dir)
logger.info(f"์์ ๋๋ ํ ๋ฆฌ: {parent_dir}")
if os.path.exists(parent_dir):
dir_contents = os.listdir(parent_dir)
logger.info(f"์์ ๋๋ ํ ๋ฆฌ ๋ด์ฉ: {dir_contents}")
# ์ค์ ์ํ ํ์ธ
logger.info("์ ํ๋ฆฌ์ผ์ด์
์ค์ ๊ฒ์ฆ ์ค...")
config_status = validate_config()
if config_status["status"] != "valid":
for warning in config_status["warnings"]:
logger.warning(f"์ค์ ๊ฒฝ๊ณ : {warning}")
# ์์ ํ ์ํฌํธ
try:
from rag_chain import RAGChain
RAG_CHAIN_AVAILABLE = True
print("RAG ์ฒด์ธ ๋ชจ๋ ๋ก๋ ์ฑ๊ณต!")
except ImportError as e:
logger.warning(f"RAG ์ฒด์ธ ๋ชจ๋์ ๋ก๋ํ ์ ์์ต๋๋ค: {e}")
RAG_CHAIN_AVAILABLE = False
except Exception as e:
logger.warning(f"RAG ์ฒด์ธ ๋ชจ๋ ๋ก๋ ์ค ์์์น ๋ชปํ ์ค๋ฅ: {e}")
RAG_CHAIN_AVAILABLE = False
# ํด๋ฐฑ RAG ๊ด๋ จ ๋ชจ๋๋ ๋ฏธ๋ฆฌ ํ์ธ
try:
from fallback_rag_chain import FallbackRAGChain
FALLBACK_AVAILABLE = True
print("ํด๋ฐฑ RAG ์ฒด์ธ ๋ชจ๋ ๋ก๋ ์ฑ๊ณต!")
except ImportError as e:
logger.warning(f"ํด๋ฐฑ RAG ์ฒด์ธ ๋ชจ๋์ ๋ก๋ํ ์ ์์ต๋๋ค: {e}")
FALLBACK_AVAILABLE = False
try:
from offline_fallback_rag import OfflineFallbackRAG
OFFLINE_FALLBACK_AVAILABLE = True
print("์คํ๋ผ์ธ ํด๋ฐฑ RAG ๋ชจ๋ ๋ก๋ ์ฑ๊ณต!")
except ImportError as e:
logger.warning(f"์คํ๋ผ์ธ ํด๋ฐฑ RAG ๋ชจ๋์ ๋ก๋ํ ์ ์์ต๋๋ค: {e}")
OFFLINE_FALLBACK_AVAILABLE = False
class DocumentProcessingError(Exception):
"""๋ฌธ์ ์ฒ๋ฆฌ ์ค ๋ฐ์ํ๋ ์์ธ"""
pass
class VectorStoreError(Exception):
"""๋ฒกํฐ ์คํ ์ด ์์
์ค ๋ฐ์ํ๋ ์์ธ"""
pass
class RAGInitializationError(Exception):
"""RAG ์ฒด์ธ ์ด๊ธฐํ ์ค ๋ฐ์ํ๋ ์์ธ"""
pass
class ConfigurationError(Exception):
"""์ค์ ๊ด๋ จ ์ค๋ฅ"""
pass
class AutoRAGChatApp:
"""
documents ํด๋์ PDF ํ์ผ์ ์๋์ผ๋ก ์ฒ๋ฆฌํ๋ RAG ์ฑ๋ด
"""
def __init__(self):
"""
RAG ์ฑ๋ด ์ ํ๋ฆฌ์ผ์ด์
์ด๊ธฐํ
"""
try:
logger.info("AutoRAGChatApp ์ด๊ธฐํ ์์")
# ๋ฐ์ดํฐ ๋๋ ํ ๋ฆฌ ์ ์ (์ค์ ์์ ๊ฐ์ ธ์ด)
# ์ ๋ ๊ฒฝ๋ก๋ก ๋ณํํ์ฌ ์ฌ์ฉ
self.pdf_directory = os.path.abspath(PDF_DIRECTORY)
self.cache_directory = os.path.abspath(CACHE_DIRECTORY)
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")
logger.info(f"์ค์ ๋ PDF ๋๋ ํ ๋ฆฌ (์ ๋ ๊ฒฝ๋ก): {self.pdf_directory}")
# ๋๋ ํ ๋ฆฌ ๊ฒ์ฆ
self._verify_pdf_directory()
# ๋๋ ํ ๋ฆฌ ์์ฑ
self._ensure_directories_exist()
logger.info(f"PDF ๋ฌธ์ ๋๋ ํ ๋ฆฌ: '{self.pdf_directory}'")
logger.info(f"์บ์ ๋๋ ํ ๋ฆฌ: '{self.cache_directory}'")
# ์ปดํฌ๋ํธ ์ด๊ธฐํ
try:
self.document_processor = OptimizedDocumentProcessor(
chunk_size=CHUNK_SIZE,
chunk_overlap=CHUNK_OVERLAP
)
except Exception as e:
logger.error(f"๋ฌธ์ ์ฒ๋ฆฌ๊ธฐ ์ด๊ธฐํ ์คํจ: {e}")
raise DocumentProcessingError(f"๋ฌธ์ ์ฒ๋ฆฌ๊ธฐ ์ด๊ธฐํ ์คํจ: {str(e)}")
# ๋ฒกํฐ ์ ์ฅ์ ์ด๊ธฐํ
try:
self.vector_store = VectorStore(use_milvus=False)
except Exception as e:
logger.error(f"๋ฒกํฐ ์ ์ฅ์ ์ด๊ธฐํ ์คํจ: {e}")
raise VectorStoreError(f"๋ฒกํฐ ์ ์ฅ์ ์ด๊ธฐํ ์คํจ: {str(e)}")
# ๋ฌธ์ ์ธ๋ฑ์ค ๋ก๋
self.file_index = self._load_file_index()
# ๊ธฐ๋ณธ ๋ณ์ ์ด๊ธฐํ
self.documents = []
self.processed_files = []
self.is_initialized = False
# ์์ ์ ์๋์ผ๋ก ๋ฌธ์ ๋ก๋ ๋ฐ ์ฒ๋ฆฌ
logger.info("๋ฌธ์ ์๋ ๋ก๋ ๋ฐ ์ฒ๋ฆฌ ์์...")
self.auto_process_documents()
logger.info("AutoRAGChatApp ์ด๊ธฐํ ์๋ฃ")
except Exception as e:
logger.critical(f"์ ํ๋ฆฌ์ผ์ด์
์ด๊ธฐํ ์ค ์ฌ๊ฐํ ์ค๋ฅ: {e}", exc_info=True)
# ๊ธฐ๋ณธ ์ํ ์ค์ ์ผ๋ก ์ต์ํ์ ๊ธฐ๋ฅ ์ ์ง
self.pdf_directory = os.path.abspath(PDF_DIRECTORY)
self.documents = []
self.processed_files = []
self.is_initialized = False
self.file_index = {}
def _ensure_directories_exist(self) -> None:
"""
ํ์ํ ๋๋ ํ ๋ฆฌ๊ฐ ์กด์ฌํ๋์ง ํ์ธํ๊ณ ์์ฑ
"""
directories = [
self.pdf_directory,
self.cache_directory,
self.chunks_dir,
self.vector_index_dir
]
for directory in directories:
try:
os.makedirs(directory, exist_ok=True)
except Exception as e:
logger.error(f"๋๋ ํ ๋ฆฌ ์์ฑ ์คํจ '{directory}': {e}")
raise OSError(f"๋๋ ํ ๋ฆฌ ์์ฑ ์คํจ '{directory}': {str(e)}")
def _process_pdf_file(self, file_path: str) -> List[Document]:
"""
PDF ํ์ผ ์ฒ๋ฆฌ - docling ์คํจ ์ PyPDFLoader ์ฌ์ฉ
Args:
file_path: ์ฒ๋ฆฌํ PDF ํ์ผ ๊ฒฝ๋ก
Returns:
์ฒ๋ฆฌ๋ ๋ฌธ์ ์ฒญํฌ ๋ฆฌ์คํธ
"""
if not os.path.exists(file_path):
logger.error(f"ํ์ผ์ด ์กด์ฌํ์ง ์์: {file_path}")
raise FileNotFoundError(f"ํ์ผ์ด ์กด์ฌํ์ง ์์: {file_path}")
try:
logger.info(f"docling์ผ๋ก ์ฒ๋ฆฌ ์๋: {file_path}")
# docling ์ฌ์ฉ ์๋
try:
# 10์ด ํ์์์ ์ค์ (์ต์
)
import signal
def timeout_handler(signum, frame):
raise TimeoutError("docling ์ฒ๋ฆฌ ์๊ฐ ์ด๊ณผ (60์ด)")
# ๋ฆฌ๋
์ค/๋งฅ์์๋ง ์๋ (์๋์ฐ์์๋ ๋ฌด์๋จ)
try:
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(60) # 60์ด ํ์์์
except (AttributeError, ValueError) as se:
logger.warning(f"์๊ทธ๋ ์ค์ ์คํจ (์๋์ฐ ํ๊ฒฝ์ผ ์ ์์): {se}")
# docling์ผ๋ก ์ฒ๋ฆฌ ์๋
chunks = self.document_processor.process_pdf(file_path, use_docling=True)
# ํ์์์ ์ทจ์
try:
signal.alarm(0)
except (AttributeError, ValueError):
pass
return chunks
except TimeoutError as te:
logger.warning(f"docling ์ฒ๋ฆฌ ์๊ฐ ์ด๊ณผ: {te}")
logger.info("PyPDFLoader๋ก ๋์ฒดํฉ๋๋ค.")
# PyPDFLoader๋ก ๋์ฒด
try:
return self.document_processor.process_pdf(file_path, use_docling=False)
except Exception as inner_e:
logger.error(f"PyPDFLoader ์ฒ๋ฆฌ ์ค๋ฅ: {inner_e}", exc_info=True)
raise DocumentProcessingError(f"PDF ๋ก๋ฉ ์คํจ (PyPDFLoader): {str(inner_e)}")
except Exception as e:
# docling ์ค๋ฅ ํ์ธ
error_str = str(e)
if "Invalid code point" in error_str or "RuntimeError" in error_str:
logger.warning(f"docling ์ฒ๋ฆฌ ์ค๋ฅ (์ฝ๋ ํฌ์ธํธ ๋ฌธ์ ): {error_str}")
logger.info("PyPDFLoader๋ก ๋์ฒดํฉ๋๋ค.")
else:
logger.warning(f"docling ์ฒ๋ฆฌ ์ค๋ฅ: {error_str}")
logger.info("PyPDFLoader๋ก ๋์ฒดํฉ๋๋ค.")
# PyPDFLoader๋ก ๋์ฒด
try:
return self.document_processor.process_pdf(file_path, use_docling=False)
except Exception as inner_e:
logger.error(f"PyPDFLoader ์ฒ๋ฆฌ ์ค๋ฅ: {inner_e}", exc_info=True)
raise DocumentProcessingError(f"PDF ๋ก๋ฉ ์คํจ (PyPDFLoader): {str(inner_e)}")
except DocumentProcessingError:
# ์ด๋ฏธ ๋ํ๋ ์์ธ๋ ๊ทธ๋๋ก ์ ๋ฌ
raise
except Exception as e:
logger.error(f"PDF ์ฒ๋ฆฌ ์ค ์ฌ๊ฐํ ์ค๋ฅ: {e}", exc_info=True)
# ๋น ์ฒญํฌ๋ผ๋ ๋ฐํํ์ฌ ์ ์ฒด ์ฒ๋ฆฌ๊ฐ ์ค๋จ๋์ง ์๋๋ก ํจ
logger.warning(f"'{file_path}' ์ฒ๋ฆฌ ์คํจ๋ก ๋น ์ฒญํฌ ๋ชฉ๋ก ๋ฐํ")
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 json.JSONDecodeError as e:
logger.error(f"์ธ๋ฑ์ค ํ์ผ JSON ํ์ฑ ์คํจ: {e}")
logger.warning("์์๋ ์ธ๋ฑ์ค ํ์ผ, ์๋ก์ด ์ธ๋ฑ์ค๋ฅผ ์์ฑํฉ๋๋ค.")
return {}
except Exception as e:
logger.error(f"์ธ๋ฑ์ค ํ์ผ ๋ก๋ ์คํจ: {e}")
return {}
return {}
def _save_file_index(self) -> None:
"""
ํ์ผ ์ธ๋ฑ์ค ์ ์ฅ
"""
try:
with open(self.index_file, 'w', encoding='utf-8') as f:
json.dump(self.file_index, f, ensure_ascii=False, indent=2)
logger.debug("ํ์ผ ์ธ๋ฑ์ค ์ ์ฅ ์๋ฃ")
except Exception as e:
logger.error(f"ํ์ผ ์ธ๋ฑ์ค ์ ์ฅ ์คํจ: {e}")
raise IOError(f"ํ์ผ ์ธ๋ฑ์ค ์ ์ฅ ์คํจ: {str(e)}")
def _calculate_file_hash(self, file_path: str) -> str:
"""
ํ์ผ ํด์ ๊ณ์ฐ
Args:
file_path: ํ์ผ ๊ฒฝ๋ก
Returns:
MD5 ํด์๊ฐ
"""
if not os.path.exists(file_path):
logger.error(f"ํด์ ๊ณ์ฐ ์คํจ - ํ์ผ์ด ์กด์ฌํ์ง ์์: {file_path}")
raise FileNotFoundError(f"ํ์ผ์ด ์กด์ฌํ์ง ์์: {file_path}")
try:
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()
except Exception as e:
logger.error(f"ํ์ผ ํด์ ๊ณ์ฐ ์ค ์ค๋ฅ: {e}")
raise IOError(f"ํ์ผ ํด์ ๊ณ์ฐ ์คํจ: {str(e)}")
def _is_file_processed(self, file_path: str) -> bool:
"""
ํ์ผ์ด ์ด๋ฏธ ์ฒ๋ฆฌ๋์๊ณ ๋ณ๊ฒฝ๋์ง ์์๋์ง ํ์ธ
Args:
file_path: ํ์ผ ๊ฒฝ๋ก
Returns:
์ฒ๋ฆฌ ์ฌ๋ถ
"""
# ํ์ผ ์กด์ฌ ํ์ธ
if not os.path.exists(file_path):
logger.warning(f"ํ์ผ์ด ์กด์ฌํ์ง ์์: {file_path}")
return False
# ์ธ๋ฑ์ค์ ํ์ผ ์กด์ฌ ์ฌ๋ถ ํ์ธ
if file_path not in self.file_index:
return False
try:
# ํ์ฌ ํด์๊ฐ ๊ณ์ฐ
current_hash = self._calculate_file_hash(file_path)
# ์ ์ฅ๋ ํด์๊ฐ๊ณผ ๋น๊ต
if self.file_index[file_path]['hash'] != current_hash:
logger.info(f"ํ์ผ ๋ณ๊ฒฝ ๊ฐ์ง: {file_path}")
return False
# ์ฒญํฌ ํ์ผ ์กด์ฌ ํ์ธ
chunks_path = self.file_index[file_path]['chunks_path']
if not os.path.exists(chunks_path):
logger.warning(f"์ฒญํฌ ํ์ผ์ด ์กด์ฌํ์ง ์์: {chunks_path}")
return False
return True
except Exception as e:
logger.error(f"ํ์ผ ์ฒ๋ฆฌ ์ํ ํ์ธ ์ค ์ค๋ฅ: {e}")
return False
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: ๋ฌธ์ ์ฒญํฌ ๋ฆฌ์คํธ
"""
try:
# ํด์ ๊ณ์ฐ
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),
'file_size': os.path.getsize(file_path),
'file_name': os.path.basename(file_path)
}
# ์ธ๋ฑ์ค ์ ์ฅ
self._save_file_index()
logger.info(f"์ฒญํฌ ์ ์ฅ ์๋ฃ: {file_path} ({len(chunks)}๊ฐ ์ฒญํฌ)")
except Exception as e:
logger.error(f"์ฒญํฌ ์ ์ฅ ์คํจ: {e}", exc_info=True)
raise IOError(f"์ฒญํฌ ์ ์ฅ ์คํจ: {str(e)}")
def _load_chunks(self, file_path: str) -> List[Document]:
"""
์ ์ฅ๋ ์ฒญํฌ ๋ฐ์ดํฐ ๋ก๋
Args:
file_path: ํ์ผ ๊ฒฝ๋ก
Returns:
๋ฌธ์ ์ฒญํฌ ๋ฆฌ์คํธ
"""
if file_path not in self.file_index:
logger.error(f"์ธ๋ฑ์ค์ ํ์ผ์ด ์กด์ฌํ์ง ์์: {file_path}")
raise KeyError(f"์ธ๋ฑ์ค์ ํ์ผ์ด ์กด์ฌํ์ง ์์: {file_path}")
chunks_path = self.file_index[file_path]['chunks_path']
if not os.path.exists(chunks_path):
logger.error(f"์ฒญํฌ ํ์ผ์ด ์กด์ฌํ์ง ์์: {chunks_path}")
raise FileNotFoundError(f"์ฒญํฌ ํ์ผ์ด ์กด์ฌํ์ง ์์: {chunks_path}")
try:
with open(chunks_path, 'rb') as f:
chunks = pickle.load(f)
logger.info(f"์ฒญํฌ ๋ก๋ ์๋ฃ: {file_path} ({len(chunks)}๊ฐ ์ฒญํฌ)")
return chunks
except pickle.UnpicklingError as e:
logger.error(f"์ฒญํฌ ํ์ผ ์ญ์ง๋ ฌํ ์คํจ: {e}")
raise IOError(f"์ฒญํฌ ํ์ผ ์์: {str(e)}")
except Exception as e:
logger.error(f"์ฒญํฌ ๋ก๋ ์คํจ: {e}", exc_info=True)
raise IOError(f"์ฒญํฌ ๋ก๋ ์คํจ: {str(e)}")
def _verify_pdf_directory(self):
"""PDF ๋๋ ํ ๋ฆฌ ๊ฒ์ฆ ๋ฐ ํ์ผ ์กด์ฌ ํ์ธ"""
try:
# ๋๋ ํ ๋ฆฌ ์กด์ฌ ํ์ธ
if not os.path.exists(self.pdf_directory):
try:
logger.warning(f"PDF ๋๋ ํ ๋ฆฌ๊ฐ ์กด์ฌํ์ง ์์ ์์ฑํฉ๋๋ค: {self.pdf_directory}")
os.makedirs(self.pdf_directory, exist_ok=True)
except Exception as e:
logger.error(f"PDF ๋๋ ํ ๋ฆฌ ์์ฑ ์คํจ: {e}")
raise
# ๋๋ ํ ๋ฆฌ์ธ์ง ํ์ธ
if not os.path.isdir(self.pdf_directory):
logger.error(f"PDF ๊ฒฝ๋ก๊ฐ ๋๋ ํ ๋ฆฌ๊ฐ ์๋๋๋ค: {self.pdf_directory}")
raise ConfigurationError(f"PDF ๊ฒฝ๋ก๊ฐ ๋๋ ํ ๋ฆฌ๊ฐ ์๋๋๋ค: {self.pdf_directory}")
# PDF ํ์ผ ์กด์ฌ ํ์ธ
pdf_files = [f for f in os.listdir(self.pdf_directory) if f.lower().endswith('.pdf')]
if pdf_files:
logger.info(f"PDF ๋๋ ํ ๋ฆฌ์์ {len(pdf_files)}๊ฐ์ PDF ํ์ผ์ ์ฐพ์์ต๋๋ค: {pdf_files}")
else:
# ์ฌ๋ฌ ๊ฒฝ๋ก์์ PDF ํ์ผ ํ์ ์๋
alternative_paths = [
"./documents",
"../documents",
"documents",
os.path.join(os.getcwd(), "documents")
]
found_pdfs = False
for alt_path in alternative_paths:
if os.path.exists(alt_path) and os.path.isdir(alt_path):
alt_pdf_files = [f for f in os.listdir(alt_path) if f.lower().endswith('.pdf')]
if alt_pdf_files:
logger.warning(f"๋์ฒด ๊ฒฝ๋ก '{alt_path}'์์ PDF ํ์ผ์ ์ฐพ์์ต๋๋ค. ์ด ๊ฒฝ๋ก๋ฅผ ์ฌ์ฉํฉ๋๋ค.")
self.pdf_directory = os.path.abspath(alt_path)
found_pdfs = True
break
if not found_pdfs:
logger.warning(f"PDF ๋๋ ํ ๋ฆฌ์ PDF ํ์ผ์ด ์์ต๋๋ค: {self.pdf_directory}")
logger.info("PDF ํ์ผ์ ๋๋ ํ ๋ฆฌ์ ์ถ๊ฐํด์ฃผ์ธ์.")
except Exception as e:
logger.error(f"PDF ๋๋ ํ ๋ฆฌ ๊ฒ์ฆ ์ค ์ค๋ฅ: {e}", exc_info=True)
raise
def auto_process_documents(self) -> str:
"""
documents ํด๋์ PDF ํ์ผ ์๋ ์ฒ๋ฆฌ
Returns:
์ฒ๋ฆฌ ๊ฒฐ๊ณผ ๋ฉ์์ง
"""
try:
start_time = time.time()
# PDF ํ์ผ ๋ชฉ๋ก ์์ง์ ๊ฐ์ ํ์ฌ ๋ค์ํ ๊ฒฝ๋ก ์ฒ๋ฆฌ
try:
pdf_files = []
# ์ค์ ๋ ๋๋ ํ ๋ฆฌ์์ PDF ํ์ผ ์ฐพ๊ธฐ
logger.info(f"PDF ํ์ผ ๊ฒ์ ๊ฒฝ๋ก: {self.pdf_directory}")
if os.path.exists(self.pdf_directory) and os.path.isdir(self.pdf_directory):
# ๋๋ ํ ๋ฆฌ ๋ด์ฉ ์ถ๋ ฅ (๋๋ฒ๊น
์ฉ)
dir_contents = os.listdir(self.pdf_directory)
logger.info(f"๋๋ ํ ๋ฆฌ ๋ด์ฉ: {dir_contents}")
# PDF ํ์ผ๋ง ํํฐ๋ง
for filename in os.listdir(self.pdf_directory):
if filename.lower().endswith('.pdf'):
file_path = os.path.join(self.pdf_directory, filename)
if os.path.isfile(file_path): # ์ค์ ํ์ผ์ธ์ง ํ์ธ
pdf_files.append(file_path)
logger.info(f"PDF ํ์ผ ์ฐพ์: {file_path}")
# ๋ฐ๊ฒฌ๋ ๋ชจ๋ ํ์ผ ๋ก๊ทธ
logger.info(f"๋ฐ๊ฒฌ๋ ๋ชจ๋ PDF ํ์ผ: {pdf_files}")
except FileNotFoundError:
logger.error(f"PDF ๋๋ ํ ๋ฆฌ๋ฅผ ์ฐพ์ ์ ์์: {self.pdf_directory}")
return f"'{self.pdf_directory}' ๋๋ ํ ๋ฆฌ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค. ๋๋ ํ ๋ฆฌ๊ฐ ์กด์ฌํ๋์ง ํ์ธํ์ธ์."
except PermissionError:
logger.error(f"PDF ๋๋ ํ ๋ฆฌ ์ ๊ทผ ๊ถํ ์์: {self.pdf_directory}")
return f"'{self.pdf_directory}' ๋๋ ํ ๋ฆฌ์ ์ ๊ทผํ ์ ์์ต๋๋ค. ๊ถํ์ ํ์ธํ์ธ์."
if not pdf_files:
logger.warning(f"'{self.pdf_directory}' ํด๋์ PDF ํ์ผ์ด ์์ต๋๋ค.")
return f"'{self.pdf_directory}' ํด๋์ PDF ํ์ผ์ด ์์ต๋๋ค."
logger.info(f"๋ฐ๊ฒฌ๋ PDF ํ์ผ: {len(pdf_files)}๊ฐ")
# ํด๋ ๋ด PDF ํ์ผ ์ฒ๋ฆฌ
new_files = []
updated_files = []
cached_files = []
failed_files = []
all_chunks = []
for file_path in pdf_files:
try:
if self._is_file_processed(file_path):
# ์บ์์์ ์ฒญํฌ ๋ก๋
try:
chunks = self._load_chunks(file_path)
all_chunks.extend(chunks)
cached_files.append(file_path)
self.processed_files.append(os.path.basename(file_path))
except Exception as e:
logger.error(f"์บ์๋ ์ฒญํฌ ๋ก๋ ์คํจ: {e}")
# ํ์ผ์ ๋ค์ ์ฒ๋ฆฌ
logger.info(f"์บ์ ์คํจ๋ก ํ์ผ ์ฌ์ฒ๋ฆฌ: {file_path}")
chunks = self._process_pdf_file(file_path)
if chunks:
self._save_chunks(file_path, chunks)
all_chunks.extend(chunks)
updated_files.append(file_path)
self.processed_files.append(os.path.basename(file_path))
else:
failed_files.append(file_path)
else:
# ์ ํ์ผ ๋๋ ๋ณ๊ฒฝ๋ ํ์ผ ์ฒ๋ฆฌ
logger.info(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:
logger.warning(f"'{file_path}' ์ฒ๋ฆฌ ์คํจ: ์ถ์ถ๋ ์ฒญํฌ ์์")
failed_files.append(file_path)
except Exception as e:
logger.error(f"'{file_path}' ์ฒ๋ฆฌ ์ค ์ค๋ฅ: {e}", exc_info=True)
failed_files.append(file_path)
except Exception as e:
logger.error(f"'{file_path}' ํ์ผ ์ฒ๋ฆฌ ๋ฃจํ ์ค ์ค๋ฅ: {e}", exc_info=True)
failed_files.append(file_path)
# ๋ชจ๋ ์ฒญํฌ ์ ์ฅ
self.documents = all_chunks
processing_time = time.time() - start_time
logger.info(f"๋ฌธ์ ์ฒ๋ฆฌ ์๋ฃ: {len(all_chunks)}๊ฐ ์ฒญํฌ, {processing_time:.2f}์ด")
# ๋ฒกํฐ ์ธ๋ฑ์ค ์ฒ๋ฆฌ
try:
self._process_vector_index(new_files, updated_files)
except Exception as e:
logger.error(f"๋ฒกํฐ ์ธ๋ฑ์ค ์ฒ๋ฆฌ ์คํจ: {e}", exc_info=True)
return f"๋ฌธ์๋ ์ฒ๋ฆฌ๋์์ผ๋ ๋ฒกํฐ ์ธ๋ฑ์ค ์์ฑ์ ์คํจํ์ต๋๋ค: {str(e)}"
# RAG ์ฒด์ธ ์ด๊ธฐํ
if RAG_CHAIN_AVAILABLE:
try:
logger.info("RAGChain์ผ๋ก ์ด๊ธฐํ๋ฅผ ์๋ํฉ๋๋ค.")
self.rag_chain = RAGChain(self.vector_store)
self.is_initialized = True
logger.info("RAG ์ฒด์ธ ์ด๊ธฐํ ์ฑ๊ณต")
except Exception as e:
logger.error(f"RAG ์ฒด์ธ ์ด๊ธฐํ ์คํจ: {e}", exc_info=True)
# FallbackRAGChain์ผ๋ก ๋์ฒด ์๋
try:
logger.info("FallbackRAGChain์ผ๋ก ๋์ฒดํฉ๋๋ค...")
from fallback_rag_chain import FallbackRAGChain
self.rag_chain = FallbackRAGChain(self.vector_store)
self.is_initialized = True
logger.info("ํด๋ฐฑ RAG ์ฒด์ธ ์ด๊ธฐํ ์ฑ๊ณต")
except Exception as fallback_e:
logger.error(f"ํด๋ฐฑ RAG ์ฒด์ธ ์ด๊ธฐํ ์คํจ: {fallback_e}", exc_info=True)
# SimpleRAGChain ์๋ (์ตํ์ ์๋จ)
try:
logger.info("SimpleRAGChain์ผ๋ก ๋์ฒดํฉ๋๋ค...")
from simple_rag_chain import SimpleRAGChain
# API ์ ๋ณด ๊ฐ์ ธ์ค๊ธฐ
try:
from config import DEEPSEEK_API_KEY, DEEPSEEK_MODEL, DEEPSEEK_ENDPOINT
logger.info(f"์ค์ ํ์ผ์์ DeepSeek API ์ ๋ณด๋ฅผ ๋ก๋ํ์ต๋๋ค: ๋ชจ๋ธ={DEEPSEEK_MODEL}")
except ImportError:
# ์ค์ ํ์ผ์์ ๊ฐ์ ธ์ฌ ์ ์๋ ๊ฒฝ์ฐ ํ๊ฒฝ ๋ณ์ ํ์ธ
DEEPSEEK_API_KEY = os.environ.get("DEEPSEEK_API_KEY", "")
DEEPSEEK_MODEL = os.environ.get("DEEPSEEK_MODEL", "deepseek-chat")
DEEPSEEK_ENDPOINT = os.environ.get("DEEPSEEK_ENDPOINT",
"https://api.deepseek.com/v1/chat/completions")
logger.info(f"ํ๊ฒฝ ๋ณ์์์ DeepSeek API ์ ๋ณด๋ฅผ ๋ก๋ํ์ต๋๋ค: ๋ชจ๋ธ={DEEPSEEK_MODEL}")
# SimpleRAGChain ์ด๊ธฐํ ์๋
self.rag_chain = SimpleRAGChain(self.vector_store)
self.is_initialized = True
logger.info("SimpleRAGChain ์ด๊ธฐํ ์ฑ๊ณต")
except Exception as simple_e:
logger.error(f"๋ชจ๋ RAG ์ฒด์ธ ์ด๊ธฐํ ์คํจ: {simple_e}", exc_info=True)
return f"๋ฌธ์์ ๋ฒกํฐ ์ธ๋ฑ์ค๋ ์ฒ๋ฆฌ๋์์ผ๋ RAG ์ฒด์ธ ์ด๊ธฐํ์ ์คํจํ์ต๋๋ค: {str(e)}"
else:
# RAGChain์ ์ฌ์ฉํ ์ ์๋ ๊ฒฝ์ฐ
try:
logger.info("๊ธฐ๋ณธ RAG Chain์ ์ฌ์ฉํ ์ ์์ด ๋์ฒด ๋ฒ์ ์ ์๋ํฉ๋๋ค...")
# FallbackRAGChain ์๋
try:
from fallback_rag_chain import FallbackRAGChain
self.rag_chain = FallbackRAGChain(self.vector_store)
self.is_initialized = True
logger.info("ํด๋ฐฑ RAG ์ฒด์ธ ์ด๊ธฐํ ์ฑ๊ณต")
except Exception as fallback_e:
logger.error(f"ํด๋ฐฑ RAG ์ฒด์ธ ์ด๊ธฐํ ์คํจ: {fallback_e}", exc_info=True)
# SimpleRAGChain ์๋ (์ตํ์ ์๋จ)
try:
from simple_rag_chain import SimpleRAGChain
self.rag_chain = SimpleRAGChain(self.vector_store)
self.is_initialized = True
logger.info("SimpleRAGChain ์ด๊ธฐํ ์ฑ๊ณต")
except Exception as simple_e:
logger.error(f"๋ชจ๋ RAG ์ฒด์ธ ์ด๊ธฐํ ์คํจ: {simple_e}", exc_info=True)
return f"๋ฌธ์์ ๋ฒกํฐ ์ธ๋ฑ์ค๋ ์ฒ๋ฆฌ๋์์ผ๋ RAG ์ฒด์ธ ์ด๊ธฐํ์ ์คํจํ์ต๋๋ค"
except Exception as e:
logger.error(f"RAG ์ฒด์ธ ์ด๊ธฐํ ์คํจ: {e}", exc_info=True)
return f"๋ฌธ์์ ๋ฒกํฐ ์ธ๋ฑ์ค๋ ์ฒ๋ฆฌ๋์์ผ๋ RAG ์ฒด์ธ ์ด๊ธฐํ์ ์คํจํ์ต๋๋ค: {str(e)}"
# ์ฑ๊ณต ๋ฉ์์ง ์์ฑ
result_message = f"""๋ฌธ์ ์ฒ๋ฆฌ ์๋ฃ!
- ์ฒ๋ฆฌ๋ ํ์ผ: {len(pdf_files)}๊ฐ
- ์บ์๋ ํ์ผ: {len(cached_files)}๊ฐ
- ์ ํ์ผ: {len(new_files)}๊ฐ
- ์
๋ฐ์ดํธ๋ ํ์ผ: {len(updated_files)}๊ฐ
- ์คํจํ ํ์ผ: {len(failed_files)}๊ฐ
- ์ด ์ฒญํฌ ์: {len(all_chunks)}๊ฐ
- ์ฒ๋ฆฌ ์๊ฐ: {processing_time:.2f}์ด
์ด์ ์ง๋ฌธํ ์ค๋น๊ฐ ๋์์ต๋๋ค!"""
return result_message
except Exception as e:
error_message = f"๋ฌธ์ ์ฒ๋ฆฌ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
logger.error(error_message, exc_info=True)
return error_message
def _process_vector_index(self, new_files: List[str], updated_files: List[str]) -> None:
"""
๋ฒกํฐ ์ธ๋ฑ์ค ์ฒ๋ฆฌ
Args:
new_files: ์๋ก ์ถ๊ฐ๋ ํ์ผ ๋ชฉ๋ก
updated_files: ์
๋ฐ์ดํธ๋ ํ์ผ ๋ชฉ๋ก
"""
# ๋ฒกํฐ ์ธ๋ฑ์ค ์ ์ฅ ๊ฒฝ๋ก ํ์ธ
if os.path.exists(self.vector_index_dir) and any(os.listdir(self.vector_index_dir)):
# ๊ธฐ์กด ๋ฒกํฐ ์ธ๋ฑ์ค ๋ก๋
try:
logger.info("์ ์ฅ๋ ๋ฒกํฐ ์ธ๋ฑ์ค ๋ก๋ ์ค...")
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:
logger.info("๋ฒกํฐ ์ธ๋ฑ์ค ์
๋ฐ์ดํธ ์ค...")
self.vector_store.add_documents(self.documents)
logger.info("๋ฒกํฐ ์ธ๋ฑ์ค ๋ก๋ ์๋ฃ")
else:
logger.warning("๋ฒกํฐ ์ธ๋ฑ์ค๋ฅผ ๋ก๋ํ์ผ๋ ์ ํจํ์ง ์์, ์๋ก ์์ฑํฉ๋๋ค.")
self.vector_store.create_or_load(self.documents)
except Exception as e:
logger.error(f"๋ฒกํฐ ์ธ๋ฑ์ค ๋ก๋ ์คํจ, ์๋ก ์์ฑํฉ๋๋ค: {e}", exc_info=True)
# ์ ๋ฒกํฐ ์ธ๋ฑ์ค ์์ฑ
self.vector_store.create_or_load(self.documents)
else:
# ์ ๋ฒกํฐ ์ธ๋ฑ์ค ์์ฑ
logger.info("์ ๋ฒกํฐ ์ธ๋ฑ์ค ์์ฑ ์ค...")
self.vector_store.create_or_load(self.documents)
# ๋ฒกํฐ ์ธ๋ฑ์ค ์ ์ฅ
if self.vector_store and self.vector_store.vector_store is not None:
try:
logger.info(f"๋ฒกํฐ ์ธ๋ฑ์ค ์ ์ฅ ์ค: {self.vector_index_dir}")
save_result = self.vector_store.save_local(self.vector_index_dir)
logger.info(f"๋ฒกํฐ ์ธ๋ฑ์ค ์ ์ฅ ์๋ฃ: {self.vector_index_dir}")
except Exception as e:
logger.error(f"๋ฒกํฐ ์ธ๋ฑ์ค ์ ์ฅ ์คํจ: {e}", exc_info=True)
raise VectorStoreError(f"๋ฒกํฐ ์ธ๋ฑ์ค ์ ์ฅ ์คํจ: {str(e)}")
else:
logger.warning("๋ฒกํฐ ์ธ๋ฑ์ค๊ฐ ์ด๊ธฐํ๋์ง ์์ ์ ์ฅํ์ง ์์ต๋๋ค.")
def reset_cache(self) -> str:
"""
์บ์ ์ด๊ธฐํ
Returns:
๊ฒฐ๊ณผ ๋ฉ์์ง
"""
try:
# ์ฒญํฌ ํ์ผ ์ญ์
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)
logger.info("์ฒญํฌ ์บ์ ํ์ผ ์ญ์ ์๋ฃ")
except Exception as e:
logger.error(f"์ฒญํฌ ํ์ผ ์ญ์ ์ค ์ค๋ฅ: {e}")
return f"์ฒญํฌ ํ์ผ ์ญ์ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
# ์ธ๋ฑ์ค ์ด๊ธฐํ
self.file_index = {}
try:
self._save_file_index()
logger.info("ํ์ผ ์ธ๋ฑ์ค ์ด๊ธฐํ ์๋ฃ")
except Exception as e:
logger.error(f"์ธ๋ฑ์ค ํ์ผ ์ด๊ธฐํ ์ค ์ค๋ฅ: {e}")
return f"์ธ๋ฑ์ค ํ์ผ ์ด๊ธฐํ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
# ๋ฒกํฐ ์ธ๋ฑ์ค ์ญ์
try:
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)
logger.info("๋ฒกํฐ ์ธ๋ฑ์ค ํ์ผ ์ญ์ ์๋ฃ")
except Exception as e:
logger.error(f"๋ฒกํฐ ์ธ๋ฑ์ค ํ์ผ ์ญ์ ์ค ์ค๋ฅ: {e}")
return f"๋ฒกํฐ ์ธ๋ฑ์ค ํ์ผ ์ญ์ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
self.documents = []
self.processed_files = []
self.is_initialized = False
logger.info("์บ์ ์ด๊ธฐํ ์๋ฃ")
return "์บ์๊ฐ ์ด๊ธฐํ๋์์ต๋๋ค. ๋ค์ ์คํ ์ ๋ชจ๋ ๋ฌธ์๊ฐ ๋ค์ ์ฒ๋ฆฌ๋ฉ๋๋ค."
except Exception as e:
error_msg = f"์บ์ ์ด๊ธฐํ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
logger.error(error_msg, exc_info=True)
return error_msg
def process_query(self, query: str, chat_history: List[Tuple[str, str]]) -> Tuple[str, List[Tuple[str, str]]]:
"""
์ฌ์ฉ์ ์ฟผ๋ฆฌ ์ฒ๋ฆฌ
Args:
query: ์ฌ์ฉ์ ์ง๋ฌธ
chat_history: ๋ํ ๊ธฐ๋ก
Returns:
์๋ต ๋ฐ ์
๋ฐ์ดํธ๋ ๋ํ ๊ธฐ๋ก
"""
if not query or not query.strip():
response = "์ง๋ฌธ์ด ๋น์ด ์์ต๋๋ค. ์ง๋ฌธ์ ์
๋ ฅํด ์ฃผ์ธ์."
chat_history.append((query, response))
return "", chat_history
if not self.is_initialized:
response = "๋ฌธ์ ๋ก๋๊ฐ ์ด๊ธฐํ๋์ง ์์์ต๋๋ค. ์๋ ๋ก๋๋ฅผ ์๋ํฉ๋๋ค."
chat_history.append((query, response))
# ์๋ ๋ก๋ ์๋
try:
init_result = self.auto_process_documents()
if not self.is_initialized:
response = f"๋ฌธ์๋ฅผ ๋ก๋ํ ์ ์์ต๋๋ค. 'documents' ํด๋์ PDF ํ์ผ์ด ์๋์ง ํ์ธํ์ธ์. ์ด๊ธฐํ ๊ฒฐ๊ณผ: {init_result}"
chat_history.append((query, response))
return "", chat_history
except Exception as e:
response = f"๋ฌธ์ ๋ก๋ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
logger.error(f"์๋ ๋ก๋ ์คํจ: {e}", exc_info=True)
chat_history.append((query, response))
return "", chat_history
try:
# RAG ์ฒด์ธ ์คํ ๋ฐ ์๋ต ์์ฑ
start_time = time.time()
logger.info(f"์ฟผ๋ฆฌ ์ฒ๋ฆฌ ์์: {query}")
# rag_chain์ด ์ด๊ธฐํ๋์๋์ง ํ์ธ
if not hasattr(self, 'rag_chain') or self.rag_chain is None:
raise RAGInitializationError("RAG ์ฒด์ธ์ด ์ด๊ธฐํ๋์ง ์์์ต๋๋ค")
# 1. ๋จผ์ ํ์ค RAG ์ฒด์ธ์ผ๋ก ์๋
try:
response = self.rag_chain.run(query)
logger.info(f"๊ธฐ๋ณธ RAG ์ฒด์ธ์ผ๋ก ์๋ต ์์ฑ ์ฑ๊ณต")
except Exception as rag_error:
logger.error(f"๊ธฐ๋ณธ RAG ์ฒด์ธ ์คํ ์คํจ: {rag_error}, ๋์ ์๋")
# 2. DeepSeek API ์ง์ ํธ์ถ ์๋ (RAG ์ฒด์ธ ์ฐํ)
try:
# DeepSeek API ์ ๋ณด ๊ฐ์ ธ์ค๊ธฐ
try:
from config import DEEPSEEK_API_KEY, DEEPSEEK_MODEL, DEEPSEEK_ENDPOINT
except ImportError:
# ์ค์ ๋ชจ๋์์ ๊ฐ์ ธ์ฌ ์ ์๋ ๊ฒฝ์ฐ ๊ธฐ๋ณธ๊ฐ ์ค์
DEEPSEEK_API_KEY = os.environ.get("DEEPSEEK_API_KEY", "")
DEEPSEEK_MODEL = os.environ.get("DEEPSEEK_MODEL", "deepseek-chat")
DEEPSEEK_ENDPOINT = os.environ.get("DEEPSEEK_ENDPOINT",
"https://api.deepseek.com/v1/chat/completions")
# ์ง์ API ํธ์ถ ํจ์ ์ ์ (์ธ๋ถ ๋ชจ๋ ์์กด์ฑ ์ ๊ฑฐ)
def direct_api_call(query, context, api_key, model_name, endpoint, max_retries=3, timeout=60):
"""DeepSeek API ์ง์ ํธ์ถ ํจ์"""
import requests
import json
import time
# ํ๋กฌํํธ ๊ธธ์ด ์ ํ
if len(context) > 6000:
context = context[:2500] + "\n...(์ค๋ต)...\n" + context[-2500:]
# ํ๋กฌํํธ ๊ตฌ์ฑ
prompt = f"""
๋ค์ ์ ๋ณด๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ์ง๋ฌธ์ ์ ํํ๊ฒ ๋ต๋ณํด์ฃผ์ธ์.
์ง๋ฌธ: {query}
์ฐธ๊ณ ์ ๋ณด:
{context}
์ฐธ๊ณ ์ ๋ณด์ ๋ต์ด ์์ผ๋ฉด ๋ฐ๋์ ๊ทธ ์ ๋ณด๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ๋ต๋ณํ์ธ์.
์ฐธ๊ณ ์ ๋ณด์ ๋ต์ด ์๋ ๊ฒฝ์ฐ์๋ ์ผ๋ฐ์ ์ธ ์ง์์ ํ์ฉํ์ฌ ๋ต๋ณํ ์ ์์ง๋ง, "์ ๊ณต๋ ๋ฌธ์์๋ ์ด ์ ๋ณด๊ฐ ์์ผ๋, ์ผ๋ฐ์ ์ผ๋ก๋..." ์์ผ๋ก ์์ํ์ธ์.
๋ต๋ณ์ ์ ํํ๊ณ ๊ฐ๊ฒฐํ๊ฒ ์ ๊ณตํ๋, ๊ฐ๋ฅํ ์ฐธ๊ณ ์ ๋ณด์์ ๊ทผ๊ฑฐ๋ฅผ ์ฐพ์ ์ค๋ช
ํด์ฃผ์ธ์.
์ฐธ๊ณ ์ ๋ณด์ ์ถ์ฒ๋ ํจ๊ป ์๋ ค์ฃผ์ธ์.
"""
# API ์์ฒญ ์๋
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
payload = {
"model": model_name,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.3,
"max_tokens": 1000
}
# ์ฌ์๋ ๋ก์ง
retry_delay = 1.0
for attempt in range(max_retries):
try:
logger.info(f"DeepSeek API ์ง์ ํธ์ถ ์๋ ({attempt + 1}/{max_retries})...")
response = requests.post(
endpoint,
headers=headers,
json=payload,
timeout=timeout
)
if response.status_code == 200:
result = response.json()
content = result.get("choices", [{}])[0].get("message", {}).get("content", "")
logger.info(f"DeepSeek API ์ง์ ํธ์ถ ์ฑ๊ณต")
return content
else:
logger.warning(f"API ์ค๋ฅ: ์ํ ์ฝ๋ {response.status_code}")
# ์์ฒญ ํ๋์ธ ๊ฒฝ์ฐ ๋ ์ค๋ ๋๊ธฐ
if response.status_code == 429:
retry_delay = min(retry_delay * 3, 15)
else:
retry_delay = min(retry_delay * 2, 10)
if attempt < max_retries - 1:
logger.info(f"{retry_delay}์ด ํ ์ฌ์๋...")
time.sleep(retry_delay)
except Exception as e:
logger.error(f"API ํธ์ถ ์ค๋ฅ: {e}")
if attempt < max_retries - 1:
logger.info(f"{retry_delay}์ด ํ ์ฌ์๋...")
time.sleep(retry_delay)
retry_delay = min(retry_delay * 2, 10)
# ๋ชจ๋ ์๋ ์คํจ
raise Exception("์ต๋ ์ฌ์๋ ํ์ ์ด๊ณผ")
# ๋ฒกํฐ ๊ฒ์ ์ํ
if self.vector_store and hasattr(self.vector_store, "similarity_search"):
logger.info("๋ฒกํฐ ๊ฒ์ ์ํ...")
docs = self.vector_store.similarity_search(query, k=5)
# ๊ฒ์ ๊ฒฐ๊ณผ ์ปจํ
์คํธ ๊ตฌ์ฑ
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")
context = "\n".join(context_parts)
# ์ง์ API ํธ์ถ
logger.info("DeepSeek API ์ง์ ํธ์ถ ์๋...")
response = direct_api_call(
query,
context,
DEEPSEEK_API_KEY,
DEEPSEEK_MODEL,
DEEPSEEK_ENDPOINT,
max_retries=3,
timeout=120
)
logger.info("DeepSeek API ์ง์ ํธ์ถ ์ฑ๊ณต")
else:
raise Exception("๋ฒกํฐ ์คํ ์ด๊ฐ ์ด๊ธฐํ๋์ง ์์์ต๋๋ค")
except Exception as direct_api_error:
logger.error(f"DeepSeek API ์ง์ ํธ์ถ ์คํจ: {direct_api_error}, ๊ฒ์ ๊ฒฐ๊ณผ ๋ฐํ")
# 3. ๊ฒ์ ๊ฒฐ๊ณผ๋ง์ด๋ผ๋ ๋ฐํ
try:
# ๋ฒกํฐ ๊ฒ์ ์ํ
if self.vector_store and hasattr(self.vector_store, "similarity_search"):
docs = self.vector_store.similarity_search(query, k=5)
# ๊ฒ์ ๊ฒฐ๊ณผ ์ปจํ
์คํธ ๊ตฌ์ฑ
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")
context = "\n".join(context_parts)
# ๊ฐ๋จํ ์๋ต ์์ฑ
predefined_answers = {
"๋ํ๋ฏผ๊ตญ์ ์๋": "๋ํ๋ฏผ๊ตญ์ ์๋๋ ์์ธ์
๋๋ค.",
"์๋": "๋ํ๋ฏผ๊ตญ์ ์๋๋ ์์ธ์
๋๋ค.",
"๋๊ตฌ์ผ": "์ ๋ RAG ๊ธฐ๋ฐ ์ง์์๋ต ์์คํ
์
๋๋ค. ๋ฌธ์๋ฅผ ๊ฒ์ํ๊ณ ๊ด๋ จ ์ ๋ณด๋ฅผ ์ฐพ์๋๋ฆฝ๋๋ค.",
"์๋
": "์๋
ํ์ธ์! ๋ฌด์์ ๋์๋๋ฆด๊น์?",
"๋ญํด": "์ฌ์ฉ์์ ์ง๋ฌธ์ ๋ต๋ณํ๊ธฐ ์ํด ๋ฌธ์๋ฅผ ๊ฒ์ํ๊ณ ์์ต๋๋ค. ๋ฌด์์ ์๋ ค๋๋ฆด๊น์?"
}
# ์ง๋ฌธ์ ๋ง๋ ๋ฏธ๋ฆฌ ์ ์๋ ์๋ต์ด ์๋์ง ํ์ธ
for key, answer in predefined_answers.items():
if key in query.lower():
response = answer
logger.info(f"๋ฏธ๋ฆฌ ์ ์๋ ์๋ต ์ ๊ณต: {key}")
break
else:
# ๋ฏธ๋ฆฌ ์ ์๋ ์๋ต์ด ์์ผ๋ฉด ๊ฒ์ ๊ฒฐ๊ณผ๋ง ํ์
response = f"""
API ์๋ฒ ์ฐ๊ฒฐ์ ๋ฌธ์ ๊ฐ ์์ด ๊ฒ์ ๊ฒฐ๊ณผ๋ง ํ์ํฉ๋๋ค.
์ง๋ฌธ: {query}
๊ฒ์๋ ๊ด๋ จ ๋ฌธ์:
{context}
[์ฐธ๊ณ ] API ์ฐ๊ฒฐ ๋ฌธ์ ๋ก ์ธํด ์๋ ์์ฝ์ด ์ ๊ณต๋์ง ์์ต๋๋ค. ๋ค์ ์๋ํ๊ฑฐ๋ ๋ค๋ฅธ ์ง๋ฌธ์ ํด๋ณด์ธ์.
"""
logger.info("๊ฒ์ ๊ฒฐ๊ณผ๋ง ํ์")
else:
response = f"API ์ฐ๊ฒฐ ๋ฐ ๋ฒกํฐ ๊ฒ์์ ๋ชจ๋ ์คํจํ์ต๋๋ค. ์์คํ
๊ด๋ฆฌ์์๊ฒ ๋ฌธ์ํ์ธ์."
except Exception as fallback_error:
logger.error(f"์ต์ข
ํด๋ฐฑ ์๋ต ์์ฑ ์คํจ: {fallback_error}")
# 4. ์ตํ์ ๋ฐฉ๋ฒ: ์ค๋ฅ ๋ฉ์์ง๋ฅผ ์๋ต์ผ๋ก ๋ฐํ
if "Connection error" in str(rag_error) or "timeout" in str(rag_error).lower():
response = f"""
API ์๋ฒ ์ฐ๊ฒฐ์ ๋ฌธ์ ๊ฐ ์์ต๋๋ค. ์ ์ ํ ๋ค์ ์๋ํด์ฃผ์ธ์.
์ง๋ฌธ: {query}
[์ฐธ๊ณ ] ํ์ฌ DeepSeek API ์๋ฒ์์ ์ฐ๊ฒฐ์ด ์ํํ์ง ์์ต๋๋ค. ์ด๋ก ์ธํด ์ง๋ฌธ์ ๋ํ ์๋ต์ ์ ๊ณตํ ์ ์์ต๋๋ค.
"""
else:
response = f"์ฟผ๋ฆฌ ์ฒ๋ฆฌ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค: {str(rag_error)}"
end_time = time.time()
query_time = end_time - start_time
logger.info(f"์ฟผ๋ฆฌ ์ฒ๋ฆฌ ์๋ฃ: {query_time:.2f}์ด")
chat_history.append((query, response))
return "", chat_history
except RAGInitializationError as e:
error_msg = f"RAG ์์คํ
์ด๊ธฐํ ์ค๋ฅ: {str(e)}. 'documents' ํด๋์ PDF ํ์ผ์ด ์๋์ง ํ์ธํ๊ณ , ์ฌ์์ํด ๋ณด์ธ์."
logger.error(f"์ฟผ๋ฆฌ ์ฒ๋ฆฌ ์ค RAG ์ด๊ธฐํ ์ค๋ฅ: {e}", exc_info=True)
chat_history.append((query, error_msg))
return "", chat_history
except (VectorStoreError, DocumentProcessingError) as e:
error_msg = f"๋ฌธ์ ์ฒ๋ฆฌ ์์คํ
์ค๋ฅ: {str(e)}. ๋ฌธ์ ํ์์ด ์ฌ๋ฐ๋ฅธ์ง ํ์ธํด ๋ณด์ธ์."
logger.error(f"์ฟผ๋ฆฌ ์ฒ๋ฆฌ ์ค ๋ฌธ์/๋ฒกํฐ ์คํ ์ด ์ค๋ฅ: {e}", exc_info=True)
chat_history.append((query, error_msg))
return "", chat_history
except Exception as e:
error_msg = f"์ฟผ๋ฆฌ ์ฒ๋ฆฌ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
logger.error(f"์ฟผ๋ฆฌ ์ฒ๋ฆฌ ์ค ์์์น ๋ชปํ ์ค๋ฅ: {e}", exc_info=True)
chat_history.append((query, error_msg))
return "", chat_history
def launch_app(self) -> None:
"""
Gradio ์ฑ ์คํ
"""
try:
import gradio as gr
except ImportError:
logger.error("Gradio ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค. pip install gradio๋ก ์ค์นํ์ธ์.")
print("Gradio ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค. pip install gradio๋ก ์ค์นํ์ธ์.")
return
# ๋ด๋ถ ํจ์๋ค์ด ํ์ฌ ์ธ์คํด์ค(self)์ ์ ๊ทผํ ์ ์๋๋ก ํด๋ก์ ๋ณ์๋ก ์ ์
app_instance = self
try:
with gr.Blocks(title="PDF ๋ฌธ์ ๊ธฐ๋ฐ RAG ์ฑ๋ด") as app:
gr.Markdown("# PDF ๋ฌธ์ ๊ธฐ๋ฐ RAG ์ฑ๋ด")
gr.Markdown(f"* ์ฌ์ฉ ์ค์ธ LLM ๋ชจ๋ธ: **{LLM_MODEL}**")
# ์ฌ๊ธฐ๋ฅผ ์์ : ์ค์ ๊ฒฝ๋ก ํ์
actual_pdf_dir = self.pdf_directory.replace('\\', '\\\\') if os.name == 'nt' else self.pdf_directory
gr.Markdown(f"* PDF ๋ฌธ์ ํด๋: **{actual_pdf_dir}**")
with gr.Row():
with gr.Column(scale=1):
# ๋ฌธ์ ์ํ ์น์
status_box = gr.Textbox(
label="๋ฌธ์ ์ฒ๋ฆฌ ์ํ",
value=self._get_status_message(),
lines=5,
interactive=False
)
# ์บ์ ๊ด๋ฆฌ ๋ฒํผ
refresh_button = gr.Button("๋ฌธ์ ์๋ก ์ฝ๊ธฐ", variant="primary")
reset_button = gr.Button("์บ์ ์ด๊ธฐํ", variant="stop")
# ์ํ ๋ฐ ์ค๋ฅ ํ์
status_info = gr.Markdown(
value=f"์์คํ
์ํ: {'์ด๊ธฐํ๋จ' if self.is_initialized else '์ด๊ธฐํ๋์ง ์์'}"
)
# ์ฒ๋ฆฌ๋ ํ์ผ ์ ๋ณด
with gr.Accordion("์บ์ ์ธ๋ถ ์ ๋ณด", open=False):
cache_info = gr.Textbox(
label="์บ์๋ ํ์ผ ์ ๋ณด",
value=self._get_cache_info(),
lines=5,
interactive=False
)
with gr.Column(scale=2):
# ์ฑํ
์ธํฐํ์ด์ค
chatbot = gr.Chatbot(
label="๋ํ ๋ด์ฉ",
bubble_full_width=False,
height=500,
show_copy_button=True
)
# ์์ฑ ๋
น์ UI ์ถ๊ฐ
with gr.Row():
with gr.Column(scale=4):
# ์ง๋ฌธ ์
๋ ฅ๊ณผ ์ ์ก ๋ฒํผ
query_box = gr.Textbox(
label="์ง๋ฌธ",
placeholder="์ฒ๋ฆฌ๋ ๋ฌธ์ ๋ด์ฉ์ ๋ํด ์ง๋ฌธํ์ธ์...",
lines=2
)
with gr.Column(scale=1):
# ์์ฑ ๋
น์ ์ปดํฌ๋ํธ
audio_input = gr.Audio(
sources=["microphone"],
type="numpy",
label="์์ฑ์ผ๋ก ์ง๋ฌธํ๊ธฐ"
)
with gr.Row():
submit_btn = gr.Button("์ ์ก", variant="primary")
clear_chat_button = gr.Button("๋ํ ์ด๊ธฐํ")
# ์์ฑ ์ธ์ ์ฒ๋ฆฌ ํจ์
# app.py ๋ด process_audio ํจ์ ๋ณด๊ฐ
# Gradio ์ฑ ๋ด์ ์๋ ์์ฑ ์ธ์ ์ฒ๋ฆฌ ํจ์ (์๋ณธ)
def process_audio(audio):
logger.info("์์ฑ ์ธ์ ์ฒ๋ฆฌ ์์...")
try:
from clova_stt import ClovaSTT
import numpy as np
import soundfile as sf
import tempfile
import os
if audio is None:
return "์์ฑ์ด ๋
น์๋์ง ์์์ต๋๋ค."
# ์ค๋์ค ๋ฐ์ดํฐ๋ฅผ ์์ ํ์ผ๋ก ์ ์ฅ
sr, y = audio
logger.info(f"์ค๋์ค ๋
น์ ๋ฐ์ดํฐ ์์ : ์ํ๋ ์ดํธ={sr}Hz, ๊ธธ์ด={len(y)}์ํ")
if len(y) / sr < 1.0:
return "๋
น์๋ ์์ฑ์ด ๋๋ฌด ์งง์ต๋๋ค. ๋ค์ ์๋ํด์ฃผ์ธ์."
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
temp_path = temp_file.name
sf.write(temp_path, y, sr, format="WAV")
logger.info(f"์์ WAV ํ์ผ ์ ์ฅ๋จ: {temp_path}")
# ์์ฑ ์ธ์ ์คํ
stt_client = ClovaSTT()
with open(temp_path, "rb") as f:
audio_bytes = f.read()
result = stt_client.recognize(audio_bytes)
# ์์ ํ์ผ ์ญ์
try:
os.unlink(temp_path)
logger.info("์์ ์ค๋์ค ํ์ผ ์ญ์ ๋จ")
except Exception as e:
logger.warning(f"์์ ํ์ผ ์ญ์ ์คํจ: {e}")
if result["success"]:
recognized_text = result["text"]
logger.info(f"์์ฑ์ธ์ ์ฑ๊ณต: {recognized_text}")
return recognized_text
else:
error_msg = f"์์ฑ ์ธ์ ์คํจ: {result.get('error', '์ ์ ์๋ ์ค๋ฅ')}"
logger.error(error_msg)
return error_msg
except ImportError as e:
logger.error(f"ํ์ํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ๋๋ฝ: {e}")
return "์์ฑ์ธ์์ ํ์ํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๊ฐ ์ค์น๋์ง ์์์ต๋๋ค. pip install soundfile numpy requests๋ฅผ ์คํํด์ฃผ์ธ์."
except Exception as e:
logger.error(f"์์ฑ ์ฒ๋ฆฌ ์ค ์ค๋ฅ ๋ฐ์: {e}", exc_info=True)
return f"์์ฑ ์ฒ๋ฆฌ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}"
# ์๋ก ์ถ๊ฐํ process_audio_and_submit ํจ์
def process_audio_and_submit(audio, chat_history):
"""
๋
น์ ์ ์ง ์ ์์ฑ ์ธ์ ํ ์๋์ผ๋ก ์ง๋ฌธ์ ์ฒ๋ฆฌํ๋ ํจ์.
์
๋ ฅ:
- audio: ๋
น์ ๋ฐ์ดํฐ (gr.Audio์ ๊ฐ)
- chat_history: ํ์ฌ ๋ํ ๊ธฐ๋ก (gr.Chatbot์ ๊ฐ)
์ถ๋ ฅ:
- query_box: ๋น ๋ฌธ์์ด (์ง๋ฌธ ์
๋ ฅ๋ ์ด๊ธฐํ)
- chatbot: ์
๋ฐ์ดํธ๋ ๋ํ ๊ธฐ๋ก
"""
recognized_text = process_audio(audio)
# ์์ฑ ์ธ์ ๊ฒฐ๊ณผ๊ฐ ์ค๋ฅ ๋ฉ์์ง์ธ ๊ฒฝ์ฐ ๊ทธ๋๋ก ๋ฐํ
if not recognized_text or recognized_text.startswith("์์ฑ ์ธ์ ์คํจ") or recognized_text.startswith(
"์์ฑ ์ฒ๋ฆฌ ์ค ์ค๋ฅ"):
return recognized_text, chat_history
# ์ธ์๋ ํ
์คํธ๋ฅผ ์ฌ์ฉํ์ฌ ์ง๋ฌธ ์ฒ๋ฆฌ
return app_instance.process_query(recognized_text, chat_history)
# ๊ธฐ์กด update_ui_after_refresh ํจ์ ์์ (self ๋์ app_instance ์ฌ์ฉ)
def update_ui_after_refresh(result):
return (
result, # ์ํ ๋ฉ์์ง
app_instance._get_status_message(), # ์ํ ๋ฐ์ค ์
๋ฐ์ดํธ
f"์์คํ
์ํ: {'์ด๊ธฐํ๋จ' if app_instance.is_initialized else '์ด๊ธฐํ๋์ง ์์'}", # ์ํ ์ ๋ณด ์
๋ฐ์ดํธ
app_instance._get_cache_info() # ์บ์ ์ ๋ณด ์
๋ฐ์ดํธ
)
# --- Gradio ์ด๋ฒคํธ ํธ๋ค๋ฌ ์ค์ ---
# ์: audio_input ์ปดํฌ๋ํธ์ stop_recording ์ด๋ฒคํธ๋ฅผ ์๋์ ๊ฐ์ด ์์
audio_input.stop_recording(
fn=process_audio_and_submit,
inputs=[audio_input, chatbot],
outputs=[query_box, chatbot]
)
# ์์ฑ ์ธ์ ๊ฒฐ๊ณผ๋ฅผ ์ง๋ฌธ ์์์ ์
๋ฐ์ดํธ
audio_input.stop_recording(
fn=process_audio,
inputs=[audio_input],
outputs=[query_box]
)
# ๋ฌธ์ ์๋ก ์ฝ๊ธฐ ๋ฒํผ
refresh_button.click(
fn=lambda: update_ui_after_refresh(self.auto_process_documents()),
inputs=[],
outputs=[status_box, status_box, status_info, cache_info]
)
# ์บ์ ์ด๊ธฐํ ๋ฒํผ
def reset_and_process():
reset_result = self.reset_cache()
process_result = self.auto_process_documents()
return update_ui_after_refresh(f"{reset_result}\n\n{process_result}")
reset_button.click(
fn=reset_and_process,
inputs=[],
outputs=[status_box, status_box, status_info, cache_info]
)
# ์ ์ก ๋ฒํผ ํด๋ฆญ ์ด๋ฒคํธ
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]
)
# ๋ํ ์ด๊ธฐํ ๋ฒํผ
clear_chat_button.click(
fn=lambda: [],
outputs=[chatbot]
)
# ์ฑ ์คํ
app.launch(share=False)
except Exception as e:
logger.error(f"Gradio ์ฑ ์คํ ์ค ์ค๋ฅ ๋ฐ์: {e}", exc_info=True)
print(f"Gradio ์ฑ ์คํ ์ค ์ค๋ฅ ๋ฐ์: {e}")
def _get_status_message(self) -> str:
"""
ํ์ฌ ์ฒ๋ฆฌ ์ํ ๋ฉ์์ง ์์ฑ
Returns:
์ํ ๋ฉ์์ง
"""
if not self.processed_files:
return "์ฒ๋ฆฌ๋ ๋ฌธ์๊ฐ ์์ต๋๋ค. '๋ฌธ์ ์๋ก ์ฝ๊ธฐ' ๋ฒํผ์ ํด๋ฆญํ์ธ์."
# DeepSeek API ์ํ ํ์ธ
from config import USE_DEEPSEEK, DEEPSEEK_API_KEY, DEEPSEEK_MODEL
model_info = ""
if USE_DEEPSEEK and DEEPSEEK_API_KEY:
# DeepSeek API ํ
์คํธ ์ํ
try:
# ํ
์คํธ ํจ์ ๊ฐ์ ธ์ค๊ธฐ ์๋
try:
from deepseek_utils import test_deepseek_api
# DeepSeek ์ค์ ๊ฐ์ ธ์ค๊ธฐ
from config import DEEPSEEK_ENDPOINT
# API ํ
์คํธ
test_result = test_deepseek_api(DEEPSEEK_API_KEY, DEEPSEEK_ENDPOINT, DEEPSEEK_MODEL)
if test_result["success"]:
model_info = f"\nDeepSeek API ์ํ: ์ ์ ({DEEPSEEK_MODEL})"
else:
model_info = f"\nDeepSeek API ์ํ: ์ค๋ฅ - {test_result['message']}"
except ImportError:
# ์ง์ ํ
์คํธ ์คํ
import requests
import json
# DeepSeek ์ค์ ๊ฐ์ ธ์ค๊ธฐ
from config import DEEPSEEK_ENDPOINT
# ํ
์คํธ์ฉ ๊ฐ๋จํ ํ๋กฌํํธ
test_prompt = "Hello, please respond with a short greeting."
# API ์์ฒญ ํค๋ ๋ฐ ๋ฐ์ดํฐ
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {DEEPSEEK_API_KEY}"
}
payload = {
"model": DEEPSEEK_MODEL,
"messages": [{"role": "user", "content": test_prompt}],
"temperature": 0.7,
"max_tokens": 50
}
# API ์์ฒญ ์ ์ก
try:
response = requests.post(
DEEPSEEK_ENDPOINT,
headers=headers,
data=json.dumps(payload),
timeout=5 # 5์ด ํ์์์ (UI ๋ฐ์์ฑ ์ ์ง)
)
# ์๋ต ํ์ธ
if response.status_code == 200:
model_info = f"\nDeepSeek API ์ํ: ์ ์ ({DEEPSEEK_MODEL})"
else:
error_message = response.text[:100]
model_info = f"\nDeepSeek API ์ํ: ์ค๋ฅ (์ํ ์ฝ๋: {response.status_code})"
except Exception as e:
model_info = f"\nDeepSeek API ์ํ: ์ฐ๊ฒฐ ์คํจ ({str(e)[:100]})"
except Exception as e:
model_info = f"\nDeepSeek API ์ํ ํ์ธ ์คํจ: {str(e)[:100]}"
return f"์ฒ๋ฆฌ๋ ๋ฌธ์ ({len(self.processed_files)}๊ฐ): {', '.join(self.processed_files)}{model_info}"
def _get_cache_info(self) -> str:
"""
์บ์ ์ธ๋ถ ์ ๋ณด ๋ฉ์์ง ์์ฑ
Returns:
์บ์ ์ ๋ณด ๋ฉ์์ง
"""
if not self.file_index:
return "์บ์๋ ํ์ผ์ด ์์ต๋๋ค."
file_info = ""
for file_path, info in self.file_index.items():
file_name = info.get('file_name', os.path.basename(file_path))
chunks_count = info.get('chunks_count', 0)
file_size = info.get('file_size', 0)
last_processed = info.get('last_processed', 0)
# ํ์ผ ํฌ๊ธฐ๋ฅผ ์ฌ๋์ด ์ฝ๊ธฐ ์ฌ์ด ํํ๋ก ๋ณํ
if file_size < 1024:
size_str = f"{file_size} bytes"
elif file_size < 1024 * 1024:
size_str = f"{file_size / 1024:.1f} KB"
else:
size_str = f"{file_size / (1024 * 1024):.1f} MB"
# ๋ง์ง๋ง ์ฒ๋ฆฌ ์๊ฐ์ ๋ ์ง/์๊ฐ ํ์์ผ๋ก ๋ณํ
if last_processed:
from datetime import datetime
last_time = datetime.fromtimestamp(last_processed).strftime('%Y-%m-%d %H:%M:%S')
else:
last_time = "์ ์ ์์"
file_info += f"- {file_name}: {chunks_count}๊ฐ ์ฒญํฌ, {size_str}, ๋ง์ง๋ง ์ฒ๋ฆฌ: {last_time}\n"
return file_info
if __name__ == "__main__":
app = AutoRAGChatApp()
app.launch_app() |