boudiafA commited on
Commit
0a8ae4e
·
verified ·
1 Parent(s): 5223b5a

Add CropVLM model card and code

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ docs/figures/agri_semantics_coverage.png filter=lfs diff=lfs merge=lfs -text
37
+ docs/figures/cropvlm_framework.png filter=lfs diff=lfs merge=lfs -text
38
+ docs/figures/semantic_annotation_examples.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .ipynb_checkpoints/
4
+ .DS_Store
5
+
6
+ models/*.pth
7
+ models/*.pt
8
+ models/*.ckpt
9
+ outputs/*
10
+ !outputs/.gitkeep
README.md CHANGED
@@ -1,3 +1,176 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CropVLM: A Domain-Adapted Vision-Language Model for Open-Set Crop Analysis
2
+
3
+ CropVLM is a CLIP-based zero-shot image classifier adapted for crop and fruit recognition. It compares one image embedding against text embeddings for candidate class names, then returns the class with the highest cosine similarity.
4
+
5
+ ![CropVLM framework overview](docs/figures/cropvlm_framework.png)
6
+
7
+ This repository contains:
8
+
9
+ - a simple CropVLM Python loader,
10
+ - a Gradio demo for classifying one image,
11
+ - a zero-shot evaluation script for ImageFolder-style datasets,
12
+ - five strategically selected high-margin example images in `examples/`.
13
+
14
+ ## Agri-Semantics Data
15
+
16
+ CropVLM is adapted with dense agricultural image-text supervision. The Agri-Semantics dataset spans 37 crop classes across fruits, vegetables, grains, and industrial crops, with examples covering visual diversity such as ripeness levels, varieties, and growth stages.
17
+
18
+ ![Agri-Semantics crop coverage](docs/figures/agri_semantics_coverage.png)
19
+
20
+ The generated captions encode crop identity together with phenotypic cues such as ripeness, count, color, and spatial position.
21
+
22
+ ![Agri-Semantics annotation examples](docs/figures/semantic_annotation_examples.png)
23
+
24
+ ## Zero-Shot Classification Comparison
25
+
26
+ We evaluate CropVLM against CLIP-based baselines by encoding each crop class name once, encoding each test image, and assigning the class with the highest cosine similarity in the shared image-text embedding space. The table reports results on the held-out 37-class crop test split.
27
+
28
+ | Model | Overall Accuracy (%) | Per-Class Mean +/- Std (%) |
29
+ |---|---:|---:|
30
+ | SigLIP 2 | 3.43 | 3.43 +/- 16.91 |
31
+ | AgriCLIP | 4.04 | 4.04 +/- 14.61 |
32
+ | RemoteCLIP | 42.52 | 42.52 +/- 27.57 |
33
+ | BioCLIP | 48.33 | 48.34 +/- 34.95 |
34
+ | BioTrove-CLIP | 51.07 | 51.07 +/- 36.20 |
35
+ | BioCLIP 2 | 67.74 | 67.74 +/- 31.17 |
36
+ | OpenAI CLIP ViT-B/32 | 70.24 | 70.24 +/- 28.83 |
37
+ | **CropVLM** | **72.51** | **72.51 +/- 29.71** |
38
+
39
+ ## Installation
40
+
41
+ Create an environment and install the dependencies:
42
+
43
+ ```bash
44
+ conda create -n cropvlm python=3.10 -y
45
+ conda activate cropvlm
46
+ pip install -r requirements.txt
47
+ ```
48
+
49
+ For GPU inference, install the CUDA build of PyTorch that matches your system before installing the remaining dependencies. For example:
50
+
51
+ ```bash
52
+ pip install --index-url https://download.pytorch.org/whl/cu121 torch torchvision
53
+ pip install -r requirements.txt
54
+ ```
55
+
56
+ ## Checkpoint
57
+
58
+ This Hugging Face repository includes the CropVLM checkpoint:
59
+
60
+ ```text
61
+ models/CropCLIP_FullDataset_Acc_0.75.pth
62
+ ```
63
+
64
+ You can download it with `huggingface_hub`:
65
+
66
+ ```python
67
+ from huggingface_hub import hf_hub_download
68
+
69
+ checkpoint = hf_hub_download(
70
+ repo_id="boudiafA/CropVLM",
71
+ filename="models/CropCLIP_FullDataset_Acc_0.75.pth",
72
+ )
73
+ ```
74
+
75
+ You can also clone the repository and use the local checkpoint path with `--checkpoint` or `--cropvlm-checkpoint`.
76
+
77
+ ## Gradio Demo
78
+
79
+ Run:
80
+
81
+ ```bash
82
+ python scripts/gradio_demo.py \
83
+ --checkpoint models/CropCLIP_FullDataset_Acc_0.75.pth
84
+ ```
85
+
86
+ Then open:
87
+
88
+ ```text
89
+ http://127.0.0.1:7860
90
+ ```
91
+
92
+ The demo lets you upload any image and edit the candidate class names. The default class list is:
93
+
94
+ ```text
95
+ apple, avocado, banana, barley, bell pepper, broccoli, cacao, canola,
96
+ cauliflower, cherry, chilli, coconut, coffee, corn, cotton, cucumber,
97
+ eggplant, kiwi, lemon, mango, olive, orange, pear, peas, pineapple,
98
+ pomegranate, potato, pumpkin, rice, soyabean, strawberry, sugarcane,
99
+ sunflower, tea, tomato, watermelon, wheat
100
+ ```
101
+
102
+ The included examples are `cacao`, `olive`, `cauliflower`, `sugarcane`, and `sunflower`. They were selected from correct CropVLM predictions with a large cosine-similarity gap between the correct class and the second-best class. The selection details are in `examples/selection_metadata.json`.
103
+
104
+ ## Use CropVLM In Python
105
+
106
+ ```python
107
+ from PIL import Image
108
+ from cropvlm import load_cropvlm
109
+
110
+ classifier = load_cropvlm("models/CropCLIP_FullDataset_Acc_0.75.pth")
111
+ image = Image.open("examples/cacao.png")
112
+
113
+ for label, score in classifier.predict(image, top_k=5):
114
+ print(label, score)
115
+ ```
116
+
117
+ ## Evaluate Zero-Shot Accuracy
118
+
119
+ The dataset should be arranged like `torchvision.datasets.ImageFolder`:
120
+
121
+ ```text
122
+ Crop_Dataset_testing/
123
+ apple/
124
+ image_001.png
125
+ banana/
126
+ image_001.png
127
+ ...
128
+ ```
129
+
130
+ Run CropVLM and the supported comparison CLIP models:
131
+
132
+ ```bash
133
+ python scripts/evaluate_zero_shot.py \
134
+ --dataset /mnt/e/Desktop/Datasets/FruitDataset/Crop_Dataset_testing \
135
+ --cropvlm-checkpoint models/CropCLIP_FullDataset_Acc_0.75.pth \
136
+ --output outputs/zero_shot_results.json \
137
+ --batch-size 64
138
+ ```
139
+
140
+ By default, the script evaluates:
141
+
142
+ ```text
143
+ cropvlm
144
+ openai_clip_vit_b32
145
+ bioclip
146
+ bioclip2
147
+ biotrove_clip
148
+ remoteclip
149
+ siglip2
150
+ ```
151
+
152
+ You can choose a subset:
153
+
154
+ ```bash
155
+ python scripts/evaluate_zero_shot.py \
156
+ --dataset /path/to/test_dataset \
157
+ --models cropvlm openai_clip_vit_b32 bioclip2 \
158
+ --output outputs/subset_results.json
159
+ ```
160
+
161
+ The output JSON includes:
162
+
163
+ - `models`: compact per-model scores,
164
+ - `model_results`: full per-model details keyed by model name,
165
+ - `results`: full per-model details as a list,
166
+ - per-class accuracy,
167
+ - per-class accuracy mean and standard deviation,
168
+ - confusion matrix,
169
+ - optional per-image predictions when `--save-predictions` is used.
170
+
171
+ The mean and standard deviation are computed across per-class accuracies.
172
+
173
+ ## Notes
174
+
175
+ - BioCLIP, BioCLIP2, BioTrove-CLIP, RemoteCLIP, and SigLIP2 weights are downloaded automatically by their libraries when first used.
176
+ - The score used for classification is cosine similarity between normalized image and text embeddings.
cropvlm/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .model import CROP_CLASSES, CropVLMClassifier, load_cropvlm
2
+
3
+ __all__ = ["CROP_CLASSES", "CropVLMClassifier", "load_cropvlm"]
cropvlm/model.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from typing import Dict, Iterable, List, Sequence, Tuple
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+ from PIL import Image
7
+
8
+
9
+ CROP_CLASSES = [
10
+ "apple",
11
+ "avocado",
12
+ "banana",
13
+ "barley",
14
+ "bell pepper",
15
+ "broccoli",
16
+ "cacao",
17
+ "canola",
18
+ "cauliflower",
19
+ "cherry",
20
+ "chilli",
21
+ "coconut",
22
+ "coffee",
23
+ "corn",
24
+ "cotton",
25
+ "cucumber",
26
+ "eggplant",
27
+ "kiwi",
28
+ "lemon",
29
+ "mango",
30
+ "olive",
31
+ "orange",
32
+ "pear",
33
+ "peas",
34
+ "pineapple",
35
+ "pomegranate",
36
+ "potato",
37
+ "pumpkin",
38
+ "rice",
39
+ "soyabean",
40
+ "strawberry",
41
+ "sugarcane",
42
+ "sunflower",
43
+ "tea",
44
+ "tomato",
45
+ "watermelon",
46
+ "wheat",
47
+ ]
48
+
49
+
50
+ def _normalize(features: torch.Tensor) -> torch.Tensor:
51
+ return F.normalize(features.float(), dim=-1)
52
+
53
+
54
+ class CropVLMClassifier:
55
+ """Small zero-shot wrapper around the CropVLM/OpenAI CLIP ViT-B/32 model."""
56
+
57
+ def __init__(
58
+ self,
59
+ checkpoint: str,
60
+ class_names: Sequence[str] = CROP_CLASSES,
61
+ device: str | None = None,
62
+ prompt_template: str = "{}",
63
+ ):
64
+ import clip
65
+
66
+ self.clip = clip
67
+ self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
68
+ self.prompt_template = prompt_template
69
+ self.class_names = list(class_names)
70
+
71
+ checkpoint_path = Path(checkpoint)
72
+ if not checkpoint_path.exists():
73
+ raise FileNotFoundError(f"CropVLM checkpoint not found: {checkpoint_path}")
74
+
75
+ self.model, self.preprocess = clip.load(
76
+ "ViT-B/32",
77
+ device=str(self.device),
78
+ download_root=str(Path.home() / ".cache" / "clip"),
79
+ )
80
+ ckpt = torch.load(checkpoint_path, map_location=self.device)
81
+ state = ckpt.get("model_state_dict", ckpt.get("state_dict", ckpt))
82
+ self.model.load_state_dict(state)
83
+ self.model.eval()
84
+ self.set_classes(self.class_names)
85
+
86
+ def set_classes(self, class_names: Sequence[str]) -> None:
87
+ self.class_names = [c.strip() for c in class_names if c.strip()]
88
+ prompts = [self.prompt_template.format(c) for c in self.class_names]
89
+ tokens = self.clip.tokenize(prompts, truncate=True).to(self.device)
90
+ with torch.no_grad():
91
+ self.text_features = _normalize(self.model.encode_text(tokens))
92
+
93
+ def encode_image(self, image: Image.Image) -> torch.Tensor:
94
+ image = image.convert("RGB")
95
+ batch = self.preprocess(image).unsqueeze(0).to(self.device)
96
+ with torch.no_grad():
97
+ return _normalize(self.model.encode_image(batch))
98
+
99
+ def predict(self, image: Image.Image, top_k: int = 5) -> List[Tuple[str, float]]:
100
+ return [(label, probability) for label, probability, _ in self.predict_with_scores(image, top_k=top_k)]
101
+
102
+ def predict_scores(self, image: Image.Image) -> Dict[str, float]:
103
+ image_features = self.encode_image(image)
104
+ logits = (image_features @ self.text_features.T).squeeze(0)
105
+ return {name: float(score) for name, score in zip(self.class_names, logits.tolist())}
106
+
107
+ def predict_with_scores(self, image: Image.Image, top_k: int = 5) -> List[Tuple[str, float, float]]:
108
+ image_features = self.encode_image(image)
109
+ cosine_scores = (image_features @ self.text_features.T).squeeze(0)
110
+ logit_scale = self.model.logit_scale.exp().clamp(max=100)
111
+ probabilities = (logit_scale * cosine_scores).softmax(dim=-1)
112
+ k = min(top_k, len(self.class_names))
113
+ probs, indices = probabilities.topk(k)
114
+ return [
115
+ (self.class_names[idx], float(prob), float(cosine_scores[idx]))
116
+ for prob, idx in zip(probs.tolist(), indices.tolist())
117
+ ]
118
+
119
+
120
+ def load_cropvlm(
121
+ checkpoint: str,
122
+ class_names: Sequence[str] = CROP_CLASSES,
123
+ device: str | None = None,
124
+ prompt_template: str = "{}",
125
+ ) -> CropVLMClassifier:
126
+ return CropVLMClassifier(
127
+ checkpoint=checkpoint,
128
+ class_names=class_names,
129
+ device=device,
130
+ prompt_template=prompt_template,
131
+ )
132
+
133
+
134
+ def parse_class_names(text: str | Iterable[str]) -> List[str]:
135
+ if isinstance(text, str):
136
+ raw = text.replace(",", "\n").splitlines()
137
+ else:
138
+ raw = list(text)
139
+ return [name.strip() for name in raw if name.strip()]
docs/figures/agri_semantics_coverage.png ADDED

Git LFS Details

  • SHA256: 41e76d65baf966b3b2af823a242fd4025ef554e4ded07b61322b6df41afa74e5
  • Pointer size: 132 Bytes
  • Size of remote file: 2.35 MB
docs/figures/cropvlm_framework.png ADDED

Git LFS Details

  • SHA256: dd9b27cd8dcccfb4eb311e50144dd6f4b905091a5a1ef0789f656e135192b5a6
  • Pointer size: 132 Bytes
  • Size of remote file: 1.62 MB
docs/figures/semantic_annotation_examples.png ADDED

Git LFS Details

  • SHA256: 6062ef8bbff1bd65d5492a3e9d73db5a5850e9cd43c3510affb449b8fbbddb39
  • Pointer size: 132 Bytes
  • Size of remote file: 1.34 MB
examples/cacao.png ADDED
examples/cauliflower.png ADDED
examples/olive.png ADDED
examples/selection_metadata.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "selection_method": "CropVLM was run on the full testing dataset. Examples were selected from correct predictions by descending cosine margin between the correct class and the second-highest class, preferring less-common crops and keeping at most one image per class.",
3
+ "score_type": "cosine similarity after L2-normalizing image and text embeddings",
4
+ "examples": [
5
+ {
6
+ "file": "cacao.png",
7
+ "source": "/mnt/e/Desktop/Datasets/FruitDataset/Crop_Dataset_testing/cacao/cacao_01171.png",
8
+ "class": "cacao",
9
+ "top1_score": 0.336548,
10
+ "second_class": "mango",
11
+ "second_score": 0.218446,
12
+ "margin": 0.118102
13
+ },
14
+ {
15
+ "file": "olive.png",
16
+ "source": "/mnt/e/Desktop/Datasets/FruitDataset/Crop_Dataset_testing/olive/olive_01140.png",
17
+ "class": "olive",
18
+ "top1_score": 0.329435,
19
+ "second_class": "peas",
20
+ "second_score": 0.215531,
21
+ "margin": 0.113904
22
+ },
23
+ {
24
+ "file": "cauliflower.png",
25
+ "source": "/mnt/e/Desktop/Datasets/FruitDataset/Crop_Dataset_testing/cauliflower/cauliflower_01107.png",
26
+ "class": "cauliflower",
27
+ "top1_score": 0.355567,
28
+ "second_class": "cucumber",
29
+ "second_score": 0.246063,
30
+ "margin": 0.109503
31
+ },
32
+ {
33
+ "file": "sugarcane.png",
34
+ "source": "/mnt/e/Desktop/Datasets/FruitDataset/Crop_Dataset_testing/sugarcane/sugarcane_01134.png",
35
+ "class": "sugarcane",
36
+ "top1_score": 0.334631,
37
+ "second_class": "rice",
38
+ "second_score": 0.226767,
39
+ "margin": 0.107864
40
+ },
41
+ {
42
+ "file": "sunflower.png",
43
+ "source": "/mnt/e/Desktop/Datasets/FruitDataset/Crop_Dataset_testing/sunflower/sunflower_01425.png",
44
+ "class": "sunflower",
45
+ "top1_score": 0.309900,
46
+ "second_class": "pineapple",
47
+ "second_score": 0.208610,
48
+ "margin": 0.101291
49
+ }
50
+ ]
51
+ }
examples/sugarcane.png ADDED
examples/sunflower.png ADDED
models/.gitkeep ADDED
File without changes
outputs/.gitkeep ADDED
File without changes
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ ftfy
4
+ regex
5
+ tqdm
6
+ Pillow
7
+ numpy
8
+ pandas
9
+ gradio
10
+ open_clip_torch
11
+ transformers
12
+ huggingface_hub
13
+ git+https://github.com/openai/CLIP.git
scripts/evaluate_zero_shot.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import math
4
+ import time
5
+ import traceback
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from PIL import Image
13
+ from torch.utils.data import DataLoader, Dataset
14
+ from tqdm import tqdm
15
+
16
+
17
+ IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp"}
18
+ DEFAULT_MODELS = [
19
+ "cropvlm",
20
+ "openai_clip_vit_b32",
21
+ "bioclip",
22
+ "bioclip2",
23
+ "biotrove_clip",
24
+ "remoteclip",
25
+ "siglip2",
26
+ ]
27
+
28
+
29
+ class ImageFolderPaths(Dataset):
30
+ def __init__(self, root: str):
31
+ self.root = Path(root)
32
+ self.classes = sorted([p.name for p in self.root.iterdir() if p.is_dir()])
33
+ self.class_to_idx = {name: idx for idx, name in enumerate(self.classes)}
34
+ self.samples: List[Tuple[Path, int]] = []
35
+ for class_name in self.classes:
36
+ for path in sorted((self.root / class_name).iterdir()):
37
+ if path.is_file() and path.suffix.lower() in IMAGE_EXTS:
38
+ self.samples.append((path, self.class_to_idx[class_name]))
39
+
40
+ def __len__(self) -> int:
41
+ return len(self.samples)
42
+
43
+ def __getitem__(self, idx: int):
44
+ path, label = self.samples[idx]
45
+ return Image.open(path).convert("RGB"), label, str(path)
46
+
47
+
48
+ def pil_collate(batch):
49
+ images, labels, paths = zip(*batch)
50
+ return list(images), torch.tensor(labels, dtype=torch.long), list(paths)
51
+
52
+
53
+ def display_name(class_name: str) -> str:
54
+ return class_name.replace("_", " ")
55
+
56
+
57
+ def normalize(features: torch.Tensor) -> torch.Tensor:
58
+ if isinstance(features, (tuple, list)):
59
+ features = features[0]
60
+ return F.normalize(features.float(), dim=-1)
61
+
62
+
63
+ class Adapter:
64
+ name = ""
65
+ family = ""
66
+ checkpoint: Optional[str] = None
67
+ load_message: Optional[str] = None
68
+
69
+ def encode_text(self, prompts: Sequence[str]) -> torch.Tensor:
70
+ raise NotImplementedError
71
+
72
+ def encode_images(self, images: Sequence[Image.Image]) -> torch.Tensor:
73
+ raise NotImplementedError
74
+
75
+
76
+ class OpenAIClipAdapter(Adapter):
77
+ def __init__(self, device: torch.device, checkpoint: Optional[str] = None):
78
+ import clip
79
+
80
+ self.name = "CropVLM" if checkpoint else "OpenAI CLIP ViT-B/32"
81
+ self.family = "openai_clip"
82
+ self.device = device
83
+ self.clip = clip
84
+ self.model, self.preprocess = clip.load("ViT-B/32", device=str(device))
85
+ if checkpoint:
86
+ checkpoint_path = Path(checkpoint)
87
+ if not checkpoint_path.exists():
88
+ raise FileNotFoundError(f"CropVLM checkpoint not found: {checkpoint_path}")
89
+ ckpt = torch.load(checkpoint_path, map_location=device)
90
+ state = ckpt.get("model_state_dict", ckpt.get("state_dict", ckpt))
91
+ self.model.load_state_dict(state)
92
+ self.checkpoint = str(checkpoint_path)
93
+ self.model.eval()
94
+
95
+ def encode_text(self, prompts: Sequence[str]) -> torch.Tensor:
96
+ tokens = self.clip.tokenize(list(prompts), truncate=True).to(self.device)
97
+ with torch.no_grad():
98
+ return normalize(self.model.encode_text(tokens))
99
+
100
+ def encode_images(self, images: Sequence[Image.Image]) -> torch.Tensor:
101
+ batch = torch.stack([self.preprocess(image) for image in images]).to(self.device)
102
+ with torch.no_grad():
103
+ return normalize(self.model.encode_image(batch))
104
+
105
+
106
+ class OpenClipAdapter(Adapter):
107
+ def __init__(
108
+ self,
109
+ model_name: str,
110
+ pretrained: Optional[str],
111
+ device: torch.device,
112
+ hf_checkpoint: Optional[Tuple[str, str]] = None,
113
+ ):
114
+ import open_clip
115
+
116
+ self.name = model_name
117
+ self.family = "open_clip"
118
+ self.device = device
119
+ self.model_name = model_name
120
+ self.pretrained = pretrained
121
+ self.open_clip = open_clip
122
+
123
+ if hf_checkpoint:
124
+ from huggingface_hub import hf_hub_download
125
+
126
+ repo, filename = hf_checkpoint
127
+ checkpoint = hf_hub_download(repo, filename)
128
+ self.model, _, self.preprocess = open_clip.create_model_and_transforms(model_name, pretrained=None)
129
+ ckpt = torch.load(checkpoint, map_location="cpu")
130
+ state = ckpt.get("state_dict", ckpt.get("model_state_dict", ckpt)) if isinstance(ckpt, dict) else ckpt
131
+ if any(key.startswith("module.") for key in state):
132
+ state = {key.removeprefix("module."): value for key, value in state.items()}
133
+ self.load_message = str(self.model.load_state_dict(state, strict=False))
134
+ self.checkpoint = checkpoint
135
+ else:
136
+ self.model, _, self.preprocess = open_clip.create_model_and_transforms(
137
+ model_name,
138
+ pretrained=pretrained,
139
+ )
140
+
141
+ self.tokenizer = open_clip.get_tokenizer(model_name)
142
+ self.model.to(device).eval()
143
+
144
+ def encode_text(self, prompts: Sequence[str]) -> torch.Tensor:
145
+ tokens = self.tokenizer(list(prompts)).to(self.device)
146
+ with torch.no_grad():
147
+ return normalize(self.model.encode_text(tokens))
148
+
149
+ def encode_images(self, images: Sequence[Image.Image]) -> torch.Tensor:
150
+ batch = torch.stack([self.preprocess(image) for image in images]).to(self.device)
151
+ with torch.no_grad():
152
+ return normalize(self.model.encode_image(batch))
153
+
154
+
155
+ class Siglip2Adapter(Adapter):
156
+ def __init__(self, device: torch.device):
157
+ from transformers import AutoModel, AutoProcessor
158
+
159
+ self.name = "google/siglip2-base-patch16-224"
160
+ self.family = "transformers_siglip2"
161
+ self.device = device
162
+ self.processor = AutoProcessor.from_pretrained(self.name)
163
+ self.model = AutoModel.from_pretrained(self.name).to(device).eval()
164
+
165
+ def encode_text(self, prompts: Sequence[str]) -> torch.Tensor:
166
+ inputs = self.processor(text=list(prompts), padding=True, return_tensors="pt").to(self.device)
167
+ with torch.no_grad():
168
+ if hasattr(self.model, "get_text_features"):
169
+ features = self.model.get_text_features(**inputs)
170
+ else:
171
+ features = self.model(**inputs).text_embeds
172
+ return normalize(features)
173
+
174
+ def encode_images(self, images: Sequence[Image.Image]) -> torch.Tensor:
175
+ inputs = self.processor(images=list(images), return_tensors="pt").to(self.device)
176
+ with torch.no_grad():
177
+ if hasattr(self.model, "get_image_features"):
178
+ features = self.model.get_image_features(**inputs)
179
+ else:
180
+ features = self.model(**inputs).image_embeds
181
+ return normalize(features)
182
+
183
+
184
+ def build_adapter(model_key: str, device: torch.device, cropvlm_checkpoint: str) -> Adapter:
185
+ if model_key == "cropvlm":
186
+ return OpenAIClipAdapter(device, checkpoint=cropvlm_checkpoint)
187
+ if model_key == "openai_clip_vit_b32":
188
+ return OpenAIClipAdapter(device)
189
+ if model_key == "bioclip":
190
+ return OpenClipAdapter("hf-hub:imageomics/bioclip", None, device)
191
+ if model_key == "bioclip2":
192
+ return OpenClipAdapter("hf-hub:imageomics/bioclip-2", None, device)
193
+ if model_key == "biotrove_clip":
194
+ return OpenClipAdapter(
195
+ "ViT-B-16",
196
+ None,
197
+ device,
198
+ hf_checkpoint=("BGLab/BioTrove-CLIP", "biotroveclip-vit-b-16-from-bioclip-epoch-8.pt"),
199
+ )
200
+ if model_key == "remoteclip":
201
+ return OpenClipAdapter(
202
+ "ViT-B-32",
203
+ None,
204
+ device,
205
+ hf_checkpoint=("chendelong/RemoteCLIP", "RemoteCLIP-ViT-B-32.pt"),
206
+ )
207
+ if model_key == "siglip2":
208
+ return Siglip2Adapter(device)
209
+ raise KeyError(
210
+ f"Unknown model '{model_key}'. Supported models: {', '.join(DEFAULT_MODELS)}. "
211
+ "TULIP, EVA-CLIP, and LongCLIP are intentionally excluded."
212
+ )
213
+
214
+
215
+ def per_class_stats(per_class: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
216
+ values = [item["accuracy"] for item in per_class.values() if item.get("accuracy") is not None]
217
+ if not values:
218
+ return {
219
+ "per_class_accuracy_mean": None,
220
+ "per_class_accuracy_std": None,
221
+ "per_class_accuracy_std_population": None,
222
+ "num_classes_with_accuracy": 0,
223
+ }
224
+ mean = sum(values) / len(values)
225
+ sample_std = math.sqrt(sum((x - mean) ** 2 for x in values) / (len(values) - 1)) if len(values) > 1 else 0.0
226
+ population_std = math.sqrt(sum((x - mean) ** 2 for x in values) / len(values))
227
+ return {
228
+ "per_class_accuracy_mean": mean,
229
+ "per_class_accuracy_std": sample_std,
230
+ "per_class_accuracy_std_population": population_std,
231
+ "num_classes_with_accuracy": len(values),
232
+ }
233
+
234
+
235
+ def evaluate_model(args: argparse.Namespace, dataset: ImageFolderPaths, model_key: str) -> Dict[str, Any]:
236
+ started_at = time.time()
237
+ device = torch.device(args.device or ("cuda" if torch.cuda.is_available() else "cpu"))
238
+ prompts = [args.prompt_template.format(display_name(class_name)) for class_name in dataset.classes]
239
+ result: Dict[str, Any] = {
240
+ "model_key": model_key,
241
+ "dataset": str(dataset.root),
242
+ "num_images": len(dataset),
243
+ "num_classes": len(dataset.classes),
244
+ "classes": dataset.classes,
245
+ "class_prompts": dict(zip(dataset.classes, prompts)),
246
+ "prompt_template": args.prompt_template,
247
+ "device": str(device),
248
+ "status": "started",
249
+ "started_at_unix": started_at,
250
+ }
251
+
252
+ try:
253
+ adapter = build_adapter(model_key, device, args.cropvlm_checkpoint)
254
+ result["model_name"] = adapter.name
255
+ result["family"] = adapter.family
256
+ result["checkpoint"] = adapter.checkpoint
257
+ result["load_message"] = adapter.load_message
258
+ text_features = adapter.encode_text(prompts).to(device)
259
+
260
+ loader = DataLoader(
261
+ dataset,
262
+ batch_size=args.batch_size,
263
+ shuffle=False,
264
+ num_workers=args.num_workers,
265
+ collate_fn=pil_collate,
266
+ )
267
+
268
+ class_total = [0 for _ in dataset.classes]
269
+ class_correct = [0 for _ in dataset.classes]
270
+ confusion = [[0 for _ in dataset.classes] for _ in dataset.classes]
271
+ predictions: List[Dict[str, Any]] = []
272
+ correct = 0
273
+
274
+ for images, labels, paths in tqdm(loader, desc=model_key):
275
+ image_features = adapter.encode_images(images)
276
+ logits = image_features @ text_features.T
277
+ pred = logits.argmax(dim=-1).detach().cpu()
278
+ scores = logits.max(dim=-1).values.detach().cpu()
279
+ for true_idx, pred_idx, score, path in zip(labels.tolist(), pred.tolist(), scores.tolist(), paths):
280
+ class_total[true_idx] += 1
281
+ class_correct[true_idx] += int(true_idx == pred_idx)
282
+ confusion[true_idx][pred_idx] += 1
283
+ correct += int(true_idx == pred_idx)
284
+ if args.save_predictions:
285
+ predictions.append(
286
+ {
287
+ "path": path,
288
+ "true_class": dataset.classes[true_idx],
289
+ "pred_class": dataset.classes[pred_idx],
290
+ "correct": true_idx == pred_idx,
291
+ "score": float(score),
292
+ }
293
+ )
294
+
295
+ per_class = {}
296
+ for idx, class_name in enumerate(dataset.classes):
297
+ total = class_total[idx]
298
+ per_class[class_name] = {
299
+ "correct": class_correct[idx],
300
+ "total": total,
301
+ "accuracy": class_correct[idx] / total if total else None,
302
+ }
303
+
304
+ result.update(
305
+ {
306
+ "status": "ok",
307
+ "accuracy": correct / len(dataset) if len(dataset) else None,
308
+ "correct": correct,
309
+ "per_class": per_class,
310
+ "confusion_matrix": confusion,
311
+ "predictions": predictions if args.save_predictions else None,
312
+ }
313
+ )
314
+ result.update(per_class_stats(per_class))
315
+ except Exception as exc:
316
+ result.update(
317
+ {
318
+ "status": "failed",
319
+ "error_type": type(exc).__name__,
320
+ "error": str(exc),
321
+ "traceback": traceback.format_exc(),
322
+ }
323
+ )
324
+
325
+ result["elapsed_seconds"] = time.time() - started_at
326
+ return result
327
+
328
+
329
+ def write_json(path: Path, data: Dict[str, Any]) -> None:
330
+ path.parent.mkdir(parents=True, exist_ok=True)
331
+ with open(path, "w") as f:
332
+ json.dump(data, f, indent=2)
333
+
334
+
335
+ def main():
336
+ parser = argparse.ArgumentParser()
337
+ parser.add_argument("--dataset", required=True, help="ImageFolder-style dataset root.")
338
+ parser.add_argument("--output", default="outputs/zero_shot_results.json")
339
+ parser.add_argument("--cropvlm-checkpoint", default="models/CropCLIP_FullDataset_Acc_0.75.pth")
340
+ parser.add_argument("--models", nargs="+", default=DEFAULT_MODELS)
341
+ parser.add_argument("--device", default=None)
342
+ parser.add_argument("--batch-size", type=int, default=64)
343
+ parser.add_argument("--num-workers", type=int, default=2)
344
+ parser.add_argument("--prompt-template", default="{}")
345
+ parser.add_argument("--save-predictions", action="store_true")
346
+ args = parser.parse_args()
347
+
348
+ excluded = {"tulip", "eva_clip", "eva_clip_official", "longclip"}
349
+ requested = [model for model in args.models if model not in excluded]
350
+ skipped = [model for model in args.models if model in excluded]
351
+
352
+ dataset = ImageFolderPaths(args.dataset)
353
+ results = [evaluate_model(args, dataset, model_key) for model_key in requested]
354
+ ok = [result for result in results if result.get("status") == "ok"]
355
+ failed = [result for result in results if result.get("status") != "ok"]
356
+ summary = {
357
+ "created_at": datetime.now(timezone.utc).isoformat(),
358
+ "dataset": str(dataset.root),
359
+ "num_images": len(dataset),
360
+ "num_classes": len(dataset.classes),
361
+ "classes": dataset.classes,
362
+ "requested_models": args.models,
363
+ "evaluated_models": requested,
364
+ "skipped_models": skipped,
365
+ "num_models": len(results),
366
+ "num_successful": len(ok),
367
+ "num_failed": len(failed),
368
+ "models": {
369
+ result["model_key"]: {
370
+ "status": result.get("status"),
371
+ "accuracy": result.get("accuracy"),
372
+ "correct": result.get("correct"),
373
+ "num_images": result.get("num_images"),
374
+ "per_class_accuracy_mean": result.get("per_class_accuracy_mean"),
375
+ "per_class_accuracy_std": result.get("per_class_accuracy_std"),
376
+ "per_class_accuracy_std_population": result.get("per_class_accuracy_std_population"),
377
+ "num_classes_with_accuracy": result.get("num_classes_with_accuracy"),
378
+ "elapsed_seconds": result.get("elapsed_seconds"),
379
+ "error": result.get("error"),
380
+ }
381
+ for result in results
382
+ },
383
+ "model_results": {result["model_key"]: result for result in results},
384
+ "results": results,
385
+ }
386
+ write_json(Path(args.output), summary)
387
+ print(Path(args.output))
388
+
389
+
390
+ if __name__ == "__main__":
391
+ main()
scripts/gradio_demo.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from threading import Lock
6
+ from pathlib import Path
7
+
8
+ from PIL import Image
9
+
10
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
11
+
12
+ from cropvlm import CROP_CLASSES, load_cropvlm
13
+ from cropvlm.model import parse_class_names
14
+
15
+
16
+ DEFAULT_CLASSES_TEXT = "\n".join(CROP_CLASSES)
17
+
18
+
19
+ def build_demo(checkpoint: str, device: str | None, prompt_template: str, top_k: int) -> gr.Blocks:
20
+ import gradio as gr
21
+
22
+ classifier = load_cropvlm(
23
+ checkpoint=checkpoint,
24
+ class_names=CROP_CLASSES,
25
+ device=device,
26
+ prompt_template=prompt_template,
27
+ )
28
+ classifier_lock = Lock()
29
+ current_classes = tuple(CROP_CLASSES)
30
+
31
+ def classify(image: Image.Image, classes_text: str, top_k_value: int):
32
+ if image is None:
33
+ return {}, []
34
+ nonlocal current_classes
35
+ requested_classes = tuple(parse_class_names(classes_text))
36
+ if not requested_classes:
37
+ return {}, []
38
+ with classifier_lock:
39
+ if requested_classes != current_classes:
40
+ classifier.set_classes(requested_classes)
41
+ current_classes = requested_classes
42
+ predictions = classifier.predict_with_scores(image, top_k=int(top_k_value))
43
+
44
+ label_scores = {label: probability for label, probability, _ in predictions}
45
+ score_text = "\n".join(
46
+ f"{rank}. {label}: probability={probability:.6f}, cosine={cosine:.6f}"
47
+ for rank, (label, probability, cosine) in enumerate(predictions, start=1)
48
+ )
49
+ return label_scores, score_text
50
+
51
+ examples_dir = Path(__file__).resolve().parents[1] / "examples"
52
+ example_paths = [
53
+ str(examples_dir / name)
54
+ for name in ["cacao.png", "olive.png", "cauliflower.png", "sugarcane.png", "sunflower.png"]
55
+ if (examples_dir / name).exists()
56
+ ]
57
+
58
+ with gr.Blocks(title="CropVLM Zero-Shot Demo") as demo:
59
+ gr.Markdown("# CropVLM Zero-Shot Image Classification")
60
+ with gr.Row():
61
+ with gr.Column():
62
+ image = gr.Image(type="pil", label="Image")
63
+ classes = gr.Textbox(
64
+ value=DEFAULT_CLASSES_TEXT,
65
+ lines=12,
66
+ label="Class names",
67
+ )
68
+ top_k_slider = gr.Slider(
69
+ minimum=1,
70
+ maximum=10,
71
+ value=top_k,
72
+ step=1,
73
+ label="Top-k",
74
+ )
75
+ button = gr.Button("Classify", variant="primary")
76
+ with gr.Column():
77
+ label = gr.Label(num_top_classes=top_k, label="Predictions")
78
+ score_text = gr.Textbox(
79
+ label="Scores",
80
+ lines=8,
81
+ interactive=False,
82
+ )
83
+
84
+ outputs = [label, score_text]
85
+ button.click(classify, inputs=[image, classes, top_k_slider], outputs=outputs)
86
+ classes.change(lambda: ({}, ""), outputs=outputs)
87
+
88
+ if example_paths:
89
+ gr.Examples(
90
+ examples=[[path, DEFAULT_CLASSES_TEXT, top_k] for path in example_paths],
91
+ inputs=[image, classes, top_k_slider],
92
+ outputs=outputs,
93
+ fn=classify,
94
+ cache_examples=False,
95
+ )
96
+
97
+ return demo
98
+
99
+
100
+ def main():
101
+ parser = argparse.ArgumentParser()
102
+ parser.add_argument("--checkpoint", default="models/CropCLIP_FullDataset_Acc_0.75.pth")
103
+ parser.add_argument("--device", default=None)
104
+ parser.add_argument("--prompt-template", default="{}")
105
+ parser.add_argument("--top-k", type=int, default=5)
106
+ parser.add_argument("--server-name", default="127.0.0.1")
107
+ parser.add_argument("--server-port", type=int, default=7860)
108
+ args = parser.parse_args()
109
+
110
+ demo = build_demo(
111
+ checkpoint=args.checkpoint,
112
+ device=args.device,
113
+ prompt_template=args.prompt_template,
114
+ top_k=args.top_k,
115
+ )
116
+ demo.launch(server_name=args.server_name, server_port=args.server_port)
117
+
118
+
119
+ if __name__ == "__main__":
120
+ main()