Repository navigation
Expand file tree
/
Copy pathembeddings.py
More file actions
81 lines (62 loc) · 2.81 KB
/
Copy pathembeddings.py
File metadata and controls
81 lines (62 loc) · 2.81 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from __future__ import annotations
import hashlib
import math
from pathlib import Path
from videoquery.config import Settings
def _normalize(vector: list[float]) -> list[float]:
norm = math.sqrt(sum(value * value for value in vector))
if norm == 0:
return vector
return [value / norm for value in vector]
class HashEmbeddingProvider:
"""Deterministic local fallback used for tests and dry-runs."""
def __init__(self, dimension: int = 512):
self.dimension = dimension
def _embed_bytes(self, data: bytes) -> list[float]:
values: list[float] = []
counter = 0
while len(values) < self.dimension:
digest = hashlib.sha256(data + counter.to_bytes(4, "big")).digest()
values.extend((byte / 127.5) - 1.0 for byte in digest)
counter += 1
return _normalize(values[: self.dimension])
def embed_image_paths(self, paths: list[Path]) -> list[list[float]]:
return [self._embed_bytes(path.read_bytes()) for path in paths]
def embed_text(self, text: str) -> list[float]:
return self._embed_bytes(text.encode("utf-8"))
class ClipEmbeddingProvider:
def __init__(self, model_name: str, pretrained: str):
import open_clip
import torch
self.open_clip = open_clip
self.torch = torch
self.device = "cuda" if torch.cuda.is_available() else "cpu"
model, _, preprocess = open_clip.create_model_and_transforms(
model_name, pretrained=pretrained
)
self.model = model.to(self.device)
self.model.eval()
self.preprocess = preprocess
self.tokenizer = open_clip.get_tokenizer(model_name)
def embed_image_paths(self, paths: list[Path]) -> list[list[float]]:
from PIL import Image
images = [self.preprocess(Image.open(path).convert("RGB")) for path in paths]
if not images:
return []
batch = self.torch.stack(images).to(self.device)
with self.torch.no_grad():
vectors = self.model.encode_image(batch)
vectors = vectors / vectors.norm(dim=-1, keepdim=True)
return vectors.cpu().tolist()
def embed_text(self, text: str) -> list[float]:
tokens = self.tokenizer([text]).to(self.device)
with self.torch.no_grad():
vector = self.model.encode_text(tokens)
vector = vector / vector.norm(dim=-1, keepdim=True)
return vector[0].cpu().tolist()
def make_embedding_provider(settings: Settings):
if settings.embedding_backend.lower() == "clip":
return ClipEmbeddingProvider(settings.clip_model, settings.clip_pretrained)
if settings.embedding_backend.lower() == "hash":
return HashEmbeddingProvider(settings.embedding_dimension)
raise ValueError(f"Unsupported embedding backend: {settings.embedding_backend}")