userIdc2024 commited on
Commit
70da5cc
·
verified ·
1 Parent(s): 09e34ab

Update app_pages/script_generator.py

Browse files
Files changed (1) hide show
  1. app_pages/script_generator.py +135 -131
app_pages/script_generator.py CHANGED
@@ -3,149 +3,153 @@ import tempfile
3
  import pandas as pd
4
  import streamlit as st
5
 
6
- from services.video_analyzer import analyze_video_only
7
- from components.render_analysis import render_analyzer_results
8
  from utils.video import get_video_thumbnail_base64
9
- from utils.dataframe import analysis_to_csv
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}")
 
3
  import pandas as pd
4
  import streamlit as st
5
 
6
+ from services.script_generator import generate_scripts
 
7
  from utils.video import get_video_thumbnail_base64
8
+ from components.display_variations import display_script_variations
9
+ from database import insert_script_result, get_all_scripts
10
 
11
+ def generator_page():
12
+ selected_tab = st.sidebar.radio("Select Mode", ["Script Generator", "History"], index=0)
13
+
14
+ if selected_tab == "Script Generator":
15
+ st.subheader("Script Generator")
16
 
 
 
17
  uploaded_video = st.file_uploader(
18
+ "Upload Video or ZIP (max 3 videos)",
19
+ type=['mp4','mov','avi','mkv','zip']
 
20
  )
21
+ script_duration = st.slider("Script Duration (seconds)", 0, 180, 60, 5)
22
+ num_scripts = st.slider("Number of Scripts", 1, 5, 3)
23
+
24
+ st.markdown("Additional Information")
25
+ offer_details = st.text_area("Offer Details", placeholder="e.g., Solar installation with $0 down payment...")
26
+ target_audience = st.text_area("Target Audience", placeholder="e.g., 40+ homeowners with high electricity bills...")
27
+ specific_hooks = st.text_area("Specific Hooks to Test", placeholder="e.g., Government rebate angle...")
28
+ additional_context = st.text_area("Additional Context", placeholder="Compliance requirements, brand guidelines...")
29
+
30
+ script_button = st.button("Generate Scripts", use_container_width=True)
31
+ if script_button and uploaded_video:
32
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_video.name)[1]) as tmp:
33
  tmp.write(uploaded_video.read())
34
  video_path = tmp.name
35
+ with st.spinner("Generating scripts..."):
36
+ st.session_state.setdefault("scripts", [])
37
+ result = generate_scripts(
38
+ video_path,
39
+ offer_details,
40
+ target_audience,
41
+ specific_hooks,
42
+ additional_context,
43
+ num_scripts=num_scripts,
44
+ duration=script_duration
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  )
46
+ if result and "script_variations" in result:
47
+ st.session_state["scripts"].append({
48
+ "prompt_used": "Initial Generation",
49
+ "variations": result["script_variations"]
50
+ })
51
+ st.session_state["video_name"] = uploaded_video.name
52
+ st.session_state["video_path"] = video_path
53
+ st.session_state["thumbnail"] = get_video_thumbnail_base64(video_path)
54
+ st.session_state["meta"] = {
55
+ "offer_details": offer_details,
56
+ "target_audience": target_audience,
57
+ "specific_hook": specific_hooks,
58
+ "additional_context": additional_context
59
+ }
60
+
61
+ if "scripts" in st.session_state and st.session_state["scripts"]:
62
+ for round_idx, round_data in enumerate(st.session_state["scripts"], 1):
63
+ st.markdown(f"### Generation Round {round_idx}")
64
+ st.text_input("Prompt used:", round_data["prompt_used"], disabled=True, key=f"prompt_{round_idx}")
65
+ for i, variation in enumerate(round_data["variations"], 1):
66
+ st.markdown(f"#### Variation {i}: {variation.get('variation_name','Var')}")
67
+ df = pd.DataFrame(variation.get("script_table", []))
68
+ st.table(df)
69
+
70
+ st.divider()
71
+ save_button = st.button("Save to DB", use_container_width=True)
72
+ if save_button:
73
  try:
