Python API reference¶
One-import Python API: from tokeye import TokEye.
Gradio-free, so it is safe to embed in headless programs. TokEye()
loads the default model (auto-downloading it from Hugging Face on first
use)::
from tokeye import TokEye
eye = TokEye()
seg = eye.segment(signal, fs=500e3) # Segmentation: mask + spectrogram + axes
mask = eye(signal) # just the (2, H, W) mask
TokEye
¶
A loaded TokEye segmentation model plus its preprocessing settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str | Path
|
Registry name (downloaded and cached on first use) or a path to a
local |
DEFAULT_MODEL
|
device
|
str
|
|
'auto'
|
n_fft
|
int | None
|
Override single fields of |
None
|
hop
|
int | None
|
Override single fields of |
None
|
clip_dc
|
int | None
|
Override single fields of |
None
|
clip_low
|
int | None
|
Override single fields of |
None
|
clip_high
|
int | None
|
Override single fields of |
None
|
log
|
int | None
|
Override single fields of |
None
|
config
|
SpectrogramConfig | Mapping[str, Any] | None
|
Preprocessing settings (a config or a mapping); defaults when omitted. |
None
|
fs
|
float | None
|
Default sampling rate in Hz for :meth: |
None
|
tile
|
int | str | None
|
|
'auto'
|
Attributes:
| Name | Type | Description |
|---|---|---|
model_name |
The model's label in results: the registry name, or a local
checkpoint's file name without its directories
(:func: |
|
weights |
Which weights were loaded (:func: |
Source code in src/tokeye/api.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | |
log
property
writable
¶
Whether 2D inputs are log1p-scaled (config.log).
predict(data, log=None)
¶
Run inference; returns a float32 mask of shape (C, H, W).
For big_tf_unet, channel 0 = coherent and channel 1 =
transient activity, both sigmoid scores in [0, 1].
Standardization is applied internally. A one-channel model gives
(H, W), as before 1.0; :meth:segment always gives
(C, H, W).
Source code in src/tokeye/api.py
segment(data, *, fs=None, reference=None, log=None)
¶
Segment a signal or spectrogram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
1D signal or 2D spectrogram. |
required |
fs
|
float | None
|
Sampling rate in Hz (overrides the instance |
None
|
reference
|
Any
|
Second 1D signal for a cross-power spectrum. |
None
|
log
|
bool | None
|
Per-call override of |
None
|
Returns:
| Type | Description |
|---|---|
Segmentation
|
Mask, the spectrogram it was computed from, and its axes. |
Source code in src/tokeye/api.py
spectrogram(data, log=None)
¶
The (H, W) float64 spectrogram the model will see (pre-1.0).
1D input goes through the STFT (which log-scales internally); 2D
input is used as-is, log1p-scaled first when log is on.
log=None defers to the instance setting. The result is always a
new array. The model sees these values cast to float32; use
:meth:segment for that float32 input together with its axes.
Source code in src/tokeye/api.py
Preprocessing configuration: the single source of spectrogram defaults.
Standard library only, so the CLI can build its flags from
:class:SpectrogramConfig without importing numpy, scipy or torch.
SpectrogramConfig
dataclass
¶
How a raw signal (or a stored spectrogram) becomes model input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_fft
|
int
|
STFT window length in samples. |
1024
|
hop
|
int
|
STFT hop in samples. 128 matches the released model's training. |
128
|
window
|
str
|
Window name understood by :func: |
'hann'
|
clip_dc
|
bool
|
Drop the DC (0 Hz) row of the STFT. |
True
|
clip_low
|
float
|
Percentiles the log-magnitude spectrogram is clipped to. |
1.0
|
clip_high
|
float
|
Percentiles the log-magnitude spectrogram is clipped to. |
1.0
|
log
|
bool
|
Apply |
False
|
Notes
clip_dc and log take True or False (NumPy booleans too);
the integers 0 and 1 still work, with a DeprecationWarning.
Source code in src/tokeye/config.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
coerce(value)
classmethod
¶
Accept None (defaults), a config, or a mapping of fields.
Source code in src/tokeye/config.py
from_dict(data)
classmethod
¶
Build from a mapping; unknown keys raise ValueError.
Source code in src/tokeye/config.py
replace(**changes)
¶
stft_kwargs()
¶
Keyword arguments for :func:tokeye.transforms.compute_stft.
Source code in src/tokeye/config.py
resolve_channels(preferred, n)
¶
Channel names for an n-channel mask.
Returns preferred when it has exactly n names, otherwise the
generic ("channel_0", "channel_1", ...).
Source code in src/tokeye/config.py
Segmentation: a TokEye mask together with the spectrogram it came from.
Segmentation
dataclass
¶
The result of :meth:tokeye.TokEye.segment.
Attributes:
| Name | Type | Description |
|---|---|---|
mask |
ndarray
|
|
spectrogram |
Spectrogram
|
The :class: |
channels |
tuple[str, ...]
|
One name per mask channel. |
model |
str
|
Registry name or file name of the model that produced the mask. |
weights |
Mapping[str, str | None] | None
|
Which weights produced it (see :func: |
Source code in src/tokeye/result.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | |
coherent
property
¶
(H, W) coherent-activity scores (AttributeError if absent).
freqs
property
¶
Row centres: Hz when fs is known, else bin index.
fs
property
¶
Sampling rate in Hz, or None.
times
property
¶
Column centres: seconds when fs is known, else frame index.
transient
property
¶
(H, W) transient-activity scores (AttributeError if absent).
__getitem__(name)
¶
The (H, W) scores of channel name.
Source code in src/tokeye/result.py
load(path)
classmethod
¶
Load a tokeye-analysis/v1 bundle that contains a mask.
Bundles written by the app (flat n_fft/hop/... params, no
axes) load too; missing settings fall back to the defaults, silently.
A recorded value that is invalid (an unknown or out-of-range setting,
a bad fs, kind, n_samples, channel list, weights record or
stored axis) is not used: it falls back to its default with a
UserWarning naming the file. Bundles without a weights record
load with weights=None, and without n_samples with
n_samples=None.
Bundles do not record their STFT framing, so their stored axes
(time_ms/freq_khz) are the only record of it: with a valid
fs, each valid stored axis is used as stored, and only a missing
or invalid one is rebuilt from fs and the settings.
Raises:
| Type | Description |
|---|---|
ValueError
|
The file is not a |
Source code in src/tokeye/result.py
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | |
plot(ax=None, *, threshold=0.5, alpha=0.4)
¶
Draw the spectrogram with the thresholded mask overlaid.
Uses origin="lower" (low frequencies at the bottom) and labelled
axes. Creates a new pyplot figure when ax is None.
Source code in src/tokeye/result.py
save(path)
¶
Save as a tokeye-analysis/v1 .npz (the app's schema).
Returns the path written (.npz is appended when missing). With
fs known, the result's own axes are stored (in ms and kHz).
Without it the axes are bin and frame indices and are not stored;
other axes then warn (UserWarning), since they reload as indices.
Source code in src/tokeye/result.py
Turn user data into the spectrogram the model sees.
:func:prepare is the one preprocessing entry point shared by the Python
API, the CLI, batch runs and the app:
- a 1D signal becomes a log-magnitude STFT (
kind="stft"); - a 1D signal plus
reference=becomes a cross-power STFT (kind="cross"); - a 2D array is taken as a ready spectrogram (
kind="spectrogram"),log1p-scaled first whenconfig.logis on.
The STFT frames are centred as in the model's training (see
:func:tokeye.transforms.compute_stft), so N samples give
1 + N // hop columns for an even n_fft. Every kind has the same
axes: row r is FFT bin b = r + 1 with clip_dc (else b = r),
at b * fs / n_fft Hz, and column j is at j * hop / fs seconds
from the first sample. Without fs they are the bin and frame indices.
Spectrogram
dataclass
¶
A model-ready spectrogram and its axes.
Attributes:
| Name | Type | Description |
|---|---|---|
values |
ndarray
|
|
freqs |
ndarray
|
|
times |
ndarray
|
|
kind |
str
|
|
config |
SpectrogramConfig
|
The :class: |
fs |
float | None
|
Sampling rate in Hz, or |
n_samples |
int | None
|
Length of the 1D signal (and of its reference) the values came
from, or |
Source code in src/tokeye/preprocess.py
prepare(data, config=None, *, fs=None, reference=None)
¶
Build the :class:Spectrogram the model will see.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
A 1D signal or a 2D |
required |
config
|
SpectrogramConfig | Mapping[str, Any] | None
|
Preprocessing settings; |
None
|
fs
|
float | None
|
Sampling rate in Hz. Only labels the axes; it never changes values:
row |
None
|
reference
|
Any
|
A second 1D signal, same length as |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
On complex, non-numeric, empty or non-finite input, a bad shape
(including a 2D input with a single row or column, which is a 1D
signal stored as a vector), a signal shorter than
|
Source code in src/tokeye/preprocess.py
Model inference: standardize, tile when large, forward, sigmoid.
:func:infer is the 1.0 entry point. :func:model_infer,
:func:signal_to_spectrogram and :func:warmup keep their pre-1.0
behaviour for existing callers (the app, dev scripts).
check_tile(tile)
¶
Raise if tile is not "auto", None or an int >= 512.
Source code in src/tokeye/inference.py
infer(model, values, *, device=None, tile='auto')
¶
Segment one spectrogram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
A segmentation model mapping |
required |
values
|
ndarray
|
|
required |
device
|
str | device | None
|
Where to run. |
None
|
tile
|
int | str | None
|
|
'auto'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Source code in src/tokeye/inference.py
model_infer(inp_array, model)
¶
Pre-1.0 inference helper: one untiled pass on the model's device.
Unlike :func:infer, it does no input validation (shape, dtype,
minimum size or finiteness). None for either argument passes
through: it returns None and logs a warning. It has the same
MPS->CPU fallback as :func:infer.
Returns:
| Type | Description |
|---|---|
ndarray or None
|
|
Source code in src/tokeye/inference.py
signal_to_spectrogram(signal, **stft_kwargs)
¶
Expand a 1D signal to (1, N) and run it through compute_stft.
warmup(model, iterations=10)
¶
Run dummy forward passes to trigger lazy init / kernel autotuning.
Source code in src/tokeye/inference.py
Read signals and spectrograms from common file formats.
:func:load_signal returns (array, fs): the array is a 1D signal or a
2D spectrogram, fs the sampling rate in Hz when the file says so (WAV,
FLAC and OGG headers; an fs-like field in .npz/.mat/.h5; a
time column in .csv/.txt; or an _sr<fs> filename suffix such as
shot_sr500000.npy), else None.
A container (.npz, .mat, .h5/.hdf5) can hold several
arrays. TokEye reads the one named data, signal, x,
spectrogram, values or y, else the only numeric one; when
several qualify it raises and lists them, and key= picks one.
fs_from_name(path)
¶
Sampling rate from an _sr<fs> stem suffix (x_sr200000.npy).
load_signal(path, key=None)
¶
Load a 1D signal or 2D spectrogram and its sampling rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
A file with one of the suffixes in :data: |
required |
key
|
str | None
|
Which array to read from a container ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple
|
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
TypeError
|
|
ValueError
|
For an unsupported suffix; an empty |
ImportError
|
For FLAC/OGG without |
Source code in src/tokeye/io.py
Model registry, Hugging Face downloads and local checkpoint loading.
Gradio-free. Model architectures are imported lazily by their builders, so
torchvision is only needed for ae_tf_maskrcnn (the ae extra).
DownloadError
¶
Bases: OSError
Hugging Face could not be reached, and the weights are not cached.
It means what :class:huggingface_hub.errors.LocalEntryNotFoundError
means, for the network failures huggingface_hub does not map to it.
ModelSpec
dataclass
¶
A registered model.
task is "segmentation" (TokEye, tokeye run) or
"instance" (tokeye alfvenspec); channels names the mask
channels of a segmentation model; size_mb is the download size.
Source code in src/tokeye/hub.py
cached_path(name)
¶
Local path of a registry model's weights, or None if not cached.
Source code in src/tokeye/hub.py
channels_for(source)
¶
Mask channel names for a model (the default names for local files).
download_model(name=DEFAULT_MODEL, repo_id=None)
¶
Download (or find in the cache) a registry model's weights.
Raises:
| Type | Description |
|---|---|
ValueError
|
|
(LocalEntryNotFoundError, DownloadError)
|
The hub cannot be reached and the weights are not cached. |
HfHubHTTPError
|
The hub answered with an error (a missing repo, for example). |
Source code in src/tokeye/hub.py
is_cached(name)
¶
load_model(source=DEFAULT_MODEL, device='auto')
¶
Load a registry model (downloading it once) or a local checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path
|
A registry name (see :data: |
DEFAULT_MODEL
|
device
|
str
|
|
'auto'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
An unknown or unavailable device, an unknown registry name, an unreadable checkpoint, or a state dict that fits no registered architecture. |
FileNotFoundError
|
|
(LocalEntryNotFoundError, DownloadError)
|
The hub cannot be reached and the weights are not cached. |
HfHubHTTPError
|
The hub answered with an error. |
Source code in src/tokeye/hub.py
model_label(source)
¶
The name results record for a model: never a local path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path
|
A registry name or the path of a local checkpoint. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A registry name unchanged, otherwise |
Source code in src/tokeye/hub.py
model_names(task=None)
¶
Registry names, in registry order, optionally only for one task.
repo_for(name)
¶
The Hugging Face repo a registry name downloads from and is cached under.
That is the spec's repo_id, else :data:DEFAULT_REPO_ID (the
TOKEYE_HF_REPO environment variable, read at import, else
nc1/big_tf_unet). An unknown name gets :data:DEFAULT_REPO_ID.
Source code in src/tokeye/hub.py
require_task(source, task)
¶
Raise ValueError if registry model source is not a task model.
Local checkpoint paths are not checked here (their task is only known
once loaded); :func:tokeye.inference.infer rejects detection outputs.
Source code in src/tokeye/hub.py
resolve_device(device='auto')
¶
Check device and return it; "auto" picks one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | device
|
|
'auto'
|
Returns:
| Type | Description |
|---|---|
str
|
The device |
Raises:
| Type | Description |
|---|---|
ValueError
|
Any other value, or a device this machine does not have. |
Source code in src/tokeye/hub.py
weights_info(source)
¶
Which weights a model source stands for, as results record them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path
|
A registry name, the path of a local checkpoint, or anything else (a caller's free-form model name). |
required |
Returns:
| Type | Description |
|---|---|
dict or None
|
For a registry name, |
Notes
It never raises for a file that cannot be read: an OSError while
hashing gives "sha256": None (logged at DEBUG). Digests are cached
per path, modification time and size, so a batch hashes each checkpoint
once.
Source code in src/tokeye/hub.py
Headless batch inference: run TokEye over a list of files with no GUI.
Never imports gradio or matplotlib.pyplot (previews are drawn on a bare
Figure), so this module is safe on HPC login/compute nodes and in CI.
check_key_inputs(paths, key)
¶
Reject a key that some inputs cannot use.
key= selects an array inside a container, so every input must be a
.npz, .mat, .h5 or .hdf5 file. Nothing is read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
Sequence[str | Path]
|
The inputs, e.g. from :func: |
required |
key
|
str | None
|
The array to read from each input; |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
|
Source code in src/tokeye/batch.py
check_unique_stems(paths)
¶
Reject inputs whose outputs would overwrite each other.
Every per-input output is named after the file stem, so shot.npy and
shot.wav, or a/shot.npy and b/shot.npy, would write the same
files. Stems are compared ignoring case (Shot and shot are one
file on the default macOS and Windows file systems).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
Sequence[Path]
|
The inputs, e.g. from :func: |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
Two or more inputs share a stem. The one-line message names each group of inputs (the first 5, then a count). |
Source code in src/tokeye/batch.py
collect_inputs(inputs)
¶
Expand a list of files/directories/glob patterns into concrete paths.
Each item is resolved as:
- an existing file: kept as-is, whatever its suffix (an unsupported one
then fails in :func:
tokeye.io.load_signal); - an existing directory: its files with a suffix in
:data:
tokeye.io.DIRECTORY_SUFFIXES, sorted; - otherwise a glob pattern: its matches that are files with a suffix in
:data:
tokeye.io.SIGNAL_SUFFIXES(.csv/.txtincluded), sorted.
A file reached twice under the same name (through its directory and by name, or by a relative and an absolute path) is kept once, in its first-seen position and spelling. A symlink with another name stays a separate input.
Raises:
| Type | Description |
|---|---|
ValueError
|
Nothing was collected. The message counts the glob matches that were skipped for their suffix, if any. |
Source code in src/tokeye/batch.py
load_input(path, stft_kwargs, log=False)
¶
Pre-1.0 helper: the float64 spectrogram for path.
stft_kwargs are :class:SpectrogramConfig fields; an fs key is
checked and otherwise ignored (it only labels axes, and this returns
none). The model sees these values cast to float32; use
:func:load_spectrogram for that float32 input together with its axes.
Source code in src/tokeye/batch.py
load_spectrogram(path, config=None, *, fs=None, key=None)
¶
Read path with :func:tokeye.io.load_signal and :func:prepare it.
An explicit fs wins over one found in the file. key selects the
array in a container (see :func:tokeye.io.load_signal).
Source code in src/tokeye/batch.py
process_file(path, model, config=None, out_dir=None, save_png=True, threshold=0.5, log=None, *, stft_kwargs=None, fs=None, fmt='npy', model_name=None, channels=None, tile='auto', key=None)
¶
Segment one input file and write its outputs to out_dir.
Writes <stem>_mask.npy (float32 (C, H, W)) or, with
fmt="npz", <stem>_tokeye.npz (a :class:Segmentation bundle);
<stem>_preview.png unless save_png is off; and
<stem>_params.json recording how the output was made. Returns the
mask (or bundle) path.
tile is passed to :func:tokeye.inference.infer, and key to
:func:tokeye.io.load_signal. params.json is removed before the
first write and written last, so it only ever sits beside a complete set
of outputs. A dict config is deprecated; an fs key in it
moves to fs (ValueError when fs is given too).
model_name is the registry name or checkpoint path model was
loaded from. params.json (and the fmt="npz" bundle) then record
model as :func:tokeye.hub.model_label of it (a file name, never a
local path) and weights as :func:tokeye.hub.weights_info of it,
hashed after inference. Without it they record "model": "unknown"
and "weights": null.
stft_kwargs is the deprecated 0.12.0 name of config: a dict of
settings, which warns (DeprecationWarning, removed in 2.0) and
moves an fs key to fs. Passing both raises TypeError.
out_dir is required; its default only lets config be left out
for that spelling.
Source code in src/tokeye/batch.py
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | |
process_files(paths, model, config, out_dir, *, save_png=True, threshold=0.5, fs=None, fmt='npy', tile='auto', model_name=None, channels=None, key=None, on_error=None)
¶
Segment each path with a loaded model: the loop of :func:run_batch.
Each path goes through :func:process_file into out_dir, which must
exist, under a progress bar. One input that fails does not stop the
others. Inputs that share a stem are rejected before anything is
written (:func:check_unique_stems).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
paths
|
Sequence[Path]
|
Input files, e.g. from :func: |
required |
model
|
Module
|
A loaded segmentation model (:func: |
required |
config
|
SpectrogramConfig | Mapping[str, Any] | None
|
Preprocessing settings (defaults when |
required |
out_dir
|
Path
|
Existing directory for the outputs. |
required |
save_png
|
bool
|
As for :func: |
True
|
threshold
|
bool
|
As for :func: |
True
|
fs
|
bool
|
As for :func: |
True
|
fmt
|
bool
|
As for :func: |
True
|
tile
|
bool
|
As for :func: |
True
|
channels
|
bool
|
As for :func: |
True
|
key
|
bool
|
As for :func: |
True
|
model_name
|
str | Path | None
|
The registry name or checkpoint path |
None
|
on_error
|
Callable[[Path, Exception], None] | None
|
Called as |
None
|
Returns:
| Type | Description |
|---|---|
int
|
The number of inputs that failed. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
TypeError
|
|
Source code in src/tokeye/batch.py
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 | |
run_batch(inputs, model=hub.DEFAULT_MODEL, out_dir=Path('tokeye_output'), stft_kwargs=None, save_png=True, threshold=0.5, device='auto', log=None, *, config=None, fs=None, fmt='npy', tile='auto', key=None)
¶
Segment every input, writing outputs to out_dir.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
list[str]
|
Files, directories or glob patterns (see :func: |
required |
model
|
str | Path
|
Passed to :func: |
DEFAULT_MODEL
|
device
|
str | Path
|
Passed to :func: |
DEFAULT_MODEL
|
config
|
SpectrogramConfig | None
|
Preprocessing settings (defaults when omitted). |
None
|
fs
|
float | None
|
Sampling rate for every input (else read per file, if recorded). |
None
|
fmt
|
str
|
|
'npy'
|
tile
|
int | str | None
|
|
'auto'
|
key
|
str | None
|
The array to read from each input, which must then be a |
None
|
stft_kwargs
|
dict | None
|
Deprecated spellings of |
None
|
log
|
dict | None
|
Deprecated spellings of |
None
|
Returns:
| Type | Description |
|---|---|
int
|
The number of inputs that failed (each is logged, see
:func: |
Raises:
| Type | Description |
|---|---|
ValueError
|
Bad settings, an |
TypeError
|
|
Source code in src/tokeye/batch.py
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 | |
save_overlay_png(spectrogram, mask, out_path, threshold=0.5, dpi=150)
¶
Save a grayscale spectrogram with a semi-transparent mask overlay.
Coherent activity (mask[0]) is tinted green, transient activity
(mask[1]) red, both thresholded at threshold.
Source code in src/tokeye/batch.py
Shared "save results" backbone: npz bundle schemas.
Every TokEye surface that offers a "Save results" feature (Gradio tabs, the
native Qt GUI, CLI batch) builds its output through this module so every
saved .npz follows one consistent schema. numpy-only at import time:
importing this module never pulls in torch, gradio, Qt, matplotlib, or plotly.
Two schemas:
tokeye-analysis/v1— spectrogram surfaces (:func:analysis_bundle).tokeye-modespec/v1— mode-spectrogram surfaces (:func:modespec_bundle).
Both share four keys: schema, created_utc, source,
params_json. Bundles are flat str -> np.ndarray-ish dicts saved with
:func:save_npz; optional keys are simply absent when their inputs are
absent — bundles never store None.
analysis_bundle(*, spectrogram, mask=None, stft_meta=None, raw=None, params=None, source='', axes=None)
¶
Build a tokeye-analysis/v1 npz bundle (key -> array/str).
raw, when given, is a (t_ms, x) tuple of the raw signal trace,
stored as raw_t_ms/raw_x. axes, when given, is the
(time_ms, freq_khz) pair stored as is (float64); otherwise the axes
come from :func:stft_axes applied to spectrogram's shape and
stft_meta. Optional keys are simply omitted when their inputs are
unavailable (never stored as None).
spectrogram must be 2D (H, W); mask, when given, must be
(C, H, W) or (H, W) with the same H, W (ValueError
otherwise, so a stale mask can never be saved next to a new input).
axes must be 1D of lengths W and H, all finite, and cannot
be combined with stft_meta (ValueError otherwise).
Source code in src/tokeye/export.py
default_stem(kind, *parts)
¶
Build a timestamped default filename stem:
tokeye_<kind>[_<part>...]_<YYYYmmdd-HHMMSS>. parts are
stringified; falsy ones (None, "", 0, ...) are skipped.
Source code in src/tokeye/export.py
modespec_bundle(*, result, nd=None, tok_mask=None, coh_thresh=None, params=None, source='')
¶
Build a tokeye-modespec/v1 npz bundle from a mode-spectrogram
analysis result (as returned by mode_spectrogram()): keys
t_win_ms, freq_khz, n_dominant, coherence, n_range
(2-seq), c95. nd, when given, is the TokEye-gated dominant-mode
array and is stored as n_gated.
Source code in src/tokeye/export.py
save_npz(path, bundle)
¶
Save a bundle with np.savez_compressed; mkdir parents; return the
actual path written (numpy appends .npz if not already present).
Source code in src/tokeye/export.py
stft_axes(n_rows, n_cols, stft_meta)
¶
Pixel-centre axes (time_ms, freq_khz) for an STFT image.
stft_meta keys: fs [Hz], t0_ms, n_fft, hop,
clip_dc (bool). Math (must match the GUI/plotly renderers exactly)::
offset = 1 if clip_dc else 0
df = fs / n_fft / 1e3 # kHz per row
dt = hop / fs * 1e3 # ms per column
time_ms[i] = t0_ms + i * dt (column centres, i in [0, n_cols))
freq_khz[r] = (r + offset) * df (row centres, r in [0, n_rows))
For :func:tokeye.transforms.compute_stft output with t0_ms=0,
time_ms[i] is column i's centre (to rounding).
Returns (None, None) when stft_meta is falsy or fs <= 0.
Defaults when keys are absent: n_fft=1024, hop=128,
t0_ms=0.0, clip_dc=True.
Source code in src/tokeye/export.py
Deterministic synthetic example signal for demos and smoke tests.
Produces a 1D signal with Gaussian noise plus a handful of sustained frequency-ramp "chirps" (coherent activity) and short Gaussian-windowed "bursts" (transient activity), so a log1p spectrogram of the output shows both activity classes TokEye is trained to segment.
example_filename(fs)
¶
The name of an example signal: tokeye_example_sr<fs>.npy.
The _sr suffix records the rate, so tokeye run reads it from the
name (the app does not).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fs
|
float
|
Sampling rate [Hz]. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The file name, e.g. |
Source code in src/tokeye/examples.py
format_rate(fs)
¶
A sampling rate as it is written in file names and commands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fs
|
float
|
Sampling rate [Hz]. |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
Source code in src/tokeye/examples.py
write_example_signal(directory, filename=None)
¶
Write the default example signal into directory.
filename defaults to :func:example_filename of :data:DEFAULT_FS,
the name tokeye example writes.