Skip to main content

scentience

Python client for Scentience olfaction instruments over BLE Bluetooth.

Installation

BLE only:

pip install scentience

BLE + COLIP embedding models:

pip install "scentience[models]"

Requirements

  • Python 3.8+
  • Bluetooth 4.0+ adapter
  • A Scentience developer API key (obtain from the Scentience portal)
  • For embedding models: torch, torchvision, transformers, huggingface-hub, Pillow (installed via [models] extra)

Connecting a single device

Auto-discover

Scans for the first Scentience device in range and connects to it.

import scentience as scn

device = scn.ScentienceDevice(api_key="YOUR_API_KEY")
device.connect_ble(char_uuid="YOUR_CHAR_UUID")

Target a specific device

Pass the device UID (serial number or BLE name) to connect to a particular instrument.

device.connect_ble(char_uuid="YOUR_CHAR_UUID", device_uid="A00022")

Take a single reading

data = device.sample_ble()   # returns dict
print(data)

Stream continuously

def on_sample(data: dict) -> None:
    print(data["UID"], data.get("CO2"), data.get("ENV_temperatureC"))

device.stream_ble(callback=on_sample)

# ... your application runs here ...

device.stop_stream()
device.disconnect()

Context manager

disconnect() is called automatically on exit.

with scn.ScentienceDevice(api_key="YOUR_API_KEY") as device:
    device.connect_ble(char_uuid="YOUR_CHAR_UUID", device_uid="A00022")
    data = device.sample_ble()
    print(data)

Connecting multiple devices

Pass a list of device UIDs to connect_ble. All devices are scanned for in a single BLE scan and connected concurrently. The API key and characteristic UUID are the same for every device.

Snapshot from all devices

import scentience as scn

device = scn.ScentienceDevice(api_key="YOUR_API_KEY")
device.connect_ble(
    char_uuid="YOUR_CHAR_UUID",
    device_uids=["A00022", "A00010"],   # as many UIDs as needed
)

readings = device.sample_ble()   # returns List[dict], one entry per device
for r in readings:
    print(r)

Stream from all devices simultaneously

The same callback receives packets from every device. Use the UID field to identify the source.

def on_sample(data: dict) -> None:
    print(f"[{data['UID']}]  CO2={data.get('CO2')}  temp={data.get('ENV_temperatureC')}°C")

device.stream_ble(callback=on_sample)

# ... your application runs here ...

device.stop_stream()
device.disconnect()

Context manager (multiple devices)

with scn.ScentienceDevice(api_key="YOUR_API_KEY") as device:
    device.connect_ble(
        char_uuid="YOUR_CHAR_UUID",
        device_uids=["A00022", "A00010"],
    )
    readings = device.sample_ble()

Discovering devices

Before connecting, use scan_devices() to see exactly what BLE devices are visible and confirm the names your instruments advertise.

nearby = scn.ScentienceDevice.scan_devices(timeout=10.0)
for d in nearby:
    print(d["name"], d["address"], d["rssi"])

Pass any value from the name column as device_uid / device_uids.


Logging and export

All readings from sample_ble() and stream_ble() are automatically buffered in memory across all connected devices.

print(device.log)             # list of dicts

device.export_json("readings.json")
device.export_csv("readings.csv")

device.clear_log()

CSV column order: UID and TIMESTAMP first, then all remaining fields alphabetically. Missing fields are written as empty values.


Response payload

Each reading dict may contain:

Key Description
UID Device serial number
TIMESTAMP Reading timestamp
ENV_temperatureC Ambient temperature (°C)
ENV_humidity Relative humidity (%)
ENV_pressureHpa Barometric pressure (hPa)
BATT_health Battery health
BATT_v Battery voltage
BATT_charge Battery charge (%)
BATT_time Estimated battery time remaining
STATUS_opuA Operational status
CO2, NH3, NO, NO2, CO, C2H5OH Chemical compounds (non-zero only)
H2, CH4, C3H8, C4H10, H2S, HCHO, SO2, VOC Chemical compounds (non-zero only)

