Skip to content

Repository files navigation

Food Recommender App - Complete Setup Guide

Project Structure Overview

 home_plate/
│
├── backend/                          # Django backend
│   ├── manage.py
│   ├── requirements.txt
│   ├── Dockerfile
│   ├── docker-compose.yml
│   ├── env.
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   │─  wsgi.py
│   │
│   ├── api/                          # API app
│   │   ├── models.py
│   │   ├── views.py
│   │   ├── serializers.py
│   │   ├── urls.py
│   │   ├── tasks.py                  # Celery async tasks
│   │   └── recommender_service.py    # Calls ML service or loads model
│   │
│   ├── recommender/                  # ML model training + serving
│   │   ├── __init__.py
│   │   ├── data/
│   │   │   └── sample_events.csv
│   │   ├── models/
│   │   │   ├── lightfm_model.pkl
│   │   │   └── metadata.json
│   │   ├── train/
│   │   │   ├── train_lightfm.py
│   │   │   └── preprocess.py
│   │   └── serving/
│   │       ├── predict.py
│   │       ├── vector_index.faiss
│   │       └── fastapi_server.py
│   │
│   ├── scripts/                      # Utility scripts
│   │   ├── load_sample_data.py
│   │   ├── cron_generate_recs.sh
│   │   └── build_faiss_index.py
│   │
│   └── static/
│
├── frontend/                         # React frontend
│   ├── package.json
│   ├── vite.config.js
│   ├── Dockerfile
│   ├── public/
│   └── src/
│       ├── App.jsx
│       ├── components/
│       │   ├── RecommendationList.jsx
│       │   ├── FoodCard.jsx
│       │   └── Loader.jsx
│       ├── pages/
│       │   ├── Home.jsx
│       │   ├── FoodDetail.jsx
│       │   └── Profile.jsx
│       ├── hooks/
│       │   └── useRecommendations.js
│       └── api/
│           ├── axiosClient.js
│           └── recommenderApi.js
│
├── ml_service/                       # Optional FastAPI ML microservice
│   ├── main.py
│   ├── requirements.txt
│   └── Dockerfile
│
├── docs/
│   ├── architecture-diagram.png
│   └── recommender-design.md
│
└── README.md

Prerequisites

  • Python 3.9+
  • Node.js 16+
  • PostgreSQL 12+
  • Redis (for Celery)
  • Docker & Docker Compose (recommended)

1. Backend Setup (Django)

Step 1: Navigate to Backend

cd backend

Step 2: Create Virtual Environment

python -m venv venv

# On Windows
venv\Scripts\activate

# On macOS/Linux
source venv/bin/activate

Step 3: Install Dependencies

pip install -r requirements.txt

Key packages:

Django==4.2
djangorestframework==3.14.0
django-cors-headers==4.0.0
psycopg2-binary==2.9.6
celery==5.3.0
lightfm==1.16
scikit-learn==1.3.0
faiss-cpu==1.7.4
pandas==2.0.0
numpy==1.24.0

Step 4: Environment Configuration

Create .env file from env.example:

cp env.example .env

Edit .env:

DEBUG=True
SECRET_KEY=your-super-secret-key-change-in-production

# Database
DATABASE_ENGINE=django.db.backends.postgresql
DATABASE_NAME=food_recommender_db
DATABASE_USER=postgres
DATABASE_PASSWORD=your_password
DATABASE_HOST=localhost
DATABASE_PORT=5432

# Redis (for Celery)
REDIS_URL=redis://localhost:6379/0

# CORS
CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173

# ML Settings
MODEL_PATH=recommender/models/lightfm_model.pkl
ENABLE_FAISS_INDEX=True
FAISS_INDEX_PATH=recommender/models/vector_index.faiss

# Recommendation Engine
RECOMMENDATIONS_BATCH_SIZE=10
MAX_RECOMMENDATIONS=20

Step 5: Database Setup

python manage.py makemigrations
python manage.py migrate

