import streamlit as st import requests from PIL import Image import io import base64 from datetime import datetime import time # Configure page st.set_page_config( page_title="Holiday Image Creator", page_icon="🎄", layout="wide" ) def generate_image_with_openai(prompt, api_key, size="1024x1024"): """Generate image using OpenAI DALL-E API""" try: headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } data = { "model": "dall-e-3", "prompt": prompt, "n": 1, "size": size, "quality": "standard" } response = requests.post( "https://api.openai.com/v1/images/generations", headers=headers, json=data, timeout=60 ) if response.status_code == 200: result = response.json() image_url = result['data'][0]['url'] # Download the image img_response = requests.get(image_url, timeout=30) if img_response.status_code == 200: return Image.open(io.BytesIO(img_response.content)) else: st.error("Failed to download generated image") return None else: error_msg = response.json().get('error', {}).get('message', 'Unknown error') st.error(f"API Error: {error_msg}") return None except requests.exceptions.Timeout: st.error("Request timed out. Please try again.") return None except Exception as e: st.error(f"Error generating image: {str(e)}") return None def create_download_link(image, filename): """Create download link for image""" buffered = io.BytesIO() image.save(buffered, format="PNG") img_str = base64.b64encode(buffered.getvalue()).decode() href = f'Download Image' return href def main(): # Sidebar for API configuration st.sidebar.header("🔑 API Configuration") api_key = st.sidebar.text_input( "Enter your OpenAI API Key", type="password", help="Get your API key from https://platform.openai.com/account/api-keys" ) st.sidebar.markdown("---") st.sidebar.markdown("### 📝 Instructions") st.sidebar.markdown(""" 1. Enter your OpenAI API key above 2. Choose a holiday theme 3. Customize your image details 4. Generate and download your image """) st.sidebar.markdown("### 🎨 Image Formats") image_size = st.sidebar.selectbox( "Image Size", ["1024x1024", "1792x1024", "1024x1792"], help="Square, Landscape, or Portrait format" ) # Main content st.title("🎄 Holiday Image Creator") st.markdown("Create beautiful holiday-themed images for postcards and emails!") # Check if API key is provided if not api_key: st.warning("⚠️ Please enter your OpenAI API key in the sidebar to get started.") st.info("You can get your API key from [OpenAI Platform](https://platform.openai.com/account/api-keys)") return # Holiday theme selection col1, col2 = st.columns([2, 1]) with col1: st.subheader("🎊 Choose Your Holiday Theme") holiday_themes = { "Christmas": "Christmas tree, Santa Claus, snow, presents, red and green colors", "New Year": "Fireworks, champagne, countdown, golden colors, celebration", "Thanksgiving": "Turkey, autumn leaves, pumpkins, warm colors, family gathering", "Halloween": "Pumpkins, spooky decorations, orange and black colors, trick or treat", "Easter": "Easter eggs, bunny, spring flowers, pastel colors, renewal", "Valentine's Day": "Hearts, roses, pink and red colors, romantic theme", "Fourth of July": "American flag, fireworks, red white and blue, patriotic", "Hanukkah": "Menorah, dreidel, blue and white colors, Jewish celebration", "Winter Holidays": "Snow, winter wonderland, cozy atmosphere, warm lights" } selected_theme = st.selectbox("Select Holiday Theme:", list(holiday_themes.keys())) # Custom prompt input st.subheader("✨ Customize Your Image") custom_details = st.text_area( "Additional Details (optional)", placeholder="e.g., 'with a cute dog wearing a Santa hat', 'in watercolor style', 'vintage postcard design'", help="Add specific elements, styles, or details to your image" ) # Style options style_options = [ "Realistic", "Cartoon/Illustrated", "Watercolor", "Vintage Postcard", "Modern Minimalist", "Hand-drawn", "Digital Art", "Oil Painting" ] selected_style = st.selectbox("Art Style:", style_options) with col2: st.subheader("🖼️ Preview Settings") # Format selection format_type = st.radio( "Image Purpose:", ["Postcard", "Email Header", "Social Media Post", "Custom"] ) # Quality selection if format_type == "Email Header": recommended_size = "1792x1024" elif format_type == "Social Media Post": recommended_size = "1024x1024" else: recommended_size = image_size st.info(f"💡 Recommended size for {format_type}: {recommended_size}") # Generate button st.markdown("---") if st.button("🎨 Generate Holiday Image", type="primary"): if not api_key.strip(): st.error("Please enter your OpenAI API key first!") return # Construct the prompt base_prompt = holiday_themes[selected_theme] prompt = f"Create a beautiful {selected_theme} themed image with {base_prompt}" if custom_details: prompt += f", {custom_details}" prompt += f", in {selected_style.lower()} style" if format_type == "Postcard": prompt += ", suitable for a holiday postcard" elif format_type == "Email Header": prompt += ", suitable for an email header banner" elif format_type == "Social Media Post": prompt += ", suitable for social media sharing" prompt += ", high quality, festive and cheerful" # Show the prompt being used with st.expander("🔍 View Generated Prompt"): st.code(prompt) # Generate image with st.spinner("🎨 Creating your holiday image... This may take 10-30 seconds."): try: generated_image = generate_image_with_openai(prompt, api_key, image_size) if generated_image: st.success("✅ Image generated successfully!") # Display the image st.subheader("🖼️ Your Holiday Image") st.image(generated_image, caption=f"{selected_theme} - {selected_style}", use_column_width=True) # Download section st.subheader("💾 Download Your Image") # Generate filename timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"holiday_{selected_theme.lower().replace(' ', '_')}_{timestamp}.png" # Create download button buffered = io.BytesIO() generated_image.save(buffered, format="PNG") st.download_button( label="📥 Download PNG Image", data=buffered.getvalue(), file_name=filename, mime="image/png" ) # Image info st.info(f"📊 Image size: {generated_image.size[0]} x {generated_image.size[1]} pixels") # Regenerate option if st.button("🔄 Generate Another Image"): st.experimental_rerun() except Exception as e: st.error(f"❌ Error: {str(e)}") st.error("Please check your API key and try again.") # Footer st.markdown("---") st.markdown( """