sunilsarolkar commited on
Commit
e66f1f4
·
verified ·
1 Parent(s): 9c9d73e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -135
app.py CHANGED
@@ -515,145 +515,145 @@ elif app_mode =='Run on Test Videos':
515
 
516
  prevTime = 0
517
  postfix = info["format"]["format_name"].split(",")[0]
518
-
519
- with tempfile.NamedTemporaryFile(suffix=f'.{postfix}',delete=False) as tfflie:
520
- output_file = tfflie.name#'./output.mp4'
521
- # width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))
522
- # height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
523
- fps_input = int(vid.get(cv2.CAP_PROP_FPS))
524
 
525
- #codec = cv2.VideoWriter_fourcc(*FLAGS.output_format)
526
-
527
- # codec = cv2.VideoWriter_fourcc('m','p','4','v')
528
- out = None
529
- writer=None
530
- weighted_avg_dict={}
531
-
532
- idx=0
533
-
534
- for _, row in current_test_df.iterrows():#enumerate(file_df.rolling(window=20, step=20,min_periods=1)):
535
- # print(f'captured frame#{idx}')
536
- if(vid.isOpened()):
537
- ret, frame = vid.read()
538
-
 
 
 
 
 
 
 
 
 
 
 
 
539
 
540
- if len(window)<window_size:
541
- canvas=util.drawStickmodel(frame,eval(row['bodypose_circles']),eval(row['bodypose_sticks']),eval(row['handpose_edges']),eval(row['handpose_peaks']))
542
- canvas_with_plot=util.draw_bar_plot_below_image(canvas,{}, f'Prediction bar plot - Frame number {idx+1} [** no predictions]',canvas)
543
- canvas_with_plot=util.draw_bar_plot_below_image(canvas_with_plot,weighted_avg_dict, f'Weighted avg - Frame number {idx+1} [** no predictions]',canvas)
544
- canvas_with_plot=util.add_padding_to_bottom(canvas_with_plot,(255,255,255),100)# Adds padding at bottom
545
-
546
- if writer is None:
547
- input_framesize = canvas_with_plot.shape[:2]
548
- writer = Writer(output_file, input_fps, input_framesize, input_pix_fmt,
549
- input_vcodec)
550
-
551
- # if out is None:
552
- # out=cv2.VideoWriter(output_file, codec, fps_input, frame.shape[:2])
553
-
554
-
555
- writer(canvas_with_plot)
556
- # out.write(canvas)
557
- with runtime_progress.container():
558
- df1 = pd.DataFrame([[f'{idx+1}/{current_test_df.shape[0]}','<model will output after 20 frames>']], columns=['Frames Processed','Detected Class'])
559
-
560
- my_table = st.table(df1)
561
- window.append(frame)
562
- # kpi1_text.write(f"<h1 style='text-align: center; color: red;'>{idx+1}/{current_test_df.shape[0]}</h1>", unsafe_allow_html=True)
563
- # kpi2_text.write(f"<h1 style='text-align: center; color: red;'>--</h1>", unsafe_allow_html=True)
564
- with view.container():
565
- st.image(canvas_with_plot,channels = 'BGR',use_column_width=True)
566
- else:
567
-
568
- window[:-1] = window[1:]
569
- window[-1]=frame
570
- translation_model=get_translator_model()
571
- # testing_df[]
572
-
573
- encoded_translation = translation_model(X_test_filtered[idx-20].reshape(1,X_test_filtered[idx-20].shape[0],X_test_filtered[idx-20].shape[1]))
574
- encoded_translation=encoded_translation[0].cpu().detach().numpy()
575
- sorted_index=np.argsort(encoded_translation)[::-1]
576
- maxindex=np.argmax(encoded_translation)
577
-
578
- top_3_probs = encoded_translation.argsort()[-3:][::-1] # Get indices of top 3 probabilities (descending order)
579
- top_3_categories = [expression_mapping[i] for i in top_3_probs] # Convert indices to category names (assuming class_names list exists)
580
- top_3_values = encoded_translation[top_3_probs] # Get corresponding probabilities
581
- # print(f'{idx} {encoded_translation[maxindex]:0.4f} {maxindex}-{expression_mapping[maxindex]} ')#{[(pi,encoded_translation[pi],expression_mapping[pi]) for pi in sorted_index]}
582
- for category, prob in zip(top_3_categories, top_3_values):
583
- if category not in frame_wise_outputs:
584
- frame_wise_outputs[category]=[]
585
- frame_wise_outputs[category].append(prob)
586
- current_prob={}
587
-
588
- for category, prob in zip(top_3_categories, top_3_values):
589
- current_prob[category]=prob
590
-
591
- for key in frame_wise_outputs:
592
- weighted_avg_dict[key]=weighted_average(frame_wise_outputs[key],[len(frame_wise_outputs[key]) for i in range(len(frame_wise_outputs[key]))])
593
-
594
- sorted_dict = dict(sorted(weighted_avg_dict.items(), key=lambda item: item[1], reverse=True))
595
- canvas=util.drawStickmodel(frame,eval(row['bodypose_circles']),eval(row['bodypose_sticks']),eval(row['handpose_edges']),eval(row['handpose_peaks']))
596
- canvas_with_plot=util.draw_bar_plot_below_image(canvas,current_prob, f'Prediction at frame window({idx-20+1}-{idx+1})',canvas)
597
- canvas_with_plot=util.draw_bar_plot_below_image(canvas_with_plot,weighted_avg_dict, f'Weighted avg till window {idx+1}',canvas)
598
- canvas_with_plot=util.add_padding_to_bottom(canvas_with_plot,(255,255,255),100)
599
- writer(canvas_with_plot)
600
-
601
-
602
- currTime = time.time()
603
- fps = 1 / (currTime - prevTime)
604
- prevTime = currTime
605
- # out.write(frame)
606
- # if record:
607
- # #st.checkbox("Recording", value=True)
608
- # out.write(frame)
609
- #Dashboard
610
-
611
- max_prob = float('-inf') # Initialize with negative infinity
612
- max_key = None
613
-
614
- for exp, prob in weighted_avg_dict.items():
615
- if prob > max_prob:
616
- max_prob = prob
617
- max_key = exp
618
- with runtime_progress.container():
619
- df1 = pd.DataFrame([[f'{idx+1}/{current_test_df.shape[0]}',f'{max_key} ({max_prob*100:.2f}%)']], columns=['Frames Processed','Detected Class'])
620
- my_table = st.table(df1)
621
- # kpi1_text.write(f"<h1 style='text-align: center; color: red;'>{idx+1}/{current_test_df.shape[0]}</h1>", unsafe_allow_html=True)
622
- # kpi2_text.write(f"<h1 style='text-align: center; color: red;'>{max_key} ({max_prob*100:.2f}%)</h1>", unsafe_allow_html=True)
623
- # with placeholder.container():
624
- # # st.write(weighted_avg_dict)
625
- # # data = {
626
- # # "I": 0.7350964583456516,
627
- # # "Hello": 0.1078806109726429,
628
- # # "you": 0.11776176246348768,
629
- # # "you (plural)": 0.12685142129916568
630
- # # }
631
-
632
- # # Convert the dictionary to a Pandas DataFrame for easier plotting
633
- # df = pd.DataFrame.from_dict(weighted_avg_dict, orient='index', columns=['Values'])
634
-
635
- # # Create a bar chart with Streamlit
636
- # st.bar_chart(df)
637
- # frame = cv2.resize(frame,(0,0),fx = 0.8 , fy = 0.8)
638
- # frame = image_resize(image = frame, width = 640)
639
- with view.container():
640
- st.image(canvas_with_plot,channels = 'BGR',use_column_width=True)
641
-
642
- idx=idx+1
643
 
