File size: 1,682 Bytes
de1e3fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from datetime import datetime, timezone

import numpy as np
from sqlalchemy import (
    DateTime,
    ForeignKey,
    Integer,
    LargeBinary,
    String,
    UniqueConstraint,
    func,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship

from .base import Base


class Embedding(Base):
    """An embedding vector for one picture under one model (spec §7.6).

    The vector is stored as L2-normalized float32 bytes so cosine similarity == dot product.
    Keeping embeddings in their own table lets us recompute across model versions without
    losing history.
    """

    __tablename__ = "embeddings"
    __table_args__ = (
        UniqueConstraint(
            "picture_id", "model_name", "model_version", name="uq_embedding_picture_model"
        ),
    )

    id: Mapped[int] = mapped_column(primary_key=True)
    picture_id: Mapped[int] = mapped_column(ForeignKey("pictures.id"), index=True)
    model_name: Mapped[str] = mapped_column(String(80))
    model_version: Mapped[str] = mapped_column(String(40))
    dim: Mapped[int] = mapped_column(Integer)
    vector: Mapped[bytes] = mapped_column(LargeBinary)  # float32, L2-normalized
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        default=lambda: datetime.now(timezone.utc),
        server_default=func.now(),
    )

    picture: Mapped["Picture"] = relationship(back_populates="embeddings")  # noqa: F821

    def as_array(self) -> np.ndarray:
        return np.frombuffer(self.vector, dtype=np.float32)

    @staticmethod
    def to_bytes(vec: np.ndarray) -> bytes:
        return np.asarray(vec, dtype=np.float32).tobytes()