File size: 33,092 Bytes
5926e53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
# 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()