scentience 2.2.0__tar.gz → 2.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scentience
3
- Version: 2.2.0
3
+ Version: 2.2.2
4
4
  Summary: Python client for Scentience olfaction instruments over BLE, with a hosted OVL inference client
5
5
  Project-URL: Documentation, https://scentience.github.io/docs-api/ble-api
6
6
  Project-URL: Repository, https://github.com/scentience/scentience-pypi
@@ -404,12 +404,12 @@ Each reading dict may contain:
404
404
 
405
405
  Four variants are available:
406
406
 
407
- | Variant | Embed dim | Architecture | Best for |
408
- |---------|-----------|--------------|----------|
409
- | `colip-small-base` | 512 | base GNN | Fast inference / edge devices |
410
- | `colip-small-gat` | 512 | GAT | Higher accuracy on edge devices |
411
- | `colip-large-base` | 2048 | base GNN | Accuracy-critical tasks |
412
- | `colip-large-gat` | 2048 | GAT | Highest accuracy, slower inference |
407
+ | Variant | Embed dim | Best for |
408
+ |---------|-----------|----------|
409
+ | `colip-small-base` | 512 | Fast inference / edge devices |
410
+ | `colip-small-gat` | 512 | Higher accuracy on edge devices |
411
+ | `colip-large-base` | 2048 | Accuracy-critical tasks |
412
+ | `colip-large-gat` | 2048 | Highest accuracy, slower inference |
413
413
 
414
414
  Weights are downloaded from HuggingFace Hub and cached locally on first use.
415
415
 
@@ -423,13 +423,13 @@ model = scn.ColipModel.from_pretrained("colip-small-base")
423
423
  # ColipModel(variant='colip-small-base', embed_dim=512, device='cpu')
424
424
 
425
425
  image = Image.open("scene.jpg")
426
- olf_vec = [0.0] * 138 # 138-dimensional olfactory descriptor
426
+ olf_vec = [0.0] * 138 # 138-dimensional olfactory descriptor (required length)
427
427
 
428
428
  embedding = model.embed(image, olf_vec) # torch.Tensor, shape (512,)
429
429
  arr = model.embed_numpy(image, olf_vec) # numpy array
430
430
  ```
431
431
 
432
- ### Example — large GAT model
432
+ ### Example — large model
433
433
 
434
434
  ```python
435
435
  model = scn.ColipModel.from_pretrained("colip-large-gat")
@@ -449,7 +449,9 @@ device.connect_ble(char_uuid="YOUR_CHAR_UUID", device_uid="A00022")
449
449
  scene = Image.open("scene.jpg")
450
450
 
451
451
  def on_sample(data: dict) -> None:
452
- olf_vec = [data.get(k, 0.0) for k in sorted(data) if k not in ("UID", "TIMESTAMP")]
452
+ # embed() requires exactly 138 values — pad the live channels into that vector.
453
+ channels = [float(data[k]) for k in sorted(data) if k not in ("UID", "TIMESTAMP")]
454
+ olf_vec = (channels + [0.0] * 138)[:138]
453
455
  embedding = model.embed(scene, olf_vec)
454
456
  print(f"embedding shape: {embedding.shape}, norm: {embedding.norm():.4f}")
455
457
 
@@ -491,15 +493,29 @@ print(g["regions"][0]) # highest-scoring image region
491
493
  scn.OVLClient.save_heatmap(g, "aroma_heatmap.png")