COLIP embedding models

ColipModel integrates the Olfaction-Vision-Language Embeddings to produce joint embeddings across olfaction, vision, and language modalities.

Four variants are available:

Variant Embed dim Best for
colip-small-base 512 Fast inference / edge devices
colip-small-gat 512 Higher accuracy on edge devices
colip-large-base 2048 Accuracy-critical tasks
colip-large-gat 2048 Highest accuracy, slower inference

Weights are downloaded from HuggingFace Hub and cached locally on first use.

Example — small base model

import scentience as scn
from PIL import Image

model = scn.ColipModel.from_pretrained("colip-small-base")
# ColipModel(variant='colip-small-base', embed_dim=512, device='cpu')

image   = Image.open("scene.jpg")
olf_vec = [0.0] * 138          # 138-dimensional olfactory descriptor (required length)

embedding = model.embed(image, olf_vec)       # torch.Tensor, shape (512,)
arr       = model.embed_numpy(image, olf_vec) # numpy array

Example — large model

model = scn.ColipModel.from_pretrained("colip-large-gat")
embedding = model.embed(image, olf_vec)       # torch.Tensor, shape (2048,)

Example — BLE streaming + real-time embedding

import scentience as scn
from PIL import Image

model  = scn.ColipModel.from_pretrained("colip-small-base")
device = scn.ScentienceDevice(api_key="YOUR_API_KEY")
device.connect_ble(char_uuid="YOUR_CHAR_UUID", device_uid="A00022")

scene = Image.open("scene.jpg")

def on_sample(data: dict) -> None:
    # embed() requires exactly 138 values — pad the live channels into that vector.
    channels  = [float(data[k]) for k in sorted(data) if k not in ("UID", "TIMESTAMP")]
    olf_vec   = (channels + [0.0] * 138)[:138]
    embedding = model.embed(scene, olf_vec)
    print(f"embedding shape: {embedding.shape}, norm: {embedding.norm():.4f}")

device.stream_ble(callback=on_sample)

Targeting a specific compute backend

model = scn.ColipModel.from_pretrained("colip-large-base", device="cuda")  # GPU
model = scn.ColipModel(variant="colip-small-gat", device="mps")             # Apple Silicon

Cloud inference — OVL API

OVLClient calls the hosted Olfaction-Vision-Language model with an API key, so you don't download weights or install torch/transformers — it uses only the Python standard library. It maps a molecule, a gas-sensor reading, or text/image into one shared embedding space, and can localize which object in an image is emitting a detected aroma (with an optional heatmap overlay).

import scentience as scn

ovl = scn.OVLClient(api_key="YOUR_API_KEY")   # get a key from the Scentience portal

# 1) molecule -> embedding + predicted odor descriptors
r = ovl.embed_molecule("CC(=C)C1CCC(C)=CC1")  # limonene
print([d["descriptor"] for d in r["descriptors"]])
# -> ['citrus', 'terpenic', 'herbal', 'woody']

# 2) "which object in this image emits this smell?" + save the heatmap overlay
with open("scene.jpg", "rb") as f:
    image = f.read()
g = ovl.ground(image, smiles="CC(=C)C1CCC(C)=CC1", return_heatmap=True)
print(g["regions"][0])                         # highest-scoring image region
scn.OVLClient.save_heatmap(g, "aroma_heatmap.png")

The first vision call (ground / embed_image / embed_text) warms up the scale-to-zero server and can take ~1–2 minutes; warm calls are much faster. Vision methods use a longer timeout (vision_timeout=300s) by default — tune with OVLClient(api_key=…, vision_timeout=…), or pass ground(…, grid=2) for faster, coarser heatmaps.

