Skip to content

Commit

Permalink
fix: bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
sspzoa committed Oct 11, 2024
1 parent 58d9e05 commit e1178e4
Show file tree
Hide file tree
Showing 9 changed files with 17 additions and 75 deletions.
4 changes: 2 additions & 2 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@

from app.dependencies.auth import verify_token
from app.routes import ping, root
from app.routes.food import ingredient_detect
from app.routes.recipe import recipe, ingredient, cooking_step
from app.routes.refrigerator import ingredient_detect

app = FastAPI(
title="Deening API",
Expand Down Expand Up @@ -32,4 +32,4 @@
app.include_router(recipe.router, dependencies=[Depends(verify_token)])
app.include_router(ingredient.router, dependencies=[Depends(verify_token)])
app.include_router(cooking_step.router, dependencies=[Depends(verify_token)])
app.include_router(ingredient_detect.router, dependencies=[Depends(verify_token)])
app.include_router(ingredient_detect.router, dependencies=[Depends(verify_token)])
2 changes: 1 addition & 1 deletion app/models/error_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@


class ErrorResponse(BaseModel):
error: str
error: str
2 changes: 0 additions & 2 deletions app/models/recipe/cooking_step_models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import List

from pydantic import BaseModel


Expand Down
File renamed without changes.
29 changes: 6 additions & 23 deletions app/routes/recipe/cooking_step.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

router = APIRouter()


@router.post("/cooking_step", tags=["Recipe"], response_model=CookingStepResponse,
responses={400: {"model": ErrorResponse}, 404: {"model": ErrorResponse}})
async def get_or_create_cooking_step_info(request: CookingStepRequest):
Expand Down Expand Up @@ -42,15 +43,16 @@ async def get_or_create_cooking_step_info(request: CookingStepRequest):
recipe_context = {
"name": recipe['name'],
"ingredients": recipe['ingredients'],
"instructions": recipe['instructions'][request.step_number - 1] if request.step_number <= len(recipe['instructions']) else None
"instructions": recipe['instructions'][request.step_number - 1] if request.step_number <= len(
recipe['instructions']) else None
}

cooking_step_prompt = f"""제공된 레시피에 대한 자세한 조리 과정 정보를 JSON 형식으로 생성해주세요. 다음 구조를 따라주세요:
{{
"recipe_id": "레시피 ID",
"step_number": 단계 번호,
"description": "조리 과정에 대한 상세한 설명",
"description": "조리 과정에 대한 상세한 설명과 팁",
}}
레시피 ID: {request.recipe_id}
Expand All @@ -74,10 +76,8 @@ async def get_or_create_cooking_step_info(request: CookingStepRequest):
image_prompt = f"""A high-quality, detailed photo demonstrating the cooking step for {recipe_context['name']}, step number {cooking_step.step_number}:
- Description: {cooking_step.description}
- Tools used: {', '.join(cooking_step.tools_needed)}
- Ingredients involved: {', '.join(cooking_step.ingredients_used)}
The image should clearly show the action being performed, with visible ingredients and tools.
The image should clearly show the action being performed.
Ensure the lighting is bright and even, showcasing the details of the cooking process.
The image should be from a slightly elevated angle to give a clear view of the cooking surface and the chef's hands (if applicable).
"""
Expand All @@ -91,7 +91,7 @@ async def get_or_create_cooking_step_info(request: CookingStepRequest):
)

image_url = image_response.data[0].url
image_base64 = 'data:image/png;base64,' + download_and_encode_image(image_url) # 이미지 다운로드 및 Base64 인코딩
image_base64 = 'data:image/png;base64,' + download_and_encode_image(image_url) # 이미지 다운로드 및 Base64 인코딩

cooking_step_dict = cooking_step.model_dump()
cooking_step_dict['image_base64'] = image_base64 # URL 대신 Base64 인코딩된 이미지 저장
Expand All @@ -103,20 +103,3 @@ async def get_or_create_cooking_step_info(request: CookingStepRequest):
raise HTTPException(status_code=400, detail="생성된 조리 과정 정보를 JSON으로 파싱할 수 없습니다.")
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))

@router.get("/cooking_step/{cooking_step_id}", tags=["Recipe"], response_model=CookingStepResponse,
responses={404: {"model": ErrorResponse}})
async def get_cooking_step_by_id(cooking_step_id: str):
"""
주어진 ID에 대한 조리 단계 정보를 반환합니다.
"""
try:
cooking_step_data = await cooking_step_collection.find_one({"_id": ObjectId(cooking_step_id)})
if not cooking_step_data:
raise HTTPException(status_code=404, detail="조리 단계 정보를 찾을 수 없습니다.")

image_base64 = cooking_step_data.pop('image_base64', None)
cooking_step = CookingStep(**cooking_step_data)
return CookingStepResponse(id=str(cooking_step_data['_id']), cooking_step=cooking_step, image_base64=image_base64)
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
21 changes: 1 addition & 20 deletions app/routes/recipe/ingredient.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import json

from bson import ObjectId
from fastapi import APIRouter, HTTPException

from app.config import client as openai_client
Expand All @@ -11,6 +10,7 @@

router = APIRouter()


@router.post("/ingredient", tags=["Recipe"], response_model=IngredientResponse,
responses={400: {"model": ErrorResponse}})
async def get_or_create_ingredient(request: IngredientRequest):
Expand Down Expand Up @@ -54,7 +54,6 @@ async def get_or_create_ingredient(request: IngredientRequest):

image_prompt = f"""A high-quality, detailed photo of {ingredient.name}, as described:
- Category: {ingredient.category}
- Description: {ingredient.description}
The image should clearly show the ingredient in its natural or commonly found form.
Expand Down Expand Up @@ -83,21 +82,3 @@ async def get_or_create_ingredient(request: IngredientRequest):
raise HTTPException(status_code=400, detail="생성된 식재료 정보를 JSON으로 파싱할 수 없습니다.")
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))

