dev2607 commited on
Commit
6331cc3
·
verified ·
1 Parent(s): 8e24c55

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -83
app.py CHANGED
@@ -1,11 +1,22 @@
1
  import os
2
  import subprocess
3
  import sys
 
 
 
 
 
 
 
4
 
5
- # Instead of hardcoding the path
6
- pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract'
 
 
 
 
7
 
8
- # Try this more flexible approach
9
  try:
10
  # First try the default path
11
  if os.path.exists('/usr/bin/tesseract'):
@@ -18,31 +29,39 @@ try:
18
  except:
19
  # If all else fails, try the default installation path
20
  pytesseract.pytesseract.tesseract_cmd = 'tesseract'
21
- import gradio as gr
22
- import re
23
- import numpy as np
24
- from PIL import Image
25
- import pytesseract
26
- import requests
27
- import json
28
- import os
29
- from dotenv import load_dotenv
30
- import google.generativeai as genai
31
 
32
  # Load environment variables
33
  load_dotenv()
34
 
35
- # Configure Gemini API
36
- GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
37
- genai.configure(api_key=GEMINI_API_KEY)
38
-
 
 
 
 
 
 
39
 
40
  # Function to extract text from images using OCR
41
  def extract_text_from_image(image):
42
  try:
43
  if image is None:
44
  return "No image captured. Please try again."
 
 
 
 
 
 
 
 
45
  text = pytesseract.image_to_string(image)
 
 
 
 
46
  return text
47
  except Exception as e:
48
  return f"Error extracting text: {str(e)}"
@@ -76,38 +95,39 @@ def analyze_ingredients_with_gemini(ingredients_list, health_conditions=None):
76
  if health_conditions and health_conditions.strip():
77
  prompt = f"""
78
  Analyze the following food ingredients for a person with these health conditions: {health_conditions}
79
-
80
  Ingredients: {ingredients_text}
81
-
82
  For each ingredient:
83
  1. Provide its potential health benefits
84
  2. Identify any potential risks
85
  3. Note if it may affect the specified health conditions
86
-
87
  Then provide an overall assessment of the product's suitability for someone with the specified health conditions.
88
  Format your response in markdown with clear headings and sections.
89
  """
90
  else:
91
  prompt = f"""
92
  Analyze the following food ingredients:
93
-
94
  Ingredients: {ingredients_text}
95
-
96
  For each ingredient:
97
  1. Provide its potential health benefits
98
  2. Identify any potential risks or common allergens associated with it
99
-
100
  Then provide an overall assessment of the product's general health profile.
101
  Format your response in markdown with clear headings and sections.
102
  """
103
 
104
  try:
 
 
 
 
105
  # Call the Gemini API
106
  model = genai.GenerativeModel('gemini-pro')
107
  response = model.generate_content(prompt)
108
 
109
- # Extract and return the analysis
110
- analysis = response.text
 
 
 
111
 
112
  # Add disclaimer
