Spaces:
Sleeping
Download README.md from marcolouis/romio_explore_ai_api: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/spaces/marcolouis/romio_explore_ai_api/resolve/main/README.md
- Command line
-
hf download hf://spaces/marcolouis/romio_explore_ai_api/README.md
-
curl -L -o README.md https://huggingface.co/spaces/marcolouis/romio_explore_ai_api/resolve/main/README.md
title: Romio Explore Ai Api
emoji: π
colorFrom: red
colorTo: purple
sdk: docker
pinned: false
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
Romio Explore AI Recommender API
API and ML pipeline for personalized plan recommendations with online learning and smart diversification, backed by Supabase and PyTorch, packaged for local use and Hugging Face Spaces.
Folder Structure
romio_explore_ai_api/
ββ main.py # FastAPI app + HTTP endpoints
ββ train.py # Offline/batch training + testing script
ββ Dockerfile # Image for running the API (HF Spaces / Docker)
ββ requirements.txt # Python dependencies
ββ apt.txt # System dependencies (Debian/Ubuntu)
ββ fsq_cache/ # Foursquare-style place JSON cache (cities)
β ββ *.json
ββ model/
β ββ __init__.py
β ββ recommender.py # High-level recommender orchestration
β ββ feature_extractor.py # Feature engineering from Supabase data
β ββ neural_models.py # PyTorch neural networks (plans, users, scores)
β ββ online_learner.py # Online learning (realβtime updates)
β ββ trainer.py # ML training pipeline, metrics, datasets
β ββ diversification.py # Smart diversification & exploration strategies
β ββ artifacts/ # Saved ML artifacts
β ββ neural_model.pth
β ββ best_model.pth
β ββ vocabularies.json
β ββ plan_embeddings.npz
ββ utils/
ββ __init__.py
ββ supabase_client.py # Supabase client factory (reads .env)
Core Components
FastAPI service (
main.py)- Root:
GET / - Health:
GET /health - Recommendations:
GET /recommend/{userId} - Explore feed (Flutter-compatible):
GET /explore/{userId} - Track interaction (online learning):
POST /track-interaction - Online learning stats:
GET /online-stats - Admin retrain:
POST /retrain(requiresX-Admin-Keyheader)
- Root:
Recommender (
model/recommender.py)- Loads & saves artifacts (
neural_model.pth,vocabularies.json,plan_embeddings.npz). recommend_for_user(user_id, limit, context=None)β main API used bymain.py.retrain_from_supabase()β full batch training from Supabase.- Integrates online learning via
OnlineLearner. - Integrates smart diversification via
DiversificationStrategyto prevent filter bubbles.
- Loads & saves artifacts (
Diversification System (
model/diversification.py)DiversificationStrategyβ injects diverse interests at strategic positions to balance relevance with exploration.DiversityConfigManagerβ centralized configuration for diversity levels (FOCUSED, BALANCED, DISCOVERY, AGGRESSIVE).DiversityControllerβ high-level controller for managing diversity settings.AdaptiveExplorationβ optional adaptive exploration rate based on user behavior.
ML & Training (
model/*.py)feature_extractor.pyβ builds vocabularies and tensors from plans, places, interests, interactions.neural_models.pyβ three main models:PlanEmbeddingNetworkUserPreferenceNetworkScorePredictor- Combined into
CompleteRecommenderModel.
online_learner.pyβ experience replay + miniβbatch online updates.trainer.pyβRecommendationDataset,MLTrainer, metrics (MSE/MAE/RMSE, Precision@K, Recall@K, NDCG@K).diversification.pyβ diversification strategies, config management, and exploration logic.
Supabase integration (
utils/supabase_client.py)- Uses
SUPABASE_URLandSUPABASE_SERVICE_ROLE_KEYfrom.env. - Accesses tables like
plans,users,places,interests,user_plan_interactions.
- Uses
Environment Variables
Create a .env file in the project root with at least:
SUPABASE_URL=<your-supabase-url>
SUPABASE_SERVICE_ROLE_KEY=<your-service-role-key>
SECRET_KEY=<admin-secret-for-X-Admin-Key>
Used by:
utils/supabase_client.pyβSUPABASE_URL,SUPABASE_SERVICE_ROLE_KEYmain.pyβSECRET_KEYfor admin verification
Installation (Local, Without Docker)
1. Create & activate a virtual environment (recommended)
python -m venv .venv
# Windows PowerShell
.venv\Scripts\Activate.ps1
# macOS/Linux
source .venv/bin/activate
2. Install Python dependencies
pip install --upgrade pip
pip install -r requirements.txt
3. (If needed) Install system dependency
On Debian/Ubuntu (already handled in Dockerfile, but for bare metal):
sudo apt-get update && sudo apt-get install -y libgomp1
Running the API Locally
Option A: Directly with uvicorn (recommended for dev)
uvicorn main:app --host 0.0.0.0 --port 7860 --reload
Or using the __main__ guard in main.py:
python main.py
The API will be available at:
- Base URL:
http://localhost:7860 - Docs (Swagger UI):
http://localhost:7860/docs - ReDoc:
http://localhost:7860/redoc
Option B: Run via Docker (same config as Hugging Face Space)
Build:
docker build -t romio-explore-ai-api .
Run:
docker run --rm -p 7860:7860 \
--env-file .env \
romio-explore-ai-api
API Endpoints & Usage
GET
/- Returns basic service metadata and available endpoints.
GET
/health- Health check:
{"status": "ok"}.
- Health check:
GET
/recommend/{userId}- Query params:
limit(int, default10)
- Response:
{"userId": "...", "limit": 10, "recommendations": [{"item_id": "<plan-id>", "score": <float>}, ...]}
- Query params:
GET
/explore/{userId}- Query params:
page(int, default1,>=1)limit(int, default20,1β100)
- Behavior:
- Pulls ML recommendations with smart diversification (injects diverse interests to prevent filter bubbles).
- Automatically excludes plans created by the current user (only shows other users' plans).
- Paginates results, fetches matching
plansfrom Supabase, joins with:users(creator info)places(forplaceIds)interests
- Returns a Flutterβcompatible explore feed (
ExplorePlanModel/ExplorePlace).
- Query params:
POST
/track-interaction- Body (
application/json):{ "user_id": "uuid-or-string", "plan_id": "uuid-or-string", "interaction_type": "view | bookmark | rate", "rating": 5, "duration_seconds": 120 } - Behavior:
- Inserts a row into
user_plan_interactions. - Schedules asynchronous
update_model_online(...)for real-time learning.
- Inserts a row into
- Body (
GET
/online-stats- Returns online-learning statistics (
n_interactions,n_updates,buffer_size, recent loss, etc.).
- Returns online-learning statistics (
POST
/retrain(admin)- Headers:
X-Admin-Key: <SECRET_KEY>
- Triggers full batch retraining via
Recommender.retrain_from_supabase(), saving fresh artifacts tomodel/artifacts/.
- Headers:
Training & Testing the ML Model
All offline training logic lives in train.py and model/trainer.py.
Basic Training
python train.py
This will:
- Initialize the recommender and Supabase client.
- Fetch
users,plans,places,interests,user_plan_interactions. - Build vocabularies and plan embeddings.
- Train
CompleteRecommenderModelwith train/validation split. - Save artifacts into
model/artifacts/.
Generate Dummy Interaction Data (for testing)
python train.py --generate-data --n-interactions 500
This:
- Pulls existing
usersandplansfrom Supabase. - Generates synthetic
user_plan_interactions. - Inserts them in batches into the
user_plan_interactionstable.
Train + Then Test Recommendations
python train.py --test
Or test for a specific user (after training / artifacts exist):
python train.py --test-only --user-id <some-user-id>
Online Learning (Real-Time Updates)
- Enabled automatically when:
neural_model.pthand vocabularies exist, andRecommender.load_artifacts()successfully initializesOnlineLearner.
- Each
POST /track-interaction:- Adds interaction to an experience replay buffer.
- Every
update_frequencyinteractions (default: 10), performs a mini-batch gradient update. - Saves updated artifacts (
neural_model.pth, online state) when an update happens.
To inspect behavior:
- Use
GET /online-statswhile the API is running.
Smart Diversification & Exploration
The recommender system includes intelligent diversification to prevent filter bubbles and help users discover new interests while maintaining relevance.
How It Works
- Balances relevance with exploration: Shows mostly items matching user preferences, but injects diverse interests at strategic positions (e.g., every 5th item).
- Prevents filter bubbles: Users see a mix of their favorite interests plus occasional exploration items to discover new content.
- Configurable levels: Four preset diversity levels available.
Diversity Levels
Configure the global diversity level in model/diversification.py (in DiversityConfigManager._load_config):
# Change this one line to switch global behavior:
base_level = DiversityLevel.DISCOVERY # or FOCUSED / BALANCED / AGGRESSIVE
Available levels:
FOCUSED(10% exploration)- Stays close to user's main interests
- Exploration every 10 items
- Minimum 2 different interests shown
BALANCED(20% exploration) - Default- Good mix of relevance and discovery
- Exploration every 5 items
- Minimum 3 different interests shown
DISCOVERY(35% exploration)- Emphasizes discovering new interests
- Exploration every 3 items
- Minimum 4 different interests shown
AGGRESSIVE(50% exploration)- Maximum diversity and exploration
- Exploration every 2 items
- Minimum 5 different interests shown
After changing the level, restart your API for changes to take effect.
Example Behavior
If a user likes "nightlife" and you're using DISCOVERY level:
- Positions 1-4: Mostly nightlife plans (high ML scores)
- Position 5: Diverse interest (e.g., foodie, adventure)
- Positions 6-9: Mostly nightlife again
- Position 10: Another diverse interest
- And so on...
This ensures users see their preferences while being exposed to new content that might interest them.
Hugging Face Spaces Notes
This repo already contains a Spacesβready configuration:
Dockerfile:- Uses
python:3.11-slim. - Installs
libgomp1and Python deps. - Runs:
uvicorn main:app --host 0.0.0.0 --port 7860
- Uses
- Existing
README.mdmeta (in Spaces UI) can be ignored; this file is the full developer doc.
Common Commands Reference
- Install dependencies
pip install -r requirements.txt
- Run API (dev)
uvicorn main:app --host 0.0.0.0 --port 7860 --reload- or
python main.py
- Train model (batch)
python train.py
- Train with dummy data
python train.py --generate-data --n-interactions 500
- Test recommendations
python train.py --testpython train.py --test-only --user-id <user-id>
- Trigger retrain via API
curl -X POST "http://localhost:7860/retrain" -H "X-Admin-Key: $SECRET_KEY"
- Build & run with Docker
docker build -t romio-explore-ai-api .docker run --rm -p 7860:7860 --env-file .env romio-explore-ai-api
This README should give you everything needed to understand, run, train, and extend the Romio Explore AI Recommender API.