# app.py - Main Hugging Face Spaces Application import gradio as gr import pandas as pd import numpy as np from sentence_transformers import SentenceTransformer import faiss import json import re from typing import List, Dict, Tuple import logging from datetime import datetime # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class FoodIngredientRAG: def __init__(self): """Initialize the RAG system for food ingredient analysis""" logger.info("Initializing Food Ingredient RAG System...") # Load sentence transformer for embeddings self.model = SentenceTransformer('all-MiniLM-L6-v2') # Initialize ingredient knowledge base self.ingredient_db = self._create_ingredient_database() # Create embeddings and FAISS index self.embeddings, self.faiss_index = self._create_embeddings_index() # Food scoring criteria self.scoring_weights = { 'health_score': 0.4, 'processing_level': 0.3, 'allergen_risk': 0.2, 'nutritional_value': 0.1 } logger.info("RAG System initialized successfully!") def _create_ingredient_database(self) -> List[Dict]: """Create comprehensive ingredient knowledge base""" return [ # Natural ingredients (high health score) { "name": "organic whole wheat flour", "category": "grain", "health_score": 9, "processing_level": 1, "allergens": ["gluten"], "nutritional_benefits": "High fiber, B vitamins, minerals", "description": "Minimally processed whole grain flour with complete nutrition profile" }, { "name": "olive oil", "category": "fat", "health_score": 9, "processing_level": 2, "allergens": [], "nutritional_benefits": "Monounsaturated fats, vitamin E, antioxidants", "description": "Heart-healthy oil with anti-inflammatory properties" }, { "name": "sea salt", "category": "seasoning", "health_score": 7, "processing_level": 2, "allergens": [], "nutritional_benefits": "Essential minerals, electrolyte balance", "description": "Natural salt with trace minerals" }, { "name": "cane sugar", "category": "sweetener", "health_score": 4, "processing_level": 3, "allergens": [], "nutritional_benefits": "Quick energy source", "description": "Less processed than refined sugar but still high in calories" }, # Processed ingredients (medium health score) { "name": "enriched wheat flour", "category": "grain", "health_score": 5, "processing_level": 4, "allergens": ["gluten"], "nutritional_benefits": "Added vitamins and minerals", "description": "Refined flour with synthetic nutrients added back" }, { "name": "vegetable oil", "category": "fat", "health_score": 4, "processing_level": 5, "allergens": [], "nutritional_benefits": "Omega-6 fatty acids", "description": "Highly processed oil blend, may contain trans fats" }, { "name": "natural flavors", "category": "additive", "health_score": 6, "processing_level": 4, "allergens": [], "nutritional_benefits": "None", "description": "Derived from natural sources but chemically processed" }, # Highly processed ingredients (low health score) { "name": "high fructose corn syrup", "category": "sweetener", "health_score": 2, "processing_level": 6, "allergens": [], "nutritional_benefits": "Quick energy", "description": "Highly processed sweetener linked to metabolic issues" }, { "name": "artificial colors", "category": "additive", "health_score": 2, "processing_level": 6, "allergens": [], "nutritional_benefits": "None", "description": "Synthetic dyes with potential health concerns" }, { "name": "sodium benzoate", "category": "preservative", "health_score": 3, "processing_level": 6, "allergens": [], "nutritional_benefits": "None", "description": "Chemical preservative with potential health risks" }, { "name": "monosodium glutamate", "category": "flavor enhancer", "health_score": 4, "processing_level": 5, "allergens": [], "nutritional_benefits": "Umami flavor", "description": "Flavor enhancer that may cause sensitivity in some people" }, { "name": "hydrogenated oil", "category": "fat", "health_score": 1, "processing_level": 6, "allergens": [], "nutritional_benefits": "Extended shelf life", "description": "Contains trans fats, strongly linked to heart disease" }, # Common allergens and additives { "name": "soy lecithin", "category": "emulsifier", "health_score": 6, "processing_level": 4, "allergens": ["soy"], "nutritional_benefits": "Choline source", "description": "Emulsifier derived from soybeans, generally safe" }, { "name": "milk powder", "category": "dairy", "health_score": 7, "processing_level": 3, "allergens": ["milk"], "nutritional_benefits": "Protein, calcium, vitamins", "description": "Concentrated dairy product with good nutritional value" }, { "name": "citric acid", "category": "preservative", "health_score": 8, "processing_level": 3, "allergens": [], "nutritional_benefits": "Vitamin C precursor", "description": "Natural preservative, generally safe and beneficial" }, { "name": "baking soda", "category": "leavening", "health_score": 8, "processing_level": 2, "allergens": [], "nutritional_benefits": "Alkalizing agent", "description": "Natural leavening agent, safe and effective" }, { "name": "xanthan gum", "category": "thickener", "health_score": 6, "processing_level": 4, "allergens": [], "nutritional_benefits": "Fiber content", "description": "Natural thickener, generally safe but may cause digestive issues" } ] def _create_embeddings_index(self) -> Tuple[np.ndarray, faiss.IndexFlatIP]: """Create FAISS index for ingredient similarity search""" logger.info("Creating embeddings and FAISS index...") # Create embeddings for all ingredients ingredient_texts = [] for ingredient in self.ingredient_db: text = f"{ingredient['name']} {ingredient['category']} {ingredient['description']} {ingredient['nutritional_benefits']}" ingredient_texts.append(text) embeddings = self.model.encode(ingredient_texts) # Create FAISS index dimension = embeddings.shape[1] index = faiss.IndexFlatIP(dimension) # Normalize embeddings for cosine similarity faiss.normalize_L2(embeddings) index.add(embeddings.astype('float32')) return embeddings, index def parse_ingredients(self, ingredient_text: str) -> List[str]: """Parse ingredient list from text""" # Clean and split ingredients cleaned_text = re.sub(r'[()[\]]', '', ingredient_text.lower()) ingredients = [ing.strip() for ing in cleaned_text.split(',')] # Remove empty strings and common prefixes ingredients = [ing for ing in ingredients if ing and len(ing) > 2] return ingredients def find_similar_ingredients(self, ingredient: str, k: int = 3) -> List[Dict]: """Find similar ingredients using RAG""" query_embedding = self.model.encode([ingredient]) faiss.normalize_L2(query_embedding) scores, indices = self.faiss_index.search(query_embedding.astype('float32'), k) similar_ingredients = [] for i, (score, idx) in enumerate(zip(scores[0], indices[0])): if idx < len(self.ingredient_db): ingredient_info = self.ingredient_db[idx].copy() ingredient_info['similarity_score'] = float(score) similar_ingredients.append(ingredient_info) return similar_ingredients def analyze_ingredient(self, ingredient: str) -> Dict: """Analyze a single ingredient using RAG""" similar_ingredients = self.find_similar_ingredients(ingredient, k=1) if similar_ingredients and similar_ingredients[0]['similarity_score'] > 0.5: # High similarity - use database info analysis = similar_ingredients[0] analysis['confidence'] = 'High' else: # Low similarity - provide general analysis analysis = { 'name': ingredient, 'category': 'unknown', 'health_score': 5, # Neutral score 'processing_level': 4, # Assume moderate processing 'allergens': [], 'nutritional_benefits': 'Information not available', 'description': 'Ingredient not found in database', 'confidence': 'Low', 'similarity_score': 0.0 } return analysis def analyze_food_product(self, product_name: str, ingredients_text: str) -> Dict: """Analyze complete food product""" ingredients = self.parse_ingredients(ingredients_text) if not ingredients: return { 'error': 'No ingredients found. Please check the ingredient list format.' } # Analyze each ingredient ingredient_analyses = [] total_health_score = 0 total_processing_level = 0 all_allergens = set() for ingredient in ingredients: analysis = self.analyze_ingredient(ingredient) ingredient_analyses.append(analysis) total_health_score += analysis['health_score'] total_processing_level += analysis['processing_level'] all_allergens.update(analysis['allergens']) # Calculate overall scores avg_health_score = total_health_score / len(ingredients) avg_processing_level = total_processing_level / len(ingredients) # Generate recommendations recommendations = self._generate_recommendations(ingredient_analyses) # Create detailed report report = { 'product_name': product_name, 'total_ingredients': len(ingredients), 'overall_health_score': round(avg_health_score, 2), 'processing_level': round(avg_processing_level, 2), 'allergens': list(all_allergens), 'ingredient_analyses': ingredient_analyses, 'recommendations': recommendations, 'analysis_timestamp': datetime.now().isoformat() } return report def _generate_recommendations(self, analyses: List[Dict]) -> List[str]: """Generate recommendations based on ingredient analysis""" recommendations = [] # Check for highly processed ingredients highly_processed = [a for a in analyses if a['processing_level'] >= 5] if highly_processed: recommendations.append( f"â ī¸ Contains {len(highly_processed)} highly processed ingredients. " f"Consider alternatives with whole food ingredients." ) # Check for low health score ingredients unhealthy = [a for a in analyses if a['health_score'] <= 3] if unhealthy: ingredients_list = ", ".join([a['name'] for a in unhealthy]) recommendations.append( f"đ Concerning ingredients: {ingredients_list}. " f"These may have negative health impacts." ) # Check for allergens allergen_ingredients = [a for a in analyses if a['allergens']] if allergen_ingredients: recommendations.append( f"â ī¸ Contains allergens. Check individual ingredient allergen information." ) # Positive recommendations healthy = [a for a in analyses if a['health_score'] >= 8] if healthy: recommendations.append( f"â Contains {len(healthy)} high-quality ingredients with good nutritional value." ) if not recommendations: recommendations.append( "âšī¸ This product has a moderate ingredient profile. " "Consider your dietary needs and preferences." ) return recommendations def compare_products(self, products_data: List[Dict]) -> Dict: """Compare multiple products and suggest the best one""" if len(products_data) < 2: return {'error': 'Need at least 2 products to compare'} comparison_results = [] for product in products_data: analysis = self.analyze_food_product(product['name'], product['ingredients']) if 'error' not in analysis: comparison_results.append(analysis) if not comparison_results: return {'error': 'No valid products to compare'} # Rank products by overall health score ranked_products = sorted( comparison_results, key=lambda x: x['overall_health_score'], reverse=True ) # Generate comparison report comparison_report = { 'total_products': len(ranked_products), 'best_product': ranked_products[0], 'all_products': ranked_products, 'comparison_summary': self._generate_comparison_summary(ranked_products) } return comparison_report def _generate_comparison_summary(self, ranked_products: List[Dict]) -> List[str]: """Generate comparison summary""" summary = [] best_product = ranked_products[0] worst_product = ranked_products[-1] summary.append( f"đ Best Choice: {best_product['product_name']} " f"(Health Score: {best_product['overall_health_score']}/10)" ) if len(ranked_products) > 1: summary.append( f"â Avoid: {worst_product['product_name']} " f"(Health Score: {worst_product['overall_health_score']}/10)" ) # Health score distribution high_quality = len([p for p in ranked_products if p['overall_health_score'] >= 7]) summary.append(f"đ {high_quality}/{len(ranked_products)} products have high health scores (âĨ7)") return summary def create_gradio_interface(): """Create the Gradio interface""" # Initialize RAG system rag_system = FoodIngredientRAG() def analyze_single_product(product_name, ingredients_text): """Analyze single product wrapper""" if not product_name.strip() or not ingredients_text.strip(): return "Please provide both product name and ingredients list.", "", "" analysis = rag_system.analyze_food_product(product_name.strip(), ingredients_text.strip()) if 'error' in analysis: return analysis['error'], "", "" # Create formatted output summary = f""" # đ Analysis Report for {analysis['product_name']} ## Overall Scores - **Health Score**: {analysis['overall_health_score']}/10 - **Processing Level**: {analysis['processing_level']}/6 (lower is better) - **Total Ingredients**: {analysis['total_ingredients']} - **Allergens**: {', '.join(analysis['allergens']) if analysis['allergens'] else 'None detected'} ## Recommendations """ for rec in analysis['recommendations']: summary += f"- {rec}\n" # Create ingredient details table ingredient_data = [] for ing in analysis['ingredient_analyses']: ingredient_data.append([ ing['name'], f"{ing['health_score']}/10", f"{ing['processing_level']}/6", ', '.join(ing['allergens']) if ing['allergens'] else 'None', ing['nutritional_benefits'], ing['confidence'] ]) df = pd.DataFrame(ingredient_data, columns=[ 'Ingredient', 'Health Score', 'Processing Level', 'Allergens', 'Benefits', 'Confidence' ]) # Create health score chart chart_html = create_health_chart(analysis['ingredient_analyses']) return summary, df, chart_html def compare_multiple_products(products_input): """Compare multiple products wrapper""" try: # Parse products input (expect JSON format) products_data = json.loads(products_input) if not isinstance(products_data, list): return "Please provide products as a JSON list.", "", "" comparison = rag_system.compare_products(products_data) if 'error' in comparison: return comparison['error'], "", "" # Create comparison summary summary = f""" # đ Product Comparison Results ## Summary """ for item in comparison['comparison_summary']: summary += f"- {item}\n" summary += f"\n## Detailed Rankings\n" for i, product in enumerate(comparison['all_products'], 1): summary += f""" ### {i}. {product['product_name']} - Health Score: {product['overall_health_score']}/10 - Processing Level: {product['processing_level']}/6 - Ingredients: {product['total_ingredients']} - Allergens: {', '.join(product['allergens']) if product['allergens'] else 'None'} """ # Create comparison table comparison_data = [] for product in comparison['all_products']: comparison_data.append([ product['product_name'], f"{product['overall_health_score']}/10", f"{product['processing_level']}/6", product['total_ingredients'], ', '.join(product['allergens']) if product['allergens'] else 'None' ]) df = pd.DataFrame(comparison_data, columns=[ 'Product', 'Health Score', 'Processing Level', 'Total Ingredients', 'Allergens' ]) # Create comparison chart chart_html = create_comparison_chart(comparison['all_products']) return summary, df, chart_html except json.JSONDecodeError: return "Invalid JSON format. Please check your input.", "", "" except Exception as e: return f"Error: {str(e)}", "", "" def create_health_chart(ingredient_analyses): """Create health score visualization""" chart_html = """