ImaGen / scriptgen.py
fmmkii's picture
Revamped API handling
12671eb
import streamlit as st
from dotenv import load_dotenv, set_key
from generate_script import generate_script
import os
import json
# Load environment variables
load_dotenv()
# Initialize the API key
api_key = st.session_state.get("OPENAI_API_KEY", None)
serper_api_key = st.secrets.get("SERPER_API_KEY")
# Check if API keys are available
if not api_key:
st.error("API Key not provided! Please enter it in the main app.")
else:
os.environ["OPENAI_API_KEY"] = api_key
# File to store script history
history_file = "script_history.json"
# Function to load history from file
def load_history():
if os.path.exists(history_file):
with open(history_file, "r") as file:
return json.load(file)
return []
# Function to save history to file
def save_history(history):
with open(history_file, "w") as file:
json.dump(history, file, indent=4)
# Load history from JSON file
script_history = load_history()
# Layout with two columns
col1, col2 = st.columns(2)
# Left column for inputs
with col1:
st.subheader("Input πŸ‘‡")
prompt = st.text_input("Provide the topic of the video:", placeholder="e.g., How to bake a cake")
video_length = st.number_input("Specify length in minutes", min_value=1.0, step=0.5, value=10.0)
with st.sidebar:
st.title("Options")
creativity = st.slider("Set creativity level:", min_value=0.0, max_value=1.0, value=0.5)
# Button to generate the video script
generate_script_button = st.button("Generate Script")
# Right column for results
with col2:
st.subheader("Output ✨")
if generate_script_button:
if not prompt:
st.error("Please provide a topic for the video.")
else:
try:
# Generate the video script using the utility function
with st.spinner("Generating your script..."):
title, script, search_data = generate_script(prompt, video_length, creativity, api_key, serper_api_key)
# Display the results
st.success("Script generated successfully!")
st.subheader(f"Title: {title}")
st.write(f"Script: {script}")
# Save the new script directly to the JSON file
new_entry = {
"title": title,
"script": script,
"search_data": search_data,
}
script_history.append(new_entry)
save_history(script_history)
# Add a download button for the generated script
st.download_button(
label="Download Script",
data=script,
file_name="generated_script.txt",
mime="text/plain",
)
# Display additional search data
with st.expander("Show search data for the script"):
st.write(search_data)
except Exception as e:
# Handle any errors that occur during script generation
st.error("An error occurred. Try again.")
with st.expander("Expand to see details"):
st.write(f"{e}")