113
  disclaimer = """
@@ -122,11 +142,46 @@ def analyze_ingredients_with_gemini(ingredients_list, health_conditions=None):
122
  # Fallback to basic analysis if API call fails
123
  return f"Error connecting to analysis service: {str(e)}\n\nPlease try again later."
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  # Function to process input based on method (camera, upload, or manual entry)
126
  def process_input(input_method, text_input, camera_input, upload_input, health_conditions):
127
  if input_method == "Camera":
128
  if camera_input is not None:
129
  extracted_text = extract_text_from_image(camera_input)
 
 
 
 
130
  ingredients = parse_ingredients(extracted_text)
131
  return analyze_ingredients_with_gemini(ingredients, health_conditions)
132
  else:
@@ -135,13 +190,17 @@ def process_input(input_method, text_input, camera_input, upload_input, health_c
135
  elif input_method == "Image Upload":
136
  if upload_input is not None:
137
  extracted_text = extract_text_from_image(upload_input)
 
 
 
 
138
  ingredients = parse_ingredients(extracted_text)
139
  return analyze_ingredients_with_gemini(ingredients, health_conditions)
140
  else:
141
  return "No image uploaded. Please try again."
142
 
143
  elif input_method == "Manual Entry":
144
- if text_input.strip():
145
  ingredients = parse_ingredients(text_input)
146
  return analyze_ingredients_with_gemini(ingredients, health_conditions)
147
  else:
@@ -163,7 +222,7 @@ with gr.Blocks(title="AI Ingredient Scanner") as app:
163
  )
164
 
165
  # Camera input
166
- camera_input = gr.Image(label="Capture ingredients with camera", type="pil")
167
 
168
  # Image upload
169
  upload_input = gr.Image(label="Upload image of ingredients label", type="pil", visible=False)
@@ -193,9 +252,9 @@ with gr.Blocks(title="AI Ingredient Scanner") as app:
193
  # Show/hide inputs based on selection
194
  def update_visible_inputs(choice):
195
  return {
196
- upload_input: choice == "Image Upload",
197
- camera_input: choice == "Camera",
198
- text_input: choice == "Manual Entry"
199
  }
200
 
201
  input_method.change(update_visible_inputs, input_method, [upload_input, camera_input, text_input])
@@ -229,7 +288,6 @@ with gr.Blocks(title="AI Ingredient Scanner") as app:
229
  2. Take a photo of the ingredients label or enter ingredients manually
230
  3. Optionally enter your health concerns
231
  4. Click "Analyze Ingredients" to get your personalized analysis
232
-
233
  The AI will automatically analyze the ingredients, their health implications, and their potential impact on your specific health concerns.
234
  """)
235
 
@@ -241,7 +299,6 @@ with gr.Blocks(title="AI Ingredient Scanner") as app:
241
  - Allergies: "peanut allergy" or "shellfish allergy"
242
  - Dietary restrictions: "vegetarian" or "gluten-free diet"
243
  - Multiple conditions: "diabetes, high cholesterol, and lactose intolerance"
244
-
245
  The AI will tailor its analysis to your specific needs.
246
  """)
247
 
@@ -259,56 +316,6 @@ with gr.Blocks(title="AI Ingredient Scanner") as app:
259
  Always consult with a healthcare provider regarding dietary restrictions, allergies, or health conditions.
260
  """)
261
 
262
- # Function to run when testing without API key
263
- def run_with_dummy_llm():
264
- # Override the LLM function with a dummy version for testing
265
- global analyze_ingredients_with_gemini
266
-
267
- def dummy_analyze(ingredients_list, health_conditions=None):
268
- ingredients_text = ", ".join(ingredients_list)
269
-
270
- report = f"""
271
- # Ingredient Analysis Report
272
-
273
- ## Detected Ingredients
274
- {", ".join([i.title() for i in ingredients_list])}
275
-
276
- ## Overview
277
- This is a simulated analysis since no API key was provided. In the actual application,
278
- the ingredients would be analyzed by an LLM for their health implications.
279
-
280
- ## Health Considerations
281
- """
282
-
283
- if health_conditions:
284
- report += f"""
285
- The analysis would specifically consider these health concerns: {health_conditions}
286
- """
287
- else:
288
- report += """
289
- No specific health concerns were provided, so a general analysis would be performed.
290
- """
291
-
292
- report += """
293
- ## Disclaimer
294
- This analysis is provided for informational purposes only and should not replace professional medical advice.
295
- Always consult with a healthcare provider regarding dietary restrictions, allergies, or health conditions.
296
- """
297
-
298
- return report
299
-
300
- # Replace the real function with the dummy
301
- analyze_ingredients_with_gemini = dummy_analyze
302
-
303
- # Launch the app
304
- app.launch()
305
-
306
  # Launch the app
307
  if __name__ == "__main__":
308
- # Check if API key exists
309
- if not os.getenv("GEMINI_API_KEY"):
310
- print("WARNING: No Gemini API key found. Running with simulated LLM responses.")
311
- run_with_dummy_llm()
312
- else:
313
- app.launch()
314
-
 
