-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
436 lines (368 loc) · 13.7 KB
/
api_server.py
File metadata and controls
436 lines (368 loc) · 13.7 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
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
"""
AllerLens FastAPI 서버
FastAPI 자체 REST API 제공
"""
from fastapi import FastAPI, File, UploadFile, Form, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from typing import List, Optional, Dict
import uvicorn
import os
import shutil
import tempfile
import time
from datetime import datetime
# AllerLens 모듈 임포트
from main import analyze_food_label
from config import validate_config
# ============================================
# FastAPI 앱 초기화
# ============================================
app = FastAPI(
title="AllerLens API",
description="AI 기반 식품 알레르기 분석 API",
version="1.0.0",
docs_url="/api/docs",
redoc_url="/api/redoc"
)
# CORS 설정 (Spring Boot에서 호출 가능하도록)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 프로덕션에서는 특정 도메인만 허용
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ============================================
# Pydantic 모델 (Request/Response)
# ============================================
class UserProfile(BaseModel):
"""사용자 프로필"""
name: str = Field(..., description="사용자 이름", example="홍길동")
allergies: List[str] = Field(..., description="알레르기 목록", example=["우유", "땅콩"])
intolerances: Optional[List[str]] = Field(default=[], description="불내증 목록", example=["유당"])
class Config:
json_schema_extra = {
"example": {
"name": "홍길동",
"allergies": ["우유", "땅콩"],
"intolerances": ["유당"]
}
}
class AnalysisRequest(BaseModel):
"""분석 요청 (JSON 바디)"""
image_url: Optional[str] = Field(None, description="이미지 URL (URL 또는 파일 업로드 중 하나 필수)")
user_profile: UserProfile = Field(..., description="사용자 프로필")
class Config:
json_schema_extra = {
"example": {
"image_url": "https://example.com/food_label.jpg",
"user_profile": {
"name": "홍길동",
"allergies": ["우유", "땅콩"],
"intolerances": ["유당"]
}
}
}
class AllergenInfo(BaseModel):
"""알레르기 성분 정보"""
ingredient: str
matched_allergen: Optional[str] = None
risk_level: Optional[str] = None
symptoms: Optional[List[str]] = None
reason: Optional[str] = None
class AnalysisResponse(BaseModel):
"""분석 응답"""
success: bool = Field(..., description="분석 성공 여부")
risk_level: str = Field(..., description="위험도 (HIGH/MEDIUM/LOW/SAFE)")
risk_score: int = Field(..., description="위험도 점수 (0-100)")
explanation: str = Field(..., description="사용자 친화적 설명")
matched_allergens: List[AllergenInfo] = Field(..., description="매칭된 알레르기 성분")
safe_ingredients: List[str] = Field(..., description="안전한 성분")
critical_warnings: List[str] = Field(..., description="중요 경고")
processing_time: float = Field(..., description="처리 시간 (초)")
timestamp: str = Field(..., description="분석 시간")
class Config:
json_schema_extra = {
"example": {
"success": True,
"risk_level": "HIGH",
"risk_score": 10,
"explanation": "이 제품은 드시지 마세요. ❌ 홍길동님이 알러지가 있으신 우유가 들어있어요...",
"matched_allergens": [
{
"ingredient": "우유",
"matched_allergen": "우유",
"risk_level": "HIGH",
"symptoms": ["두드러기", "호흡곤란"],
"reason": "직접 매칭"
}
],
"safe_ingredients": ["밀가루", "설탕"],
"critical_warnings": ["우유: 높은 위험"],
"processing_time": 12.32,
"timestamp": "2024-12-06T10:30:00"
}
}
class ErrorResponse(BaseModel):
"""에러 응답"""
success: bool = False
error: str
detail: Optional[str] = None
timestamp: str
class HealthResponse(BaseModel):
"""헬스체크 응답"""
status: str
message: str
timestamp: str
rag_backend: str
services: Dict[str, str]
class AllergenListResponse(BaseModel):
"""알레르기 목록 응답"""
allergens: List[Dict[str, str]]
count: int
# ============================================
# 헬퍼 함수
# ============================================
def save_upload_file(upload_file: UploadFile) -> str:
"""
업로드된 파일을 임시 디렉토리에 저장
Args:
upload_file: FastAPI UploadFile
Returns:
저장된 파일 경로
"""
try:
# 임시 파일 생성
suffix = os.path.splitext(upload_file.filename)[1]
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp_file:
shutil.copyfileobj(upload_file.file, tmp_file)
return tmp_file.name
finally:
upload_file.file.close()
def cleanup_temp_file(file_path: str):
"""임시 파일 삭제"""
try:
if os.path.exists(file_path):
os.remove(file_path)
except Exception as e:
print(f"파일 삭제 실패: {e}")
# ============================================
# API 엔드포인트
# ============================================
@app.get("/", tags=["Root"])
async def root():
"""API 루트"""
return {
"message": "AllerLens API",
"version": "1.0.0",
"docs": "/api/docs"
}
@app.get("/api/v1/health", response_model=HealthResponse, tags=["Health"])
async def health_check():
"""
헬스체크 엔드포인트
서버 상태 및 설정 확인
"""
from config import RAG_BACKEND, CLOVA_OCR_URL, UPSTAGE_API_KEY
services = {
"clova_ocr": "연결됨" if CLOVA_OCR_URL else "미설정",
"upstage_llm": "연결됨" if UPSTAGE_API_KEY else "미설정",
"rag_backend": RAG_BACKEND
}
return HealthResponse(
status="healthy",
message="AllerLens API is running",
timestamp=datetime.now().isoformat(),
rag_backend=RAG_BACKEND,
services=services
)
@app.post(
"/api/v1/analyze",
response_model=AnalysisResponse,
tags=["Analysis"],
summary="식품 라벨 분석",
description="이미지를 업로드하거나 URL을 제공하여 식품 알레르기 분석 수행"
)
async def analyze_image(
image: Optional[UploadFile] = File(None, description="식품 라벨 이미지 파일"),
name: str = Form(..., description="사용자 이름"),
allergies: str = Form(..., description="알레르기 목록 (쉼표로 구분)"),
intolerances: Optional[str] = Form("", description="불내증 목록 (쉼표로 구분)")
):
"""
식품 라벨 이미지 분석
**사용 방법**:
- **Multipart Form 방식**: 이미지 파일과 사용자 정보를 함께 전송
- **필수 파라미터**: image (파일), name (이름), allergies (알레르기)
- **옵션 파라미터**: intolerances (불내증)
**예시**:
```bash
curl -X POST "http://localhost:8000/api/v1/analyze" \
-F "image=@food_label.jpg" \
-F "name=홍길동" \
-F "allergies=우유,땅콩" \
-F "intolerances=유당"
```
"""
temp_file_path = None
try:
# 1. 이미지 파일 검증
if not image:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="이미지 파일이 필요합니다."
)
# 파일 형식 검증
allowed_extensions = {".jpg", ".jpeg", ".png", ".pdf"}
file_ext = os.path.splitext(image.filename)[1].lower()
if file_ext not in allowed_extensions:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"지원하지 않는 파일 형식입니다. 허용: {allowed_extensions}"
)
# 2. 임시 파일 저장
temp_file_path = save_upload_file(image)
# 3. 사용자 프로필 구성
user_profile = {
"name": name,
"allergies": [a.strip() for a in allergies.split(",") if a.strip()],
"intolerances": [i.strip() for i in intolerances.split(",") if i.strip()] if intolerances else []
}
# 4. AllerLens 분석 실행
result = analyze_food_label(
image_path=temp_file_path,
user_profile=user_profile
)
# 5. 응답 구성
if result.get("risk_level") == "ERROR":
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=result.get("explanation", "분석 중 오류가 발생했습니다.")
)
# AllergenInfo 리스트 구성
matched_allergens_list = [
AllergenInfo(
ingredient=allergen.get("ingredient", ""),
matched_allergen=allergen.get("matched_allergen"),
risk_level=allergen.get("risk_level"),
symptoms=allergen.get("symptoms", []),
reason=allergen.get("reason")
)
for allergen in result.get("matched_allergens", [])
]
return AnalysisResponse(
success=True,
risk_level=result.get("risk_level", "UNKNOWN"),
risk_score=result.get("risk_score", 0),
explanation=result.get("explanation", ""),
matched_allergens=matched_allergens_list,
safe_ingredients=result.get("safe_ingredients", []),
critical_warnings=result.get("critical_warnings", []),
processing_time=result.get("processing_time", 0),
timestamp=datetime.now().isoformat()
)
except HTTPException:
raise
except Exception as e:
print(f"분석 중 에러 발생: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"분석 중 오류가 발생했습니다: {str(e)}"
)
finally:
# 임시 파일 삭제
if temp_file_path:
cleanup_temp_file(temp_file_path)
@app.get(
"/api/v1/allergens",
response_model=AllergenListResponse,
tags=["Allergens"],
summary="알레르기 목록 조회",
description="시스템에 등록된 알레르기 종류 조회"
)
async def get_allergens():
"""
등록된 알레르기 목록 조회
**응답 예시**:
```json
{
"allergens": [
{"name": "우유", "type": "dairy"},
{"name": "밀", "type": "gluten"}
],
"count": 2
}
```
"""
try:
from config import RAG_BACKEND, FAISS_CSV_PATH
import pandas as pd
allergens_list = []
if RAG_BACKEND == "faiss":
# FAISS CSV에서 읽기
df = pd.read_csv(FAISS_CSV_PATH)
allergens_list = [
{
"name": row["ingredient"],
"type": row["allergy_type"],
"notes": row.get("notes", "")
}
for _, row in df.iterrows()
]
else:
# Pinecone은 하드코딩된 목록 반환
allergens_list = [
{"name": "우유", "type": "dairy", "notes": "유제품 알레르기"},
{"name": "밀", "type": "gluten", "notes": "글루텐 알레르기"},
{"name": "대두", "type": "legume", "notes": "콩 알레르기"},
{"name": "땅콩", "type": "legume", "notes": "견과류 알레르기"},
{"name": "계란", "type": "egg", "notes": "계란 알레르기"},
{"name": "갑각류", "type": "seafood", "notes": "갑각류 알레르기"},
{"name": "생선", "type": "seafood", "notes": "어류 알레르기"},
{"name": "견과류", "type": "nut", "notes": "견과류 알레르기"}
]
return AllergenListResponse(
allergens=allergens_list,
count=len(allergens_list)
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"알레르기 목록 조회 실패: {str(e)}"
)
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
"""전역 예외 핸들러"""
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content=ErrorResponse(
success=False,
error="Internal Server Error",
detail=str(exc),
timestamp=datetime.now().isoformat()
).dict()
)
# ============================================
# 서버 시작
# ============================================
@app.on_event("startup")
async def startup_event():
"""서버 시작 시 설정 검증"""
try:
validate_config()
print("AllerLens API 서버 시작")
print(f"API 문서: http://localhost:8000/api/docs")
except Exception as e:
print(f"설정 검증 실패: {e}")
raise
if __name__ == "__main__":
# 서버 실행
uvicorn.run(
"api_server:app",
host="0.0.0.0",
port=8000,
reload=True, # 개발 중에는 True, 프로덕션에서는 False
log_level="info"
)