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", )