dylanplummer commited on
Commit
8fe9a5a
·
1 Parent(s): 9da2ef1

Initial commit (old space)

Browse files
Files changed (3) hide show
  1. app.py +523 -0
  2. packages.txt +3 -0
  3. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ from PIL import Image
4
+ from openvino.runtime import Core
5
+ import os
6
+ import cv2
7
+ import uuid
8
+ import time
9
+ import subprocess
10
+ import matplotlib
11
+ matplotlib.use('Agg')
12
+ import matplotlib.pyplot as plt
13
+ from matplotlib.animation import FuncAnimation
14
+ from scipy.signal import medfilt
15
+ from functools import partial
16
+ from tqdm import tqdm
17
+ import pandas as pd
18
+ import plotly.express as px
19
+ import torch
20
+ from torchvision import transforms
21
+ import torchvision.transforms.functional as F
22
+
23
+ from huggingface_hub import hf_hub_download
24
+ from huggingface_hub import HfApi
25
+
26
+ plt.style.use('dark_background')
27
+
28
+ hf_hub_download(repo_id="dylanplummer/ropenet", filename="model.bin", repo_type="model", token=os.environ['DATASET_SECRET'])
29
+ model_xml = hf_hub_download(repo_id="dylanplummer/ropenet", filename="model.xml", repo_type="model", token=os.environ['DATASET_SECRET'])
30
+ hf_hub_download(repo_id="dylanplummer/ropenet", filename="model.mapping", repo_type="model", token=os.environ['DATASET_SECRET'])
31
+ #model_xml = "model_ir/model.xml"
32
+
33
+ ie = Core()
34
+ model_ir = ie.read_model(model=model_xml)
35
+ config = {"PERFORMANCE_HINT": "LATENCY"}
36
+ compiled_model_ir = ie.compile_model(model=model_ir, device_name="CPU", config=config)
37
+
38
+ a = os.path.join(os.path.dirname(__file__), "files", "dylan.mp4")
39
+ b = os.path.join(os.path.dirname(__file__), "files", "train14.mp4")
40
+ c = os.path.join(os.path.dirname(__file__), "files", "train3.mp4")
41
+ d = os.path.join(os.path.dirname(__file__), "files", "train29.mp4")
42
+
43
+ def sigmoid(x):
44
+ return 1 / (1 + np.exp(-x))
45
+
46
+
47
+ def confidence_analysis(periodicity, counts, frames, out_dir='confidence_animations', top_n=9):
48
+ os.makedirs(out_dir, exist_ok=True)
49
+ jump_arrs = []
50
+ confidence_arrs = []
51
+ current_jump = []
52
+ current_confidence = []
53
+ current_period = 1
54
+ for i in range(len(periodicity)):
55
+ if counts[i] < current_period:
56
+ current_jump.append(np.array(frames[i]))
57
+ current_confidence.append(periodicity[i])
58
+ else:
59
+ jump_arrs.append(current_jump)
60
+ confidence_arrs.append(current_confidence)
61
+ current_jump = [np.array(frames[i])]
62
+ current_confidence = [periodicity[i]]
63
+ current_period += 1
64
+ avg_confidences = [np.median(x) for x in confidence_arrs]
65
+ conf_order = np.argsort(avg_confidences)
66
+ tiled_img = []
67
+ tiled_confs = []
68
+ for out_i, conf_idx in enumerate(conf_order):
69
+ frames = np.array(jump_arrs[conf_idx])
70
+ confidence = np.array(confidence_arrs[conf_idx])
71
+ mean_confidence = np.median(confidence)
72
+ tiled_img.append(frames)
73
+ tiled_confs.append(mean_confidence)
74
+ # fig, axs = plt.subplots(1, 1, figsize = (3, 3))
75
+
76
+ # img_ax = axs
77
+ # img_ax.imshow(np.zeros((128, 128, 3)))
78
+
79
+ # def animate(i):
80
+ # img = frames[i]
81
+ # #img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
82
+ # print(np.min(img), np.mean(img), np.max(img))
83
+ # img_ax.imshow(np.clip(img, 0, 255))
84
+ # print(i, end=' ')
85
+ # img_ax.set_xticks([])
86
+ # img_ax.set_yticks([])
87
+ # img_ax.set_title(f'Confidence: {mean_confidence:.2f}')
88
+
89
+
90
+ # anim = FuncAnimation(fig, animate, frames=len(frames), interval=200)
91
+ # anim.save(f'{out_dir}/conf_{out_i}.gif', writer=None)
92
+ # plt.close(fig)
93
+ if top_n > 10:
94
+ break
95
+ longest_len = max([len(x) for x in tiled_img])
96
+ looped_tiled_img = []
97
+ for frames in tiled_img:
98
+ looped_tiled_img.append(np.concatenate([frames, frames[::-1]] * (longest_len // len(frames) + 1), axis=0)[:longest_len])
99
+ # animate each tile
100
+ n_rows = int(np.ceil(np.sqrt(top_n)))
101
+ n_cols = int(np.ceil(top_n / n_rows))
102
+ fig, axs = plt.subplots(n_rows, n_cols, figsize = (n_cols * 2, n_rows * 2))
103
+ for i in range(n_rows):
104
+ for j in range(n_cols):
105
+ if i * n_cols + j < len(looped_tiled_img):
106
+ img_ax = axs[i][j]
107
+ img_ax.imshow(np.zeros((128, 128, 3)))
108
+ def animate(i):
109
+ print(i, end=' ')
110
+ for row in range(n_rows):
111
+ for col in range(n_cols):
112
+ img = looped_tiled_img[row * n_cols + col][i]
113
+ img_ax = axs[row][col]
114
+ img_ax.imshow(np.clip(img, 0, 255))
115
+ img_ax.set_xticks([])
116
+ img_ax.set_yticks([])
117
+ img_ax.set_title(f'Conf: {tiled_confs[row * n_cols + col]:.2f}')
118
+ anim = FuncAnimation(fig, animate, frames=longest_len, interval=200)
119
+ anim.save(f'{out_dir}/tiled_conf.gif', writer=None)
120
+ plt.close(fig)
121
+
122
+
123
+ def inference(x, both_feet, has_misses, true_count, center_crop, img_resize, miss_threshold, img_size=192, seq_len=64, stride_length=32, stride_pad=3, batch_size=4, median_pred_filter=True, api_call=False):
124
+ print(x)
125
+ img_size = int((img_size - 64) * img_resize + 64)
126
+ api = HfApi(token=os.environ['DATASET_SECRET'])
127
+ out_file = str(uuid.uuid1())
128
+ if has_misses:
129
+ out_file = "misses_" + out_file
130
+ if true_count != -1:
131
+ out_file += '_' + str(true_count)
132
+ out_file = f"labeled_videos/{out_file}.mp4"
133
+ api.upload_file(
134
+ path_or_fileobj=x,
135
+ path_in_repo=out_file,
136
+ repo_id="dylanplummer/jumprope",
137
+ repo_type="dataset",
138
+ )
139
+
140
+
141
+ cap = cv2.VideoCapture(x)
142
+ length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
143
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
144
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
145
+ period_length_overlaps = np.zeros(length + seq_len)
146
+ fps = int(cap.get(cv2.CAP_PROP_FPS))
147
+ seconds = length / fps
148
+ all_frames = []
149
+ frame_i = 1
150
+ while cap.isOpened():
151
+ ret, frame = cap.read()
152
+ if ret is False:
153
+ frame = all_frames[-1] # padding will be with last frame
154
+ break
155
+ frame = cv2.cvtColor(np.uint8(frame), cv2.COLOR_BGR2RGB)
156
+ img = Image.fromarray(frame)
157
+ width, height = img.size
158
+ if width > height:
159
+ img = img.resize((int(width / (height / img_size)), img_size))
160
+ else:
161
+ img = img.resize((img_size, int(height / (width / img_size))))
162
+ all_frames.append(np.uint8(img))
163
+ frame_i += 1
164
+ cap.release()
165
+
166
+ # Get output layer
167
+ output_layer_period_length = compiled_model_ir.output(0)
168
+ output_layer_periodicity = compiled_model_ir.output(1)
169
+ length = len(all_frames)
170
+ period_lengths = np.zeros(len(all_frames) + seq_len + stride_length)
171
+ periodicities = np.zeros(len(all_frames) + seq_len + stride_length)
172
+ period_length_overlaps = np.zeros(len(all_frames) + seq_len + stride_length)
173
+ for _ in range(seq_len + stride_length): # pad full sequence
174
+ all_frames.append(all_frames[-1])
175
+ batch_list = []
176
+ idx_list = []
177
+ for i in tqdm(range(0, length + stride_length - stride_pad, stride_length)):
178
+ batch = all_frames[i:i + seq_len]
179
+ Xlist = []
180
+ for img in batch:
181
+ transforms_list = []
182
+ if center_crop:
183
+ #transforms_list.append(SquarePad())
184
+ transforms_list.append(transforms.CenterCrop((img_size, img_size)))
185
+ else:
186
+ transforms_list.append(transforms.Resize((img_size, img_size)))
187
+
188
+
189
+ transforms_list += [
190
+ transforms.ToTensor()]
191
+ #transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]
192
+ preprocess = transforms.Compose(transforms_list)
193
+ frameTensor = preprocess(Image.fromarray(img)).unsqueeze(0)
194
+ Xlist.append(frameTensor)
195
+
196
+ if len(Xlist) < seq_len:
197
+ for _ in range(seq_len - len(Xlist)):
198
+ Xlist.append(Xlist[-1])
199
+
200
+ X = torch.cat(Xlist)
201
+ X *= 255
202
+ batch_list.append(X.unsqueeze(0))
203
+ idx_list.append(i)
204
+ if len(batch_list) == batch_size:
205
+ batch_X = torch.cat(batch_list)
206
+ result = compiled_model_ir(batch_X)
207
+ y1pred = result[output_layer_period_length]
208
+ y2pred = result[output_layer_periodicity]
209
+ for y1, y2, idx in zip(y1pred, y2pred, idx_list):
210
+ periodLength = y1.squeeze()
211
+ periodicity = y2.squeeze()
212
+ period_lengths[idx:idx+seq_len] += periodLength
213
+ periodicities[idx:idx+seq_len] += periodicity
214
+ period_length_overlaps[idx:idx+seq_len] += 1
215
+ batch_list = []
216
+ idx_list = []
217
+ if len(batch_list) != 0: # still some leftover frames
218
+ while len(batch_list) != batch_size:
219
+ batch_list.append(batch_list[-1])
220
+ idx_list.append(idx_list[-1])
221
+ batch_X = torch.cat(batch_list)
222
+ result = compiled_model_ir(batch_X)
223
+ y1pred = result[output_layer_period_length]
224
+ y2pred = result[output_layer_periodicity]
225
+ for y1, y2, idx in zip(y1pred, y2pred, idx_list):
226
+ periodLength = y1.squeeze()
227
+ periodicity = y2.squeeze()
228
+ period_lengths[idx:idx+seq_len] += periodLength
229
+ periodicities[idx:idx+seq_len] += periodicity
230
+ period_length_overlaps[idx:idx+seq_len] += 1
231
+
232
+ periodLength = np.divide(period_lengths, period_length_overlaps, where=period_length_overlaps!=0)[:length]
233
+ periodicity = np.divide(periodicities, period_length_overlaps, where=period_length_overlaps!=0)[:length]
234
+ if api_call:
235
+ return np.array2string(periodLength, formatter={'float_kind':lambda x: "%.3f" % x}).replace('\n', ''), np.array2string(periodicity, formatter={'float_kind':lambda x: "%.3f" % x}).replace('\n', '')
236
+ if median_pred_filter:
237
+ periodicity = medfilt(periodicity, 5)
238
+ periodLength = medfilt(periodLength, 5)
239
+ periodicity = sigmoid(periodicity)
240
+ periodicity_mask = np.int32(periodicity > miss_threshold)
241
+ numofReps = 0
242
+ count = []
243
+ for i in range(len(periodLength)):
244
+ if periodLength[i] < 2 or periodicity_mask[i] == 0:
245
+ numofReps += 0
246
+ else:
247
+ numofReps += max(0, periodicity_mask[i]/(periodLength[i]))
248
+ count.append(round(float(numofReps), 2))
249
+ count_pred = count[-1]
250
+ if not both_feet:
251
+ count_pred = count_pred / 2
252
+ count = np.array(count) / 2
253
+
254
+ animate_frames = len(count)
255
+ anim_subsample = max(1, int(fps / 24))
256
+ fig, ax = plt.subplots(figsize = (3, 3))
257
+ canvas_width, canvas_height = fig.canvas.get_width_height()
258
+ img_ax = ax
259
+
260
+ # imgs = []
261
+ # for img in all_frames:
262
+ # img = Image.fromarray(img)
263
+ # width, height = img.size
264
+ # if width > height:
265
+ # img = img.resize((int(width / (height / img_size)), img_size))
266
+ # else:
267
+ # img = img.resize((img_size, int(height / (width / img_size))))
268
+ # h_center, w_center = height / 2, width / 2
269
+ # h_start, w_start = int(h_center - img_size / 2), int(w_center - img_size / 2)
270
+ # cropped = img.crop((w_start, h_start, w_start + img_size, h_start + img_size))
271
+ # imgs.append(cropped)
272
+
273
+ # confidence_analysis(periodicity, count, imgs)
274
+
275
+ # alpha=1.0
276
+ # colormap=plt.cm.OrRd
277
+ # h, w, _ = np.shape(imgs[0])
278
+ # wedge_x = 34 / canvas_width * w
279
+ # wedge_y = 34 / canvas_height * h
280
+ # wedge_r = 30 / canvas_height * h
281
+ # txt_x = 34 / canvas_width * w
282
+ # txt_y = 36 / canvas_height * h
283
+ # otxt_size = 25 / canvas_height * h
284
+ # wedge1 = matplotlib.patches.Wedge(
285
+ # center=(wedge_x, wedge_y),
286
+ # r=wedge_r,
287
+ # theta1=0,
288
+ # theta2=0,
289
+ # color=colormap(1.),
290
+ # alpha=alpha)
291
+ # wedge2 = matplotlib.patches.Wedge(
292
+ # center=(wedge_x, wedge_y),
293
+ # r=wedge_r,
294
+ # theta1=0,
295
+ # theta2=0,
296
+ # color=colormap(0.5),
297
+ # alpha=alpha)
298
+
299
+ # im = img_ax.imshow(cropped)
300
+
301
+ # img_ax.add_patch(wedge1)
302
+ # img_ax.add_patch(wedge2)
303
+ # txt = img_ax.text(
304
+ # txt_x,
305
+ # txt_y,
306
+ # '0',
307
+ # size=otxt_size,
308
+ # ha='center',
309
+ # va='center',
310
+ # alpha=0.9,
311
+ # color='white',
312
+ # )
313
+
314
+ # def animate_fn(i):
315
+ # if anim_subsample:
316
+ # i *= anim_subsample
317
+ # cropped = imgs[i + stride_pad]
318
+ # current_count = count[i]
319
+ # if current_count % 2 == 0:
320
+ # wedge1.set_color(colormap(1.0))
321
+ # wedge2.set_color(colormap(0.5))
322
+ # else:
323
+ # wedge1.set_color(colormap(0.5))
324
+ # wedge2.set_color(colormap(1.0))
325
+ # txt.set_text(int(current_count))
326
+ # wedge1.set_theta1(-90)
327
+ # wedge1.set_theta2(-90 - 360 * (1 - current_count % 1.0))
328
+ # wedge2.set_theta1(-90 - 360 * (1 - current_count % 1.0))
329
+ # wedge2.set_theta2(-90)
330
+
331
+ # im.set_data(cropped)
332
+ # img_ax.set_title(f"Time: {i / fps:.1f}s, {current_count:.1f}/{count_pred:.1f} jumps")
333
+ # img_ax.set_xticks([])
334
+ # img_ax.set_yticks([])
335
+ # img_ax.spines['top'].set_visible(False)
336
+ # img_ax.spines['right'].set_visible(False)
337
+ # img_ax.spines['bottom'].set_visible(False)
338
+ # img_ax.spines['left'].set_visible(False)
339
+
340
+ outf = x
341
+ # anim_start_time = time.time()
342
+ # # Open an ffmpeg process
343
+ # outf = x.replace('.mp4', '_jump.mp4')
344
+ # cmdstring = ('ffmpeg',
345
+ # '-y', '-r', f'{30 if anim_subsample != 1 else int(fps)}', # overwrite, 24fps
346
+ # '-s', f'{canvas_width}x{canvas_height}',
347
+ # '-pix_fmt', 'argb',
348
+ # '-hide_banner', '-loglevel', 'error',
349
+ # '-f', 'rawvideo', '-i', '-', # tell ffmpeg to expect raw video from the pipe
350
+ # '-i', x, '-map', '0:v', '-map', '1:a', # map video from the pipe, audio from the input file
351
+ # '-c:v', 'libx264', # https://trac.ffmpeg.org/wiki/Encode/H.264
352
+ # outf) # output encoding
353
+ # try:
354
+ # p = subprocess.Popen(cmdstring, stdin=subprocess.PIPE)
355
+ # except FileNotFoundError as e:
356
+ # print(e)
357
+ # print('Trying to install ffmpeg...')
358
+ # os.system("apt install ffmpeg -y")
359
+ # p = subprocess.Popen(cmdstring, stdin=subprocess.PIPE)
360
+
361
+ # # Draw frames and write to the pipe
362
+ # anim_length = int(animate_frames / anim_subsample) - 1
363
+ # for frame in range(anim_length):
364
+ # # draw the frame
365
+ # animate_fn(frame)
366
+ # fig.canvas.draw()
367
+ # # extract the image as an ARGB string
368
+ # string = fig.canvas.tostring_argb()
369
+ # # write to pipe
370
+ # p.stdin.write(string)
371
+
372
+ # # Finish up
373
+ # p.communicate()
374
+ # print(f"Animation done in {time.time() - anim_start_time:.2f} seconds")
375
+ #cvrt_string = f'ffmpeg -hide_banner -loglevel error -i "{outf}" -i "{x}" -map 0:v -map 1:a -y -r 24 -s {canvas_width}x{canvas_height} -c:v libx264 "{outf.replace(".mp4", "_audio.mp4")}"'
376
+ #os.system(cvrt_string)
377
+
378
+ if both_feet:
379
+ count_msg = f"## Predicted Count (both feet): {count_pred:.1f}"
380
+ else:
381
+ count_msg = f"## Predicted Count (one foot): {count_pred:.1f}"
382
+
383
+ jumps_per_second = np.clip(1 / ((periodLength / fps) + 0.05), 0, 8)
384
+ jumping_speed = np.copy(jumps_per_second)
385
+ misses = periodicity < miss_threshold
386
+ jumps_per_second[misses] = 0
387
+ df = pd.DataFrame.from_dict({'period length': periodLength,
388
+ 'jumping speed': jumping_speed,
389
+ 'jumps per second': jumps_per_second,
390
+ 'periodicity': periodicity,
391
+ 'miss': misses,
392
+ 'miss_size': np.clip((1 - periodicity) * 0.9 + 0.1, 1, 10),
393
+ 'seconds': np.linspace(0, seconds, num=len(periodLength))})
394
+ fig = px.scatter(data_frame=df,
395
+ x='seconds',
396
+ y='jumps per second',
397
+ symbol='miss',
398
+ symbol_map={False: 'triangle-down', True: 'circle-open'},
399
+ color='periodicity',
400
+ size='miss_size',
401
+ size_max=8,
402
+ color_continuous_scale='RdYlGn',
403
+ title="Jumping speed (jumps-per-second)",
404
+ trendline='rolling',
405
+ trendline_options=dict(window=32),
406
+ trendline_color_override="goldenrod",
407
+ trendline_scope='overall',
408
+ template="plotly_dark")
409
+ fig.update_layout(legend=dict(
410
+ orientation="h",
411
+ yanchor="bottom",
412
+ y=0.98,
413
+ xanchor="right",
414
+ x=1,
415
+ font=dict(
416
+ family="Courier",
417
+ size=12,
418
+ color="black"
419
+ ),
420
+ bgcolor="AliceBlue",
421
+ ),
422
+ paper_bgcolor='rgba(0,0,0,0)',
423
+ plot_bgcolor='rgba(0,0,0,0)'
424
+ )
425
+
426
+ hist = px.histogram(df,
427
+ x="jumps per second",
428
+ template="plotly_dark",
429
+ marginal="box",
430
+ histnorm='percent',
431
+ title="Distribution of jumping speed (jumps-per-second)",
432
+ range_x=[np.min(jumps_per_second[jumps_per_second > 0]) - 0.5, np.max(jumps_per_second) + 0.5])
433
+
434
+ vid = px.imshow(np.uint8(all_frames)[:128], animation_frame=0, binary_string=True, binary_compression_level=5, binary_format='jpg', template="plotly_dark")
435
+ vid.update_xaxes(showticklabels=False).update_yaxes(showticklabels=False)
436
+ vid.layout.updatemenus[0].buttons[0].args[1]['frame']['duration'] = 13
437
+ vid.layout.updatemenus[0].buttons[0].args[1]['transition']['duration'] = 5
438
+
439
+ return count_msg, vid, fig, hist, periodLength
440
+
441
+
442
+ DESCRIPTION = '# NextJump'
443
+ DESCRIPTION += '\n## AI Counting for Competitive Jump Rope'
444
+ DESCRIPTION += '\nDemo created by [Dylan Plummer](https://dylan-plummer.github.io/). Check out the [NextJump iOS app](https://apps.apple.com/us/app/nextjump-jump-rope-counter/id6451026115).'
445
+
446
+
447
+ with gr.Blocks() as demo:
448
+ gr.Markdown(DESCRIPTION)
449
+ with gr.Column():
450
+ with gr.Row():
451
+ in_video = gr.Video(type="file", label="Input Video", elem_id='input-video', format='mp4').style(width=400)
452
+ with gr.Column():
453
+ gr.Markdown(label="Optional settings and parameters:")
454
+ true_count = gr.Number(label="True Count (optional)", info="Provide a true count if you are ok with us using your video for training", elem_id='true-count', value=-1)
455
+ both_feet = gr.Checkbox(label="Both feet", info="Count both feet rather than only one", elem_id='both-feet', value=False)
456
+ misses = gr.Checkbox(label="Contains misses", info="Only necessary if providing a true count for training", elem_id='both-feet', value=False)
457
+ center_crop = gr.Checkbox(label="Center crop square", info="Either crop a square out of the center or stretch to a square", elem_id='center-crop', value=True)
458
+ image_size = gr.Slider(label="Image size", info="Lower image size is faster but less accurate", elem_id='miss-thresh', minimum=0.0, maximum=1.0, step=0.01, value=1.0)
459
+ miss_thresh = gr.Slider(label="Miss threshold", info="Lower values are more sensitive to misses", elem_id='miss-thresh', minimum=0.0, maximum=0.99, step=0.01, value=0.95)
460
+ with gr.Row():
461
+ run_button = gr.Button(label="Run", elem_id='run-button').style(full_width=False)
462
+ count_only = gr.Button(label="Run (No Viz)", elem_id='count-only', visible=False).style(full_width=False)
463
+
464
+ with gr.Column(elem_id='output-video-container'):
465
+ with gr.Row():
466
+ with gr.Column():
467
+ out_text = gr.Markdown(label="Predicted Count", elem_id='output-text')
468
+ period_length = gr.Textbox(label="Period Length", elem_id='period-length', visible=False)
469
+ periodicity = gr.Textbox(label="Periodicity", elem_id='periodicity', visible=False)
470
+ with gr.Column(min_width=480):
471
+ #out_video = gr.PlayableVideo(label="Output Video", elem_id='output-video', format='mp4')
472
+ out_video = gr.Plot(label="Output Video", elem_id='output-video')
473
+ out_plot = gr.Plot(label="Jumping Speed", elem_id='output-plot')
474
+ out_hist = gr.Plot(label="Speed Histogram", elem_id='output-hist')
475
+
476
+ inputs = [in_video, both_feet, misses, true_count, center_crop, image_size, miss_thresh]
477
+ with gr.Accordion(label="Instructions and more information", open=False):
478
+ instructions = "## Instructions:"
479
+ instructions += "\n* Upload a video and click 'Run' to get a prediction of the number of jumps (either one foot, or both). This could take a couple minutes! The model is trained on single rope and double dutch speed, but try out any videos you want."
480
+ instructions += "\n* If you know the true count, you can provide it and your video will be used later to improve the model."
481
+ instructions += "\n\n## Tips (optional):"
482
+ instructions += "\n* Trim the video to start and end of the event"
483
+ instructions += "\n* Frame the jumper fully, in the center of the frame"
484
+ instructions += "\n* Videos are automatically resized, so higher resolution will not help, but a closer framing of the jumper might help. Try cropping the video differently."
485
+ instructions += "\n\n\nUnfortunately due to inference costs, right now we have to deploy a slower, less accurate version of the model but it still works surprisingly well in most cases. If you run into any issues let us know. If you would like to contribute to the project, please reach out!"
486
+ gr.Markdown(instructions)
487
+
488
+ faq = "## FAQ:"
489
+ faq += "\n* **Q:** Does the model recognize misses?\n * **A:** Yes, but if it fails, you can try tuning the miss threshold slider to make it more sensitive."
490
+ faq += "\n* **Q:** Does the model recognize double dutch?\n * **A:** Yes, but it is trained on a smaller set of double dutch videos, so it may not work perfectly."
491
+ faq += "\n* **Q:** Does the model recognize double unders\n * **A:** Yes, but it is trained on a smaller set of double under videos, so it may not work perfectly. It is also trained to count the rope, not the jumps so you will need to divide the count by 2."
492
+ faq += "\n* **Q:** Does the model count both feet?\n * **A:** Yes, but for convention we usually return the halved (one foot) score."
493
+ gr.Markdown(faq)
494
+
495
+ gr.Examples(examples=[
496
+ [a, True, False, -1, True, 1.0, 0.95],
497
+ [b, False, True, -1, True, 1.0, 0.95],
498
+ [c, False, False, -1, True, 1.0, 0.95],
499
+ [d, False, False, -1, True, 1.0, 0.95]
500
+ ],
501
+ inputs=inputs,
502
+ outputs=[out_text, out_video, out_plot, out_hist],
503
+ fn=inference, cache_examples=os.getenv('SYSTEM') == 'spaces')
504
+ with gr.Accordion(label="Data usage and disclaimer", open=False):
505
+ data_usage = "## Data usage:"
506
+ data_usage += "\n* By default, no data submitted to this demo is stored by us."
507
+ data_usage += "\n* If you would like to contribute your video for further model improvements please provide the true count (either one or both feet) and specify if the video contains any misses."
508
+ data_usage += "\n* The video will be uploaded to a private dataset repository here on HuggingFace"
509
+ gr.Markdown(data_usage)
510
+
511
+ disclaimer = "## Disclaimer:"
512
+ disclaimer += "\n* This model was trained on a small dataset of videos (~20 hours). It is not guaranteed to work on all videos and should not be used yet in real competitive settings."
513
+ disclaimer += "\n* Deep learning models such as this one are susceptible to biases in the training data."
514
+ disclaimer += " We are aware of the potential for bias and expect quantifiable differences in performance on counting videos from different demographics not represented in the training data. We are working to improve the model and mitigate these biases. If you notice any issues, please let us know."
515
+ gr.Markdown(disclaimer)
516
+
517
+ run_button.click(inference, inputs, outputs=[out_text, out_video, out_plot, out_hist])
518
+ api_inference = partial(inference, api_call=True)
519
+ count_only.click(api_inference, inputs, outputs=[period_length, periodicity], api_name='inference')
520
+
521
+
522
+ if __name__ == "__main__":
523
+ demo.queue(api_open=True, max_size=15).launch(share=False)
packages.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ffmpeg
2
+ libsm6
3
+ libxext6
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ numpy
2
+ pandas
3
+ matplotlib
4
+ plotly
5
+ scipy
6
+ --find-links https://download.pytorch.org/whl/torch_stable.html
7
+ opencv-python-headless==4.7.0.68
8
+ openvino-dev==2022.3.0
9
+ torch==1.13.1+cpu
10
+ torchvision==0.14.1+cpu