"""
Street View Imagery for Cities, Part B extra: image embeddings and similarity search (run on your laptop).
Turns every image into a 512-number CLIP vector, then finds similar images and searches by text.
Setup once:  pip install open_clip_torch torch pillow pandas
Run:         python embed_images.py <folder with images>     (e.g. svi_sg/mly_svi/batch_1 or review_images_sg)
"""
import sys, glob, os
import numpy as np, torch, open_clip
from PIL import Image

folder = sys.argv[1] if len(sys.argv) > 1 else 'svi_sg/mly_svi/batch_1'
files = sorted(glob.glob(os.path.join(folder, '**', '*.jp*g'), recursive=True))[:2000]
model, _, prep = open_clip.create_model_and_transforms('ViT-B-32', pretrained='openai')   # downloads weights once
tok = open_clip.get_tokenizer('ViT-B-32'); model.eval()

vecs = []
with torch.no_grad():
    for k in range(0, len(files), 32):
        batch = torch.stack([prep(Image.open(f).convert('RGB')) for f in files[k:k + 32]])
        v = model.encode_image(batch); vecs.append((v / v.norm(dim=-1, keepdim=True)).numpy())
E = np.concatenate(vecs); np.save('embeddings.npy', E)
print(f'{len(files)} images -> embeddings of length {E.shape[1]}')

# 1. image -> image: the 5 images most similar to the first one
sim = E @ E[0]
for i in np.argsort(-sim)[1:6]:
    print(f'similar to {os.path.basename(files[0])}: {sim[i]:.3f}  {files[i]}')

# 2. text -> image: search the city with words
for q in ['a shaded street with large trees', 'a busy road with many cars', 'a quiet cafe interior']:
    with torch.no_grad():
        t = model.encode_text(tok([q])); t = (t / t.norm(dim=-1, keepdim=True)).numpy()[0]
    best = np.argsort(-(E @ t))[:3]
    print(f'"{q}":', [os.path.basename(files[i]) for i in best])
