|
|
from fastapi import FastAPI, File, UploadFile |
|
|
import google.generativeai as genai |
|
|
from PIL import Image |
|
|
import io |
|
|
import json |
|
|
from google.colab import userdata |
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
|
|
|
genai.configure(api_key=userdata.get('GOOGLE_API_KEY')) |
|
|
|
|
|
@app.get("/") |
|
|
def read_root(): |
|
|
return {"message": "FastAPI is running on Render!"} |
|
|
|
|
|
@app.head("/") |
|
|
async def root_head(): |
|
|
return {} |
|
|
|
|
|
@app.post("/analyze") |
|
|
async def analyze_food_image(file: UploadFile = File(...)): |
|
|
"""Analyzes food items in the image using Gemini 1.5 Flash""" |
|
|
image_bytes = await file.read() |
|
|
img = Image.open(io.BytesIO(image_bytes)) |
|
|
|
|
|
model = genai.GenerativeModel("gemini-1.5-flash") |
|
|
|
|
|
|
|
|
prompt = """ |
|
|
Identify all food items in the given image and determine their approximate quantity. Then, provide nutritional information |
|
|
in valid JSON format following this structure: |
|
|
|
|
|
```json |
|
|
{ |
|
|
"detected_food_items": [ |
|
|
{ |
|
|
"food_item": "Detected food name", |
|
|
"quantity": "Approximate quantity (e.g., 1 bowl, 2 slices, half a chapati)", |
|
|
"nutritional_info": { |
|
|
"calories_kcal": value, |
|
|
"protein_g": value, |
|
|
"fiber_g": value, |
|
|
"vitamins": { |
|
|
"Vitamin A_mcg": value, |
|
|
"Vitamin C_mg": value, |
|
|
"Vitamin D_mcg": value, |
|
|
"Vitamin E_mg": value, |
|
|
"Vitamin K_mcg": value, |
|
|
"Vitamin B1_mg": value, |
|
|
"Vitamin B2_mg": value, |
|
|
"Vitamin B3_mg": value, |
|
|
"Vitamin B6_mg": value, |
|
|
"Vitamin B12_mcg": value, |
|
|
"Folate_mcg": value |
|
|
} |
|
|
}, |
|
|
"health_benefits": [ |
|
|
"Brief description of health benefit 1", |
|
|
"Brief description of health benefit 2" |
|
|
] |
|
|
} |
|
|
] |
|
|
} |
|
|
``` |
|
|
|
|
|
- **Ensure the response is valid JSON** inside triple backticks (```json ... ```). |
|
|
- **Include accurate nutritional values based on the given quantity.** |
|
|
- **If exact values are unavailable, provide estimated values.** |
|
|
- **Ensure proper formatting and completeness of data.** |
|
|
""" |
|
|
|
|
|
|
|
|
response = model.generate_content([prompt, img]) |
|
|
|
|
|
|
|
|
try: |
|
|
json_response = response.text.strip("```json").strip("```") |
|
|
return json.loads(json_response) |
|
|
except json.JSONDecodeError: |
|
|
return {"error": "Invalid response format from AI model"} |
|
|
|
|
|
import os |
|
|
|
|
|
if __name__ == "__main__": |
|
|
port = int(os.getenv("PORT", 8000)) |
|
|
uvicorn.run(app, host="0.0.0.0", port=port) |