492
494
  ```
493
495
 
496
+ > The **first** vision call (`ground` / `embed_image` / `embed_text`) warms up the
497
+ > scale-to-zero server and can take ~1–2 minutes; warm calls are much faster. Vision methods use a
498
+ > longer timeout (`vision_timeout=300s`) by default — tune with
499
+ > `OVLClient(api_key=…, vision_timeout=…)`, or pass `ground(…, grid=2)` for faster, coarser heatmaps.
500
+
494
501
  | method | what it does |
495
502
  |--------|--------------|
496
- | `embed_molecule(smiles, top_k=8)` | molecule → 1152-d embedding + odor descriptors |
503
+ | `embed_molecule(smiles, top_k=8)` | molecule → shared-space embedding + odor descriptors |
497
504
  | `embed_sensor(readings, top_k=8)` | e-nose window `[T, 6]` → embedding + substance + descriptors |
498
505
  | `descriptors(smiles=… \| readings=…)` | just the top odor descriptors |
499
506
  | `embed_text(text)` / `embed_image(bytes)` | text / image → shared-space embedding |
500
- | `ground(image, smiles=… \| readings=…, return_heatmap=False)` | aroma-source regions (+ optional heatmap PNG) |
507
+ | `ground(image, smiles=… \| readings=…, return_heatmap=False, top_k=8)` | aroma-source regions (+ optional heatmap PNG) |
501
508
  | `info()` / `health()` | endpoint metadata / liveness |
502
509
 
510
+ The embedding width is whatever the deployment reports — read it from `info()["embed_dim"]`
511
+ or the `dim` field of an embedding response rather than hard-coding it.
512
+
513
+ `ground()` returns `regions` as `{"box": [x, y, size, size], "score": …}`, sorted best-first.
514
+ `grid` sets the scanning **window size**, not a tile count: each window covers `1/max(2, grid)`
515
+ of the image's shorter side and windows overlap by 50%, so a higher `grid` means smaller,
516
+ more numerous windows — finer and slower. How many regions come back depends on the image's
517
+ aspect ratio too (a 535×360 photo yields 15 windows at `grid=2` and 40 at `grid=3`).
518
+
503
519
  ### Example — live device reading → cloud inference
504
520
 
505
521
  ```python
@@ -515,15 +531,29 @@ result = ovl.embed_sensor(window)
515
531
  print(result["substance"], [d["descriptor"] for d in result["descriptors"]])
516
532
  ```
517
533
 
518
- > **Note on the sensor path.** The OVL **sensor** encoder was trained on the SmellNet MOX
519
- > array, whose channels don't line up 1:1 with the Scentience device. `device_reading_to_ovl`
520
- > provides a best-effort mapping, so device-sourced *sensor* inference is **experimental**
521
- > until the encoder is recalibrated to your hardware. The **molecule** and **vision/grounding**
522
- > endpoints are unaffected and production-ready.
534
+ > **Note on the sensor path.** The OVL **sensor** encoder was calibrated against a reference
535
+ > MOX gas-sensor array whose channels don't line up 1:1 with the Scentience device.
536
+ > `device_reading_to_ovl` provides a best-effort mapping, so device-sourced *sensor* inference
537
+ > is **experimental** until the encoder is recalibrated to your hardware. The **molecule** and
538
+ > **vision/grounding** endpoints are unaffected and production-ready.
523
539
 
524
540
  A private deployment can be targeted with `OVLClient(api_key=..., base_url="https://your-host")`.
525
541
  A runnable end-to-end script is in [`example_ovl_cloud.py`](example_ovl_cloud.py).
526
542
 
543
+ ### Handling of your API key
544
+
545
+ `OVLClient` is built so a key cannot leak by accident:
546
+
547
+ - `base_url` must be `http://` or `https://` — other schemes (`file://`, `data:`, …) are rejected.
548
+ - Plain `http://` to a non-loopback host raises a `UserWarning`, because the key would go out unencrypted.
549
+ - On a redirect that changes host, or that downgrades `https` → `http`, the `X-API-Key` header is
550
+ **dropped** rather than replayed to the new destination.
551
+ - `repr(client)` shows only the base URL, so the key does not end up in logs or tracebacks.
552
+ - Error bodies from the endpoint are truncated, and oversized responses are refused instead of
553
+ being buffered into memory.
554
+
555
+ Keep the key in an environment variable (`os.environ["SCENTIENCE_API_KEY"]`) rather than in source.
556
+
527
557
  ---
528
558
 
529
559
  ## API reference
@@ -185,12 +185,12 @@ Each reading dict may contain:
185
185
 
186
186
  Four variants are available:
187
187
 
