ShubhangiAg's picture
Create app.py
5926e53 verified
Raw History Blame Contribute Delete
33.1 kB
# 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 = """
<div style="padding: 20px;">
<h3>πŸ“Š Ingredient Health Scores</h3>
<div style="display: flex; flex-direction: column; gap: 8px;">
"""
for ing in ingredient_analyses:
score = ing['health_score']
max_score = 10
bar_width = (score / max_score) * 100
# Color based on health score
if score >= 8:
color = "#4CAF50" # Green
elif score >= 6:
color = "#FFC107" # Yellow
elif score >= 4:
color = "#FF9800" # Orange
else:
color = "#F44336" # Red
chart_html += f"""
<div style="margin-bottom: 8px;">
<div style="font-size: 12px; margin-bottom: 2px; display: flex; justify-content: space-between;">
<span>{ing['name'][:30]}...</span>
<span>{score}/10</span>
</div>
<div style="background-color: #e0e0e0; height: 20px; border-radius: 10px; overflow: hidden;">
<div style="background-color: {color}; height: 100%; width: {bar_width}%; transition: width 0.3s;"></div>
</div>
</div>
"""
chart_html += """
</div>
<div style="margin-top: 15px; font-size: 12px; color: #666;">
🟒 Excellent (8-10) | 🟑 Good (6-7) | 🟠 Fair (4-5) | πŸ”΄ Poor (0-3)
</div>
</div>
"""
return chart_html
def create_comparison_chart(products):
"""Create product comparison visualization"""
chart_html = """
<div style="padding: 20px;">
<h3>πŸ“Š Product Health Score Comparison</h3>
<div style="display: flex; flex-direction: column; gap: 10px;">
"""
max_score = max([p['overall_health_score'] for p in products])
for product in products:
score = product['overall_health_score']
bar_width = (score / 10) * 100
# Color based on health score
if score >= 7:
color = "#4CAF50" # Green
elif score >= 5:
color = "#FFC107" # Yellow
else:
color = "#F44336" # Red
chart_html += f"""
<div style="margin-bottom: 10px;">
<div style="font-size: 14px; margin-bottom: 4px; display: flex; justify-content: space-between;">
<span><strong>{product['product_name']}</strong></span>
<span>{score}/10</span>
</div>
<div style="background-color: #e0e0e0; height: 25px; border-radius: 12px; overflow: hidden;">
<div style="background-color: {color}; height: 100%; width: {bar_width}%; transition: width 0.3s;"></div>
</div>
</div>
"""
chart_html += """
</div>
</div>
"""
return chart_html
# Create Gradio interface
with gr.Blocks(
title="πŸ₯— Smart Food Ingredient Analyzer",
css="""
.gradio-container {
max-width: 1400px !important;
}
.ingredient-input {
font-family: monospace;
}
"""
) as demo:
gr.Markdown("""
# πŸ₯— Smart Food Ingredient Analyzer
**AI-Powered RAG System for Food Safety & Health Analysis**
Analyze packaged food ingredients using advanced AI to make informed dietary choices.
Our system uses Retrieval-Augmented Generation (RAG) to provide detailed ingredient analysis.
## Features:
- πŸ” **Ingredient Analysis**: Detailed health scoring for each ingredient
- πŸ“Š **Health Scoring**: 1-10 scale based on nutritional value and processing level
- ⚠️ **Allergen Detection**: Identifies common allergens
- πŸ† **Product Comparison**: Compare multiple products to find the healthiest option
- πŸ€– **RAG Technology**: Uses semantic search for accurate ingredient matching
""")
with gr.Tabs():
# Single Product Analysis Tab
with gr.TabItem("πŸ” Single Product Analysis"):
gr.Markdown("### Analyze Individual Food Products")
with gr.Row():
with gr.Column(scale=1):
product_name_input = gr.Textbox(
label="Product Name",
placeholder="e.g., Whole Grain Crackers",
lines=1
)
ingredients_input = gr.Textbox(
label="Ingredients List",
placeholder="e.g., whole wheat flour, olive oil, sea salt, yeast",
lines=6,
elem_classes=["ingredient-input"]
)
analyze_btn = gr.Button("πŸ” Analyze Product", variant="primary")
gr.Markdown("""
**Tips:**
- Copy ingredients exactly as listed on package
- Separate ingredients with commas
- Include all ingredients for accurate analysis
""")
with gr.Column(scale=2):
analysis_output = gr.Markdown()
with gr.Tabs():
with gr.TabItem("πŸ“‹ Ingredient Details"):
ingredient_table = gr.Dataframe(
headers=["Ingredient", "Health Score", "Processing Level",
"Allergens", "Benefits", "Confidence"],
interactive=False
)
with gr.TabItem("πŸ“Š Health Chart"):
health_chart = gr.HTML()
# Product Comparison Tab
with gr.TabItem("πŸ† Product Comparison"):
gr.Markdown("### Compare Multiple Products")
with gr.Row():
with gr.Column(scale=1):
comparison_input = gr.Textbox(
label="Products (JSON Format)",
placeholder='[{"name": "Product A", "ingredients": "ingredient1, ingredient2"}, {"name": "Product B", "ingredients": "ingredient3, ingredient4"}]',
lines=10,
elem_classes=["ingredient-input"]
)
compare_btn = gr.Button("πŸ† Compare Products", variant="primary")
gr.Markdown("""
**JSON Format Example:**
```json
[
{
"name": "Organic Crackers",
"ingredients": "organic whole wheat flour, olive oil, sea salt"
},
{
"name": "Regular Crackers",
"ingredients": "enriched flour, vegetable oil, high fructose corn syrup"
}
]
```
""")
with gr.Column(scale=2):
comparison_output = gr.Markdown()
with gr.Tabs():
with gr.TabItem("πŸ“Š Comparison Table"):
comparison_table = gr.Dataframe(
headers=["Product", "Health Score", "Processing Level",
"Total Ingredients", "Allergens"],
interactive=False
)
with gr.TabItem("πŸ“ˆ Score Chart"):
comparison_chart = gr.HTML()
# Information Tab
with gr.TabItem("ℹ️ How It Works"):
gr.Markdown("""
## πŸ€– RAG Technology Explained
Our system uses **Retrieval-Augmented Generation (RAG)** to analyze food ingredients:
### 1. Knowledge Base
- Comprehensive database of ingredients and their health profiles
- Processing levels, allergen information, and nutritional benefits
- Continuously updated with latest nutritional research
### 2. Semantic Search
- Uses sentence transformers to understand ingredient context
- FAISS vector database for fast similarity matching
- Handles variations in ingredient naming and descriptions
### 3. Health Scoring Algorithm
```
Health Score = Base Score Γ— Processing Factor Γ— Allergen Factor
- Base Score: Nutritional value (1-10)
- Processing Factor: Less processed = higher score
- Allergen Factor: Common allergens reduce score
```
### 4. Recommendations
- Personalized suggestions based on ingredient analysis
- Identifies concerning additives and preservatives
- Suggests healthier alternatives when available
## πŸ“Š Scoring System
**Health Scores:**
- 🟒 **8-10**: Excellent (whole foods, minimal processing)
- 🟑 **6-7**: Good (some processing, generally safe)
- 🟠 **4-5**: Fair (moderate concerns, use occasionally)
- πŸ”΄ **0-3**: Poor (highly processed, avoid if possible)
**Processing Levels:**
- **1-2**: Minimal processing (whole foods)
- **3-4**: Moderate processing (refined but acceptable)
- **5-6**: High processing (additives, preservatives)
## 🎯 Use Cases
- **Grocery Shopping**: Compare similar products
- **Dietary Restrictions**: Identify allergens and additives
- **Health Goals**: Choose products aligned with nutrition goals
- **Education**: Learn about ingredient impacts on health
""")
# Event handlers
analyze_btn.click(
fn=analyze_single_product,
inputs=[product_name_input, ingredients_input],
outputs=[analysis_output, ingredient_table, health_chart]
)
compare_btn.click(
fn=compare_multiple_products,
inputs=[comparison_input],
outputs=[comparison_output, comparison_table, comparison_chart]
)
# Example data on load
demo.load(
fn=lambda: (
"Whole Grain Crackers",
"organic whole wheat flour, olive oil, sea salt, yeast, rosemary extract"
),
outputs=[product_name_input, ingredients_input]
)
return demo
if __name__ == "__main__":
demo = create_gradio_interface()
demo.launch()