Spaces:
Sleeping
Sleeping
File size: 5,930 Bytes
3932a6f 9031b79 488913f 9031b79 3932a6f 488913f 9031b79 488913f 3932a6f 488913f 3932a6f 488913f 9031b79 488913f 3932a6f 9031b79 3932a6f 488913f 9031b79 488913f 3932a6f 9031b79 488913f 9031b79 488913f 3932a6f 9031b79 488913f 9031b79 488913f 9031b79 488913f 9031b79 488913f 3932a6f 488913f 9031b79 488913f 9031b79 488913f 9031b79 488913f 3932a6f 9031b79 488913f 9031b79 488913f 9031b79 3932a6f 488913f 9031b79 488913f 9031b79 488913f 3932a6f 9031b79 3932a6f 488913f 3932a6f 9031b79 488913f 9031b79 3932a6f 9031b79 3932a6f 9031b79 3932a6f 9031b79 3932a6f 9031b79 488913f 9031b79 488913f 9031b79 488913f 9031b79 488913f 9031b79 488913f 9031b79 488913f 9031b79 488913f 9031b79 488913f 9031b79 488913f 9031b79 488913f 9031b79 488913f | 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 | """
Standalone training script for Romio ML recommender models.
Supports:
- Training the model with real Supabase data
- Generating dummy interaction data for testing
- Testing recommendation output
"""
import argparse
import sys
from pathlib import Path
import random
from datetime import datetime, timedelta
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
from model.recommender import init_recommender
from utils.supabase_client import get_supabase_client
# ============================================================
# Dummy data generation
# ============================================================
def generate_dummy_data(n_interactions=500):
"""
Generate fake user → plan interactions for testing model training.
Used only when real data does not exist.
"""
supabase = get_supabase_client()
# Get existing users
users_resp = supabase.table("users").select("id").execute()
users = [u["id"] for u in users_resp.data]
if not users:
return False
# Get existing plans
plans_resp = supabase.table("plans").select("id").execute()
plans = [p["id"] for p in plans_resp.data]
if not plans:
return False
interactions = []
# Create random interactions
for _ in range(n_interactions):
user_id = random.choice(users)
plan_id = random.choice(plans)
interaction_type = random.choices(
["view", "bookmark", "rate"], weights=[0.7, 0.2, 0.1]
)[0]
interaction = {
"user_id": user_id,
"plan_id": plan_id,
"interaction_type": interaction_type,
"created_at": (
datetime.now() - timedelta(days=random.randint(0, 30))
).isoformat(),
}
# Add extra fields depending on interaction type
if interaction_type == "rate":
interaction["rating"] = random.choices(
[1, 2, 3, 4, 5], weights=[0.05, 0.1, 0.2, 0.35, 0.3]
)[0]
if interaction_type == "view":
interaction["duration_seconds"] = random.randint(10, 180)
interactions.append(interaction)
# Insert into database in batches
batch_size = 50
for i in range(0, len(interactions), batch_size):
batch = interactions[i : i + batch_size]
try:
supabase.table("user_plan_interactions").insert(batch).execute()
except Exception:
continue
return True
# ============================================================
# Training
# ============================================================
def train_model():
"""Train recommendation model using Supabase data."""
try:
print("[TRAIN] Initializing recommender...")
recommender = init_recommender()
print("[TRAIN] Starting training...")
result = recommender.retrain_from_supabase()
if "error" in result:
print(f"[ERROR] Training failed: {result['error']}")
return False
print("[TRAIN] Training completed successfully")
print(f" Plans: {result.get('n_plans')}")
print(f" Interactions: {result.get('n_interactions')}")
print(f" Training samples: {result.get('n_training_samples')}")
print(f" Validation loss: {result.get('final_val_loss'):.4f}")
print("[TRAIN] Artifacts saved in model/artifacts/")
return True
except Exception as e:
print(f"[ERROR] Training exception: {e}")
import traceback
traceback.print_exc()
return False
# ============================================================
# Testing recommendations
# ============================================================
def test_recommendations(user_id=None, limit=10):
"""
Test the trained model by generating recommendation output.
"""
try:
recommender = init_recommender()
# Pick a random user if none provided
if user_id is None:
supabase = get_supabase_client()
users_resp = supabase.table("users").select("id").limit(1).execute()
if users_resp.data:
user_id = users_resp.data[0]["id"]
else:
return False
recommender.recommend_for_user(user_id, limit=limit)
return True
except Exception:
return False
# ============================================================
# CLI entry point
# ============================================================
def main():
"""Main CLI controller for training and testing."""
parser = argparse.ArgumentParser(description="Romio ML Training Utility")
parser.add_argument("--generate-data", action="store_true",
help="Generate dummy interactions before training")
parser.add_argument("--n-interactions", type=int, default=500,
help="Number of dummy interactions to generate")
parser.add_argument("--test", action="store_true",
help="Test recommendations after training")
parser.add_argument("--test-only", action="store_true",
help="Only test recommendations (skip training)")
parser.add_argument("--user-id", type=str, default=None,
help="User ID for testing (optional)")
args = parser.parse_args()
success = True
# Generate dummy data
if args.generate_data:
success = generate_dummy_data(args.n_interactions)
if not success:
sys.exit(1)
# Only test mode
if args.test_only:
success = test_recommendations(args.user_id)
sys.exit(0 if success else 1)
# Train model
if success:
success = train_model()
# Optional test after training
if success and args.test:
test_recommendations(args.user_id)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()
|