RajatMalviya commited on
Commit
9f9138d
·
verified ·
1 Parent(s): 27c51d5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -12
app.py CHANGED
@@ -3,12 +3,14 @@ import google.generativeai as genai
3
  from PIL import Image
4
  import io
5
  import json
6
-
 
 
7
 
8
  app = FastAPI()
9
 
10
- # Set your API key
11
- genai.configure(api_key="AIzaSyAlvHXHO7xFFjfEyaNOmyZvn9FFPPJdIx4")
12
 
13
  @app.get("/")
14
  def read_root():
@@ -21,12 +23,15 @@ async def root_head():
21
  @app.post("/analyze")
22
  async def analyze_food_image(file: UploadFile = File(...)):
23
  """Analyzes food items in the image using Gemini 1.5 Flash"""
 
 
24
  image_bytes = await file.read()
25
  img = Image.open(io.BytesIO(image_bytes))
26
 
27
- model = genai.GenerativeModel("gemini-1.5-flash") # Best for real-time image processing
 
28
 
29
- # Updated prompt for structured JSON response
30
  prompt = """
31
  Identify all food items in the given image and determine their approximate quantity. Then, provide nutritional information
32
  in valid JSON format following this structure:
@@ -71,17 +76,24 @@ async def analyze_food_image(file: UploadFile = File(...)):
71
  """
72
 
73
  # Get response from API
74
- response = model.generate_content([prompt, img])
 
 
 
75
 
76
  # Extract JSON response
77
  try:
78
- json_response = response.text.strip("```json").strip("```") # Remove markdown formatting
79
- return json.loads(json_response) # Convert to Python dictionary
 
 
 
 
 
80
  except json.JSONDecodeError:
81
- return {"error": "Invalid response format from AI model"}
82
-
83
- import os
84
 
 
85
  if __name__ == "__main__":
86
  port = int(os.getenv("PORT", 7860)) # Render assigns PORT dynamically
87
- uvicorn.run(app, host="0.0.0.0", port=port)
 
3
  from PIL import Image
4
  import io
5
  import json
6
+ import re
7
+ import os
8
+ import uvicorn
9
 
10
  app = FastAPI()
11
 
12
+ # Set your API key (Make sure to store it securely, e.g., using environment variables)
13
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY", "YOUR_API_KEY_HERE"))
14
 
15
  @app.get("/")
16
  def read_root():
 
23
  @app.post("/analyze")
24
  async def analyze_food_image(file: UploadFile = File(...)):
25
  """Analyzes food items in the image using Gemini 1.5 Flash"""
26
+
27
+ # Read the uploaded image file
28
  image_bytes = await file.read()
29
  img = Image.open(io.BytesIO(image_bytes))
30
 
31
+ # Load the generative model
32
+ model = genai.GenerativeModel("gemini-1.5-flash") # Optimized for real-time image processing
33
 
34
+ # Updated structured JSON prompt
35
  prompt = """
36
  Identify all food items in the given image and determine their approximate quantity. Then, provide nutritional information
37
  in valid JSON format following this structure:
 
76
  """
77
 
78
  # Get response from API
79
+ response = model.generate_content([prompt, image_bytes]) # Pass raw image bytes
80
+
81
+ # Debugging: Print the raw response
82
+ print("Raw Response from Gemini:", response.text)
83
 
84
  # Extract JSON response
85
  try:
86
+ # Use regex to extract JSON block
87
+ match = re.search(r'```json\s*(\{.*?\})\s*```', response.text, re.DOTALL)
88
+ if match:
89
+ json_response = match.group(1) # Extract JSON content
90
+ return json.loads(json_response) # Convert to Python dictionary
91
+ else:
92
+ return {"error": "Response does not contain valid JSON format", "raw_response": response.text}
93
  except json.JSONDecodeError:
94
+ return {"error": "Failed to parse JSON response", "raw_response": response.text}
 
 
95
 
96
+ # Entry point for Render deployment
97
  if __name__ == "__main__":
98
  port = int(os.getenv("PORT", 7860)) # Render assigns PORT dynamically
99
+ uvicorn.run(app, host="0.0.0.0", port=port)