188
- | Variant | Embed dim | Architecture | Best for |
189
- |---------|-----------|--------------|----------|
190
- | `colip-small-base` | 512 | base GNN | Fast inference / edge devices |
191
- | `colip-small-gat` | 512 | GAT | Higher accuracy on edge devices |
192
- | `colip-large-base` | 2048 | base GNN | Accuracy-critical tasks |
193
- | `colip-large-gat` | 2048 | GAT | Highest accuracy, slower inference |
188
+ | Variant | Embed dim | Best for |
189
+ |---------|-----------|----------|
190
+ | `colip-small-base` | 512 | Fast inference / edge devices |
191
+ | `colip-small-gat` | 512 | Higher accuracy on edge devices |
192
+ | `colip-large-base` | 2048 | Accuracy-critical tasks |
193
+ | `colip-large-gat` | 2048 | Highest accuracy, slower inference |
194
194
 
195
195
  Weights are downloaded from HuggingFace Hub and cached locally on first use.
196
196
 
@@ -204,13 +204,13 @@ model = scn.ColipModel.from_pretrained("colip-small-base")
204
204
  # ColipModel(variant='colip-small-base', embed_dim=512, device='cpu')
205
205
 
206
206
  image = Image.open("scene.jpg")
207
- olf_vec = [0.0] * 138 # 138-dimensional olfactory descriptor
207
+ olf_vec = [0.0] * 138 # 138-dimensional olfactory descriptor (required length)
208
208
 
209
209
  embedding = model.embed(image, olf_vec) # torch.Tensor, shape (512,)
210
210
  arr = model.embed_numpy(image, olf_vec) # numpy array
211
211
  ```
212
212
 
213
- ### Example — large GAT model
213
+ ### Example — large model
214
214
 
215
215
  ```python
216
216
  model = scn.ColipModel.from_pretrained("colip-large-gat")
@@ -230,7 +230,9 @@ device.connect_ble(char_uuid="YOUR_CHAR_UUID", device_uid="A00022")
230
230
  scene = Image.open("scene.jpg")
231
231
 
232
232
  def on_sample(data: dict) -> None:
233
- olf_vec = [data.get(k, 0.0) for k in sorted(data) if k not in ("UID", "TIMESTAMP")]
233
+ # embed() requires exactly 138 values — pad the live channels into that vector.
234
+ channels = [float(data[k]) for k in sorted(data) if k not in ("UID", "TIMESTAMP")]
235
+ olf_vec = (channels + [0.0] * 138)[:138]
234
236
  embedding = model.embed(scene, olf_vec)
235
237
  print(f"embedding shape: {embedding.shape}, norm: {embedding.norm():.4f}")
236
238
 
@@ -272,15 +274,29 @@ print(g["regions"][0]) # highest-scoring image region
272
274
  scn.OVLClient.save_heatmap(g, "aroma_heatmap.png")
273
275
  ```
274
276
 
277
+ > The **first** vision call (`ground` / `embed_image` / `embed_text`) warms up the
278
+ > scale-to-zero server and can take ~1–2 minutes; warm calls are much faster. Vision methods use a
279
+ > longer timeout (`vision_timeout=300s`) by default — tune with
280
+ > `OVLClient(api_key=…, vision_timeout=…)`, or pass `ground(…, grid=2)` for faster, coarser heatmaps.
281
+
275
282
  | method | what it does |
276
283
  |--------|--------------|
277
- | `embed_molecule(smiles, top_k=8)` | molecule → 1152-d embedding + odor descriptors |
284
+ | `embed_molecule(smiles, top_k=8)` | molecule → shared-space embedding + odor descriptors |
278
285
  | `embed_sensor(readings, top_k=8)` | e-nose window `[T, 6]` → embedding + substance + descriptors |
279
286
  | `descriptors(smiles=… \| readings=…)` | just the top odor descriptors |
280
287
  | `embed_text(text)` / `embed_image(bytes)` | text / image → shared-space embedding |
281
- | `ground(image, smiles=… \| readings=…, return_heatmap=False)` | aroma-source regions (+ optional heatmap PNG) |
288
+ | `ground(image, smiles=… \| readings=…, return_heatmap=False, top_k=8)` | aroma-source regions (+ optional heatmap PNG) |
282
289
  | `info()` / `health()` | endpoint metadata / liveness |
283
290
 
291
+ The embedding width is whatever the deployment reports — read it from `info()["embed_dim"]`
292
+ or the `dim` field of an embedding response rather than hard-coding it.
293
+
294
+ `ground()` returns `regions` as `{"box": [x, y, size, size], "score": …}`, sorted best-first.
295
+ `grid` sets the scanning **window size**, not a tile count: each window covers `1/max(2, grid)`
296
+ of the image's shorter side and windows overlap by 50%, so a higher `grid` means smaller,
297
+ more numerous windows — finer and slower. How many regions come back depends on the image's
298
+ aspect ratio too (a 535×360 photo yields 15 windows at `grid=2` and 40 at `grid=3`).
299
+
284
300
  ### Example — live device reading → cloud inference
285
301
 
286
302
  ```python
