nompnomp / app.py
dindizz's picture
Update app.py
56d8b8a verified
import gradio as gr
import openai
import os
from PIL import Image
# Set up the OpenAI API key and prompt from environment variables (secrets)
openai.api_key = os.getenv('OPENAI_API_KEY').strip()
nutrition_prompt = os.getenv('NUTRITION_PROMPT').strip()
# Function to call GPT-4o-mini to get nutritional information from text description
def get_nutritional_info(description):
prompt = f"{nutrition_prompt}: {description}"
try:
response = openai.ChatCompletion.create(
model="gpt-4o-mini", # Ensure this is the correct model identifier
messages=[
{"role": "system", "content": "You are a nutrition expert."},
{"role": "user", "content": prompt}
],
max_tokens=300,
temperature=0.7
)
return response.choices[0].message['content'].strip()
except Exception as e:
return f"Oops! Something went wrong with nutritional breakdown: {str(e)}"
# Gradio interface function
def analyze_meal(image, description):
if image is not None:
# Handling if image is given but no text description is provided
if not description:
return "Please describe your meal in the text box below the image upload."
try:
# Process the image if necessary or use the description
result = get_nutritional_info(description)
return result
except Exception as e:
return f"Error processing image or description: {str(e)}"
elif description:
# Use the description to get nutritional information
try:
result = get_nutritional_info(description)
return result
except Exception as e:
return f"Error processing description: {str(e)}"
else:
return "Please upload an image and provide a description of the meal."
# Gradio app layout
inputs = [
gr.Image(label="Upload your meal (Take a bite out of that picture!)", type="pil"),
gr.Textbox(label="Describe your meal if image recognition fails", lines=2, placeholder="e.g., a plate of upma with coconut chutney")
]
outputs = gr.Textbox(label="Nutritional Breakdown (Let's see what’s on your plate!)")
# Launch the Gradio app with a fun and playful description
app = gr.Interface(
fn=analyze_meal,
inputs=inputs,
outputs=outputs,
title="NOMP NOMP: Nutrition on My Plate",
description="👋 Welcome to NOMP NOMP! Nomp nomp... what's on your plate? Upload a picture or tell us about your meal, and we'll break it down nutritionally for you!"
)
if __name__ == "__main__":
app.launch()