@router.get("/ingredient/{ingredient_id}", tags=["Recipe"], response_model=IngredientResponse,
responses={404: {"model": ErrorResponse}})
async def get_ingredient_by_id(ingredient_id: str):
"""
주어진 ID에 대한 식재료 정보를 반환합니다.
"""
try:
ingredient_data = await ingredient_collection.find_one({"_id": ObjectId(ingredient_id)})
if not ingredient_data:
raise HTTPException(status_code=404, detail="식재료 정보를 찾을 수 없습니다.")

image_base64 = ingredient_data.pop('image_base64', None)
ingredient_id = str(ingredient_data.pop('_id'))
ingredient = Ingredient(**ingredient_data)
return IngredientResponse(ingredient=ingredient, image_base64=image_base64, id=ingredient_id)
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
25 changes: 2 additions & 23 deletions app/routes/recipe/recipe.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import json

from bson import ObjectId
from fastapi import APIRouter, HTTPException

from app.config import client as openai_client
Expand All @@ -11,6 +10,7 @@

router = APIRouter()


@router.post("/recipe", tags=["Recipe"], response_model=RecipeResponse, responses={400: {"model": ErrorResponse}})
async def get_or_create_recipe(request: RecipeRequest):
"""
Expand Down Expand Up @@ -78,10 +78,6 @@ async def get_or_create_recipe(request: RecipeRequest):
Recipe details:
- Description: {recipe.description}
- Main ingredients: {', '.join([ingredient.name for ingredient in recipe.ingredients[:5]])}
- Cuisine tags: {', '.join(recipe.tags)}
The image should clearly show the main ingredients and reflect the cuisine style indicated by the tags.
Ensure the presentation matches the difficulty level of '{recipe.difficulty}' and serves {recipe.servings}.
"""

image_response = openai_client.images.generate(
Expand All @@ -93,7 +89,7 @@ async def get_or_create_recipe(request: RecipeRequest):
)

image_url = image_response.data[0].url
image_base64 = 'data:image/png;base64,' + download_and_encode_image(image_url) # 이미지 다운로드 및 Base64 인코딩
image_base64 = 'data:image/png;base64,' + download_and_encode_image(image_url) # 이미지 다운로드 및 Base64 인코딩

recipe_dict = recipe.model_dump()
recipe_dict['image_base64'] = image_base64 # URL 대신 Base64 인코딩된 이미지 저장
Expand All @@ -105,20 +101,3 @@ async def get_or_create_recipe(request: RecipeRequest):
raise HTTPException(status_code=400, detail="생성된 레시피를 JSON으로 파싱할 수 없습니다.")
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))

@router.get("/recipe/{recipe_id}", tags=["Recipe"], response_model=RecipeResponse,
responses={404: {"model": ErrorResponse}})
async def get_recipe_by_id(recipe_id: str):
"""
주어진 ID에 대한 레시피를 반환합니다.
"""
try:
recipe_data = await recipe_collection.find_one({"_id": ObjectId(recipe_id)})
if not recipe_data:
raise HTTPException(status_code=404, detail="레시피를 찾을 수 없습니다.")

image_base64 = recipe_data.pop('image_base64', None)
recipe = Recipe(**recipe_data)
return RecipeResponse(id=str(recipe_data['_id']), recipe=recipe, image_base64=image_base64)
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@

from app.config import client
from app.models.error_models import ErrorResponse
from app.models.food.ingredient_detect_models import IngredientDetectResponse, NoIngredientsFoundResponse
from app.models.refrigerator.ingredient_detect_models import IngredientDetectResponse, NoIngredientsFoundResponse

router = APIRouter()

@router.post("/ingredient_detect", tags=["Food"],

@router.post("/ingredient_detect", tags=["Refrigerator"],
response_model=IngredientDetectResponse,
responses={400: {"model": ErrorResponse}, 404: {"model": NoIngredientsFoundResponse}})
async def ingredient_detect(image: UploadFile = File(...)):
Expand Down Expand Up @@ -78,4 +79,4 @@ async def ingredient_detect(image: UploadFile = File(...)):
raise http_ex
except Exception as e:
logging.error(f"Unexpected error: {str(e)}")
raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")
raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")
2 changes: 1 addition & 1 deletion app/routes/root.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ async def root():
"""
Landing Page
"""
return FileResponse("app/static/index.html")
return FileResponse("app/static/index.html")

0 comments on commit e1178e4

Please sign in to comment.