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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py - Main Hugging Face Spaces Application
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
+
from sentence_transformers import SentenceTransformer
|
| 6 |
+
import faiss
|
| 7 |
+
import json
|
| 8 |
+
import re
|
| 9 |
+
from typing import List, Dict, Tuple
|
| 10 |
+
import logging
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
|
| 13 |
+
# Configure logging
|
| 14 |
+
logging.basicConfig(level=logging.INFO)
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
class FoodIngredientRAG:
|
| 18 |
+
def __init__(self):
|
| 19 |
+
"""Initialize the RAG system for food ingredient analysis"""
|
| 20 |
+
logger.info("Initializing Food Ingredient RAG System...")
|
| 21 |
+
|
| 22 |
+
# Load sentence transformer for embeddings
|
| 23 |
+
self.model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 24 |
+
|
| 25 |
+
# Initialize ingredient knowledge base
|
| 26 |
+
self.ingredient_db = self._create_ingredient_database()
|
| 27 |
+
|
| 28 |
+
# Create embeddings and FAISS index
|
| 29 |
+
self.embeddings, self.faiss_index = self._create_embeddings_index()
|
| 30 |
+
|
| 31 |
+
# Food scoring criteria
|
| 32 |
+
self.scoring_weights = {
|
| 33 |
+
'health_score': 0.4,
|
| 34 |
+
'processing_level': 0.3,
|
| 35 |
+
'allergen_risk': 0.2,
|
| 36 |
+
'nutritional_value': 0.1
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
logger.info("RAG System initialized successfully!")
|
| 40 |
+
|
| 41 |
+
def _create_ingredient_database(self) -> List[Dict]:
|
| 42 |
+
"""Create comprehensive ingredient knowledge base"""
|
| 43 |
+
return [
|
| 44 |
+
# Natural ingredients (high health score)
|
| 45 |
+
{
|
| 46 |
+
"name": "organic whole wheat flour",
|
| 47 |
+
"category": "grain",
|
| 48 |
+
"health_score": 9,
|
| 49 |
+
"processing_level": 1,
|
| 50 |
+
"allergens": ["gluten"],
|
| 51 |
+
"nutritional_benefits": "High fiber, B vitamins, minerals",
|
| 52 |
+
"description": "Minimally processed whole grain flour with complete nutrition profile"
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"name": "olive oil",
|
| 56 |
+
"category": "fat",
|
| 57 |
+
"health_score": 9,
|
| 58 |
+
"processing_level": 2,
|
| 59 |
+
"allergens": [],
|
| 60 |
+
"nutritional_benefits": "Monounsaturated fats, vitamin E, antioxidants",
|
| 61 |
+
"description": "Heart-healthy oil with anti-inflammatory properties"
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"name": "sea salt",
|
| 65 |
+
"category": "seasoning",
|
| 66 |
+
"health_score": 7,
|
| 67 |
+
"processing_level": 2,
|
| 68 |
+
"allergens": [],
|
| 69 |
+
"nutritional_benefits": "Essential minerals, electrolyte balance",
|
| 70 |
+
"description": "Natural salt with trace minerals"
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"name": "cane sugar",
|
| 74 |
+
"category": "sweetener",
|
| 75 |
+
"health_score": 4,
|
| 76 |
+
"processing_level": 3,
|
| 77 |
+
"allergens": [],
|
| 78 |
+
"nutritional_benefits": "Quick energy source",
|
| 79 |
+
"description": "Less processed than refined sugar but still high in calories"
|
| 80 |
+
},
|
| 81 |
+
|
| 82 |
+
# Processed ingredients (medium health score)
|
| 83 |
+
{
|
| 84 |
+
"name": "enriched wheat flour",
|
| 85 |
+
"category": "grain",
|
| 86 |
+
"health_score": 5,
|
| 87 |
+
"processing_level": 4,
|
| 88 |
+
"allergens": ["gluten"],
|
| 89 |
+
"nutritional_benefits": "Added vitamins and minerals",
|
| 90 |
+
"description": "Refined flour with synthetic nutrients added back"
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"name": "vegetable oil",
|
| 94 |
+
"category": "fat",
|
| 95 |
+
"health_score": 4,
|
| 96 |
+
"processing_level": 5,
|
| 97 |
+
"allergens": [],
|
| 98 |
+
"nutritional_benefits": "Omega-6 fatty acids",
|
| 99 |
+
"description": "Highly processed oil blend, may contain trans fats"
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"name": "natural flavors",
|
| 103 |
+
"category": "additive",
|
| 104 |
+
"health_score": 6,
|
| 105 |
+
"processing_level": 4,
|
| 106 |
+
"allergens": [],
|
| 107 |
+
"nutritional_benefits": "None",
|
| 108 |
+
"description": "Derived from natural sources but chemically processed"
|
| 109 |
+
},
|
| 110 |
+
|
| 111 |
+
# Highly processed ingredients (low health score)
|
| 112 |
+
{
|
| 113 |
+
"name": "high fructose corn syrup",
|
| 114 |
+
"category": "sweetener",
|
| 115 |
+
"health_score": 2,
|
| 116 |
+
"processing_level": 6,
|
| 117 |
+
"allergens": [],
|
| 118 |
+
"nutritional_benefits": "Quick energy",
|
| 119 |
+
"description": "Highly processed sweetener linked to metabolic issues"
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"name": "artificial colors",
|
| 123 |
+
"category": "additive",
|
| 124 |
+
"health_score": 2,
|
| 125 |
+
"processing_level": 6,
|
| 126 |
+
"allergens": [],
|
| 127 |
+
"nutritional_benefits": "None",
|
| 128 |
+
"description": "Synthetic dyes with potential health concerns"
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"name": "sodium benzoate",
|
| 132 |
+
"category": "preservative",
|
| 133 |
+
"health_score": 3,
|
| 134 |
+
"processing_level": 6,
|
| 135 |
+
"allergens": [],
|
| 136 |
+
"nutritional_benefits": "None",
|
| 137 |
+
"description": "Chemical preservative with potential health risks"
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"name": "monosodium glutamate",
|
| 141 |
+
"category": "flavor enhancer",
|
| 142 |
+
"health_score": 4,
|
| 143 |
+
"processing_level": 5,
|
| 144 |
+
"allergens": [],
|
| 145 |
+
"nutritional_benefits": "Umami flavor",
|
| 146 |
+
"description": "Flavor enhancer that may cause sensitivity in some people"
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"name": "hydrogenated oil",
|
| 150 |
+
"category": "fat",
|
| 151 |
+
"health_score": 1,
|
| 152 |
+
"processing_level": 6,
|
| 153 |
+
"allergens": [],
|
| 154 |
+
"nutritional_benefits": "Extended shelf life",
|
| 155 |
+
"description": "Contains trans fats, strongly linked to heart disease"
|
| 156 |
+
},
|
| 157 |
+
|
| 158 |
+
# Common allergens and additives
|
| 159 |
+
{
|
| 160 |
+
"name": "soy lecithin",
|
| 161 |
+
"category": "emulsifier",
|
| 162 |
+
"health_score": 6,
|
| 163 |
+
"processing_level": 4,
|
| 164 |
+
"allergens": ["soy"],
|
| 165 |
+
"nutritional_benefits": "Choline source",
|
| 166 |
+
"description": "Emulsifier derived from soybeans, generally safe"
|
| 167 |
+
},
|
| 168 |
+
{
|
| 169 |
+
"name": "milk powder",
|
| 170 |
+
"category": "dairy",
|
| 171 |
+
"health_score": 7,
|
| 172 |
+
"processing_level": 3,
|
| 173 |
+
"allergens": ["milk"],
|
| 174 |
+
"nutritional_benefits": "Protein, calcium, vitamins",
|
| 175 |
+
"description": "Concentrated dairy product with good nutritional value"
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"name": "citric acid",
|
| 179 |
+
"category": "preservative",
|
| 180 |
+
"health_score": 8,
|
| 181 |
+
"processing_level": 3,
|
| 182 |
+
"allergens": [],
|
| 183 |
+
"nutritional_benefits": "Vitamin C precursor",
|
| 184 |
+
"description": "Natural preservative, generally safe and beneficial"
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"name": "baking soda",
|
| 188 |
+
"category": "leavening",
|
| 189 |
+
"health_score": 8,
|
| 190 |
+
"processing_level": 2,
|
| 191 |
+
"allergens": [],
|
| 192 |
+
"nutritional_benefits": "Alkalizing agent",
|
| 193 |
+
"description": "Natural leavening agent, safe and effective"
|
| 194 |
+
},
|
| 195 |
+
{
|
| 196 |
+
"name": "xanthan gum",
|
| 197 |
+
"category": "thickener",
|
| 198 |
+
"health_score": 6,
|
| 199 |
+
"processing_level": 4,
|
| 200 |
+
"allergens": [],
|
| 201 |
+
"nutritional_benefits": "Fiber content",
|
| 202 |
+
"description": "Natural thickener, generally safe but may cause digestive issues"
|
| 203 |
+
}
|
| 204 |
+
]
|
| 205 |
+
|
| 206 |
+
def _create_embeddings_index(self) -> Tuple[np.ndarray, faiss.IndexFlatIP]:
|
| 207 |
+
"""Create FAISS index for ingredient similarity search"""
|
| 208 |
+
logger.info("Creating embeddings and FAISS index...")
|
| 209 |
+
|
| 210 |
+
# Create embeddings for all ingredients
|
| 211 |
+
ingredient_texts = []
|
| 212 |
+
for ingredient in self.ingredient_db:
|
| 213 |
+
text = f"{ingredient['name']} {ingredient['category']} {ingredient['description']} {ingredient['nutritional_benefits']}"
|
| 214 |
+
ingredient_texts.append(text)
|
| 215 |
+
|
| 216 |
+
embeddings = self.model.encode(ingredient_texts)
|
| 217 |
+
|
| 218 |
+
# Create FAISS index
|
| 219 |
+
dimension = embeddings.shape[1]
|
| 220 |
+
index = faiss.IndexFlatIP(dimension)
|
| 221 |
+
|
| 222 |
+
# Normalize embeddings for cosine similarity
|
| 223 |
+
faiss.normalize_L2(embeddings)
|
| 224 |
+
index.add(embeddings.astype('float32'))
|
| 225 |
+
|
| 226 |
+
return embeddings, index
|
| 227 |
+
|
| 228 |
+
def parse_ingredients(self, ingredient_text: str) -> List[str]:
|
| 229 |
+
"""Parse ingredient list from text"""
|
| 230 |
+
# Clean and split ingredients
|
| 231 |
+
cleaned_text = re.sub(r'[()[\]]', '', ingredient_text.lower())
|
| 232 |
+
ingredients = [ing.strip() for ing in cleaned_text.split(',')]
|
| 233 |
+
|
| 234 |
+
# Remove empty strings and common prefixes
|
| 235 |
+
ingredients = [ing for ing in ingredients if ing and len(ing) > 2]
|
| 236 |
+
|
| 237 |
+
return ingredients
|
| 238 |
+
|
| 239 |
+
def find_similar_ingredients(self, ingredient: str, k: int = 3) -> List[Dict]:
|
| 240 |
+
"""Find similar ingredients using RAG"""
|
| 241 |
+
query_embedding = self.model.encode([ingredient])
|
| 242 |
+
faiss.normalize_L2(query_embedding)
|
| 243 |
+
|
| 244 |
+
scores, indices = self.faiss_index.search(query_embedding.astype('float32'), k)
|
| 245 |
+
|
| 246 |
+
similar_ingredients = []
|
| 247 |
+
for i, (score, idx) in enumerate(zip(scores[0], indices[0])):
|
| 248 |
+
if idx < len(self.ingredient_db):
|
| 249 |
+
ingredient_info = self.ingredient_db[idx].copy()
|
| 250 |
+
ingredient_info['similarity_score'] = float(score)
|
| 251 |
+
similar_ingredients.append(ingredient_info)
|
| 252 |
+
|
| 253 |
+
return similar_ingredients
|
| 254 |
+
|
| 255 |
+
def analyze_ingredient(self, ingredient: str) -> Dict:
|
| 256 |
+
"""Analyze a single ingredient using RAG"""
|
| 257 |
+
similar_ingredients = self.find_similar_ingredients(ingredient, k=1)
|
| 258 |
+
|
| 259 |
+
if similar_ingredients and similar_ingredients[0]['similarity_score'] > 0.5:
|
| 260 |
+
# High similarity - use database info
|
| 261 |
+
analysis = similar_ingredients[0]
|
| 262 |
+
analysis['confidence'] = 'High'
|
| 263 |
+
else:
|
| 264 |
+
# Low similarity - provide general analysis
|
| 265 |
+
analysis = {
|
| 266 |
+
'name': ingredient,
|
| 267 |
+
'category': 'unknown',
|
| 268 |
+
'health_score': 5, # Neutral score
|
| 269 |
+
'processing_level': 4, # Assume moderate processing
|
| 270 |
+
'allergens': [],
|
| 271 |
+
'nutritional_benefits': 'Information not available',
|
| 272 |
+
'description': 'Ingredient not found in database',
|
| 273 |
+
'confidence': 'Low',
|
| 274 |
+
'similarity_score': 0.0
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
return analysis
|
| 278 |
+
|
| 279 |
+
def analyze_food_product(self, product_name: str, ingredients_text: str) -> Dict:
|
| 280 |
+
"""Analyze complete food product"""
|
| 281 |
+
ingredients = self.parse_ingredients(ingredients_text)
|
| 282 |
+
|
| 283 |
+
if not ingredients:
|
| 284 |
+
return {
|
| 285 |
+
'error': 'No ingredients found. Please check the ingredient list format.'
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
# Analyze each ingredient
|
| 289 |
+
ingredient_analyses = []
|
| 290 |
+
total_health_score = 0
|
| 291 |
+
total_processing_level = 0
|
| 292 |
+
all_allergens = set()
|
| 293 |
+
|
| 294 |
+
for ingredient in ingredients:
|
| 295 |
+
analysis = self.analyze_ingredient(ingredient)
|
| 296 |
+
ingredient_analyses.append(analysis)
|
| 297 |
+
|
| 298 |
+
total_health_score += analysis['health_score']
|
| 299 |
+
total_processing_level += analysis['processing_level']
|
| 300 |
+
all_allergens.update(analysis['allergens'])
|
| 301 |
+
|
| 302 |
+
# Calculate overall scores
|
| 303 |
+
avg_health_score = total_health_score / len(ingredients)
|
| 304 |
+
avg_processing_level = total_processing_level / len(ingredients)
|
| 305 |
+
|
| 306 |
+
# Generate recommendations
|
| 307 |
+
recommendations = self._generate_recommendations(ingredient_analyses)
|
| 308 |
+
|
| 309 |
+
# Create detailed report
|
| 310 |
+
report = {
|
| 311 |
+
'product_name': product_name,
|
| 312 |
+
'total_ingredients': len(ingredients),
|
| 313 |
+
'overall_health_score': round(avg_health_score, 2),
|
| 314 |
+
'processing_level': round(avg_processing_level, 2),
|
| 315 |
+
'allergens': list(all_allergens),
|
| 316 |
+
'ingredient_analyses': ingredient_analyses,
|
| 317 |
+
'recommendations': recommendations,
|
| 318 |
+
'analysis_timestamp': datetime.now().isoformat()
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
return report
|
| 322 |
+
|
| 323 |
+
def _generate_recommendations(self, analyses: List[Dict]) -> List[str]:
|
| 324 |
+
"""Generate recommendations based on ingredient analysis"""
|
| 325 |
+
recommendations = []
|
| 326 |
+
|
| 327 |
+
# Check for highly processed ingredients
|
| 328 |
+
highly_processed = [a for a in analyses if a['processing_level'] >= 5]
|
| 329 |
+
if highly_processed:
|
| 330 |
+
recommendations.append(
|
| 331 |
+
f"β οΈ Contains {len(highly_processed)} highly processed ingredients. "
|
| 332 |
+
f"Consider alternatives with whole food ingredients."
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
# Check for low health score ingredients
|
| 336 |
+
unhealthy = [a for a in analyses if a['health_score'] <= 3]
|
| 337 |
+
if unhealthy:
|
| 338 |
+
ingredients_list = ", ".join([a['name'] for a in unhealthy])
|
| 339 |
+
recommendations.append(
|
| 340 |
+
f"π Concerning ingredients: {ingredients_list}. "
|
| 341 |
+
f"These may have negative health impacts."
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
# Check for allergens
|
| 345 |
+
allergen_ingredients = [a for a in analyses if a['allergens']]
|
| 346 |
+
if allergen_ingredients:
|
| 347 |
+
recommendations.append(
|
| 348 |
+
f"β οΈ Contains allergens. Check individual ingredient allergen information."
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
# Positive recommendations
|
| 352 |
+
healthy = [a for a in analyses if a['health_score'] >= 8]
|
| 353 |
+
if healthy:
|
| 354 |
+
recommendations.append(
|
| 355 |
+
f"β
Contains {len(healthy)} high-quality ingredients with good nutritional value."
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
if not recommendations:
|
| 359 |
+
recommendations.append(
|
| 360 |
+
"βΉοΈ This product has a moderate ingredient profile. "
|
| 361 |
+
"Consider your dietary needs and preferences."
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
return recommendations
|
| 365 |
+
|
| 366 |
+
def compare_products(self, products_data: List[Dict]) -> Dict:
|
| 367 |
+
"""Compare multiple products and suggest the best one"""
|
| 368 |
+
if len(products_data) < 2:
|
| 369 |
+
return {'error': 'Need at least 2 products to compare'}
|
| 370 |
+
|
| 371 |
+
comparison_results = []
|
| 372 |
+
|
| 373 |
+
for product in products_data:
|
| 374 |
+
analysis = self.analyze_food_product(product['name'], product['ingredients'])
|
| 375 |
+
if 'error' not in analysis:
|
| 376 |
+
comparison_results.append(analysis)
|
| 377 |
+
|
| 378 |
+
if not comparison_results:
|
| 379 |
+
return {'error': 'No valid products to compare'}
|
| 380 |
+
|
| 381 |
+
# Rank products by overall health score
|
| 382 |
+
ranked_products = sorted(
|
| 383 |
+
comparison_results,
|
| 384 |
+
key=lambda x: x['overall_health_score'],
|
| 385 |
+
reverse=True
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
# Generate comparison report
|
| 389 |
+
comparison_report = {
|
| 390 |
+
'total_products': len(ranked_products),
|
| 391 |
+
'best_product': ranked_products[0],
|
| 392 |
+
'all_products': ranked_products,
|
| 393 |
+
'comparison_summary': self._generate_comparison_summary(ranked_products)
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
return comparison_report
|
| 397 |
+
|
| 398 |
+
def _generate_comparison_summary(self, ranked_products: List[Dict]) -> List[str]:
|
| 399 |
+
"""Generate comparison summary"""
|
| 400 |
+
summary = []
|
| 401 |
+
|
| 402 |
+
best_product = ranked_products[0]
|
| 403 |
+
worst_product = ranked_products[-1]
|
| 404 |
+
|
| 405 |
+
summary.append(
|
| 406 |
+
f"π Best Choice: {best_product['product_name']} "
|
| 407 |
+
f"(Health Score: {best_product['overall_health_score']}/10)"
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
if len(ranked_products) > 1:
|
| 411 |
+
summary.append(
|
| 412 |
+
f"β Avoid: {worst_product['product_name']} "
|
| 413 |
+
f"(Health Score: {worst_product['overall_health_score']}/10)"
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
# Health score distribution
|
| 417 |
+
high_quality = len([p for p in ranked_products if p['overall_health_score'] >= 7])
|
| 418 |
+
summary.append(f"π {high_quality}/{len(ranked_products)} products have high health scores (β₯7)")
|
| 419 |
+
|
| 420 |
+
return summary
|
| 421 |
+
|
| 422 |
+
def create_gradio_interface():
|
| 423 |
+
"""Create the Gradio interface"""
|
| 424 |
+
|
| 425 |
+
# Initialize RAG system
|
| 426 |
+
rag_system = FoodIngredientRAG()
|
| 427 |
+
|
| 428 |
+
def analyze_single_product(product_name, ingredients_text):
|
| 429 |
+
"""Analyze single product wrapper"""
|
| 430 |
+
if not product_name.strip() or not ingredients_text.strip():
|
| 431 |
+
return "Please provide both product name and ingredients list.", "", ""
|
| 432 |
+
|
| 433 |
+
analysis = rag_system.analyze_food_product(product_name.strip(), ingredients_text.strip())
|
| 434 |
+
|
| 435 |
+
if 'error' in analysis:
|
| 436 |
+
return analysis['error'], "", ""
|
| 437 |
+
|
| 438 |
+
# Create formatted output
|
| 439 |
+
summary = f"""
|
| 440 |
+
# π Analysis Report for {analysis['product_name']}
|
| 441 |
+
|
| 442 |
+
## Overall Scores
|
| 443 |
+
- **Health Score**: {analysis['overall_health_score']}/10
|
| 444 |
+
- **Processing Level**: {analysis['processing_level']}/6 (lower is better)
|
| 445 |
+
- **Total Ingredients**: {analysis['total_ingredients']}
|
| 446 |
+
- **Allergens**: {', '.join(analysis['allergens']) if analysis['allergens'] else 'None detected'}
|
| 447 |
+
|
| 448 |
+
## Recommendations
|
| 449 |
+
"""
|
| 450 |
+
for rec in analysis['recommendations']:
|
| 451 |
+
summary += f"- {rec}\n"
|
| 452 |
+
|
| 453 |
+
# Create ingredient details table
|
| 454 |
+
ingredient_data = []
|
| 455 |
+
for ing in analysis['ingredient_analyses']:
|
| 456 |
+
ingredient_data.append([
|
| 457 |
+
ing['name'],
|
| 458 |
+
f"{ing['health_score']}/10",
|
| 459 |
+
f"{ing['processing_level']}/6",
|
| 460 |
+
', '.join(ing['allergens']) if ing['allergens'] else 'None',
|
| 461 |
+
ing['nutritional_benefits'],
|
| 462 |
+
ing['confidence']
|
| 463 |
+
])
|
| 464 |
+
|
| 465 |
+
df = pd.DataFrame(ingredient_data, columns=[
|
| 466 |
+
'Ingredient', 'Health Score', 'Processing Level',
|
| 467 |
+
'Allergens', 'Benefits', 'Confidence'
|
| 468 |
+
])
|
| 469 |
+
|
| 470 |
+
# Create health score chart
|
| 471 |
+
chart_html = create_health_chart(analysis['ingredient_analyses'])
|
| 472 |
+
|
| 473 |
+
return summary, df, chart_html
|
| 474 |
+
|
| 475 |
+
def compare_multiple_products(products_input):
|
| 476 |
+
"""Compare multiple products wrapper"""
|
| 477 |
+
try:
|
| 478 |
+
# Parse products input (expect JSON format)
|
| 479 |
+
products_data = json.loads(products_input)
|
| 480 |
+
|
| 481 |
+
if not isinstance(products_data, list):
|
| 482 |
+
return "Please provide products as a JSON list.", "", ""
|
| 483 |
+
|
| 484 |
+
comparison = rag_system.compare_products(products_data)
|
| 485 |
+
|
| 486 |
+
if 'error' in comparison:
|
| 487 |
+
return comparison['error'], "", ""
|
| 488 |
+
|
| 489 |
+
# Create comparison summary
|
| 490 |
+
summary = f"""
|
| 491 |
+
# π Product Comparison Results
|
| 492 |
+
|
| 493 |
+
## Summary
|
| 494 |
+
"""
|
| 495 |
+
for item in comparison['comparison_summary']:
|
| 496 |
+
summary += f"- {item}\n"
|
| 497 |
+
|
| 498 |
+
summary += f"\n## Detailed Rankings\n"
|
| 499 |
+
|
| 500 |
+
for i, product in enumerate(comparison['all_products'], 1):
|
| 501 |
+
summary += f"""
|
| 502 |
+
### {i}. {product['product_name']}
|
| 503 |
+
- Health Score: {product['overall_health_score']}/10
|
| 504 |
+
- Processing Level: {product['processing_level']}/6
|
| 505 |
+
- Ingredients: {product['total_ingredients']}
|
| 506 |
+
- Allergens: {', '.join(product['allergens']) if product['allergens'] else 'None'}
|
| 507 |
+
"""
|
| 508 |
+
|
| 509 |
+
# Create comparison table
|
| 510 |
+
comparison_data = []
|
| 511 |
+
for product in comparison['all_products']:
|
| 512 |
+
comparison_data.append([
|
| 513 |
+
product['product_name'],
|
| 514 |
+
f"{product['overall_health_score']}/10",
|
| 515 |
+
f"{product['processing_level']}/6",
|
| 516 |
+
product['total_ingredients'],
|
| 517 |
+
', '.join(product['allergens']) if product['allergens'] else 'None'
|
| 518 |
+
])
|
| 519 |
+
|
| 520 |
+
df = pd.DataFrame(comparison_data, columns=[
|
| 521 |
+
'Product', 'Health Score', 'Processing Level',
|
| 522 |
+
'Total Ingredients', 'Allergens'
|
| 523 |
+
])
|
| 524 |
+
|
| 525 |
+
# Create comparison chart
|
| 526 |
+
chart_html = create_comparison_chart(comparison['all_products'])
|
| 527 |
+
|
| 528 |
+
return summary, df, chart_html
|
| 529 |
+
|
| 530 |
+
except json.JSONDecodeError:
|
| 531 |
+
return "Invalid JSON format. Please check your input.", "", ""
|
| 532 |
+
except Exception as e:
|
| 533 |
+
return f"Error: {str(e)}", "", ""
|
| 534 |
+
|
| 535 |
+
def create_health_chart(ingredient_analyses):
|
| 536 |
+
"""Create health score visualization"""
|
| 537 |
+
chart_html = """
|
| 538 |
+
<div style="padding: 20px;">
|
| 539 |
+
<h3>π Ingredient Health Scores</h3>
|
| 540 |
+
<div style="display: flex; flex-direction: column; gap: 8px;">
|
| 541 |
+
"""
|
| 542 |
+
|
| 543 |
+
for ing in ingredient_analyses:
|
| 544 |
+
score = ing['health_score']
|
| 545 |
+
max_score = 10
|
| 546 |
+
bar_width = (score / max_score) * 100
|
| 547 |
+
|
| 548 |
+
# Color based on health score
|
| 549 |
+
if score >= 8:
|
| 550 |
+
color = "#4CAF50" # Green
|
| 551 |
+
elif score >= 6:
|
| 552 |
+
color = "#FFC107" # Yellow
|
| 553 |
+
elif score >= 4:
|
| 554 |
+
color = "#FF9800" # Orange
|
| 555 |
+
else:
|
| 556 |
+
color = "#F44336" # Red
|
| 557 |
+
|
| 558 |
+
chart_html += f"""
|
| 559 |
+
<div style="margin-bottom: 8px;">
|
| 560 |
+
<div style="font-size: 12px; margin-bottom: 2px; display: flex; justify-content: space-between;">
|
| 561 |
+
<span>{ing['name'][:30]}...</span>
|
| 562 |
+
<span>{score}/10</span>
|
| 563 |
+
</div>
|
| 564 |
+
<div style="background-color: #e0e0e0; height: 20px; border-radius: 10px; overflow: hidden;">
|
| 565 |
+
<div style="background-color: {color}; height: 100%; width: {bar_width}%; transition: width 0.3s;"></div>
|
| 566 |
+
</div>
|
| 567 |
+
</div>
|
| 568 |
+
"""
|
| 569 |
+
|
| 570 |
+
chart_html += """
|
| 571 |
+
</div>
|
| 572 |
+
<div style="margin-top: 15px; font-size: 12px; color: #666;">
|
| 573 |
+
π’ Excellent (8-10) | π‘ Good (6-7) | π Fair (4-5) | π΄ Poor (0-3)
|
| 574 |
+
</div>
|
| 575 |
+
</div>
|
| 576 |
+
"""
|
| 577 |
+
|
| 578 |
+
return chart_html
|
| 579 |
+
|
| 580 |
+
def create_comparison_chart(products):
|
| 581 |
+
"""Create product comparison visualization"""
|
| 582 |
+
chart_html = """
|
| 583 |
+
<div style="padding: 20px;">
|
| 584 |
+
<h3>π Product Health Score Comparison</h3>
|
| 585 |
+
<div style="display: flex; flex-direction: column; gap: 10px;">
|
| 586 |
+
"""
|
| 587 |
+
|
| 588 |
+
max_score = max([p['overall_health_score'] for p in products])
|
| 589 |
+
|
| 590 |
+
for product in products:
|
| 591 |
+
score = product['overall_health_score']
|
| 592 |
+
bar_width = (score / 10) * 100
|
| 593 |
+
|
| 594 |
+
# Color based on health score
|
| 595 |
+
if score >= 7:
|
| 596 |
+
color = "#4CAF50" # Green
|
| 597 |
+
elif score >= 5:
|
| 598 |
+
color = "#FFC107" # Yellow
|
| 599 |
+
else:
|
| 600 |
+
color = "#F44336" # Red
|
| 601 |
+
|
| 602 |
+
chart_html += f"""
|
| 603 |
+
<div style="margin-bottom: 10px;">
|
| 604 |
+
<div style="font-size: 14px; margin-bottom: 4px; display: flex; justify-content: space-between;">
|
| 605 |
+
<span><strong>{product['product_name']}</strong></span>
|
| 606 |
+
<span>{score}/10</span>
|
| 607 |
+
</div>
|
| 608 |
+
<div style="background-color: #e0e0e0; height: 25px; border-radius: 12px; overflow: hidden;">
|
| 609 |
+
<div style="background-color: {color}; height: 100%; width: {bar_width}%; transition: width 0.3s;"></div>
|
| 610 |
+
</div>
|
| 611 |
+
</div>
|
| 612 |
+
"""
|
| 613 |
+
|
| 614 |
+
chart_html += """
|
| 615 |
+
</div>
|
| 616 |
+
</div>
|
| 617 |
+
"""
|
| 618 |
+
|
| 619 |
+
return chart_html
|
| 620 |
+
|
| 621 |
+
# Create Gradio interface
|
| 622 |
+
with gr.Blocks(
|
| 623 |
+
title="π₯ Smart Food Ingredient Analyzer",
|
| 624 |
+
css="""
|
| 625 |
+
.gradio-container {
|
| 626 |
+
max-width: 1400px !important;
|
| 627 |
+
}
|
| 628 |
+
.ingredient-input {
|
| 629 |
+
font-family: monospace;
|
| 630 |
+
}
|
| 631 |
+
"""
|
| 632 |
+
) as demo:
|
| 633 |
+
|
| 634 |
+
gr.Markdown("""
|
| 635 |
+
# π₯ Smart Food Ingredient Analyzer
|
| 636 |
+
|
| 637 |
+
**AI-Powered RAG System for Food Safety & Health Analysis**
|
| 638 |
+
|
| 639 |
+
Analyze packaged food ingredients using advanced AI to make informed dietary choices.
|
| 640 |
+
Our system uses Retrieval-Augmented Generation (RAG) to provide detailed ingredient analysis.
|
| 641 |
+
|
| 642 |
+
## Features:
|
| 643 |
+
- π **Ingredient Analysis**: Detailed health scoring for each ingredient
|
| 644 |
+
- π **Health Scoring**: 1-10 scale based on nutritional value and processing level
|
| 645 |
+
- β οΈ **Allergen Detection**: Identifies common allergens
|
| 646 |
+
- π **Product Comparison**: Compare multiple products to find the healthiest option
|
| 647 |
+
- π€ **RAG Technology**: Uses semantic search for accurate ingredient matching
|
| 648 |
+
""")
|
| 649 |
+
|
| 650 |
+
with gr.Tabs():
|
| 651 |
+
# Single Product Analysis Tab
|
| 652 |
+
with gr.TabItem("π Single Product Analysis"):
|
| 653 |
+
gr.Markdown("### Analyze Individual Food Products")
|
| 654 |
+
|
| 655 |
+
with gr.Row():
|
| 656 |
+
with gr.Column(scale=1):
|
| 657 |
+
product_name_input = gr.Textbox(
|
| 658 |
+
label="Product Name",
|
| 659 |
+
placeholder="e.g., Whole Grain Crackers",
|
| 660 |
+
lines=1
|
| 661 |
+
)
|
| 662 |
+
|
| 663 |
+
ingredients_input = gr.Textbox(
|
| 664 |
+
label="Ingredients List",
|
| 665 |
+
placeholder="e.g., whole wheat flour, olive oil, sea salt, yeast",
|
| 666 |
+
lines=6,
|
| 667 |
+
elem_classes=["ingredient-input"]
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
analyze_btn = gr.Button("π Analyze Product", variant="primary")
|
| 671 |
+
|
| 672 |
+
gr.Markdown("""
|
| 673 |
+
**Tips:**
|
| 674 |
+
- Copy ingredients exactly as listed on package
|
| 675 |
+
- Separate ingredients with commas
|
| 676 |
+
- Include all ingredients for accurate analysis
|
| 677 |
+
""")
|
| 678 |
+
|
| 679 |
+
with gr.Column(scale=2):
|
| 680 |
+
analysis_output = gr.Markdown()
|
| 681 |
+
|
| 682 |
+
with gr.Tabs():
|
| 683 |
+
with gr.TabItem("π Ingredient Details"):
|
| 684 |
+
ingredient_table = gr.Dataframe(
|
| 685 |
+
headers=["Ingredient", "Health Score", "Processing Level",
|
| 686 |
+
"Allergens", "Benefits", "Confidence"],
|
| 687 |
+
interactive=False
|
| 688 |
+
)
|
| 689 |
+
|
| 690 |
+
with gr.TabItem("π Health Chart"):
|
| 691 |
+
health_chart = gr.HTML()
|
| 692 |
+
|
| 693 |
+
# Product Comparison Tab
|
| 694 |
+
with gr.TabItem("π Product Comparison"):
|
| 695 |
+
gr.Markdown("### Compare Multiple Products")
|
| 696 |
+
|
| 697 |
+
with gr.Row():
|
| 698 |
+
with gr.Column(scale=1):
|
| 699 |
+
comparison_input = gr.Textbox(
|
| 700 |
+
label="Products (JSON Format)",
|
| 701 |
+
placeholder='[{"name": "Product A", "ingredients": "ingredient1, ingredient2"}, {"name": "Product B", "ingredients": "ingredient3, ingredient4"}]',
|
| 702 |
+
lines=10,
|
| 703 |
+
elem_classes=["ingredient-input"]
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
compare_btn = gr.Button("π Compare Products", variant="primary")
|
| 707 |
+
|
| 708 |
+
gr.Markdown("""
|
| 709 |
+
**JSON Format Example:**
|
| 710 |
+
```json
|
| 711 |
+
[
|
| 712 |
+
{
|
| 713 |
+
"name": "Organic Crackers",
|
| 714 |
+
"ingredients": "organic whole wheat flour, olive oil, sea salt"
|
| 715 |
+
},
|
| 716 |
+
{
|
| 717 |
+
"name": "Regular Crackers",
|
| 718 |
+
"ingredients": "enriched flour, vegetable oil, high fructose corn syrup"
|
| 719 |
+
}
|
| 720 |
+
]
|
| 721 |
+
```
|
| 722 |
+
""")
|
| 723 |
+
|
| 724 |
+
with gr.Column(scale=2):
|
| 725 |
+
comparison_output = gr.Markdown()
|
| 726 |
+
|
| 727 |
+
with gr.Tabs():
|
| 728 |
+
with gr.TabItem("π Comparison Table"):
|
| 729 |
+
comparison_table = gr.Dataframe(
|
| 730 |
+
headers=["Product", "Health Score", "Processing Level",
|
| 731 |
+
"Total Ingredients", "Allergens"],
|
| 732 |
+
interactive=False
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
with gr.TabItem("π Score Chart"):
|
| 736 |
+
comparison_chart = gr.HTML()
|
| 737 |
+
|
| 738 |
+
# Information Tab
|
| 739 |
+
with gr.TabItem("βΉοΈ How It Works"):
|
| 740 |
+
gr.Markdown("""
|
| 741 |
+
## π€ RAG Technology Explained
|
| 742 |
+
|
| 743 |
+
Our system uses **Retrieval-Augmented Generation (RAG)** to analyze food ingredients:
|
| 744 |
+
|
| 745 |
+
### 1. Knowledge Base
|
| 746 |
+
- Comprehensive database of ingredients and their health profiles
|
| 747 |
+
- Processing levels, allergen information, and nutritional benefits
|
| 748 |
+
- Continuously updated with latest nutritional research
|
| 749 |
+
|
| 750 |
+
### 2. Semantic Search
|
| 751 |
+
- Uses sentence transformers to understand ingredient context
|
| 752 |
+
- FAISS vector database for fast similarity matching
|
| 753 |
+
- Handles variations in ingredient naming and descriptions
|
| 754 |
+
|
| 755 |
+
### 3. Health Scoring Algorithm
|
| 756 |
+
```
|
| 757 |
+
Health Score = Base Score Γ Processing Factor Γ Allergen Factor
|
| 758 |
+
|
| 759 |
+
- Base Score: Nutritional value (1-10)
|
| 760 |
+
- Processing Factor: Less processed = higher score
|
| 761 |
+
- Allergen Factor: Common allergens reduce score
|
| 762 |
+
```
|
| 763 |
+
|
| 764 |
+
### 4. Recommendations
|
| 765 |
+
- Personalized suggestions based on ingredient analysis
|
| 766 |
+
- Identifies concerning additives and preservatives
|
| 767 |
+
- Suggests healthier alternatives when available
|
| 768 |
+
|
| 769 |
+
## π Scoring System
|
| 770 |
+
|
| 771 |
+
**Health Scores:**
|
| 772 |
+
- π’ **8-10**: Excellent (whole foods, minimal processing)
|
| 773 |
+
- π‘ **6-7**: Good (some processing, generally safe)
|
| 774 |
+
- π **4-5**: Fair (moderate concerns, use occasionally)
|
| 775 |
+
- π΄ **0-3**: Poor (highly processed, avoid if possible)
|
| 776 |
+
|
| 777 |
+
**Processing Levels:**
|
| 778 |
+
- **1-2**: Minimal processing (whole foods)
|
| 779 |
+
- **3-4**: Moderate processing (refined but acceptable)
|
| 780 |
+
- **5-6**: High processing (additives, preservatives)
|
| 781 |
+
|
| 782 |
+
## π― Use Cases
|
| 783 |
+
|
| 784 |
+
- **Grocery Shopping**: Compare similar products
|
| 785 |
+
- **Dietary Restrictions**: Identify allergens and additives
|
| 786 |
+
- **Health Goals**: Choose products aligned with nutrition goals
|
| 787 |
+
- **Education**: Learn about ingredient impacts on health
|
| 788 |
+
""")
|
| 789 |
+
|
| 790 |
+
# Event handlers
|
| 791 |
+
analyze_btn.click(
|
| 792 |
+
fn=analyze_single_product,
|
| 793 |
+
inputs=[product_name_input, ingredients_input],
|
| 794 |
+
outputs=[analysis_output, ingredient_table, health_chart]
|
| 795 |
+
)
|
| 796 |
+
|
| 797 |
+
compare_btn.click(
|
| 798 |
+
fn=compare_multiple_products,
|
| 799 |
+
inputs=[comparison_input],
|
| 800 |
+
outputs=[comparison_output, comparison_table, comparison_chart]
|
| 801 |
+
)
|
| 802 |
+
|
| 803 |
+
# Example data on load
|
| 804 |
+
demo.load(
|
| 805 |
+
fn=lambda: (
|
| 806 |
+
"Whole Grain Crackers",
|
| 807 |
+
"organic whole wheat flour, olive oil, sea salt, yeast, rosemary extract"
|
| 808 |
+
),
|
| 809 |
+
outputs=[product_name_input, ingredients_input]
|
| 810 |
+
)
|
| 811 |
+
|
| 812 |
+
return demo
|
| 813 |
+
|
| 814 |
+
if __name__ == "__main__":
|
| 815 |
+
demo = create_gradio_interface()
|
| 816 |
+
demo.launch()
|