Download src/utils.py from precove/fclip: direct link, hf CLI and curl.
- Browser
- Download file 1.15 kB
-
https://huggingface.co/spaces/precove/fclip/resolve/main/src/utils.py
- Command line
-
hf download hf://spaces/precove/fclip/src/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/precove/fclip/resolve/main/src/utils.py
1.15 kB
| from typing import List | |
| import requests, torch | |
| from PIL import Image | |
| REQUESTS_HEADERS = { | |
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" | |
| } | |
| def download_image_as_pil(url: str, timeout: int = 10) -> Image.Image: | |
| try: | |
| response = requests.get( | |
| url, stream=True, headers=REQUESTS_HEADERS, timeout=timeout | |
| ) | |
| if response.status_code == 200: | |
| return Image.open(response.raw) | |
| except Exception as e: | |
| return | |
| def normalize_vectors(vectors: torch.Tensor) -> torch.Tensor: | |
| norms = torch.norm(vectors, p=2, dim=1, keepdim=True) | |
| norms = torch.norm(vectors, p=2, dim=1, keepdim=True) | |
| norms = torch.where(norms > 1e-8, norms, torch.ones_like(norms)) | |
| normalized_vectors = vectors / norms | |
| return normalized_vectors | |
| def delete_images(images: List[Image.Image]) -> bool: | |
| try: | |
| for image in images: | |
| if hasattr(image, "close"): | |
| image.close() | |
| success = True | |
| except Exception: | |
| success = False | |
| del images | |
| return success | |