from fastapi import FastAPI, UploadFile, File, HTTPException, Body from fastapi.templating import Jinja2Templates from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi import Request import os from uuid import uuid4 from typing import Dict, List # 필요한 모듈 임포트 (여러분이 구현한 모듈) from .embedding_utils import split_text, get_embedding, rerank from .supabase_utils import ( save_embedding, save_embeddings_batch, search_similar_embeddings, search_by_keyword, get_document_id_by_hash, ) from .config import ( UPLOAD_DIR, ALLOWED_EXTENSIONS, OPENAI_API_KEY, OPENAI_CHAT_MODEL, EMBED_WORKERS, ) import pdfplumber from openai import ( OpenAI, RateLimitError, AuthenticationError, APITimeoutError, APIConnectionError, ) from tenacity import retry, wait_exponential, stop_after_attempt, retry_if_exception import hashlib import time from concurrent.futures import ThreadPoolExecutor app = FastAPI(title="DocuFlow AI Agent") client = OpenAI(api_key=OPENAI_API_KEY) @app.get("/health") async def health_check(): """헬스체크 엔드포인트 - 배포 상태 확인용""" return {"status": "healthy"} def _is_transient_error(e: Exception) -> bool: """타임아웃·연결 오류·rate limit(quota 부족 제외)을 재시도 대상으로 판단""" if isinstance(e, (APITimeoutError, APIConnectionError)): return True if isinstance(e, RateLimitError): return e.code != "insufficient_quota" return False @retry( retry=retry_if_exception(_is_transient_error), wait=wait_exponential(multiplier=1, min=2, max=30), stop=stop_after_attempt(3), ) def _call_llm(messages: list, model: str) -> str: response = client.chat.completions.create(model=model, messages=messages) return response.choices[0].message.content # 템플릿 및 정적 파일 설정 templates = Jinja2Templates(directory="app/templates") app.mount("/static", StaticFiles(directory="app/static"), name="static") def allowed_file(filename: str) -> bool: return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS def _table_to_markdown(table: list[list]) -> str: """pdfplumber 테이블(리스트의 리스트)을 마크다운 테이블 문자열로 변환한다.""" if not table: return "" # None → 빈 문자열, 셀 내 줄바꿈 → 공백 cleaned = [] for row in table: cleaned.append([(cell or "").replace("\n", " ").strip() for cell in row]) # 모든 셀이 비어있으면 빈 문자열 반환 if all(cell == "" for row in cleaned for cell in row): return "" header = cleaned[0] col_count = len(header) lines = [ "| " + " | ".join(header) + " |", "| " + " | ".join(["---"] * col_count) + " |", ] for row in cleaned[1:]: # 열 수가 맞지 않으면 패딩 padded = ( row + [""] * (col_count - len(row)) if len(row) < col_count else row[:col_count] ) lines.append("| " + " | ".join(padded) + " |") return "\n".join(lines) def extract_text_from_pdf(file_path: str) -> str: """ PDF 파일에서 텍스트를 추출하는 함수. 표(table)가 있는 페이지는 마크다운 테이블로 변환하여 구조를 보존한다. """ all_pages_text = [] with pdfplumber.open(file_path) as pdf: for page in pdf.pages: tables = page.find_tables() print(f"[DEBUG] page {page.page_number}: {len(tables)} tables found") # 테이블이 없으면 기존 빠른 경로 if not tables: page_text = page.extract_text() if page_text: all_pages_text.append(f"[p.{page.page_number}] {page_text}") continue # 테이블이 있는 페이지: 테이블과 비-테이블 영역을 분리하여 추출 segments = [] # (y좌표, 텍스트) 튜플 리스트 # 테이블 bbox 수집 table_bboxes = [] for table in tables: bbox = table.bbox # (x0, top, x1, bottom) table_bboxes.append(bbox) md = _table_to_markdown(table.extract()) if md: segments.append((bbox[1], md)) # top y좌표 기준 # 비-테이블 영역 텍스트 추출 # 페이지를 테이블 영역 기준으로 crop하여 나머지 텍스트 추출 page_height = page.height page_width = page.width # 테이블 영역을 y좌표 순으로 정렬 sorted_bboxes = sorted(table_bboxes, key=lambda b: b[1]) # 비-테이블 영역 구간 계산 non_table_regions = [] current_top = 0 for bbox in sorted_bboxes: if bbox[1] > current_top: non_table_regions.append((0, current_top, page_width, bbox[1])) current_top = max(current_top, bbox[3]) if current_top < page_height: non_table_regions.append((0, current_top, page_width, page_height)) for region in non_table_regions: try: cropped = page.crop(region) region_text = cropped.extract_text() if region_text: segments.append((region[1], region_text)) except Exception: pass # y좌표 순으로 정렬하여 읽기 순서 유지 segments.sort(key=lambda s: s[0]) page_text = "\n".join(seg[1] for seg in segments) if page_text: all_pages_text.append(f"[p.{page.page_number}] {page_text}") return "\n".join(all_pages_text) @app.get("/", response_class=HTMLResponse) async def root_page(request: Request): return templates.TemplateResponse("index.html", {"request": request}) @app.post("/documents/") async def upload_document(file: UploadFile = File(...)): """ 문서 업로드 및 임베딩 처리 엔드포인트 프로세스: 1. 업로드된 파일을 로컬(UPLOAD_DIR)에 저장 2. PDF에서 텍스트 추출 3. 텍스트를 청크로 분할 4. 각 청크를 임베딩하고 DB에 저장 """ document_id = str(uuid4()) if not allowed_file(file.filename): raise HTTPException(status_code=400, detail="허용되지 않는 파일 형식입니다.") try: content = await file.read() file_hash = hashlib.sha256(content).hexdigest() existing_id = get_document_id_by_hash(file_hash) if existing_id: return { "message": "이미 동일한 문서가 업로드되어 있습니다.", "document_id": existing_id, } # 1. 파일 저장 file_path = os.path.join(UPLOAD_DIR, f"{document_id}_{file.filename}") with open(file_path, "wb") as f: f.write(content) # 2. 텍스트 추출 t0 = time.perf_counter() text = extract_text_from_pdf(file_path) t1 = time.perf_counter() # 3. 청크 분할 chunks = split_text(text) t2 = time.perf_counter() # 4. 임베딩 및 저장 def _embed_chunk(chunk: str): return get_embedding(chunk) with ThreadPoolExecutor(max_workers=EMBED_WORKERS) as executor: embeddings = list(executor.map(_embed_chunk, chunks)) save_embeddings_batch(document_id, chunks, embeddings, file_hash=file_hash) t3 = time.perf_counter() return { "message": "문서 처리가 완료되었습니다.", "document_id": document_id, "chunks_count": len(chunks), "timing": { "extract_text_sec": round(t1 - t0, 2), "split_text_sec": round(t2 - t1, 2), "embed_and_save_sec": round(t3 - t2, 2), "total_sec": round(t3 - t0, 2), }, } except AuthenticationError: print("오류 발생: OpenAI API 키가 유효하지 않습니다.") raise HTTPException( status_code=500, detail="서버 설정 오류가 발생했습니다. 관리자에게 문의해주세요.", ) except APITimeoutError: print("오류 발생: OpenAI API 요청 시간 초과") raise HTTPException( status_code=504, detail="요청 처리 시간이 초과되었습니다. 잠시 후 다시 시도해주세요.", ) except Exception as e: print(f"오류 발생: {str(e)}") raise HTTPException(status_code=500, detail=str(e)) finally: pass @app.post("/qa") async def question_answering(question: Dict[str, str] = Body(...)): """ RAG 기반 질의응답 엔드포인트 프로세스: 1. 쿼리 리라이팅 2. 질문 임베딩 3. 하이브리드 검색 (벡터 + 키워드) 4. 리랭킹 5. LLM 응답 생성 """ try: if "document_id" not in question: raise HTTPException(status_code=400, detail="document_id is required") user_question = question["query"] document_id = question["document_id"] # 1. 쿼리 리라이팅: LLM으로 검색 최적화 쿼리 생성 rewrite_prompt = ( "당신은 문서 검색 쿼리 최적화 전문가입니다.\n" "다음 사용자 질문을 문서 검색에 적합한 형태로 변환하세요.\n\n" "규칙:\n" "1. 핵심 명사와 고유명사를 보존하세요\n" "2. 한국어 조사(은/는/이/가/을/를/의)를 제거하세요\n" "3. 검색에 불필요한 표현(알려주세요, 무엇인가요 등)을 제거하세요\n" "4. 동의어나 관련 용어가 있다면 추가하세요\n" "5. 변환된 키워드/구문만 출력하세요 (설명 없이)\n\n" f"질문: {user_question}" ) rewritten_query = _call_llm( messages=[{"role": "user", "content": rewrite_prompt}], model=OPENAI_CHAT_MODEL, ).strip() print(f"\n{'='*60}") print(f" [QA] 원본 질문: {user_question}") print(f" [QA] 리라이팅: {rewritten_query}") print(f"{'='*60}") # 2. 질문 임베딩 (리라이팅된 쿼리 사용) question_embedding = get_embedding(rewritten_query) # 3. 하이브리드 검색: 벡터 검색 + 키워드 검색 vector_chunks = search_similar_embeddings(question_embedding, document_id) keyword_chunks = search_by_keyword(user_question, document_id) # 중복 제거 후 합침 seen_contents = set() all_chunks_content = [] for chunk in vector_chunks: content = chunk["content"] if content not in seen_contents: seen_contents.add(content) all_chunks_content.append(content) for chunk in keyword_chunks: content = chunk["content"] if content not in seen_contents: seen_contents.add(content) all_chunks_content.append(content) print(f"\n 하이브리드 검색 결과:") print(f" 벡터 검색: {len(vector_chunks)}건") print(f" 키워드 검색: {len(keyword_chunks)}건") print(f" 중복 제거 후: {len(all_chunks_content)}건") # 4. 빈 결과 방어: 검색 결과가 없으면 즉시 반환 if not all_chunks_content: print(f" ⚠ 검색 결과 없음 → 빈 응답 반환") return {"answer": "문서에서 해당 정보를 찾을 수 없습니다.", "sources": []} # 5. 리랭킹: Cross-encoder로 상위 5개 선별 reranked_chunks = rerank(user_question, all_chunks_content, top_k=5) print(f"\n 리랭킹 후 최종 {len(reranked_chunks)}건 선별:") for i, chunk in enumerate(reranked_chunks, 1): preview = chunk[:60].replace("\n", " ") print(f" [{i}] {preview}...") print(f"{'='*60}\n") # 6. 프롬프트 구성 context = "\n\n".join( f"[참고자료 {i}]\n{chunk}" for i, chunk in enumerate(reranked_chunks, 1) ) system_prompt = ( "[역할]\n" "- 너는 업로드된 문서를 근거로만 답변하는 RAG 어시스턴트다.\n" "[행동 원칙]\n" "- 제공된 참고 문서에 근거가 있는 내용만 답변한다.\n" "- 참고 문서에 없는 사실은 추정하지 않는다.\n" "- 질문이 모호하면 필요한 정보를 먼저 물어본다.\n" "- 문서 외 질문이면 '문서에서 확인할 수 없다'라고 명시한다.\n" "[금지 사항]\n" "- 참고 문서에 없는 정보를 추정, 추론, 지어내지 않는다.\n" "- 확신이 없으면 '확인할 수 없다'라고만 답한다.\n" "[답변 전 검증]\n" "- 답변의 각 문장이 참고 문서에 근거가 있는지 확인한다.\n" "- 근거가 없는 문장은 삭제하거나 '문서에 명시되지 않음'으로 표시한다.\n" "[불확실성 처리]\n" "- 참고 문서에 부분적으로만 언급된 내용은 '제한적으로 확인됨' 등으로 표현한다.\n" "- 관련 내용이 전혀 없으면 추측하지 않고 '해당 정보는 문서에 없습니다'라고만 답한다.\n" "[근거 제시]\n" "- 근거 제시 시 페이지 번호([p.N])가 있으면 포함하세요.\n" "[응답 형식]\n" "- 답변:\n" "- 근거:\n" "- 한계/추가 확인 필요사항:" ) # 7. LLM 응답 생성 messages = [ {"role": "system", "content": f"{system_prompt}\n\n[참고 문서]\n{context}"}, {"role": "user", "content": user_question}, ] answer = _call_llm(messages=messages, model=OPENAI_CHAT_MODEL) return { "answer": answer, "sources": reranked_chunks, } except AuthenticationError: print("오류 발생: OpenAI API 키가 유효하지 않습니다.") raise HTTPException( status_code=500, detail="서버 설정 오류가 발생했습니다. 관리자에게 문의해주세요.", ) except APITimeoutError: print("오류 발생: OpenAI API 요청 시간 초과") raise HTTPException( status_code=504, detail="요청 처리 시간이 초과되었습니다. 잠시 후 다시 시도해주세요.", ) except RateLimitError as e: if e.code == "insufficient_quota": raise HTTPException( status_code=402, detail="OpenAI API 크레딧이 부족합니다. 플랜을 확인해주세요.", ) raise HTTPException( status_code=429, detail="OpenAI API 요청 한도를 초과했습니다. 잠시 후 다시 시도해주세요.", ) except Exception as e: print(f"오류 발생: {str(e)}") raise HTTPException(status_code=500, detail=str(e))