petpal / README.md
priaansh's picture
Update README.md
1b542a7 verified
metadata
title: PetPal
emoji: πŸ•
colorFrom: indigo
colorTo: blue
sdk: docker
app_port: 7860
pinned: false
license: mit
short_description: AI-Powered Dog Breed Analyzer & Nutrition Recipe Generator

πŸ• PetPal: Dog Breed Analyzer & Recipe Generator API

PetPal is an AI-powered FastAPI service that identifies dog breeds from images and generates personalized, healthy recipes with detailed nutritional information. Built with Google Gemini AI and BioCLIP for accurate breed detection.

License: MIT Python 3.10+ FastAPI Hugging Face Spaces


🌟 Features

  • πŸ” AI Breed Detection: Upload a dog image and instantly identify the breed using BioCLIP neural networks
  • πŸ“ Text-Based Search: Enter any dog breed name to get instant recipe recommendations
  • πŸ– Custom Recipes: Generate 4 unique, breed-specific healthy dog food recipes
  • πŸ₯— Dietary Options: Support for 8 dietary preferences (grain-free, high-protein, vegan, etc.)
  • πŸ“Š Full Nutrition Info: Complete breakdown of calories, protein, fat, carbs, and micronutrients
  • πŸ’¬ Nutrition Chatbot: Ask breed-specific diet and health questions
  • 🌐 REST API: Easy integration with any frontend or mobile app
  • ⚑ Fast & Reliable: Responses in 2-5 seconds with retry logic

πŸ“‹ Table of Contents


πŸš€ Quick Start

For Complete Beginners

What You Need:

  1. A web browser
  2. Your PetPal Space URL (e.g., https://huggingface.co/spaces/your-username/petpal)
  3. Optional: A tool like Postman or Insomnia for testing

First API Call (No coding required):

  1. Open your browser and go to: https://your-petpal-url.hf.space/docs
  2. You'll see an interactive API documentation page (Swagger UI)
  3. Click on any endpoint (e.g., /get_recipes)
  4. Click "Try it out"
  5. Fill in the form fields
  6. Click "Execute"
  7. See your results!

πŸ“‘ API Endpoints

πŸ” Breed Detection

1. POST /predict_dog_breed_image

Upload a dog image to detect breed and get recipes.

Parameters:

  • file (required): Image file (JPG, PNG)
  • dietary_options (optional): Comma-separated values (e.g., "grain-free,high-protein")

Response:

[
  {
    "breed": "Golden Retriever",
    "species": "Canis familiaris",
    "confidence": 0.95,
    "recipes": [...]
  }
]

2. POST /predict_dog_breed_text

Enter a breed name to get tailored recipes.

Parameters:

  • breed (required): Dog breed name (e.g., "German Shepherd")
  • dietary_options (optional): Comma-separated dietary preferences

Response:

{
  "breed": "German Shepherd",
  "species": "German Shepherd",
  "confidence": 1.0,
  "recipes": [
    {
      "title": "High-Protein Chicken & Rice Bowl",
      "tags": ["high-protein", "grain-free"],
      "ingredients": "1. 2 cups chicken breast\n2. 1 cup brown rice\n3. 1/2 cup carrots",
      "instructions": "1. Cook chicken thoroughly\n2. Steam rice\n3. Mix together",
      "nutrition": {
        "calories": 350,
        "protein": 28,
        "fat": 12,
        "carbs": 35,
        "micronutrients": "Calcium, Iron, Omega-3, Vitamins A, B, D"
      }
    }
  ]
}

πŸ– Recipe Management

3. POST /get_recipes

Get recipes for a specific breed.

Parameters:

  • breed (required): Dog breed name
  • dietary_options (optional): Comma-separated preferences
  • count (optional): Number of recipes (1-10, default: 3)

Response: List of recipe cards (see structure above)

4. POST /generate_more_recipes

Generate fresh recipes for the same breed.

Parameters:

  • breed (required): Dog breed name
  • dietary_options (optional): Dietary preferences
  • count (optional): Number of recipes (1-10, default: 3)

Response: List of newly generated recipe cards

πŸ’¬ Chatbot & Utilities

5. POST /chatbot

Ask breed-specific nutrition questions.

Request Body (JSON):

{
  "breed": "Labrador",
  "question": "What foods help with joint health?"
}

Response:

{
  "answer": "For Labradors, foods rich in Omega-3 fatty acids..."
}

6. GET /dietary_options

Get list of available dietary preferences.

Response:

[
  "grain-free",
  "high-protein",
  "low-fat",
  "low-carb",
  "allergy-friendly",
  "veg",
  "vegan",
  "non-veg"
]

7. GET /popular_breeds

Get list of popular dog breeds with descriptions.

Response:

{
  "Golden Retriever": "Large, active, prone to joint issues",
  "German Shepherd": "Large, active, needs balanced nutrition",
  ...
}

8. GET /health

Check API health status.

Response:

{
  "status": "healthy",
  "classifier_initialized": true,
  "api_key_set": true
}

9. GET /

Get API information and available endpoints.

πŸ’‘ Usage Examples

Example 1: Get Recipes Using cURL

curl -X POST "https://your-petpal-url.hf.space/get_recipes" \
  -H "Content-Type: multipart/form-data" \
  -F "breed=Golden Retriever" \
  -F "dietary_options=high-protein,grain-free" \
  -F "count=3"

Example 2: Upload Image Using Python

import requests

url = "https://your-petpal-url.hf.space/predict_dog_breed_image"
files = {"file": open("dog_image.jpg", "rb")}
data = {"dietary_options": "grain-free,high-protein"}

response = requests.post(url, files=files, data=data)
result = response.json()

print(f"Detected Breed: {result['breed']}")
print(f"Confidence: {result['confidence']}")
print(f"Number of Recipes: {len(result['recipes'])}")

Example 3: Ask Chatbot Using JavaScript

const response = await fetch('https://your-petpal-url.hf.space/chatbot', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    breed: 'Beagle',
    question: 'What portion sizes are recommended for adult Beagles?'
  })
});

