Spaces:
Sleeping
Sleeping
Upload indexer.py
Browse files- indexer.py +53 -0
indexer.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import clip
|
| 3 |
+
from torch.utils.data import DataLoader
|
| 4 |
+
from dataset import FlickrStreamer
|
| 5 |
+
from torchvision import transforms
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
|
| 8 |
+
# --- SETTINGS ---
|
| 9 |
+
INDEX_LIMIT = 5000 # How many images to make searchable
|
| 10 |
+
BATCH_SIZE = 32
|
| 11 |
+
SAVE_PATH = "flickr_embeddings.pt"
|
| 12 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 13 |
+
# ----------------
|
| 14 |
+
|
| 15 |
+
def build_index():
|
| 16 |
+
print(f"Loading CLIP on {DEVICE}...")
|
| 17 |
+
model, preprocess = clip.load("ViT-B/32", device=DEVICE)
|
| 18 |
+
|
| 19 |
+
# We need the images resized for CLIP (224x224)
|
| 20 |
+
tf = transforms.Compose([
|
| 21 |
+
transforms.Resize((224, 224)),
|
| 22 |
+
transforms.ToTensor()
|
| 23 |
+
])
|
| 24 |
+
|
| 25 |
+
# Load Dataset (Stream mode)
|
| 26 |
+
print(f"Connecting to Deep Lake (Limit: {INDEX_LIMIT})...")
|
| 27 |
+
dataset = FlickrStreamer(limit=INDEX_LIMIT, transform=tf)
|
| 28 |
+
loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=0)
|
| 29 |
+
|
| 30 |
+
all_embeddings = []
|
| 31 |
+
|
| 32 |
+
print("Indexing images (calculating fingerprints)...")
|
| 33 |
+
with torch.no_grad():
|
| 34 |
+
for images in tqdm(loader):
|
| 35 |
+
images = images.to(DEVICE)
|
| 36 |
+
|
| 37 |
+
# Calculate features
|
| 38 |
+
features = model.encode_image(images)
|
| 39 |
+
|
| 40 |
+
# Normalize features (Crucial for Cosine Similarity later)
|
| 41 |
+
features /= features.norm(dim=-1, keepdim=True)
|
| 42 |
+
|
| 43 |
+
all_embeddings.append(features.cpu())
|
| 44 |
+
|
| 45 |
+
# Concatenate all batches into one big list
|
| 46 |
+
final_index = torch.cat(all_embeddings)
|
| 47 |
+
|
| 48 |
+
# Save to file
|
| 49 |
+
torch.save(final_index, SAVE_PATH)
|
| 50 |
+
print(f"\nSuccess! Saved {len(final_index)} image fingerprints to '{SAVE_PATH}'")
|
| 51 |
+
|
| 52 |
+
if __name__ == "__main__":
|
| 53 |
+
build_index()
|