midah commited on
Commit
6a3be6d
·
verified ·
1 Parent(s): cc126b6

Reorganize: scripts/eval/embed_figures.py

Browse files
Files changed (1) hide show
  1. scripts/eval/embed_figures.py +107 -0
scripts/eval/embed_figures.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compute CLIP embeddings for all extracted patent figures.
2
+
3
+ Uses open_clip ViT-L/14 (best open-source CLIP) to embed each TIF.
4
+ Saves embeddings as parquet with figure_id index for fast lookup.
5
+
6
+ Usage:
7
+ python scripts/eval/embed_figures.py \
8
+ --enriched data/enriched/enriched_2022.parquet \
9
+ --images /tmp/patent_sample/2022 \
10
+ --out data/embeddings/embeddings_2022.parquet \
11
+ --batch 64
12
+ """
13
+
14
+ import argparse
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+ import open_clip
19
+ import pandas as pd
20
+ import torch
21
+ from PIL import Image
22
+ from tqdm import tqdm
23
+
24
+
25
+ def find_image(images_dir: Path, image_filename: str) -> Path | None:
26
+ parts = image_filename.split("-D0")
27
+ if len(parts) < 2:
28
+ return None
29
+ p = images_dir / parts[0] / image_filename
30
+ return p if p.exists() else None
31
+
32
+
33
+ def embed_batch(model, preprocess, paths: list[Path], device: str) -> np.ndarray:
34
+ imgs = []
35
+ for p in paths:
36
+ try:
37
+ img = Image.open(p).convert("RGB")
38
+ imgs.append(preprocess(img))
39
+ except Exception:
40
+ imgs.append(torch.zeros(3, 224, 224))
41
+ batch = torch.stack(imgs).to(device)
42
+ with torch.no_grad():
43
+ feats = model.encode_image(batch)
44
+ feats = feats / feats.norm(dim=-1, keepdim=True)
45
+ return feats.cpu().numpy()
46
+
47
+
48
+ def main():
49
+ parser = argparse.ArgumentParser()
50
+ parser.add_argument("--enriched", default="data/enriched/enriched_2022.parquet")
51
+ parser.add_argument("--images", default="/tmp/patent_sample/2022")
52
+ parser.add_argument("--out", default="data/embeddings/embeddings_2022.parquet")
53
+ parser.add_argument("--batch", type=int, default=64)
54
+ parser.add_argument("--model", default="ViT-L-14")
55
+ parser.add_argument("--pretrained", default="openai")
56
+ args = parser.parse_args()
57
+
58
+ device = "cuda" if torch.cuda.is_available() else "cpu"
59
+ print(f"Device: {device}")
60
+
61
+ print(f"Loading {args.model} ({args.pretrained})...")
62
+ model, _, preprocess = open_clip.create_model_and_transforms(
63
+ args.model, pretrained=args.pretrained
64
+ )
65
+ model = model.to(device).eval()
66
+
67
+ df = pd.read_parquet(args.enriched)
68
+ images_dir = Path(args.images)
69
+
70
+ # Resolve image paths
71
+ df["_img_path"] = df["image_filename"].apply(
72
+ lambda fn: find_image(images_dir, fn)
73
+ )
74
+ found = df["_img_path"].notna().sum()
75
+ print(f"Images resolved: {found:,} / {len(df):,}")
76
+ df = df[df["_img_path"].notna()].reset_index(drop=True)
77
+
78
+ # Embed in batches
79
+ all_ids, all_vecs = [], []
80
+ batch_size = args.batch
81
+ paths = df["_img_path"].tolist()
82
+ fig_ids = df["figure_id"].tolist()
83
+
84
+ for i in tqdm(range(0, len(paths), batch_size), desc="Embedding"):
85
+ batch_paths = paths[i : i + batch_size]
86
+ batch_ids = fig_ids[i : i + batch_size]
87
+ vecs = embed_batch(model, preprocess, batch_paths, device)
88
+ all_ids.extend(batch_ids)
89
+ all_vecs.append(vecs)
90
+
91
+ all_vecs = np.vstack(all_vecs)
92
+ print(f"Embedding matrix: {all_vecs.shape}")
93
+
94
+ Path(args.out).parent.mkdir(parents=True, exist_ok=True)
95
+ out_df = pd.DataFrame({"figure_id": all_ids})
96
+ # Store each embedding dimension as a column — efficient for FAISS loading
97
+ out_df["embedding"] = list(all_vecs)
98
+ out_df.to_parquet(args.out, index=False)
99
+ print(f"Saved → {args.out}")
100
+
101
+ # Quick sanity check
102
+ print(f"Sample figure: {all_ids[0]}")
103
+ print(f"Embedding norm: {np.linalg.norm(all_vecs[0]):.4f} (should be 1.0)")
104
+
105
+
106
+ if __name__ == "__main__":
107
+ main()