|
| 1 | +import uuid |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import faiss |
| 5 | +import numpy as np |
| 6 | +import numpy.typing as np |
| 7 | +import pandas as pd |
| 8 | +from tqdm import tqdm |
| 9 | + |
| 10 | +from lmm_tools import LMM, Embedder |
| 11 | + |
| 12 | +tqdm.pandas() |
| 13 | + |
| 14 | + |
| 15 | +class Data: |
| 16 | + def __init__(self, df: pd.DataFrame): |
| 17 | + self.df = pd.DataFrame() |
| 18 | + self.lmm: LMM = None |
| 19 | + self.emb: Embedder = None |
| 20 | + self.index = None |
| 21 | + if "image_paths" not in df.columns: |
| 22 | + raise ValueError("image_paths column must be present in DataFrame") |
| 23 | + |
| 24 | + def add_embedder(self, emb: Embedder): |
| 25 | + self.emb = emb |
| 26 | + |
| 27 | + def add_lmm(self, lmm: LMM): |
| 28 | + self.lmm = lmm |
| 29 | + |
| 30 | + def add_column(self, name: str, prompt: str) -> None: |
| 31 | + self.df[name] = self.df["image_paths"].progress_apply( |
| 32 | + lambda x: self.lmm.generate(prompt, image=x) |
| 33 | + ) |
| 34 | + |
| 35 | + def add_index(self, target_col: str) -> None: |
| 36 | + embeddings = self.df[target_col].progress_apply(lambda x: self.emb.embed(x)) |
| 37 | + embeddings = np.array(embeddings.tolist()).astype(np.float32) |
| 38 | + self.index = faiss.IndexFlatL2(embeddings.shape[1]) |
| 39 | + self.index.add(embeddings) |
| 40 | + |
| 41 | + def get_embeddings(self) -> np.ndarray: |
| 42 | + ntotal = self.index.ntotal |
| 43 | + d = self.index.d |
| 44 | + return faiss.rev_swig_ptr(self.index.get_xb(), ntotal * d).reshape(ntotal, d) |
| 45 | + |
| 46 | + def search(self, query: str, top_k: int = 10) -> list[dict]: |
| 47 | + query_embedding = self.emb.embed(query) |
| 48 | + _, I = self.index.search(query_embedding.reshape(1, -1), top_k) |
| 49 | + return self.df.iloc[I[0]].to_dict(orient="records") |
| 50 | + |
| 51 | + |
| 52 | +def build_data(self, data: str | Path | list[str | Path]) -> Data: |
| 53 | + if isinstance(data, Path) or isinstance(data, str): |
| 54 | + data = Path(data) |
| 55 | + data_files = list(Path(data).glob("*")) |
| 56 | + elif isinstance(data, list): |
| 57 | + data_files = [Path(d) for d in data] |
| 58 | + |
| 59 | + df = pd.DataFrame() |
| 60 | + df["image_paths"] = data_files |
| 61 | + df["image_id"] = [uuid.uuid4() for _ in range(len(data_files))] |
| 62 | + return Data(df) |
0 commit comments