Ridealist commited on
Commit
77df4ca
1 Parent(s): 2b2461f

feat: set gradio UI and adjust logic

Browse files
Files changed (1) hide show
  1. src/obs_eval_gradio.py +261 -32
src/obs_eval_gradio.py CHANGED
@@ -1,14 +1,56 @@
 
 
1
  import gradio as gr
2
  import cv2
3
  import base64
4
  import openai
5
 
6
- def process_video(video_file, api_key, instruction):
7
- # Set the OpenAI API key
8
- openai.api_key = api_key
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
 
 
10
  # Read and process the video file
11
- video = cv2.VideoCapture(video_file.name)
 
12
  base64Frames = []
13
  while video.isOpened():
14
  success, frame = video.read()
@@ -17,44 +59,231 @@ def process_video(video_file, api_key, instruction):
17
  _, buffer = cv2.imencode(".jpg", frame)
18
  base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
19
  video.release()
 
 
 
20
 
21
- PROMPT_MESSAGES = [
22
- {
23
- "role": "user",
24
- "content": [
25
- instruction,
26
- *map(lambda x: {"image": x, "resize": 768}, base64Frames[0::10]),
27
- ],
28
- },
29
- ]
30
 
31
- try:
32
- result = openai.ChatCompletion.create(
33
- model="gpt-4-vision-preview",
34
- messages=PROMPT_MESSAGES,
35
- api_key=openai.api_key,
36
- max_tokens=500,
37
- )
38
- return result.choices[0].message.content
39
- except Exception as e:
40
- return f"Error: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  # Define the Gradio app
43
  def main():
44
- with gr.Blocks() as app:
45
- gr.Markdown("## GPT-4 Vision for Evaluation")
 
46
  with gr.Row():
47
  with gr.Column(scale=1):
