Spaces:
Sleeping
Sleeping
File size: 42,281 Bytes
64371be |
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 |
"""
RAG κ²μ μ±λ΄ μΉ μ ν리μΌμ΄μ
(μΈμ
μ€μ μμ μ μ© λ° μ€λ³΅ λΌμ°νΈ λ±λ‘ λ°©μ§)
"""
import os
import json
import logging
import tempfile
import threading
import datetime
from flask import Flask, request, jsonify, render_template, send_from_directory, session, redirect, url_for
from flask_cors import CORS
from werkzeug.utils import secure_filename
from dotenv import load_dotenv
from functools import wraps
# λ‘κ±° μ€μ
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.DEBUG # INFOμμ DEBUGλ‘ λ³κ²½νμ¬ λ μμΈν λ‘κ·Έ νμΈ
)
logger = logging.getLogger(__name__)
# νκ²½ λ³μ λ‘λ
load_dotenv()
# νκ²½ λ³μ λ‘λ μν νμΈ λ° λ‘κΉ
ADMIN_USERNAME = os.getenv('ADMIN_USERNAME')
ADMIN_PASSWORD = os.getenv('ADMIN_PASSWORD')
# μ₯μΉ μλ² URL νκ²½ λ³μ μΆκ°
DEVICE_SERVER_URL = os.getenv('DEVICE_SERVER_URL', 'http://localhost:5050')
logger.info(f"μ₯μΉ μλ² URL: {DEVICE_SERVER_URL}")
logger.info(f"==== νκ²½ λ³μ λ‘λ μν ====")
logger.info(f"ADMIN_USERNAME μ€μ μ¬λΆ: {ADMIN_USERNAME is not None}")
# λΉλ°λ²νΈλ λ‘λ μ¬λΆλ§ κΈ°λ‘ (보μ)
logger.info(f"ADMIN_PASSWORD μ€μ μ¬λΆ: {ADMIN_PASSWORD is not None}")
# νκ²½ λ³μκ° μμΌλ©΄ κΈ°λ³Έκ° μ€μ (κ°λ°μ©, λ°°ν¬ μ νκ²½ λ³μ μ€μ κΆμ₯)
if not ADMIN_USERNAME:
ADMIN_USERNAME = 'admin'
logger.warning("ADMIN_USERNAME νκ²½λ³μκ° μμ΄ κΈ°λ³Έκ° 'admin'μΌλ‘ μ€μ ν©λλ€.")
if not ADMIN_PASSWORD:
ADMIN_PASSWORD = 'rag12345'
logger.warning("ADMIN_PASSWORD νκ²½λ³μκ° μμ΄ κΈ°λ³Έκ° 'rag12345'λ‘ μ€μ ν©λλ€.")
class MockComponent: pass
# --- λ‘컬 λͺ¨λ μν¬νΈ ---
# μ€μ κ²½λ‘μ λ§κ² utils, retrieval ν΄λκ° μ‘΄μ¬ν΄μΌ ν©λλ€.
try:
from utils.vito_stt import VitoSTT
from utils.llm_interface import LLMInterface
from utils.document_processor import DocumentProcessor
from retrieval.vector_retriever import VectorRetriever
from retrieval.reranker import ReRanker
# μ₯μΉ λΌμ°νΈ λ±λ‘ ν¨μ μν¬νΈ
from app.app_device_routes import register_device_routes
except ImportError as e:
logger.error(f"λ‘컬 λͺ¨λ μν¬νΈ μ€ν¨: {e}. utils, retrieval, app ν¨ν€μ§κ° μ¬λ°λ₯Έ κ²½λ‘μ μλμ§ νμΈνμΈμ.")
# κ°λ°/ν
μ€νΈλ₯Ό μν΄ μμ ν΄λμ€/ν¨μ μ μ (μ€μ μ¬μ© μ μ κ±°)
VitoSTT = LLMInterface = DocumentProcessor = VectorRetriever = ReRanker = MockComponent
def register_device_routes(*args, **kwargs):
logger.warning("Mock register_device_routes ν¨μ νΈμΆλ¨.")
pass
# --- λ‘컬 λͺ¨λ μν¬νΈ λ ---
# Flask μ± μ΄κΈ°ν
app = Flask(__name__)
# CORS μ€μ - λͺ¨λ λλ©μΈμμμ μμ² νμ©
CORS(app, supports_credentials=True)
# μΈμ
μ€μ - κ³ μ λ μν¬λ¦Ώ ν€ μ¬μ© (μ€μ λ°°ν¬ μ νκ²½ λ³μ λ±μΌλ‘ κ΄λ¦¬ κΆμ₯)
app.secret_key = os.getenv('FLASK_SECRET_KEY', 'rag_chatbot_fixed_secret_key_12345') # νκ²½ λ³μ μ°μ μ¬μ©
# --- μΈμ
μΏ ν€ μ€μ μμ (νκΉ
νμ΄μ€ νκ²½ κ³ λ €) ---
# νκΉ
νμ΄μ€ μ€νμ΄μ€λ μΌλ°μ μΌλ‘ HTTPSλ‘ μλΉμ€λλ―λ‘ Secure=True μ€μ
app.config['SESSION_COOKIE_SECURE'] = True
app.config['SESSION_COOKIE_HTTPONLY'] = True # JavaScriptμμ μΏ ν€ μ κ·Ό λ°©μ§ (보μ κ°ν)
# SameSite='Lax'κ° λλΆλΆμ κ²½μ°μ λ μμ νκ³ νΈνμ±μ΄ μ’μ.
# λ§μ½ μ±μ΄ λ€λ₯Έ λλ©μΈμ iframe λ΄μμ μ€νλμ΄μΌ νλ€λ©΄ 'None'μΌλ‘ μ€μ ν΄μΌ ν¨.
# (λ¨, 'None'μΌλ‘ μ€μ μ λ°λμ Secure=Trueμ¬μΌ ν¨)
# λ‘κ·Έ λΆμ κ²°κ³Ό iframe νκ²½μΌλ‘ νμΈλμ΄ 'None'μΌλ‘ λ³κ²½
app.config['SESSION_COOKIE_SAMESITE'] = 'None' # <--- μ΄λ κ² λ³κ²½ν©λλ€.
app.config['SESSION_COOKIE_DOMAIN'] = None # νΉμ λλ©μΈ μ ν μμ
app.config['SESSION_COOKIE_PATH'] = '/' # μ± μ 체 κ²½λ‘μ μΏ ν€ μ μ©
app.config['PERMANENT_SESSION_LIFETIME'] = datetime.timedelta(days=1) # μΈμ
μ ν¨ μκ° μ¦κ°
# --- μΈμ
μΏ ν€ μ€μ λ ---
# μ΅λ νμΌ ν¬κΈ° μ€μ (10MB)
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024
# μ ν리μΌμ΄μ
νμΌ κΈ°μ€ μλ κ²½λ‘ μ€μ
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
app.config['UPLOAD_FOLDER'] = os.path.join(APP_ROOT, 'uploads')
app.config['DATA_FOLDER'] = os.path.join(APP_ROOT, '..', 'data')
app.config['INDEX_PATH'] = os.path.join(APP_ROOT, '..', 'data', 'index')
# νμν ν΄λ μμ±
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs(app.config['DATA_FOLDER'], exist_ok=True)
os.makedirs(app.config['INDEX_PATH'], exist_ok=True)
# νμ©λλ μ€λμ€/λ¬Έμ νμΌ νμ₯μ
ALLOWED_AUDIO_EXTENSIONS = {'mp3', 'wav', 'ogg', 'm4a'}
ALLOWED_DOC_EXTENSIONS = {'txt', 'md', 'pdf', 'docx', 'csv'}
# --- μ μ κ°μ²΄ μ΄κΈ°ν ---
try:
llm_interface = LLMInterface(default_llm="openai")
stt_client = VitoSTT()
except NameError:
logger.warning("LLM λλ STT μΈν°νμ΄μ€ μ΄κΈ°ν μ€ν¨. Mock κ°μ²΄λ₯Ό μ¬μ©ν©λλ€.")
llm_interface = MockComponent()
stt_client = MockComponent()
base_retriever = None
retriever = None
app_ready = False # μ± μ΄κΈ°ν μν νλκ·Έ
DEVICE_ROUTES_REGISTERED = False # μ₯μΉ λΌμ°νΈ λ±λ‘ μν νλκ·Έ
# --- μ μ κ°μ²΄ μ΄κΈ°ν λ ---
# --- μΈμ¦ λ°μ½λ μ΄ν° (μμ λ¨) ---
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
logger.info(f"----------- μΈμ¦ νμ νμ΄μ§ μ κ·Ό μλ: {request.path} -----------")
logger.info(f"νμ¬ νλΌμ€ν¬ μΈμ
κ°μ²΄: {session}")
logger.info(f"νμ¬ μΈμ
μν: logged_in={session.get('logged_in', False)}, username={session.get('username', 'None')}")
# λΈλΌμ°μ κ° λ³΄λΈ μ€μ μΏ ν€ νμΈ (λλ²κΉ
μ©)
logger.info(f"μμ²μ μΈμ
μΏ ν€ κ°: {request.cookies.get('session', 'None')}")
# API μμ²μ΄κ³ ν΄λΌμ΄μΈνΈμμ μ€λ κ²½μ° μΈμ¦ 무μ (μμ μ‘°μΉ)
# ---> μ£Όμ: μ΄ λΆλΆμ 보μ κ²ν ν μ€μ νκ²½μμλ μ κ±°νκ±°λ λ μμ ν λ°©μμΌλ‘ λ³κ²½ν΄μΌ ν μ μμ΅λλ€.
if request.path.startswith('/api/device/'):
logger.info(f"μ₯μΉ API μμ²: {request.path} - μΈμ¦ μ μΈ (μ£Όμ: μμ μ‘°μΉ)")
return f(*args, **kwargs)
# Flask μΈμ
μ 'logged_in' ν€κ° μλμ§ μ§μ νμΈ
if 'logged_in' not in session:
logger.warning(f"νλΌμ€ν¬ μΈμ
μ 'logged_in' μμ. λ‘κ·ΈμΈ νμ΄μ§λ‘ 리λλ μ
.")
# μλ μΏ ν€ νμΈ λ‘μ§ μ κ±°λ¨
return redirect(url_for('login', next=request.url)) # λ‘κ·ΈμΈ ν μλ νμ΄μ§λ‘ λμκ°λλ‘ next νλΌλ―Έν° μΆκ°
logger.info(f"μΈμ¦ μ±κ³΅: {session.get('username', 'unknown')} μ¬μ©μκ° {request.path} μ κ·Ό")
return f(*args, **kwargs)
return decorated_function
# --- μΈμ¦ λ°μ½λ μ΄ν° λ ---
# --- μ€λ₯ νΈλ€λ¬ μΆκ° ---
@app.errorhandler(404)
def not_found(e):
# ν΄λΌμ΄μΈνΈκ° JSONμ κΈ°λνλ API νΈμΆμΈ κ²½μ° JSON μλ΅
if request.path.startswith('/api/'):
return jsonify({"success": False, "error": "μμ²ν API μλν¬μΈνΈλ₯Ό μ°Ύμ μ μμ΅λλ€."}), 404
# μΌλ° μΉ νμ΄μ§ μμ²μΈ κ²½μ° HTML μλ΅
return "νμ΄μ§λ₯Ό μ°Ύμ μ μμ΅λλ€.", 404
@app.errorhandler(500)
def internal_error(e):
# ν΄λΌμ΄μΈνΈκ° JSONμ κΈ°λνλ API νΈμΆμΈ κ²½μ° JSON μλ΅
if request.path.startswith('/api/'):
return jsonify({"success": False, "error": "μλ² λ΄λΆ μ€λ₯κ° λ°μνμ΅λλ€."}), 500
# μΌλ° μΉ νμ΄μ§ μμ²μΈ κ²½μ° HTML μλ΅
return "μλ² μ€λ₯κ° λ°μνμ΅λλ€.", 500
# --- μ€λ₯ νΈλ€λ¬ λ ---
# --- μ₯μΉ κ΄λ ¨ λΌμ°νΈ λ±λ‘ (μμ λ¨: μ€λ³΅ λ°©μ§) ---
# μ μ νλκ·Έλ₯Ό μ¬μ©νμ¬ ν λ²λ§ λ±λ‘λλλ‘ ν¨
if not DEVICE_ROUTES_REGISTERED:
try:
# μν¬νΈλ register_device_routes ν¨μ μ¬μ©
# μΈμ¦ λ°μ½λ μ΄ν°(login_required)μ μλ² URL μ λ¬
register_device_routes(app, login_required, DEVICE_SERVER_URL)
DEVICE_ROUTES_REGISTERED = True # λ±λ‘ μ±κ³΅ μ νλκ·Έ μ€μ
logger.info("μ₯μΉ κ΄λ ¨ λΌμ°νΈ λ±λ‘ μλ£")
except NameError:
logger.error("register_device_routes ν¨μλ₯Ό μ°Ύμ μ μμ΅λλ€. app.app_device_routes λͺ¨λ νμΈ νμ.")
except Exception as e:
logger.error(f"μ₯μΉ κ΄λ ¨ λΌμ°νΈ λ±λ‘ μ€ν¨: {e}", exc_info=True)
else:
logger.info("μ₯μΉ κ΄λ ¨ λΌμ°νΈκ° μ΄λ―Έ λ±λ‘λμ΄ μμ΄ κ±΄λ<0xEB>λλλ€.")
# --- μ₯μΉ κ΄λ ¨ λΌμ°νΈ λ±λ‘ λ ---
# --- ν¬νΌ ν¨μ ---
def allowed_audio_file(filename):
"""νμΌμ΄ νμ©λ μ€λμ€ νμ₯μλ₯Ό κ°μ§λμ§ νμΈ"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_AUDIO_EXTENSIONS
def allowed_doc_file(filename):
"""νμΌμ΄ νμ©λ λ¬Έμ νμ₯μλ₯Ό κ°μ§λμ§ νμΈ"""
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_DOC_EXTENSIONS
# --- ν¬νΌ ν¨μ λ ---
# init_retriever ν¨μ λ΄λΆμ λ‘κΉ
μΆκ° μμ
# --- κ²μκΈ° μ΄κΈ°ν κ΄λ ¨ ν¨μ ---
def init_retriever():
"""κ²μκΈ° κ°μ²΄ μ΄κΈ°ν λλ λ‘λ"""
global base_retriever, retriever
index_path = app.config['INDEX_PATH']
data_path = app.config['DATA_FOLDER'] # data_path μ μ νμΈ
logger.info("--- init_retriever μμ ---")
# 1. κΈ°λ³Έ κ²μκΈ° λ‘λ λλ μ΄κΈ°ν
if os.path.exists(os.path.join(index_path, "documents.json")):
try:
logger.info(f"μΈλ±μ€ λ‘λ μλ: {index_path}")
base_retriever = VectorRetriever.load(index_path)
logger.info(f"μΈλ±μ€ λ‘λ μ±κ³΅. λ¬Έμ {len(getattr(base_retriever, 'documents', []))}κ°")
except Exception as e:
logger.error(f"μΈλ±μ€ λ‘λ μ€ν¨: {e}", exc_info=True)
logger.info("μ VectorRetriever μ΄κΈ°ν μλ...")
try:
base_retriever = VectorRetriever()
logger.info("μ VectorRetriever μ΄κΈ°ν μ±κ³΅.")
except Exception as e_init:
logger.error(f"μ VectorRetriever μ΄κΈ°ν μ€ν¨: {e_init}", exc_info=True)
base_retriever = None
else:
logger.info("μΈλ±μ€ νμΌ μμ. μ VectorRetriever μ΄κΈ°ν μλ...")
try:
base_retriever = VectorRetriever()
logger.info("μ VectorRetriever μ΄κΈ°ν μ±κ³΅.")
except Exception as e_init:
logger.error(f"μ VectorRetriever μ΄κΈ°ν μ€ν¨: {e_init}", exc_info=True)
base_retriever = None
if base_retriever is None:
logger.error("base_retriever μ΄κΈ°ν/λ‘λμ μ€ν¨νμ¬ init_retriever μ€λ¨.")
return None
# 2. λ°μ΄ν° ν΄λ λ¬Έμ λ‘λ (κΈ°λ³Έ κ²μκΈ°κ° λΉμ΄μμ λ)
needs_loading = (not hasattr(base_retriever, 'documents') or not getattr(base_retriever, 'documents', None)) # None μ²΄ν¬ μΆκ°
if needs_loading and os.path.exists(data_path):
logger.info(f"κΈ°λ³Έ κ²μκΈ°κ° λΉμ΄μμ΄ {data_path}μμ λ¬Έμ λ‘λ μλ...")
try:
docs = DocumentProcessor.load_documents_from_directory(
directory=data_path,
extensions=[".txt", ".md", ".csv"],
recursive=True
)
logger.info(f"{len(docs)}κ° λ¬Έμ λ‘λ μ±κ³΅.")
if docs and hasattr(base_retriever, 'add_documents'):
logger.info("κ²μκΈ°μ λ¬Έμ μΆκ° μλ...")
base_retriever.add_documents(docs)
logger.info("λ¬Έμ μΆκ° μλ£.")
if hasattr(base_retriever, 'save'):
logger.info(f"κ²μκΈ° μν μ μ₯ μλ: {index_path}")
try:
base_retriever.save(index_path)
logger.info("μΈλ±μ€ μ μ₯ μλ£.")
except Exception as e_save:
logger.error(f"μΈλ±μ€ μ μ₯ μ€ν¨: {e_save}", exc_info=True)
except Exception as e_load_add:
logger.error(f"DATA_FOLDER λ¬Έμ λ‘λ/μΆκ° μ€ μ€λ₯: {e_load_add}", exc_info=True)
# 3. μ¬μμν κ²μκΈ° μ΄κΈ°ν
logger.info("μ¬μμν κ²μκΈ° μ΄κΈ°ν μλ...")
try:
def custom_rerank_fn(query, results):
query_terms = set(query.lower().split())
for result in results:
if isinstance(result, dict) and "text" in result:
text = result["text"].lower()
term_freq = sum(1 for term in query_terms if term in text)
normalized_score = term_freq / (len(text.split()) + 1) * 10
result["rerank_score"] = result.get("score", 0) * 0.7 + normalized_score * 0.3
elif isinstance(result, dict):
result["rerank_score"] = result.get("score", 0)
results.sort(key=lambda x: x.get("rerank_score", 0) if isinstance(x, dict) else 0, reverse=True)
return results
# ReRanker ν΄λμ€ μ¬μ©
retriever = ReRanker(
base_retriever=base_retriever,
rerank_fn=custom_rerank_fn,
rerank_field="text"
)
logger.info("μ¬μμν κ²μκΈ° μ΄κΈ°ν μλ£.")
except Exception as e_rerank:
logger.error(f"μ¬μμν κ²μκΈ° μ΄κΈ°ν μ€ν¨: {e_rerank}", exc_info=True)
logger.warning("μ¬μμν μ€ν¨, κΈ°λ³Έ κ²μκΈ°λ₯Ό retrieverλ‘ μ¬μ©ν©λλ€.")
retriever = base_retriever # fallback
logger.info("--- init_retriever μ’
λ£ ---")
return retriever
def background_init():
"""λ°±κ·ΈλΌμ΄λμμ κ²μκΈ° μ΄κΈ°ν μν"""
global app_ready, retriever, base_retriever, llm_interface, stt_client
temp_app_ready = False # μμ μν νλκ·Έ
try:
logger.info("λ°±κ·ΈλΌμ΄λ μ΄κΈ°ν μμ...")
# 1. LLM, STT μΈν°νμ΄μ€ μ΄κΈ°ν (νμ μ)
if llm_interface is None or isinstance(llm_interface, MockComponent):
if 'LLMInterface' in globals() and LLMInterface != MockComponent:
llm_interface = LLMInterface(default_llm="openai")
logger.info("LLM μΈν°νμ΄μ€ μ΄κΈ°ν μλ£.")
else:
logger.warning("LLMInterface ν΄λμ€ μμ. Mock μ¬μ©.")
llm_interface = MockComponent() # Mock κ°μ²΄ 보μ₯
if stt_client is None or isinstance(stt_client, MockComponent):
if 'VitoSTT' in globals() and VitoSTT != MockComponent:
stt_client = VitoSTT()
logger.info("STT ν΄λΌμ΄μΈνΈ μ΄κΈ°ν μλ£.")
else:
logger.warning("VitoSTT ν΄λμ€ μμ. Mock μ¬μ©.")
stt_client = MockComponent() # Mock κ°μ²΄ 보μ₯
# 2. κ²μκΈ° μ΄κΈ°ν
if 'VectorRetriever' in globals() and VectorRetriever != MockComponent:
logger.info("μ€μ κ²μκΈ° μ΄κΈ°ν μλ...")
retriever = init_retriever()
if hasattr(retriever, 'base_retriever') and base_retriever is None:
base_retriever = retriever.base_retriever
elif base_retriever is None:
logger.warning("init_retriever ν base_retrieverκ° μ€μ λμ§ μμ. νμΈ νμ.")
if isinstance(retriever, VectorRetriever):
base_retriever = retriever
if retriever is not None and base_retriever is not None:
logger.info("κ²μκΈ° (Retriever, Base Retriever) μ΄κΈ°ν μ±κ³΅")
temp_app_ready = True
else:
logger.error("κ²μκΈ° μ΄κΈ°ν νμλ retriever λλ base_retrieverκ° Noneμ
λλ€.")
if base_retriever is None: base_retriever = MockComponent()
if retriever is None: retriever = MockComponent()
if not hasattr(retriever, 'search'): retriever.search = lambda query, **kwargs: []
if not hasattr(base_retriever, 'documents'): base_retriever.documents = []
temp_app_ready = True
else:
logger.warning("VectorRetriever ν΄λμ€ μμ. Mock κ²μκΈ° μ¬μ©.")
base_retriever = MockComponent()
retriever = MockComponent()
if not hasattr(retriever, 'search'): retriever.search = lambda query, **kwargs: []
if not hasattr(base_retriever, 'documents'): base_retriever.documents = []
temp_app_ready = True
logger.info(f"λ°±κ·ΈλΌμ΄λ μ΄κΈ°ν μλ£. μ΅μ’
μν: {'Ready' if temp_app_ready else 'Not Ready (Error during init)'}")
except Exception as e:
logger.error(f"μ± λ°±κ·ΈλΌμ΄λ μ΄κΈ°ν μ€ μ¬κ°ν μ€λ₯ λ°μ: {e}", exc_info=True)
if base_retriever is None: base_retriever = MockComponent()
if retriever is None: retriever = MockComponent()
if not hasattr(retriever, 'search'): retriever.search = lambda query, **kwargs: []
if not hasattr(base_retriever, 'documents'): base_retriever.documents = []
temp_app_ready = True
logger.warning("μ΄κΈ°ν μ€ μ€λ₯κ° λ°μνμ§λ§ Mock κ°μ²΄λ‘ λ체 ν μ± μ¬μ© κ°λ₯ μνλ‘ μ€μ .")
finally:
# μ΅μ’
μ μΌλ‘ app_ready μν μ
λ°μ΄νΈ
app_ready = temp_app_ready
# μ₯μΉ λΌμ°νΈ λ±λ‘ νΈμΆμ μ¬κΈ°μ μ κ±°λ¨ (λ©μΈ λ 벨μμ μ²λ¦¬)
# λ°±κ·ΈλΌμ΄λ μ€λ λ μμ λΆλΆμ κ·Έλλ‘ μ μ§
init_thread = threading.Thread(target=background_init)
init_thread.daemon = True
init_thread.start()
# --- Flask λΌμ°νΈ μ μ ---
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
next_url = request.args.get('next') # 리λλ μ
ν URL κ°μ Έμ€κΈ°
logger.info(f"-------------- λ‘κ·ΈμΈ νμ΄μ§ μ μ (Next: {next_url}) --------------")
logger.info(f"Method: {request.method}")
if request.method == 'POST':
logger.info("λ‘κ·ΈμΈ μλ λ°μ")
username = request.form.get('username', '')
password = request.form.get('password', '')
logger.info(f"μ
λ ₯λ μ¬μ©μλͺ
: {username}")
logger.info(f"λΉλ°λ²νΈ μ
λ ₯ μ¬λΆ: {len(password) > 0}")
valid_username = ADMIN_USERNAME
valid_password = ADMIN_PASSWORD
logger.info(f"κ²μ¦μ© μ¬μ©μλͺ
: {valid_username}")
logger.info(f"κ²μ¦μ© λΉλ°λ²νΈ μ‘΄μ¬ μ¬λΆ: {valid_password is not None and len(valid_password) > 0}")
if username == valid_username and password == valid_password:
logger.info(f"λ‘κ·ΈμΈ μ±κ³΅: {username}")
logger.debug(f"μΈμ
μ€μ μ : {session}")
session.permanent = True
session['logged_in'] = True
session['username'] = username
session.modified = True
logger.info(f"μΈμ
μ€μ ν: {session}")
logger.info("μΈμ
μ€μ μλ£, 리λλ μ
μλ")
redirect_to = next_url or url_for('index')
logger.info(f"리λλ μ
λμ: {redirect_to}")
response = redirect(redirect_to)
return response
else:
logger.warning("λ‘κ·ΈμΈ μ€ν¨: μμ΄λ λλ λΉλ°λ²νΈ λΆμΌμΉ")
if username != valid_username: logger.warning("μ¬μ©μλͺ
λΆμΌμΉ")
if password != valid_password: logger.warning("λΉλ°λ²νΈ λΆμΌμΉ")
error = 'μμ΄λ λλ λΉλ°λ²νΈκ° μ¬λ°λ₯΄μ§ μμ΅λλ€.'
else:
logger.info("λ‘κ·ΈμΈ νμ΄μ§ GET μμ²")
if 'logged_in' in session:
logger.info("μ΄λ―Έ λ‘κ·ΈμΈλ μ¬μ©μ, λ©μΈ νμ΄μ§λ‘ 리λλ μ
")
return redirect(url_for('index'))
logger.info("---------- λ‘κ·ΈμΈ νμ΄μ§ λ λλ§ ----------")
return render_template('login.html', error=error, next=next_url)
@app.route('/logout')
def logout():
logger.info("-------------- λ‘κ·Έμμ μμ² --------------")
logger.info(f"λ‘κ·Έμμ μ μΈμ
μν: {session}")
if 'logged_in' in session:
username = session.get('username', 'unknown')
logger.info(f"μ¬μ©μ {username} λ‘κ·Έμμ μ²λ¦¬ μμ")
session.pop('logged_in', None)
session.pop('username', None)
session.modified = True
logger.info(f"μΈμ
μ 보 μμ μλ£. νμ¬ μΈμ
: {session}")
else:
logger.warning("λ‘κ·ΈμΈλμ§ μμ μνμμ λ‘κ·Έμμ μλ")
logger.info("λ‘κ·ΈμΈ νμ΄μ§λ‘ 리λλ μ
")
response = redirect(url_for('login'))
return response
@app.route('/')
@login_required
def index():
"""λ©μΈ νμ΄μ§"""
global app_ready
current_time = datetime.datetime.now()
try:
start_time = datetime.datetime.fromtimestamp(os.path.getmtime(__file__))
time_diff = (current_time - start_time).total_seconds()
if not app_ready and time_diff > 30:
logger.warning(f"μ±μ΄ 30μ΄ μ΄μ μ΄κΈ°ν μ€ μνμ
λλ€. κ°μ λ‘ ready μνλ‘ λ³κ²½ν©λλ€.")
app_ready = True
except FileNotFoundError:
logger.warning("__file__ κ²½λ‘λ₯Ό μ°Ύμ μ μμ΄ μκ° λΉκ΅ λ‘μ§μ 건λ<0xEB>λλλ€.")
if not app_ready: # κΈ°λ³Έ νμμμ λμ κ°λ¨ν λ‘μ§ μΆκ° κ°λ₯
logger.warning("μ± μ€λΉ μν νμΈ (μκ° λΉκ΅ λΆκ°)")
# νμμ λ€λ₯Έ μ€λΉ μν νμΈ λ‘μ§ μΆκ°
pass # μμλ‘ ν΅κ³Ό
if not app_ready:
logger.info("μ±μ΄ μμ§ μ€λΉλμ§ μμ λ‘λ© νμ΄μ§ νμ")
return render_template('loading.html'), 503
logger.info("λ©μΈ νμ΄μ§ μμ²")
return render_template('index.html')
@app.route('/api/status')
@login_required
def app_status():
"""μ± μ΄κΈ°ν μν νμΈ API"""
logger.info(f"μ± μν νμΈ μμ²: {'Ready' if app_ready else 'Not Ready'}")
return jsonify({"ready": app_ready})
@app.route('/api/llm', methods=['GET', 'POST'])
@login_required
def llm_api():
"""μ¬μ© κ°λ₯ν LLM λͺ©λ‘ λ° μ ν API"""
global llm_interface
if not app_ready:
return jsonify({"error": "μ±μ΄ μμ§ μ΄κΈ°ν μ€μ
λλ€. μ μ ν λ€μ μλν΄μ£ΌμΈμ."}), 503
if request.method == 'GET':
logger.info("LLM λͺ©λ‘ μμ²")
try:
current_details = llm_interface.get_current_llm_details() if hasattr(llm_interface, 'get_current_llm_details') else {"id": "unknown", "name": "Unknown"}
supported_llms_dict = llm_interface.SUPPORTED_LLMS if hasattr(llm_interface, 'SUPPORTED_LLMS') else {}
supported_list = [{
"name": name, "id": id, "current": id == current_details.get("id")
} for name, id in supported_llms_dict.items()]
return jsonify({
"supported_llms": supported_list,
"current_llm": current_details
})
except Exception as e:
logger.error(f"LLM μ 보 μ‘°ν μ€λ₯: {e}")
return jsonify({"error": "LLM μ 보 μ‘°ν μ€ μ€λ₯ λ°μ"}), 500
elif request.method == 'POST':
data = request.get_json()
if not data or 'llm_id' not in data:
return jsonify({"error": "LLM IDκ° μ 곡λμ§ μμμ΅λλ€."}), 400
llm_id = data['llm_id']
logger.info(f"LLM λ³κ²½ μμ²: {llm_id}")
try:
if not hasattr(llm_interface, 'set_llm') or not hasattr(llm_interface, 'llm_clients'):
raise NotImplementedError("LLM μΈν°νμ΄μ€μ νμν λ©μλ/μμ± μμ")
if llm_id not in llm_interface.llm_clients:
return jsonify({"error": f"μ§μλμ§ μλ LLM ID: {llm_id}"}), 400
success = llm_interface.set_llm(llm_id)
if success:
new_details = llm_interface.get_current_llm_details()
logger.info(f"LLMμ΄ '{new_details.get('name', llm_id)}'λ‘ λ³κ²½λμμ΅λλ€.")
return jsonify({
"success": True,
"message": f"LLMμ΄ '{new_details.get('name', llm_id)}'λ‘ λ³κ²½λμμ΅λλ€.",
"current_llm": new_details
})
else:
logger.error(f"LLM λ³κ²½ μ€ν¨ (ID: {llm_id})")
return jsonify({"error": "LLM λ³κ²½ μ€ λ΄λΆ μ€λ₯ λ°μ"}), 500
except Exception as e:
logger.error(f"LLM λ³κ²½ μ²λ¦¬ μ€ μ€λ₯: {e}", exc_info=True)
return jsonify({"error": f"LLM λ³κ²½ μ€ μ€λ₯ λ°μ: {str(e)}"}), 500
@app.route('/api/chat', methods=['POST'])
@login_required
def chat():
"""ν
μ€νΈ κΈ°λ° μ±λ΄ API"""
global retriever
if not app_ready or retriever is None:
return jsonify({"error": "μ±/κ²μκΈ°κ° μμ§ μ΄κΈ°ν μ€μ
λλ€. μ μ ν λ€μ μλν΄μ£ΌμΈμ."}), 503
try:
data = request.get_json()
if not data or 'query' not in data:
return jsonify({"error": "μΏΌλ¦¬κ° μ 곡λμ§ μμμ΅λλ€."}), 400
query = data['query']
logger.info(f"ν
μ€νΈ 쿼리 μμ : {query[:100]}...")
if not hasattr(retriever, 'search'):
raise NotImplementedError("Retrieverμ search λ©μλκ° μμ΅λλ€.")
search_results = retriever.search(query, top_k=5, first_stage_k=6)
if not hasattr(DocumentProcessor, 'prepare_rag_context'):
raise NotImplementedError("DocumentProcessorμ prepare_rag_context λ©μλκ° μμ΅λλ€.")
context = DocumentProcessor.prepare_rag_context(search_results, field="text")
if not context:
logger.warning("κ²μ κ²°κ³Όκ° μμ΄ μ»¨ν
μ€νΈλ₯Ό μμ±νμ§ λͺ»ν¨.")
pass
llm_id = data.get('llm_id', None)
if not hasattr(llm_interface, 'rag_generate'):
raise NotImplementedError("LLMInterfaceμ rag_generate λ©μλκ° μμ΅λλ€.")
if not context:
answer = "μ£μ‘ν©λλ€. κ΄λ ¨ μ 보λ₯Ό μ°Ύμ μ μμ΅λλ€."
logger.info("컨ν
μ€νΈ μμ΄ κΈ°λ³Έ μλ΅ μμ±")
else:
answer = llm_interface.rag_generate(query, context, llm_id=llm_id)
logger.info(f"LLM μλ΅ μμ± μλ£ (κΈΈμ΄: {len(answer)})")
sources = []
if search_results:
for result in search_results:
if not isinstance(result, dict):
logger.warning(f"μμμΉ λͺ»ν κ²μ κ²°κ³Ό νμ: {type(result)}")
continue
if "source" in result:
source_info = {
"source": result.get("source", "Unknown"),
"score": result.get("rerank_score", result.get("score", 0))
}
if "text" in result and result.get("filetype") == "csv":
try:
text_lines = result["text"].strip().split('\n')
if text_lines:
first_line = text_lines[0].strip()
if ',' in first_line:
first_column = first_line.split(',')[0].strip()
source_info["id"] = first_column
logger.debug(f"CSV μμ€ ID μΆμΆ: {first_column} from {source_info['source']}")
except Exception as e:
logger.warning(f"CSV μμ€ ID μΆμΆ μ€ν¨ ({result.get('source')}): {e}")
sources.append(source_info)
response_data = {
"answer": answer,
"sources": sources,
"llm": llm_interface.get_current_llm_details() if hasattr(llm_interface, 'get_current_llm_details') else {}
}
return jsonify(response_data)
except Exception as e:
logger.error(f"μ±ν
μ²λ¦¬ μ€ μ€λ₯ λ°μ: {e}", exc_info=True)
return jsonify({"error": f"μ²λ¦¬ μ€ μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}"}), 500
@app.route('/api/voice', methods=['POST'])
@login_required
def voice_chat():
"""μμ± μ± API μλν¬μΈνΈ"""
global retriever, stt_client
if not app_ready:
logger.warning("μ± μ΄κΈ°νκ° μλ£λμ§ μμμ§λ§ μμ± API μμ² μ²λ¦¬ μλ")
if retriever is None:
logger.error("retrieverκ° μμ§ μ΄κΈ°νλμ§ μμμ΅λλ€")
return jsonify({
"transcription": "(μμ±μ ν
μ€νΈλ‘ λ³ννμ§λ§ κ²μ μμ§μ΄ μμ§ μ€λΉλμ§ μμμ΅λλ€)",
"answer": "μ£μ‘ν©λλ€. κ²μ μμ§μ΄ μμ§ μ΄κΈ°ν μ€μ
λλ€. μ μ ν λ€μ μλν΄μ£ΌμΈμ.",
"sources": []
})
if stt_client is None:
return jsonify({
"transcription": "(μμ± μΈμ κΈ°λ₯μ΄ μ€λΉ μ€μ
λλ€)",
"answer": "μ£μ‘ν©λλ€. νμ¬ μμ± μΈμ μλΉμ€κ° μ΄κΈ°ν μ€μ
λλ€. μ μ ν λ€μ μλν΄μ£ΌμΈμ.",
"sources": []
})
logger.info("μμ± μ± μμ² μμ ")
if 'audio' not in request.files:
logger.error("μ€λμ€ νμΌμ΄ μ 곡λμ§ μμ")
return jsonify({"error": "μ€λμ€ νμΌμ΄ μ 곡λμ§ μμμ΅λλ€."}), 400
audio_file = request.files['audio']
logger.info(f"μμ λ μ€λμ€ νμΌ: {audio_file.filename} ({audio_file.content_type})")
try:
with tempfile.NamedTemporaryFile(delete=True) as temp_audio:
audio_file.save(temp_audio.name)
logger.info(f"μ€λμ€ νμΌμ μμ μ μ₯: {temp_audio.name}")
if not hasattr(stt_client, 'transcribe_audio'):
raise NotImplementedError("STT ν΄λΌμ΄μΈνΈμ transcribe_audio λ©μλκ° μμ΅λλ€.")
with open(temp_audio.name, 'rb') as f_bytes:
audio_bytes = f_bytes.read()
stt_result = stt_client.transcribe_audio(audio_bytes, language="ko")
if not isinstance(stt_result, dict) or not stt_result.get("success"):
error_msg = stt_result.get("error", "μ μ μλ STT μ€λ₯") if isinstance(stt_result, dict) else "STT κ²°κ³Ό νμ μ€λ₯"
logger.error(f"μμ±μΈμ μ€ν¨: {error_msg}")
return jsonify({
"error": "μμ±μΈμ μ€ν¨",
"details": error_msg
}), 500
transcription = stt_result.get("text", "")
if not transcription:
logger.warning("μμ±μΈμ κ²°κ³Όκ° λΉμ΄μμ΅λλ€.")
return jsonify({"error": "μμ±μμ ν
μ€νΈλ₯Ό μΈμνμ§ λͺ»νμ΅λλ€.", "transcription": ""}), 400
logger.info(f"μμ±μΈμ μ±κ³΅: {transcription[:50]}...")
if retriever is None:
logger.error("STT μ±κ³΅ ν κ²μ μλ μ€ retrieverκ° Noneμ")
return jsonify({
"transcription": transcription,
"answer": "μμ±μ μΈμνμ§λ§, νμ¬ κ²μ μμ€ν
μ΄ μ€λΉλμ§ μμμ΅λλ€. μ μ ν λ€μ μλν΄μ£ΌμΈμ.",
"sources": []
})
search_results = retriever.search(transcription, top_k=5, first_stage_k=6)
context = DocumentProcessor.prepare_rag_context(search_results, field="text")
if not context:
logger.warning("μμ± μΏΌλ¦¬μ λν κ²μ κ²°κ³Ό μμ.")
pass
llm_id = request.form.get('llm_id', None)
if not context:
answer = "μ£μ‘ν©λλ€. κ΄λ ¨ μ 보λ₯Ό μ°Ύμ μ μμ΅λλ€."
logger.info("컨ν
μ€νΈ μμ΄ κΈ°λ³Έ μλ΅ μμ±")
else:
answer = llm_interface.rag_generate(transcription, context, llm_id=llm_id)
logger.info(f"LLM μλ΅ μμ± μλ£ (κΈΈμ΄: {len(answer)})")
enhanced_sources = []
if search_results:
for doc in search_results:
if not isinstance(doc, dict): continue
if "source" in doc:
source_info = {
"source": doc.get("source", "Unknown"),
"score": doc.get("rerank_score", doc.get("score", 0))
}
if "text" in doc and doc.get("filetype") == "csv":
try:
text_lines = doc["text"].strip().split('\n')
if text_lines:
first_line = text_lines[0].strip()
if ',' in first_line:
first_column = first_line.split(',')[0].strip()
source_info["id"] = first_column
except Exception as e:
logger.warning(f"[μμ±μ±] CSV μμ€ ID μΆμΆ μ€ν¨ ({doc.get('source')}): {e}")
enhanced_sources.append(source_info)
response_data = {
"transcription": transcription,
"answer": answer,
"sources": enhanced_sources,
"llm": llm_interface.get_current_llm_details() if hasattr(llm_interface, 'get_current_llm_details') else {}
}
return jsonify(response_data)
except Exception as e:
logger.error(f"μμ± μ± μ²λ¦¬ μ€ μ€λ₯ λ°μ: {e}", exc_info=True)
return jsonify({
"error": "μμ± μ²λ¦¬ μ€ λ΄λΆ μ€λ₯ λ°μ",
"details": str(e)
}), 500
@app.route('/api/upload', methods=['POST'])
@login_required
def upload_document():
"""μ§μλ² μ΄μ€ λ¬Έμ μ
λ‘λ API"""
global base_retriever, retriever
if not app_ready or base_retriever is None:
return jsonify({"error": "μ±/κΈ°λ³Έ κ²μκΈ°κ° μμ§ μ΄κΈ°ν μ€μ
λλ€."}), 503
if 'document' not in request.files:
return jsonify({"error": "λ¬Έμ νμΌμ΄ μ 곡λμ§ μμμ΅λλ€."}), 400
doc_file = request.files['document']
if doc_file.filename == '':
return jsonify({"error": "μ νλ νμΌμ΄ μμ΅λλ€."}), 400
if not allowed_doc_file(doc_file.filename):
logger.error(f"νμ©λμ§ μλ νμΌ νμ: {doc_file.filename}")
return jsonify({"error": f"νμ©λμ§ μλ νμΌ νμμ
λλ€. νμ©: {', '.join(ALLOWED_DOC_EXTENSIONS)}"}), 400
try:
filename = secure_filename(doc_file.filename)
filepath = os.path.join(app.config['DATA_FOLDER'], filename)
doc_file.save(filepath)
logger.info(f"λ¬Έμ μ μ₯ μλ£: {filepath}")
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
except UnicodeDecodeError:
logger.info(f"UTF-8 λμ½λ© μ€ν¨, CP949λ‘ μλ: {filename}")
try:
with open(filepath, 'r', encoding='cp949') as f:
content = f.read()
except Exception as e_cp949:
logger.error(f"CP949 λμ½λ© μ€ν¨ ({filename}): {e_cp949}")
return jsonify({"error": "νμΌ μΈμ½λ©μ μ½μ μ μμ΅λλ€ (UTF-8, CP949 μλ μ€ν¨)."}), 400
except Exception as e_read:
logger.error(f"νμΌ μ½κΈ° μ€λ₯ ({filename}): {e_read}")
return jsonify({"error": f"νμΌ μ½κΈ° μ€ μ€λ₯ λ°μ: {str(e_read)}"}), 500
metadata = {
"source": filename, "filename": filename,
"filetype": filename.rsplit('.', 1)[1].lower(),
"filepath": filepath
}
file_ext = metadata["filetype"]
docs = []
if not hasattr(DocumentProcessor, 'csv_to_documents') or not hasattr(DocumentProcessor, 'text_to_documents'):
raise NotImplementedError("DocumentProcessorμ νμν λ©μλ μμ")
if file_ext == 'csv':
logger.info(f"CSV νμΌ μ²λ¦¬ μμ: {filename}")
docs = DocumentProcessor.csv_to_documents(content, metadata)
else:
logger.info(f"μΌλ° ν
μ€νΈ λ¬Έμ μ²λ¦¬ μμ: {filename}")
if file_ext in ['pdf', 'docx']:
logger.warning(f".{file_ext} νμΌ μ²λ¦¬λ νμ¬ κ΅¬νλμ§ μμμ΅λλ€. ν
μ€νΈ μΆμΆ λ‘μ§ μΆκ° νμ.")
content = ""
if content:
docs = DocumentProcessor.text_to_documents(
content, metadata=metadata,
chunk_size=512, chunk_overlap=50
)
if docs:
if not hasattr(base_retriever, 'add_documents') or not hasattr(base_retriever, 'save'):
raise NotImplementedError("κΈ°λ³Έ κ²μκΈ°μ add_documents λλ save λ©μλ μμ")
logger.info(f"{len(docs)}κ° λ¬Έμ μ²ν¬λ₯Ό κ²μκΈ°μ μΆκ°ν©λλ€...")
base_retriever.add_documents(docs)
logger.info(f"κ²μκΈ° μνλ₯Ό μ μ₯ν©λλ€...")
index_path = app.config['INDEX_PATH']
try:
base_retriever.save(index_path)
logger.info("μΈλ±μ€ μ μ₯ μλ£")
# μ¬μμν κ²μκΈ° μ
λ°μ΄νΈ λ‘μ§ νμ μ μΆκ°
# μ: if retriever != base_retriever and hasattr(retriever, 'update_base_retriever'): retriever.update_base_retriever(base_retriever)
return jsonify({
"success": True,
"message": f"νμΌ '{filename}' μ
λ‘λ λ° μ²λ¦¬ μλ£ ({len(docs)}κ° μ²ν¬ μΆκ°)."
})
except Exception as e_save:
logger.error(f"μΈλ±μ€ μ μ₯ μ€ μ€λ₯ λ°μ: {e_save}")
return jsonify({"error": f"μΈλ±μ€ μ μ₯ μ€ μ€λ₯: {str(e_save)}"}), 500
else:
logger.warning(f"νμΌ '{filename}'μμ μ²λ¦¬ν λ΄μ©μ΄ μκ±°λ μ§μλμ§ μλ νμμ
λλ€.")
return jsonify({
"warning": True,
"message": f"νμΌ '{filename}'μ΄ μ μ₯λμμ§λ§ μ²λ¦¬ν λ΄μ©μ΄ μμ΅λλ€."
})
except Exception as e:
logger.error(f"νμΌ μ
λ‘λ λλ μ²λ¦¬ μ€ μ€λ₯ λ°μ: {e}", exc_info=True)
return jsonify({"error": f"νμΌ μ
λ‘λ μ€ μ€λ₯: {str(e)}"}), 500
@app.route('/api/documents', methods=['GET'])
@login_required
def list_documents():
"""μ§μλ² μ΄μ€ λ¬Έμ λͺ©λ‘ API"""
global base_retriever
if not app_ready or base_retriever is None:
return jsonify({"error": "μ±/κΈ°λ³Έ κ²μκΈ°κ° μμ§ μ΄κΈ°ν μ€μ
λλ€."}), 503
try:
sources = {}
total_chunks = 0
if hasattr(base_retriever, 'documents') and base_retriever.documents:
logger.info(f"μ΄ {len(base_retriever.documents)}κ° λ¬Έμ μ²ν¬μμ μμ€ λͺ©λ‘ μμ± μ€...")
for doc in base_retriever.documents:
if not isinstance(doc, dict): continue
source = doc.get("source", "unknown")
if source == "unknown" and "metadata" in doc and isinstance(doc["metadata"], dict):
source = doc["metadata"].get("source", "unknown")
if source != "unknown":
if source in sources:
sources[source]["chunks"] += 1
else:
filename = doc.get("filename", source)
filetype = doc.get("filetype", "unknown")
if "metadata" in doc and isinstance(doc["metadata"], dict):
filename = doc["metadata"].get("filename", filename)
filetype = doc["metadata"].get("filetype", filetype)
sources[source] = {
"filename": filename,
"chunks": 1,
"filetype": filetype
}
total_chunks += 1
else:
logger.info("κ²μκΈ°μ λ¬Έμκ° μκ±°λ documents μμ±μ μ°Ύμ μ μμ΅λλ€.")
documents = [{"source": src, **info} for src, info in sources.items()]
documents.sort(key=lambda x: x["chunks"], reverse=True)
logger.info(f"λ¬Έμ λͺ©λ‘ μ‘°ν μλ£: {len(documents)}κ° μμ€ νμΌ, {total_chunks}κ° μ²ν¬")
return jsonify({
"documents": documents,
"total_documents": len(documents),
"total_chunks": total_chunks
})
except Exception as e:
logger.error(f"λ¬Έμ λͺ©λ‘ μ‘°ν μ€ μ€λ₯ λ°μ: {e}", exc_info=True)
return jsonify({"error": f"λ¬Έμ λͺ©λ‘ μ‘°ν μ€ μ€λ₯: {str(e)}"}), 500
# μ μ νμΌ μλΉ
@app.route('/static/<path:path>')
def send_static(path):
return send_from_directory('static', path)
# --- μμ² μ²λ¦¬ ν
---
@app.after_request
def after_request_func(response):
"""λͺ¨λ μλ΅μ λν΄ νμ²λ¦¬ μν"""
# logger.debug(f"[After Request] μλ΅ ν€λ: {response.headers}") # λλ²κΉ
μ Set-Cookie νμΈ
return response
# μ± μ€ν (λ‘컬 ν
μ€νΈμ©)
if __name__ == '__main__':
logger.info("Flask μ±μ μ§μ μ€νν©λλ€ (κ°λ°μ© μλ²).")
# λλ²κ·Έ λͺ¨λλ κ°λ° μ€μλ§ Trueλ‘ μ€μ νκ³ , μ€μ λ°°ν¬ μμλ Falseλ‘ μ€μ ν΄μΌ ν©λλ€.
# host='0.0.0.0' μ λͺ¨λ λ€νΈμν¬ μΈν°νμ΄μ€μμ μ μ κ°λ₯νκ² ν©λλ€.
port = int(os.environ.get("PORT", 7860))
logger.info(f"μλ²λ₯Ό http://0.0.0.0:{port} μμ μμν©λλ€.")
# debug=True μ¬μ© μ werkzeug reloaderκ° νμ±νλμ΄ μ½λκ° λ³κ²½λ λ μλ²κ° μ¬μμλ μ μμΌλ©°,
# μ΄ κ³Όμ μμ μ μ μ΄κΈ°ν μ½λκ° λ€μ μ€νλ μ μμ΅λλ€.
# DEVICE_ROUTES_REGISTERED νλκ·Έκ° μ΄λ₯Ό λ°©μ§ν©λλ€.
app.run(debug=True, host='0.0.0.0', port=port) |