-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrag_faiss.py
More file actions
371 lines (298 loc) · 10.9 KB
/
rag_faiss.py
File metadata and controls
371 lines (298 loc) · 10.9 KB
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
"""
rag_faiss.py - FAISS 기반 RAG 엔진
SentenceTransformer + FAISS를 사용한 알레르기 정보 검색
기존 Pinecone 기반 rag_tool.py를 대체합니다.
"""
import os
import numpy as np
import pandas as pd
import faiss
import json
from typing import List, Dict
from sentence_transformers import SentenceTransformer
from langchain.tools import tool
# ============================================
# 설정
# ============================================
# CSV 파일 경로 (프로젝트 루트 기준)
CSV_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"data",
"allergens_small_extended.csv"
)
# 임베딩 모델 (로컬에서 빠르고 가벼운 모델)
EMBEDDING_MODEL = "all-MiniLM-L6-v2"
# OCR 오타 정규화 맵
NORM_MAP = {
"mieko": "milk",
"soya": "soy",
"wheatt": "wheat",
"wheat flour": "wheat",
"milk powder": "milk",
"almond bits": "almond",
"pork meat": "pork",
# 한글 추가
"우유": "milk",
"밀가루": "wheat",
"소맥분": "wheat",
"대두": "soy",
"콩": "soy",
"땅콩": "peanut",
"계란": "egg",
"난백": "egg",
"난황": "egg"
}
# ============================================
# 헬퍼 함수
# ============================================
def clean_and_tokenize(ocr_text: str) -> List[str]:
"""
OCR 텍스트를 정규화하고 토큰화
Args:
ocr_text: OCR 결과 텍스트
Returns:
정규화된 성분 토큰 리스트
"""
import re
s = str(ocr_text).lower()
s = re.sub(r"[^a-z0-9가-힣, ]", " ", s) # 한글 지원
# "ingredients" 또는 "원재료명" 이후만 추출
if "ingredients" in s:
s = s.split("ingredients")[-1]
elif "원재료명" in s or "원재료" in s:
s = s.split("원재료")[-1]
# 쉼표로 분리
tokens = [t.strip() for t in s.split(",") if t.strip()]
# 정규화 맵 적용
normalized = []
for t in tokens:
# 정규화 맵 체크
matched = False
for k, v in NORM_MAP.items():
if k in t:
t = v
matched = True
break
normalized.append(t)
return normalized
def load_allergen_db(csv_path: str = CSV_PATH) -> pd.DataFrame:
"""
알레르기 CSV 데이터 로드
Args:
csv_path: CSV 파일 경로
Returns:
DataFrame
"""
if not os.path.exists(csv_path):
raise FileNotFoundError(
f"Allergen CSV not found at {csv_path}\n"
f"Please ensure the CSV file is in the correct location."
)
df = pd.read_csv(csv_path)
# doc_text 컬럼 생성 (검색용)
if "doc_text" not in df.columns:
df["doc_text"] = (
df["ingredient"].astype(str) + " - " +
df["allergy_type"].astype(str) + " - " +
df["notes"].astype(str)
)
return df
# ============================================
# RAG 엔진 클래스
# ============================================
class RagEngine:
"""FAISS 기반 RAG 엔진"""
def __init__(self, df: pd.DataFrame = None, model_name: str = EMBEDDING_MODEL):
"""
RAG 엔진 초기화
Args:
df: 알레르기 데이터프레임
model_name: SentenceTransformer 모델명
"""
self.df = df if df is not None else load_allergen_db()
print("📦 임베딩 모델 로딩 중... (첫 실행시 모델 다운로드)")
self.model = SentenceTransformer(model_name)
# 문서 임베딩 생성
print("🔄 알레르기 데이터베이스 임베딩 생성 중...")
self.doc_texts = self.df["doc_text"].tolist()
self.doc_embeddings = self.model.encode(
self.doc_texts,
normalize_embeddings=True,
show_progress_bar=False
)
self.doc_embeddings = np.array(self.doc_embeddings).astype("float32")
# FAISS 인덱스 구축
self.dimension = self.doc_embeddings.shape[1]
self.index = faiss.IndexFlatL2(self.dimension)
self.index.add(self.doc_embeddings)
print(f"✅ FAISS 인덱스 구축 완료 ({self.index.ntotal}개 문서)")
def search(self, token: str, top_k: int = 1) -> List[Dict]:
"""
단일 토큰 검색
Args:
token: 검색할 성분명
top_k: 반환할 결과 개수
Returns:
매칭 결과 리스트
"""
# 토큰 임베딩
emb = self.model.encode([token], normalize_embeddings=True).astype("float32")
# FAISS 검색
distances, indices = self.index.search(emb, top_k)
results = []
for dist, idx in zip(distances[0], indices[0]):
# 거리가 너무 크면 매칭 안 됨
if dist > 1.5: # 임계값 (조정 가능)
continue
results.append({
"token": token,
"ingredient": self.df.loc[idx, "ingredient"],
"allergy_type": self.df.loc[idx, "allergy_type"],
"notes": self.df.loc[idx, "notes"],
"distance": float(dist),
"confidence": 1.0 - min(float(dist) / 2.0, 1.0) # 거리를 신뢰도로 변환
})
return results
def search_multiple(self, tokens: List[str], top_k: int = 1) -> List[Dict]:
"""
여러 토큰 검색
Args:
tokens: 검색할 성분 리스트
top_k: 각 토큰당 반환할 결과 개수
Returns:
모든 매칭 결과 리스트
"""
all_results = []
for token in tokens:
matches = self.search(token, top_k=top_k)
if matches:
all_results.extend(matches)
return all_results
# ============================================
# 싱글톤 엔진
# ============================================
_rag_engine = None
def get_rag_engine() -> RagEngine:
"""RAG 엔진 싱글톤"""
global _rag_engine
if _rag_engine is None:
df = load_allergen_db()
_rag_engine = RagEngine(df=df)
return _rag_engine
# ============================================
# LangChain Tool 정의
# ============================================
@tool
def search_allergen_info(ingredients: List[str]) -> str:
"""
식품 성분 리스트를 입력받아 FAISS에서 알레르기 정보를 검색합니다.
Args:
ingredients: 검색할 성분 리스트. 예: ["milk", "wheat", "soy", "sugar"]
Returns:
각 성분에 대한 알레르기 정보를 담은 JSON 문자열
Example:
>>> search_allergen_info(["milk", "wheat"])
'[{"ingredient": "milk", "matched": true, ...}, ...]'
"""
engine = get_rag_engine()
# 정규화
normalized_ingredients = []
for ing in ingredients:
ing_lower = ing.lower().strip()
# 정규화 맵 적용
for k, v in NORM_MAP.items():
if k in ing_lower:
ing_lower = v
break
normalized_ingredients.append(ing_lower)
# 검색
all_matches = engine.search_multiple(normalized_ingredients, top_k=1)
# 결과 포맷팅 (기존 Pinecone 형식과 호환)
results = []
for ingredient in ingredients:
# 해당 성분의 매칭 찾기
matched = [m for m in all_matches if m["token"].lower() in ingredient.lower()]
if matched:
best_match = matched[0]
results.append({
"ingredient": ingredient,
"matched": True,
"matched_allergen": best_match["ingredient"],
"allergen_name_ko": best_match["ingredient"], # 한글명 (CSV에 추가 필요시)
"allergen_type": best_match["allergy_type"],
"severity": "HIGH" if best_match["allergy_type"] in ["dairy", "nut", "seafood"] else "MEDIUM",
"cross_reactive": [], # CSV에 추가 가능
"symptoms": [], # CSV에 추가 가능
"alternative_names": [],
"confidence": best_match["confidence"],
"safe": False,
"notes": best_match["notes"]
})
else:
# 매칭 안 됨 (안전)
results.append({
"ingredient": ingredient,
"matched": False,
"matched_allergen": None,
"safe": True,
"confidence": 0.0,
"note": "알려진 알레르기 성분 아님"
})
return json.dumps(results, ensure_ascii=False, indent=2)
# ============================================
# 통합 함수
# ============================================
def run_allergy_check(ocr_text: str) -> Dict:
"""
AllerLens 통합 함수 (main.py용)
Args:
ocr_text: OCR 추출 텍스트
Returns:
{
"ingredients_detected": [...],
"allergy_types": [...],
"notes": [...],
"explanation_basic": "..."
}
"""
# 토큰화 및 정규화
tokens = clean_and_tokenize(ocr_text)
# RAG 검색
result_json = search_allergen_info.invoke({"ingredients": tokens})
matches = json.loads(result_json)
# 결과 추출
detected = [m["matched_allergen"] for m in matches if m.get("matched")]
allergy_types = list({m["allergen_type"] for m in matches if m.get("matched")})
notes = [m.get("notes", "") for m in matches if m.get("matched")]
# 기본 설명 생성
if detected:
explanation = f"이 제품에는 {', '.join(detected)}이(가) 포함되어 있습니다. 알레르기 유형: {', '.join(allergy_types)}"
else:
explanation = "주요 알레르기 성분이 감지되지 않았습니다."
return {
"ingredients_detected": detected,
"allergy_types": allergy_types,
"notes": notes,
"explanation_basic": explanation,
"raw_matches": matches
}
# ============================================
# 테스트 코드
# ============================================
if __name__ == "__main__":
print("=== FAISS RAG 엔진 테스트 ===\n")
# 테스트 케이스
tests = [
"Ingredients: sugar, mieko, soya, wheatt",
"원재료명: 우유, 밀가루, 설탕",
"Ingredients: wheat flour, MILK powder, alcohol, salt",
"Ingredients: pea protein, almond bits, sugar, pork"
]
for test_text in tests:
print(f"\n📄 입력: {test_text}")
result = run_allergy_check(test_text)
print(f"✅ 결과:")
print(f" - 감지된 성분: {result['ingredients_detected']}")
print(f" - 알레르기 유형: {result['allergy_types']}")
print(f" - 설명: {result['explanation_basic']}")
print()