kevalfst commited on
Commit
c4ccad7
·
verified ·
1 Parent(s): 868b112

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -123
app.py CHANGED
@@ -1,138 +1,88 @@
1
- import torch
2
  import gradio as gr
3
  import numpy as np
4
  import random
 
 
5
 
6
- from diffusers import (
7
- StableDiffusionPipeline,
8
- StableDiffusionInstructPix2PixPipeline,
9
- StableVideoDiffusionPipeline,
10
- WanPipeline,
11
- )
12
- from diffusers.utils import export_to_video, load_image
13
-
14
- # Force CPU mode
15
- device = "cpu"
16
- dtype = torch.float32
17
- MAX_SEED = np.iinfo(np.int32).max
18
-
19
- # Global pipeline holders
20
- TXT2IMG_PIPE = None
21
- IMG2IMG_PIPE = None
22
- TXT2VID_PIPE = None
23
- IMG2VID_PIPE = None
24
 
25
- # Helper to load models
26
- def make_pipe(cls, model_id, **kwargs):
27
- pipe = cls.from_pretrained(model_id, torch_dtype=dtype, **kwargs)
28
- pipe.to(device)
29
- return pipe
30
 
31
- # Text Image
32
- def generate_image_from_text(prompt, seed, randomize_seed):
33
- global TXT2IMG_PIPE
34
- if TXT2IMG_PIPE is None:
35
- TXT2IMG_PIPE = make_pipe(StableDiffusionPipeline, "stabilityai/stable-diffusion-2-1-base")
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
- generator = torch.manual_seed(seed)
39
- image = TXT2IMG_PIPE(prompt=prompt, num_inference_steps=20, generator=generator).images[0]
40
- return image, seed
41
 
42
- # Image Image
43
- def generate_image_from_image_and_prompt(image, prompt, seed, randomize_seed):
44
- global IMG2IMG_PIPE
45
- if IMG2IMG_PIPE is None:
46
- IMG2IMG_PIPE = make_pipe(StableDiffusionInstructPix2PixPipeline, "timbrooks/instruct-pix2pix")
47
- if randomize_seed:
48
- seed = random.randint(0, MAX_SEED)
49
- generator = torch.manual_seed(seed)
50
- out = IMG2IMG_PIPE(prompt=prompt, image=image, num_inference_steps=8, generator=generator)
51
- return out.images[0], seed
52
 
53
- # Text → Video
54
- def generate_video_from_text(prompt, seed, randomize_seed):
55
- global TXT2VID_PIPE
56
- if TXT2VID_PIPE is None:
57
- TXT2VID_PIPE = make_pipe(WanPipeline, "Wan-AI/Wan2.1-T2V-1.3B-Diffusers")
58
- if randomize_seed:
59
- seed = random.randint(0, MAX_SEED)
60
- generator = torch.manual_seed(seed)
61
- frames = TXT2VID_PIPE(prompt=prompt, num_frames=12, generator=generator).frames[0]
62
- return export_to_video(frames, "/tmp/wan_video.mp4", fps=8), seed
 
 
63
 
64
- # Image Video
65
- def generate_video_from_image(image, seed, randomize_seed):
66
- global IMG2VID_PIPE
67
- if IMG2VID_PIPE is None:
68
- IMG2VID_PIPE = make_pipe(
69
- StableVideoDiffusionPipeline,
70
- "stabilityai/stable-video-diffusion-img2vid-xt"
71
- )
72
  if randomize_seed:
73
  seed = random.randint(0, MAX_SEED)
74
- generator = torch.manual_seed(seed)
75
- image = load_image(image).resize((512, 288))
76
- frames = IMG2VID_PIPE(image=image, num_inference_steps=16, generator=generator).frames[0]
77
- return export_to_video(frames, "/tmp/svd_video.mp4", fps=8), seed
 
 
 
 
 
 
 
 
 
 
78
 
79
- # Gradio Interface
80
  with gr.Blocks() as demo:
81
- gr.Markdown("# 🧠 AI Playground – Text & Image Image & Video")
82
-
83
- with gr.Tabs():
84
- # Text Image
85
- with gr.Tab("Text Image"):
86
- prompt_txt = gr.Textbox(label="Prompt")
87
- btn_txt2img = gr.Button("Generate")
88
- result_img = gr.Image()
89
- seed_txt = gr.Slider(0, MAX_SEED, value=42, label="Seed")
90
- rand_txt = gr.Checkbox(label="Randomize seed", value=True)
91
- btn_txt2img.click(
92
- generate_image_from_text,
93
- inputs=[prompt_txt, seed_txt, rand_txt],
94
- outputs=[result_img, seed_txt]
95
- )
96
-
97
- # Image → Image
98
- with gr.Tab("Image → Image"):
99
- image_in = gr.Image(label="Input Image")
100
- prompt_img = gr.Textbox(label="Edit Prompt")
101
- btn_img2img = gr.Button("Generate")
102
- result_img2 = gr.Image()
103
- seed_img = gr.Slider(0, MAX_SEED, value=123, label="Seed")
104
- rand_img = gr.Checkbox(label="Randomize seed", value=True)
105
- btn_img2img.click(
106
- generate_image_from_image_and_prompt,
107
- inputs=[image_in, prompt_img, seed_img, rand_img],
108
- outputs=[result_img2, seed_img]
109
- )
110
-
111
- # Text → Video
112
- with gr.Tab("Text → Video"):
113
- prompt_vid = gr.Textbox(label="Prompt")
114
- btn_txt2vid = gr.Button("Generate")
115
- result_vid = gr.Video()
116
- seed_vid = gr.Slider(0, MAX_SEED, value=555, label="Seed")
117
- rand_vid = gr.Checkbox(label="Randomize seed", value=True)
118
- btn_txt2vid.click(
119
- generate_video_from_text,
120
- inputs=[prompt_vid, seed_vid, rand_vid],
121
- outputs=[result_vid, seed_vid]
122
- )
123
 