1
  import os
2
  import subprocess
3
  import sys
4
+ import re
5
+ import numpy as np
6
+ from PIL import Image
7
+ import gradio as gr
8
+ import requests
9
+ import json
10
+ from dotenv import load_dotenv
11
 
12
+ # Attempt to install pytesseract if not found
13
+ try:
14
+ import pytesseract
15
+ except ImportError:
16
+ subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'pytesseract'])
17
+ import pytesseract
18
 
19
+ # AFTER importing pytesseract, then set the path
20
  try:
21
  # First try the default path
22
  if os.path.exists('/usr/bin/tesseract'):
 
29
  except:
30
  # If all else fails, try the default installation path
31
  pytesseract.pytesseract.tesseract_cmd = 'tesseract'
 
 
 
 
 
 
 
 
 
 
32
 
33
  # Load environment variables
34
  load_dotenv()
35
 
36
+ # Import and configure Gemini API
37
+ try:
38
+ import google.generativeai as genai
39
+ # Configure Gemini API
40
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
41
+ if GEMINI_API_KEY:
42
+ genai.configure(api_key=GEMINI_API_KEY)
43
+ except ImportError:
44
+ print("Google Generative AI package not found, using dummy implementation")
45
+ genai = None
46
 
47
  # Function to extract text from images using OCR
48
  def extract_text_from_image(image):
49
  try:
50
  if image is None:
51
  return "No image captured. Please try again."
52
+
53
+ # Verify Tesseract executable is accessible
54
+ try:
55
+ subprocess.run([pytesseract.pytesseract.tesseract_cmd, "--version"],
56
+ check=True, capture_output=True, text=True)
57
+ except (subprocess.SubprocessError, FileNotFoundError):
58
+ return "Tesseract OCR is not installed or not properly configured. Please check installation."
59
+
60
  text = pytesseract.image_to_string(image)
61
+
62
+ if not text.strip():
63
+ return "No text could be extracted. Ensure image is clear and readable."
64
+
65
  return text
66
  except Exception as e:
67
  return f"Error extracting text: {str(e)}"
 
95
  if health_conditions and health_conditions.strip():
96
  prompt = f"""
97
  Analyze the following food ingredients for a person with these health conditions: {health_conditions}
 
98
  Ingredients: {ingredients_text}
 
99
  For each ingredient:
100
  1. Provide its potential health benefits
101
  2. Identify any potential risks
102
  3. Note if it may affect the specified health conditions
 
103
  Then provide an overall assessment of the product's suitability for someone with the specified health conditions.
104
  Format your response in markdown with clear headings and sections.
105
  """
106
  else:
107
  prompt = f"""
108
  Analyze the following food ingredients:
 
109
  Ingredients: {ingredients_text}
 
110
  For each ingredient:
111
  1. Provide its potential health benefits
112
  2. Identify any potential risks or common allergens associated with it
 
113
  Then provide an overall assessment of the product's general health profile.
114
  Format your response in markdown with clear headings and sections.
115
  """
116
 
117
  try:
118
+ # Check if Gemini API is available
119
+ if not genai or not os.getenv("GEMINI_API_KEY"):
120
+ return dummy_analyze(ingredients_list, health_conditions)
121
+
122
  # Call the Gemini API
123
  model = genai.GenerativeModel('gemini-pro')
124
  response = model.generate_content(prompt)
125
 
126
+ # Check if response is valid
127
+ if hasattr(response, 'text') and response.text:
128
+ analysis = response.text
129
+ else:
130
+ return "Error: Received empty response from analysis service. Please try again."
131
 
132
  # Add disclaimer
