File size: 3,890 Bytes
59830d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
from pathlib import Path
from pathlib import Path
from sqlite3 import Row
from typing import Any, Literal, Sequence
from urllib.parse import quote

import numpy as np
from PIL import Image
from pydantic import json
from sentence_transformers import SentenceTransformer

SRC_PATH = Path(__file__).resolve().parents[1]

def load_image_paths(data_dir: Path) -> list[Path]:
    paths = sorted(data_dir.glob("*.jpg"))

    if not paths:
        raise FileNotFoundError(f"No JPG images found in {data_dir}")

    return paths

def encode_images(
    model: SentenceTransformer,
    images: list[Image.Image],
    batch_size: int = 16,
) -> np.ndarray:
    return model.encode(
        images,
        batch_size=batch_size,
        normalize_embeddings=True,
        convert_to_numpy=True,
        show_progress_bar=True,
    )

def encode_texts(
    model: SentenceTransformer,
    texts: list[str],
) -> np.ndarray:
    return model.encode(
        texts,
        normalize_embeddings=True,
        convert_to_numpy=True,
    )

def _public_file_url(path: Path) -> str:
    absolute_path = str(path.resolve())

    return (
        "/gradio_api/file="
        + quote(absolute_path, safe="/:")
    )

def _row_to_item(row: Row) -> dict[str, Any]:
    path = Path(row["path"])

    return {
        "id": row["id"],
        "name": row["name"],
        "category": row["category"],
        "available": bool(row["available"]),
        "url": _public_file_url(path),
    }

def normalize_rows(values: Any) -> np.ndarray:
    values = np.asarray(values, dtype=np.float32)

    if values.ndim == 1:
        values = values[None, :]

    norms = np.linalg.norm(values, axis=1, keepdims=True)

    if np.any(norms == 0):
        raise ValueError("Received a zero embedding")

    return values / norms


def deserialize_embedding(
    blob: bytes | bytearray | memoryview,
    embedding_dim: int,
    embedding_dtype: str,
) -> np.ndarray:
    if isinstance(blob, memoryview):
        blob = blob.tobytes()

    dtype = np.dtype(embedding_dtype)

    embedding = np.frombuffer(
        blob,
        dtype=dtype,
    )

    if embedding.size != embedding_dim:
        raise ValueError(
            "Invalid stored embedding: "
            f"expected dimension {embedding_dim}, "
            f"got {embedding.size}"
        )

    return embedding.astype(np.float32, copy=False)


def load_outfit_embeddings(
    conn,
    outfit: Sequence[dict[str, Any]],
    embedding_type: Literal["clip", "outfit"],
) -> np.ndarray:
    outfit_ids = [str(item["id"]) for item in outfit]

    if not outfit_ids:
        raise ValueError("Cannot load embeddings for an empty outfit")

    if embedding_type not in {"clip", "outfit"}:
        raise ValueError(
            f"Unsupported embedding type: {embedding_type}"
        )

    placeholders = ", ".join("?" for _ in outfit_ids)

    rows = conn.execute(
        f"""
        SELECT
            id,
            {embedding_type}_image_embedding,
            {embedding_type}_embedding_dim,
            {embedding_type}_embedding_dtype
        FROM metadata
        WHERE id IN ({placeholders})
        """,
        outfit_ids,
    ).fetchall()

    embeddings_by_id = {
        str(row["id"]): deserialize_embedding(
            blob=row[f"{embedding_type}_image_embedding"],
            embedding_dim=row[f"{embedding_type}_embedding_dim"],
            embedding_dtype=row[f"{embedding_type}_embedding_dtype"],
        )
        for row in rows
    }

    missing_ids = [
        item_id
        for item_id in outfit_ids
        if item_id not in embeddings_by_id
    ]

    if missing_ids:
        raise ValueError(
            f"Missing {embedding_type} embeddings for items: "
            f"{missing_ids}"
        )

    return normalize_rows(
        np.stack([
            embeddings_by_id[item_id]
            for item_id in outfit_ids
        ])
    )