File size: 1,732 Bytes
2d37af9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()