Skip to main content
KeywordTensor Logo

A Python library for training custom keyword spotting models and running real-time voice command detection.

PyPI - Version Python License


⚡ About KeywordTensor

KeywordTensor is built for developers who want to integrate voice commands into their Python projects without requiring deep knowledge of audio processing.

  • Download public datasets so you can choose your own words, and let KeywordTensor automatically distil them into a tiny personalized model for your device.
  • Bring your own .wav files: Just put your audio files into folders (e.g., dataset/hello/, dataset/stop/).
  • Trigger custom Python actions: Easily map recognized words directly to your own Python functions. No Speech-to-Text required—KeywordTensor detects predefined commands and directly triggers Python callbacks.
  • Automated Export & Config: Training automatically generates your optimized model and its configuration file. This allows you to launch live inference with a single command later. No manual saving required!
  • Lightweight Edge Variant: A standalone, PyTorch-free inference engine. Perfect for microcontrollers, Raspberry Pi, and IoT devices.
  • Built-in Audio Augmentation: We automatically mutate your .wav files during training (PitchShift, Gain & Polarity Inversion, Colored Noise) to improve robustness in noisy environments.
  • SpecAugment Pipeline: Raw audio is converted to Mel-spectrograms with Time and Frequency Masking applied. The model learns to recognize commands even if the microphone crackles or the audio drops out.
  • Continuous Listening: A rolling buffer averages predictions over time to prevent sudden false positive clicks.
  • Full Control: We hide the complexity by default, but give you full access to all deep learning training and listening parameters (training configuration, validation settings, and inference thresholds).

📦 Pre-trained Models

Don't have time to record your own dataset? You can use our ready-to-go models.

  • prawda_falsz KeywordTensor LogoLive Demo

    [SOON] A highly robust model trained specifically to handle high-pitched children's voices and extremely noisy environments. This model was successfully deployed in a live public demonstration during the "Noc Naukowców" (Researchers' Night) event.

  • More models coming soon!


💻 Quick Start & API

1. Installation (Choose your variant)

The library is available in two variants on PyPI depending on your needs:

  • pip install keywordtensor Installs the full training environment. Use this on your PC or Server to train your models.

  • pip install keywordtensor-edge A lightweight runtime variant. It completely strips out heavy training dependencies (like PyTorch and fastai), providing only what is needed for real-time inference and dataset collection (listen() and record()). Perfect for microcontrollers or IoT devices.


2. Creating your own dataset

If you don't want to use public datasets, you can easily record your own voice to build a custom dataset using the built-in .record() tool.

import keywordtensor as kt

model = kt.Engine()

# Record 50 samples of the word "hello" and "stop"
model.record(
    target="my_dataset", 
    classes=["hello", "stop"], 
    samples=50,
    duration=3.0
)

Record parameters: Available parameters in .record():

  • target (required): Path where the audio folders will be saved.
  • classes (required): List of strings. Words you want to record.
  • samples (default: 100): Number of audio samples to record per class.
  • actions (default: None): Optional dictionary mapping words to custom callbacks. If provided, your callback will receive three kwargs: start_recording (a callable you must execute to begin recording), current_time (a callable returning elapsed seconds), and total_time (the target duration). If None, the engine simply prints the recording progress.
  • source (default: "microphone"): Audio input source.
    • "microphone" uses the default system microphone.
    • "microphone:1" uses a specific microphone ID.
    • my_variable: You can pass your own audio buffer directly (as a NumPy array/list) or a tuple (sample_rate, audio_array). If you pass a tuple with a different sample rate, KeywordTensor will automatically resample it to sr under the hood!
  • duration (default: 3.0): The exact duration of each audio clip in seconds.
  • stop (default: None): Optional callback function that returns True to stop the recording loop.
  • sr (default: 16000): Sample rate for the recorded audio files.

3. Training your model

The .train() method takes your audio files and trains a neural network using PyTorch and FastAI under the hood.

import keywordtensor

model = keywordtensor.Engine()

# The engine automatically applies audio & spectrogram augmentations during training
model.train(
    dataset="google",
    classes=["up", "down", "mixed:other"],
    model_path="my_custom_model",
    epochs=10,
    batch_size=32
)

Training parameters: You have total control over the pipeline. Available parameters in .train():

  • dataset (required): Path to your audio dataset. You can provide a local folder path, or use one of the built-in presets: "google", "mswc", or "hf:username/repo".
  • classes (default: None): List of specific words (folders) you want to recognize. If None, trains on all available folders. Pro-tip: Add "mixed:other" to the list, and the engine will automatically aggregate random words from your dataset to create a robust background noise class!
  • model_path (default: 'myownmodel'): Name of the final exported model.
  • epochs (default: 30): Number of training cycles over your dataset.
  • batch_size (default: 32): Number of audio samples processed simultaneously.
  • learning_rate (Automatic): The engine dynamically searches for the optimal learning rate for your specific dataset and automatically applies the One-Cycle Policy.
  • wd (default: 0.01): Weight decay (L2 penalty) to prevent overfitting.
  • eps (default: 0.01): Label smoothing epsilon to improve generalization.
  • valid_pct (default: 0.1): Percentage of data reserved for validation.
  • duration (default: 3.0): The exact duration of your audio clips in seconds. If an audio clip is shorter, it will be automatically padded with zeros (silence). If it is longer, it will be accurately truncated to match this length.
  • sr (default: 16000): Sample rate of your audio files.