48
- api_key_input = gr.Textbox(label="Enter your OpenAI API Key (Your API Key must be allowed to use GPT-4 Vision)", lines=1)
49
- instruction_input = gr.Textbox(label="Enter Your Prompt", placeholder="Enter your prompt here...", lines=5)
50
- video_upload = gr.File(label="Upload your video (under 10 second video is the best..!)", type="file")
51
- submit_button = gr.Button("Summit")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  with gr.Column(scale=1):
53
- output_box = gr.Textbox(label="Generated Response", lines=7, interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
- submit_button.click(fn=process_video, inputs=[video_upload, api_key_input, instruction_input], outputs=output_box)
 
 
56
 
57
- app.launch()
58
 
59
  if __name__ == "__main__":
60
  main()
 
1
+ import time
2
+ import io
3
  import gradio as gr
4
  import cv2
5
  import base64
6
  import openai
7
 
8
+ from langchain.prompts import PromptTemplate
9
+ from langchain.chat_models import ChatOpenAI
10
+ from langchain.schema import StrOutputParser
11
+ from PIL import Image
12
+
13
+ global_dict = {}
14
+
15
+
16
+ def failure():
17
+ raise gr.Error("This should fail!")
18
+
19
+ def validate_api_key(api_key):
20
+ client = openai.OpenAI(api_key=api_key)
21
+
22
+ try:
23
+ # Make your OpenAI API request here
24
+ response = client.completions.create(
25
+ prompt="Hello world",
26
+ model="gpt-3.5-turbo-instruct"
27
+ )
28
+ except openai.RateLimitError as e:
29
+ # Handle rate limit error (we recommend using exponential backoff)
30
+ print(f"OpenAI API request exceeded rate limit: {e}")
31
+ response = None
32
+ pass
33
+ except openai.APIConnectionError as e:
34
+ # Handle connection error here
35
+ print(f"Failed to connect to OpenAI API: {e}")
36
+ response = None
37
+ pass
38
+ except openai.APIError as e:
39
+ # Handle API error here, e.g. retry or log
40
+ print(f"OpenAI API returned an API Error: {e}")
41
+ response = None
42
+ pass
43
+
44
+ if response:
45
+ return True
46
+ else:
47
+ raise gr.Error(f"OpenAI API returned an API Error")
48
 
49
+
50
+ def _process_video(image_file):
51
  # Read and process the video file
52
+ video = cv2.VideoCapture(image_file)
53
+
54
  base64Frames = []
55
  while video.isOpened():
56
  success, frame = video.read()
 
59
  _, buffer = cv2.imencode(".jpg", frame)
60
  base64Frames.append(base64.b64encode(buffer).decode("utf-8"))
61
  video.release()
62
+ if len(base64Frames) > 400:
63
+ raise gr.Warning(f"Video's play time is too long. (>10s)")
64
+ print(len(base64Frames), "frames read.")
65
 
66
+ if not base64Frames:
67
+ raise gr.Error(f"Cannot open the video.")
68
+ return base64Frames
 
 
 
 
 
 
69
 
70
+
71
+ def _make_video_batch(image_file, total_batch_percent):
72
+
73
+ frames = _process_video(image_file)
74
+
75
+ TOTAL_FRAME_COUNT = len(frames)
76
+ BATCH_SIZE = 5
77
+ TOTAL_BATCH_SIZE = int(TOTAL_FRAME_COUNT * total_batch_percent / 100)
78
+ BATCH_STEP = int(TOTAL_FRAME_COUNT / TOTAL_BATCH_SIZE)
79
+
80
+ base64FramesBatch = []
81
+
82
+ for idx in range(0, TOTAL_FRAME_COUNT, BATCH_STEP * BATCH_SIZE):
83
+ # print(f'## {idx}')
84
+ temp = []
85
+ for i in range(BATCH_SIZE):
86
+ # print(f'# {idx + BATCH_STEP * i}')
87
+ if (idx + BATCH_STEP * i) < TOTAL_FRAME_COUNT:
88
+ temp.append(frames[idx + BATCH_STEP * i])
89
+ else:
90
+ continue
91
+ base64FramesBatch.append(temp)
92
+
93
+ for idx, batch in enumerate(base64FramesBatch):
94
+ # assert len(batch) <= BATCH_SIZE
95
+ print(f'##{idx} - batch_size: {len(batch)}')
96
+
97
+ global_dict.setdefault('batched_frames', base64FramesBatch)
98
+ return base64FramesBatch
99
+
100
+
101
+ def show_batches(image_file, total_batch_size):
102
+
103
+ batched_frames = _make_video_batch(image_file, total_batch_size)
104
+
105
+ images = []
106
+ for i, l in enumerate(batched_frames):
107
+ print(f"#### Batch_{i+1}")
108
+ for j, img in enumerate(l):
109
+ print(f'## Image_{j+1}')
110
+ image_bytes = base64.b64decode(img.encode("utf-8"))
111
+ # Convert the bytes to a stream (file-like object)
112
+ image_stream = io.BytesIO(image_bytes)
113
+ # Open the image as a PIL image
114
+ image = Image.open(image_stream)
115
+ images.append((image, f"batch {i+1}"))
116
+ print("-"*100)
117
+
118
+ return images
119
+
120
+
121
+ def call_gpt_vision(api_key, instruction):
122
+ frames = global_dict.get('batched_frames')
123
+ openai.api_key = api_key
124
+
125
+ full_result = []
126
+
127
+ for idx, batch in enumerate(frames):
128
+ PROMPT_MESSAGES = [
129
+ {
130
+ "role": "system",
131
+ "content": "You will evaluate the behavior of the person in the sequences of images. They show discrete parts of the whole continuous behavior. You should only evaluate the parts you can rate based on the given images. Remember, you're evaluating the given parts to evaluate the whole continuous behavior, and you'll connect them later to evaluate the whole. Never add your own judgment. Evlaute only in the contents of images themselves. If you can't evaluate it, just answer '(Unevaluable)'"
132
+ },
133
+ {
134
+ "role": "user",
135
+ "content": [
136
+ "Evaluate the behavior's actions based on the <CRITERIA> provided.\n\n" + instruction,
137
+ *map(lambda x: {"image": x, "resize": 300}, batch),
138
+ ],
139
+ },
140
+ ]
141
+
142
+ params = {
143
+ "model": "gpt-4-vision-preview",
144
+ "messages": PROMPT_MESSAGES,
145
+ "max_tokens": 1024,
146
+ }
147
+
148
+ try:
149
+ result = openai.chat.completions.create(**params)
150
+ print(result.choices[0].message.content)
151
+ full_result.append(result)
152
+ except Exception as e:
153
+ print(f"Error: {e}")
154
+ pass
155
+
156
+ if 'full_result' not in global_dict:
157
+ global_dict.setdefault('full_result', full_result)
158
+ else:
159
+ global_dict['full_result'] = full_result
160
+
161
+ print(f'### BATCH_{idx+1}')
162
+ print('-'*100)
163
+ time.sleep(2)
164
+
165
+ yield f'### BATCH_{idx+1}\n' + "-"*50 + "\n" + result.choices[0].message.content + "\n" + "-"*50
166
+
167
+
168
+ def get_full_result():
169
+ full_result = global_dict.get('full_result')
170
 
171
+ result_text = ""
172
+
173
+ for idx, res in enumerate(full_result):
174
+ result_text += f'<Evaluation_{idx+1}>\n'
175
+ result_text += res.choices[0].message.content
176
+ result_text += "\n"
177
+ result_text += "-"*5
178
+ result_text += "\n"
179
+
180
+ global_dict.setdefault('result_text', result_text)
181
+
182
+ return result_text
183
+
184
+
185
+ def get_final_anser(api_key, result_text):
186
+ chain = ChatOpenAI(model="gpt-4", max_tokens=1024, temperature=0, api_key=api_key)
187
+ prompt = PromptTemplate.from_template(
188
+ """
189
+ You see the following list of texts that evaluate forward roll:
190
+ {evals}
191
+ Write an full text that synthesizes and summarizes the contents of all the text above.
192
+ Each evaluates a specific part, and you should combine them based on what was evaluated in each part.
193
+ The way to combine them is 'or', not 'and', which means you only need to evaluate the parts of a post that are rated based on that.
194
+ Concatenate based on what was evaluated, if anything.
195
+
196
+ Example:
197
+ an overview of evaluations
198
+ 1. Specific assessments for each item
199
+ 2.
200
+ 3.
201
+ ....
202
+ Overall opinion
203
+
204
+ Total score : 1~10 / 10
205
+
206
+ Output:
207
+ """
208
+ )
209
+ runnable = prompt | chain | StrOutputParser()
210
+
211
+ final_eval = runnable.invoke({"evals": result_text})
212
+ return final_eval
213
+
214
+
215
  # Define the Gradio app
216
  def main():
217
+ with gr.Blocks() as demo:
218
+ gr.Markdown("# GPT-4 Vision for Evaluation")
219
+ gr.Markdown("## 1st STEP. Make Batched Snapshots")
220
  with gr.Row():
221
  with gr.Column(scale=1):
222
+ api_key_input = gr.Textbox(
223
+ label="Enter your OpenAI API Key",
224
+ info="Your API Key must be allowed to use GPT-4 Vision",
225
+ placeholder="sk-*********...",
226
+ lines=1
227
+ )
228
+ video_upload = gr.File(label="Upload your video (under 10 second video is the best..!)")
229
+ # batch_size = gr.Number(
230
+ # label="Number of images in one batch",
231
+ # value=2,
232
+ # minimum=2,
233
+ # maximum=5
234
+ # )
235
+ total_batch_percent = gr.Number(
236
+ label="Percentage(%) of batched image frames to total frames",
237
+ value=10,
238
+ minimum=10,
239
+ maximum=40,
240
+ step=5
241
+ )
242
+ process_button = gr.Button("Process")
243
+
244
  with gr.Column(scale=1):
245
+ gallery = gr.Gallery(
246
+ label="Batched Snapshots of Video",
247
+ columns=[5],
248
+ rows=[1],
249
+ object_fit="contain",
250
+ height="auto"
251
+ )
252
+ gr.Markdown("## 2nd STEP. Set Evaluation Criteria")
253
+ with gr.Row():
254
+ with gr.Column(scale=1):
255
+ instruction_input = gr.Textbox(
256
+ label="Evaluation Criteria",
257
+ info="Enter your evaluation criteria here...",
258
+ placeholder="<CRITERIA>\nThe correct way to do a forward roll is as follows:\n1. From standing, bend your knees and straighten your arms in front of you.\n2. Place your hands on the floor, shoulder width apart with fingers pointing forward and your chin on your chest.\n3. Rock forward, straighten legs and transfer body weight onto shoulders.\n4. Rock forward on a rounded back placing both feet on the floor.\n5. Stand using arms for balance, without hands touching the floor.",
259
+ lines=7)
260
+ submit_button = gr.Button("Submit")
261
+
262
+ with gr.Column(scale=1):
263
+ output_box = gr.Textbox(
264
+ label="Batched Generated Response...(Streaming)",
265
+ lines=10,
266
+ interactive=False
267
+ )
268
+ gr.Markdown("## 3rd STEP. Summarize and Get Result")
269
+ with gr.Row():
270
+ with gr.Column(scale=1):
271
+ output_box_fin = gr.Textbox(
272
+ label="FULL Response",
273
+ info="You can edit partial evaluation in here...",
274
+ lines=10,
275
+ interactive=True)
276
+ submit_button_2 = gr.Button("Submit")
277
+
278
+ with gr.Column(scale=1):
279
+ output_box_fin_fin = gr.Textbox(label="FINAL EVALUATION", lines=10, interactive=True)
280
+
281
 
282
+ process_button.click(fn=validate_api_key, inputs=api_key_input, outputs=None).success(fn=show_batches, inputs=[video_upload, total_batch_percent], outputs=gallery)
283
+ submit_button.click(fn=call_gpt_vision, inputs=[api_key_input, instruction_input], outputs=output_box).then(get_full_result, None, output_box_fin)
284
+ submit_button_2.click(fn=get_final_anser, inputs=[api_key_input, output_box_fin], outputs=output_box_fin_fin)
285
 
286
+ demo.launch()
287
 
288
  if __name__ == "__main__":
289
  main()