# BloodFIT Complete API

A comprehensive health and fitness API providing personalized meal planning and workout recommendations based on blood type, diet preferences, and fitness goals.

## 🌟 Features

### Meal Planning API

- **Personalized Meal Plans**: Generate custom meal plans based on blood type and diet preferences
- **Nutrition Calculation**: Calculate optimal daily calories and macronutrients
- **Meal Swapping**: Get alternative meal suggestions while maintaining nutritional targets
- **Food Scanning**: Analyze food images to identify harmful ingredients based on user profile
- **Meal Image Generation**: AI-powered meal visualization
- **Multilingual Support**: Available in English and Korean

### Workout Planning API

- **Blood Type-Based Workouts**: Personalized exercise routines aligned with blood type characteristics
- **Comprehensive User Profiling**: Considers age, BMI, body shape, activity level, and fitness goals
- **Focus Area Training**: Target specific body areas (Arms, Abs, Legs, etc.)
- **Exercise Video Generation**: AI-generated demonstration videos for each exercise
- **Smart Caching**: Efficient video caching system for improved performance
- **Goal-Oriented Plans**: Customized plans for weight loss, muscle gain, or general fitness

## 📋 Table of Contents

- [Installation](#installation)
- [Environment Setup](#environment-setup)
- [Running the API](#running-the-api)
- [API Structure](#api-structure)
- [Meal Planning Endpoints](#meal-planning-endpoints)
- [Workout Planning Endpoints](#workout-planning-endpoints)
- [Language Support](#language-support)
- [Examples](#examples)
- [Error Handling](#error-handling)

## 🚀 Installation

### Prerequisites

- Python 3.8+
- pip package manager
- SQLite (included with Python)

### Setup

1. **Clone the repository**

```bash
git clone <repository-url>
cd bloodfit-api
```

2. **Create virtual environment**

```bash
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
```

3. **Install dependencies**

```bash
pip install -r requirements.txt
```

## 🔧 Environment Setup

Create a `.env` file in the project root:

```env
# OpenAI API (Required for meal and workout planning)
OPENAI_API_KEY=your_openai_api_key_here

# Replicate API (Required for exercise video generation)
REPLICATE_API_TOKEN=your_replicate_api_token_here

# Google Cloud Translation (Optional - for multilingual support)
GOOGLE_APPLICATION_CREDENTIALS=path/to/your/credentials.json

# Database (Optional - defaults to SQLite)
DATABASE_URL=sqlite:///./exercise_videos.db
```

### API Keys Setup

#### OpenAI API Key

1. Visit [OpenAI Platform](https://platform.openai.com/)
2. Sign up or log in
3. Navigate to API Keys section
4. Create a new secret key
5. Copy and paste into `.env`

#### Replicate API Token

1. Visit [Replicate](https://replicate.com/)
2. Sign up or log in
3. Go to Account Settings
4. Copy your API token
5. Paste into `.env`

#### Google Cloud Translation (Optional)

1. Create a project in [Google Cloud Console](https://console.cloud.google.com/)
2. Enable Cloud Translation API
3. Create a service account
4. Download JSON credentials
5. Set path in `.env`

## 🏃 Running the API

### Development Mode

```bash
python run.py
```

### Production Mode

```bash
uvicorn run:app --host 0.0.0.0 --port 8000 --workers 4
```

The API will be available at:

- **Main API**: http://localhost:8000
- **Meal Planning API**: http://localhost:8000/meal
- **Workout Planning API**: http://localhost:8000/workout
- **Interactive Docs**: http://localhost:8000/docs
- **Alternative Docs**: http://localhost:8000/redoc

## 🏗️ API Structure

```
BloodFIT API
│
├── /meal                    # Meal Planning API
│   ├── /generate-meal-plan
│   ├── /calculate-daily-nutrition
│   ├── /swap-meal
│   ├── /scan-food
│   └── /generate-meal-images
│
└── /workout                 # Workout Planning API
    ├── /weekly_workout_plan_ui
    ├── /api/generate_video
    ├── /api/exercise_video/{hash}
    └── /api/video_cache/stats
```

## 🍽️ Meal Planning Endpoints

### 1. Calculate Daily Nutrition

Calculate optimal daily calories and macronutrients based on user profile.

**Endpoint**: `GET /meal/calculate-daily-nutrition`

**Parameters**:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| user_id | string | Yes | Unique user identifier |
| blood_type | string | Yes | O, A, B, or AB |
| diet_type | string | Yes | vegan, carnivore, pescatarian, or standard |
| age | integer | No | Age in years |
| weight | float | No | Weight in kg |
| height | float | No | Height in cm |
| country | string | No | Country for regional cuisine |
| food_dislikes | string | No | Comma-separated list |
| allergies | string | No | Comma-separated list |
| activity_level | string | No | sedentary, light, moderate, active, very_active |
| language | string | No | en or ko (default: en) |

**Example Request**:

```bash
curl "http://localhost:8000/meal/calculate-daily-nutrition?user_id=user123&blood_type=O&diet_type=standard&age=30&weight=70&height=175&activity_level=moderate&language=en"
```

**Example Response**:

```json
{
  "user_id": "user123",
  "blood_type": "O",
  "diet_type": "standard",
  "total_daily_calories": 2400,
  "total_daily_macronutrients": {
    "carbohydrates": 300.0,
    "protein": 120.0,
    "fat": 80.0
  },
  "calculation_method": "harris-benedict",
  "calculation_timestamp": "2025-01-22T10:30:00"
}
```

### 2. Generate Meal Plan

Generate a complete personalized meal plan.

**Endpoint**: `GET /meal/generate-meal-plan`

**Parameters**: Same as Calculate Daily Nutrition, plus:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| total_daily_calories | integer | No | Pre-calculated daily calories |
| carbs | float | No | Pre-calculated carbs in grams |
| protein | float | No | Pre-calculated protein in grams |
| fat | float | No | Pre-calculated fat in grams |

**Example Request**:

```bash
curl "http://localhost:8000/meal/generate-meal-plan?user_id=user123&blood_type=O&diet_type=standard&age=30&weight=70&height=175&country=USA&language=en"
```

**Example Response**:

```json
{
  "user_id": "user123",
  "blood_type": "O",
  "diet_type": "standard",
  "daily_nutrition": {
    "total_daily_calories": 2400,
    "total_daily_macronutrients": {
      "carbohydrates": 300.0,
      "protein": 120.0,
      "fat": 80.0
    }
  },
  "meals": {
    "breakfast": {
      "name": "Grilled Chicken Salad",
      "description": "Fresh greens with grilled chicken",
      "calories": 450,
      "macronutrients": {
        "carbohydrates": 30.0,
        "protein": 40.0,
        "fat": 15.0
      },
      "ingredients": [
        { "name": "Chicken Breast", "quantity": "150g" },
        { "name": "Mixed Greens", "quantity": "100g" }
      ]
    },
    "lunch": {
      /* ... */
    },
    "dinner": {
      /* ... */
    }
  }
}
```

### 3. Swap Meal

Get alternative meal suggestions for a specific category.

**Endpoint**: `GET /meal/swap-meal`

**Parameters**:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| user_id | string | Yes | Unique user identifier |
| blood_type | string | Yes | O, A, B, or AB |
| diet_type | string | Yes | vegan, carnivore, pescatarian, standard |
| category | string | Yes | breakfast, lunch, or dinner |
| current_calories | integer | Yes | Current meal calories to match |
| country | string | No | Country for regional cuisine |
| food_dislikes | string | No | Comma-separated list |
| allergies | string | No | Comma-separated list |
| language | string | No | en or ko |

**Example Request**:

```bash
curl "http://localhost:8000/meal/swap-meal?user_id=user123&blood_type=O&diet_type=standard&category=breakfast&current_calories=450&language=en"
```

### 4. Scan Food

Analyze a food image to identify potentially harmful ingredients.

**Endpoint**: `POST /meal/scan-food`

**Parameters** (as query params):

- user_id, blood_type, diet_type, country, allergies, food_dislikes, language

**Body**: `multipart/form-data`

- image: Image file (JPG, PNG, etc.)

**Example Request**:

```bash
curl -X POST "http://localhost:8000/meal/scan-food?user_id=user123&blood_type=O&diet_type=standard" \
  -F "image=@food_photo.jpg"
```

**Example Response**:

```json
{
  "food_identified": "Cheese Pizza",
  "is_safe": false,
  "harmful_ingredients": [
    {
      "name": "Wheat",
      "reason": "Not recommended for blood type O"
    },
    {
      "name": "Dairy",
      "reason": "May cause digestive issues for blood type O"
    }
  ],
  "recommendations": "Consider gluten-free pizza with vegetable toppings"
}
```

### 5. Generate Meal Images

Generate AI-powered meal visualization.

**Endpoint**: `POST /meal/generate-meal-images`

**Request Body**:

```json
{
  "meal_name": "Grilled Salmon with Vegetables",
  "description": "Fresh salmon fillet with roasted vegetables",
  "ingredients": [
    { "name": "Salmon", "quantity": "200g" },
    { "name": "Broccoli", "quantity": "100g" }
  ]
}
```

**Example Response**:

```json
{
  "meal_image_base64": "iVBORw0KGgoAAAANSUhEUgAA..."
}
```

## 💪 Workout Planning Endpoints

### 1. Generate Weekly Workout Plan

Generate a comprehensive weekly workout plan with exercise videos.

**Endpoint**: `GET /workout/weekly_workout_plan_ui`

**Parameters**:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| user_id | string | Yes | Unique user identifier |
| blood_type | string | Yes | O, A, B, or AB |
| age | integer | No | Age in years (10-100) |
| weight | float | No | Weight in kg |
| height | float | No | Height in cm |
| body_shape | string | No | Medium, Flabby, Skinny, Muscular |
| activity_level | string | No | Sedentary, Lightly Active, Moderately Active, Very Active |
| workout_level | string | No | Easy To Start, Break A Light Sweat, Challenging |
| main_goal | string | No | Lose Weight, Gain Muscle, Stay Fit |
| desired_weight | float | No | Target weight in kg |
| focus_areas | string | No | Comma-separated: Arms, Upper Body, Abs, Butt, Legs |
| generate_videos | boolean | No | Generate exercise videos (default: true) |
| language | string | No | en or ko |

**Example Request**:

```bash
curl "http://localhost:8000/workout/weekly_workout_plan_ui?user_id=user123&blood_type=O&age=30&weight=75&height=175&body_shape=Medium&activity_level=Moderately%20Active&workout_level=Break%20A%20Light%20Sweat&main_goal=Lose%20Weight&focus_areas=Abs,Legs&generate_videos=true&language=en"
```

**Example Response**:

```json
{
  "user_id": "user123",
  "blood_type": "O",
  "age": 30,
  "bmi": 24.5,
  "bmi_category": "Normal",
  "body_shape": "Medium",
  "activity_level": "Moderately Active",
  "main_goal": "Lose Weight",
  "workout_level": "Break A Light Sweat",
  "focus_areas": ["Abs", "Legs"],
  "plan_summary": {
    "total_workouts": 5,
    "total_calories_per_week": 2500,
    "average_duration": "45 Min",
    "intensity_distribution": {
      "high": 2,
      "medium": 2,
      "low": 1
    }
  },
  "weekly_workouts": [
    {
      "day": "Monday",
      "title": "HIIT Cardio Blast",
      "duration": "45 Min",
      "intensity": "High",
      "total_calories": "550 Calories",
      "category": "CARDIO",
      "warmup_exercises": [
        {
          "name": "Jumping Jacks",
          "duration": "5 Min",
          "sets": "1 Set",
          "calories": "50 Calories",
          "video_url": "/workout/api/exercise_video/abc123",
          "video_status": "cached"
        }
      ],
      "main_exercises": [
        {
          "name": "Burpees",
          "duration": "10 Min",
          "sets": "3 Sets",
          "calories": "150 Calories",
          "video_url": "/workout/api/exercise_video/def456",
          "video_status": "generated"
        },
        {
          "name": "Mountain Climbers",
          "duration": "10 Min",
          "sets": "3 Sets",
          "calories": "120 Calories",
          "video_url": "/workout/api/exercise_video/ghi789",
          "video_status": "cached"
        }
      ],
      "cooldown_exercises": [
        {
          "name": "Stretching",
          "duration": "5 Min",
          "sets": "1 Set",
          "calories": "30 Calories",
          "video_url": "/workout/api/exercise_video/jkl012",
          "video_status": "cached"
        }
      ]
    }
  ],
  "videos_generated": 1,
  "videos_cached": 3
}
```

### 2. Generate Exercise Video

Generate or retrieve a demonstration video for a specific exercise.

**Endpoint**: `POST /workout/api/generate_video`

**Request Body**:

```json
{
  "exercise_name": "Push Ups",
  "force_regenerate": false
}
```

**Example Response**:

```json
{
  "exercise_name": "Push Ups",
  "video_base64": "UklGRiQAAABXQVZFZm10...",
  "video_url": "/workout/api/exercise_video/abc123def456",
  "status": "cached",
  "from_cache": true,
  "file_size": 1048576,
  "created_at": "2025-01-22T10:30:00",
  "message": "Retrieved from cache"
}
```

### 3. Get Exercise Video

Retrieve a video by its hash for direct playback.

**Endpoint**: `GET /workout/api/exercise_video/{exercise_hash}`

**Example Request**:

```bash
curl "http://localhost:8000/workout/api/exercise_video/abc123def456" --output exercise.mp4
```

### 4. Video Cache Statistics

Get statistics about the video cache system.

**Endpoint**: `GET /workout/api/video_cache/stats`

**Example Response**:

```json
{
  "total_videos": 150,
  "total_size_mb": 245.67,
  "average_size_kb": 1677.45,
  "most_accessed": [
    {
      "exercise": "Push Ups",
      "access_count": 87,
      "last_accessed": "2025-01-22T10:30:00"
    }
  ],
  "recent_additions": [
    {
      "exercise": "Plank",
      "created_at": "2025-01-22T09:15:00",
      "file_size_kb": 1523.45
    }
  ]
}
```

## 🌐 Language Support

The API supports multilingual responses in English and Korean.

### Setting Language

**Method 1: Query Parameter** (Recommended)

```bash
curl "http://localhost:8000/meal/generate-meal-plan?...&language=ko"
```

**Method 2: HTTP Header**

```bash
curl -H "Accept-Language: ko" "http://localhost:8000/meal/generate-meal-plan?..."
```

**Method 3: Cookie**

```bash
curl -b "language=ko" "http://localhost:8000/meal/generate-meal-plan?..."
```

### Supported Languages

- `en` - English (default)
- `ko` - Korean (한국어)

## 📝 Examples

### Complete Meal Planning Workflow

```python
import requests

BASE_URL = "http://localhost:8000"

# Step 1: Calculate nutrition targets
nutrition_response = requests.get(
    f"{BASE_URL}/meal/calculate-daily-nutrition",
    params={
        "user_id": "user123",
        "blood_type": "O",
        "diet_type": "standard",
        "age": 30,
        "weight": 70,
        "height": 175,
        "activity_level": "moderate"
    }
)
nutrition = nutrition_response.json()

# Step 2: Generate meal plan with calculated nutrition
meal_plan_response = requests.get(
    f"{BASE_URL}/meal/generate-meal-plan",
    params={
        "user_id": "user123",
        "blood_type": "O",
        "diet_type": "standard",
        "total_daily_calories": nutrition["total_daily_calories"],
        "carbs": nutrition["total_daily_macronutrients"]["carbohydrates"],
        "protein": nutrition["total_daily_macronutrients"]["protein"],
        "fat": nutrition["total_daily_macronutrients"]["fat"]
    }
)
meal_plan = meal_plan_response.json()

# Step 3: Swap a meal if needed
swap_response = requests.get(
    f"{BASE_URL}/meal/swap-meal",
    params={
        "user_id": "user123",
        "blood_type": "O",
        "diet_type": "standard",
        "category": "breakfast",
        "current_calories": 450
    }
)
alternatives = swap_response.json()
```

### Complete Workout Planning Workflow

```python
import requests

BASE_URL = "http://localhost:8000"

# Generate workout plan
workout_response = requests.get(
    f"{BASE_URL}/workout/weekly_workout_plan_ui",
    params={
        "user_id": "user123",
        "blood_type": "O",
        "age": 30,
        "weight": 75,
        "height": 175,
        "body_shape": "Medium",
        "activity_level": "Moderately Active",
        "main_goal": "Lose Weight",
        "focus_areas": "Abs,Legs",
        "generate_videos": True
    }
)
workout_plan = workout_response.json()

# Get video cache statistics
cache_stats = requests.get(f"{BASE_URL}/workout/api/video_cache/stats").json()
print(f"Total cached videos: {cache_stats['total_videos']}")
```

## ⚠️ Error Handling

### Common Error Responses

**400 Bad Request**

```json
{
  "detail": "Invalid blood type. Must be O, A, B, or AB."
}
```

**404 Not Found**

```json
{
  "detail": "Video not found"
}
```

**500 Internal Server Error**

```json
{
  "detail": "Image generation failed: API rate limit exceeded"
}
```

### Error Codes

- `400` - Invalid parameters or request
- `404` - Resource not found
- `500` - Server error (API key issues, service unavailable)

## 🔒 Rate Limiting

- **OpenAI API**: Depends on your API plan
- **Replicate API**: Video generation may have rate limits
- **Google Translation**: 500,000 characters/month on free tier

## 📊 Database

The API uses SQLite for video caching:

- **Location**: `./exercise_videos.db`
- **Purpose**: Stores generated exercise videos to avoid regeneration
- **Automatic**: Created on first run

## 🛠️ Troubleshooting

### Issue: "OPENAI_API_KEY not configured"

**Solution**: Add your OpenAI API key to `.env` file

### Issue: "REPLICATE_API_TOKEN not configured"

**Solution**: Add your Replicate API token to `.env` file

### Issue: Translation not working

**Solution**:

1. Ensure Google Cloud credentials are properly set
2. API will fall back to English if translation fails

### Issue: Video generation slow

**Solution**:

- Videos are cached after first generation
- Use `generate_videos=false` to skip video generation

## 🔄 Version History

- **v1.0.0** - Initial release with meal planning and workout planning APIs
- Combined API structure with multilingual support

---

**Made with ❤️ by BloodFIT Team**