method what it does
embed_molecule(smiles, top_k=8) molecule → shared-space embedding + odor descriptors
embed_sensor(readings, top_k=8) e-nose window [T, 6] → embedding + substance + descriptors
descriptors(smiles=… | readings=…) just the top odor descriptors
embed_text(text) / embed_image(bytes) text / image → shared-space embedding
ground(image, smiles=… | readings=…, return_heatmap=False, top_k=8) aroma-source regions (+ optional heatmap PNG)
info() / health() endpoint metadata / liveness

The embedding width is whatever the deployment reports — read it from info()["embed_dim"] or the dim field of an embedding response rather than hard-coding it.

ground() returns regions as {"box": [x, y, size, size], "score": …}, sorted best-first. grid sets the scanning window size, not a tile count: each window covers 1/max(2, grid) of the image's shorter side and windows overlap by 50%, so a higher grid means smaller, more numerous windows — finer and slower. How many regions come back depends on the image's aspect ratio too (a 535×360 photo yields 15 windows at grid=2 and 40 at grid=3).

Example — live device reading → cloud inference

import scentience as scn

ovl    = scn.OVLClient(api_key="YOUR_API_KEY")
device = scn.ScentienceDevice(api_key="YOUR_API_KEY")
device.connect_ble(char_uuid="YOUR_CHAR_UUID", device_uid="A00022")

# collect a short window of sensor samples, then embed it
window = [scn.OVLClient.device_reading_to_ovl(device.sample_ble()) for _ in range(64)]
result = ovl.embed_sensor(window)
print(result["substance"], [d["descriptor"] for d in result["descriptors"]])

Note on the sensor path. The OVL sensor encoder was calibrated against a reference MOX gas-sensor array whose channels don't line up 1:1 with the Scentience device. device_reading_to_ovl provides a best-effort mapping, so device-sourced sensor inference is experimental until the encoder is recalibrated to your hardware. The molecule and vision/grounding endpoints are unaffected and production-ready.

A private deployment can be targeted with OVLClient(api_key=..., base_url="https://your-host"). A runnable end-to-end script is in example_ovl_cloud.py.

Handling of your API key

OVLClient is built so a key cannot leak by accident:

  • base_url must be http:// or https:// — other schemes (file://, data:, …) are rejected.
  • Plain http:// to a non-loopback host raises a UserWarning, because the key would go out unencrypted.
  • On a redirect that changes host, or that downgrades https → http, the X-API-Key header is dropped rather than replayed to the new destination.
  • repr(client) shows only the base URL, so the key does not end up in logs or tracebacks.
  • Error bodies from the endpoint are truncated, and oversized responses are refused instead of being buffered into memory.

Keep the key in an environment variable (os.environ["SCENTIENCE_API_KEY"]) rather than in source.


API reference

See the full BLE API documentation.

License

Apache 2.0

Metadata

Release files for scentience 2.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for scentience 2.2.2
File Size Uploaded Provenance Actions
scentience-2.2.2.tar.gz 47.6 kB Without provenance Details for scentience-2.2.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for scentience 2.2.2
File Interpreter ABI Platform Actions
scentience-2.2.2-py3-none-any.whl Python 3 none any Details for scentience-2.2.2-py3-none-any.whl

Total release size: 76.7 kB

Release files / scentience-2.2.2.tar.gz

Download URL scentience-2.2.2.tar.gz
Size 47.6 kB
Tags Source
SHA-256 checksum
How to use checksums
70537dec84ec218bfc1957e14008f3ddaa11e77aeacf4a8130134f955a2d8490
BLAKE2b-256 checksum
How to use checksums
884161c12ecbc9f3e1d0a66dc4a336c967df9fd296df6679353b65799d5eaf39
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.0

Release files / scentience-2.2.2-py3-none-any.whl

Download URL scentience-2.2.2-py3-none-any.whl
Size 29.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
713b9f1020cf93ef4346381140a39cfe55aacfabebb93e9fcc52f1a5a1581692
BLAKE2b-256 checksum
How to use checksums
e16cd267648d28039b28117ec135aa9573da191942288190a98763b8aea5b9b1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.0

Security for scentience 2.2.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page