Spaces:
Runtime error
Runtime error
File size: 2,341 Bytes
9d6c8f3 d9bb4ca 6740350 d9bb4ca d0a1850 d9bb4ca 9d6c8f3 d9bb4ca 9d6c8f3 6740350 d9bb4ca 9d6c8f3 d9bb4ca 6740350 d9bb4ca 6740350 d9bb4ca 6740350 9d6c8f3 d9bb4ca 9d6c8f3 d9bb4ca 6740350 9d6c8f3 d9bb4ca 6740350 9d6c8f3 d9bb4ca 9d6c8f3 d9bb4ca 9d6c8f3 6740350 d9bb4ca 9d6c8f3 6740350 |
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 |
import gradio as gr
import torch
from diffusers import StableDiffusionPipeline
from datetime import datetime
from PIL import Image
# Load the model
model_id = "stabilityai/stable-diffusion-2"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
pipe = pipe.to("cpu")
# Keep image history
image_history = []
# Style templates
STYLE_TEMPLATES = {
"Photo": "highly detailed, realistic photo, natural lighting",
"Anime": "anime style, vibrant colors, line art, cel shading",
"Oil Painting": "oil painting style, brush strokes, classic fine art"
}
def enhance_prompt(prompt, style):
style_suffix = STYLE_TEMPLATES.get(style, "")
return f"{prompt}, {style_suffix}"
def generate_image(prompt, style, uploaded_image):
if not prompt.strip():
return None, image_history
final_prompt = enhance_prompt(prompt, style)
# Currently not using uploaded_image β could be used with img2img later
image = pipe(final_prompt).images[0]
# Add to history
timestamp = datetime.now().strftime("%H:%M:%S")
caption = f"{style} - {timestamp}"
image_history.append((image, caption))
return image, image_history[-5:]
def clear_history():
global image_history
image_history = []
return None, []
# Gradio UI
with gr.Blocks() as demo:
gr.Markdown("## π¨ Realistic Text-to-Image Generator")
gr.Markdown("Powered by **Stable Diffusion 2** | Now with style presets, prompt enhancer, image history, and optional image upload!")
with gr.Row():
prompt = gr.Textbox(label="Enter your prompt", placeholder="e.g., A golden retriever in the snow")
style = gr.Dropdown(["Photo", "Anime", "Oil Painting"], label="Choose Style", value="Photo")
uploaded_image = gr.Image(label="Upload Optional Image (future use)", type="pil", tool=None)
with gr.Row():
generate_btn = gr.Button("π¨ Generate Image")
clear_btn = gr.Button("π§Ή Clear History")
output_image = gr.Image(label="Generated Image", type="pil")
gallery = gr.Gallery(label="πΌοΈ Image History (last 5)", columns=3, object_fit="contain")
generate_btn.click(generate_image, inputs=[prompt, style, uploaded_image], outputs=[output_image, gallery])
clear_btn.click(clear_history, outputs=[output_image, gallery])
demo.launch() |