# src/vector_store.py from pathlib import Path import pickle import faiss import numpy as np import pandas as pd from embedder import FashionEmbedder class FashionVectorStore: def __init__( self, dimension=768 ): self.dimension = dimension self.index = faiss.IndexFlatL2( dimension ) self.metadata = [] def build_index( self, dataframe, sample_size=50000 ): embedder = FashionEmbedder() dataframe = dataframe.iloc[ :sample_size ] embeddings = [] total = len(dataframe) for idx, row in dataframe.iterrows(): image_path = row["image_path"] try: embedding = ( embedder.get_image_embedding( image_path ) ) embeddings.append( embedding ) self.metadata.append({ "id": row["id"], "product": row["productDisplayName"], "category": row["articleType"], "color": row["baseColour"], "image_path": image_path }) if len(embeddings) % 500 == 0: print( f"Processed {len(embeddings)} / {total}" ) except Exception as e: print( f"Error processing {image_path}: {e}" ) embeddings = np.array( embeddings, dtype=np.float32 ) self.index.add( embeddings ) print( f"Indexed {self.index.ntotal} images." ) def save( self, index_path="vectorstore/fashion.index", metadata_path="vectorstore/metadata.pkl" ): faiss.write_index( self.index, index_path ) with open( metadata_path, "wb" ) as f: pickle.dump( self.metadata, f ) print("Index saved.") if __name__ == "__main__": df = pd.read_csv( "data/styles.csv", on_bad_lines="skip" ) image_dir = Path( "data/images" ) df["image_path"] = df["id"].apply( lambda x: str( image_dir / f"{x}.jpg" ) ) df = df[ df["image_path"].apply( lambda x: Path(x).exists() ) ] store = FashionVectorStore() store.build_index( dataframe=df, sample_size=50000 ) store.save()