Spaces:
Sleeping
Sleeping
refactor: Update model loading to include weights_only parameter and ensure model evaluation state
6454a3f Download model/recommender.py from marcolouis/romio_explore_ai_api: direct link, hf CLI and curl.
- Browser
- Download file 23.5 kB
-
https://huggingface.co/spaces/marcolouis/romio_explore_ai_api/resolve/main/model/recommender.py
- Command line
-
hf download hf://spaces/marcolouis/romio_explore_ai_api/model/recommender.py
-
curl -L -o recommender.py https://huggingface.co/spaces/marcolouis/romio_explore_ai_api/resolve/main/model/recommender.py
23.5 kB
| """ML-Powered Recommender System with Online Learning Support""" | |
| import os | |
| import json | |
| import torch | |
| import numpy as np | |
| from typing import List, Dict, Any, Optional | |
| from utils.supabase_client import get_supabase_client | |
| # Import ML models | |
| try: | |
| from model.neural_models import CompleteRecommenderModel | |
| from model.feature_extractor import FeatureExtractor | |
| from model.online_learner import OnlineLearner | |
| from model.diversification import DiversificationStrategy, DiversityConfigManager, DiversityController | |
| NEURAL_ML_AVAILABLE = True | |
| except ImportError as e: | |
| print(f"[WARN] Neural ML models not available: {e}") | |
| NEURAL_ML_AVAILABLE = False | |
| # Artifact storage directory | |
| ARTIFACT_DIR = os.path.join(os.path.dirname(__file__), "artifacts") | |
| os.makedirs(ARTIFACT_DIR, exist_ok=True) | |
| # Model file paths | |
| ML_MODEL_PATH = os.path.join(ARTIFACT_DIR, "neural_model.pth") | |
| VOCAB_PATH = os.path.join(ARTIFACT_DIR, "vocabularies.json") | |
| PLAN_EMBEDDINGS_PATH = os.path.join(ARTIFACT_DIR, "plan_embeddings.npz") | |
| ONLINE_LEARNER_PATH = os.path.join(ARTIFACT_DIR, "online_learner_state.pth") | |
| def init_recommender() -> "Recommender": | |
| """Create recommender and load ML artifacts if available.""" | |
| r = Recommender() | |
| r.load_artifacts() | |
| return r | |
| class Recommender: | |
| """ML-Powered Recommender System with Online Learning""" | |
| def __init__(self): | |
| self.supabase = get_supabase_client() | |
| self.device = "cuda" if torch.cuda.is_available() else "cpu" | |
| # ML model components | |
| self.ml_model: Optional[CompleteRecommenderModel] = None | |
| self.feature_extractor: Optional[FeatureExtractor] = None | |
| self.plan_embeddings: Dict[str, torch.Tensor] = {} | |
| self.online_learner: Optional[OnlineLearner] = None | |
| # Data caches | |
| self.plans_cache: Dict[str, Dict] = {} | |
| self.places_cache: Dict[str, Dict] = {} | |
| self.user_interactions_cache: Dict[str, List[Dict]] = {} | |
| # Diversification components | |
| self.diversity_config_manager = DiversityConfigManager() | |
| self.diversity_controller = DiversityController(self.diversity_config_manager) | |
| print(f"[INFO] Recommender initialized (device: {self.device})") | |
| def load_artifacts(self): | |
| """Load trained ML models from disk""" | |
| if not NEURAL_ML_AVAILABLE: | |
| print("[WARN] Neural ML not available") | |
| return False | |
| try: | |
| # Load feature extractor vocabularies | |
| self.feature_extractor = FeatureExtractor() | |
| if os.path.exists(VOCAB_PATH): | |
| self.feature_extractor.load_vocabularies(VOCAB_PATH) | |
| print("[INFO] Loaded feature extractor vocabularies") | |
| # Load trained ML model | |
| if os.path.exists(ML_MODEL_PATH): | |
| n_interests = len(self.feature_extractor.interest_to_idx) or 20 | |
| n_categories = len(self.feature_extractor.category_to_idx) or 50 | |
| self.ml_model = CompleteRecommenderModel( | |
| n_interests=n_interests, n_categories=n_categories, embedding_dim=64 | |
| ) | |
| checkpoint = torch.load(ML_MODEL_PATH, map_location=self.device, weights_only=False) | |
| self.ml_model.load_state_dict(checkpoint["model_state_dict"]) | |
| self.ml_model.to(self.device) | |
| self.ml_model.eval() | |
| print( | |
| f"[INFO] Loaded ML model with {sum(p.numel() for p in self.ml_model.parameters()):,} parameters" | |
| ) | |
| self._initialize_online_learner() | |
| else: | |
| print("[WARN] ML model not found, will need training") | |
| # Load pre-computed plan embeddings | |
| if os.path.exists(PLAN_EMBEDDINGS_PATH): | |
| data = np.load(PLAN_EMBEDDINGS_PATH, allow_pickle=True) | |
| plan_ids = data["plan_ids"] | |
| embeddings = data["embeddings"] | |
| for pid, emb in zip(plan_ids, embeddings): | |
| self.plan_embeddings[str(pid)] = torch.tensor(emb) | |
| print(f"[INFO] Loaded {len(self.plan_embeddings)} plan embeddings") | |
| return True | |
| except Exception as e: | |
| print(f"[ERROR] Failed to load ML artifacts: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return False | |
| def _initialize_online_learner(self): | |
| """Initialize online learning system""" | |
| try: | |
| if self.ml_model and self.feature_extractor: | |
| self.online_learner = OnlineLearner( | |
| model=self.ml_model, | |
| feature_extractor=self.feature_extractor, | |
| device=self.device, | |
| learning_rate=0.0001, | |
| batch_size=32, | |
| update_frequency=10, | |
| ) | |
| if os.path.exists(ONLINE_LEARNER_PATH): | |
| self.online_learner.load_state(ONLINE_LEARNER_PATH) | |
| print("[INFO] Online learning ENABLED") | |
| print( | |
| f" - Updates every {self.online_learner.update_frequency} interactions" | |
| ) | |
| print(f" - Batch size: {self.online_learner.batch_size}") | |
| else: | |
| print( | |
| "[WARN] Online learner not initialized (missing model or feature extractor)" | |
| ) | |
| except Exception as e: | |
| print(f"[WARN] Could not initialize online learner: {e}") | |
| self.online_learner = None | |
| def save_artifacts(self): | |
| """Save trained ML models to disk""" | |
| try: | |
| # Save ML model weights | |
| if self.ml_model is not None: | |
| checkpoint = { | |
| "model_state_dict": self.ml_model.state_dict(), | |
| } | |
| torch.save(checkpoint, ML_MODEL_PATH) | |
| print(f"[INFO] Saved ML model to {ML_MODEL_PATH}") | |
| # Save vocabularies | |
| if self.feature_extractor is not None: | |
| self.feature_extractor.save_vocabularies(VOCAB_PATH) | |
| # Save plan embeddings | |
| if self.plan_embeddings: | |
| plan_ids = list(self.plan_embeddings.keys()) | |
| embeddings = [self.plan_embeddings[pid].numpy() for pid in plan_ids] | |
| np.savez_compressed( | |
| PLAN_EMBEDDINGS_PATH, plan_ids=plan_ids, embeddings=embeddings | |
| ) | |
| print(f"[INFO] Saved {len(plan_ids)} plan embeddings") | |
| # Save online learner state | |
| if self.online_learner is not None: | |
| self.online_learner.save_state(ONLINE_LEARNER_PATH) | |
| return True | |
| except Exception as e: | |
| print(f"[ERROR] Failed to save artifacts: {e}") | |
| return False | |
| def recommend_for_user( | |
| self, | |
| user_id: str, | |
| limit: int = 10, | |
| filter_seen: bool = True, | |
| context: Optional[Dict[str, Any]] = None, | |
| ) -> List[Dict[str, Any]]: | |
| """Generate ML-powered recommendations for a user""" | |
| print(f"[INFO] Generating ML recommendations for user: {user_id}") | |
| if self.ml_model is None or self.feature_extractor is None: | |
| print("[WARN] ML model not available, using fallback") | |
| return self._popular_items(limit) | |
| try: | |
| # Fetch all plans | |
| plans = self._fetch_all_plans() | |
| if not plans: | |
| print("[WARN] No plans available in database") | |
| return [] | |
| # Get user interaction history | |
| user_interactions = self._fetch_user_interactions(user_id) | |
| is_new_user = len(user_interactions) == 0 | |
| if is_new_user: | |
| print(f"[INFO] New user detected - using cold start strategy") | |
| candidate_plans = plans | |
| # Compute plan embeddings if needed | |
| self._ensure_plan_embeddings(candidate_plans) | |
| # Compute user embedding from history | |
| user_embedding = self._compute_user_embedding(user_interactions) | |
| # Score all candidate plans | |
| scores = [] | |
| plan_ids = [] | |
| plan_objects = [] | |
| for plan in candidate_plans: | |
| plan_id = str(plan["id"]) | |
| if plan_id in self.plan_embeddings: | |
| plan_embedding = ( | |
| self.plan_embeddings[plan_id].unsqueeze(0).to(self.device) | |
| ) | |
| user_emb = user_embedding.unsqueeze(0).to(self.device) | |
| with torch.no_grad(): | |
| score = self.ml_model.predict_score(user_emb, plan_embedding) | |
| scores.append(score.item()) | |
| plan_ids.append(plan_id) | |
| plan_objects.append(plan) | |
| if not scores: | |
| print("[WARN] No scoreable plans found, using popular items") | |
| return self._popular_items(limit) | |
| # Cold start: blend ML scores with popularity for new users | |
| if is_new_user: | |
| adjusted_scores = [] | |
| for i, plan in enumerate(plan_objects): | |
| ml_score = scores[i] | |
| popularity_score = float(plan.get("rating", 3.0)) / 5.0 | |
| blended_score = 0.7 * ml_score + 0.3 * popularity_score | |
| adjusted_scores.append(blended_score) | |
| scores = adjusted_scores | |
| print("[INFO] Applied cold start blending (ML + popularity)") | |
| # Sort by score | |
| sorted_indices = np.argsort(scores)[::-1] | |
| # Apply diversification | |
| user_interest_history = self._get_user_interest_history(user_id) | |
| diversity_params = self.diversity_controller.get_diversification_params() | |
| if context: | |
| diversity_params = self.diversity_controller.apply_context_adjustment( | |
| diversity_params, context | |
| ) | |
| diversifier = DiversificationStrategy( | |
| exploration_rate=diversity_params["exploration_rate"], | |
| strategic_positions=diversity_params["strategic_positions"], | |
| exploration_frequency=diversity_params["exploration_frequency"], | |
| min_interest_coverage=diversity_params["min_interest_coverage"], | |
| ) | |
| recommendations = diversifier.diversify_recommendations( | |
| sorted_indices=sorted_indices, | |
| plan_objects=plan_objects, | |
| plan_ids=plan_ids, | |
| scores=scores, | |
| limit=limit, | |
| user_interest_history=user_interest_history, | |
| ) | |
| return recommendations | |
| except Exception as e: | |
| print(f"[ERROR] ML recommendation failed: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return self._popular_items(limit) | |
| def update_online(self, interaction_data: dict) -> Dict[str, Any]: | |
| """Update model online from a single interaction""" | |
| if not self.online_learner: | |
| return {"updated": False, "message": "Online learner not initialized"} | |
| try: | |
| # Get plan data | |
| plan_id = interaction_data["plan_id"] | |
| plan = self.plans_cache.get(plan_id) | |
| if not plan: | |
| plan_resp = ( | |
| self.supabase.table("plans").select("*").eq("id", plan_id).execute() | |
| ) | |
| if plan_resp.data: | |
| plan = plan_resp.data[0] | |
| self.plans_cache[plan_id] = plan | |
| else: | |
| print(f"[WARN] Plan {plan_id} not found") | |
| return {"updated": False, "message": "Plan not found"} | |
| # Get user history | |
| user_id = interaction_data["user_id"] | |
| user_history = self._fetch_user_interactions(user_id) | |
| # Update model | |
| result = self.online_learner.add_interaction( | |
| interaction=interaction_data, | |
| plan_data=plan, | |
| user_history=user_history, | |
| plan_embeddings=self.plan_embeddings, | |
| ) | |
| # Save if model was updated | |
| if result.get("updated"): | |
| self.save_artifacts() | |
| return result | |
| except Exception as e: | |
| print(f"[ERROR] Online update failed: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return {"updated": False, "error": str(e)} | |
| def _compute_user_embedding(self, interactions: List[Dict]) -> torch.Tensor: | |
| """Compute user embedding from interaction history using LSTM""" | |
| if not interactions: | |
| return torch.zeros(64) | |
| sequence = self.feature_extractor.extract_user_interaction_sequence( | |
| interactions, self.plan_embeddings, max_sequence_length=20 | |
| ) | |
| sequence_batch = sequence.unsqueeze(0).to(self.device) | |
| with torch.no_grad(): | |
| user_embedding = self.ml_model.encode_user(sequence_batch) | |
| return user_embedding.squeeze(0).cpu() | |
| def _ensure_plan_embeddings(self, plans: List[Dict]): | |
| """Compute embeddings for plans that don't have them yet""" | |
| plans_to_embed = [] | |
| for plan in plans: | |
| plan_id = str(plan["id"]) | |
| if plan_id not in self.plan_embeddings: | |
| plans_to_embed.append(plan) | |
| if not plans_to_embed: | |
| return | |
| print(f"[INFO] Computing embeddings for {len(plans_to_embed)} plans") | |
| self.ml_model.eval() | |
| for plan in plans_to_embed: | |
| try: | |
| interest_ids, numerical_features = ( | |
| self.feature_extractor.extract_plan_features(plan) | |
| ) | |
| interest_batch = interest_ids.unsqueeze(0).to(self.device) | |
| numerical_batch = numerical_features.unsqueeze(0).to(self.device) | |
| with torch.no_grad(): | |
| plan_embedding = self.ml_model.encode_plan( | |
| interest_batch, numerical_batch | |
| ) | |
| plan_id = str(plan["id"]) | |
| self.plan_embeddings[plan_id] = plan_embedding.squeeze(0).cpu() | |
| except Exception as e: | |
| print(f"[WARN] Failed to embed plan {plan.get('id')}: {e}") | |
| def _fetch_all_plans(self) -> List[Dict]: | |
| """Fetch all plans from Supabase""" | |
| try: | |
| response = self.supabase.table("plans").select("*").execute() | |
| plans = response.data or [] | |
| for plan in plans: | |
| self.plans_cache[str(plan["id"])] = plan | |
| return plans | |
| except Exception as e: | |
| print(f"[ERROR] Failed to fetch plans: {e}") | |
| return [] | |
| def _fetch_user_interactions(self, user_id: str) -> List[Dict]: | |
| """Fetch user's interaction history""" | |
| try: | |
| response = ( | |
| self.supabase.table("user_plan_interactions") | |
| .select("*") | |
| .eq("user_id", user_id) | |
| .order("created_at", desc=False) | |
| .execute() | |
| ) | |
| interactions = response.data or [] | |
| self.user_interactions_cache[user_id] = interactions | |
| return interactions | |
| except Exception as e: | |
| print(f"[WARN] No interactions found for user {user_id}: {e}") | |
| return [] | |
| def _popular_items(self, limit: int = 10) -> List[Dict[str, Any]]: | |
| """Fallback: return popular plans""" | |
| try: | |
| response = ( | |
| self.supabase.table("plans") | |
| .select("id, rating") | |
| .order("rating", desc=True) | |
| .limit(limit) | |
| .execute() | |
| ) | |
| items = response.data or [] | |
| if not items: | |
| print("[WARN] No rated plans, fetching any available plans") | |
| response = ( | |
| self.supabase.table("plans").select("id").limit(limit).execute() | |
| ) | |
| items = response.data or [] | |
| recommendations = [ | |
| {"item_id": str(item["id"]), "score": float(item.get("rating", 3.0))} | |
| for item in items | |
| ] | |
| print(f"[INFO] Returning {len(recommendations)} popular items as fallback") | |
| return recommendations | |
| except Exception as e: | |
| print(f"[ERROR] Failed to fetch popular items: {e}") | |
| return [] | |
| def retrain_from_supabase(self) -> Dict[str, Any]: | |
| """Train ML model from scratch using Supabase data""" | |
| print("=" * 60) | |
| print("STARTING ML MODEL TRAINING (BATCH)") | |
| print("=" * 60) | |
| if not NEURAL_ML_AVAILABLE: | |
| return {"error": "Neural ML not available"} | |
| try: | |
| from model.trainer import ( | |
| MLTrainer, | |
| RecommendationDataset, | |
| create_train_val_split, | |
| ) | |
| from torch.utils.data import DataLoader | |
| # Fetch data | |
| print("[1/7] Fetching data from Supabase...") | |
| plans = self._fetch_all_plans() | |
| interests_resp = self.supabase.table("interests").select("*").execute() | |
| interests = interests_resp.data or [] | |
| places_resp = self.supabase.table("places").select("*").execute() | |
| places = places_resp.data or [] | |
| interactions_resp = ( | |
| self.supabase.table("user_plan_interactions").select("*").execute() | |
| ) | |
| interactions = interactions_resp.data or [] | |
| print(f" Loaded: {len(plans)} plans, {len(interactions)} interactions") | |
| if len(interactions) < 50: | |
| return {"error": "Need at least 50 interactions to train"} | |
| # Build feature extractor | |
| print("[2/7] Building feature vocabularies...") | |
| self.feature_extractor = FeatureExtractor() | |
| vocab_info = self.feature_extractor.build_vocabularies( | |
| plans, places, interests | |
| ) | |
| # Initialize ML model | |
| print("[3/7] Initializing ML model...") | |
| self.ml_model = CompleteRecommenderModel( | |
| n_interests=vocab_info["n_interests"], | |
| n_categories=vocab_info["n_categories"], | |
| embedding_dim=64, | |
| ) | |
| # Prepare training data | |
| print("[4/7] Preparing training data...") | |
| self._ensure_plan_embeddings(plans) | |
| user_ids = [] | |
| plan_ids = [] | |
| labels = [] | |
| user_interactions_dict = {} | |
| for interaction in interactions: | |
| uid = str(interaction["user_id"]) | |
| if uid not in user_interactions_dict: | |
| user_interactions_dict[uid] = [] | |
| user_interactions_dict[uid].append(interaction) | |
| plans_dict = {str(p["id"]): p for p in plans} | |
| for interaction in interactions: | |
| uid = str(interaction["user_id"]) | |
| pid = str(interaction["plan_id"]) | |
| rating_val = interaction.get("rating") | |
| if rating_val is not None: | |
| try: | |
| label = float(rating_val) | |
| except (TypeError, ValueError): | |
| label = 3.0 | |
| elif interaction.get("interaction_type") == "bookmark": | |
| label = 5.0 | |
| elif interaction.get("interaction_type") == "view": | |
| raw_duration = interaction.get("duration_seconds") | |
| try: | |
| duration = float(raw_duration) if raw_duration is not None else 0.0 | |
| except (TypeError, ValueError): | |
| duration = 0.0 | |
| label = min(5.0, 2.0 + duration / 60.0) | |
| else: | |
| label = 3.0 | |
| user_ids.append(uid) | |
| plan_ids.append(pid) | |
| labels.append(label) | |
| print(f" Created {len(user_ids)} training samples") | |
| # Create train/val split | |
| print("[5/7] Splitting train/validation...") | |
| train_users, train_plans, train_labels, val_users, val_plans, val_labels = ( | |
| create_train_val_split(user_ids, plan_ids, labels, val_ratio=0.2) | |
| ) | |
| train_dataset = RecommendationDataset( | |
| train_users, | |
| train_plans, | |
| train_labels, | |
| plans_dict, | |
| user_interactions_dict, | |
| self.plan_embeddings, | |
| self.feature_extractor, | |
| ) | |
| val_dataset = RecommendationDataset( | |
| val_users, | |
| val_plans, | |
| val_labels, | |
| plans_dict, | |
| user_interactions_dict, | |
| self.plan_embeddings, | |
| self.feature_extractor, | |
| ) | |
| train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) | |
| val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False) | |
| # Train the model | |
| print("[6/7] Training ML model...") | |
| trainer = MLTrainer(self.ml_model, device=self.device) | |
| train_losses, val_losses, metrics = trainer.train( | |
| train_loader, val_loader, n_epochs=30, early_stopping_patience=5 | |
| ) | |
| # Save artifacts | |
| print("\n[7/7] Saving trained artifacts...") | |
| self.save_artifacts() | |
| print("\n[INIT] Reinitializing online learner...") | |
| self._initialize_online_learner() | |
| print("\n" + "=" * 60) | |
| print("ML TRAINING COMPLETE!") | |
| print("=" * 60) | |
| return { | |
| "status": "success", | |
| "n_plans": len(plans), | |
| "n_interactions": len(interactions), | |
| "n_training_samples": len(train_users), | |
| "final_val_loss": val_losses[-1] if val_losses else None, | |
| "model_parameters": sum(p.numel() for p in self.ml_model.parameters()), | |
| "online_learning": "enabled" if self.online_learner else "disabled", | |
| } | |
| except Exception as e: | |
| print(f"[ERROR] Training failed: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return {"error": str(e)} | |
| def _get_user_interest_history(self, user_id: str) -> set: | |
| """Get all interests the user has interacted with""" | |
| user_interest_history = set() | |
| interactions = self._fetch_user_interactions(user_id) | |
| for interaction in interactions: | |
| plan_id = str(interaction.get("plan_id")) | |
| if plan_id in self.plans_cache: | |
| plan = self.plans_cache[plan_id] | |
| raw_interests = plan.get("interestIds", []) | |
| if isinstance(raw_interests, str): | |
| try: | |
| interests = json.loads(raw_interests) | |
| except: | |
| interests = [] | |
| else: | |
| interests = raw_interests | |
| user_interest_history.update(str(i) for i in interests) | |
| return user_interest_history | |