@@ -296,15 +312,29 @@ result = ovl.embed_sensor(window)
296
312
  print(result["substance"], [d["descriptor"] for d in result["descriptors"]])
297
313
  ```
298
314
 
299
- > **Note on the sensor path.** The OVL **sensor** encoder was trained on the SmellNet MOX
300
- > array, whose channels don't line up 1:1 with the Scentience device. `device_reading_to_ovl`
301
- > provides a best-effort mapping, so device-sourced *sensor* inference is **experimental**
302
- > until the encoder is recalibrated to your hardware. The **molecule** and **vision/grounding**
303
- > endpoints are unaffected and production-ready.
315
+ > **Note on the sensor path.** The OVL **sensor** encoder was calibrated against a reference
316
+ > MOX gas-sensor array whose channels don't line up 1:1 with the Scentience device.
317
+ > `device_reading_to_ovl` provides a best-effort mapping, so device-sourced *sensor* inference
318
+ > is **experimental** until the encoder is recalibrated to your hardware. The **molecule** and
319
+ > **vision/grounding** endpoints are unaffected and production-ready.
304
320
 
305
321
  A private deployment can be targeted with `OVLClient(api_key=..., base_url="https://your-host")`.
306
322
  A runnable end-to-end script is in [`example_ovl_cloud.py`](example_ovl_cloud.py).
307
323
 
324
+ ### Handling of your API key
325
+
326
+ `OVLClient` is built so a key cannot leak by accident:
327
+
328
+ - `base_url` must be `http://` or `https://` — other schemes (`file://`, `data:`, …) are rejected.
329
+ - Plain `http://` to a non-loopback host raises a `UserWarning`, because the key would go out unencrypted.
330
+ - On a redirect that changes host, or that downgrades `https` → `http`, the `X-API-Key` header is
331
+ **dropped** rather than replayed to the new destination.
332
+ - `repr(client)` shows only the base URL, so the key does not end up in logs or tracebacks.
333
+ - Error bodies from the endpoint are truncated, and oversized responses are refused instead of
334
+ being buffered into memory.
335
+
336
+ Keep the key in an environment variable (`os.environ["SCENTIENCE_API_KEY"]`) rather than in source.
337
+
308
338
  ---
309
339
 
310
340
  ## API reference