644
 
645
- # st.text('Video Processed')
646
- with view.container():
647
- if writer is not None: # ✅ safeguard
648
- writer.close()
649
- output_video = open(output_file,'rb')
650
- out_bytes = output_video.read()
651
- st.video(out_bytes)
652
- print(f'Output file - {output_file}')
 
 
 
653
  else:
654
- st.warning("No video was processed, writer is empty.")
655
- # out.release()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
656
 
 
 
 
 
 
 
 
 
657
  print(f'Output file - {output_file}')
658
- cv2.destroyAllWindows()
659
- vid.release()
 
 
 
 
 
 
515
 
516
  prevTime = 0
517
  postfix = info["format"]["format_name"].split(",")[0]
 
 
 
 
 
 
518
 
519
+
520
+ output_file = f"/tmp/output_{uuid.uuid4().hex}.{postfix}"
521
+
522
+ # height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
523
+ fps_input = int(vid.get(cv2.CAP_PROP_FPS))
524
+
525
+ #codec = cv2.VideoWriter_fourcc(*FLAGS.output_format)
526
+
527
+ # codec = cv2.VideoWriter_fourcc('m','p','4','v')
528
+ out = None
529
+ writer=None
530
+ weighted_avg_dict={}
531
+
532
+ idx=0
533
+
534
+ for _, row in current_test_df.iterrows():#enumerate(file_df.rolling(window=20, step=20,min_periods=1)):
535
+ # print(f'captured frame#{idx}')
536
+ if(vid.isOpened()):
537
+ ret, frame = vid.read()
538
+
539
+
540
+ if len(window)<window_size:
541
+ canvas=util.drawStickmodel(frame,eval(row['bodypose_circles']),eval(row['bodypose_sticks']),eval(row['handpose_edges']),eval(row['handpose_peaks']))
542
+ canvas_with_plot=util.draw_bar_plot_below_image(canvas,{}, f'Prediction bar plot - Frame number {idx+1} [** no predictions]',canvas)
543
+ canvas_with_plot=util.draw_bar_plot_below_image(canvas_with_plot,weighted_avg_dict, f'Weighted avg - Frame number {idx+1} [** no predictions]',canvas)
544
+ canvas_with_plot=util.add_padding_to_bottom(canvas_with_plot,(255,255,255),100)# Adds padding at bottom
545
 
