| """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) |
|
|
| |
| 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) |
|
|
| |
| 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}) |
| |
| out_df["embedding"] = list(all_vecs) |
| out_df.to_parquet(args.out, index=False) |
| print(f"Saved → {args.out}") |
|
|
| |
| 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() |
|
|