Step 6: Create Superuser

python manage.py createsuperuser

Step 7: Load Sample Data

python manage.py shell < scripts/load_sample_data.py

Step 8: Train ML Model (Initial)

python recommender/train/train_lightfm.py

This will:

  • Load data from recommender/data/sample_events.csv
  • Train LightFM model
  • Save to recommender/models/lightfm_model.pkl
  • Create metadata.json

Step 9: Build FAISS Index (Optional)

python scripts/build_faiss_index.py

Step 10: Run Celery Worker (Async Tasks)

In a separate terminal:

celery -A config worker -l info

Step 11: Run Development Server

python manage.py runserver

Backend available at: http://localhost:8000

Admin panel: http://localhost:8000/admin/


2. Frontend Setup (React + Vite)

Step 1: Navigate to Frontend

cd frontend

Step 2: Install Dependencies

npm install

Step 3: Create Environment File

Create .env:

VITE_API_URL=http://localhost:8000/api
VITE_ENVIRONMENT=development

Step 4: Run Development Server

npm run dev

Frontend available at: http://localhost:5173

Step 5: Build for Production

npm run build

3. Optional: ML Microservice (FastAPI)

Deploy the recommender as a separate microservice for scalability.

Step 1: Navigate to ML Service

cd ml_service

Step 2: Install Dependencies

pip install -r requirements.txt

Step 3: Create .env

MODEL_PATH=../backend/recommender/models/lightfm_model.pkl
FAISS_INDEX_PATH=../backend/recommender/models/vector_index.faiss
PORT=8001
WORKERS=4

Step 4: Run FastAPI Server

uvicorn main:app --host 0.0.0.0 --port 8001 --reload

ML Service available at: http://localhost:8001

Update Django to call this service:

In backend/api/recommender_service.py:

import requests

ML_SERVICE_URL = os.getenv('ML_SERVICE_URL', 'http://localhost:8001')

def get_recommendations(user_id, n=10):
    response = requests.post(
        f'{ML_SERVICE_URL}/recommend',
        json={'user_id': user_id, 'n_recommendations': n}
    )
    return response.json()

4. Docker Setup

Using Docker Compose (Recommended)

Create docker-compose.yml in backend directory or root:

version: '3.9'

services:
  db:
    image: postgres:15
    environment:
      POSTGRES_DB: food_recommender_db
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

  backend:
    build: ./backend
    command: python manage.py runserver 0.0.0.0:8000
    environment:
      DEBUG: "False"
      SECRET_KEY: your-secret-key
      DATABASE_HOST: db
      REDIS_URL: redis://redis:6379/0
    ports:
      - "8000:8000"
    depends_on:
      - db
      - redis
    volumes:
      - ./backend:/app

  celery_worker:
    build: ./backend
    command: celery -A config worker -l info
    environment:
      DEBUG: "False"
      DATABASE_HOST: db
      REDIS_URL: redis://redis:6379/0
    depends_on:
      - db
      - redis
    volumes:
      - ./backend:/app

  frontend:
    build: ./frontend
    ports:
      - "3000:3000"
    environment:
      VITE_API_URL: http://localhost:8000/api
    depends_on:
      - backend
    volumes:
      - ./frontend:/app

  ml_service:
    build: ./ml_service
    ports:
      - "8001:8001"
    depends_on:
      - backend
    volumes:
      - ./backend/recommender/models:/app/models

volumes:
  postgres_data:

Run everything:

docker-compose up --build

API Endpoints

Authentication

POST   /api/auth/register/
POST   /api/auth/login/
POST   /api/auth/logout/
GET    /api/auth/user/

Foods

GET    /api/foods/                    # List all foods
GET    /api/foods/<id>/               # Food details
GET    /api/foods/search/?q=keyword   # Search foods
POST   /api/foods/                    # Create food (admin)

Recommendations

