Prathamesh Sable commited on
Commit
c43a7a2
·
1 Parent(s): 7d533c9
interfaces/productModels.py CHANGED
@@ -1,5 +1,5 @@
1
- from typing import List, Dict, Optional
2
- from pydantic import BaseModel
3
  from datetime import datetime
4
 
5
  # Add this class to define the request body structure
@@ -21,41 +21,42 @@ class ProductCreate(BaseModel):
21
  timestamp: datetime
22
  ingredient_ids: List[int]|str
23
 
24
- class SafetyScore(BaseModel):
25
- isPresent: bool
26
- value: Optional[int] = None
27
-
28
- class ProductInfo(BaseModel):
29
- id: Optional[int] = None
30
- name: Optional[str] = None
31
- barcode: Optional[str] = None
32
  image_url: Optional[str] = None
33
- brand: Optional[str] = None
34
- manufacturing_places: Optional[str] = None
35
- stores: Optional[str] = None
36
- countries: Optional[str] = None
 
 
 
37
 
38
  class IngredientInfo(BaseModel):
39
- ingredients_text: Optional[str] = None
40
- ingredients_analysis: Optional[List[Dict[str, Any]]] = None # Adjust type if analysis has a specific structure
41
- additives: Optional[List[str]] = None
42
 
43
  class AllergenInfo(BaseModel):
44
- allergens: Optional[List[str]] = None
45
- traces: Optional[List[str]] = None
46
 
47
- class DietInfo(BaseModel):
48
- vegan: Optional[bool] = None
49
- vegetarian: Optional[bool] = None
 
50
 
51
  class ProductAnalysisResponse(BaseModel):
52
- found: bool
53
- safety_score: SafetyScore
54
- product_info: Optional[ProductInfo] = None
55
- ingredient_info: Optional[IngredientInfo] = None
56
- allergen_info: Optional[AllergenInfo] = None
57
- diet_info: Optional[DietInfo] = None
58
- nutritional_info: Optional[Dict[str, Any]] = None # Adjust type if nutritional info has a specific structure
59
- manufacturing_info: Optional[Dict[str, Any]] = None # Adjust type if manufacturing info has a specific structure
60
 
61
 
 
1
+ from pydantic import BaseModel, Field
2
+ from typing import List, Dict, Any, Optional
3
  from datetime import datetime
4
 
5
  # Add this class to define the request body structure
 
21
  timestamp: datetime
22
  ingredient_ids: List[int]|str
23
 
24
+ class BasicProductInfo(BaseModel):
25
+ product_id: str
26
+ product_name: str
27
+ brand: Optional[str] = ""
28
+ category: Optional[str] = ""
 
 
 
29
  image_url: Optional[str] = None
30
+ barcode: Optional[str] = None
31
+
32
+ class SafetyInfo(BaseModel):
33
+ safety_score: float = 0
34
+ is_safe: bool = False
35
+ warnings: List[str] = []
36
+ benefits: List[str] = []
37
 
38
  class IngredientInfo(BaseModel):
39
+ ingredients_list: List[str] = []
40
+ ingredients_analysis: List[Dict[str, Any]] = []
41
+ ingredient_count: int = 0
42
 
43
  class AllergenInfo(BaseModel):
44
+ allergens: List[str] = []
45
+ has_allergens: bool = False
46
 
47
+ class DietaryInfo(BaseModel):
48
+ dietary_flags: List[str] = []
49
+ is_vegetarian: bool = False
50
+ is_vegan: bool = False
51
 
52
  class ProductAnalysisResponse(BaseModel):
53
+ """Response model for product analysis by marker ID"""
54
+ found: bool = Field(..., description="Whether the product was found")
55
+ basic_info: BasicProductInfo = Field(..., description="Basic product information")
56
+ safety_info: SafetyInfo = Field(..., description="Safety information about the product")
57
+ ingredient_info: IngredientInfo = Field(..., description="Information about ingredients")
58
+ allergen_info: AllergenInfo = Field(..., description="Information about allergens")
59
+ dietary_info: DietaryInfo = Field(..., description="Dietary information")
60
+ timestamp: str = Field(..., description="Timestamp of the response")
61
 
62
 
routers/analysis.py CHANGED
@@ -7,7 +7,7 @@ from fastapi.responses import JSONResponse, FileResponse
7
  import pytz
8
  from sqlalchemy.orm import Session
9
  from typing import List, Dict, Any
10
- from db.models import User, Ingredient
11
  from interfaces.ingredientModels import IngredientAnalysisResult, IngredientRequest
12
  from interfaces.productModels import ProductIngredientsRequest
13
  from logger_manager import log_info, log_error
@@ -138,21 +138,65 @@ async def process_ingredients_endpoint(product_ingredient: ProductIngredientsReq
138
  raise HTTPException(status_code=500, detail="Internal Server Error")
139
 
140
 
141
- @router.get("/get_by_marker_id/{target_id}", response_model=ProductAnalysisResponse)
142
  async def get_analysis_by_marker_id(target_id: str, db: Session = Depends(get_db)):
143
  """
144
  Retrieves product analysis and ingredient information by marker ID.
145
  """
146
  log_info(f"Received request for analysis by marker ID: {target_id}")
147
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  product_data = get_analysis_service_data(db, target_id)
149
-
 
150
  if not product_data:
151
- raise HTTPException(status_code=404, detail=f"Product not found for marker ID: {target_id}")
152
-
153
- log_info(f"Successfully retrieved product data for marker ID: {target_id}")
 
 
 
 
 
 
 
 
 
 
154
  return product_data
155
 
156
  except Exception as e:
157
- log_error(f"Error in get_analysis_by_marker_id: {str(e)}", e)
158
- raise HTTPException(status_code=500, detail="Internal Server Error")
 
 
 
 
 
 
 
 
 
7
  import pytz
8
  from sqlalchemy.orm import Session
9
  from typing import List, Dict, Any
10
+ from db.models import Marker, Product, User, Ingredient
11
  from interfaces.ingredientModels import IngredientAnalysisResult, IngredientRequest
12
  from interfaces.productModels import ProductIngredientsRequest
13
  from logger_manager import log_info, log_error
 
138
  raise HTTPException(status_code=500, detail="Internal Server Error")
139
 
140
 
141
+ @router.get("/get_by_marker_id/{target_id}", response_model=None)
142
  async def get_analysis_by_marker_id(target_id: str, db: Session = Depends(get_db)):
143
  """
144
  Retrieves product analysis and ingredient information by marker ID.
145
  """
146
  log_info(f"Received request for analysis by marker ID: {target_id}")
147
  try:
148
+ # Check if marker exists
149
+ marker = db.query(Marker).filter(Marker.vuforia_id == target_id).first()
150
+ if not marker:
151
+ return JSONResponse(
152
+ status_code=404,
153
+ content={
154
+ "found": False,
155
+ "message": f"Marker with ID {target_id} not found",
156
+ "timestamp": datetime.now(tz=pytz.timezone('Asia/Kolkata')).isoformat()
157
+ }
158
+ )
159
+
160
+ # Check if product exists
161
+ product = db.query(Product).filter(Product.id == marker.product_id).first()
162
+ if not product:
163
+ return JSONResponse(
164
+ status_code=404,
165
+ content={
166
+ "found": False,
167
+ "message": f"Product not found for marker ID: {target_id}",
168
+ "timestamp": datetime.now(tz=pytz.timezone('Asia/Kolkata')).isoformat()
169
+ }
170
+ )
171
+
172
+ # Try to get complete product data
173
  product_data = get_analysis_service_data(db, target_id)
174
+
175
+ # If complete data retrieval fails, return minimal data
176
  if not product_data:
177
+ return JSONResponse(
178
+ status_code=200,
179
+ content={
180
+ "found": True,
181
+ "basic_info": {
182
+ "product_id": str(product.id),
183
+ "product_name": getattr(product, 'product_name', 'Unknown Product'),
184
+ },
185
+ "message": "Product found but analysis data could not be processed",
186
+ "timestamp": datetime.now(tz=pytz.timezone('Asia/Kolkata')).isoformat()
187
+ }
188
+ )
189
+
190
  return product_data
191
 
192
  except Exception as e:
193
+ log_error(f"Error in get_analysis_by_marker_id: {str(e)}", e)
194
+ return JSONResponse(
195
+ status_code=500,
196
+ content={
197
+ "found": False,
198
+ "error": str(e),
199
+ "message": "Error processing request",
200
+ "timestamp": datetime.now(tz=pytz.timezone('Asia/Kolkata')).isoformat()
201
+ }
202
+ )
services/analysis_service.py CHANGED
@@ -1,9 +1,72 @@
1
  from sqlalchemy.orm import Session
2
- from db.models import Marker, Product
3
  from utils.analysis_utils import format_product_analysis_response
4
- from utils.logger_manager import log_info, log_error
5
  from interfaces.productModels import ProductAnalysisResponse
6
- from typing import Optional
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  def get_product_data_by_marker_id(db: Session, target_id: str) -> Optional[ProductAnalysisResponse]:
9
  """
@@ -15,12 +78,11 @@ def get_product_data_by_marker_id(db: Session, target_id: str) -> Optional[Produ
15
 
16
  Returns:
17
  A ProductAnalysisResponse object or None if no product is found.
18
-
19
  """
20
  log_info(f"Attempting to retrieve product data for marker ID: {target_id}")
21
  try:
22
  # Find the marker with the given target_id
23
- marker = db.query(Marker).filter(Marker.target_id == target_id).first()
24
 
25
  if not marker:
26
  log_info(f"No marker found for target ID: {target_id}")
@@ -33,11 +95,26 @@ def get_product_data_by_marker_id(db: Session, target_id: str) -> Optional[Produ
33
  log_info(f"No product found for product_id: {marker.product_id} linked to marker ID: {target_id}")
34
  return None
35
 
36
- log_info(f"Product found for marker ID {target_id}: {product.name}")
37
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  # Format the response using the utility function
39
  response_data = format_product_analysis_response(product)
40
-
41
  return response_data
42
 
43
  except Exception as e:
 
1
  from sqlalchemy.orm import Session
2
+ from db.models import Marker, Product, Ingredient
3
  from utils.analysis_utils import format_product_analysis_response
4
+ from logger_manager import log_info, log_error, log_debug
5
  from interfaces.productModels import ProductAnalysisResponse
6
+ from typing import Optional, List
7
+ import json
8
+
9
+ def get_product_ingredients(db: Session, product: Product) -> List[dict]:
10
+ """
11
+ Fetch ingredients associated with a product.
12
+
13
+ Args:
14
+ db: Database session
15
+ product: Product model instance
16
+
17
+ Returns:
18
+ List of ingredient data dictionaries
19
+ """
20
+ ingredient_data = []
21
+
22
+ try:
23
+ # Check if product has ingredient_ids field
24
+ ingredient_ids = []
25
+
26
+ if hasattr(product, 'ingredient_ids') and product.ingredient_ids:
27
+ # Handle string or list format
28
+ if isinstance(product.ingredient_ids, str):
29
+ try:
30
+ ingredient_ids = [int(id.strip()) for id in product.ingredient_ids.split(',') if id.strip()]
31
+ except:
32
+ try:
33
+ ingredient_ids = json.loads(product.ingredient_ids)
34
+ except:
35
+ log_error(f"Failed to parse ingredient_ids: {product.ingredient_ids}")
36
+ elif isinstance(product.ingredient_ids, list):
37
+ ingredient_ids = product.ingredient_ids
38
+
39
+ log_info(f"Found {len(ingredient_ids)} ingredient IDs for product {product.id}")
40
+
41
+ # Fetch ingredients by IDs
42
+ for ing_id in ingredient_ids:
43
+ ingredient = db.query(Ingredient).filter(Ingredient.id == ing_id).first()
44
+ if ingredient:
45
+ ingredient_data.append({
46
+ "id": ingredient.id,
47
+ "name": ingredient.name,
48
+ "safety_rating": getattr(ingredient, "safety_rating", 5),
49
+ "description": getattr(ingredient, "description", ""),
50
+ "health_effects": getattr(ingredient, "health_effects", []),
51
+ "allergens": getattr(ingredient, "allergens", [])
52
+ })
53
+
54
+ # If we still don't have ingredients, try looking for a relationship
55
+ if not ingredient_data and hasattr(product, 'ingredients') and product.ingredients:
56
+ for ingredient in product.ingredients:
57
+ ingredient_data.append({
58
+ "id": ingredient.id,
59
+ "name": ingredient.name,
60
+ "safety_rating": getattr(ingredient, "safety_rating", 5),
61
+ "description": getattr(ingredient, "description", ""),
62
+ "health_effects": getattr(ingredient, "health_effects", []),
63
+ "allergens": getattr(ingredient, "allergens", [])
64
+ })
65
+
66
+ return ingredient_data
67
+ except Exception as e:
68
+ log_error(f"Error fetching ingredients for product {product.id}: {str(e)}")
69
+ return []
70
 
71
  def get_product_data_by_marker_id(db: Session, target_id: str) -> Optional[ProductAnalysisResponse]:
72
  """
 
78
 
79
  Returns:
80
  A ProductAnalysisResponse object or None if no product is found.
 
81
  """
82
  log_info(f"Attempting to retrieve product data for marker ID: {target_id}")
83
  try:
84
  # Find the marker with the given target_id
85
+ marker = db.query(Marker).filter(Marker.vuforia_id == target_id).first()
86
 
87
  if not marker:
88
  log_info(f"No marker found for target ID: {target_id}")
 
95
  log_info(f"No product found for product_id: {marker.product_id} linked to marker ID: {target_id}")
96
  return None
97
 
98
+ log_info(f"Product found for marker ID {target_id}: {product.product_name}")
99
+
100
+ # Log product fields for debugging
101
+ log_info(f"Product fields: ID={product.id}, Name={product.product_name}")
102
+
103
+ # Get ingredient details if needed
104
+ ingredients = get_product_ingredients(db, product)
105
+ if ingredients:
106
+ log_info(f"Found {len(ingredients)} ingredients for product {product.id}")
107
+ # Update product with ingredients if needed
108
+ if not hasattr(product, 'ingredients_list') or not product.ingredients_list:
109
+ product.ingredients_list = [ing["name"] for ing in ingredients]
110
+
111
+ # Add ingredient analysis data if needed
112
+ if not hasattr(product, 'ingredients_analysis') or not product.ingredients_analysis:
113
+ product.ingredients_analysis = ingredients
114
+
115
  # Format the response using the utility function
116
  response_data = format_product_analysis_response(product)
117
+
118
  return response_data
119
 
120
  except Exception as e:
utils/analysis_utils.py CHANGED
@@ -1,54 +1,167 @@
1
- from typing import Dict, Any, Optional, Any
 
 
 
 
2
  from interfaces.productModels import ProductAnalysisResponse
 
3
 
4
- def format_product_analysis_response(product_data: Optional[Any]) -> Optional[ProductAnalysisResponse]:
5
- """
6
- Formats the retrieved product analysis data into a consistent response structure.
7
-
8
- Args:
9
- product_data: A SQLAlchemy Product object, or None if not found.
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- Returns:
12
- A ProductAnalysisResponse object or None.
13
  """
14
- if product_data is None:
15
- return None
16
-
17
- # Assuming product_data is a SQLAlchemy Product object
18
- safety_score_value = product_data.overall_safety_score
19
- safety_score_isPresent = safety_score_value is not None
20
-
21
- return ProductAnalysisResponse(
22
- found=True,
23
- safety_score={
24
- "isPresent": safety_score_isPresent,
25
- "value": safety_score_value,
26
- },
27
- product_info= {
28
- "id": product_data.id,
29
- "name": product_data.product_name,
30
- "barcode": None, # Assuming barcode is not in Product model
31
- "image_url": None, # Assuming image_url is not in Product model
32
- "brand": None, # Assuming brand is not in Product model
33
- "manufacturing_places": None, # Assuming manufacturing_places is not in Product model
34
- "stores": None, # Assuming stores is not in Product model
35
- "countries": None, # Assuming countries is not in Product model
36
- },
37
- ingredient_info={
38
- "ingredients_text": product_data.ingredients,
39
- "ingredients_analysis": product_data.ingredient_interactions, # Assuming ingredient_interactions maps to analysis
40
- "additives": None, # Assuming additives are not directly in Product model
41
- },
42
- allergen_info= {
43
- "allergens": product_data.allergy_warnings,
44
- "traces": None, # Assuming traces are not directly in Product model
45
- },
46
- diet_info={
47
- "vegan": None, # Assuming vegan is not directly in Product model
48
- "vegetarian": None, # Assuming vegetarian is not directly in Product model
49
- },
50
- nutritional_info=None, # Assuming nutritional_info is not directly in Product model
51
- manufacturing_info=None # Assuming manufacturing_info is not directly in Product model
52
- )
53
-
54
- # Add other helper functions as needed for analysis
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from datetime import datetime
3
+ import pytz
4
+ from typing import Dict, Any, List, Optional
5
+ from db.models import Product
6
  from interfaces.productModels import ProductAnalysisResponse
7
+ from logger_manager import log_info, log_error, log_debug
8
 
9
+ def safe_parse_json(value, default=None):
10
+ """Safely parse a JSON string, with fallback to default value"""
11
+ if value is None:
12
+ return default
13
+
14
+ if not isinstance(value, str):
15
+ return value
16
+
17
+ try:
18
+ # Handle double-quoted JSON strings (e.g. '"Vegetarian"')
19
+ parsed = json.loads(value)
20
+ return parsed
21
+ except json.JSONDecodeError:
22
+ # If it's not valid JSON but might be a comma-separated list
23
+ if ',' in value:
24
+ return [item.strip() for item in value.split(',')]
25
+ return default
26
 
27
+ def format_product_analysis_response(product):
 
28
  """
29
+ Format product data into a ProductAnalysisResponse object with simple error handling.
30
+ """
31
+ try:
32
+ # Print product data for debugging
33
+ log_debug(f"Product object attributes: {dir(product)}")
34
+ log_debug(f"Product __dict__: {product.__dict__}")
35
+
36
+ # Extract and parse the dietary flags - handle the specific case that's failing
37
+ dietary_flags = []
38
+ try:
39
+ diet_types = getattr(product, 'suitable_diet_types', None)
40
+ if diet_types:
41
+ # Parse the JSON string - handle the case where it's a quoted string like '"Vegetarian"'
42
+ parsed_diet = safe_parse_json(diet_types, [])
43
+ if isinstance(parsed_diet, str):
44
+ dietary_flags = [parsed_diet] # Convert single string to list
45
+ elif isinstance(parsed_diet, list):
46
+ dietary_flags = parsed_diet
47
+ except Exception as e:
48
+ log_error(f"Error parsing dietary flags: {e}")
49
+ dietary_flags = []
50
+
51
+ # Parse health insights
52
+ health_insights = {}
53
+ try:
54
+ insights_str = getattr(product, 'health_insights', None)
55
+ if insights_str:
56
+ health_insights = safe_parse_json(insights_str, {})
57
+ except Exception as e:
58
+ log_error(f"Error parsing health insights: {e}")
59
+
60
+ # Extract warnings and benefits from health insights if available
61
+ warnings = []
62
+ benefits = []
63
+ try:
64
+ if isinstance(health_insights, dict):
65
+ warnings = health_insights.get('concerns', [])
66
+ benefits = health_insights.get('benefits', [])
67
+ except Exception as e:
68
+ log_error(f"Error extracting warnings/benefits: {e}")
69
+
70
+ # Parse allergy warnings
71
+ allergens = []
72
+ try:
73
+ allergy_str = getattr(product, 'allergy_warnings', None)
74
+ if allergy_str:
75
+ allergens = safe_parse_json(allergy_str, [])
76
+ except Exception as e:
77
+ log_error(f"Error parsing allergens: {e}")
78
+
79
+ # Parse ingredients list
80
+ ingredients_list = []
81
+ try:
82
+ ing_list = getattr(product, 'ingredients_list', None) or getattr(product, 'ingredients', None)
83
+ if ing_list:
84
+ ingredients_list = safe_parse_json(ing_list, [])
85
+ except Exception as e:
86
+ log_error(f"Error parsing ingredients list: {e}")
87
+
88
+ # Parse ingredients analysis if available
89
+ ingredients_analysis = []
90
+ try:
91
+ ing_analysis = getattr(product, 'ingredients_analysis', [])
92
+ if ing_analysis:
93
+ if isinstance(ing_analysis, list):
94
+ ingredients_analysis = ing_analysis
95
+ else:
96
+ ingredients_analysis = safe_parse_json(ing_analysis, [])
97
+ except Exception as e:
98
+ log_error(f"Error parsing ingredients analysis: {e}")
99
+
100
+ # Construct the final response
101
+ return ProductAnalysisResponse(
102
+ found=True,
103
+ basic_info={
104
+ "product_id": str(product.id),
105
+ "product_name": getattr(product, 'product_name', ''),
106
+ "brand": "",
107
+ "category": "",
108
+ "image_url": None,
109
+ "barcode": None
110
+ },
111
+ safety_info={
112
+ "safety_score": float(getattr(product, 'overall_safety_score', 0)),
113
+ "is_safe": getattr(product, 'overall_safety_score', 0) > 5,
114
+ "warnings": warnings,
115
+ "benefits": benefits
116
+ },
117
+ ingredient_info={
118
+ "ingredients_list": ingredients_list,
119
+ "ingredients_analysis": ingredients_analysis,
120
+ "ingredient_count": getattr(product, 'ingredients_count', 0)
121
+ },
122
+ allergen_info={
123
+ "allergens": allergens,
124
+ "has_allergens": len(allergens) > 0
125
+ },
126
+ dietary_info={
127
+ "dietary_flags": dietary_flags,
128
+ "is_vegetarian": any(flag.lower() == 'vegetarian' for flag in dietary_flags),
129
+ "is_vegan": any(flag.lower() == 'vegan' for flag in dietary_flags)
130
+ },
131
+ timestamp=datetime.now(tz=pytz.timezone('Asia/Kolkata')).isoformat()
132
+ )
133
+ except Exception as e:
134
+ log_error(f"Error in format_product_analysis_response: {str(e)}")
135
+ # Return a minimal valid response rather than raising an exception
136
+ return ProductAnalysisResponse(
137
+ found=True,
138
+ basic_info={
139
+ "product_id": str(product.id),
140
+ "product_name": getattr(product, 'product_name', 'Unknown Product'),
141
+ "brand": "",
142
+ "category": "",
143
+ "image_url": None,
144
+ "barcode": None
145
+ },
146
+ safety_info={
147
+ "safety_score": 0.0,
148
+ "is_safe": False,
149
+ "warnings": [],
150
+ "benefits": []
151
+ },
152
+ ingredient_info={
153
+ "ingredients_list": [],
154
+ "ingredients_analysis": [],
155
+ "ingredient_count": 0
156
+ },
157
+ allergen_info={
158
+ "allergens": [],
159
+ "has_allergens": False
160
+ },
161
+ dietary_info={
162
+ "dietary_flags": [],
163
+ "is_vegetarian": False,
164
+ "is_vegan": False
165
+ },
166
+ timestamp=datetime.now(tz=pytz.timezone('Asia/Kolkata')).isoformat()
167
+ )