74
+ insert_script_result(
75
  video_name=st.session_state.get("video_name", "unknown"),
76
+ offer_details=st.session_state["meta"].get("offer_details", ""),
77
+ target_audience=st.session_state["meta"].get("target_audience", ""),
78
+ specific_hook=st.session_state["meta"].get("specific_hook", ""),
79
+ additional_context=st.session_state["meta"].get("additional_context", ""),
80
+ response=st.session_state["scripts"],
81
  thumbnail=st.session_state.get("thumbnail", "")
82
  )
83
+ st.success("Scripts saved to database!")
84
  except Exception as e:
85
+ st.error(f"Failed to save scripts: {e}")
86
+
87
+ st.subheader("Generate More Scripts")
88
+ more_num = st.slider("How many more scripts?", 1, 5, 1, key="more_scripts_slider")
89
+ more_prompt = st.text_area("Required Prompt", placeholder="Add specific guidance")
90
+ if st.button("Generate More Scripts", use_container_width=True):
91
+ if not more_prompt.strip():
92
+ st.error("Please provide a prompt before generating more scripts.")
93
+ else:
94
+ video_path = st.session_state.get("video_path")
95
+ if not video_path:
96
+ st.error("No video available. Please upload again.")
97
+ else:
98
+ with st.spinner("Generating more scripts..."):
99
+ extra_result = generate_scripts(
100
+ video_path,
101
+ st.session_state["meta"]["offer_details"],
102
+ st.session_state["meta"]["target_audience"],
103
+ st.session_state["meta"]["specific_hook"],
104
+ st.session_state["meta"]["additional_context"] + "\n\n" + more_prompt,
105
+ num_scripts=more_num,
106
+ duration=script_duration
107
+ )
108
+ if extra_result and "script_variations" in extra_result:
109
+ st.session_state["scripts"].append({
110
+ "prompt_used": more_prompt,
111
+ "variations": extra_result["script_variations"]
112
+ })
113
 
114
  else:
115
+ history_items = get_all_scripts(limit=20)
116
+ if history_items:
117
+ video_titles = [
118
+ f"{item['video_name']} ({item['created_at'].strftime('%Y-%m-%d %H:%M ')})"
119
+ for item in history_items
120
+ ]
121
+ selected = st.sidebar.radio("History Items", video_titles, index=0)
122
+ idx = video_titles.index(selected)
123
+ selected_data = history_items[idx]
124
+
125
+ st.subheader(f"Scripts for: {selected_data['video_name']}")
126
+ if selected_data.get("thumbnail"):
127
+ st.image("data:image/jpeg;base64," + selected_data["thumbnail"], width=150)
128
+
129
+ json_response = selected_data.get("response")
130
+ if json_response:
131
+ if isinstance(json_response, list):
132
+ all_tables = []
133
+ for round_idx, round_data in enumerate(json_response, 1):
134
+ st.markdown(f"### Generation Round {round_idx}")
135
+ st.text_input("Prompt used:", round_data.get("prompt_used", "N/A"), disabled=True)
136
+ for i, variation in enumerate(round_data.get("variations", []), 1):
137
+ st.markdown(f"#### Variation {i}: {variation.get('variation_name','Var')}")
138
+ df = pd.DataFrame(variation.get("script_table", []))
139
+ st.table(df)
140
+ if not df.empty:
141
+ df["Variation"] = variation.get("variation_name", f"Var{i}")
142
+ df["Round"] = round_idx
143
+ all_tables.append(df)
144
+
145
+ if all_tables:
146
+ csv_scripts = pd.concat(all_tables, ignore_index=True).to_csv(index=False)
147
+ st.download_button(
148
+ "Download CSV",
149
+ data=csv_scripts,
150
+ file_name=f"{selected_data['video_name']}_scripts.csv",
151
+ mime="text/csv",
152
+ use_container_width=True
153
+ )
154
+ else:
155
+ st.info("No saved history available.")