userIdc2024 commited on
Commit
09e34ab
·
verified ·
1 Parent(s): 71e5bba

Update app_pages/video_analyzer.py

Browse files
Files changed (1) hide show
  1. app_pages/video_analyzer.py +125 -87
app_pages/video_analyzer.py CHANGED
@@ -10,104 +10,142 @@ from utils.dataframe import analysis_to_csv
10
  from database import insert_video_analysis, get_all_video_analyses
11
 
12
  def analyzer_page():
 
13
  selected_tab = st.sidebar.radio("Select Mode", ["Video Analyser", "History"], index=0)
14
 
15
  if selected_tab == "Video Analyser":
16
  st.subheader(" Video Analyser")
17
- uploaded_video = st.file_uploader("Upload Video",
18
- type=['mp4','mov','avi','mkv'],
19
- help="Upload a video for analysis")
 
 
20
  analyse_button = st.button("Run Analysis", use_container_width=True)
21
 
22
  if uploaded_video and analyse_button:
23
- print("Analysing")
24
- with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_video.name)[1]) as tmp:
 
25
  tmp.write(uploaded_video.read())
26
  video_path = tmp.name
 
27
  with st.spinner("Analyzing video..."):
28
- st.session_state["analysis"] = analyze_video_only(video_path)
29
- st.session_state["video_name"] = uploaded_video.name
30
- st.session_state["video_path"] = video_path
31
- st.session_state["thumbnail"] = get_video_thumbnail_base64(video_path)
32
-
33
- if "analysis" in st.session_state and st.session_state["analysis"]:
34
- render_analyzer_results(st.session_state["analysis"])
35
-
36
- col1, col2 = st.columns(2)
37
- with col1:
38
- analysis = st.session_state["analysis"]
39
- frames = []
40
- if "storyboard" in analysis:
41
- df_storyboard = pd.DataFrame(analysis["storyboard"])
42
- df_storyboard["section"] = "Storyboard"
43
- frames.append(df_storyboard)
44
- if "script" in analysis:
45
- df_script = pd.DataFrame(analysis["script"])
46
- df_script["section"] = "Script"
47
- frames.append(df_script)
48
- if "video_analysis" in analysis and "video_metrics" in analysis["video_analysis"]:
49
- df_metrics = pd.DataFrame(analysis["video_analysis"]["video_metrics"])
50
- df_metrics["section"] = "Metrics"
51
- frames.append(df_metrics)
52
- if "timestamp_improvements" in analysis:
53
- df_improvements = pd.DataFrame(analysis["timestamp_improvements"])
54
- df_improvements["section"] = "Improvements"
55
- frames.append(df_improvements)
56
-
57
- if frames:
58
- csv_content = pd.concat(frames, ignore_index=True).to_csv(index=False)
59
- st.download_button(
60
- "Download CSV",
61
- data=csv_content,
62
- file_name=f"{st.session_state.get('video_name','analysis')}.csv",
63
- mime="text/csv",
64
- use_container_width=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  )
66
- else:
67
- st.info("No tabular data available for CSV export.")
68
-
69
- with col2:
70
- if st.button("Save to DB", use_container_width=True):
71
- try:
72
- insert_video_analysis(
73
- video_name=st.session_state.get("video_name", "unknown"),
74
- response=st.session_state["analysis"],
75
- thumbnail=st.session_state.get("thumbnail", "")
76
- )
77
- st.success("Analysis saved to database ")
78
- except Exception as e:
79
- st.error(f"Failed to save analysis: {e}")
80
 
81
  else:
82
- history_items = get_all_video_analyses(limit=20)
83
- if history_items:
84
- video_titles = [
85
- f"{item['video_name']} ({item['created_at'].strftime('%Y-%m-%d %H:%M')})"
86
- for item in history_items
87
- ]
88
- selected = st.sidebar.radio("History Items", video_titles, index=0)
89
- idx = video_titles.index(selected)
90
- selected_data = history_items[idx]
91
-
92
- st.subheader(f"Analysis for: {selected_data['video_name']}")
93
- if selected_data.get("thumbnail"):
94
- st.image("data:image/jpeg;base64," + selected_data["thumbnail"], width=150)
95
-
96
- json_response = selected_data.get("response")
97
- if json_response:
98
- tabs = st.tabs(["Video Analysis"])
99
- with tabs[0]:
100
- render_analyzer_results(json_response)
101
- try:
102
- csv_data = analysis_to_csv(json_response)
103
- st.download_button(
104
- "Download CSV",
105
- data=csv_data,
106
- file_name=f"{selected_data['video_name']}_analysis.csv",
107
- mime="text/csv",
108
- use_container_width=True
109
- )
110
- except Exception as e:
111
- st.error(f"CSV export failed: {e}")
112
- else:
113
  st.info("No saved history available.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  from database import insert_video_analysis, get_all_video_analyses
11
 
12
  def analyzer_page():
13
+ st.sidebar.header("Analyzer")
14
  selected_tab = st.sidebar.radio("Select Mode", ["Video Analyser", "History"], index=0)
15
 
16
  if selected_tab == "Video Analyser":
17
  st.subheader(" Video Analyser")
18
+ uploaded_video = st.file_uploader(
19
+ "Upload Video",
20
+ type=['mp4', 'mov', 'avi', 'mkv'],
21
+ help="Upload a video for analysis"
22
+ )
23
  analyse_button = st.button("Run Analysis", use_container_width=True)
24
 
25
  if uploaded_video and analyse_button:
26
+ # Save to a temp file
27
+ suffix = os.path.splitext(uploaded_video.name)[1]
28
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
29
  tmp.write(uploaded_video.read())
30
  video_path = tmp.name
31
+
32
  with st.spinner("Analyzing video..."):
33
+ result = analyze_video_only(video_path)
34
+
35
+
36
+ st.session_state["video_name"] = uploaded_video.name
37
+ st.session_state["video_path"] = video_path
38
+ st.session_state["thumbnail"] = get_video_thumbnail_base64(video_path)
39
+ st.session_state["analysis"] = result
40
+
41
+ analysis = st.session_state.get("analysis")
42
+
43
+ if analysis is None:
44
+ return
45
+
46
+
47
+ if not analysis:
48
+ st.error("Analysis returned no data.")
49
+ return
50
+
51
+ if "__error__" in analysis:
52
+ st.error(f"Analysis failed: {analysis['__error__']}")
53
+ return
54
+
55
+
56
+ render_analyzer_results(analysis)
57
+
58
+ col1, col2 = st.columns(2)
59
+
60
+ # CSV export
61
+ with col1:
62
+ frames = []
63
+ if "storyboard" in analysis:
64
+ df_storyboard = pd.DataFrame(analysis["storyboard"])
65
+ df_storyboard["section"] = "Storyboard"
66
+ frames.append(df_storyboard)
67
+
68
+ if "script" in analysis:
69
+ df_script = pd.DataFrame(analysis["script"])
70
+ df_script["section"] = "Script"
71
+ frames.append(df_script)
72
+
73
+ if "video_analysis" in analysis and "video_metrics" in analysis["video_analysis"]:
74
+ df_metrics = pd.DataFrame(analysis["video_analysis"]["video_metrics"])
75
+ df_metrics["section"] = "Metrics"
76
+ frames.append(df_metrics)
77
+
78
+ if "timestamp_improvements" in analysis:
79
+ df_improvements = pd.DataFrame(analysis["timestamp_improvements"])
80
+ df_improvements["section"] = "Improvements"
81
+ frames.append(df_improvements)
82
+
83
+ if frames:
84
+ csv_content = pd.concat(frames, ignore_index=True).to_csv(index=False)
85
+ st.download_button(
86
+ "Download CSV",
87
+ data=csv_content,
88
+ file_name=f"{st.session_state.get('video_name', 'analysis')}.csv",
89
+ mime="text/csv",
90
+ use_container_width=True,
91
+ )
92
+ else:
93
+ st.info("No tabular data available for CSV export.")
94
+
95
+ # Save to DB
96
+ with col2:
97
+ if st.button("Save to DB", use_container_width=True):
98
+ try:
99
+ insert_video_analysis(
100
+ video_name=st.session_state.get("video_name", "unknown"),
101
+ response=analysis,
102
+ thumbnail=st.session_state.get("thumbnail", "")
103
  )
104
+ st.success("Analysis saved to database ")
105
+ except Exception as e:
106
+ st.error(f"Failed to save analysis: {e}")
 
 
 
 
 
 
 
 
 
 
 
107
 
108
  else:
109
+ # History tab
110
+ st.subheader(" History")
111
+ try:
112
+ history_items = get_all_video_analyses(limit=20)
113
+ except Exception as e:
114
+ st.error(f"Failed to load history: {e}")
115
+ return
116
+
117
+ if not history_items:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  st.info("No saved history available.")
119
+ return
120
+
121
+ video_titles = [
122
+ f"{item['video_name']} ({item['created_at'].strftime('%Y-%m-%d %H:%M')})"
123
+ for item in history_items
124
+ ]
125
+ selected = st.sidebar.radio("History Items", video_titles, index=0)
126
+ idx = video_titles.index(selected)
127
+ selected_data = history_items[idx]
128
+
129
+ st.subheader(f"Analysis for: {selected_data['video_name']}")
130
+ if selected_data.get("thumbnail"):
131
+ st.image("data:image/jpeg;base64," + selected_data["thumbnail"], width=150)
132
+
133
+ json_response = selected_data.get("response")
134
+ if not json_response:
135
+ st.info("No analysis payload found for this item.")
136
+ return
137
+
138
+ tabs = st.tabs(["Video Analysis"])
139
+ with tabs[0]:
140
+ render_analyzer_results(json_response)
141
+ try:
142
+ csv_data = analysis_to_csv(json_response)
143
+ st.download_button(
144
+ "Download CSV",
145
+ data=csv_data,
146
+ file_name=f"{selected_data['video_name']}_analysis.csv",
147
+ mime="text/csv",
148
+ use_container_width=True,
149
+ )
150
+ except Exception as e:
151
+ st.error(f"CSV export failed: {e}")