GET    /api/recommendations/          # Get personalized recommendations
GET    /api/recommendations/similar/<food_id>/
POST   /api/recommendations/feedback/ # Submit user feedback (like/dislike)
GET    /api/recommendations/history/  # View recommendation history

User Profile

GET    /api/users/profile/
PUT    /api/users/profile/
GET    /api/users/preferences/
PUT    /api/users/preferences/

Running the Full Stack

Option 1: Individual Terminals

Terminal 1 - Database (if not using Docker):

# Ensure PostgreSQL is running
# macOS: brew services start postgresql
# Linux: sudo service postgresql start

Terminal 2 - Redis (if not using Docker):

redis-server

Terminal 3 - Backend:

cd backend
source venv/bin/activate
python manage.py runserver

Terminal 4 - Celery Worker:

cd backend
source venv/bin/activate
celery -A config worker -l info

Terminal 5 - Frontend:

cd frontend
npm run dev

Terminal 6 - ML Service (Optional):

cd ml_service
source venv/bin/activate
uvicorn main:app --reload --port 8001

Option 2: Docker Compose (All-in-One)

docker-compose up --build

Model Training & Retraining

Initial Training

cd backend
python recommender/train/train_lightfm.py

Scheduled Retraining with Celery Beat

Configure in backend/config/settings.py:

from celery.schedules import crontab

CELERY_BEAT_SCHEDULE = {
    'retrain-recommender': {
        'task': 'api.tasks.retrain_model',
        'schedule': crontab(hour=2, minute=0),  # Daily at 2 AM
    },
}

Run Celery Beat:

celery -A config beat -l info

Data Flow

  1. User interacts with food items (view, like, dislike)
  2. Frontend sends events to Django API
  3. Django stores user interactions in database
  4. Celery tasks aggregate data periodically
  5. LightFM model trained on interaction data
  6. FAISS index built for fast similarity search
  7. Recommendations generated via API endpoint
  8. Frontend displays personalized recommendations

Troubleshooting

CORS Errors

Update CORS_ALLOWED_ORIGINS in .env:

CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173

Port Already in Use

# macOS/Linux - Find and kill process on port 8000
lsof -ti:8000 | xargs kill -9

# Windows
netstat -ano | findstr :8000
taskkill /PID <PID> /F

Database Connection Refused

# Check PostgreSQL is running
psql -U postgres -h localhost

# Or with Docker:
docker-compose exec db psql -U postgres

Celery Not Picking Up Tasks

  1. Ensure Redis is running: redis-cli ping → should return PONG
  2. Check Celery worker logs for errors
  3. Verify REDIS_URL in .env

Model File Not Found

# Retrain model
python recommender/train/train_lightfm.py

# Check file exists
ls -la recommender/models/

Frontend Can't Connect to Backend

  1. Check VITE_API_URL in .env
  2. Ensure backend is running on port 8000
  3. Check browser console for CORS errors
  4. Verify firewall settings

Deployment

Backend (Heroku/Railway)

# Create Procfile
web: gunicorn config.wsgi:application
worker: celery -A config worker
beat: celery -A config beat

# Deploy
git push heroku main
heroku run python manage.py migrate

Frontend (Vercel/Netlify)

npm run build
# Deploy the dist/ folder

ML Service (Docker Hub/AWS ECR)

docker build -t food-recommender-ml ./ml_service
docker tag food-recommender-ml:latest <your-registry>/food-recommender-ml:latest
docker push <your-registry>/food-recommender-ml:latest

Key Files Explained

backend/recommender/train/train_lightfm.py

Trains collaborative filtering model using user-food interactions.

backend/api/recommender_service.py

Service layer that loads model and generates recommendations.

backend/recommender/serving/predict.py

Inference logic for getting recommendations and similar items.

frontend/hooks/useRecommendations.js

React hook for fetching and managing recommendations.

ml_service/main.py

FastAPI microservice for model serving with REST endpoints.


Contributing

git checkout -b feature/your-feature
git commit -m "Add your feature"
git push origin feature/your-feature

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages