File size: 3,519 Bytes
6a3be6d | 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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | """Compute CLIP embeddings for all extracted patent figures.
Uses open_clip ViT-L/14 (best open-source CLIP) to embed each TIF.
Saves embeddings as parquet with figure_id index for fast lookup.
Usage:
python scripts/eval/embed_figures.py \
--enriched data/enriched/enriched_2022.parquet \
--images /tmp/patent_sample/2022 \
--out data/embeddings/embeddings_2022.parquet \
--batch 64
"""
import argparse
from pathlib import Path
import numpy as np
import open_clip
import pandas as pd
import torch
from PIL import Image
from tqdm import tqdm
def find_image(images_dir: Path, image_filename: str) -> Path | None:
parts = image_filename.split("-D0")
if len(parts) < 2:
return None
p = images_dir / parts[0] / image_filename
return p if p.exists() else None
def embed_batch(model, preprocess, paths: list[Path], device: str) -> np.ndarray:
imgs = []
for p in paths:
try:
img = Image.open(p).convert("RGB")
imgs.append(preprocess(img))
except Exception:
imgs.append(torch.zeros(3, 224, 224))
batch = torch.stack(imgs).to(device)
with torch.no_grad():
feats = model.encode_image(batch)
feats = feats / feats.norm(dim=-1, keepdim=True)
return feats.cpu().numpy()
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--enriched", default="data/enriched/enriched_2022.parquet")
parser.add_argument("--images", default="/tmp/patent_sample/2022")
parser.add_argument("--out", default="data/embeddings/embeddings_2022.parquet")
parser.add_argument("--batch", type=int, default=64)
parser.add_argument("--model", default="ViT-L-14")
parser.add_argument("--pretrained", default="openai")
args = parser.parse_args()
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Device: {device}")
print(f"Loading {args.model} ({args.pretrained})...")
model, _, preprocess = open_clip.create_model_and_transforms(
args.model, pretrained=args.pretrained
)
model = model.to(device).eval()
df = pd.read_parquet(args.enriched)
images_dir = Path(args.images)
# Resolve image paths
df["_img_path"] = df["image_filename"].apply(
lambda fn: find_image(images_dir, fn)
)
found = df["_img_path"].notna().sum()
print(f"Images resolved: {found:,} / {len(df):,}")
df = df[df["_img_path"].notna()].reset_index(drop=True)
# Embed in batches
all_ids, all_vecs = [], []
batch_size = args.batch
paths = df["_img_path"].tolist()
fig_ids = df["figure_id"].tolist()
for i in tqdm(range(0, len(paths), batch_size), desc="Embedding"):
batch_paths = paths[i : i + batch_size]
batch_ids = fig_ids[i : i + batch_size]
vecs = embed_batch(model, preprocess, batch_paths, device)
all_ids.extend(batch_ids)
all_vecs.append(vecs)
all_vecs = np.vstack(all_vecs)
print(f"Embedding matrix: {all_vecs.shape}")
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
out_df = pd.DataFrame({"figure_id": all_ids})
# Store each embedding dimension as a column — efficient for FAISS loading
out_df["embedding"] = list(all_vecs)
out_df.to_parquet(args.out, index=False)
print(f"Saved → {args.out}")
# Quick sanity check
print(f"Sample figure: {all_ids[0]}")
print(f"Embedding norm: {np.linalg.norm(all_vecs[0]):.4f} (should be 1.0)")
if __name__ == "__main__":
main()
|