Spaces:
Sleeping
Sleeping
File size: 17,188 Bytes
ac96909 21e55c7 8c6369e e816734 8c6369e e816734 ac96909 21e55c7 ac96909 8c6369e ac96909 8c6369e ac96909 e816734 ac96909 21e55c7 ac96909 8c6369e ac96909 e816734 8c6369e e816734 8c6369e e816734 8c6369e e816734 8c6369e e816734 8c6369e e816734 8c6369e e816734 8c6369e e816734 21e55c7 ac96909 21e55c7 ac96909 21e55c7 ac96909 21e55c7 ac96909 21e55c7 ac96909 21e55c7 ac96909 21e55c7 8c6369e e816734 8c6369e e816734 ac96909 21e55c7 ac96909 21e55c7 8c6369e ac96909 21e55c7 ac96909 21e55c7 ac96909 8c6369e 21e55c7 8c6369e 21e55c7 e816734 8c6369e 21e55c7 8c6369e e816734 8c6369e e816734 8c6369e ac96909 21e55c7 ac96909 21e55c7 8c6369e 21e55c7 e816734 8c6369e 21e55c7 8c6369e ac96909 21e55c7 ac96909 e816734 8c6369e ac96909 8c6369e ac96909 e816734 8c6369e e816734 8c6369e e816734 ac96909 21e55c7 e816734 21e55c7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | 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) |