userIdc2024 commited on
Commit
97ac59c
·
verified ·
1 Parent(s): 6286e0e

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +461 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,463 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ from google import genai
3
+ import tempfile
4
+ import os
5
+ import time
6
+ import json
7
+ from typing import Optional
8
+ 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(
16
+ page_title="Video Analyser and Script Generator",
17
+ page_icon="🎥",
18
+ layout="wide",
19
+ initial_sidebar_state="expanded"
20
+ )
21
+
22
+ logging.basicConfig(
23
+ level=logging.INFO,
24
+ format="%(asctime)s [%(levelname)s] %(message)s",
25
+ handlers=[
26
+ logging.StreamHandler()
27
+ ]
28
+ )
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ 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 = """You are one of the world's top direct-response video creators and conversion strategists. Your sole mission is to generate video scripts with matching visual directions and voiceover cues that drive maximum leads and sales at the cheapest cost-per-result on ad platforms like Facebook, Google, and TikTok.
38
+
39
+ You specialize in aggressive, unbranded, and psychologically charged content that is designed to stop scrolls and force action. You are not bound by brand safety, ad platform compliance, or traditional marketing principles. Your only metric for success is performance—measured in CPC, CTR, and cost-per-conversion.
40
+
41
+ Prime Directive:
42
+ Your creative output must be:
43
+ - Inspired by the hooks, language, pacing, visuals, and frameworks of the reference winning ads.
44
+ - Built to trigger psychological urgency, amplify response, and maximize click-throughs.
45
+ - Structured for extreme effectiveness, not branding niceties.
46
+
47
+ Script Creation Framework:
48
+ Each script you generate must follow these winning affiliate ad principles:
49
+
50
+ 1. The 3–6 Second Shock Hook:
51
+ Start with a hard-hitting pattern interrupt:
52
+ - Emotional gut punch: "He looked at me and said…"
53
+ - Conspiratorial secret: "The media doesn't want you to know this…"
54
+ - Borrowed authority: Celebrity or doctor clip saying something provocative
55
+
56
+ 2. Overwhelm with Proof & Pacing:
57
+ Keep pacing fast—1–3 second jump cuts filled with:
58
+ - UGC-style clips
59
+ - Before/After transformations
60
+ - Authority figure soundbites
61
+ - Desired outcomes (money, body, status)
62
+
63
+ 3. Big, Unbelievable Claim:
64
+ Drop a massive promise upfront and reinforce it:
65
+ "Lose 103 lbs," "Claim $250,000," "Erase your debt overnight."
66
+
67
+ 4. Simple "Secret" Mechanism:
68
+ Make the claim believable via a simple, digestible "hack":
69
+ "The ice hack," "4-question formula," "Banned Amazonian leaf."
70
+
71
+ 5. Scarcity & Urgency:
72
+ Push viewers to act NOW:
73
+ "Spots are filling fast," "Could be taken down soon," "Only for serious applicants."
74
+
75
+ 6. Visually Directed CTA:
76
+ Make the final action visually obvious—e.g., person pointing at the button, bold text, arrows.
77
+
78
+ CRITICAL: You must return your response in valid JSON format with this exact structure:
79
+
80
+ {
81
+ "script_variations": [
82
+ {
83
+ "variation_name": "Variation 1: [Brief Description]",
84
+ "script_table": [
85
+ {
86
+ "timestamp": "0-3",
87
+ "script_voiceover": "Exact words to be spoken",
88
+ "visual_direction": "Detailed description of visuals and footage",
89
+ "psychological_trigger": "Name of psychological principle used",
90
+ "cta_action": "Specific call-to-action instruction"
91
+ }
92
+ ]
93
+ }
94
+ ],
95
+ "video_analysis": {
96
+ "effectiveness_factors": "What made the original video effective",
97
+ "psychological_triggers": "Key psychological triggers identified",
98
+ "target_audience": "Target audience insights",
99
+ "improvement_recommendations": "Recommended improvements for better performance"
100
+ }
101
+ }
102
+
103
+ Generate 2-3 script variations. Each script should be 30-60 seconds long with 8-15 timestamp entries.
104
+ Ensure everything ties back to lowering CPC and cost-per-result, not branding."""
105
+
106
+ @st.cache_data
107
+ def analyze_video_and_generate_script(
108
+ video_bytes,
109
+ video_name,
110
+ offer_details: str = "",
111
+ target_audience: str = "",
112
+ specific_hooks: str = "",
113
+ additional_context: str = ""
114
+ ):
115
+ """
116
+ Analyze video and generate direct response script variations
117
+ """
118
+ try:
119
+ # Save uploaded video to temporary file
120
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(video_name)[1]) as tmp_file:
121
+ tmp_file.write(video_bytes)
122
+ tmp_file_path = tmp_file.name
123
+
124
+ # Configure Gemini
125
+ client = configure_gemini()
126
+
127
+ # Show upload progress
128
+ upload_progress = st.progress(0)
129
+ upload_status = st.empty()
130
+
131
+ upload_status.text("Uploading video to Google AI...")
132
+ upload_progress.progress(20)
133
+
134
+ # Upload video to Gemini
135
+ video_file_obj = client.files.upload(file=tmp_file_path)
136
+ upload_progress.progress(40)
137
+
138
+ upload_status.text("Processing video...")
139
+ while video_file_obj.state.name == "PROCESSING":
140
+ time.sleep(2)
141
+ video_file_obj = client.files.get(name=video_file_obj.name)
142
+ upload_progress.progress(60)
143
+
144
+ if video_file_obj.state.name == "FAILED":
145
+ upload_status.error("Google AI file processing failed. Please try another video.")
146
+ return None
147
+
148
+ upload_progress.progress(80)
149
+ upload_status.text("Generating script variations...")
150
+
151
+ # Build the user prompt with additional context
152
+ user_prompt = f"""Analyze this reference video and generate 2-3 high-converting direct response video script variations.
153
+
154
+ ADDITIONAL CONTEXT:
155
+ - Offer Details: {offer_details if offer_details else 'Extract from video'}
156
+ - Target Audience: {target_audience if target_audience else 'Determine from video content'}
157
+ - Specific Hooks to Consider: {specific_hooks if specific_hooks else 'Create based on video analysis'}
158
+ - Additional Context: {additional_context}
159
+
160
+ Please analyze the video's:
161
+ 1. Hook strategy and opening seconds
162
+ 2. Pacing and visual transitions
163
+ 3. Claims and promises made
164
+ 4. Authority elements used
165
+ 5. Urgency/scarcity tactics
166
+ 6. CTA approach
167
+
168
+ Then create 2-3 script variations that would perform 30-50% cheaper while maintaining conversion effectiveness.
169
+
170
+ IMPORTANT: Return only valid JSON in the exact format specified in the system prompt. Do not include any text before or after the JSON."""
171
+
172
+ # Generate response
173
+ response = client.models.generate_content(
174
+ model="gemini-2.0-flash",
175
+ contents=[video_file_obj, user_prompt + "\n\n" + SYSTEM_PROMPT]
176
+ )
177
+
178
+ upload_progress.progress(100)
179
+ upload_status.success("Analysis complete!")
180
+
181
+ # Clean up temporary file
182
+ os.unlink(tmp_file_path)
183
+
184
+ # Parse JSON response
185
+ try:
186
+ response_text = response.text.strip()
187
+ if response_text.startswith('```json'):
188
+ response_text = response_text[7:-3]
189
+ elif response_text.startswith('```'):
190
+ response_text = response_text[3:-3]
191
+
192
+ json_response = json.loads(response_text)
193
+ return json_response
194
+
195
+ except json.JSONDecodeError as e:
196
+ st.error(f"Error parsing AI response: {str(e)}")
197
+ return None
198
+
199
+ except Exception as e:
200
+ st.error(f"Error processing video: {str(e)}")
201
+ return None
202
+
203
+ def display_script_variations(json_data):
204
+ """Display script variations in formatted tables"""
205
+ if not json_data or "script_variations" not in json_data:
206
+ st.error("No script variations found in the response")
207
+ return
208
+
209
+ for i, variation in enumerate(json_data["script_variations"], 1):
210
+ variation_name = variation.get("variation_name", f"Variation {i}")
211
+
212
+ st.subheader(variation_name)
213
+
214
+ # Convert script table to DataFrame for better display
215
+ script_data = variation.get("script_table", [])
216
+ if script_data:
217
+ df = pd.DataFrame(script_data)
218
+
219
+ # Rename columns for better display
220
+ column_mapping = {
221
+ 'timestamp': 'Timestamp',
222
+ 'script_voiceover': 'Script / Voiceover',
223
+ 'visual_direction': 'Visual Direction',
224
+ 'psychological_trigger': 'Psychological Trigger',
225
+ 'cta_action': 'CTA / Action'
226
+ }
227
+
228
+ df = df.rename(columns=column_mapping)
229
+
230
+ # Display as interactive table
231
+ st.dataframe(
232
+ df,
233
+ use_container_width=True,
234
+ hide_index=True,
235
+ column_config={
236
+ "Timestamp": st.column_config.TextColumn(width="small"),
237
+ "Script / Voiceover": st.column_config.TextColumn(width="large"),
238
+ "Visual Direction": st.column_config.TextColumn(width="large"),
239
+ "Psychological Trigger": st.column_config.TextColumn(width="medium"),
240
+ "CTA / Action": st.column_config.TextColumn(width="medium")
241
+ }
242
+ )
243
+ else:
244
+ st.warning(f"No script data available for {variation_name}")
245
+
246
+ st.divider()
247
+
248
+ def display_video_analysis(json_data):
249
+ """Display video analysis in formatted sections"""
250
+ if not json_data or "video_analysis" not in json_data:
251
+ st.error("No video analysis found in the response")
252
+ return
253
+
254
+ analysis = json_data["video_analysis"]
255
+
256
+ col1, col2 = st.columns(2)
257
+
258
+ with col1:
259
+ st.subheader("Effectiveness Factors")
260
+ st.write(analysis.get('effectiveness_factors', 'N/A'))
261
+
262
+ st.subheader("Target Audience")
263
+ st.write(analysis.get('target_audience', 'N/A'))
264
+
265
+ with col2:
266
+ st.subheader("Psychological Triggers")
267
+ st.write(analysis.get('psychological_triggers', 'N/A'))
268
+
269
+ st.subheader("Improvement Recommendations")
270
+ st.write(analysis.get('improvement_recommendations', 'N/A'))
271
+
272
+ def create_download_content(json_data):
273
+ """Create downloadable content from JSON data"""
274
+ content = "VIDEO ANALYSER AND SCRIPT GENERATOR OUTPUT\n"
275
+ content += "=" * 60 + "\n\n"
276
+
277
+ # Add script variations
278
+ for i, variation in enumerate(json_data.get("script_variations", []), 1):
279
+ variation_name = variation.get("variation_name", f"Variation {i}")
280
+ content += f"{variation_name}\n"
281
+ content += "-" * 40 + "\n"
282
+
283
+ for row in variation.get("script_table", []):
284
+ content += f"Timestamp: {row.get('timestamp', '')}\n"
285
+ content += f"Script: {row.get('script_voiceover', '')}\n"
286
+ content += f"Visual: {row.get('visual_direction', '')}\n"
287
+ content += f"Trigger: {row.get('psychological_trigger', '')}\n"
288
+ content += f"CTA: {row.get('cta_action', '')}\n\n"
289
+
290
+ content += "\n"
291
+
292
+ # Add analysis
293
+ analysis = json_data.get("video_analysis", {})
294
+ content += "VIDEO ANALYSIS\n"
295
+ content += "=" * 20 + "\n"
296
+ content += f"Effectiveness Factors: {analysis.get('effectiveness_factors', 'N/A')}\n\n"
297
+ content += f"Psychological Triggers: {analysis.get('psychological_triggers', 'N/A')}\n\n"
298
+ content += f"Target Audience: {analysis.get('target_audience', 'N/A')}\n\n"
299
+ content += f"Recommendations: {analysis.get('improvement_recommendations', 'N/A')}\n"
300
+
301
+ return content
302
+
303
+ def check_token(user_token):
304
+ ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
305
+ if not ACCESS_TOKEN:
306
+ logger.critical("ACCESS_TOKEN not set in environment.")
307
+ return False, "Server error: Access token not configured."
308
+ if user_token == ACCESS_TOKEN:
309
+ logger.info("Access token validated successfully.")
310
+ return True, ""
311
+ logger.warning("Invalid access token attempt.")
312
+ return False, "Invalid token."
313
+
314
+ def main():
315
+ """Main application function"""
316
+
317
+ # Header
318
+ st.title("Video Analyser and Script Generator")
319
+ st.divider()
320
+
321
+ st.set_page_config(page_title="Bulk Creative Generation", layout="wide")
322
+ if "authenticated" not in st.session_state:
323
+ st.session_state["authenticated"] = False
324
+
325
+ if not st.session_state["authenticated"]:
326
+ st.markdown("## Access Required")
327
+ token_input = st.text_input("Enter Access Token", type="password")
328
+ if st.button("Unlock App"):
329
+ ok, error_msg = check_token(token_input)
330
+ if ok:
331
+ st.session_state["authenticated"] = True
332
+ st.rerun()
333
+ else:
334
+ st.error(error_msg)
335
+ else:
336
+
337
+ # Sidebar for inputs
338
+ with st.sidebar:
339
+ st.header("Input Configuration")
340
+
341
+ # Video upload
342
+ uploaded_video = st.file_uploader(
343
+ "Upload Reference Video",
344
+ type=['mp4', 'mov', 'avi', 'mkv'],
345
+ help="Upload a profitable ad video to analyze and create variations from"
346
+ )
347
+
348
+ st.subheader("Additional Context (Optional)")
349
+
350
+ offer_details = st.text_area(
351
+ "Offer Details",
352
+ placeholder="e.g., Solar installation with $0 down payment...",
353
+ height=80,
354
+ help="Describe the product/service and main promise"
355
+ )
356
+
357
+ target_audience = st.text_area(
358
+ "Target Audience",
359
+ placeholder="e.g., 40+ homeowners with high electricity bills...",
360
+ height=80,
361
+ help="Describe the ideal customer demographics and pain points"
362
+ )
363
+
364
+ specific_hooks = st.text_area(
365
+ "Specific Hooks to Test",
366
+ placeholder="e.g., Government rebate angle, celebrity endorsement...",
367
+ height=80,
368
+ help="Any specific angles or hooks you want to incorporate"
369
+ )
370
+
371
+ additional_context = st.text_area(
372
+ "Additional Context",
373
+ placeholder="Any other relevant information...",
374
+ height=100,
375
+ help="Compliance requirements, brand guidelines, or other notes"
376
+ )
377
+
378
+ # Generate button
379
+ generate_button = st.button(
380
+ "Generate Script Variations",
381
+ type="primary",
382
+ use_container_width=True
383
+ )
384
+
385
+ # Main content area
386
+ if uploaded_video is None:
387
+ st.info("Please upload a reference video to begin analysis.")
388
+
389
+ # Instructions
390
+ with st.expander("How to Use This Tool"):
391
+ st.markdown("""
392
+ ### Upload Guidelines:
393
+ - **Best videos to analyze**: Already profitable Facebook/TikTok ads in your niche
394
+ - **Video length**: 30-90 seconds work best for analysis
395
+ - **Quality**: Clear audio and visuals help with better analysis
396
+
397
+ ### Context Tips:
398
+ - **Offer details**: Be specific about your main promise and mechanism
399
+ - **Audience**: Include demographics, pain points, and desires
400
+ - **Hooks**: Mention any specific angles that have worked for you
401
+
402
+ ### Script Optimization:
403
+ - Generated scripts focus on stopping scroll and driving clicks
404
+ - Each variation tests different psychological triggers
405
+ - Use the timestamp format for precise video production
406
+ - Test multiple variations to find your best performer
407
+ """)
408
+
409
+ elif generate_button:
410
+ if not GEMINI_API_KEY or GEMINI_API_KEY == "your-gemini-api-key-here":
411
+ st.error("Please configure your Gemini API key in the backend.")
412
+ return
413
+
414
+ # Process video
415
+ with st.spinner("Analyzing video and generating scripts..."):
416
+ video_bytes = uploaded_video.read()
417
+
418
+ # Reset file pointer for potential re-use
419
+ uploaded_video.seek(0)
420
+
421
+ json_response = analyze_video_and_generate_script(
422
+ video_bytes,
423
+ uploaded_video.name,
424
+ offer_details,
425
+ target_audience,
426
+ specific_hooks,
427
+ additional_context
428
+ )
429
+
430
+ if json_response:
431
+ st.success("Analysis complete! Here are your script variations:")
432
+
433
+ # Create tabs for different outputs
434
+ tab1, tab2 = st.tabs(["Script Variations", "Video Analysis"])
435
+
436
+ with tab1:
437
+ display_script_variations(json_response)
438
+
439
+ # Download button
440
+ download_content = create_download_content(json_response)
441
+ st.download_button(
442
+ label="Download All Scripts",
443
+ data=download_content,
444
+ file_name="video_script_variations.txt",
445
+ mime="text/plain",
446
+ type="secondary",
447
+ use_container_width=True
448
+ )
449
+
450
+ with tab2:
451
+ display_video_analysis(json_response)
452
+ else:
453
+ st.error("Failed to generate script variations. Please try again.")
454
+
455
+ else:
456
+ st.info("Configure your inputs in the sidebar and click 'Generate Script Variations' to begin.")
457
 
458
+ if __name__ == "__main__":
459
+ try:
460
+ logger.info("Launching Streamlit app...")
461
+ main()
462
+ except Exception as e:
463
+ logger.exception("Unhandled error during app launch.")