burak commited on
Commit
4e1e279
1 Parent(s): 61a1c75

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +297 -0
app.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ from typing import List, Tuple, Optional
4
+ from pathlib import Path
5
+
6
+ import google.generativeai as genai
7
+ import gradio as gr
8
+ from PIL import Image
9
+
10
+
11
+ GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
12
+
13
+ TITLE = """<h1 align="center">🏋️ Online Personal Trainer 💪</h1>"""
14
+ SUBTITLE = """<h3 align="center">Upload your workout video and let the AI analyze your form 🖇️</h3>"""
15
+
16
+ Prompt = """
17
+ You are the world's best fitness expert. Your goal is to analyze in detail how people perform their exercises and sports movements. Watch the provided video carefully and give them constructive feedback in at least 10 sentences. Focus on the following aspects:
18
+
19
+ Form and Technique: Identify any issues with the form and technique of the exercises being performed. Provide specific suggestions for improvement.
20
+ Repetitions and Sets: Count the number of repetitions and sets for each exercise. Ensure they match the intended workout plan.
21
+ Pacing and Timing: Evaluate the pacing and timing of the exercises. Suggest any adjustments needed to optimize performance.
22
+ Overall Performance: Give an overall assessment of the workout, highlighting strengths and areas for improvement.
23
+ Remember to be encouraging and supportive in your feedback. Your goal is to help them improve and stay motivated. Thank you!
24
+ """
25
+ #If the image does not show an exercise, respond with: 'What are you doing? This is no time for games! Upload a real exercise video.'
26
+
27
+
28
+
29
+ def preprocess_stop_sequences(stop_sequences: str) -> Optional[List[str]]:
30
+ if not stop_sequences:
31
+ return None
32
+ return [sequence.strip() for sequence in stop_sequences.split(",")]
33
+
34
+ def user(text_prompt: str, chatbot: List[Tuple[str, str]]):
35
+ return "", chatbot + [[text_prompt, None]]
36
+
37
+ def bot(
38
+ google_key: str,
39
+ model_name: str,
40
+ video_prompt,
41
+ temperature: float,
42
+ max_output_tokens: int,
43
+ stop_sequences: str,
44
+ top_k: int,
45
+ top_p: float,
46
+ text_prompt_component: str,
47
+ chatbot: List[Tuple[str, str]]
48
+ ):
49
+ google_key = google_key if google_key else GOOGLE_API_KEY
50
+ if not google_key:
51
+ raise ValueError(
52
+ "GOOGLE_API_KEY is not set. "
53
+ "Please follow the instructions in the README to set it up.")
54
+
55
+ user_input = chatbot[-1][0]
56
+ combined_prompt = Prompt + "\n" + user_input
57
+
58
+ genai.configure(api_key=google_key)
59
+ generation_config = genai.types.GenerationConfig(
60
+ temperature=temperature,
61
+ max_output_tokens=max_output_tokens,
62
+ stop_sequences=preprocess_stop_sequences(stop_sequences=stop_sequences),
63
+ top_k=top_k,
64
+ top_p=top_p)
65
+
66
+ if video_prompt is not None:
67
+ model = genai.GenerativeModel(model_name)
68
+
69
+ video_file = genai.upload_file(path=video_prompt)
70
+ while video_file.state.name == "PROCESSING":
71
+ print('.', end='')
72
+ time.sleep(10)
73
+ video_file = genai.get_file(video_file.name)
74
+
75
+ if video_file.state.name == "FAILED":
76
+ raise ValueError(video_file.state.name)
77
+
78
+ response = model.generate_content(
79
+ contents=[video_file, combined_prompt],
80
+ stream=True,
81
+ generation_config=generation_config,
82
+ request_options={"timeout": 600})
83
+ response.resolve()
84
+ else:
85
+ model = genai.GenerativeModel(model_name)
86
+ response = model.generate_content(
87
+ combined_prompt,
88
+ stream=True,
89
+ generation_config=generation_config)
90
+ response.resolve()
91
+
92
+
93
+ # streaming effect
94
+ chatbot[-1][1] = ""
95
+ for chunk in response:
96
+ for i in range(0, len(chunk.text), 10):
97
+ section = chunk.text[i:i + 10]
98
+ chatbot[-1][1] += section
99
+ time.sleep(0.01)
100
+ yield chatbot
101
+
102
+ google_key_component = gr.Textbox(
103
+ label="GOOGLE API KEY",
104
+ value="",
105
+ type="password",
106
+ placeholder="...",
107
+ info="You have to provide your own GOOGLE_API_KEY for this app to function properly",
108
+ visible=GOOGLE_API_KEY is None
109
+ )
110
+
111
+ video_prompt_component = gr.Video(label="Video", autoplay=True)
112
+
113
+ model_selection = gr.Dropdown(["gemini-1.5-flash-latest", "gemini-1.5-pro-latest"], label="Select Gemini Model", value="gemini-1.5-pro-latest")
114
+
115
+ chatbot_component = gr.Chatbot(
116
+ label='Gemini',
117
+ bubble_full_width=False,
118
+ scale=3, height=500
119
+ )
120
+ text_prompt_component = gr.Textbox(
121
+ placeholder="Hi there!",
122
+ label="Ask me anything and press Enter"
123
+ )
124
+ run_button_component = gr.Button()
125
+ temperature_component = gr.Slider(
126
+ minimum=0,
127
+ maximum=1.0,
128
+ value=0.6,
129
+ step=0.05,
130
+ label="Temperature",
131
+ info=(
132
+ "Temperature controls the degree of randomness in token selection. Lower "
133
+ "temperatures are good for prompts that expect a true or correct response, "
134
+ "while higher temperatures can lead to more diverse or unexpected results. "
135
+ ))
136
+ max_output_tokens_component = gr.Slider(
137
+ minimum=1,
138
+ maximum=2048,
139
+ value=1024,
140
+ step=1,
141
+ label="Token limit",
142
+ info=(
143
+ "Token limit determines the maximum amount of text output from one prompt. A "
144
+ "token is approximately four characters. The default value is 2048."
145
+ ))
146
+ stop_sequences_component = gr.Textbox(
147
+ label="Add stop sequence",
148
+ value="",
149
+ type="text",
150
+ placeholder="STOP, END",
151
+ info=(
152
+ "A stop sequence is a series of characters (including spaces) that stops "
153
+ "response generation if the model encounters it. The sequence is not included "
154
+ "as part of the response. You can add up to five stop sequences."
155
+ ))
156
+ top_k_component = gr.Slider(
157
+ minimum=1,
158
+ maximum=40,
159
+ value=32,
160
+ step=1,
161
+ label="Top-K",
162
+ info=(
163
+ "Top-k changes how the model selects tokens for output. A top-k of 1 means the "
164
+ "selected token is the most probable among all tokens in the model's "
165
+ "vocabulary (also called greedy decoding), while a top-k of 3 means that the "
166
+ "next token is selected from among the 3 most probable tokens (using "
167
+ "temperature)."
168
+ ))
169
+ top_p_component = gr.Slider(
170
+ minimum=0,
171
+ maximum=1,
172
+ value=1,
173
+ step=0.01,
174
+ label="Top-P",
175
+ info=(
176
+ "Top-p changes how the model selects tokens for output. Tokens are selected "
177
+ "from most probable to least until the sum of their probabilities equals the "
178
+ "top-p value. For example, if tokens A, B, and C have a probability of .3, .2, "
179
+ "and .1 and the top-p value is .5, then the model will select either A or B as "
180
+ "the next token (using temperature). "
181
+ ))
182
+
183
+ user_inputs = [text_prompt_component,
184
+ chatbot_component
185
+ ]
186
+
187
+ bot_inputs = [
188
+ google_key_component,
189
+ model_selection,
190
+ video_prompt_component,
191
+ temperature_component,
192
+ max_output_tokens_component,
193
+ stop_sequences_component,
194
+ top_k_component,
195
+ top_p_component,
196
+ text_prompt_component,
197
+ chatbot_component
198
+ ]
199
+
200
+ with gr.Blocks() as demo:
201
+ gr.HTML(TITLE)
202
+ gr.HTML(SUBTITLE)
203
+ with gr.Column():
204
+ google_key_component.render()
205
+ with gr.Row():
206
+ video_prompt_component.render()
207
+
208
+ chatbot_component.render()
209
+ text_prompt_component.render()
210
+ run_button_component.render()
211
+ with gr.Accordion("Parameters", open=False):
212
+ model_selection.render()
213
+ temperature_component.render()
214
+ max_output_tokens_component.render()
215
+ stop_sequences_component.render()
216
+ with gr.Accordion("Advanced", open=False):
217
+ top_k_component.render()
218
+ top_p_component.render()
219
+
220
+ run_button_component.click(
221
+ fn=user,
222
+ inputs=user_inputs,
223
+ outputs=[text_prompt_component, chatbot_component],
224
+ queue=False
225
+ ).then(
226
+ fn=bot, inputs=bot_inputs, outputs=[chatbot_component]
227
+ )
228
+
229
+ text_prompt_component.submit(
230
+ fn=user,
231
+ inputs=user_inputs,
232
+ outputs=[text_prompt_component, chatbot_component],
233
+ queue=False
234
+ ).then(
235
+ fn=bot, inputs=bot_inputs, outputs=[chatbot_component]
236
+ )
237
+
238
+ gr.Examples(
239
+ fn=bot,
240
+ inputs=bot_inputs,
241
+ outputs=[chatbot_component],
242
+ examples=
243
+ [
244
+
245
+ [
246
+ "",
247
+ "gemini-1.5-pro-latest",
248
+ "./example1.mp4",
249
+ .7,
250
+ 1024,
251
+ "",
252
+ 32,
253
+ 1,
254
+ "Give me some tips to improve my deadlift.",
255
+ [("", "")]
256
+ ],
257
+ [
258
+ "",
259
+ "gemini-1.5-pro-latest",
260
+ "./example2.mp4",
261
+ .7,
262
+ 1024,
263
+ "",
264
+ 32,
265
+ 1,
266
+ "How is my form?",
267
+ [("", "")]
268
+ ],
269
+ [
270
+ "",
271
+ "gemini-1.5-pro-latest",
272
+ "./example3.mp4",
273
+ .7,
274
+ 1024,
275
+ "",
276
+ 32,
277
+ 1,
278
+ "What improvements can I make?",
279
+ [("", "")]
280
+ ],
281
+ [
282
+ "",
283
+ "gemini-1.5-pro-latest",
284
+ "./example4.mp4",
285
+ .7,
286
+ 1024,
287
+ "",
288
+ 32,
289
+ 1,
290
+ "I just started working out. I'm not sure I'm doing it right. Can you check?",
291
+ [("", "")]
292
+ ]
293
+ ],
294
+ #cache_examples="lazy",
295
+ )
296
+
297
+ demo.queue(max_size=99).launch(debug=False, show_error=True)