124
- # Image → Video
125
- with gr.Tab("Image → Video"):
126
- image_vid = gr.Image(label="Input Image")
127
- btn_img2vid = gr.Button("Animate")
128
- result_vid2 = gr.Video()
129
- seed_vid2 = gr.Slider(0, MAX_SEED, value=999, label="Seed")
130
- rand_vid2 = gr.Checkbox(label="Randomize seed", value=True)
131
- btn_img2vid.click(
132
- generate_video_from_image,
133
- inputs=[image_vid, seed_vid2, rand_vid2],
134
- outputs=[result_vid2, seed_vid2]
135
- )
136
 
137
- demo.queue()
138
- demo.launch(show_error=True)
 
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
+ import torch
5
+ from diffusers import DiffusionPipeline
6
 
7
+ # Define available models and their corresponding Hugging Face repositories
8
+ MODEL_REPOS = {
9
+ "Stable Diffusion XL Base 1.0": "stabilityai/stable-diffusion-xl-base-1.0",
10
+ "SDXL-Turbo": "stabilityai/sdxl-turbo",
11
+ "Playground v2 1024px Aesthetic": "playgroundai/playground-v2-1024px-aesthetic",
12
+ "Segmind Vega": "segmind/Segmind-Vega",
13
+ "SSD-1B": "segmind/SSD-1B",
14
+ "Kandinsky 3": "kandinsky-community/kandinsky-3",
15
+ "PixArt-LCM-XL-2-1024-MS": "PixArt-alpha/PixArt-LCM-XL-2-1024-MS",
16
+ "BLIP Diffusion": "salesforce/blipdiffusion",
17
+ "Muse-512-Finetuned": "amused/muse-512-finetuned",
18
+ "Flux 1 Dev": "black-forest-labs/FLUX.1-dev"
19
+ }
 
 
 
 
 
20
 
21
+ # Set device
22
+ device = "cuda" if torch.cuda.is_available() else "cpu"
23
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
 
 
24
 
25
+ # Cache for loaded pipelines
26
+ loaded_pipelines = {}
 
 
 
 
 
 
 
 
27
 
28
+ # Maximum seed value
29
+ MAX_SEED = np.iinfo(np.int32).max
 
 
 
 
 
 
 
 
30
 
31
+ def load_pipeline(model_name):
32
+ """Load and cache the pipeline for the selected model."""
33
+ if model_name in loaded_pipelines:
34
+ return loaded_pipelines[model_name]
35
+ repo_id = MODEL_REPOS[model_name]
36
+ try:
37
+ pipeline = DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch_dtype)
38
+ pipeline.to(device)
39
+ loaded_pipelines[model_name] = pipeline
40
+ return pipeline
41
+ except Exception as e:
42
+ raise RuntimeError(f"Failed to load model '{model_name}': {e}")
43
 
44
+ def generate_image(prompt, model_name, width, height, guidance_scale, num_inference_steps, seed, randomize_seed):
45
+ """Generate an image using the selected model and parameters."""
 
 
 
 
 
 
46
  if randomize_seed:
47
  seed = random.randint(0, MAX_SEED)
48
+ generator = torch.Generator(device=device).manual_seed(seed)
49
+ pipeline = load_pipeline(model_name)
50
+ try:
51
+ image = pipeline(
52
+ prompt=prompt,
53
+ guidance_scale=guidance_scale,
54
+ num_inference_steps=num_inference_steps,
55
+ width=width,
56
+ height=height,
57
+ generator=generator
58
+ ).images[0]
59
+ return image, seed
60
+ except Exception as e:
61
+ raise RuntimeError(f"Image generation failed: {e}")
62
 
63
+ # Define the Gradio interface
64
  with gr.Blocks() as demo:
65
+ gr.Markdown("# 🖼️ Text-to-Image Generator with Multiple Models")
66
+ with gr.Row():
67
+ with gr.Column():
68
+ prompt = gr.Textbox(label="Prompt", placeholder="Enter your prompt here")
69
+ model_name = gr.Dropdown(label="Select Model", choices=list(MODEL_REPOS.keys()), value="Stable Diffusion XL Base 1.0")
70
+ width = gr.Slider(label="Width", minimum=256, maximum=1024, step=64, value=512)
71
+ height = gr.Slider(label="Height", minimum=256, maximum=1024, step=64, value=512)
72
+ guidance_scale = gr.Slider(label="Guidance Scale", minimum=1.0, maximum=20.0, step=0.5, value=7.5)
73
+ num_inference_steps = gr.Slider(label="Inference Steps", minimum=1, maximum=100, step=1, value=50)
74
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
75
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
76
+ generate_button = gr.Button("Generate Image")
77
+ with gr.Column():
78
+ output_image = gr.Image(label="Generated Image")
79
+ output_seed = gr.Textbox(label="Used Seed", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ generate_button.click(
82
+ fn=generate_image,
83
+ inputs=[prompt, model_name, width, height, guidance_scale, num_inference_steps, seed, randomize_seed],
84
+ outputs=[output_image, output_seed]
85
+ )
 
 
 
 
 
 
 
86
 
87
+ if __name__ == "__main__":
88
+ demo.launch()