Reaper200 commited on
Commit
8a88200
·
verified ·
1 Parent(s): b6d1ef4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -131
app.py CHANGED
@@ -1,154 +1,168 @@
1
- import gradio as gr
2
- import numpy as np
3
- import random
4
 
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
 
 
 
7
  import torch
 
8
 
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
11
 
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
 
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
19
 
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
 
 
22
 
 
 
 
23
 
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
- ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
 
39
- generator = torch.Generator().manual_seed(seed)
 
 
 
 
 
 
 
 
 
40
 
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
 
51
- return image, seed
 
52
 
53
 
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
 
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
- }
65
- """
66
 
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
- )
79
-
80
- run_button = gr.Button("Run", scale=0, variant="primary")
81
-
82
- result = gr.Image(label="Result", show_label=False)
83
-
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
90
- )
91
-
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
98
- )
99
-
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
-
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
110
 
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
  )
118
 
119
- with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
134
- )
135
 
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
- ],
150
- outputs=[result, seed],
151
- )
152
 
153
- if __name__ == "__main__":
154
- demo.launch()
 
 
 
 
1
 
2
+ import os
3
+ import tempfile
4
+ from typing import List
5
+
6
+ import gradio as gr
7
  import torch
8
+ from PIL import Image
9
 
10
+ from diffusers import StableVideoDiffusionPipeline
11
+ from diffusers.utils import export_to_video
12
 
13
+ MODEL_ID_DEFAULT = os.getenv("MODEL_ID", "stabilityai/stable-video-diffusion-img2vid")
14
+ DTYPE = torch.float16 if torch.cuda.is_available() else torch.float32
 
 
15
 
16
+ pipe = None
 
17
 
18
+ def load_pipeline(model_id: str = MODEL_ID_DEFAULT):
19
+ global pipe
20
+ if pipe is not None:
21
+ return pipe
22
 
23
+ kwargs = {
24
+ "torch_dtype": DTYPE,
25
+ }
26
 
27
+ # fp16 variant helps on GPU spaces
28
+ if DTYPE == torch.float16:
29
+ kwargs["variant"] = "fp16"
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ pipe_local = StableVideoDiffusionPipeline.from_pretrained(
32
+ model_id,
33
+ **kwargs,
34
+ )
35
+
36
+ # memory & speed tweaks
37
+ if torch.cuda.is_available():
38
+ pipe_local.enable_model_cpu_offload() # good default for Spaces GPUs
39
+ else:
40
+ pipe_local.enable_sequential_cpu_offload()
41
 
42
+ pipe_local.enable_vae_slicing()
43
+ pipe_local.enable_attention_slicing()
 
 
 
 
 
 
 
44
 
45
+ pipe = pipe_local
46
+ return pipe
47
 
48
 
49
+ def _ensure_rgb(img: Image.Image) -> Image.Image:
50
+ if img.mode != "RGB":
51
+ return img.convert("RGB")
52
+ return img
 
53
 
 
 
 
 
 
 
54
 
55
+ def generate(
56
+ image: Image.Image,
57
+ num_frames: int = 14,
58
+ fps: int = 8,
59
+ motion_bucket_id: int = 127,
60
+ noise_aug_strength: float = 0.02,
61
+ seed: int = 0,
62
+ decode_chunk_size: int = 8,
63
+ model_id: str = MODEL_ID_DEFAULT,
64
+ ):
65
+ if image is None:
66
+ raise gr.Error("Please upload an image.")
67
+
68
+ pipe = load_pipeline(model_id)
69
+
70
+ # Determinism
71
+ generator = torch.Generator(device="cuda" if torch.cuda.is_available() else "cpu")
72
+ if seed is None or seed < 0:
73
+ seed = torch.seed() % (2**31)
74
+ generator = generator.manual_seed(int(seed))
75
+
76
+ image = _ensure_rgb(image)
77
+
78
+ with torch.inference_mode():
79
+ result = pipe(
80
+ image=image,
81
+ num_frames=int(num_frames),
82
+ fps=fps,
83
+ motion_bucket_id=int(motion_bucket_id),
84
+ noise_aug_strength=float(noise_aug_strength),
85
+ decode_chunk_size=int(decode_chunk_size),
86
+ generator=generator,
87
+ )
88
+
89
+ frames: List[Image.Image] = result.frames[0]
90
+
91
+ # Save to a temp .mp4
92
+ tmpdir = tempfile.mkdtemp()
93
+ out_path = os.path.join(tmpdir, "output.mp4")
94
+ export_to_video(frames, out_path, fps=fps)
95
+
96
+ return out_path
97
+
98
+
99
+ def build_demo():
100
+ with gr.Blocks(theme=gr.themes.Soft(), fill_width=True) as demo:
101
+ gr.Markdown(
102
+ """
103
+ # Image → Video (Stable Video Diffusion)
104
+ Pretrained **Stable Video Diffusion (Img2Vid)** from the Hugging Face Hub.
105
+ - Default model: `stabilityai/stable-video-diffusion-img2vid`
106
+ - Try alternative ids like `stabilityai/stable-video-diffusion-img2vid-xt`
107
+ """
108
+ )
109
 
110
  with gr.Row():
111
+ with gr.Column(scale=1):
112
+ inp_img = gr.Image(type="pil", label="Input image", width=512)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
+ model_id = gr.Textbox(
115
+ value=MODEL_ID_DEFAULT,
116
+ label="Model repo id",
117
+ info="Any compatible Img2Vid pipeline on the Hub",
 
 
118
  )
119
 
120
+ with gr.Accordion("Advanced", open=False):
121
+ num_frames = gr.Slider(8, 25, value=14, step=1, label="Frames")
122
+ fps = gr.Slider(4, 30, value=8, step=1, label="FPS")
123
+ motion_bucket_id = gr.Slider(1, 255, value=127, step=1, label="Motion bucket id")
124
+ noise_aug_strength = gr.Slider(0.0, 0.5, value=0.02, step=0.01, label="Noise aug strength")
125
+ decode_chunk_size = gr.Slider(1, 32, value=8, step=1, label="Decode chunk size")
126
+ seed = gr.Number(value=0, precision=0, label="Seed (0 for random)")
127
+
128
+ run = gr.Button("Generate", variant="primary")
129
+
130
+ with gr.Column(scale=1):
131
+ out_vid = gr.Video(label="Output video (.mp4)")
132
+
133
+ run.click(
134
+ fn=generate,
135
+ inputs=[
136
+ inp_img,
137
+ num_frames,
138
+ fps,
139
+ motion_bucket_id,
140
+ noise_aug_strength,
141
+ seed,
142
+ decode_chunk_size,
143
+ model_id,
144
+ ],
145
+ outputs=[out_vid],
146
+ queue=True,
147
+ api_name="predict",
148
+ )
149
+
150
+ gr.Examples(
151
+ examples=[
152
+ ["https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/sketch-mountains-input.jpg", 14, 8, 127, 0.02, 0, 8, MODEL_ID_DEFAULT],
153
+ ],
154
+ inputs=[inp_img, num_frames, fps, motion_bucket_id, noise_aug_strength, seed, decode_chunk_size, model_id],
155
+ label="Try an example (downloads on-click)",
156
+ )
157
+
158
+ return demo
159
+
160
+
161
+ demo = build_demo()
162
+
163
+ if __name__ == "__main__":
164
+ demo.queue(concurrency_count=1, max_size=8).launch()
165
+
166
 
 
 
 
 
 
 
 
167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168