import gradio as gr from openai import OpenAI from dotenv import load_dotenv import os import requests import base64 from PIL import Image from io import BytesIO load_dotenv() # Initialize OpenAI client client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) # System prompt (to be updated) SYSTEM_PROMPT = """ You are tasked with enhancing user prompts to generate clear, detailed, and creative descriptions for a sticker creation AI. The final prompt should be imaginative, visually rich, and aligned with the goal of producing a cute, stylized, and highly personalized sticker based on the user's input. Instructions: Visual Clarity: The enhanced prompt must provide clear visual details that can be directly interpreted by the image generation model. Break down and elaborate on specific elements of the scene, object, or character based on the user input. Example: If the user says "A girl with pink hair," elaborate by adding features like "short wavy pink hair with soft, pastel hues." Style & Theme: Emphasize that the final output should reflect a cute, playful, and approachable style. Add terms like "adorable," "cartoonish," "sticker-friendly," or "chibi-like" to guide the output to a lighter, cuter aesthetic. Include styling prompts like “minimalistic lines,” “soft shading,” and “vibrant yet soothing colors.” Personalization: If a reference or context is given, enhance it to make the sticker feel personalized. Add context-appropriate descriptors like “wearing a cozy blue hoodie,” “soft pink blush on cheeks,” or “a playful expression.” Expression & Pose: Where applicable, refine prompts with suggestions about facial expressions or body language. For example, “Smiling softly with big sparkling eyes” or “A cute wink and a slight tilt of the head.” Background & Accessories: Optionally suggest simple, complementary backgrounds or accessories, depending on user input. For instance, "A light pastel background with small, floating hearts" or "Holding a tiny, sparkling star." Colors: Emphasize the color scheme based on the user's description, making sure it's consistent with a cute, playful style. Use descriptors like “soft pastels,” “bright and cheerful,” or “warm and friendly hues” to set the mood. Avoid Overcomplication: Keep the descriptions short enough to be concise and not overly complex, as the output should retain a sticker-friendly quality. Avoid unnecessary details that could clutter the design. Tone and Language: The tone should be light, imaginative, and fun, matching the playful nature of stickers. Example: User Input: "A girl with pink hair wearing a hoodie." Enhanced Prompt: "An adorable girl with short, wavy pink hair in soft pastel hues, wearing a cozy light blue hoodie. She has a sweet smile with big, sparkling eyes, and a playful expression. The sticker style is cartoonish with minimalistic lines and soft shading. The background is a simple light pastel color with small floating hearts, creating a cute and inviting look." """ # Function to enhance the user's prompt def enhance_prompt(user_prompt) -> str: completion = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user_prompt} ] ) ep = completion.choices[0].message.content print('Enhanced Prompt:', ep) return ep # Function to generate images using the selected models def generate_images(user_prompt, selected_models): enhanced_prompt = enhance_prompt(user_prompt) images = [] headers = { "Authorization": f"Bearer {os.getenv('AIMLAPI_API_KEY')}", } for model in selected_models: try: payload = { "prompt": enhanced_prompt, "model": model, } response = requests.post( "https://api.aimlapi.com/images/generations", headers=headers, json=payload ) if response.status_code == 201: response_json = response.json() print("Response JSON:", response_json) # Handle OpenAI models differently (Aspect 2) if model in ["dall-e-3", "dall-e-2"]: if 'data' in response_json and 'url' in response_json['data'][0]: image_url = response_json['data'][0]['url'] image_response = requests.get(image_url) image = Image.open(BytesIO(image_response.content)) images.append(image) else: print(f"No URL found for model {model}") else: # Handle other models (Aspect 1) if 'images' in response_json and 'url' in response_json['images'][0]: image_url = response_json['images'][0]['url'] image_response = requests.get(image_url) image = Image.open(BytesIO(image_response.content)) images.append(image) else: print(f"No URL found for model {model}") else: print(f"Error with model {model}: {response.text}") except Exception as e: print(f"Exception occurred with model {model}: {e}") continue return images # List of available image generation models model_list = [ "stable-diffusion-v35-large", "flux-pro/v1.1", "dall-e-3", "stable-diffusion-v3-medium", "runwayml/stable-diffusion-v1-5", "stabilityai/stable-diffusion-xl-base-1.0", "stabilityai/stable-diffusion-2-1", "SG161222/Realistic_Vision_V3.0_VAE", "prompthero/openjourney", "wavymulder/Analog-Diffusion", "flux-pro", "flux-realism", "dall-e-2", ] # Examples data as a list of dictionaries examples = [ { 'user_prompt': "An adorable kitten playing with a ball of yarn", 'enhanced_prompt': "An adorable, fluffy kitten with big, sparkling eyes and playful whiskers, tumbling around with a vibrant ball of yarn. The kitten's fur is a soft blend of warm creams and greys, giving it a cuddly, huggable appearance. Its expression is full of joy and mischief, with a tiny pink tongue playfully sticking out. The ball of yarn is a bright and cheerful red, unraveling with dynamic loops and curls. The style is chibi-like and sticker-friendly, with minimalistic lines and gentle shading. The background is a simple, soft pastel color with tiny floating paw prints, enhancing the cute and playful theme.", 'generated_image': "./generated-images/cat-and-yarn.jpeg", 'ai_model': "dall-e-3" }, { 'user_prompt': "A cutesy cat eating ice cream under a rainbow", 'enhanced_prompt': "A playful, cartoonish cat with big, sparkling eyes and soft, rounded features, happily licking a colorful ice cream cone. The cat has fluffy fur, pastel colors—like soft cream, peach, or light gray—and tiny pink blush on its cheeks for added charm. It sits contentedly under a bright, arched rainbow with soft, blended hues. Small, floating sparkles and tiny hearts surround the cat and ice cream to add a touch of magic. The ice cream cone has multiple scoops in fun, bright colors like pink, blue, and mint green, making the whole scene feel adorable and sweet, perfect for a cute sticker!", 'generated_image': "./generated-images/cat-and-icecream.jpeg", 'ai_model': "dall-e-3" }, { 'user_prompt': "A girl with short pink+black hair wearing a pink shirt.", 'enhanced_prompt': "An adorable chibi-style character with a soft, cozy look. She has a short, wavy bob hairstyle in gradient shades of gray with delicate highlights that sparkle. Her large, expressive brown eyes have a gentle shine, and her cheeks are lightly blushed, adding a touch of warmth. She wears an off-shoulder, cream-colored sweater, giving a relaxed and comforting vibe. The background is a soft pastel gradient in warm beige and cream tones, decorated with small, floating sparkles and star shapes for a magical effect. The overall style is cute, minimalist, and sticker-friendly.", 'generated_image': "./generated-images/girl-with-white-grey-hair.png", 'ai_model': "dall-e-3" } ] # Function to create an HTML table for the examples def create_examples_table(examples): html = '' # Table headers html += '' html += '' html += '' html += '' html += '' html += '' # Table rows for example in examples: html += '' html += f'' html += f'' # Read and encode the image try: with open(example["generated_image"], "rb") as image_file: image_data = image_file.read() encoded_image = base64.b64encode(image_data).decode('utf-8') html += f'' except Exception as e: print(f"Error loading image {example['generated_image']}: {e}") html += '' html += f'' html += '' html += '
User PromptEnhanced PromptGenerated ImageAI Model
{example["user_prompt"]}{example["enhanced_prompt"]}Generated ImageImage not available{example["ai_model"]}
' return html # Gradio Interface with styling and functionality with gr.Blocks( css=""" #download { height: 118px; } .slider .inner { width: 5px; background: #FFF; } .viewport { aspect-ratio: 4/3; } .tabs button.selected { font-size: 20px !important; color: crimson !important; } h1, h2, h3 { text-align: center; display: block; } .md_feedback li { margin-bottom: 0px !important; } """, ) as demo: gr.Markdown(""" # Let's Generate Cutesy AI Sticker!

