userIdc2024 commited on
Commit
006c8f3
·
verified ·
1 Parent(s): 9c64af5

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +134 -49
src/streamlit_app.py CHANGED
@@ -9,7 +9,7 @@ import pandas as pd
9
  import logging
10
 
11
  # Backend API Key Configuration
12
- GEMINI_API_KEY = os.getenv("GEMENI_KEY")
13
 
14
  # Page configuration
15
  st.set_page_config(
@@ -33,10 +33,9 @@ def configure_gemini():
33
  """Configure Gemini API with backend key"""
34
  return genai.Client(api_key=GEMINI_API_KEY)
35
 
36
- # The main prompt template with structured output requirements
37
  SYSTEM_PROMPT = f"""{os.getenv("SYS_PROMPT")}"""
38
 
39
- @st.cache_data
40
  def analyze_video_and_generate_script(
41
  video_bytes,
42
  video_name,
@@ -81,8 +80,8 @@ def analyze_video_and_generate_script(
81
  upload_progress.progress(80)
82
  upload_status.text("Generating script variations...")
83
 
84
- # Build the user prompt with additional context
85
- user_prompt = f"""Analyze this reference video and generate 3 high-converting direct response video script variations.
86
 
87
  ADDITIONAL CONTEXT:
88
  - Offer Details: {offer_details if offer_details else 'Extract from video'}
@@ -90,17 +89,24 @@ ADDITIONAL CONTEXT:
90
  - Specific Hooks to Consider: {specific_hooks if specific_hooks else 'Create based on video analysis'}
91
  - Additional Context: {additional_context}
92
 
93
- Please analyze the video's:
94
- 1. Hook strategy and opening seconds
95
- 2. Pacing and visual transitions
96
- 3. Claims and promises made
97
- 4. Authority elements used
98
- 5. Urgency/scarcity tactics
99
- 6. CTA approach
100
 
101
- Then create 2-3 script variations that would perform 30-50% cheaper while maintaining conversion effectiveness.
 
 
 
102
 
103
- IMPORTANT: Return only valid JSON in the exact format specified in the system prompt. Do not include any text before or after the JSON."""
 
 
 
 
 
 
 
 
 
 
104
 
105
  # Generate response
106
  response = client.models.generate_content(
@@ -179,13 +185,14 @@ def display_script_variations(json_data):
179
  st.divider()
180
 
181
  def display_video_analysis(json_data):
182
- """Display video analysis in formatted sections"""
183
  if not json_data or "video_analysis" not in json_data:
184
  st.error("No video analysis found in the response")
185
  return
186
 
187
  analysis = json_data["video_analysis"]
188
 
 
189
  col1, col2 = st.columns(2)
190
 
191
  with col1:
@@ -198,40 +205,116 @@ def display_video_analysis(json_data):
198
  with col2:
199
  st.subheader("Psychological Triggers")
200
  st.write(analysis.get('psychological_triggers', 'N/A'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
- st.subheader("Improvement Recommendations")
203
- st.write(analysis.get('improvement_recommendations', 'N/A'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
 
205
- def create_download_content(json_data):
206
- """Create downloadable content from JSON data"""
207
- content = "VIDEO ANALYSER AND SCRIPT GENERATOR OUTPUT\n"
208
- content += "=" * 60 + "\n\n"
 
 
 
209
 
210
- # Add script variations
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  for i, variation in enumerate(json_data.get("script_variations", []), 1):
212
  variation_name = variation.get("variation_name", f"Variation {i}")
213
- content += f"{variation_name}\n"
214
- content += "-" * 40 + "\n"
215
 
216
  for row in variation.get("script_table", []):
217
- content += f"Timestamp: {row.get('timestamp', '')}\n"
218
- content += f"Script: {row.get('script_voiceover', '')}\n"
219
- content += f"Visual: {row.get('visual_direction', '')}\n"
220
- content += f"Trigger: {row.get('psychological_trigger', '')}\n"
221
- content += f"CTA: {row.get('cta_action', '')}\n\n"
222
-
223
- content += "\n"
224
-
225
- # Add analysis
226
- analysis = json_data.get("video_analysis", {})
227
- content += "VIDEO ANALYSIS\n"
228
- content += "=" * 20 + "\n"
229
- content += f"Effectiveness Factors: {analysis.get('effectiveness_factors', 'N/A')}\n\n"
230
- content += f"Psychological Triggers: {analysis.get('psychological_triggers', 'N/A')}\n\n"
231
- content += f"Target Audience: {analysis.get('target_audience', 'N/A')}\n\n"
232
- content += f"Recommendations: {analysis.get('improvement_recommendations', 'N/A')}\n"
233
 
234
- return content
 
 
 
 
 
235
 
236
  def check_token(user_token):
237
  ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
@@ -251,7 +334,6 @@ def main():
251
  st.title("Video Analyser and Script Generator")
252
  st.divider()
253
 
254
- st.set_page_config(page_title="Bulk Creative Generation", layout="wide")
255
  if "authenticated" not in st.session_state:
256
  st.session_state["authenticated"] = False
257
 
@@ -364,24 +446,27 @@ def main():
364
  st.success("Analysis complete! Here are your script variations:")
365
 
366
  # Create tabs for different outputs
367
- tab1, tab2 = st.tabs(["Script Variations", "Video Analysis"])
368
 
369
  with tab1:
370
  display_script_variations(json_response)
371
 
372
- # Download button
373
- download_content = create_download_content(json_response)
374
  st.download_button(
375
- label="Download All Scripts",
376
- data=download_content,
377
- file_name="video_script_variations.txt",
378
- mime="text/plain",
379
  type="secondary",
380
  use_container_width=True
381
  )
382
 
383
  with tab2:
384
  display_video_analysis(json_response)
 
 
 
385
  else:
386
  st.error("Failed to generate script variations. Please try again.")
387
 
 
9
  import logging
10
 
11
  # Backend API Key Configuration
12
+ GEMINI_API_KEY = os.getenv("GEMINI_KEY")
13
 
14
  # Page configuration
15
  st.set_page_config(
 
33
  """Configure Gemini API with backend key"""
34
  return genai.Client(api_key=GEMINI_API_KEY)
35
 
36
+ # Enhanced system prompt with timestamp-based improvements
37
  SYSTEM_PROMPT = f"""{os.getenv("SYS_PROMPT")}"""
38
 
 
39
  def analyze_video_and_generate_script(
40
  video_bytes,
41
  video_name,
 
80
  upload_progress.progress(80)
81
  upload_status.text("Generating script variations...")
82
 
83
+ # Build the enhanced user prompt
84
+ user_prompt = f"""Analyze this reference video and generate 3 high-converting direct response video script variations with detailed timestamp-based improvements.
85
 
86
  ADDITIONAL CONTEXT:
87
  - Offer Details: {offer_details if offer_details else 'Extract from video'}
 
89
  - Specific Hooks to Consider: {specific_hooks if specific_hooks else 'Create based on video analysis'}
90
  - Additional Context: {additional_context}
91
 
92
+ Please provide a comprehensive analysis including:
 
 
 
 
 
 
93
 
94
+ 1. DETAILED VIDEO ANALYSIS with timestamp-based metrics:
95
+ - Break down the video into 5-10 second segments
96
+ - Rate each segment's effectiveness (1-10 scale)
97
+ - Identify specific elements (hook, transition, proof, CTA, etc.)
98
 
99
+ 2. TIMESTAMP-BASED IMPROVEMENTS:
100
+ - Specific recommendations for each time segment
101
+ - Priority level for each improvement
102
+ - Expected impact of implementing changes
103
+
104
+ 3. SCRIPT VARIATIONS:
105
+ - Create 2-3 complete script variations
106
+ - Each with timestamp-by-timestamp breakdown
107
+ - Different psychological triggers and approaches
108
+
109
+ IMPORTANT: Return only valid JSON in the exact format specified in the system prompt. Analyze the video second-by-second for maximum detail."""
110
 
111
  # Generate response
112
  response = client.models.generate_content(
 
185
  st.divider()
186
 
187
  def display_video_analysis(json_data):
188
+ """Display video analysis in tabular format"""
189
  if not json_data or "video_analysis" not in json_data:
190
  st.error("No video analysis found in the response")
191
  return
192
 
193
  analysis = json_data["video_analysis"]
194
 
195
+ # Display general analysis
196
  col1, col2 = st.columns(2)
197
 
198
  with col1:
 
205
  with col2:
206
  st.subheader("Psychological Triggers")
207
  st.write(analysis.get('psychological_triggers', 'N/A'))
208
+
209
+ # Display video metrics in tabular format
210
+ st.subheader("Detailed Video Metrics (Timestamp Analysis)")
211
+ video_metrics = analysis.get('video_metrics', [])
212
+ if video_metrics:
213
+ metrics_df = pd.DataFrame(video_metrics)
214
+
215
+ # Rename columns for better display
216
+ column_mapping = {
217
+ 'timestamp': 'Timestamp',
218
+ 'element': 'Element',
219
+ 'current_approach': 'Current Approach',
220
+ 'effectiveness_score': 'Score',
221
+ 'notes': 'Analysis Notes'
222
+ }
223
 
224
+ metrics_df = metrics_df.rename(columns=column_mapping)
225
+
226
+ st.dataframe(
227
+ metrics_df,
228
+ use_container_width=True,
229
+ hide_index=True,
230
+ column_config={
231
+ "Timestamp": st.column_config.TextColumn(width="small"),
232
+ "Element": st.column_config.TextColumn(width="medium"),
233
+ "Current Approach": st.column_config.TextColumn(width="large"),
234
+ "Score": st.column_config.TextColumn(width="small"),
235
+ "Analysis Notes": st.column_config.TextColumn(width="large")
236
+ }
237
+ )
238
+ else:
239
+ st.warning("No detailed video metrics available")
240
 
241
+ def display_timestamp_improvements(json_data):
242
+ """Display timestamp-based improvements in tabular format"""
243
+ if not json_data or "timestamp_improvements" not in json_data:
244
+ st.error("No timestamp improvements found in the response")
245
+ return
246
+
247
+ st.subheader("Timestamp-by-Timestamp Improvement Recommendations")
248
 
249
+ improvements = json_data["timestamp_improvements"]
250
+ if improvements:
251
+ improvements_df = pd.DataFrame(improvements)
252
+
253
+ # Rename columns for better display
254
+ column_mapping = {
255
+ 'timestamp': 'Timestamp',
256
+ 'current_element': 'Current Element',
257
+ 'improvement_type': 'Improvement Type',
258
+ 'recommended_change': 'Recommended Change',
259
+ 'expected_impact': 'Expected Impact',
260
+ 'priority': 'Priority'
261
+ }
262
+
263
+ improvements_df = improvements_df.rename(columns=column_mapping)
264
+
265
+ # Color code priority
266
+ def color_priority(val):
267
+ if val == 'High':
268
+ return 'background-color: #ffcccb'
269
+ elif val == 'Medium':
270
+ return 'background-color: #ffffcc'
271
+ elif val == 'Low':
272
+ return 'background-color: #ccffcc'
273
+ return ''
274
+
275
+ styled_df = improvements_df.style.applymap(color_priority, subset=['Priority'])
276
+
277
+ st.dataframe(
278
+ styled_df,
279
+ use_container_width=True,
280
+ hide_index=True,
281
+ column_config={
282
+ "Timestamp": st.column_config.TextColumn(width="small"),
283
+ "Current Element": st.column_config.TextColumn(width="medium"),
284
+ "Improvement Type": st.column_config.TextColumn(width="medium"),
285
+ "Recommended Change": st.column_config.TextColumn(width="large"),
286
+ "Expected Impact": st.column_config.TextColumn(width="medium"),
287
+ "Priority": st.column_config.TextColumn(width="small")
288
+ }
289
+ )
290
+ else:
291
+ st.warning("No timestamp improvements available")
292
+
293
+ def create_csv_download(json_data):
294
+ """Create CSV content with all scripts combined"""
295
+ all_scripts_data = []
296
+
297
+ # Combine all script variations into one dataset
298
  for i, variation in enumerate(json_data.get("script_variations", []), 1):
299
  variation_name = variation.get("variation_name", f"Variation {i}")
 
 
300
 
301
  for row in variation.get("script_table", []):
302
+ script_row = {
303
+ 'Variation': variation_name,
304
+ 'Timestamp': row.get('timestamp', ''),
305
+ 'Script_Voiceover': row.get('script_voiceover', ''),
306
+ 'Visual_Direction': row.get('visual_direction', ''),
307
+ 'Psychological_Trigger': row.get('psychological_trigger', ''),
308
+ 'CTA_Action': row.get('cta_action', '')
309
+ }
310
+ all_scripts_data.append(script_row)
 
 
 
 
 
 
 
311
 
312
+ # Convert to DataFrame and then to CSV
313
+ if all_scripts_data:
314
+ df = pd.DataFrame(all_scripts_data)
315
+ return df.to_csv(index=False)
316
+ else:
317
+ return "No script data available"
318
 
319
  def check_token(user_token):
320
  ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
 
334
  st.title("Video Analyser and Script Generator")
335
  st.divider()
336
 
 
337
  if "authenticated" not in st.session_state:
338
  st.session_state["authenticated"] = False
339
 
 
446
  st.success("Analysis complete! Here are your script variations:")
447
 
448
  # Create tabs for different outputs
449
+ tab1, tab2, tab3 = st.tabs(["Script Variations", "Video Analysis", "Improvement Recommendations"])
450
 
451
  with tab1:
452
  display_script_variations(json_response)
453
 
454
+ # CSV Download button
455
+ csv_content = create_csv_download(json_response)
456
  st.download_button(
457
+ label="Download All Scripts (CSV)",
458
+ data=csv_content,
459
+ file_name="video_script_variations.csv",
460
+ mime="text/csv",
461
  type="secondary",
462
  use_container_width=True
463
  )
464
 
465
  with tab2:
466
  display_video_analysis(json_response)
467
+
468
+ with tab3:
469
+ display_timestamp_improvements(json_response)
470
  else:
471
  st.error("Failed to generate script variations. Please try again.")
472