Spaces:
Sleeping
Sleeping
| import os | |
| import tempfile | |
| import pandas as pd | |
| import streamlit as st | |
| from services.script_generator import generate_scripts | |
| from utils.video import get_video_thumbnail_base64 | |
| from components.display_variations import display_script_variations | |
| from database import insert_script_result, get_all_scripts | |
| def generator_page(): | |
| selected_tab = st.sidebar.radio("Select Mode", ["Script Generator", "History"], index=0) | |
| if selected_tab == "Script Generator": | |
| st.subheader("Script Generator") | |
| uploaded_video = st.file_uploader( | |
| "Upload Video or ZIP (max 3 videos)", | |
| type=['mp4','mov','avi','mkv','zip'] | |
| ) | |
| script_duration = st.slider("Script Duration (seconds)", 0, 180, 60, 5) | |
| num_scripts = st.slider("Number of Scripts", 1, 5, 3) | |
| st.markdown("Additional Information") | |
| offer_details = st.text_area("Offer Details", placeholder="e.g., Solar installation with $0 down payment...") | |
| target_audience = st.text_area("Target Audience", placeholder="e.g., 40+ homeowners with high electricity bills...") | |
| specific_hooks = st.text_area("Specific Hooks to Test", placeholder="e.g., Government rebate angle...") | |
| additional_context = st.text_area("Additional Context", placeholder="Compliance requirements, brand guidelines...") | |
| script_button = st.button("Generate Scripts", use_container_width=True) | |
| if script_button and uploaded_video: | |
| with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_video.name)[1]) as tmp: | |
| tmp.write(uploaded_video.read()) | |
| video_path = tmp.name | |
| with st.spinner("Generating scripts..."): | |
| st.session_state.setdefault("scripts", []) | |
| result = generate_scripts( | |
| video_path, | |
| offer_details, | |
| target_audience, | |
| specific_hooks, | |
| additional_context, | |
| num_scripts=num_scripts, | |
| duration=script_duration | |
| ) | |
| if result and "script_variations" in result: | |
| st.session_state["scripts"].append({ | |
| "prompt_used": "Initial Generation", | |
| "variations": result["script_variations"] | |
| }) | |
| st.session_state["video_name"] = uploaded_video.name | |
| st.session_state["video_path"] = video_path | |
| st.session_state["thumbnail"] = get_video_thumbnail_base64(video_path) | |
| st.session_state["meta"] = { | |
| "offer_details": offer_details, | |
| "target_audience": target_audience, | |
| "specific_hook": specific_hooks, | |
| "additional_context": additional_context | |
| } | |
| if "scripts" in st.session_state and st.session_state["scripts"]: | |
| for round_idx, round_data in enumerate(st.session_state["scripts"], 1): | |
| st.markdown(f"### Generation Round {round_idx}") | |
| st.text_input("Prompt used:", round_data["prompt_used"], disabled=True, key=f"prompt_{round_idx}") | |
| for i, variation in enumerate(round_data["variations"], 1): | |
| st.markdown(f"#### Variation {i}: {variation.get('variation_name','Var')}") | |
| df = pd.DataFrame(variation.get("script_table", [])) | |
| st.table(df) | |
| st.divider() | |
| save_button = st.button("Save to DB", use_container_width=True) | |
| if save_button: | |
| try: | |
| insert_script_result( | |
| video_name=st.session_state.get("video_name", "unknown"), | |
| offer_details=st.session_state["meta"].get("offer_details", ""), | |
| target_audience=st.session_state["meta"].get("target_audience", ""), | |
| specific_hook=st.session_state["meta"].get("specific_hook", ""), | |
| additional_context=st.session_state["meta"].get("additional_context", ""), | |
| response=st.session_state["scripts"], | |
| thumbnail=st.session_state.get("thumbnail", "") | |
| ) | |
| st.success("Scripts saved to database!") | |
| except Exception as e: | |
| st.error(f"Failed to save scripts: {e}") | |
| st.subheader("Generate More Scripts") | |
| more_num = st.slider("How many more scripts?", 1, 5, 1, key="more_scripts_slider") | |
| more_prompt = st.text_area("Required Prompt", placeholder="Add specific guidance") | |
| if st.button("Generate More Scripts", use_container_width=True): | |
| if not more_prompt.strip(): | |
| st.error("Please provide a prompt before generating more scripts.") | |
| else: | |
| video_path = st.session_state.get("video_path") | |
| if not video_path: | |
| st.error("No video available. Please upload again.") | |
| else: | |
| with st.spinner("Generating more scripts..."): | |
| extra_result = generate_scripts( | |
| video_path, | |
| st.session_state["meta"]["offer_details"], | |
| st.session_state["meta"]["target_audience"], | |
| st.session_state["meta"]["specific_hook"], | |
| st.session_state["meta"]["additional_context"] + "\n\n" + more_prompt, | |
| num_scripts=more_num, | |
| duration=script_duration | |
| ) | |
| if extra_result and "script_variations" in extra_result: | |
| st.session_state["scripts"].append({ | |
| "prompt_used": more_prompt, | |
| "variations": extra_result["script_variations"] | |
| }) | |
| else: | |
| history_items = get_all_scripts(limit=20) | |
| if history_items: | |
| video_titles = [ | |
| f"{item['video_name']} ({item['created_at'].strftime('%Y-%m-%d %H:%M ')})" | |
| for item in history_items | |
| ] | |
| selected = st.sidebar.radio("History Items", video_titles, index=0) | |
| idx = video_titles.index(selected) | |
| selected_data = history_items[idx] | |
| st.subheader(f"Scripts for: {selected_data['video_name']}") | |
| if selected_data.get("thumbnail"): | |
| st.image("data:image/jpeg;base64," + selected_data["thumbnail"], width=150) | |
| json_response = selected_data.get("response") | |
| if json_response: | |
| if isinstance(json_response, list): | |
| all_tables = [] | |
| for round_idx, round_data in enumerate(json_response, 1): | |
| st.markdown(f"### Generation Round {round_idx}") | |
| st.text_input("Prompt used:", round_data.get("prompt_used", "N/A"), disabled=True) | |
| for i, variation in enumerate(round_data.get("variations", []), 1): | |
| st.markdown(f"#### Variation {i}: {variation.get('variation_name','Var')}") | |
| df = pd.DataFrame(variation.get("script_table", [])) | |
| st.table(df) | |
| if not df.empty: | |
| df["Variation"] = variation.get("variation_name", f"Var{i}") | |
| df["Round"] = round_idx | |
| all_tables.append(df) | |
| if all_tables: | |
| csv_scripts = pd.concat(all_tables, ignore_index=True).to_csv(index=False) | |
| st.download_button( | |
| "Download CSV", | |
| data=csv_scripts, | |
| file_name=f"{selected_data['video_name']}_scripts.csv", | |
| mime="text/csv", | |
| use_container_width=True | |
| ) | |
| else: | |
| st.info("No saved history available.") |