Spaces:
Sleeping
Sleeping
import gradio as gr | |
import torch | |
from diffusers import StableDiffusionPipeline, DDIMScheduler | |
from PIL import Image | |
device = "cuda" if torch.cuda.is_available() else "cpu" | |
# Load SD model (use SD1.5 or SDXL-based) | |
model_id = "stabilityai/stable-diffusion-2-1" | |
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16 if device == "cuda" else torch.float32) | |
pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config) | |
pipe = pipe.to(device) | |
# Preset styles | |
styles = { | |
"Pixar": "pixar style portrait of", | |
"Anime": "anime style portrait of", | |
"Cyberpunk": "cyberpunk futuristic avatar of", | |
"Disney": "disney movie character of", | |
"Sketch": "pencil sketch portrait of", | |
"Astronaut": "realistic astronaut with helmet, portrait of" | |
} | |
def generate_avatar(image, style): | |
if image is None: | |
return None | |
# Preprocess image (convert to prompt-only for simplicity) | |
base_prompt = styles[style] | |
prompt = f"{base_prompt} a person" | |
image = pipe(prompt=prompt, num_inference_steps=30, guidance_scale=7.5).images[0] | |
return image | |
with gr.Blocks() as demo: | |
gr.Markdown("## π¨ Stable Diffusion Avatar Generator with Preset Styles") | |
with gr.Row(): | |
with gr.Column(): | |
image_input = gr.Image(label="Upload your photo", type="pil", sources=["upload", "webcam"]) | |
style_selector = gr.Radio(choices=list(styles.keys()), label="Choose a style", value="Anime") | |
generate_btn = gr.Button("Generate Avatar") | |
with gr.Column(): | |
output_image = gr.Image(label="Generated Avatar") | |
generate_btn.click(fn=generate_avatar, inputs=[image_input, style_selector], outputs=output_image) | |
demo.launch() | |