#!/usr/bin/env python3 """ Group 5 Pattern Recognition Project - Deployment Version ======================================================= Recipe Recommendation System with Google Drive file loading for deployment. Optimized for Hugging Face Spaces or similar platforms. """ import gradio as gr import torch from transformers import BertTokenizer, BertModel import pickle import os import csv from typing import List, Dict import time import ast import requests import gdown from pathlib import Path # Google Drive file IDs (you'll need to replace these with your actual file IDs) GOOGLE_DRIVE_FILES = { 'torch_recipe_embeddings_231630.pt': '1PSidY1toSfgECXDxa4pGza56Jq6vOq6t', 'tag_based_bert_model.pth': '1LBl7yFs5JFqOsgfn88BF9g83W9mxiBm6', 'RAW_recipes.csv': '1rFJQzg_ErwEpN6WmhQ4jRyiXv6JCINyf', 'recipe_statistics_231630.pkl': '1n8TNT-6EA_usv59CCCU1IXqtuM7i084E', 'recipe_scores_231630.pkl': '1gfPBzghKHOZqgJu4VE9NkandAd6FGjrA' } def download_file_from_drive(file_id: str, destination: str) -> bool: """Download file from Google Drive""" try: print(f"📥 Downloading {destination}...") url = f"https://drive.google.com/uc?id={file_id}" gdown.download(url, destination, quiet=False) return True except Exception as e: print(f"❌ Error downloading {destination}: {e}") return False def ensure_files_downloaded(): """Ensure all required files are downloaded from Google Drive""" print("🔍 Checking required files...") for filename, file_id in GOOGLE_DRIVE_FILES.items(): if not os.path.exists(filename): if file_id == 'YOUR_EMBEDDINGS_FILE_ID_HERE': print(f"⚠️ {filename} not configured for download") continue print(f"📥 Downloading {filename} from Google Drive...") success = download_file_from_drive(file_id, filename) if not success: print(f"❌ Failed to download {filename}") return False print("✅ All files ready!") return True class DeployableRecipeSearch: """ Deployment-ready recipe search system """ def __init__(self): print("🚀 Initializing Recipe Search System...") self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(f"📱 Device: {self.device}") # Ensure files are downloaded if not ensure_files_downloaded(): print("❌ Failed to download required files") self.is_ready = False return # Load tokenizer and model self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') self.model = BertModel.from_pretrained('bert-base-uncased') # Load trained model if available if os.path.exists('tag_based_bert_model.pth'): print("🧠 Loading trained BERT model...") self.model.load_state_dict(torch.load('tag_based_bert_model.pth', map_location=self.device)) print("✅ Trained model loaded!") else: print("⚠️ Using pre-trained BERT") self.model.to(self.device) self.model.eval() # Load data self.load_data() print("🎉 Recipe Search System ready!") def safe_literal_eval(self, text): """Safely evaluate string representations of lists""" if not text or text == 'nan' or str(text).lower() == 'nan': return [] try: if isinstance(text, str) and text.startswith('[') and text.endswith(']'): return ast.literal_eval(text) elif isinstance(text, str): return [item.strip() for item in text.split(',') if item.strip()] elif isinstance(text, list): return text else: return [] except: return [] def safe_int(self, value): """Safely convert value to int""" try: return int(float(value)) except: return 0 def load_data(self): """Load all required data""" # Load PyTorch embeddings embeddings_file = 'torch_recipe_embeddings_231630.pt' if os.path.exists(embeddings_file): print(f"📥 Loading embeddings...") self.recipe_embeddings = torch.load(embeddings_file, map_location=self.device) print(f"✅ Loaded {self.recipe_embeddings.shape[0]} embeddings") else: print(f"❌ Embeddings not found") self.is_ready = False return # Load recipes from CSV self.load_recipes_from_csv() # Load statistics and scores self.load_statistics_and_scores() # Check if we have everything we need self.is_ready = all([ self.recipe_embeddings is not None, len(self.recipes) > 0, len(self.recipe_stats) > 0, len(self.recipe_scores) > 0 ]) if self.is_ready: self.fix_recipe_id_mismatches() print("🎯 All data loaded successfully!") else: print("⚠️ Some data missing") def load_recipes_from_csv(self): """Load and filter recipes from CSV""" print("📊 Loading recipes from CSV...") self.recipes = [] if os.path.exists('RAW_recipes.csv'): valid_recipes = [] with open('RAW_recipes.csv', 'r', encoding='utf-8') as file: csv_reader = csv.DictReader(file) for row_idx, row in enumerate(csv_reader): try: # Apply filtering logic name = row.get('name', '') if not name or str(name).lower().strip() in ['', 'nan', 'unknown recipe']: continue name = str(name).lower().strip() tags = self.safe_literal_eval(row.get('tags', '[]')) ingredients = self.safe_literal_eval(row.get('ingredients', '[]')) # Filter conditions if not tags or len(tags) == 0: continue if not ingredients or len(ingredients) == 0: continue if len(name) == 0 or name == 'unknown recipe': continue recipe = { 'id': int(row.get('id', row_idx)), 'name': name, 'minutes': self.safe_int(row.get('minutes', 0)), 'tags': tags, 'ingredients': ingredients, 'n_steps': self.safe_int(row.get('n_steps', 0)), 'description': str(row.get('description', '')).strip() } valid_recipes.append(recipe) if len(valid_recipes) >= 231630: break except Exception as e: continue self.recipes = valid_recipes print(f"✅ Loaded {len(self.recipes)} recipes") else: print("❌ RAW_recipes.csv not found") self.recipes = [] def load_statistics_and_scores(self): """Load recipe statistics and scores""" # Load statistics stats_file = 'recipe_statistics_231630.pkl' try: if os.path.exists(stats_file): with open(stats_file, 'rb') as f: self.recipe_stats = pickle.load(f) print(f"✅ Loaded statistics for {len(self.recipe_stats)} recipes") else: self.recipe_stats = {} for recipe in self.recipes: self.recipe_stats[recipe['id']] = (4.0, 10, 5) except Exception as e: print(f"⚠️ Statistics loading failed: {e}") self.recipe_stats = {} for recipe in self.recipes: self.recipe_stats[recipe['id']] = (4.0, 10, 5) # Load scores scores_file = 'recipe_scores_231630.pkl' try: if os.path.exists(scores_file): with open(scores_file, 'rb') as f: self.recipe_scores = pickle.load(f) print(f"✅ Loaded scores for {len(self.recipe_scores)} recipes") else: self.recipe_scores = {} for recipe in self.recipes: self.recipe_scores[recipe['id']] = 0.5 except Exception as e: print(f"⚠️ Scores loading failed: {e}") self.recipe_scores = {} for recipe in self.recipes: self.recipe_scores[recipe['id']] = 0.5 def fix_recipe_id_mismatches(self): """Filter statistics and scores to match loaded recipes""" loaded_recipe_ids = set(recipe['id'] for recipe in self.recipes) # Filter statistics original_stats_count = len(self.recipe_stats) self.recipe_stats = { recipe_id: stats for recipe_id, stats in self.recipe_stats.items() if recipe_id in loaded_recipe_ids } # Filter scores original_scores_count = len(self.recipe_scores) self.recipe_scores = { recipe_id: score for recipe_id, score in self.recipe_scores.items() if recipe_id in loaded_recipe_ids } print(f"🔧 Aligned data: Stats {original_stats_count}→{len(self.recipe_stats)}, Scores {original_scores_count}→{len(self.recipe_scores)}") def search_recipes(self, query: str, num_results: int = 5, min_rating: float = 3.0) -> str: """Search for recipes and return formatted HTML results""" if not self.is_ready: return """
⚡ Search completed in {search_time:.2f}s
Enter a search query and click "Search Recipes" to see results.