Spaces:
Sleeping
Sleeping
Update generate.py
Browse files- generate.py +42 -25
generate.py
CHANGED
|
@@ -1,37 +1,54 @@
|
|
| 1 |
import torch
|
| 2 |
-
from diffusers import AnimateDiffPipeline,
|
|
|
|
| 3 |
|
| 4 |
-
# Load model only once (on import)
|
| 5 |
def load_model():
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
|
| 22 |
-
|
|
|
|
| 23 |
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
#
|
| 26 |
pipe = load_model()
|
| 27 |
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
+
from diffusers import AnimateDiffPipeline, MotionAdapter, EulerDiscreteScheduler
|
| 3 |
+
from diffusers.utils import export_to_gif
|
| 4 |
|
|
|
|
| 5 |
def load_model():
|
| 6 |
+
try:
|
| 7 |
+
# Load Motion Adapter
|
| 8 |
+
adapter = MotionAdapter.from_pretrained(
|
| 9 |
+
"guoyww/animatediff-motion-adapter-v1-5",
|
| 10 |
+
torch_dtype=torch.float16
|
| 11 |
+
)
|
| 12 |
|
| 13 |
+
# Load AnimateDiff pipeline with Stable Diffusion 1.5
|
| 14 |
+
pipeline = AnimateDiffPipeline.from_pretrained(
|
| 15 |
+
"runwayml/stable-diffusion-v1-5",
|
| 16 |
+
motion_adapter=adapter,
|
| 17 |
+
torch_dtype=torch.float16
|
| 18 |
+
)
|
| 19 |
|
| 20 |
+
# Use Euler scheduler (smoother animations)
|
| 21 |
+
pipeline.scheduler = EulerDiscreteScheduler.from_config(
|
| 22 |
+
pipeline.scheduler.config,
|
| 23 |
+
timestep_spacing="trailing"
|
| 24 |
+
)
|
| 25 |
|
| 26 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 27 |
+
pipeline = pipeline.to(device)
|
| 28 |
|
| 29 |
+
print("✅ Models loaded successfully!")
|
| 30 |
+
return pipeline
|
| 31 |
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"❌ Error during model loading: {e}")
|
| 34 |
+
raise
|
| 35 |
|
| 36 |
+
# Load once globally
|
| 37 |
pipe = load_model()
|
| 38 |
|
| 39 |
|
| 40 |
+
def generate(prompt: str, num_frames: int = 16, steps: int = 25, guidance: float = 7.5, seed: int = 42, out_path: str = "output.gif"):
|
| 41 |
+
"""
|
| 42 |
+
Generate an animated GIF from a text prompt.
|
| 43 |
+
"""
|
| 44 |
+
generator = torch.Generator("cuda" if torch.cuda.is_available() else "cpu").manual_seed(seed)
|
| 45 |
+
result = pipe(
|
| 46 |
+
prompt=prompt,
|
| 47 |
+
num_frames=num_frames,
|
| 48 |
+
num_inference_steps=steps,
|
| 49 |
+
guidance_scale=guidance,
|
| 50 |
+
generator=generator
|
| 51 |
+
)
|
| 52 |
+
frames = result.frames[0]
|
| 53 |
+
export_to_gif(frames, out_path)
|
| 54 |
+
return out_path
|