keywordtensor 1.0.0__py3-none-any.whl

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.
@@ -0,0 +1 @@
1
+ from .core import Engine
keywordtensor/core.py ADDED
@@ -0,0 +1,260 @@
1
+ import json
2
+ import torch
3
+ import torchaudio
4
+ import torchaudio.transforms as T
5
+ import onnxruntime as ort
6
+ from pathlib import Path
7
+ import os
8
+ import time
9
+ from collections import deque
10
+ import numpy as np
11
+ import sounddevice as sd
12
+ #klasy niezbedne do transformacji danych audio i spektrogramów
13
+
14
+ try:
15
+ from fastai.vision.all import *
16
+ from fastcore.foundation import L
17
+ import itertools
18
+ if not hasattr(L, 'starmap'):
19
+ L.starmap = lambda self, f: L(itertools.starmap(f, self))
20
+ from torch_audiomentations import Compose, Shift, Gain, PolarityInversion, AddColoredNoise, PitchShift, HighPassFilter, LowPassFilter
21
+ HAS_FASTAI = True
22
+ except ImportError:
23
+ HAS_FASTAI = False
24
+ class Transform:
25
+ pass
26
+ class TensorImage:
27
+ def __new__(cls, x, *args, **kwargs):
28
+ return x
29
+ def show_image(*args, **kwargs):
30
+ pass
31
+
32
+
33
+ #zamiana pliku na falę dźwiękową
34
+ class LoadAudio(Transform):
35
+ def __init__(self, duration=3.0):
36
+ self.duration = duration
37
+
38
+ def encodes(self, file: Path):
39
+ waveform, sr = torchaudio.load(file)
40
+ target_length = int(self.duration * sr)
41
+ if waveform.shape[1] > target_length:
42
+ waveform = waveform[:, :target_length]
43
+ elif waveform.shape[1] < target_length:
44
+ pad_amount = target_length - waveform.shape[1]
45
+ waveform = torch.nn.functional.pad(waveform, (0, pad_amount))
46
+ return waveform
47
+
48
+ #definicja wyświetlenia spektrogramu
49
+ class AudioSpectrogram(TensorImage):
50
+ def show(self, ctx=None, **kwargs):
51
+ return show_image(self, ctx=ctx, cmap='magma', **kwargs)
52
+
53
+ #definicja zamiany fali dźwiękowej na spektrogram
54
+ class WaveformToSpectrogram(Transform):
55
+ def __init__(self, sr=16000):
56
+ self.melspec = T.MelSpectrogram(sample_rate=sr, n_mels=128, n_fft=1024, hop_length=128)
57
+ self.todb = T.AmplitudeToDB(top_db=80.0)
58
+
59
+ def encodes(self, waveform):
60
+ spec = self.todb(self.melspec(waveform))
61
+ return AudioSpectrogram(spec)
62
+
63
+ #definicja augmentacji audio
64
+ class AudioAugment(Transform):
65
+ split_idx = 0
66
+
67
+ def __init__(self, sr=16000):
68
+ self.sr = sr
69
+
70
+ self.audio_augcompose = Compose([
71
+ Shift(min_shift=-0.1, max_shift=0.1, sample_rate=self.sr, p=0.4, rollover=False, output_type="dict"),
72
+ Gain(min_gain_in_db=-15.0, max_gain_in_db=15.0, p=0.6, output_type="dict"),
73
+ PolarityInversion(p=0.5, output_type="dict"),
74
+ AddColoredNoise(min_snr_in_db=20.0, max_snr_in_db=35.0, p=0.6, output_type="dict"),
75
+ PitchShift(min_transpose_semitones=-8, max_transpose_semitones=8, sample_rate=self.sr, p=0.6, output_type="dict"),
76
+ HighPassFilter(min_cutoff_freq=50, max_cutoff_freq=300, sample_rate=self.sr, p=0.3, output_type="dict"),
77
+ LowPassFilter(min_cutoff_freq=5000, max_cutoff_freq=7000, sample_rate=self.sr, p=0.3, output_type="dict"),
78
+ ], output_type="dict")
79
+
80
+ def encodes(self, waveform):
81
+ audio_input = waveform.unsqueeze(0)
82
+ augment_dict = self.audio_augcompose(audio_input, sample_rate=self.sr)
83
+ audio_output = augment_dict.samples
84
+ return audio_output.squeeze(0)
85
+
86
+ #defdinicja augmentacji spektrogramu
87
+ class SpecAugment(Transform):
88
+ split_idx = 0
89
+ def __init__(self):
90
+ self.tmask = T.TimeMasking(time_mask_param=4)
91
+ self.fmask = T.FrequencyMasking(freq_mask_param=4)
92
+
93
+ def encodes(self, spec: AudioSpectrogram):
94
+ return self.fmask(self.tmask(spec))
95
+
96
+ #definicja normalizacji spektrogramu
97
+ class NormalizeSpec(Transform):
98
+ def __init__(self, mean=0.0, std=1.0):
99
+ self.mean = mean
100
+ self.std = std
101
+
102
+ def setups(self, items):
103
+ sum_x, sum_x2, n = 0.0, 0.0, 0
104
+ for x in items:
105
+ sum_x += x.sum().item()
106
+ sum_x2 += (x**2).sum().item()
107
+ n += x.numel()
108
+ self.mean = sum_x / n
109
+ self.std = (sum_x2 / n - self.mean**2)**0.5
110
+
111
+ def encodes(self, spec: AudioSpectrogram):
112
+ normalized = (spec - self.mean) / self.std
113
+ return AudioSpectrogram(normalized)
114
+
115
+ #def decodes(self, spec: AudioSpectrogram):
116
+ #denormalized = (spec * self.std) + self.mean
117
+ #return AudioSpectrogram(denormalized)
118
+
119
+
120
+ #klasa gdy ktos chce trenowac swoj wlasny model, a nie korzystac z wbudowanych wytrenowanych przykladow
121
+ class Engine:
122
+ def __init__(self):
123
+ self.model_name = None
124
+
125
+ def train(self, dataset_path, epochs=30, batch_size=32, wd=0.01, eps=0.01, valid_pct=0.1, model_name='myownmodel', duration=3.0, sr=16000):
126
+ if not HAS_FASTAI:
127
+ raise RuntimeError("Training requires fastai. Install the full package: pip install keywordtensor")
128
+
129
+ self.model_name = model_name
130
+
131
+ get_audio_files = partial(get_files, extensions=['.wav'])
132
+ files = get_audio_files(Path(dataset_path))
133
+ splits = RandomSplitter(valid_pct=valid_pct, seed=42)(files)
134
+
135
+ norm_spec = NormalizeSpec()
136
+
137
+ tfms = [
138
+ [LoadAudio(duration=duration), AudioAugment(sr=sr), WaveformToSpectrogram(sr=sr), norm_spec, SpecAugment()],
139
+ [parent_label, Categorize()]
140
+ ]
141
+ dsets = Datasets(files, tfms, splits=splits)
142
+ dls = dsets.dataloaders(bs=batch_size)
143
+
144
+ model = xresnet18(c_in=1, n_out=len(dls.vocab), pretrained=False)
145
+ learn = Learner(dls, model, wd=wd, metrics=accuracy, loss_func=LabelSmoothingCrossEntropy(eps=eps))
146
+
147
+ res = learn.lr_find()
148
+ base_lr = res.valley
149
+ learn.fit_one_cycle(epochs, lr_max=slice(base_lr/10, base_lr))
150
+
151
+ config = {
152
+ "labels": list(dls.vocab),
153
+ "mean": float(norm_spec.mean),
154
+ "std": float(norm_spec.std),
155
+ "duration": float(duration),
156
+ "sr": int(sr)
157
+ }
158
+ with open(f"{model_name}_config.json", "w", encoding="utf-8") as f:
159
+ json.dump(config, f, ensure_ascii=False, indent=4)
160
+
161
+ x, y = learn.dls.one_batch()
162
+ dummy_input = x[0].unsqueeze(0).cpu()
163
+
164
+ model = learn.model.cpu()
165
+ model.eval()
166
+
167
+ torch.onnx.export(
168
+ model,
169
+ dummy_input,
170
+ f"{model_name}.onnx",
171
+ input_names=['input'],
172
+ output_names=['output'],
173
+ opset_version=12,
174
+ dynamo=False
175
+ )
176
+
177
+
178
+ def listen(self, model_name, actions=None, min_confidence=0.6, n_averages=3):
179
+ if actions is None:
180
+ actions = {}
181
+
182
+ user_model_path = Path(f"{model_name}.onnx")
183
+ user_config_path = Path(f"{model_name}_config.json")
184
+
185
+ library_dir = os.path.dirname(os.path.abspath(__file__))
186
+ builtin_base_path = os.path.join(library_dir, "pretrained", model_name)
187
+ builtin_model_path = Path(f"{builtin_base_path}.onnx")
188
+ builtin_config_path = Path(f"{builtin_base_path}_config.json")
189
+
190
+ if user_model_path.exists() and user_config_path.exists():
191
+ resolved_path = model_name
192
+ elif builtin_model_path.exists() and builtin_config_path.exists():
193
+ resolved_path = builtin_base_path
194
+
195
+ with open(f"{resolved_path}_config.json", "r", encoding="utf-8") as f:
196
+ cfg = json.load(f)
197
+
198
+ labels = cfg["labels"]
199
+ sr = cfg["sr"]
200
+ duration = cfg["duration"]
201
+
202
+ wav_to_spec = WaveformToSpectrogram(sr=sr)
203
+ normalize_spec = NormalizeSpec(mean=cfg["mean"], std=cfg["std"])
204
+
205
+ sess = ort.InferenceSession(f"{resolved_path}.onnx")
206
+ inp_name = sess.get_inputs()[0].name
207
+
208
+ buf_len = int(sr * duration)
209
+ audio_buffer = deque([0.0] * buf_len, maxlen=buf_len)
210
+ prediction_history = deque(maxlen=n_averages)
211
+
212
+
213
+ def _audio_callback(indata, frames, time_info, status):
214
+ audio_buffer.extend(indata[:, 0])
215
+
216
+ last_trigger_times = {}
217
+
218
+ with sd.InputStream(samplerate=sr, channels=1, blocksize=int(sr * 0.1), callback=_audio_callback):
219
+ time.sleep(duration)
220
+ while True:
221
+
222
+ wav_tensor = torch.tensor(list(audio_buffer), dtype=torch.float32)
223
+
224
+ spectrogram = wav_to_spec.encodes(wav_tensor)
225
+ spectrogram = normalize_spec.encodes(spectrogram)
226
+
227
+ onnx_data = spectrogram.unsqueeze(0).unsqueeze(0).numpy()
228
+
229
+ logits = sess.run(None, {inp_name: onnx_data})[0][0]
230
+
231
+ exp_res = np.exp(logits - np.max(logits))
232
+ probs = exp_res / exp_res.sum()
233
+
234
+ prediction_history.append(probs)
235
+
236
+ if len(prediction_history) == n_averages:
237
+ mean_probs = np.mean(prediction_history, axis=0)
238
+ idx = np.argmax(mean_probs)
239
+ confidence = mean_probs[idx]
240
+ predicted_class = labels[idx]
241
+
242
+ if confidence > min_confidence:
243
+ if predicted_class in actions:
244
+ action_val = actions[predicted_class]
245
+
246
+ if callable(action_val):
247
+ func = action_val
248
+ cooldown = 0.0
249
+ else:
250
+ func = action_val.get("funkcja")
251
+ cooldown = action_val.get("cooldown", 0.0)
252
+
253
+ last_time = last_trigger_times.get(predicted_class, 0.0)
254
+
255
+ if func and (time.time() - last_time >= cooldown):
256
+ func()
257
+ prediction_history.clear()
258
+ last_trigger_times[predicted_class] = time.time()
259
+
260
+ time.sleep(0.05)
File without changes
@@ -0,0 +1,11 @@
1
+ {
2
+ "labels": [
3
+ "falsz",
4
+ "other",
5
+ "prawda"
6
+ ],
7
+ "mean": -40.1587,
8
+ "std": 17.3580,
9
+ "duration": 3.0,
10
+ "sr": 16000
11
+ }
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.4
2
+ Name: keywordtensor
3
+ Version: 1.0.0
4
+ Summary: A Python library for training custom keyword spotting models and running real-time voice command detection.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Requires-Dist: numpy
8
+ Requires-Dist: sounddevice
9
+ Requires-Dist: onnxruntime
10
+ Requires-Dist: torch
11
+ Requires-Dist: torchaudio
12
+ Requires-Dist: fastai
13
+ Requires-Dist: torch-audiomentations
14
+ Requires-Dist: torchcodec
15
+ Requires-Dist: onnx
16
+ Dynamic: license-file
@@ -0,0 +1,10 @@
1
+ keywordtensor/__init__.py,sha256=OQS2-5O86f3V1w1JH9hnqaqGa_b-TVRzPhZUojGnPLo,25
2
+ keywordtensor/core.py,sha256=QubRXLxQ9JK9-NexfXml_r5mIoUYNJYypIHww0aIJ_o,9993
3
+ keywordtensor/pretrained/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ keywordtensor/pretrained/prawda_falsz.onnx,sha256=ZlkNPuHJT1zUUU2ue9Mpd6PXF62bBJdIEVJVnnvJmbE,44779043
5
+ keywordtensor/pretrained/prawda_falsz_config.json,sha256=WNi-iBzg8G6vE0VCVbn4oxrz9Hixr-6qwwe88iFl0Hg,157
6
+ keywordtensor-1.0.0.dist-info/licenses/LICENSE,sha256=lUg2Kw2XUzbk6EJ7mo-6Cfou-rF-9dVbWQA98UMH9T0,1071
7
+ keywordtensor-1.0.0.dist-info/METADATA,sha256=cIB5AMzx1kYP85Nh7bGf2Q1Txf4omggE2ysjTqeKNCQ,458
8
+ keywordtensor-1.0.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
9
+ keywordtensor-1.0.0.dist-info/top_level.txt,sha256=SAanXXDIwqzsPeUSKHTyVHZfYArUKvaH3VQ49JHVU6k,14
10
+ keywordtensor-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fabian Kondela
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ keywordtensor