File size: 1,147 Bytes
31e72fa
88e0bae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31e72fa
5cc3519
 
 
 
 
 
 
 
88e0bae
 
31e72fa
 
 
 
 
 
fdf1598
31e72fa
 
fdf1598
31e72fa
fdf1598
31e72fa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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