woongmin commited on
Commit
afc8097
·
1 Parent(s): 9054d39

[Delta-02] 표 데이터 정합성 개선

Browse files
Files changed (5) hide show
  1. Pipfile +1 -1
  2. Pipfile.lock +3 -3
  3. app/embedding_utils.py +16 -2
  4. app/main.py +151 -22
  5. app/supabase_utils.py +25 -2
Pipfile CHANGED
@@ -16,8 +16,8 @@ langchain = "*"
16
  pdfplumber = "*"
17
  requests = "*"
18
  nltk = "*"
19
- sentence-transformers = "*"
20
  numpy = "*"
 
21
 
22
  [dev-packages]
23
  pre-commit = "*"
 
16
  pdfplumber = "*"
17
  requests = "*"
18
  nltk = "*"
 
19
  numpy = "*"
20
+ sentence-transformers = "*"
21
 
22
  [dev-packages]
23
  pre-commit = "*"
Pipfile.lock CHANGED
@@ -774,11 +774,11 @@
774
  },
775
  "huggingface-hub": {
776
  "hashes": [
777
- "sha256:38c6cce7419bbde8caac26a45ed22b0cea24152a8961565d70ec21f88752bfaa",
778
- "sha256:be38fe66e9b03c027ad755cb9e4b87ff0303c98acf515b5d579690beb0bf3048"
779
  ],
780
  "markers": "python_full_version >= '3.9.0'",
781
- "version": "==1.7.1"
782
  },
