Spaces:
Sleeping
Sleeping
Download train.py from marcolouis/romio_explore_ai_api: direct link, hf CLI and curl.
- Browser
- Download file 5.93 kB
-
https://huggingface.co/spaces/marcolouis/romio_explore_ai_api/resolve/main/train.py
- Command line
-
hf download hf://spaces/marcolouis/romio_explore_ai_api/train.py
-
curl -L -o train.py https://huggingface.co/spaces/marcolouis/romio_explore_ai_api/resolve/main/train.py
5.93 kB
| """ | |
| 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() | |