marcolouis's picture
refactor: Revise FastAPI app structure and enhance documentation
9031b79
|
Raw History Blame Contribute Delete
11.9 kB
---
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
```text
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` (requires `X-Admin-Key` header)
- **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 by `main.py`.
- `retrain_from_supabase()` β€” full batch training from Supabase.
- Integrates **online learning** via `OnlineLearner`.
- Integrates **smart diversification** via `DiversificationStrategy` to prevent filter bubbles.
- **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:
- `PlanEmbeddingNetwork`
- `UserPreferenceNetwork`
- `ScorePredictor`
- 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_URL` and `SUPABASE_SERVICE_ROLE_KEY` from `.env`.
- Accesses tables like `plans`, `users`, `places`, `interests`, `user_plan_interactions`.
---
### Environment Variables
Create a `.env` file in the project root with at least:
```bash
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_KEY`
- `main.py` β†’ `SECRET_KEY` for admin verification
---
### Installation (Local, Without Docker)
**1. Create & activate a virtual environment (recommended)**
```bash
python -m venv .venv
# Windows PowerShell
.venv\Scripts\Activate.ps1
# macOS/Linux
source .venv/bin/activate
```
**2. Install Python dependencies**
```bash
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):
```bash
sudo apt-get update && sudo apt-get install -y libgomp1
```
---
### Running the API Locally
#### Option A: Directly with `uvicorn` (recommended for dev)
```bash
uvicorn main:app --host 0.0.0.0 --port 7860 --reload
```
Or using the `__main__` guard in `main.py`:
```bash
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:
```bash
docker build -t romio-explore-ai-api .
```
Run:
```bash
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"}`.
- **GET `/recommend/{userId}`**
- **Query params**:
- `limit` (int, default `10`)
- **Response**:
- `{"userId": "...", "limit": 10, "recommendations": [{"item_id": "<plan-id>", "score": <float>}, ...]}`
- **GET `/explore/{userId}`**
- **Query params**:
- `page` (int, default `1`, `>=1`)
- `limit` (int, default `20`, `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 `plans` from Supabase, joins with:
- `users` (creator info)
- `places` (for `placeIds`)
- `interests`
- Returns a Flutter‑compatible explore feed (`ExplorePlanModel`/`ExplorePlace`).
- **POST `/track-interaction`**
- **Body** (`application/json`):
```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.
- **GET `/online-stats`**
- Returns online-learning statistics (`n_interactions`, `n_updates`, `buffer_size`, recent loss, etc.).
- **POST `/retrain`** (admin)
- **Headers**:
- `X-Admin-Key: <SECRET_KEY>`
- Triggers full **batch retraining** via `Recommender.retrain_from_supabase()`, saving fresh artifacts to `model/artifacts/`.
---
### Training & Testing the ML Model
All offline training logic lives in `train.py` and `model/trainer.py`.
#### Basic Training
```bash
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 `CompleteRecommenderModel` with train/validation split.
- Save artifacts into `model/artifacts/`.
#### Generate Dummy Interaction Data (for testing)
```bash
python train.py --generate-data --n-interactions 500
```
This:
- Pulls existing `users` and `plans` from Supabase.
- Generates synthetic `user_plan_interactions`.
- Inserts them in batches into the `user_plan_interactions` table.
#### Train + Then Test Recommendations
```bash
python train.py --test
```
Or test for a specific user (after training / artifacts exist):
```bash
python train.py --test-only --user-id <some-user-id>
```
---
### Online Learning (Real-Time Updates)
- Enabled automatically when:
- `neural_model.pth` and vocabularies exist, and
- `Recommender.load_artifacts()` successfully initializes `OnlineLearner`.
- Each `POST /track-interaction`:
- Adds interaction to an experience replay buffer.
- Every `update_frequency` interactions (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-stats` while 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`):
```python
# 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 `libgomp1` and Python deps.
- Runs:
```bash
uvicorn main:app --host 0.0.0.0 --port 7860
```
- Existing `README.md` meta (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 --test`
- `python 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.