const data = await response.json();
console.log(data.answer);

πŸ₯— Dietary Options

Option Description
grain-free No grains (wheat, oats, rice, etc.)
high-protein High protein content for muscle health and active dogs
low-fat Reduced fat content for weight management
low-carb Reduced carbohydrates for diabetic or overweight dogs
allergy-friendly Hypoallergenic ingredients (no common allergens)
veg Vegetarian recipes (dairy, eggs allowed)
vegan Fully plant-based recipes (no animal products)
non-veg Traditional meat-based recipes

How to Use:

  • Single option: "high-protein"
  • Multiple options: "grain-free,high-protein,low-fat"
  • Leave empty for no specific preferences

πŸ”§ Installation

Prerequisites

  • Python 3.10 or higher
  • pip (Python package manager)
  • Google Gemini API key (Get one here)

Local Setup

  1. Clone or download the project files:

    • app.py
    • requirements.txt
    • Dockerfile
    • README.md
  2. Install dependencies:

pip install -r requirements.txt
  1. Set environment variable:
# Linux/Mac
export GEMINI_API_KEY="your-api-key-here"

# Windows
set GEMINI_API_KEY=your-api-key-here
  1. Run the application:
uvicorn app:app --host 0.0.0.0 --port 7860
  1. Open your browser:
    • API Docs: http://localhost:7860/docs
    • Health Check: http://localhost:7860/health

🚒 Deployment

Deploy to Hugging Face Spaces

  1. Create a new Space:

    • Go to Hugging Face Spaces
    • Click "Create new Space"
    • Select Docker as the SDK
    • Choose a name for your Space
  2. Upload files:

    • Upload all project files to your Space repository
  3. Add secrets:

    • Go to Space Settings β†’ Repository secrets
    • Add secret: GEMINI_API_KEY = your-api-key
  4. Wait for build:

    • Space will automatically build and deploy (5-10 minutes)
    • Check logs for any errors
  5. Test your API:

    • Visit: https://your-username-spacename.hf.space/docs

Deploy to Other Platforms

Docker:

docker build -t petpal-api .
docker run -e GEMINI_API_KEY=your-key -p 7860:7860 petpal-api

Railway/Render/Fly.io:

  • Set GEMINI_API_KEY environment variable
  • Deploy using Dockerfile
  • Set port to 7860

πŸ“š API Reference

Recipe Card Structure

{
  "title": "Recipe name",
  "tags": ["dietary-tag-1", "dietary-tag-2"],
  "ingredients": "1. ingredient with quantity\n2. ingredient with quantity",
  "instructions": "1. Step one\n2. Step two\n3. Step three",
  "nutrition": {
    "calories": 250.0,
    "protein": 20.0,
    "fat": 12.0,
    "carbs": 18.0,
    "micronutrients": "Calcium, Iron, Omega-3, Vitamins A, B, D, E"
  }
}

Error Responses

All endpoints return proper HTTP status codes:

  • 200: Success
  • 400: Bad Request (missing/invalid parameters)
  • 500: Internal Server Error

Error Format:

{
  "error": "Error message description"
}

πŸ› οΈ Troubleshooting

Common Issues

Problem: Empty recipes returned []

  • Solution: Check that GEMINI_API_KEY is set correctly
  • Verify breed name is valid (use /popular_breeds for examples)
  • Check application logs for detailed errors

Problem: "BioCLIP classifier not initialized"

  • Solution: Wait 30-60 seconds after startup for model to load
  • Check /health endpoint to verify initialization
  • Review logs for download errors

Problem: Slow response times

  • Cause: First request after startup loads models (20-30 seconds)
  • Solution: Subsequent requests will be much faster (2-5 seconds)

Problem: "GEMINI_API_KEY not set"

  • Solution: Ensure environment variable is set:
    echo $GEMINI_API_KEY  # Should print your key
    

Problem: Docker build fails

  • Solution: Ensure all files are present and Docker has enough memory (4GB+)

πŸ“ˆ Performance & Limits

Metric Value
Initial Model Load 20-30 seconds
Recipe Generation 2-5 seconds
Image Processing 1-2 seconds
Chatbot Response 1-3 seconds
Max Recipes per Request 10
Retry Attempts 3

🀝 Contributing

We welcome contributions! Here's how you can help:

  1. Report bugs: Open a discussion in the Hugging Face Space community tab
  2. Suggest features: Share your ideas in the Space discussions
  3. Submit improvements: Duplicate this Space, make changes, and share your version
  4. Improve docs: Help make this README even better by suggesting edits

πŸ“ License

This project is licensed under the MIT License.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.


πŸ™ Acknowledgments

Built with:


🌟 Support This Project

If you find PetPal useful, please consider:

  • ❀️ Liking this Space on Hugging Face
  • πŸ”— Sharing it with other pet lovers
  • πŸ’¬ Leaving feedback in the Community tab

Made with ❀️ for dogs and their humans