Prathamesh Sable commited on
Commit
fd00bfb
·
1 Parent(s): 0f54ea3

accepting product request implemention pending

Browse files
Files changed (1) hide show
  1. routers/product.py +62 -40
routers/product.py CHANGED
@@ -28,9 +28,10 @@ from utils.db_utils import add_product_to_database
28
  from utils.vuforia_utils import add_target_to_vuforia, UPLOADED_IMAGES_DIR
29
  from utils.fetch_data import fetch_product_data_from_api
30
  import uuid
 
31
 
32
  # import environment variables
33
- from env import VUFORIA_SERVER_ACCESS_KEY,VUFORIA_SERVER_SECRET_KEY,VUFORIA_TARGET_DATABASE_NAME,VUFORIA_TARGET_DATABASE_ID
34
 
35
  router = APIRouter()
36
 
@@ -83,33 +84,45 @@ def crop_image(image_np, box):
83
 
84
  @router.post("/add")
85
  async def create_product(
86
- request: Request, db: Session = Depends(get_db)
 
87
  ):
88
  """Endpoint to add a new product, its ingredients, and associated markers."""
89
  try:
90
  log_info("Create product endpoint called")
91
- data = await request.json()
92
- print("Received data:", data)
93
-
94
- # Extract product details and data from request body
95
-
96
- image_names: List[str] = data.get("image_names")
97
-
98
- # Parse ProductCreate model from data
 
 
 
 
 
 
 
 
 
 
 
99
  product_create_data = ProductCreate(
100
- product_name=data.get("name"),
101
- ingredients=data.get("ingredients"),
102
- overall_safety_score=data.get("overall_safety_score"),
103
- suitable_diet_types=data.get("suitable_diet_types"),
104
- allergy_warnings=data.get("allergy_warnings"),
105
- usage_recommendations=data.get("usage_recommendations"),
106
- health_insights=data.get("health_insights"),
107
- ingredient_interactions=data.get("ingredient_interactions"),
108
- key_takeaway=data.get("key_takeaway"),
109
- ingredients_count=data.get("ingredients_count"),
110
- user_id=data.get("user_id"),
111
- timestamp=data.get("timestamp"),
112
- ingredient_ids=[]
113
  )
114
 
115
  # Find ingredients and append their IDs
@@ -119,7 +132,7 @@ async def create_product(
119
  if ingredient:
120
  product_create_data.ingredient_ids.append(ingredient.id)
121
 
122
- # Analyze product ingredients and store analysis data
123
  ingredient_results = []
124
  for ingredient_name in product_create_data.ingredients:
125
  ingredient = ingredient_repo.get_ingredient_by_name(ingredient_name)
@@ -136,25 +149,26 @@ async def create_product(
136
  )
137
  product_create_data.ingredients_analysis = product_analysis
138
 
139
- # use repository to add product
140
  product_repo = ProductRepository(db)
141
  product = product_repo.add_product(product_create_data)
142
- product_id=product.id
143
- await add_product_to_database(product_id, image_names, db, data)
144
- return JSONResponse(
145
- {
146
- "message": "Product data and image processed successfully",
147
- "product_id":product_id,
148
- "data":data,
149
- "product_data": product_create_data.model_dump()
150
-
151
- }
152
- )
153
-
154
- except HTTPException as e:
155
- return JSONResponse({"error": e.detail}, status_code=e.status_code)
156
  except Exception as e:
157
- return JSONResponse({"error": str(e)}, status_code=500)
 
 
158
 
159
 
160
  @router.post("/process_image")
@@ -177,6 +191,14 @@ async def process_image_endpoint(image: UploadFile = File(...), db: Session = De
177
  # Check if any objects were detected
178
  if box is None:
179
  log_info("No food objects detected in image")
 
 
 
 
 
 
 
 
180
  return JSONResponse({
181
  "error": "No food objects detected in the image",
182
  "detected": False
 
28
  from utils.vuforia_utils import add_target_to_vuforia, UPLOADED_IMAGES_DIR
29
  from utils.fetch_data import fetch_product_data_from_api
30
  import uuid
31
+ import json
32
 
33
  # import environment variables
34
+ from env import FAKE_TARGET_IMAGE_NAME, SEND_FAKE_TARGET, VUFORIA_SERVER_ACCESS_KEY,VUFORIA_SERVER_SECRET_KEY,VUFORIA_TARGET_DATABASE_NAME,VUFORIA_TARGET_DATABASE_ID
35
 
36
  router = APIRouter()
37
 
 
84
 
85
  @router.post("/add")
86
  async def create_product(
87
+ request: Request,
88
+ db: Session = Depends(get_db)
89
  ):
90
  """Endpoint to add a new product, its ingredients, and associated markers."""
91
  try:
92
  log_info("Create product endpoint called")
93
+ # Get the request body
94
+ form_data = await request.form()
95
+ name = form_data.get("name")
96
+ image_name = form_data.get("image_name")
97
+
98
+ # Extract all ingredients[] fields as a list
99
+ ingredients_list = []
100
+ for key, value in form_data.multi_items():
101
+ if key == "ingredients[]":
102
+ ingredients_list.append(value)
103
+
104
+ log_debug(f"Received product name: {name}")
105
+ log_debug(f"Received ingredients: {ingredients_list}")
106
+ log_debug(f"Received image name: {image_name}")
107
+
108
+ # Save the uploaded image
109
+ image_path = os.path.join(UPLOADED_IMAGES_DIR, image_name)
110
+
111
+ # Create product data model
112
  product_create_data = ProductCreate(
113
+ product_name=name,
114
+ ingredients=ingredients_list,
115
+ overall_safety_score=0, # Default values
116
+ suitable_diet_types=[],
117
+ allergy_warnings=[],
118
+ usage_recommendations="",
119
+ health_insights="",
120
+ ingredient_interactions="",
121
+ key_takeaway="",
122
+ ingredients_count=len(ingredients_list),
123
+ user_id=None, # Can be updated later if needed
124
+ timestamp=None,
125
+ ingredient_ids=[]
126
  )
127
 
128
  # Find ingredients and append their IDs
 
132
  if ingredient:
133
  product_create_data.ingredient_ids.append(ingredient.id)
134
 
135
+ # Analyze product ingredients
136
  ingredient_results = []
137
  for ingredient_name in product_create_data.ingredients:
138
  ingredient = ingredient_repo.get_ingredient_by_name(ingredient_name)
 
149
  )
150
  product_create_data.ingredients_analysis = product_analysis
151
 
152
+ # Add product to database
153
  product_repo = ProductRepository(db)
154
  product = product_repo.add_product(product_create_data)
155
+
156
+ # Add Vuforia target if needed
157
+ await add_product_to_database(product.id, [image_name], db, {
158
+ "name": name,
159
+ "ingredients": ingredients,
160
+ "image_name": image_name,
161
+ })
162
+
163
+ return JSONResponse({
164
+ "message": "Product data and image processed successfully",
165
+ "product_id": product.id,
166
+ "image_name": image_name
167
+ })
 
168
  except Exception as e:
169
+ log_error(f"Error creating product: {e}", e)
170
+ print(e)
171
+ return JSONResponse({"error": str(e)}, status_code=500)
172
 
173
 
174
  @router.post("/process_image")
 
191
  # Check if any objects were detected
192
  if box is None:
193
  log_info("No food objects detected in image")
194
+ # if send dummy target is allowed send default image
195
+ if SEND_FAKE_TARGET:
196
+ return JSONResponse({
197
+ "class_name": "food",
198
+ "score": float(0.24),
199
+ "image_name": FAKE_TARGET_IMAGE_NAME,
200
+ "detected": True
201
+ })
202
  return JSONResponse({
203
  "error": "No food objects detected in the image",
204
  "detected": False