Spaces:
Sleeping
Sleeping
Create generate.py
Browse files- generate.py +37 -0
generate.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from diffusers import AnimateDiffPipeline, DDIMScheduler
|
| 3 |
+
|
| 4 |
+
# Load model only once (on import)
|
| 5 |
+
def load_model():
|
| 6 |
+
# Example AnimateDiff model from HF Hub
|
| 7 |
+
model_id = "guoyww/animatediff-motion-adapter-v1-5-2"
|
| 8 |
+
|
| 9 |
+
pipe = AnimateDiffPipeline.from_pretrained(
|
| 10 |
+
model_id,
|
| 11 |
+
torch_dtype=torch.float16
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
scheduler = DDIMScheduler.from_pretrained(
|
| 15 |
+
"runwayml/stable-diffusion-v1-5",
|
| 16 |
+
subfolder="scheduler"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
pipe.scheduler = scheduler
|
| 20 |
+
pipe = pipe.to("cuda" if torch.cuda.is_available() else "cpu")
|
| 21 |
+
|
| 22 |
+
return pipe
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# Global model instance (loaded once)
|
| 26 |
+
pipe = load_model()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# Generation function
|
| 30 |
+
def generate(prompt: str, num_inference_steps: int = 50, guidance_scale: float = 7.5):
|
| 31 |
+
with torch.autocast("cuda" if torch.cuda.is_available() else "cpu"):
|
| 32 |
+
result = pipe(
|
| 33 |
+
prompt,
|
| 34 |
+
num_inference_steps=num_inference_steps,
|
| 35 |
+
guidance_scale=guidance_scale
|
| 36 |
+
)
|
| 37 |
+
return result.frames[0] # returning first frame (you can adapt this to video/gif)
|