Spaces:
Runtime error
Runtime error
Download api.py from Rique777xl/api-imagev2: direct link, hf CLI and curl.
- Browser
- Download file 1.39 kB
-
https://huggingface.co/spaces/Rique777xl/api-imagev2/resolve/main/api.py
- Command line
-
hf download hf://spaces/Rique777xl/api-imagev2/api.py
-
curl -L -o api.py https://huggingface.co/spaces/Rique777xl/api-imagev2/resolve/main/api.py
1.39 kB
| from fastapi import FastAPI, UploadFile, File | |
| from fastapi.responses import FileResponse | |
| from diffusers import DiffusionPipeline | |
| from PIL import Image | |
| import torch | |
| import os | |
| import imageio | |
| # Inicializa a API | |
| app = FastAPI() | |
| # Verifica GPU disponível | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| dtype = torch.float16 if device == "cuda" else torch.float32 # CPU usa float32 | |
| # Carrega o modelo corretamente | |
| pipe = DiffusionPipeline.from_pretrained( | |
| "stabilityai/stable-video-diffusion-img2vid", | |
| torch_dtype=dtype, | |
| safety_checker=None # Desativa verificações que travam na CPU | |
| ) | |
| # Muda para GPU ou otimiza para CPU | |
| if device == "cuda": | |
| pipe.to("cuda") | |
| else: | |
| pipe.to("cpu") | |
| pipe.enable_model_cpu_offload() # Melhora performance na CPU | |
| async def generate_video(file: UploadFile = File(...)): | |
| try: | |
| # Abre a imagem enviada pelo usuário | |
| image = Image.open(file.file).convert("RGB") | |
| # Gera os frames do vídeo | |
| video_frames = pipe(image).frames | |
| # Define o caminho do vídeo | |
| video_path = "output.mp4" | |
| # Salva os frames como um vídeo MP4 | |
| imageio.mimsave(video_path, video_frames, fps=10) # FPS ajustável | |
| return FileResponse(video_path, media_type="video/mp4") | |
| except Exception as e: | |
| return {"error": str(e)} |