File size: 6,352 Bytes
9bc1376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92ed524
9bc1376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4013df7
9bc1376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4013df7
9bc1376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4013df7
9bc1376
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import os
import tempfile
import pandas as pd
import streamlit as st

from generator_function.script_generator import generate_scripts
from helpers_function.helpers import get_video_thumbnail_base64
from database.operations import insert_script_result
from authen.authentication import login_gate

def _fmt_ts(ts) -> str:
    try:
        return ts.strftime("%Y-%m-%d %H:%M")
    except Exception:
        return "Unknown time"


def generator_page(uid: str):
    st.subheader("Script Generator")

    uploaded_video = st.file_uploader(
        "Upload Video or ZIP (max 3 videos)", type=["mp4", "mov", "avi", "mkv", "zip"], key="sg_upload"
    )
    script_duration = st.slider("Script Duration (seconds)", 0, 180, 60, 5, key="sg_dur")
    num_scripts = st.slider("Number of Scripts", 1, 5, 3, key="sg_count")

    st.markdown("Additional Information")
    offer_details = st.text_area(
        "Offer Details",
        placeholder="e.g., Solar installation with $0 down payment...",
        key="sg_offer",
    )
    target_audience = st.text_area(
        "Target Audience",
        placeholder="e.g., 40+ homeowners with high electricity bills...",
        key="sg_aud",
    )
    specific_hooks = st.text_area(
        "Specific Hooks to Test",
        placeholder="e.g., Government rebate angle...",
        key="sg_hooks",
    )
    additional_context = st.text_area(
        "Additional Context",
        placeholder="Compliance requirements, brand guidelines...",
        key="sg_ctx",
    )

    script_button = st.button("Generate Scripts",width='stretch', key="sg_go")
    if script_button and uploaded_video:
        with tempfile.NamedTemporaryFile(
            delete=False, suffix=os.path.splitext(uploaded_video.name)[1]
        ) as tmp:
            src_bytes = uploaded_video.read()
            tmp.write(src_bytes)
            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
                try:
                    st.session_state["thumbnail"] = get_video_thumbnail_base64(video_path)
                except Exception:
                    st.session_state["thumbnail"] = ""
                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", width='stretch', key="sg_save")
        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", ""),
                    created_by=uid,
                    num_scripts=len(st.session_state["scripts"][-1]["variations"]),
                    category="general",
                )
                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="sg_more_count")
        more_prompt = st.text_area("Required Prompt", placeholder="Add specific guidance", key="sg_more_prompt")
        if st.button("Generate More Scripts", width='stretch', key="sg_more_go"):
            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"]}
                            )