badge-github-stars social social
Please consider starring the GitHub Repo if you find this useful! """) with gr.Tabs(elem_classes=["tabs"]): with gr.TabItem("Generate Stickers"): with gr.Row(): with gr.Column(scale=1): # Model selection selected_models = gr.CheckboxGroup( choices=model_list, label="Select Image Generation Models", value=["dall-e-3"] ) # User prompt input user_prompt = gr.Textbox( placeholder="A girl with short pink hair wearing an oversize hoodie...", label="Enter your prompt here" ) seed = gr.Number( label="Seed (optional)", value=0, minimum=0, maximum=999999999, ) # Generate and Reset buttons with gr.Row(): generate_button = gr.Button("Generate Images", variant="primary") reset_button = gr.Button("Reset") with gr.Column(scale=2): # Outputs image_outputs = gr.Gallery( label="Generated Images", elem_id="gallery", columns=[3], rows=[1], ) # Event bindings def on_click(user_prompt, selected_models): images = generate_images(user_prompt, selected_models) return images generate_button.click( fn=on_click, inputs=[user_prompt, selected_models], outputs=image_outputs ) reset_button.click( fn=lambda: ("", []), inputs=[], outputs=[user_prompt, selected_models], queue=False, ) with gr.TabItem("Examples"): # Create and display the examples table examples_html = create_examples_table(examples) gr.HTML(examples_html) # Launch the Gradio app demo.launch(share=True)