@@ -4,19 +4,26 @@ Example: hitting the hosted Scentience OVL inference API (no local models requir
4
4
  pip install scentience
5
5
  python example_ovl_cloud.py
6
6
 
7
- Fill in API_KEY below. SCENE_IMAGE is optional — the vision/grounding part is skipped
8
- if the file is missing.
7
+ Set SCENTIENCE_API_KEY in your environment (keeping keys out of source is safer than
8
+ editing them in). SCENE_IMAGE is optional — the vision/grounding part is skipped if the
9
+ file is missing.
9
10
  """
11
+ import os
12
+ import sys
13
+
10
14
  from scentience import OVLClient
11
15
 
12
16
  # ── Configuration ────────────────────────────────────────────────────────────
13
- API_KEY = "<YOUR_API_KEY>" # from the Scentience portal
17
+ API_KEY = os.environ.get("SCENTIENCE_API_KEY", "") # from the Scentience portal
14
18
  SCENE_IMAGE = "scene.jpg" # an image to localize an aroma in (optional)
15
19
  SMILES = "CC(=C)C1CCC(C)=CC1" # limonene (a citrus aroma molecule)
16
20
  # ─────────────────────────────────────────────────────────────────────────────
17
21
 
18
22
 
19
23
  def main() -> None:
24
+ if not API_KEY:
25
+ sys.exit("set SCENTIENCE_API_KEY in your environment first")
26
+
20
27
  ovl = OVLClient(api_key=API_KEY)
21
28
 
22
29
  print("endpoint:", ovl.info()["version"])
@@ -35,6 +42,7 @@ def main() -> None:
35
42
  print(f"\n(skipping grounding — '{SCENE_IMAGE}' not found)")
36
43
  return
37
44
 
45
+ print("\nlocalizing aroma (the first vision call warms the server — can take ~1-2 min)...")
38
46
  g = ovl.ground(image, smiles=SMILES, return_heatmap=True, grid=3)
39
47
  top = g["regions"][0]
40
48
  print(f"\naroma source in '{SCENE_IMAGE}':")
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "scentience"
7
- version = "2.2.0"
7
+ version = "2.2.2"
8
8
  description = "Python client for Scentience olfaction instruments over BLE, with a hosted OVL inference client"
9
9
  readme = "README.md"
10
10
  license = { file = "LICENSE" }
@@ -0,0 +1,15 @@
1
+ # Convenience install for local development: the BLE client plus the optional
2
+ # [models] extra. pyproject.toml is the authoritative source of these constraints —
3
+ # keep the two in step (tests/test_distribution_hygiene.py checks that they agree).
4
+ #
5
+ # Note: `pip install scentience` needs none of this. The hosted OVLClient is
6
+ # stdlib-only, and bleak is the only hard runtime dependency.
7
+ bleak>=0.21.0
8
+
9
+ # [models] extra — only needed to run ColipModel locally.
10
+ torch>=2.0.0
11
+ torchvision>=0.15.0
12
+ transformers>=4.30.0
13
+ huggingface-hub>=0.16.0
14
+ Pillow>=9.0.0
15
+ numpy>=1.24.0
@@ -16,7 +16,7 @@ __all__ = [
16
16
  "OVL_SENSOR_CHANNELS",
17
17
  "DEFAULT_BASE_URL",
18
18
  ]
19
- __version__ = "2.2.0"
19
+ __version__ = "2.2.2"
20
20
 
21
21
 
22
22
  def __getattr__(name: str):
@@ -11,6 +11,32 @@ from bleak import BleakClient, BleakScanner
11
11
  from bleak.backends.device import BLEDevice
12
12
 
13
13
 
14
+ def _decode_reading(raw) -> Optional[dict]:
15
+ """Decode one BLE packet into a reading dict, or ``None`` if it is unusable.
16
+
17
+ Packet contents come straight off the air, so nothing here may raise: a corrupt
18
+ or hostile payload has to be dropped rather than take down the BLE callback
19
+ thread. Anything that is not a JSON object is rejected too — the rest of the
20
+ client (logging, CSV export, callbacks) is written against dicts.
21
+ """
22
+ try:
23
+ payload = json.loads(bytes(raw).decode("utf-8"))
24
+ except (ValueError, UnicodeDecodeError, RecursionError, TypeError):
25
+ return None
26
+ return payload if isinstance(payload, dict) else None
27
+
28
+
29
+ def _require_reading(raw) -> dict:
30
+ """Like :func:`_decode_reading`, but for the request/response path where the
31
+ caller is waiting on a value and silence would be worse than an error."""
32
+ payload = _decode_reading(raw)
33
+ if payload is None:
34
+ raise RuntimeError(
35
+ "Device returned an unreadable packet (expected a JSON object)."
36
+ )
37
+ return payload
38
+
39
+
14
40
  class ScentienceDevice:
15
41
  """
16
42
  Python client for Scentience olfaction instruments over BLE.
@@ -344,23 +370,22 @@ class ScentienceDevice:
344
370
  async def _sample_async(self) -> dict:
345
371
  client = next(iter(self._clients.values()))
346
372
  raw = await client.read_gatt_char(self._char_uuid)
347
- return json.loads(raw.decode("utf-8"))
373
+ return _require_reading(raw)
348
374
 
349
375
  async def _sample_all_async(self) -> List[dict]:
350
376
  async def _read_one(client: BleakClient) -> dict:
351
377
  raw = await client.read_gatt_char(self._char_uuid)
352
- return json.loads(raw.decode("utf-8"))
378
+ return _require_reading(raw)
353
379
 
354
380
  return list(await asyncio.gather(*[_read_one(c) for c in self._clients.values()]))
355
381
 
356
382
  async def _start_notify_async(self, callback: Callable[[dict], None]) -> None:
357
383
  def _handler(sender, data: bytearray) -> None:
358
- try:
359
- payload = json.loads(data.decode("utf-8"))
360
- self._log.append(payload)
361
- callback(payload)
362
- except (json.JSONDecodeError, UnicodeDecodeError):
363
- pass # drop malformed packets silently
384
+ payload = _decode_reading(data)
385
+ if payload is None:
386
+ return # drop malformed packets silently
387
+ self._log.append(payload)
388
+ callback(payload)
364
389
 
365
390
  await asyncio.gather(*[
366
391
  client.start_notify(self._char_uuid, _handler)
@@ -4,12 +4,8 @@ COLIP: Olfaction-Vision-Language Embedding models.
4
4
  Four variants are available, all hosted at:
5
5
  kordelfrance/Olfaction-Vision-Language-Embeddings
6
6
 
7
- Each model combines:
8
- - A CLIP vision-language backbone (openai/clip-vit-base-patch32)
9
- - A TorchScript olfactory encoder
10
- - A TorchScript graph neural network (base) or graph-attention network (gat)
11
-
12
- The result is a joint embedding that aligns olfaction, vision, and language
7
+ Each variant fuses a pretrained vision-language backbone with trained olfactory
8
+ components to produce a joint embedding that aligns olfaction, vision, and language
13
9
  in a shared latent space.
14
10
  """
15
11
  from __future__ import annotations
@@ -21,35 +17,38 @@ import torch.nn as nn
21
17
  from huggingface_hub import hf_hub_download
22
18
  from PIL import Image
23
19
  from torchvision import transforms
24
- from transformers import CLIPModel
20
+ from transformers import AutoModel
25
21
 
26
22
  _HF_REPO = "kordelfrance/Olfaction-Vision-Language-Embeddings"
27
- _CLIP_BACKBONE = "openai/clip-vit-base-patch32"
23
+ _VISION_BACKBONE = "openai/clip-vit-base-patch32"
24
+
25
+ #: Expected length of the olfactory descriptor vector passed to :meth:`ColipModel.embed`.
26
+ OLF_VECTOR_DIM = 138
28
27
 
29
28
  # Maps public variant name → file paths inside the HF repo and config.
30
29
  _VARIANTS: dict = {
31
30
  "colip-small-base": {
32
31
  "embed_dim": 512,
33
32
  "encoder_file": "model/colip-small/base/olf_encoder_512.pt",
34
- "gnn_file": "model/colip-small/base/gnn_512.pt",
33
+ "fusion_file": "model/colip-small/base/gnn_512.pt",
35
34
  "is_gat": False,
36
35
  },
37
36
  "colip-small-gat": {
38
37
  "embed_dim": 512,
39
38
  "encoder_file": "model/colip-small/gat/olf_encoder_gat_512.pt",
40
- "gnn_file": "model/colip-small/gat/gnn_gat_512.pt",
39
+ "fusion_file": "model/colip-small/gat/gnn_gat_512.pt",
41
40
  "is_gat": True,
42
41
  },
43
42
  "colip-large-base": {
44
43
  "embed_dim": 2048,
45
44
  "encoder_file": "model/colip-large/base/olf_encoder_2048.pt",
46
- "gnn_file": "model/colip-large/base/gnn_2048.pt",
45
+ "fusion_file": "model/colip-large/base/gnn_2048.pt",
47
46
  "is_gat": False,
48
47
  },
49
48
  "colip-large-gat": {
50
49
  "embed_dim": 2048,
51
50
  "encoder_file": "model/colip-large/gat/olf_encoder_gat_2048.pt",
52
- "gnn_file": "model/colip-large/gat/gnn_gat_2048.pt",
51
+ "fusion_file": "model/colip-large/gat/gnn_gat_2048.pt",
53
52
  "is_gat": True,
54
53
  },
55
54
  }
@@ -64,20 +63,19 @@ class ColipModel:
64
63
  """
65
64
  COLIP: Olfaction-Vision-Language Embedding model.
66
65
 
67
- Produces joint olfaction-vision-language embeddings by fusing a CLIP
68
- vision backbone with a trained olfactory encoder and a graph neural
69
- network (base variants) or graph-attention network (gat variants).
66
+ Produces joint olfaction-vision-language embeddings from an image and an
67
+ olfactory descriptor vector.
70
68
 
71
69
  Four variants are available:
72
70
 
73
- =================== ========== ============ ================================
74
- Variant Embed dim Architecture Best for
75
- =================== ========== ============ ================================
76
- ``colip-small-base`` 512 base GNN Fast inference / edge devices
77
- ``colip-small-gat`` 512 GAT Higher accuracy on edge devices
78
- ``colip-large-base`` 2048 base GNN Accuracy-critical tasks
79
- ``colip-large-gat`` 2048 GAT Highest accuracy, slower
80
- =================== ========== ============ ================================
71
+ =================== ========== ================================
72
+ Variant Embed dim Best for
73
+ =================== ========== ================================
74
+ ``colip-small-base`` 512 Fast inference / edge devices
75
+ ``colip-small-gat`` 512 Higher accuracy on edge devices
76
+ ``colip-large-base`` 2048 Accuracy-critical tasks
77
+ ``colip-large-gat`` 2048 Highest accuracy, slower
78
+ =================== ========== ================================
81
79
 
82
80
  Model weights are downloaded automatically from HuggingFace Hub and cached
83
81
  locally on first use.
@@ -98,14 +96,18 @@ class ColipModel:
98
96
 
99
97
  arr = model.embed_numpy(image, olf_vec) # np.ndarray (512,)
100
98
 
101
- Example — large GAT variant::
99
+ Example — large variant::
102
100
 
103
101
  model = scn.ColipModel.from_pretrained("colip-large-gat")
104
102
  embedding = model.embed(image, olf_vec) # torch.Tensor (2048,)
105
103
  """
106
104
 
107
105
  HF_REPO: str = _HF_REPO
108
- CLIP_BACKBONE: str = _CLIP_BACKBONE
106
+ VISION_BACKBONE: str = _VISION_BACKBONE
107
+ OLF_VECTOR_DIM: int = OLF_VECTOR_DIM
108
+
109
+ #: Public variant names accepted by :meth:`from_pretrained`.
110
+ VARIANTS: tuple = tuple(_VARIANTS)
109
111
 
110
112
  def __init__(
111
113
  self,
@@ -138,11 +140,9 @@ class ColipModel:
138
140
  self._is_gat: bool = cfg["is_gat"]
139
141
  self.device: torch.device = _resolve_device(device)
140
142
 
141
- # --- CLIP vision-language backbone ---
142
- self._clip: CLIPModel = (
143
- CLIPModel.from_pretrained(self.CLIP_BACKBONE).to(self.device)
144
- )
145
- self._clip.eval()
143
+ # --- pretrained vision-language backbone ---
144
+ self._vision = AutoModel.from_pretrained(self.VISION_BACKBONE).to(self.device)
145
+ self._vision.eval()
146
146
 
147
147
  # --- TorchScript olfactory encoder ---
148
148
  encoder_path = hf_hub_download(
@@ -153,19 +153,19 @@ class ColipModel:
153
153
  )
154
154
  self._olf_encoder.eval()
155
155
 
156
- # --- TorchScript GNN / GAT ---
157
- gnn_path = hf_hub_download(
158
- repo_id=self.HF_REPO, filename=cfg["gnn_file"]
156
+ # --- TorchScript fusion head ---
157
+ fusion_path = hf_hub_download(
158
+ repo_id=self.HF_REPO, filename=cfg["fusion_file"]
159
159
  )
160
- self._gnn = torch.jit.load(gnn_path, map_location=self.device)
161
- self._gnn.eval()
160
+ self._fusion = torch.jit.load(fusion_path, map_location=self.device)
161
+ self._fusion.eval()
162
162
 
163
- # CLIP base-patch32 outputs 512-dim vectors. Large COLIP variants
164
- # operate in 2048-dim space, so we add a learned projection.
165
- clip_proj_dim: int = self._clip.config.projection_dim # 512
166
- if self.embed_dim != clip_proj_dim:
163
+ # The backbone emits 512-dim vectors. Large COLIP variants operate in
164
+ # 2048-dim space, so we add a projection.
165
+ backbone_dim: int = self._vision.config.projection_dim # 512
166
+ if self.embed_dim != backbone_dim:
167
167
  self._vision_proj: nn.Module | None = nn.Linear(
168
- clip_proj_dim, self.embed_dim
168
+ backbone_dim, self.embed_dim
169
169
  ).to(self.device)
170
170
  else:
171
171
  self._vision_proj = None
@@ -216,17 +216,20 @@ class ColipModel:
216
216
 
217
217
  Returns:
218
218
  torch.Tensor: 1-D embedding of shape ``(embed_dim,)``.
219
+
220
+ Raises:
221
+ TypeError: If *image* is not a PIL Image.
222
+ ValueError: If *olf_vec* is not a 1-D vector of length 138.
219
223
  """
224
+ if not isinstance(image, Image.Image):
225
+ raise TypeError(
226
+ f"image must be a PIL.Image.Image, got {type(image).__name__}"
227
+ )
220
228
  img_tensor = _IMAGE_TRANSFORM(image).unsqueeze(0).to(self.device)
221
-
222
- if not isinstance(olf_vec, torch.Tensor):
223
- olf_tensor = torch.tensor(olf_vec, dtype=torch.float32)
224
- else:
225
- olf_tensor = olf_vec.float()
226
- olf_tensor = olf_tensor.unsqueeze(0).to(self.device)
229
+ olf_tensor = _as_olf_tensor(olf_vec).unsqueeze(0).to(self.device)
227
230
 
228
231
  with torch.no_grad():
229
- vision_embed = self._clip.get_image_features(pixel_values=img_tensor)
232
+ vision_embed = self._vision.get_image_features(pixel_values=img_tensor)
230
233
 
231
234
  if self._vision_proj is not None:
232
235
  vision_embed = self._vision_proj(vision_embed)
@@ -241,9 +244,9 @@ class ColipModel:
241
244
  torch.arange(n, device=self.device),
242
245
  torch.arange(n, device=self.device),
243
246
  ).T
244
- result = self._gnn(nodes, edge_index)
247
+ result = self._fusion(nodes, edge_index)
245
248
  else:
246
- result = self._gnn(vision_embed, olf_embed)
249
+ result = self._fusion(vision_embed, olf_embed)
247
250
 
248
251
  return result.squeeze()
249
252
 
@@ -280,6 +283,28 @@ class ColipModel:
280
283
  # Helpers
281
284
  # ------------------------------------------------------------------
282
285
 
286
+ def _as_olf_tensor(olf_vec: Union[List[float], "torch.Tensor"]) -> torch.Tensor:
287
+ """Coerce *olf_vec* to a 1-D float32 tensor of length :data:`OLF_VECTOR_DIM`."""
288
+ if isinstance(olf_vec, torch.Tensor):
289
+ tensor = olf_vec.detach().float()
290
+ else:
291
+ try:
292
+ tensor = torch.as_tensor(olf_vec, dtype=torch.float32)
293
+ except (TypeError, ValueError, RuntimeError):
294
+ raise ValueError(
295
+ "olf_vec must be a sequence of floats, a NumPy array, or a torch.Tensor"
296
+ ) from None
297
+ if tensor.ndim != 1:
298
+ raise ValueError(f"olf_vec must be 1-D, got shape {tuple(tensor.shape)}")
299
+ if tensor.numel() != OLF_VECTOR_DIM:
300
+ raise ValueError(
301
+ f"olf_vec must have {OLF_VECTOR_DIM} elements, got {tensor.numel()}"
302
+ )
303
+ if not bool(torch.isfinite(tensor).all()):
304
+ raise ValueError("olf_vec contains NaN or infinity")
305
+ return tensor
306
+
307
+
283
308
  def _resolve_device(device: str | None) -> torch.device:
284
309
  if device is not None:
285
310
  return torch.device(device)