File size: 3,520 Bytes
9bc1376
 
 
 
 
 
78bcffe
 
 
 
9bc1376
 
 
 
 
 
 
78bcffe
9bc1376
78bcffe
9bc1376
 
 
 
 
 
 
78bcffe
9bc1376
 
 
 
 
007c24e
9bc1376
 
 
 
78bcffe
9bc1376
 
 
 
 
 
 
 
 
 
 
 
78bcffe
9bc1376
 
 
78bcffe
9bc1376
 
 
 
 
 
78bcffe
9bc1376
 
 
78bcffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e513d94
78bcffe
 
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
from datetime import datetime, timedelta
from typing import Any, Dict

import streamlit as st
import pandas as pd

from database.operations import find_script_results


def render_script_library(uid: str, prefix: str = "scripts") -> None:
    st.subheader("Generated Scripts")

    today = datetime.utcnow().date()
    default_start = today - timedelta(days=30)

    f1, f2, _ = st.columns([1, 1, 1.2])
    with f1:
        start_date_scripts = st.date_input("Start date", value=default_start, key=f"{prefix}_start")
    with f2:
        end_date_scripts = st.date_input("End date", value=today, key=f"{prefix}_end")

    if "scripts_page" not in st.session_state:
        st.session_state.scripts_page = 0

    start_dt = datetime.combine(start_date_scripts, datetime.min.time())
    end_dt = datetime.combine(end_date_scripts + timedelta(days=1), datetime.min.time())


    records, total_count = find_script_results(
        start_date=start_dt,
        end_date=end_dt,
        page=st.session_state.scripts_page,
        page_size=20,
        created_by=uid,
    )

    if total_count == 0 or not records:
        st.info("No script generations for the selected filters.")
        return

    start_idx = st.session_state.scripts_page * 20 + 1
    end_idx = min(start_idx + len(records) - 1, total_count)
    st.caption(f"Showing {start_idx}-{end_idx} of {total_count} items")

    def _label(d: Dict[str, Any]) -> str:
        ts = d.get("created_at")
        ts_s = ts.strftime("%Y-%m-%d %H:%M") if hasattr(ts, "strftime") else "Unknown time"
        vn = d.get("video_name") or d.get("file_name") or "Untitled"
        return f"{ts_s} · {vn}"

    options = [_label(d) for d in records]
    selected_label = st.selectbox("Select generated script", options=options, index=0, key=f"{prefix}_sel_dropdown")
    sel_idx = options.index(selected_label) if selected_label in options else 0
    doc = records[sel_idx]


    if doc.get("thumbnail"):
        try:
            st.image("data:image/jpeg;base64," + doc["thumbnail"], width=160, caption="Thumbnail")
        except Exception:
            pass


    json_response = doc.get("response")
    if not json_response:
        st.info("No variations saved.")
        return

    all_tables = []
    if isinstance(json_response, list):
        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,
                key=f"{prefix}_hist_prompt_{doc.get('_id')}_{round_idx}",
            )
            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"{(doc.get('video_name') or doc.get('file_name') or 'scripts')}_scripts.csv",
            mime="text/csv",
            width='stretch',
            key=f"{prefix}_download_csv",
        )