133
  disclaimer = """
 
142
  # Fallback to basic analysis if API call fails
143
  return f"Error connecting to analysis service: {str(e)}\n\nPlease try again later."
144
 
145
+ # Dummy analysis function for when API is not available
146
+ def dummy_analyze(ingredients_list, health_conditions=None):
147
+ ingredients_text = ", ".join(ingredients_list)
148
+
149
+ report = f"""
150
+ # Ingredient Analysis Report
151
+ ## Detected Ingredients
152
+ {", ".join([i.title() for i in ingredients_list])}
153
+ ## Overview
154
+ This is a simulated analysis since no API key was provided. In the actual application,
155
+ the ingredients would be analyzed by an LLM for their health implications.
156
+ ## Health Considerations
157
+ """
158
+
159
+ if health_conditions:
160
+ report += f"""
161
+ The analysis would specifically consider these health concerns: {health_conditions}
162
+ """
163
+ else:
164
+ report += """
165
+ No specific health concerns were provided, so a general analysis would be performed.
166
+ """
167
+
168
+ report += """
169
+ ## Disclaimer
170
+ This analysis is provided for informational purposes only and should not replace professional medical advice.
171
+ Always consult with a healthcare provider regarding dietary restrictions, allergies, or health conditions.
172
+ """
173
+
174
+ return report
175
+
176
  # Function to process input based on method (camera, upload, or manual entry)
177
  def process_input(input_method, text_input, camera_input, upload_input, health_conditions):
178
  if input_method == "Camera":
179
  if camera_input is not None:
180
  extracted_text = extract_text_from_image(camera_input)
181
+ # If OCR fails, inform the user they can try manual entry
182
+ if "Error" in extracted_text or "No text could be extracted" in extracted_text:
183
+ return extracted_text + "\n\nPlease try using the 'Manual Entry' option instead."
184
+
185
  ingredients = parse_ingredients(extracted_text)
186
  return analyze_ingredients_with_gemini(ingredients, health_conditions)
187
  else:
 
190
  elif input_method == "Image Upload":
191
  if upload_input is not None:
192
  extracted_text = extract_text_from_image(upload_input)
193
+ # If OCR fails, inform the user they can try manual entry
194
+ if "Error" in extracted_text or "No text could be extracted" in extracted_text:
195
+ return extracted_text + "\n\nPlease try using the 'Manual Entry' option instead."
196
+
197
  ingredients = parse_ingredients(extracted_text)
198
  return analyze_ingredients_with_gemini(ingredients, health_conditions)
199
  else:
200
  return "No image uploaded. Please try again."
201
 
202
  elif input_method == "Manual Entry":
203
+ if text_input and text_input.strip():
204
  ingredients = parse_ingredients(text_input)
205
  return analyze_ingredients_with_gemini(ingredients, health_conditions)
206
  else:
 
222
  )
223
 
224
  # Camera input
225
+ camera_input = gr.Image(label="Capture ingredients with camera", type="pil", visible=True)
226
 
227
  # Image upload
228
  upload_input = gr.Image(label="Upload image of ingredients label", type="pil", visible=False)
 
252
  # Show/hide inputs based on selection
253
  def update_visible_inputs(choice):
254
  return {
255
+ upload_input: gr.update(visible=(choice == "Image Upload")),
256
+ camera_input: gr.update(visible=(choice == "Camera")),
257
+ text_input: gr.update(visible=(choice == "Manual Entry"))
258
  }
259
 
260
  input_method.change(update_visible_inputs, input_method, [upload_input, camera_input, text_input])
 
288
  2. Take a photo of the ingredients label or enter ingredients manually
289
  3. Optionally enter your health concerns
290
  4. Click "Analyze Ingredients" to get your personalized analysis
 
291
  The AI will automatically analyze the ingredients, their health implications, and their potential impact on your specific health concerns.
292
  """)
293
 
 
299
  - Allergies: "peanut allergy" or "shellfish allergy"
300
  - Dietary restrictions: "vegetarian" or "gluten-free diet"
301
  - Multiple conditions: "diabetes, high cholesterol, and lactose intolerance"
 
302
  The AI will tailor its analysis to your specific needs.
303
  """)
304
 
 
316
  Always consult with a healthcare provider regarding dietary restrictions, allergies, or health conditions.
317
  """)
318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
  # Launch the app
320
  if __name__ == "__main__":
321
+ app.launch()