546
+ if writer is None:
547
+ input_framesize = canvas_with_plot.shape[:2]
548
+ writer = Writer(output_file, input_fps, input_framesize, input_pix_fmt,
549
+ input_vcodec)
550
+
551
+ # if out is None:
552
+ # out=cv2.VideoWriter(output_file, codec, fps_input, frame.shape[:2])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
553
 
554
 
555
+ writer(canvas_with_plot)
556
+ # out.write(canvas)
557
+ with runtime_progress.container():
558
+ df1 = pd.DataFrame([[f'{idx+1}/{current_test_df.shape[0]}','<model will output after 20 frames>']], columns=['Frames Processed','Detected Class'])
559
+
560
+ my_table = st.table(df1)
561
+ window.append(frame)
562
+ # kpi1_text.write(f"<h1 style='text-align: center; color: red;'>{idx+1}/{current_test_df.shape[0]}</h1>", unsafe_allow_html=True)
563
+ # kpi2_text.write(f"<h1 style='text-align: center; color: red;'>--</h1>", unsafe_allow_html=True)
564
+ with view.container():
565
+ st.image(canvas_with_plot,channels = 'BGR',use_column_width=True)
566
  else:
567
+
568
+ window[:-1] = window[1:]
569
+ window[-1]=frame
570
+ translation_model=get_translator_model()
571
+ # testing_df[]
572
+
573
+ encoded_translation = translation_model(X_test_filtered[idx-20].reshape(1,X_test_filtered[idx-20].shape[0],X_test_filtered[idx-20].shape[1]))
574
+ encoded_translation=encoded_translation[0].cpu().detach().numpy()
575
+ sorted_index=np.argsort(encoded_translation)[::-1]
576
+ maxindex=np.argmax(encoded_translation)
577
+
578
+ top_3_probs = encoded_translation.argsort()[-3:][::-1] # Get indices of top 3 probabilities (descending order)
579
+ top_3_categories = [expression_mapping[i] for i in top_3_probs] # Convert indices to category names (assuming class_names list exists)
580
+ top_3_values = encoded_translation[top_3_probs] # Get corresponding probabilities
581
+ # print(f'{idx} {encoded_translation[maxindex]:0.4f} {maxindex}-{expression_mapping[maxindex]} ')#{[(pi,encoded_translation[pi],expression_mapping[pi]) for pi in sorted_index]}
582
+ for category, prob in zip(top_3_categories, top_3_values):
583
+ if category not in frame_wise_outputs:
584
+ frame_wise_outputs[category]=[]
585
+ frame_wise_outputs[category].append(prob)
586
+ current_prob={}
587
+
588
+ for category, prob in zip(top_3_categories, top_3_values):
589
+ current_prob[category]=prob
590
+
591
+ for key in frame_wise_outputs:
592
+ weighted_avg_dict[key]=weighted_average(frame_wise_outputs[key],[len(frame_wise_outputs[key]) for i in range(len(frame_wise_outputs[key]))])
593
+
594
+ sorted_dict = dict(sorted(weighted_avg_dict.items(), key=lambda item: item[1], reverse=True))
595
+ canvas=util.drawStickmodel(frame,eval(row['bodypose_circles']),eval(row['bodypose_sticks']),eval(row['handpose_edges']),eval(row['handpose_peaks']))
596
+ canvas_with_plot=util.draw_bar_plot_below_image(canvas,current_prob, f'Prediction at frame window({idx-20+1}-{idx+1})',canvas)
597
+ canvas_with_plot=util.draw_bar_plot_below_image(canvas_with_plot,weighted_avg_dict, f'Weighted avg till window {idx+1}',canvas)
598
+ canvas_with_plot=util.add_padding_to_bottom(canvas_with_plot,(255,255,255),100)
599
+ writer(canvas_with_plot)
600
+
601
+
602
+ currTime = time.time()
603
+ fps = 1 / (currTime - prevTime)
604
+ prevTime = currTime
605
+ # out.write(frame)
606
+ # if record:
607
+ # #st.checkbox("Recording", value=True)
608
+ # out.write(frame)
609
+ #Dashboard
610
+
611
+ max_prob = float('-inf') # Initialize with negative infinity
612
+ max_key = None
613
+
614
+ for exp, prob in weighted_avg_dict.items():
615
+ if prob > max_prob:
616
+ max_prob = prob
617
+ max_key = exp
618
+ with runtime_progress.container():
619
+ df1 = pd.DataFrame([[f'{idx+1}/{current_test_df.shape[0]}',f'{max_key} ({max_prob*100:.2f}%)']], columns=['Frames Processed','Detected Class'])
620
+ my_table = st.table(df1)
621
+ # kpi1_text.write(f"<h1 style='text-align: center; color: red;'>{idx+1}/{current_test_df.shape[0]}</h1>", unsafe_allow_html=True)
622
+ # kpi2_text.write(f"<h1 style='text-align: center; color: red;'>{max_key} ({max_prob*100:.2f}%)</h1>", unsafe_allow_html=True)
623
+ # with placeholder.container():
624
+ # # st.write(weighted_avg_dict)
625
+ # # data = {
626
+ # # "I": 0.7350964583456516,
627
+ # # "Hello": 0.1078806109726429,
628
+ # # "you": 0.11776176246348768,
629
+ # # "you (plural)": 0.12685142129916568
630
+ # # }
631
+
632
+ # # Convert the dictionary to a Pandas DataFrame for easier plotting
633
+ # df = pd.DataFrame.from_dict(weighted_avg_dict, orient='index', columns=['Values'])
634
+
635
+ # # Create a bar chart with Streamlit
636
+ # st.bar_chart(df)
637
+ # frame = cv2.resize(frame,(0,0),fx = 0.8 , fy = 0.8)
638
+ # frame = image_resize(image = frame, width = 640)
639
+ with view.container():
640
+ st.image(canvas_with_plot,channels = 'BGR',use_column_width=True)
641
+
642
+ idx=idx+1
643
 
644
+
645
+ # st.text('Video Processed')
646
+ with view.container():
647
+ if writer is not None: # ✅ safeguard
648
+ writer.close()
649
+ output_video = open(output_file,'rb')
650
+ out_bytes = output_video.read()
651
+ st.video(out_bytes)
652
  print(f'Output file - {output_file}')
653
+ else:
654
+ st.warning("No video was processed, writer is empty.")
655
+ # out.release()
656
+
657
+ print(f'Output file - {output_file}')
658
+ cv2.destroyAllWindows()
659
+ vid.release()