Create an app that generate animations using remotion and OpenAI based on user input, to create cartoons and animations
To upload files, please first save the app
import streamlit as st
import openai
from PIL import Image
import requests
from io import BytesIO
import time
# Configure page
st.set_page_config(page_title="AI Animation Studio", page_icon="🎨")
# Check for OpenAI API key in Streamlit secrets
if "OPENAI_API_KEY" not in st.secrets:
st.error("OpenAI API key is required in Streamlit secrets!")
st.stop()
# Initialize OpenAI API key
openai.api_key = st.secrets["OPENAI_API_KEY"]
# Custom CSS for better styling
st.markdown(
"""
<style>
.stApp {
max-width: 1200px;
margin: 0 auto;
}
.generation-container {
padding: 20px;
border-radius: 10px;
background-color: #f0f2f6;
}
</style>
""",
unsafe_allow_html=True
)
# Initialize session state
if "frames" not in st.session_state:
st.session_state.frames = []
if "animation_settings" not in st.session_state:
st.session_state.animation_settings = {
"style": "cartoon",
"frame_count": 4,
"size": "512x512",
}
def create_enhanced_prompt(base_prompt, frame_num, style):
"""Create a detailed prompt for each frame."""
styles = {
"cartoon": "in a vibrant cartoon style with clean lines",
"anime": "in anime art style with distinctive characteristics",
"realistic": "in photorealistic style with detailed textures",
"pixel": "in retro pixel art style",
}
return f"{base_prompt} {styles[style]}. Frame {frame_num} of sequence."
def generate_frame(prompt):
"""Generate a single frame using DALL-E."""
try:
response = openai.Image.create(
prompt=prompt,
n=1,
size=st.session_state.animation_settings["size"]
)
image_url = response["data"][0]["url"]
return Image.open(BytesIO(requests.get(image_url).content))
except Exception as e:
st.error(f"Frame generation error: {str(e)}")
return None
# Sidebar for settings
with st.sidebar:
st.title("Animation Settings")
st.session_state.animation_settings["style"] = st.selectbox(
"Art Style", ["cartoon", "anime", "realistic", "pixel"]
)
st.session_state.animation_settings["frame_count"] = st.slider(
"Number of Frames",
min_value=2,
max_value=6,
value=4
)
preview_speed = st.slider(
"Preview Speed (seconds)",
min_value=0.2,
max_value=2.0,
value=0.5,
step=0.1
)
# Main content
st.title("🎨 AI Animation Studio")
st.markdown("Create amazing animations with AI — just describe what you want to see!")
# Input section
with st.container():
prompt = st.text_area(
"Describe your animation",
placeholder="E.g., a butterfly landing on a flower in a garden",
help="Be specific about the action, colors, and setting"
)
col1, col2 = st.columns([1, 3])
with col1:
generate_button = st.button("🎬 Generate", use_container_width=True)
# Generation logic
if generate_button and prompt:
with st.spinner("🎨 Generating your animation..."):
frames = []
for i in range(st.session_state.animation_settings["frame_count"]):
st.write(f"Generating frame {i+1}...")
enhanced_prompt = create_enhanced_prompt(
prompt,
i+1,
st.session_state.animation_settings["style"]
)
frame = generate_frame(enhanced_prompt)
if frame:
frames.append(frame)
time.sleep(1) # A short pause for rate-limiting (optional)
if len(frames) == st.session_state.animation_settings["frame_count"]:
st.session_state.frames = frames
st.success("✨ Generation complete!")
# Display results
if st.session_state.frames:
st.subheader("Generated Frames")
# Display individual frames
cols = st.columns(len(st.session_state.frames))
for idx, (col, frame) in enumerate(zip(cols, st.session_state.frames)):
with col:
st.image(frame, caption=f"Frame {idx+1}", use_column_width=True)
# Animation preview
st.subheader("Animation Preview")
preview_container = st.empty()
# Simple "Play Preview" button to cycle through frames
if st.button("â–¶ Play Preview"):
for _ in range(3): # Loop a few times; adjust as desired
for frame in st.session_state.frames:
preview_container.image(frame, width=300)
time.sleep(preview_speed)
st.success("Preview finished! Click 'Play Preview' again to replay.")
# Tips and information
with st.expander("✨ Tips for Better Results"):
st.markdown(
"""
* **Be Specific**: Detail the action, movement, and setting
* **Choose Appropriate Style**: Different styles work better for different concepts
* **Frame Count**: More frames = smoother animation but longer generation time
* **Keep it Simple**: Focus on one main action or transformation
* **Use Clear Language**: Avoid ambiguous descriptions
"""
)
st.markdown("---")
st.caption("Made with 💖 using OpenAI DALL-E and Streamlit")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?