File size: 2,823 Bytes
42ecad8
 
 
 
 
7c29aab
42ecad8
7c29aab
42ecad8
7c29aab
 
42ecad8
 
 
 
 
 
 
 
 
 
7c29aab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42ecad8
7c29aab
42ecad8
7c29aab
42ecad8
7c29aab
 
 
 
 
42ecad8
7c29aab
 
42ecad8
7c29aab
 
 
 
 
 
42ecad8
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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()

# Set your API key
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 {}  # Empty response for HEAD requests

@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")  # Best for real-time image processing

    # Updated prompt for structured JSON response
    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.**
    """

    # Get response from API
    response = model.generate_content([prompt, img])

    # Extract JSON response
    try:
        json_response = response.text.strip("```json").strip("```")  # Remove markdown formatting
        return json.loads(json_response)  # Convert to Python dictionary
    except json.JSONDecodeError:
        return {"error": "Invalid response format from AI model"}

import os

if __name__ == "__main__":
    port = int(os.getenv("PORT", 8000))  # Render assigns PORT dynamically
    uvicorn.run(app, host="0.0.0.0", port=port)