4. Live Inference & Custom Actions

Once trained (or using a pre-trained model like prawda_falsz), you can run real-time inference using your microphone.

import keywordtensor as kt

model = kt.Engine()

# Define your custom actions
def on_hello():
    print("Action triggered: 'Hello' detected!")

def on_stop():
    print("Action triggered: Stopping the robot!")

# Map keywords to your Python functions
model.listen(
    model_path="my_custom_model",
    actions={
        "hello": on_hello,
        "stop": on_stop
    },
    min_confidence=0.6,
    n_averages=3,
    source="microphone"
)

Listen parameters: The .listen() method itself accepts the following runtime arguments:

  • model_path (required): The name of the model to load. You can provide the path to your own trained model, or use the built-in "prawda_falsz" model which is highly robust to noise and pitched voices.
  • actions (default: None): Optional dictionary mapping detected keywords to your own Python callbacks. If None, the engine prints the detected word and waits for the sample duration. If you provide callbacks, they execute immediately upon detection, and you must implement any required "cooldown" inside your function (the listen core will pause while your function runs).
  • min_confidence (default: 0.6): The probability threshold (0.0 to 1.0) required to trigger the action.
  • n_averages (default: 3): Temporal smoothing. Averages the last N predictions to prevent false positive clicks.
  • source (default: "microphone"): Audio input source.
    • "microphone" uses the default system microphone.
    • "microphone:1" uses a specific microphone ID.
    • my_variable: You can pass your own audio buffer directly (as a NumPy array/list) or a tuple (sample_rate, audio_array) for automatic resampling.
  • listen_time (default: -1): How long to listen in seconds. -1 means listen forever, 0 performs a single prediction, and >0 sets a specific duration.
  • stop (default: None): Optional callback function that returns True to stop the listening loop.
  • threads (default: None): Number of CPU threads to use for ONNX inference.

Config file parameters: The rest of the underlying parameters are loaded automatically from the <model_path>_config.json file! When you run .train(), this file is automatically generated for you. It looks like this:

{
    "labels": ["hello", "stop"],
    "mean": -40.15,
    "std": 17.35,
    "duration": 3.0,
    "sr": 16000
}

This file dictates the rules for the inference engine:

  • labels: The list of keywords the model was trained on.
  • duration: The size of the rolling audio buffer in seconds.
  • sr: The microphone sample rate.
  • mean / std: Normalization statistics for the Mel-spectrogram.

💡 Total Flexibility: Want to adjust the microphone sample rate or buffer duration without retraining? Just open the JSON file and edit it!

Bringing your own model? No problem! If you trained an ONNX model entirely outside of KeywordTensor, simply drop it into your folder, create a matching your_model_config.json file next to it with the parameters above, and the .listen() method will load and run your external model.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

keywordtensor_edge-1.2.0.tar.gz (41.9 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

keywordtensor_edge-1.2.0-py3-none-any.whl (41.6 MB view details)

Uploaded Python 3

File details

Details for the file keywordtensor_edge-1.2.0.tar.gz.

File metadata

  • Download URL: keywordtensor_edge-1.2.0.tar.gz
  • Upload date:
  • Size: 41.9 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for keywordtensor_edge-1.2.0.tar.gz
Algorithm Hash digest
SHA256 b8c2013363777f39dce48bccfe1b027542bd33524d794043d79b4abdd41b9ed4
MD5 b53d98fbd6eed9f1bb3b85cb9a687436
BLAKE2b-256 f31070b54b33e97cde20146850650308ada6f6a1b06c55a197591e3b2105d4b6

See more details on using hashes here.

Provenance

The following attestation bundles were made for keywordtensor_edge-1.2.0.tar.gz:

Publisher: publish.yml on fkondela/keywordtensor

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file keywordtensor_edge-1.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for keywordtensor_edge-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e43da7e8ed536b5b0114b6f9caeab69297c8154d43ef489280534ffcaf8000b3
MD5 e762fcd3a1081ea3f5a13f7a025e8fb8
BLAKE2b-256 766a2b24595f5df98ef5a7086fbec6476f0f698dd1d4ca90e70879b31d2fee1a

See more details on using hashes here.

Provenance

The following attestation bundles were made for keywordtensor_edge-1.2.0-py3-none-any.whl:

Publisher: publish.yml on fkondela/keywordtensor

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

1.5.2

2 files

1.5.1

2 files

1.5.0

2 files

1.4.1

2 files

1.3.0

2 files

1.2.8

2 files

1.2.7

2 files

1.2.6

2 files

1.2.5

2 files

1.2.4

2 files

1.2.3

2 files

1.2.2

2 files

1.2.1

2 files

This release

1.2.0 This release

2 files

1.1.0

2 files

1.0.4

2 files

1.0.3

2 files

1.0.2

2 files

1.0.1

2 files

1.0.0

2 files

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