nimrita commited on
Commit
a25e9ac
1 Parent(s): 077ecbe

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -0
app.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ !pip install google-generativeai
2
+ !pip install gradio huggingface_hub
3
+
4
+ from pathlib import Path
5
+ import google.generativeai as genai
6
+ import re
7
+ from PIL import Image
8
+ import os
9
+ #from google.colab import userdata
10
+ #os.environ['GOOGLE_API_KEY'] = userdata.get('GOOGLE_API_KEY')
11
+ #GOOGLE_API_KEY = os.environ['GOOGLE_API_KEY']
12
+ #genai.configure(api_key=os.environ["GOOGLE_API_KEY"])
13
+ #or use this for personal notebook genai.configure(api_key="AIzaSyD----")
14
+
15
+ # Configuration for our Gemini Models
16
+
17
+ textgeneration_config = {
18
+ "temperature": 0.9,
19
+ "top_p": 1,
20
+ "top_k": 1,
21
+ "max_output_tokens": 2048,}
22
+
23
+
24
+ visiongeneration_config = {
25
+ "temperature": 0.9,
26
+ "top_p": 1,
27
+ "top_k": 10,
28
+ "max_output_tokens": 1024,
29
+ }
30
+
31
+ safety_settings = [
32
+ {
33
+ "category": "HARM_CATEGORY_HARASSMENT",
34
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
35
+ },
36
+ {
37
+ "category": "HARM_CATEGORY_HATE_SPEECH",
38
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
39
+ },
40
+ {
41
+ "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
42
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
43
+ },
44
+ {
45
+ "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
46
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
47
+ },
48
+ ]
49
+
50
+ # Two models - vision and text
51
+ textmodel = genai.GenerativeModel('gemini-1.0-pro',
52
+ generation_config=textgeneration_config,
53
+ safety_settings=safety_settings)
54
+
55
+ #imagemodel = genai.GenerativeModel('gemini-pro-vision')
56
+
57
+ visionmodel = genai.GenerativeModel(model_name="gemini-1.0-pro-vision-latest",
58
+ generation_config=visiongeneration_config,
59
+ safety_settings=safety_settings)
60
+
61
+
62
+
63
+ # Utility Functions
64
+ # Convert an image to base64 string format
65
+ import base64
66
+ def img2base64(image):
67
+ with open(image, 'rb') as img:
68
+ encoded_string = base64.b64encode(img.read())
69
+ return encoded_string.decode('utf-8')
70
+
71
+
72
+ # Check image format and display user messages in GUI
73
+ def user_inputs(history, txt, img):
74
+ if not img:
75
+ history += [(txt, None)]
76
+ return history
77
+
78
+ # Open the image for format verification
79
+ try:
80
+ with Image.open(img) as image:
81
+ # Get image format (e.g., PNG, JPEG)
82
+ image_format = image.format.upper()
83
+ except (IOError, OSError):
84
+ return history
85
+
86
+ if image_format not in ('JPEG','JPG','PNG'):
87
+ print(f"Warning: Unsupported image format: {image_format}")
88
+ return history
89
+
90
+ base64 = img2base64(img)
91
+ data_url = f"data:image/{image_format.lower()};base64,{base64}"
92
+ history += [(f"{txt} ![]({data_url})", None)]
93
+
94
+
95
+
96
+ import gradio as gr
97
+
98
+ TITLE = """<h1 align="center">Your Personal Health Coach</h1>"""
99
+ SUBTITLE = """<h2 align="center">Upload an image of your food to knows its calories, macronutrients or ask questions about heath and exercise.</h2>"""
100
+ DES = """
101
+ <div style="text-align: center; display: flex; justify-content: center; align-items: center;">
102
+ <span>You need to enter your FREE GEMINI KEY in the first text box to connect to Gemini Models. You can find your key here:
103
+ <a href="https://makersuite.google.com/app/apikey">GOOGLE API KEY</a>. <br><br>
104
+ <b> If you wish to ask a question unrelated to the image you have uploaded, just cross the image (top right corner of image) and then submit your question in the textbox.
105
+ </span>
106
+ </div>
107
+ """
108
+
109
+ def generate_model_response(api_key, history, text, img):
110
+ genai.configure(api_key=api_key)
111
+ if not img:
112
+ text = "You are an expert nutritionist and fitness coach. You are accurate, you always stick to the facts, and never make up new facts. \
113
+ For the questions asked by the user, answer accurately and to the point, in a friendly tone." + text
114
+ response = textmodel.generate_content(text)
115
+
116
+ else:
117
+ text = "From the image uploaded by the user answer with following information: Food items in the image, \
118
+ percentage of each macronutrient in the food in image and approximate number of calories in the food in image. If there is any additional question, answer that too." + text
119
+ img = Image.open(img)
120
+ response = visionmodel.generate_content([text,img])
121
+ history += [(None, response.text)]
122
+ return history
123
+
124
+
125
+ with gr.Blocks() as app:
126
+
127
+ gr.HTML(TITLE)
128
+ gr.HTML(SUBTITLE)
129
+ gr.HTML(DES)
130
+
131
+ api_key_box = gr.Textbox(placeholder = "Enter your GEMINI API KEY", label="Your GEMINI API KEY", type="password")
132
+
133
+ with gr.Row():
134
+ image_box = gr.Image(type="filepath")
135
+ chatbot = gr.Chatbot(
136
+ scale=3,
137
+ height=750
138
+ )
139
+
140
+ text_box = gr.Textbox(
141
+ placeholder="Ask something about the image your uploaded or ask for any health and fitness advice without uploading an image too",
142
+ container=False,
143
+ )
144
+
145
+ btn = gr.Button("Submit")
146
+
147
+ btn_clicked = btn.click(user_inputs,
148
+ [chatbot, text_box, image_box],
149
+ chatbot).then(generate_model_response,[api_key_box, chatbot, text_box, image_box], chatbot)
150
+
151
+ app.queue()
152
+ app.launch(debug=True)
153
+