783
  "idna": {
784
  "hashes": [
 
774
  },
775
  "huggingface-hub": {
776
  "hashes": [
777
+ "sha256:288f33a0a17b2a73a1359e2a5fd28d1becb2c121748c6173ab8643fb342c850e",
778
+ "sha256:7f7e294e9bbb822e025bdb2ada025fa4344d978175a7f78e824d86e35f7ab43b"
779
  ],
780
  "markers": "python_full_version >= '3.9.0'",
781
+ "version": "==1.7.2"
782
  },
783
  "idna": {
784
  "hashes": [
app/embedding_utils.py CHANGED
@@ -2,15 +2,19 @@ from typing import List
2
  import nltk
3
  import numpy as np
4
  import requests
 
5
  from app.config import OLLAMA_BASE, OLLAMA_EMBED_MODEL
6
 
 
 
 
7
  # 문장 수가 이 값을 초과하면 의미 기반 분할 대신 글자 수 기반 분할 사용
8
  # (대용량 PDF에서 문장당 임베딩 호출 시 Ollama 500 에러 방지)
9
  SENTENCE_LIMIT_FOR_SEMANTIC_CHUNKING = 500
10
 
11
 
12
  def _simple_split_by_chars(
13
- text: str, chunk_size: int = 1000, chunk_overlap: int = 100
14
  ) -> List[str]:
15
  """임베딩 없이 글자 수 기준으로만 청크 분할. 대용량 문서용 fallback."""
16
  text = text.strip()
@@ -52,7 +56,7 @@ def _cosine_similarity(a: np.ndarray, b: np.ndarray) -> float:
52
 
53
 
54
  def split_text(
55
- text: str, chunk_size: int = 1000, chunk_overlap: int = 100
56
  ) -> List[str]:
57
  """
58
  긴 텍스트를 의미 기반으로 청크로 분할하는 함수.
@@ -159,3 +163,13 @@ def get_embedding(text: str) -> List[float]:
159
  List[float]: 임베딩 벡터
160
  """
161
  return _ollama_embed(text)
 
 
 
 
 
 
 
 
 
 
 
2
  import nltk
3
  import numpy as np
4
  import requests
5
+ from sentence_transformers import CrossEncoder
6
  from app.config import OLLAMA_BASE, OLLAMA_EMBED_MODEL
7
 
8
+ # Cross-encoder 리랭커 (첫 호출 시 모델 다운로드)
9
+ reranker = CrossEncoder("BAAI/bge-reranker-v2-m3")
10
+
11
  # 문장 수가 이 값을 초과하면 의미 기반 분할 대신 글자 수 기반 분할 사용
12
  # (대용량 PDF에서 문장당 임베딩 호출 시 Ollama 500 에러 방지)
13
  SENTENCE_LIMIT_FOR_SEMANTIC_CHUNKING = 500
14
 
15
 
16
  def _simple_split_by_chars(
17
+ text: str, chunk_size: int = 1000, chunk_overlap: int = 200
18
  ) -> List[str]:
19
  """임베딩 없이 글자 수 기준으로만 청크 분할. 대용량 문서용 fallback."""
20
  text = text.strip()
 
56
 
57
 
58
  def split_text(
59
+ text: str, chunk_size: int = 1000, chunk_overlap: int = 200
60
  ) -> List[str]:
61
  """
62
  긴 텍스트를 의미 기반으로 청크로 분할하는 함수.
 
163
  List[float]: 임베딩 벡터
164
  """
165
  return _ollama_embed(text)
166
+
167
+
168
+ def rerank(query: str, chunks: List[str], top_k: int = 5) -> List[str]:
169
+ """Cross-encoder로 query-chunk 쌍을 재평가하여 관련도 높은 청크를 상위로 정렬."""
170
+ if not chunks:
171
+ return []
172
+ pairs = [[query, chunk] for chunk in chunks]
173
+ scores = reranker.predict(pairs)
174
+ ranked = sorted(zip(chunks, scores), key=lambda x: x[1], reverse=True)
175
+ return [chunk for chunk, _ in ranked[:top_k]]
app/main.py CHANGED
@@ -8,11 +8,12 @@ from uuid import uuid4
8
  from typing import Dict, List
9
 
10
  # 필요한 모듈 임포트 (여러분이 구현한 모듈)
11
- from .embedding_utils import split_text, get_embedding
12
  from .supabase_utils import (
13
  save_embedding,
14
  save_embeddings_batch,
15
  search_similar_embeddings,
 
16
  get_document_id_by_hash,
17
  )
18
  from .config import UPLOAD_DIR, ALLOWED_EXTENSIONS, OLLAMA_BASE, OLLAMA_CHAT_MODEL
@@ -34,25 +35,103 @@ def allowed_file(filename: str) -> bool:
34
  return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
35
 
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def extract_text_from_pdf(file_path: str) -> str:
38
  """
39
- [TODO Day 1] PDF 파일에서 텍스트를 추출하는 함수입니다.
40
-
41
- 요구사항:
42
- 1. PDF에서 텍스트를 추출할 수 있는 방법을 직접 조사하여 구현하세요.
43
- - 어떤 라이브러리를 사용할지는 스스로 결정하세요. (Pipfile에 설치된 패키지를 확인하세요.)
44
- 2. 모든 페이지의 텍스트를 추출하여 하나의 문자열로 합치세요.
45
  """
46
- # ---------------------------------------------------------
47
- # [Day 1] 과제: PDF 텍스트 추출 로직 작성
48
- # ---------------------------------------------------------
49
- text = ""
50
  with pdfplumber.open(file_path) as pdf:
51
  for page in pdf.pages:
52
- page_text = page.extract_text()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  if page_text:
54
- text += page_text + "\n"
55
- return text
 
56
 
57
 
58
  @app.get("/", response_class=HTMLResponse)
@@ -178,14 +257,64 @@ async def question_answering(question: Dict[str, str] = Body(...)):
178
  # 4. LLM 응답 생성
179
  # ---------------------------------------------------------
180
 
181
- # 1. 질문 임베딩
182
- question_embedding = get_embedding(user_question)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
 
184
- # 2. 벡터 검색
185
- similar_chunks = search_similar_embeddings(question_embedding, document_id)
 
186
 
187
- # 3. 프롬프트 구성
188
- context = "\n".join([chunk["content"] for chunk in similar_chunks])
 
 
 
 
189
 
190
  system_prompt = """
191
  [역할]
@@ -209,7 +338,7 @@ async def question_answering(question: Dict[str, str] = Body(...)):
209
  - 근거:
210
  - 한계/추가 확인 필요사항:"""
211
 
212
- # 4. LLM 응답 생성
213
  messages = [
214
  {"role": "system", "content": system_prompt},
215
  {
@@ -231,7 +360,7 @@ async def question_answering(question: Dict[str, str] = Body(...)):
231
 
232
  return {
233
  "answer": answer,
234
- "sources": [chunk["content"] for chunk in similar_chunks],
235
  }
236
 
237
  except requests.exceptions.ConnectionError:
 
8
  from typing import Dict, List
9
 
10
  # 필요한 모듈 임포트 (여러분이 구현한 모듈)
11
+ from .embedding_utils import split_text, get_embedding, rerank
12
  from .supabase_utils import (
13
  save_embedding,
14
  save_embeddings_batch,
15
  search_similar_embeddings,
16
+ search_by_keyword,
17
  get_document_id_by_hash,
18
  )
19
  from .config import UPLOAD_DIR, ALLOWED_EXTENSIONS, OLLAMA_BASE, OLLAMA_CHAT_MODEL
 
35
  return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
36
 
37
 
38
+ def _table_to_markdown(table: list[list]) -> str:
39
+ """pdfplumber 테이블(리스트의 리스트)을 마크다운 테이블 문자열로 변환한다."""
40
+ if not table:
41
+ return ""
42
+
43
+ # None → 빈 문자열, 셀 내 줄바꿈 → 공백
44
+ cleaned = []
45
+ for row in table:
46
+ cleaned.append([(cell or "").replace("\n", " ").strip() for cell in row])
47
+
48
+ # 모든 셀이 비어있으면 빈 문자열 반환
49
+ if all(cell == "" for row in cleaned for cell in row):
50
+ return ""
51
+
52
+ header = cleaned[0]
53
+ col_count = len(header)
54
+ lines = [
55
+ "| " + " | ".join(header) + " |",
56
+ "| " + " | ".join(["---"] * col_count) + " |",
57
+ ]
58
+ for row in cleaned[1:]:
59
+ # 열 수가 맞지 않으면 패딩
60
+ padded = (
61
+ row + [""] * (col_count - len(row))
62
+ if len(row) < col_count
63
+ else row[:col_count]
64
+ )
65
+ lines.append("| " + " | ".join(padded) + " |")
66
+
67
+ return "\n".join(lines)
68
+
69
+
70
  def extract_text_from_pdf(file_path: str) -> str:
71
  """
72
+ PDF 파일에서 텍스트를 추출하는 함수.
73
+ 표(table)가 있는 페이지는 마크다운 테이블로 변환하여 구조를 보존한다.
 
 
 
 
74
  """
75
+ all_pages_text = []
76
+
 
 
77
  with pdfplumber.open(file_path) as pdf:
78
  for page in pdf.pages:
79
+ tables = page.find_tables()
80
+ print(f"[DEBUG] page {page.number}: {len(tables)} tables found")
81
+
82
+ # 테이블이 없으면 기존 빠른 경로
83
+ if not tables:
84
+ page_text = page.extract_text()
85
+ if page_text:
86
+ all_pages_text.append(page_text)
87
+ continue
88
+
89
+ # 테이블이 있는 페이지: 테이블과 비-테이블 영역을 분리하여 추출
90
+ segments = [] # (y좌표, 텍스트) 튜플 리스트
91
+
92
+ # 테이블 bbox 수집
93
+ table_bboxes = []
94
+ for table in tables:
95
+ bbox = table.bbox # (x0, top, x1, bottom)
96
+ table_bboxes.append(bbox)
97
+ md = _table_to_markdown(table.extract())
98
+ if md:
99
+ segments.append((bbox[1], md)) # top y좌표 기준
100
+
101
+ # 비-테이블 영역 텍스트 추출
102
+ # 페이지를 테이블 영역 기준으로 crop하여 나머지 텍스트 추출
103
+ page_height = page.height
104
+ page_width = page.width
105
+
106
+ # 테이블 영역을 y좌표 순으로 정렬
107
+ sorted_bboxes = sorted(table_bboxes, key=lambda b: b[1])
108
+
109
+ # 비-테이블 영역 구간 계산
110
+ non_table_regions = []
111
+ current_top = 0
112
+ for bbox in sorted_bboxes:
113
+ if bbox[1] > current_top:
114
+ non_table_regions.append((0, current_top, page_width, bbox[1]))
115
+ current_top = max(current_top, bbox[3])
116
+ if current_top < page_height:
117
+ non_table_regions.append((0, current_top, page_width, page_height))
118
+
119
+ for region in non_table_regions:
120
+ try:
121
+ cropped = page.crop(region)
122
+ region_text = cropped.extract_text()
123
+ if region_text:
124
+ segments.append((region[1], region_text))
125
+ except Exception:
126
+ pass
127
+
128
+ # y좌표 순으로 정렬하여 읽기 순서 유지
129
+ segments.sort(key=lambda s: s[0])
130
+ page_text = "\n".join(seg[1] for seg in segments)
131
  if page_text:
132
+ all_pages_text.append(page_text)
133
+
134
+ return "\n".join(all_pages_text)
135
 
136
 
137
  @app.get("/", response_class=HTMLResponse)
 
257
  # 4. LLM 응답 생성
258
  # ---------------------------------------------------------
259
 
260
+ # 1. 쿼리 리라이팅: LLM으로 검색 최적화 쿼리 생성
261
+ rewrite_prompt = (
262
+ "다음 질문을 문서 검색에 적합한 키워드 중심 문장으로 바꿔주세요. "
263
+ "변환된 문장만 출력하세요:\n" + user_question
264
+ )
265
+ rewrite_response = requests.post(
266
+ f"{OLLAMA_BASE}/api/chat",
267
+ json={
268
+ "model": OLLAMA_CHAT_MODEL,
269
+ "messages": [{"role": "user", "content": rewrite_prompt}],
270
+ "stream": False,
271
+ },
272
+ timeout=30,
273
+ )
274
+ rewrite_response.raise_for_status()
275
+ rewritten_query = (
276
+ rewrite_response.json()
277
+ .get("message", {})
278
+ .get("content", user_question)
279
+ .strip()
280
+ )
281
+ print(f"[DEBUG] rewritten query: {rewritten_query}")
282
+
283
+ # 2. 질문 임베딩 (리라이팅된 쿼리 사용)
284
+ question_embedding = get_embedding(rewritten_query)
285
+
286
+ # 3. 하이브리드 검색: 벡터 검색 + 키워드 검색
287
+ vector_chunks = search_similar_embeddings(question_embedding, document_id)
288
+ keyword_chunks = search_by_keyword(user_question, document_id)
289
+
290
+ # 중복 제거 후 합침
291
+ seen_contents = set()
292
+ all_chunks_content = []
293
+ for chunk in vector_chunks:
294
+ content = chunk["content"]
295
+ if content not in seen_contents:
296
+ seen_contents.add(content)
297
+ all_chunks_content.append(content)
298
+ for chunk in keyword_chunks:
299
+ content = chunk["content"]
300
+ if content not in seen_contents:
301
+ seen_contents.add(content)
302
+ all_chunks_content.append(content)
303
+
304
+ print(
305
+ f"[DEBUG] vector={len(vector_chunks)}, keyword={len(keyword_chunks)}, merged={len(all_chunks_content)}"
306
+ )
307
 
308
+ # 4. 빈 결과 방어: 검색 결과가 없으면 즉시 반환
309
+ if not all_chunks_content:
310
+ return {"answer": "문서에서 해당 정보를 찾을 수 없습니다.", "sources": []}
311
 
312
+ # 5. 리랭킹: Cross-encoder로 상위 5개 선별
313
+ reranked_chunks = rerank(user_question, all_chunks_content, top_k=5)
314
+ print(f"[DEBUG] reranked top {len(reranked_chunks)} chunks")
315
+
316
+ # 6. 프롬프트 구성
317
+ context = "\n".join(reranked_chunks)
318
 
319
  system_prompt = """
320
  [역할]
 
338
  - 근거:
339
  - 한계/추가 확인 필요사항:"""
340
 
341
+ # 7. LLM 응답 생성
342
  messages = [
343
  {"role": "system", "content": system_prompt},
344
  {
 
360
 
361
  return {
362
  "answer": answer,
363
+ "sources": reranked_chunks,
364
  }
365
 
366
  except requests.exceptions.ConnectionError:
app/supabase_utils.py CHANGED
@@ -87,8 +87,8 @@ def save_embeddings_batch(
87
  def search_similar_embeddings(
88
  query_embedding: List[float],
89
  document_id: str,
90
- limit: int = 5,
91
- similarity_threshold: float = 0.7,
92
  ) -> List[Dict[str, Any]]:
93
  """
94
  [TODO Day 3] 사용자의 질문 벡터와 유사한 문서 청크를 검색하는 함수입니다.
@@ -116,13 +116,36 @@ def search_similar_embeddings(
116
  },
117
  ).execute()
118
 
 
 
 
 
 
 
119
  filtered = [
120
  row for row in result.data if row.get("similarity", 0) >= similarity_threshold
121
  ]
122
 
 
 
123
  return filtered
124
 
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  def get_document_id_by_hash(file_hash: str) -> str:
127
  result = supabase.rpc("get_document_by_hash", {"p_hash": file_hash}).execute()
128
  if result.data:
 
87
  def search_similar_embeddings(
88
  query_embedding: List[float],
89
  document_id: str,
90
+ limit: int = 10,
91
+ similarity_threshold: float = 0.6,
92
  ) -> List[Dict[str, Any]]:
93
  """
94
  [TODO Day 3] 사용자의 질문 벡터와 유사한 문서 청크를 검색하는 함수입니다.
 
116
  },
117
  ).execute()
118
 
119
+ # 디버깅: 필터링 전 결과 확인
120
+ for row in result.data:
121
+ print(
122
+ f"[DEBUG] similarity={row.get('similarity', 'N/A'):.4f} | content preview: {row.get('content', '')[:80]}"
123
+ )
124
+
125
  filtered = [
126
  row for row in result.data if row.get("similarity", 0) >= similarity_threshold
127
  ]
128
 
129
+ print(f"[DEBUG] total={len(result.data)}, filtered(>=0.7)={len(filtered)}")
130
+
131
  return filtered
132
 
133
 
134
+ def search_by_keyword(
135
+ query: str, document_id: str, limit: int = 5
136
+ ) -> List[Dict[str, Any]]:
137
+ """키워드 기반 검색 (벡터 검색 보완용). 고유명사 등 정확한 매칭이 필요할 때 사용."""
138
+ result = (
139
+ supabase.table("document_chunks")
140
+ .select("content")
141
+ .eq("document_id", document_id)
142
+ .ilike("content", f"%{query}%")
143
+ .limit(limit)
144
+ .execute()
145
+ )
146
+ return result.data
147
+
148
+
149
  def get_document_id_by_hash(file_hash: str) -> str:
150
  result = supabase.rpc("get_document_by_hash", {"p_hash": file_hash}).execute()
151
  if result.data: