Spaces:
Sleeping
Sleeping
File size: 23,504 Bytes
9031b79 ed62f2d be7f94e 3932a6f be7f94e 3932a6f be7f94e 884ecd8 3932a6f be1c9c3 fb762c2 3932a6f 884ecd8 3932a6f 9031b79 be7f94e 9031b79 3932a6f 9031b79 be7f94e ed62f2d be7f94e 3932a6f be7f94e ed62f2d be7f94e 9031b79 be7f94e 3932a6f 9031b79 3932a6f 884ecd8 3932a6f 9031b79 be1c9c3 3932a6f be7f94e 3932a6f 9031b79 3932a6f 9031b79 3932a6f 6454a3f 3932a6f 884ecd8 3932a6f 9031b79 3932a6f 884ecd8 3932a6f be7f94e 884ecd8 9031b79 884ecd8 9031b79 884ecd8 9031b79 884ecd8 be7f94e 3932a6f 9031b79 3932a6f be7f94e 3932a6f 9031b79 884ecd8 3932a6f be1c9c3 3932a6f 9031b79 3932a6f be7f94e 3932a6f be7f94e 9031b79 3932a6f a2f9242 3932a6f 9031b79 3932a6f a2f9242 3932a6f a2f9242 3932a6f a2f9242 9031b79 3932a6f 9031b79 3932a6f 9031b79 3932a6f a2f9242 3932a6f a2f9242 9031b79 a2f9242 9031b79 a2f9242 3932a6f a2f9242 9031b79 be1c9c3 9031b79 be1c9c3 57fc5f7 3932a6f be1c9c3 ed62f2d 3932a6f be1c9c3 a2f9242 3932a6f ed62f2d 3932a6f be7f94e 884ecd8 9031b79 884ecd8 9031b79 884ecd8 3932a6f ed62f2d 3932a6f ed62f2d 3932a6f be7f94e 3932a6f 884ecd8 3932a6f be7f94e 3932a6f be7f94e 3932a6f be7f94e 3932a6f 6454a3f 3932a6f 884ecd8 3932a6f 884ecd8 3932a6f 884ecd8 720e732 884ecd8 720e732 884ecd8 3932a6f 884ecd8 be7f94e 3932a6f 9031b79 3932a6f a2f9242 3932a6f a2f9242 ed62f2d be7f94e 3932a6f 9031b79 3932a6f 884ecd8 3932a6f 884ecd8 3932a6f 9166aef 3932a6f 884ecd8 3932a6f 884ecd8 3932a6f 884ecd8 3932a6f 4646187 3932a6f 4646187 884ecd8 3932a6f 884ecd8 3932a6f 884ecd8 3932a6f 884ecd8 3932a6f 884ecd8 3932a6f 884ecd8 3932a6f be1c9c3 | 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 | """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
|