AnimateScenes / app.py
KilgorePennington's picture
Update app.py
e816734 verified
import streamlit as st
import time
import random
import requests
from PIL import Image, ImageDraw, ImageFont
import io
import hashlib
# Page config
st.set_page_config(
page_title="StoryVision AI",
page_icon="πŸ“š",
layout="wide"
)
# Custom CSS
st.markdown("""
<style>
.main-header {
font-size: 3rem;
color: #FF6B6B;
text-align: center;
margin-bottom: 2rem;
}
.story-container {
background-color: #f8f9fa;
padding: 2rem;
border-radius: 15px;
border-left: 5px solid #FF6B6B;
margin: 1rem 0;
}
.image-container {
border-radius: 15px;
overflow: hidden;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
margin: 1rem 0;
}
</style>
""", unsafe_allow_html=True)
# Initialize session state
if 'generated_image' not in st.session_state:
st.session_state.generated_image = None
# Header
st.markdown('<h1 class="main-header">πŸ“š StoryVision AI</h1>', unsafe_allow_html=True)
st.markdown('<p style="text-align: center; font-size: 1.2rem; color: #666;">Create magical stories with AI-generated artwork!</p>', unsafe_allow_html=True)
# Sidebar controls
st.sidebar.markdown("## 🎨 Story Settings")
genre = st.sidebar.selectbox(
"Choose a genre:",
["Fantasy", "Sci-Fi", "Mystery", "Romance", "Adventure", "Horror", "Comedy"]
)
protagonist = st.sidebar.text_input("Main character name:", placeholder="e.g., Luna the brave")
if not protagonist:
protagonist = "The Hero"
setting = st.sidebar.selectbox(
"Setting:",
["Enchanted Forest", "Space Station", "Victorian London", "Post-Apocalyptic City",
"Underwater Kingdom", "Flying City", "Desert Oasis", "Mountain Village"]
)
art_style = st.sidebar.selectbox(
"Art style:",
["Fantasy Art", "Digital Painting", "Watercolor", "Anime Style", "Photorealistic", "Concept Art"]
)
# Working image generation using Pollinations AI (No API key needed!)
@st.cache_data(show_spinner=False)
def generate_image_pollinations(prompt, width=512, height=512):
"""Generate image using Pollinations.ai - completely free, no API key needed"""
try:
# Clean and encode the prompt
clean_prompt = prompt.replace(" ", "%20").replace(",", "%2C")
# Pollinations.ai API endpoint
url = f"https://image.pollinations.ai/prompt/{clean_prompt}?width={width}&height={height}&seed={random.randint(1, 10000)}"
response = requests.get(url, timeout=30)
if response.status_code == 200:
image = Image.open(io.BytesIO(response.content))
return image, True
else:
return None, False
except Exception as e:
st.error(f"Error: {str(e)}")
return None, False
# Alternative: Generate artistic image using code (always works)
def generate_procedural_art(prompt, protagonist, setting, genre, style):
"""Generate artistic image using Python - always works offline"""
# Create a 512x512 image
width, height = 512, 512
image = Image.new('RGB', (width, height))
draw = ImageDraw.Draw(image)
# Color schemes based on genre
color_schemes = {
"Fantasy": [(138, 43, 226), (75, 0, 130), (72, 61, 139), (147, 112, 219)],
"Sci-Fi": [(0, 191, 255), (30, 144, 255), (0, 100, 0), (50, 205, 50)],
"Mystery": [(25, 25, 112), (72, 61, 139), (105, 105, 105), (128, 128, 128)],
"Romance": [(255, 182, 193), (255, 105, 180), (219, 112, 147), (199, 21, 133)],
"Adventure": [(255, 140, 0), (255, 165, 0), (218, 165, 32), (184, 134, 11)],
"Horror": [(139, 0, 0), (128, 0, 0), (105, 105, 105), (47, 79, 79)],
"Comedy": [(255, 215, 0), (255, 165, 0), (255, 192, 203), (255, 20, 147)]
}
colors = color_schemes.get(genre, color_schemes["Fantasy"])
# Create gradient background
for y in range(height):
for x in range(width):
# Create complex gradient patterns
color_index = int((x + y + random.randint(-20, 20)) / 100) % len(colors)
base_color = colors[color_index]
# Add some variation
r = max(0, min(255, base_color[0] + random.randint(-30, 30)))
g = max(0, min(255, base_color[1] + random.randint(-30, 30)))
b = max(0, min(255, base_color[2] + random.randint(-30, 30)))
draw.point((x, y), (r, g, b))
# Add geometric patterns based on genre
if genre == "Fantasy":
# Draw magical circles
for _ in range(5):
x = random.randint(50, width-50)
y = random.randint(50, height-50)
radius = random.randint(20, 80)
draw.ellipse([x-radius, y-radius, x+radius, y+radius],
outline=(255, 215, 0), width=3)
elif genre == "Sci-Fi":
# Draw tech patterns
for _ in range(10):
x1 = random.randint(0, width)
y1 = random.randint(0, height)
x2 = random.randint(0, width)
y2 = random.randint(0, height)
draw.line([x1, y1, x2, y2], fill=(0, 255, 255), width=2)
# Add title text
try:
font_size = 24
# Try to use a better font, fall back to default
try:
font = ImageFont.truetype("arial.ttf", font_size)
except:
font = ImageFont.load_default()
# Add protagonist name
text_bbox = draw.textbbox((0, 0), protagonist, font=font)
text_width = text_bbox[2] - text_bbox[0]
text_x = (width - text_width) // 2
text_y = height - 60
# Add text with outline
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if dx != 0 or dy != 0:
draw.text((text_x + dx, text_y + dy), protagonist, font=font, fill=(0, 0, 0))
draw.text((text_x, text_y), protagonist, font=font, fill=(255, 255, 255))
# Add setting
setting_bbox = draw.textbbox((0, 0), setting, font=font)
setting_width = setting_bbox[2] - setting_bbox[0]
setting_x = (width - setting_width) // 2
setting_y = 30
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if dx != 0 or dy != 0:
draw.text((setting_x + dx, setting_y + dy), setting, font=font, fill=(0, 0, 0))
draw.text((setting_x, setting_y), setting, font=font, fill=(255, 255, 255))
except:
pass # Skip text if font issues
return image
# Story templates (keeping the same as before)
STORY_TEMPLATES = {
"Fantasy": [
"In the mystical realm of {setting}, {protagonist} discovered an ancient artifact that pulsed with magical energy. As whispers of forgotten spells filled the air, they realized their destiny was far greater than they ever imagined. Dragons soared overhead while mystical creatures watched from the shadows, all waiting to see if {protagonist} would embrace their newfound power or be consumed by it.",
"The {setting} had always been a place of wonder, but when {protagonist} stepped through the shimmering portal, everything changed. Magic flowed through their veins as they encountered beings of legend. With a prophecy to fulfill and dark forces gathering, {protagonist} must master ancient arts before the realm falls to eternal darkness."
],
"Sci-Fi": [
"Captain {protagonist} gazed at the vast expanse of {setting} through the viewport. The year 2387 had brought humanity to the stars, but nothing could have prepared them for what they found. An alien signal, a mysterious technology, and a discovery that would rewrite the laws of physics. {protagonist} knew that first contact would change everything.",
"In the depths of {setting}, {protagonist} uncovered technology that defied explanation. Quantum computers hummed with alien algorithms while holographic displays showed star maps of unknown galaxies. As reality itself began to shift, {protagonist} realized they were part of an experiment that spanned millennia."
],
"Mystery": [
"Detective {protagonist} arrived at {setting} as fog rolled through the streets. The crime scene was unlike anything they'd encountered - a locked room, no witnesses, and only a cryptic symbol carved into the wall. As {protagonist} pieced together the clues, they discovered a conspiracy that reached the highest levels of power.",
"The {setting} held secrets that {protagonist} was determined to uncover. Each clue led to more questions, each witness told a different story. In a web of lies and deception, {protagonist} raced against time to solve a mystery that threatened to destroy everything they held dear."
],
"Adventure": [
"{protagonist} clutched the weathered map as they ventured into {setting}. Legend spoke of a treasure beyond imagination, but the path was fraught with danger. Ancient traps, rival treasure hunters, and the unforgiving environment tested every skill {protagonist} possessed. Victory would mean glory, but failure meant certain doom.",
"The call of adventure echoed through {setting} as {protagonist} embarked on a journey that would test their limits. With only their wits and courage, they faced challenges that seemed impossible. Each step forward brought new dangers, but also the promise of discoveries that would change their life forever."
],
"Romance": [
"In the enchanting {setting}, {protagonist} never expected to find love. But when fate intervened, bringing two hearts together against all odds, magic seemed to fill the air. Through misunderstandings and moments of pure joy, {protagonist} discovered that true love was worth fighting for, no matter the obstacles.",
"The {setting} became the backdrop for an unexpected romance as {protagonist} met someone who challenged everything they believed about love. Through stolen glances and heartfelt conversations, a connection formed that transcended all boundaries."
],
"Horror": [
"The {setting} was supposed to be abandoned, but {protagonist} could feel eyes watching from the shadows. Strange sounds echoed through empty corridors while an oppressive darkness seemed to consume all light. As reality began to blur with nightmare, {protagonist} realized some places are abandoned for very good reasons.",
"Something was terribly wrong in {setting}. {protagonist} felt it the moment they arrived - a creeping dread that seemed to seep from the very walls. As night fell and the true horror revealed itself, {protagonist} discovered that some evils are better left undisturbed."
],
"Comedy": [
"Everything that could go wrong did go wrong when {protagonist} found themselves in {setting}. From mistaken identities to slapstick mishaps, their simple plan had turned into a comedy of errors. With each attempt to fix things only making them worse, {protagonist} learned that sometimes you just have to laugh at life's absurdities.",
"The {setting} was the perfect place for chaos, and {protagonist} seemed to be a magnet for it. Ridiculous situations, eccentric characters, and perfectly timed misunderstandings created a whirlwind of hilarity that {protagonist} would never forget."
]
}
def generate_story(genre, protagonist, setting):
"""Generate a story based on the selected parameters"""
templates = STORY_TEMPLATES.get(genre, STORY_TEMPLATES["Fantasy"])
template = random.choice(templates)
return template.format(protagonist=protagonist, setting=setting)
def create_image_prompt(protagonist, setting, genre, art_style):
"""Create optimized prompt for image generation"""
prompts = {
"Fantasy": f"fantasy art of {protagonist} in {setting}, magical, ethereal, detailed artwork",
"Sci-Fi": f"sci-fi art of {protagonist} in {setting}, futuristic, technology, space art",
"Mystery": f"mysterious scene with {protagonist} in {setting}, noir style, detective",
"Romance": f"romantic art of {protagonist} in {setting}, beautiful, soft lighting",
"Adventure": f"adventure art of {protagonist} in {setting}, action, dynamic scene",
"Horror": f"dark art of {setting}, horror atmosphere, mysterious figure, gothic",
"Comedy": f"cheerful art of {protagonist} in {setting}, bright colors, happy scene"
}
base_prompt = prompts.get(genre, f"{protagonist} in {setting}")
return f"{base_prompt}, {art_style.lower()}, high quality, detailed"
# Main app
col1, col2 = st.columns([1, 1])
if st.button("✨ Generate Story & Art", type="primary"):
with st.spinner("🎭 Crafting your story..."):
story = generate_story(genre, protagonist, setting)
time.sleep(1)
with col1:
st.markdown("### πŸ“– Your Story")
st.markdown(f'<div class="story-container">{story}</div>', unsafe_allow_html=True)
# Story stats
word_count = len(story.split())
reading_time = max(1, word_count // 200)
st.markdown(f"""
**Story Stats:**
- **Words:** {word_count}
- **Reading time:** {reading_time} min
- **Genre:** {genre}
- **Setting:** {setting}
""")
# Download button
st.download_button(
label="πŸ“₯ Download Story",
data=story,
file_name=f"{protagonist.replace(' ', '_')}_story.txt",
mime="text/plain"
)
with col2:
st.markdown("### 🎨 AI Generated Artwork")
image_prompt = create_image_prompt(protagonist, setting, genre, art_style)
with st.spinner("🎨 Generating AI artwork..."):
# Try Pollinations AI first (free, no API key)
generated_image, success = generate_image_pollinations(image_prompt)
if not success or generated_image is None:
st.info("🎨 Using procedural art generation...")
generated_image = generate_procedural_art(image_prompt, protagonist, setting, genre, art_style)
st.session_state.generated_image = generated_image
if generated_image:
st.markdown('<div class="image-container">', unsafe_allow_html=True)
st.image(generated_image, caption=f"Generated: {protagonist} in {setting}", use_column_width=True)
st.markdown('</div>', unsafe_allow_html=True)
# Image download
img_buffer = io.BytesIO()
generated_image.save(img_buffer, format="PNG")
img_buffer.seek(0)
st.download_button(
label="πŸ–ΌοΈ Download Image",
data=img_buffer.getvalue(),
file_name=f"{protagonist.replace(' ', '_')}_artwork.png",
mime="image/png"
)
with st.expander("πŸ” Image Details"):
st.markdown(f"**Prompt:** {image_prompt}")
st.markdown(f"**Style:** {art_style}")
st.markdown(f"**Method:** {'Pollinations AI' if success else 'Procedural Art'}")
# Show previous image if available
elif st.session_state.generated_image:
col1, col2 = st.columns([1, 1])
with col2:
st.markdown("### 🎨 Previous Generated Image")
st.image(st.session_state.generated_image, caption="Previously Generated Artwork", use_column_width=True)
# Action buttons
st.markdown("---")
col3, col4, col5 = st.columns(3)
with col3:
if st.button("πŸ”„ New Story Only"):
st.rerun()
with col4:
if st.button("🎨 New Artwork"):
if 'generated_image' in st.session_state:
# Regenerate with different seed
image_prompt = create_image_prompt(protagonist, setting, genre, art_style)
with st.spinner("🎨 Creating new artwork..."):
generated_image, success = generate_image_pollinations(image_prompt)
if not success:
generated_image = generate_procedural_art(image_prompt, protagonist, setting, genre, art_style)
st.session_state.generated_image = generated_image
st.rerun()
with col5:
if st.button("🎲 Surprise Me!"):
st.rerun()
# Sidebar info
st.sidebar.markdown("---")
st.sidebar.markdown("### πŸš€ About StoryVision AI")
st.sidebar.info("""
🎯 **Features:**
- βœ… Real AI image generation
- βœ… No API keys required
- βœ… Always works offline backup
- βœ… Download stories & images
πŸ› οΈ **Tech Stack:**
- Streamlit
- Pollinations.ai (free)
- Python PIL
- Procedural art generation
🎨 **Art Methods:**
1. Pollinations AI (primary)
2. Procedural art (backup)
""")
# Footer
st.markdown("---")
st.markdown("""
<div style="text-align: center; color: #666; padding: 2rem;">
<p>🌟 <strong>StoryVision AI</strong> - Reliable AI artwork generation!</p>
<p>Made with ❀️ | Always works, no API keys needed</p>
</div>
""", unsafe_allow_html=True)