muhammadsalmanalfaridzi commited on
Commit
53e779a
·
verified ·
1 Parent(s): 10bf89e

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +127 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import necessary libraries
2
+ import streamlit as st
3
+ from dotenv import load_dotenv, find_dotenv
4
+ import os
5
+ from PIL import Image
6
+ import openai
7
+ import base64
8
+ from io import BytesIO
9
+
10
+ # Load environment variables from the .env file
11
+ load_dotenv(find_dotenv())
12
+
13
+ # Configure Streamlit page settings
14
+ st.set_page_config(page_title="Nutrition Assistant", page_icon="🔮")
15
+
16
+ # Configure Sambanova API with an API key from environment variables
17
+ openai.api_key = os.getenv("SAMBANOVA_API_KEY")
18
+ openai.api_base = "https://api.sambanova.ai/v1"
19
+
20
+ # Define a function to encode an image to base64 format
21
+ def image_to_base64(image):
22
+ buffered = BytesIO()
23
+ image.save(buffered, format="PNG")
24
+ return base64.b64encode(buffered.getvalue()).decode("utf-8")
25
+
26
+ # Define a function to handle the response from the Sambanova Llama model
27
+ def get_llama_response(input, image):
28
+ # Convert image to base64 format
29
+ image_base64 = image_to_base64(image)
30
+
31
+ # Prepend the base64 data with the appropriate format
32
+ image_data_url = f"data:image/png;base64,{image_base64}"
33
+
34
+ try:
35
+ # Send input and image data to the model and get textual response
36
+ response = openai.ChatCompletion.create(
37
+ model="Llama-3.2-90B-Vision-Instruct",
38
+ messages=[{
39
+ "role": "user",
40
+ "content": [
41
+ {"type": "text", "text": input},
42
+ {"type": "image_url", "image_url": {"url": image_data_url}}
43
+ ]
44
+ }],
45
+ temperature=0.1,
46
+ top_p=0.1
47
+ )
48
+
49
+ # Print the entire response to debug
50
+ print(response) # For debugging purposes, this will print to your server's log
51
+
52
+ # Check if the response contains 'choices'
53
+ if 'choices' in response:
54
+ return response['choices'][0]['message']['content']
55
+ else:
56
+ # Handle the case where 'choices' is missing
57
+ return f"Error: Response structure is missing 'choices'. Full response: {response}"
58
+
59
+ except Exception as e:
60
+ # Catch any exceptions (e.g., network issues, invalid API key, etc.)
61
+ return f"An error occurred: {str(e)}"
62
+
63
+ # Define a function to set up image uploading and handle the image data
64
+ def input_image_setup(uploaded_file):
65
+ if uploaded_file:
66
+ return Image.open(uploaded_file)
67
+ else:
68
+ raise FileNotFoundError("No image uploaded")
69
+
70
+ # Sidebar configuration for navigation and file upload
71
+ st.sidebar.title("Navigation")
72
+ st.sidebar.header("Upload Section")
73
+ uploaded_file = st.sidebar.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
74
+
75
+ # Display the main header of the application
76
+ st.header("Nutrition Assistant")
77
+ if uploaded_file:
78
+ image = Image.open(uploaded_file)
79
+ st.image(image, caption="Uploaded Image", use_container_width=True)
80
+
81
+ # Create a button for triggering the food analysis
82
+ submit = st.button("Analyze this Food")
83
+
84
+ # Set the prompt for the AI model
85
+ input_prompt = """
86
+ You are an expert nutritionist analyzing the food items in the image.
87
+ Start by determining if the image contains food items.
88
+ If the image does not contain any food items,
89
+ clearly state "No food items detected in the image."
90
+ and do not provide any calorie information.
91
+ If food items are detected,
92
+ start by naming the meal based on the image,
93
+ identify and list every ingredient you can find in the image,
94
+ and then estimate the total calories for each ingredient.
95
+ Summarize the total calories based on the identified ingredients.
96
+ Follow the format below:
97
+
98
+ If no food items are detected:
99
+ No food items detected in the image.
100
+
101
+ If food items are detected:
102
+ Meal Name: [Name of the meal]
103
+
104
+ 1. Ingredient 1 - estimated calories
105
+ 2. Ingredient 2 - estimated calories
106
+ ----
107
+ Total estimated calories: X
108
+
109
+ Finally, mention whether the food is healthy or not,
110
+ and provide the percentage split of protein, carbs, and fats in the food item.
111
+ Also, mention the total fiber content in the food item and any other important details.
112
+ """
113
+
114
+ # Action to take when the 'Analyze this Food' button is clicked
115
+ if submit:
116
+ if uploaded_file:
117
+ with st.spinner("Processing..."):
118
+ try:
119
+ image_data = input_image_setup(uploaded_file)
120
+ response = get_llama_response(input_prompt, image_data)
121
+ st.success("Analysis Complete!")
122
+ st.subheader("Food Analysis")
123
+ st.write(response)
124
+ except Exception as e:
125
+ st.error(f"Error: {str(e)}")
126
+ else:
127
+ st.warning("Please upload an image first.")
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ streamlit==1.19.0
2
+ python-dotenv==1.0.0
3
+ Pillow==8.4.0
4
+ openai==0.27.0