nniehaus's picture
Update app.py
9d8abed verified
import streamlit as st
from openai import OpenAI
import os
import re
# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def search_location_info(location, script_content):
"""
Uses AI to search for location-specific information relevant to the script content.
"""
try:
search_prompt = f"""
You are a location research expert. Search for current, relevant information about {location} that would be useful for customizing the following video script content.
Script content preview: {script_content[:500]}...
Please search for and provide:
1. Key local businesses, landmarks, or services mentioned in or relevant to this script
2. Local regulations, practices, or customs that might be relevant
3. Popular local areas, neighborhoods, or districts
4. Local events, seasons, or cultural aspects that could be incorporated
5. Demographics and target audience characteristics for this location
Focus on information that would help make this script feel authentic and locally relevant.
"""
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a local market research expert with access to current information. Use web search capabilities to find relevant, current information about locations."},
{"role": "user", "content": search_prompt}
]
)
return response.choices[0].message.content
except Exception as e:
return f"Unable to gather location-specific information: {str(e)}"
def customize_script_for_location(original_script, location, research_info):
"""
Customizes the video script for the specific location using research information.
"""
try:
customization_prompt = f"""
You are a expert video script writer specializing in local content adaptation.
Original Script:
{original_script}
Target Location: {location}
Research Information:
{research_info}
Your task is to customize this script to be specific and relevant to {location}. Guidelines:
1. **Subtle Integration**: Use the location name SPARINGLY (1-3 times maximum) and only where it feels natural
2. **Strategic Local Context**: Add 1-2 authentic local details that enhance the message without overwhelming it
3. **Maintain Original Flow**: Keep the exact same structure, length, and tone of the original script
4. **Quality Over Quantity**: Better to make fewer, higher-impact local references than to force many
5. **Natural Feel**: The script should feel like the original with just enough local flavor to be relevant
SPECIFIC RULES:
- Use the location name maximum 2-3 times in the entire script
- Add only 1-2 specific local references (businesses, landmarks, regulations, or practices)
- Keep the same conversational tone and length as the original
- Don't add unnecessary local adjectives or descriptors
- Focus on enhancing key points rather than adding location references everywhere
If the script topic isn't naturally location-based:
- Add the location name once in the opening or closing
- Include ONE relevant local reference if it naturally fits
- Don't force location into every sentence
If the script IS location-based (real estate, local services, etc.):
- Replace 1-2 generic references with specific local ones
- Mention local market conditions or regulations only if directly relevant
- Use local area names sparingly and only where they add real value
Return only the customized script, maintaining the same format and structure as the original.
"""
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are an expert video script writer who specializes in creating location-specific content that feels authentic and locally relevant."},
{"role": "user", "content": customization_prompt}
]
)
return response.choices[0].message.content
except Exception as e:
return f"Error customizing script: {str(e)}"
def generate_social_media_content(customized_script, location, original_script):
"""
Generates optimized social media content including title, description, and hashtags.
"""
try:
# Extract key themes from the script for better social media content
script_preview = customized_script[:800] if len(customized_script) > 800 else customized_script
social_media_prompt = f"""
Based on this location-customized video script for {location}, create optimized social media content:
Script Preview:
{script_preview}
Create:
1. **Video Title** (60 characters max, engaging and location-specific)
2. **Description** (150-300 words, engaging copy that includes the location and key script themes)
3. **Hashtags** (15-20 relevant hashtags including location-based and topic-based tags)
Guidelines:
- Make the title compelling and click-worthy with the location mentioned ONCE
- Write the description to hook viewers, mention location 1-2 times maximum
- Don't over-emphasize location in the description - focus on value and engagement
- Include location hashtags (city, state, region) - about 3-5 location tags
- Add topic-specific hashtags related to the script content - about 8-10 topic tags
- Include 2-3 popular general hashtags that could boost reach
- Mix broad and niche hashtags for optimal discoverability
- Keep total hashtags to 15-20 maximum
Format as:
**TITLE:**
[Title here]
**DESCRIPTION:**
[Description here]
**HASHTAGS:**
[All hashtags here]
"""
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a social media marketing expert who creates viral, location-specific content that maximizes local engagement and discoverability."},
{"role": "user", "content": social_media_prompt}
]
)
return response.choices[0].message.content
except Exception as e:
return f"Error generating social media content: {str(e)}"
# Define initial system message for context
initial_system_message = {
"role": "system",
"content": """You are a expert content localization specialist with deep knowledge of local markets, cultural nuances, and location-based marketing strategies. You excel at making any content feel authentically local while maintaining its original purpose and effectiveness."""
}
# Streamlit setup
st.set_page_config(layout="wide")
# Initialize session state
if "customized_script" not in st.session_state:
st.session_state["customized_script"] = None
if "social_content" not in st.session_state:
st.session_state["social_content"] = None
if "show_notice" not in st.session_state:
st.session_state["show_notice"] = False
# Centered title
st.markdown("<h1 style='text-align: center; color: black;'>Local Video Script Customizer</h1>", unsafe_allow_html=True)
st.markdown("<h3 style='text-align: center; color: gray;'>Transform any video script for local markets</h3>", unsafe_allow_html=True)
# User inputs
st.markdown("<h2 style='text-align: center; color: black;'>Script Customization Details</h2>", unsafe_allow_html=True)
location = st.text_input(
"Target Location (City, State or Region)",
placeholder="e.g., Austin, Texas or Miami, FL or San Francisco Bay Area"
)
original_script = st.text_area(
"Original Video Script",
placeholder="Paste your complete video script here...",
height=300
)
# Optional customization preferences
st.markdown("### Customization Preferences (Optional)")
col1, col2 = st.columns(2)
with col1:
focus_areas = st.multiselect(
"Areas to emphasize in localization:",
["Local businesses", "Cultural references", "Local events", "Demographics", "Local regulations", "Landmarks"],
default=["Local businesses", "Landmarks"]
)
with col2:
tone_preference = st.selectbox(
"Tone for local adaptation:",
["Keep original tone", "More casual/friendly", "More professional", "More community-focused"],
index=0
)
generate_button = st.button('Customize Script for Location', type="primary")
# Process results on button click
if generate_button:
if not location or not original_script:
st.error("Please provide both a target location and original script.")
else:
st.session_state["show_notice"] = True
with st.spinner(f"Researching {location} and customizing your script..."):
try:
# Step 1: Research location information
research_info = search_location_info(location, original_script)
# Step 2: Customize the script
customized_script = customize_script_for_location(original_script, location, research_info)
# Step 3: Generate social media content
social_content = generate_social_media_content(customized_script, location, original_script)
# Store results in session state
st.session_state["customized_script"] = customized_script
st.session_state["social_content"] = social_content
st.session_state["show_notice"] = False
except Exception as e:
st.error(f"An error occurred: {str(e)}")
st.session_state["show_notice"] = False
# Display the waiting notice
if st.session_state["show_notice"]:
st.info(f"Researching {location} and customizing your script. This may take a minute or two...")
# Display results if available
if st.session_state["customized_script"] and st.session_state["social_content"]:
st.markdown("<h2 style='text-align: center; color: black;'>Your Localized Content ⬇️</h2>", unsafe_allow_html=True)
# Display customized script
st.markdown("### 📝 Customized Video Script")
st.markdown("---")
formatted_script = st.session_state["customized_script"].replace('\n', '<br>')
st.markdown(f"<div style='background-color: #f8f9fa; padding: 20px; border-radius: 10px; border-left: 4px solid #007bff;'>{formatted_script}</div>", unsafe_allow_html=True)
# Display social media content
st.markdown("### 📱 Social Media Content")
st.markdown("---")
formatted_social = st.session_state["social_content"].replace('\n', '<br>')
st.markdown(f"<div style='background-color: #f0f8f0; padding: 20px; border-radius: 10px; border-left: 4px solid #28a745;'>{formatted_social}</div>", unsafe_allow_html=True)
# Download buttons
st.markdown("### 📥 Download Your Content")
col1, col2 = st.columns(2)
with col1:
script_download = f"CUSTOMIZED SCRIPT FOR {location.upper()}\n\n{st.session_state['customized_script']}"
st.download_button(
label="Download Script",
data=script_download,
file_name=f"customized_script_{location.replace(' ', '_').replace(',', '')}.txt",
mime="text/plain"
)
with col2:
social_download = f"SOCIAL MEDIA CONTENT FOR {location.upper()}\n\n{st.session_state['social_content']}"
st.download_button(
label="Download Social Media Content",
data=social_download,
file_name=f"social_media_{location.replace(' ', '_').replace(',', '')}.txt",
mime="text/plain"
)
# Help section
with st.expander("ℹ️ How to Use This Tool"):
st.markdown("""
**This tool helps you:**
- Customize any video script for specific locations
- Research local information to make content authentic
- Generate optimized social media content for local audiences
**Best Practices:**
- Be specific with your location (include city and state)
- Provide complete scripts for best results
- Use the customization preferences to guide the adaptation
- Review and adjust the output to match your brand voice
**Tips:**
- Works with any type of script (educational, promotional, entertainment, etc.)
- The tool will find creative ways to incorporate location even for non-location-based content
- Generated hashtags are optimized for local discovery
""")