naptrap 0.1.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.
- naptrap/__init__.py +15 -0
- naptrap/__main__.py +5 -0
- naptrap/artifacts.py +49 -0
- naptrap/audio.py +24 -0
- naptrap/cli.py +35 -0
- naptrap/features.py +69 -0
- naptrap/google.py +96 -0
- naptrap/hub.py +21 -0
- naptrap/models/__init__.py +5 -0
- naptrap/models/network.py +61 -0
- naptrap/models/phonmatchnet.py +128 -0
- naptrap/registry.py +42 -0
- naptrap/text.py +106 -0
- naptrap/types.py +61 -0
- naptrap-0.1.0.dist-info/METADATA +213 -0
- naptrap-0.1.0.dist-info/RECORD +22 -0
- naptrap-0.1.0.dist-info/WHEEL +5 -0
- naptrap-0.1.0.dist-info/entry_points.txt +2 -0
- naptrap-0.1.0.dist-info/licenses/LICENSE +202 -0
- naptrap-0.1.0.dist-info/licenses/NOTICE +19 -0
- naptrap-0.1.0.dist-info/licenses/licenses/PhonMatchNet-BSD-3-Clause.txt +28 -0
- naptrap-0.1.0.dist-info/top_level.txt +1 -0
naptrap/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""naptrap: local, text-defined wake word and keyword detection."""
|
|
2
|
+
|
|
3
|
+
from .artifacts import ArtifactError
|
|
4
|
+
from .audio import load_wav
|
|
5
|
+
from .google import GoogleSpeechEmbedding
|
|
6
|
+
from .models import PhonMatchNet
|
|
7
|
+
from .registry import available_models, load_model, register_model
|
|
8
|
+
from .text import G2PTextEncoder, normalize_keyword
|
|
9
|
+
from .types import Keyword, KeywordModel, Prediction
|
|
10
|
+
|
|
11
|
+
__version__ = "0.1.0"
|
|
12
|
+
__all__ = [
|
|
13
|
+
"ArtifactError", "G2PTextEncoder", "GoogleSpeechEmbedding", "Keyword", "KeywordModel", "PhonMatchNet",
|
|
14
|
+
"Prediction", "available_models", "load_model", "load_wav", "normalize_keyword", "register_model",
|
|
15
|
+
]
|
naptrap/__main__.py
ADDED
naptrap/artifacts.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Load and verify a model artifact directory: ``config.json`` + ``model.safetensors``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Dict, Tuple
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
|
|
12
|
+
WEIGHTS = "model.safetensors"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ArtifactError(ValueError):
|
|
16
|
+
"""A model artifact is missing, has the wrong format or fails its checksum."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def sha256(path: Path) -> str:
|
|
20
|
+
digest = hashlib.sha256()
|
|
21
|
+
with path.open("rb") as stream:
|
|
22
|
+
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
|
23
|
+
digest.update(block)
|
|
24
|
+
return digest.hexdigest()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def read_config(directory: str | Path, expected_format: str) -> Tuple[Path, Dict[str, Any]]:
|
|
28
|
+
root = Path(directory).expanduser().resolve()
|
|
29
|
+
try:
|
|
30
|
+
config = json.loads((root / "config.json").read_text(encoding="utf-8"))
|
|
31
|
+
except (OSError, json.JSONDecodeError) as error:
|
|
32
|
+
raise ArtifactError(f"Cannot read config.json in {root}") from error
|
|
33
|
+
if not isinstance(config, dict) or config.get("format") != expected_format:
|
|
34
|
+
raise ArtifactError(f"{root} is not a {expected_format} artifact")
|
|
35
|
+
return root, config
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def load_artifact(directory: str | Path, expected_format: str) -> Tuple[Dict[str, Any], Dict[str, torch.Tensor]]:
|
|
39
|
+
"""Return ``(config, state_dict)`` after checking format and weight checksum."""
|
|
40
|
+
from safetensors.torch import load_file
|
|
41
|
+
|
|
42
|
+
root, config = read_config(directory, expected_format)
|
|
43
|
+
path = root / WEIGHTS
|
|
44
|
+
if not path.is_file():
|
|
45
|
+
raise ArtifactError(f"Missing {WEIGHTS} in {root}")
|
|
46
|
+
expected = config.get("sha256", {}).get(WEIGHTS)
|
|
47
|
+
if not isinstance(expected, str) or sha256(path) != expected:
|
|
48
|
+
raise ArtifactError(f"{WEIGHTS} checksum mismatch in {root}")
|
|
49
|
+
return config, load_file(str(path), device="cpu")
|
naptrap/audio.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Minimal WAV reading without NumPy or audio libraries."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import array
|
|
6
|
+
import sys
|
|
7
|
+
import wave
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
|
|
12
|
+
from .features import SAMPLE_RATE
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def load_wav(path: str | Path) -> torch.Tensor:
|
|
16
|
+
"""Read a mono 16 kHz 16-bit PCM WAV file as float32 samples in [-1, 1)."""
|
|
17
|
+
with wave.open(str(Path(path).expanduser()), "rb") as stream:
|
|
18
|
+
if stream.getnchannels() != 1 or stream.getsampwidth() != 2 or stream.getframerate() != SAMPLE_RATE:
|
|
19
|
+
raise ValueError("Expected a mono, 16-bit PCM, 16 kHz WAV file; convert it first, "
|
|
20
|
+
"e.g. ffmpeg -i in.wav -ac 1 -ar 16000 -sample_fmt s16 out.wav")
|
|
21
|
+
samples = array.array("h", stream.readframes(stream.getnframes()))
|
|
22
|
+
if sys.byteorder == "big":
|
|
23
|
+
samples.byteswap()
|
|
24
|
+
return torch.tensor(samples, dtype=torch.float32) / 32768
|
naptrap/cli.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Command-line interface: ``naptrap detect AUDIO.wav "keyword"``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .audio import load_wav
|
|
12
|
+
from .registry import available_models, load_model
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main(argv=None):
|
|
16
|
+
parser = argparse.ArgumentParser(prog="naptrap", description="Text-defined keyword detection for short clips.")
|
|
17
|
+
parser.add_argument("--version", action="version", version=f"naptrap {__version__}")
|
|
18
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
19
|
+
detect = commands.add_parser("detect", help="score one 0.5-2 s mono 16 kHz 16-bit WAV clip against a keyword")
|
|
20
|
+
detect.add_argument("audio", type=Path)
|
|
21
|
+
detect.add_argument("keyword")
|
|
22
|
+
detect.add_argument("--model", choices=available_models(), default="phonmatchnet")
|
|
23
|
+
detect.add_argument("--far", type=float, default=0.01, help="calibrated operating point (default 0.01)")
|
|
24
|
+
detect.add_argument("--model-dir", type=Path, help="local model directory (default: download)")
|
|
25
|
+
detect.add_argument("--google-dir", type=Path, help="local Google speech embedding directory")
|
|
26
|
+
detect.add_argument("--g2p-dir", type=Path, help="local G2P decoder directory")
|
|
27
|
+
args = parser.parse_args(argv)
|
|
28
|
+
try:
|
|
29
|
+
model = load_model(args.model, model_dir=args.model_dir, google_dir=args.google_dir, g2p_dir=args.g2p_dir)
|
|
30
|
+
result = model.detect(load_wav(args.audio), args.keyword, far=args.far)
|
|
31
|
+
except (ImportError, OSError, ValueError, RuntimeError) as error:
|
|
32
|
+
parser.exit(2, f"naptrap: {error}\n")
|
|
33
|
+
json.dump(result.to_dict(), sys.stdout, indent=2)
|
|
34
|
+
print()
|
|
35
|
+
return 0 if result.accepted else 1
|
naptrap/features.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Input validation and the 40-bin log-mel frontend used by PhonMatchNet."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
from torch import nn
|
|
9
|
+
|
|
10
|
+
SAMPLE_RATE = 16000
|
|
11
|
+
MIN_SAMPLES = SAMPLE_RATE // 2
|
|
12
|
+
MAX_SAMPLES = SAMPLE_RATE * 2
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def feature_tensor(value: Any, name: str, width: int, minimum: int, maximum: int) -> torch.Tensor:
|
|
16
|
+
"""Accept ``[time, width]`` or ``[1, time, width]`` float32 and return ``[1, time, width]`` on CPU."""
|
|
17
|
+
try:
|
|
18
|
+
tensor = torch.as_tensor(value)
|
|
19
|
+
except (TypeError, ValueError, RuntimeError) as error:
|
|
20
|
+
raise ValueError(f"{name} must be a float32 feature array") from error
|
|
21
|
+
if tensor.dtype != torch.float32:
|
|
22
|
+
raise ValueError(f"{name} must have dtype float32")
|
|
23
|
+
if tensor.ndim == 2:
|
|
24
|
+
tensor = tensor.unsqueeze(0)
|
|
25
|
+
if tensor.ndim != 3 or tensor.shape[0] != 1 or tensor.shape[2] != width:
|
|
26
|
+
raise ValueError(f"{name} must have shape [time,{width}] or [1,time,{width}]")
|
|
27
|
+
if not minimum <= tensor.shape[1] <= maximum:
|
|
28
|
+
raise ValueError(f"{name} time length must be between {minimum} and {maximum}")
|
|
29
|
+
tensor = tensor.detach().to(device="cpu").contiguous()
|
|
30
|
+
if not torch.isfinite(tensor).all():
|
|
31
|
+
raise ValueError(f"{name} must contain finite values")
|
|
32
|
+
return tensor
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def waveform_tensor(value: Any, sample_rate: int) -> torch.Tensor:
|
|
36
|
+
"""Validate one mono 16 kHz clip of 0.5-2 s, float32 scaled into [-1, 1]."""
|
|
37
|
+
if sample_rate != SAMPLE_RATE:
|
|
38
|
+
raise ValueError("Audio must be mono 16 kHz; resample before inference")
|
|
39
|
+
try:
|
|
40
|
+
wave = torch.as_tensor(value)
|
|
41
|
+
except (TypeError, ValueError, RuntimeError) as error:
|
|
42
|
+
raise ValueError("waveform must be a float32 array") from error
|
|
43
|
+
if wave.dtype != torch.float32 or wave.ndim != 1:
|
|
44
|
+
raise ValueError("waveform must be a one-dimensional float32 array scaled into [-1, 1]")
|
|
45
|
+
if not MIN_SAMPLES <= wave.numel() <= MAX_SAMPLES:
|
|
46
|
+
raise ValueError("Clip duration must be 0.5-2 seconds (8,000-32,000 samples at 16 kHz)")
|
|
47
|
+
wave = wave.detach().to(device="cpu").contiguous()
|
|
48
|
+
if not torch.isfinite(wave).all() or wave.abs().max() > 1:
|
|
49
|
+
raise ValueError("waveform must contain finite samples in [-1, 1]")
|
|
50
|
+
return wave
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class KeywordMel(nn.Module):
|
|
54
|
+
"""Log10 power mel spectrogram: 400-sample window, 160 hop, 512 FFT, 40 bins.
|
|
55
|
+
|
|
56
|
+
The mel matrix and window are stored with the trained weights.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(self):
|
|
60
|
+
super().__init__()
|
|
61
|
+
self.register_buffer("mel_matrix", torch.zeros(257, 40))
|
|
62
|
+
self.register_buffer("window", torch.zeros(400))
|
|
63
|
+
|
|
64
|
+
@torch.inference_mode()
|
|
65
|
+
def forward(self, wave: torch.Tensor) -> torch.Tensor:
|
|
66
|
+
spectrum = torch.stft(wave, n_fft=512, hop_length=160, win_length=400,
|
|
67
|
+
window=self.window, center=True, pad_mode="reflect", return_complex=True)
|
|
68
|
+
features = torch.log10(spectrum.abs().square().transpose(0, 1) @ self.mel_matrix + 1e-7)
|
|
69
|
+
return features[:(wave.numel() + 159) // 160].unsqueeze(0)
|
naptrap/google.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""PyTorch port of Google's speech_embedding/1 (Apache-2.0) feature extractor.
|
|
2
|
+
|
|
3
|
+
The converted weights, mel matrix and window come from the original TensorFlow
|
|
4
|
+
model unchanged; this module never imports TensorFlow or NumPy.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import torch
|
|
12
|
+
from torch import nn
|
|
13
|
+
from torch.nn import functional as F
|
|
14
|
+
|
|
15
|
+
from .artifacts import ArtifactError, load_artifact
|
|
16
|
+
from .features import SAMPLE_RATE, waveform_tensor
|
|
17
|
+
|
|
18
|
+
FORMAT = "naptrap-google-speech-embedding-v1"
|
|
19
|
+
PARENT_SHA256 = "0f626c42009c1eb916401b7b2800229a211e43100115bc591b9afbf1b60da27f"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class GoogleSpeechEmbedding(nn.Module):
|
|
23
|
+
"""16 kHz clip -> ``[floor(samples / 1280), 96]`` speech embeddings.
|
|
24
|
+
|
|
25
|
+
The clip is left-padded with 11,120 zeros and not trimmed, matching how the
|
|
26
|
+
keyword models were trained.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self):
|
|
30
|
+
super().__init__()
|
|
31
|
+
self.register_buffer("window", torch.zeros(400))
|
|
32
|
+
self.register_buffer("mel_matrix", torch.zeros(257, 32))
|
|
33
|
+
self.initial = nn.Conv2d(1, 24, (3, 3), padding=(0, 1), bias=False)
|
|
34
|
+
self.norms = nn.ModuleList([nn.BatchNorm2d(24, eps=.001)])
|
|
35
|
+
self.convs = nn.ModuleList()
|
|
36
|
+
channels = 24
|
|
37
|
+
for index in range(18):
|
|
38
|
+
target = {2: 48, 6: 72, 10: 96}.get(index, channels)
|
|
39
|
+
frequency = index % 2 == 0
|
|
40
|
+
self.convs.append(nn.Conv2d(channels, target, (1, 3) if frequency else (3, 1),
|
|
41
|
+
padding=(0, 1) if frequency else 0, bias=False))
|
|
42
|
+
self.norms.append(nn.BatchNorm2d(target, eps=.001))
|
|
43
|
+
channels = target
|
|
44
|
+
self.output = nn.Conv2d(96, 96, (3, 1), bias=False)
|
|
45
|
+
self._loaded = False
|
|
46
|
+
self.requires_grad_(False)
|
|
47
|
+
self.eval()
|
|
48
|
+
|
|
49
|
+
def train(self, mode=True):
|
|
50
|
+
# A frozen pretrained feature extractor; BatchNorm stays in inference mode.
|
|
51
|
+
return super().train(False)
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def from_pretrained(cls, directory: str | Path) -> "GoogleSpeechEmbedding":
|
|
55
|
+
config, state = load_artifact(directory, FORMAT)
|
|
56
|
+
if config.get("source", {}).get("archive_sha256") != PARENT_SHA256:
|
|
57
|
+
raise ArtifactError("Google speech embedding was converted from an unexpected source archive")
|
|
58
|
+
model = cls()
|
|
59
|
+
model.load_state_dict(state, strict=True)
|
|
60
|
+
model._loaded = True
|
|
61
|
+
return model.eval()
|
|
62
|
+
|
|
63
|
+
@staticmethod
|
|
64
|
+
def activation(value):
|
|
65
|
+
# Original graph: max(max(0.2*x,x),-0.4), after inference BatchNorm.
|
|
66
|
+
return F.leaky_relu(value, negative_slope=.2).clamp(min=-.4)
|
|
67
|
+
|
|
68
|
+
def log_mel(self, waveform):
|
|
69
|
+
padded = F.pad(waveform, (11120, 0))
|
|
70
|
+
# TensorFlow STFT windows start at frame zero: no centered FFT window.
|
|
71
|
+
frames = padded.unfold(0, 400, 160) * self.window
|
|
72
|
+
magnitude = torch.fft.rfft(frames, n=512, dim=-1).abs()
|
|
73
|
+
return torch.log(magnitude @ self.mel_matrix + .001)
|
|
74
|
+
|
|
75
|
+
def encode_log_mel(self, features):
|
|
76
|
+
value = features.unsqueeze(0).unsqueeze(0)
|
|
77
|
+
value = self.activation(self.norms[0](F.relu(self.initial(value))))
|
|
78
|
+
for index, conv in enumerate(self.convs):
|
|
79
|
+
value = self.activation(self.norms[index + 1](conv(value)))
|
|
80
|
+
if index in (1, 9, 17):
|
|
81
|
+
value = F.max_pool2d(value, kernel_size=(2, 2), stride=(2, 2))
|
|
82
|
+
elif index in (5, 13):
|
|
83
|
+
# The fixed 32-bin input gives even frequency widths here, so the
|
|
84
|
+
# original SAME pooling at index 5 adds no padding.
|
|
85
|
+
value = F.max_pool2d(value, kernel_size=(1, 2), stride=(1, 2))
|
|
86
|
+
return self.output(value)[0, :, :, 0].transpose(0, 1)
|
|
87
|
+
|
|
88
|
+
@torch.inference_mode()
|
|
89
|
+
def forward(self, waveform, sample_rate=SAMPLE_RATE):
|
|
90
|
+
if not self._loaded:
|
|
91
|
+
raise RuntimeError("Load pretrained weights with GoogleSpeechEmbedding.from_pretrained()")
|
|
92
|
+
wave = waveform_tensor(waveform, sample_rate).to(self.window.device)
|
|
93
|
+
result = self.encode_log_mel(self.log_mel(wave))
|
|
94
|
+
if result.shape != (wave.numel() // 1280, 96) or not torch.isfinite(result).all():
|
|
95
|
+
raise RuntimeError("Google speech embedding produced an invalid output")
|
|
96
|
+
return result
|
naptrap/hub.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Optional Hugging Face Hub downloads (``pip install 'naptrap[hub]'``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
DEFAULT_REVISION = "v1"
|
|
9
|
+
_FILES = ["config.json", "model.safetensors", "README.md", "LICENSE", "NOTICE"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def download(repo_id: str, revision: str = DEFAULT_REVISION, cache_dir: Optional[str] = None) -> Path:
|
|
13
|
+
"""Download one model repository's inference files and return its local directory."""
|
|
14
|
+
try:
|
|
15
|
+
from huggingface_hub import snapshot_download
|
|
16
|
+
except ImportError as error:
|
|
17
|
+
raise ImportError(
|
|
18
|
+
"Downloading models requires huggingface_hub: pip install 'naptrap[hub]'. "
|
|
19
|
+
"Alternatively, download the model directories yourself and pass their paths."
|
|
20
|
+
) from error
|
|
21
|
+
return Path(snapshot_download(repo_id, revision=revision, cache_dir=cache_dir, allow_patterns=_FILES))
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""PhonMatchNet network for single-clip inference.
|
|
2
|
+
|
|
3
|
+
Architecture after PhonMatchNet (Lee et al., Interspeech 2023) and NCSOFT's
|
|
4
|
+
BSD-3-Clause PyTorch implementation; see licenses/PhonMatchNet-BSD-3-Clause.txt.
|
|
5
|
+
Tensors hold one unpadded clip, so time axes are the valid lengths.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import math
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
from torch import nn
|
|
12
|
+
from torch.nn import functional as F
|
|
13
|
+
|
|
14
|
+
from ..features import KeywordMel
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class _Norm(nn.Module):
|
|
18
|
+
def __init__(self):
|
|
19
|
+
super().__init__()
|
|
20
|
+
# Nested name kept so weight keys match the trained checkpoint.
|
|
21
|
+
self.bn = nn.BatchNorm1d(128)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _Audio(nn.Module):
|
|
25
|
+
def __init__(self):
|
|
26
|
+
super().__init__()
|
|
27
|
+
self.frontend = KeywordMel()
|
|
28
|
+
self.conv1 = nn.Conv1d(40, 128, 3, stride=2, padding=1)
|
|
29
|
+
self.bn1 = _Norm()
|
|
30
|
+
self.conv2 = nn.Conv1d(128, 128, 3, padding=1)
|
|
31
|
+
self.bn2 = _Norm()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class PhonMatchNetwork(nn.Module):
|
|
35
|
+
def __init__(self):
|
|
36
|
+
super().__init__()
|
|
37
|
+
self.audio = _Audio()
|
|
38
|
+
self.google_upsample = nn.ConvTranspose1d(96, 128, 5, stride=4)
|
|
39
|
+
self.text_projection = nn.Linear(256, 128)
|
|
40
|
+
self.attention = nn.MultiheadAttention(128, 1, batch_first=True)
|
|
41
|
+
self.utterance_gru = nn.GRU(128, 128, batch_first=True)
|
|
42
|
+
self.utterance_head = nn.Linear(128, 1)
|
|
43
|
+
self.requires_grad_(False)
|
|
44
|
+
self.eval()
|
|
45
|
+
|
|
46
|
+
def train(self, mode=True):
|
|
47
|
+
return super().train(False)
|
|
48
|
+
|
|
49
|
+
def forward(self, keyword_mel, google, text):
|
|
50
|
+
value = F.relu(self.audio.bn1.bn(self.audio.conv1(keyword_mel.transpose(1, 2))))
|
|
51
|
+
value = F.relu(self.audio.bn2.bn(self.audio.conv2(value))).transpose(1, 2)
|
|
52
|
+
pretrained = F.leaky_relu(self.google_upsample(google.transpose(1, 2))).transpose(1, 2)
|
|
53
|
+
pretrained = F.pad(pretrained, (0, 0, 0, value.shape[1]))[:, :value.shape[1]]
|
|
54
|
+
textual = F.leaky_relu(self.text_projection(text))
|
|
55
|
+
joint = torch.cat([value + pretrained, textual], dim=1)
|
|
56
|
+
q, k, v = F.linear(joint, self.attention.in_proj_weight, self.attention.in_proj_bias).chunk(3, dim=-1)
|
|
57
|
+
logits = (q / math.sqrt(128.)) @ k.transpose(1, 2)
|
|
58
|
+
mask = torch.triu(torch.ones((joint.shape[1], joint.shape[1]), dtype=torch.bool, device=joint.device), diagonal=1)
|
|
59
|
+
attended = self.attention.out_proj(torch.softmax(logits.masked_fill(mask, float("-inf")), dim=-1) @ v)
|
|
60
|
+
_, hidden = self.utterance_gru(attended)
|
|
61
|
+
return self.utterance_head(hidden[-1]).squeeze(-1)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""PhonMatchNet text-defined keyword detection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Dict, Mapping, Optional, Union
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
from ..artifacts import WEIGHTS, ArtifactError, load_artifact, read_config, sha256
|
|
12
|
+
from ..features import SAMPLE_RATE, feature_tensor, waveform_tensor
|
|
13
|
+
from ..google import FORMAT as GOOGLE_FORMAT, GoogleSpeechEmbedding
|
|
14
|
+
from ..hub import DEFAULT_REVISION, download
|
|
15
|
+
from ..text import FORMAT as G2P_FORMAT, G2PTextEncoder, normalize_keyword
|
|
16
|
+
from ..types import Keyword, Prediction
|
|
17
|
+
from .network import PhonMatchNetwork
|
|
18
|
+
|
|
19
|
+
FORMAT = "naptrap-phonmatchnet-v1"
|
|
20
|
+
DEFAULT_REPO = "androiddrew/naptrap-phonmatchnet-en"
|
|
21
|
+
PathLike = Union[str, Path]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class PhonMatchNet:
|
|
25
|
+
"""Content-only (C-KWS) detection: was this keyword spoken in the clip?
|
|
26
|
+
|
|
27
|
+
Inputs are one mono 16 kHz clip of 0.5-2 seconds and an English keyword.
|
|
28
|
+
The keyword is converted to G2P decoder features, and the audio to 40-bin
|
|
29
|
+
log-mels plus Google speech embeddings. The model has no speaker
|
|
30
|
+
enrollment: it does not check who is speaking.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
name = "phonmatchnet"
|
|
34
|
+
task = "C-KWS"
|
|
35
|
+
|
|
36
|
+
def __init__(self, model_dir: PathLike, google_dir: PathLike, g2p_dir: PathLike):
|
|
37
|
+
config, state = load_artifact(model_dir, FORMAT)
|
|
38
|
+
try:
|
|
39
|
+
self._thresholds = {float(far): float(value) for far, value in config["thresholds"].items()}
|
|
40
|
+
except (KeyError, TypeError, ValueError, AttributeError) as error:
|
|
41
|
+
raise ArtifactError("config.json has no valid thresholds") from error
|
|
42
|
+
if not self._thresholds or not all(math.isfinite(v) for v in self._thresholds.values()):
|
|
43
|
+
raise ArtifactError("config.json has no valid thresholds")
|
|
44
|
+
self.config = config
|
|
45
|
+
self._check_companion("google", google_dir, GOOGLE_FORMAT)
|
|
46
|
+
self._check_companion("g2p", g2p_dir, G2P_FORMAT)
|
|
47
|
+
self._model = PhonMatchNetwork()
|
|
48
|
+
self._model.load_state_dict(state, strict=True)
|
|
49
|
+
self._frontend = self._model.audio.frontend
|
|
50
|
+
self.google_encoder = GoogleSpeechEmbedding.from_pretrained(google_dir)
|
|
51
|
+
self.text_encoder = G2PTextEncoder.from_pretrained(g2p_dir)
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def from_pretrained(cls, model_dir: Optional[PathLike] = None, *, google_dir: Optional[PathLike] = None,
|
|
55
|
+
g2p_dir: Optional[PathLike] = None, revision: Optional[str] = None,
|
|
56
|
+
cache_dir: Optional[str] = None) -> "PhonMatchNet":
|
|
57
|
+
"""Load from local directories, downloading any that are not given.
|
|
58
|
+
|
|
59
|
+
Downloads need ``pip install 'naptrap[hub]'``. ``revision`` applies to
|
|
60
|
+
the PhonMatchNet repository; companion encoders use the revisions
|
|
61
|
+
pinned in its ``config.json``.
|
|
62
|
+
"""
|
|
63
|
+
if model_dir is None:
|
|
64
|
+
model_dir = download(DEFAULT_REPO, revision or DEFAULT_REVISION, cache_dir)
|
|
65
|
+
_, config = read_config(model_dir, FORMAT)
|
|
66
|
+
requires = config.get("requires", {})
|
|
67
|
+
if google_dir is None:
|
|
68
|
+
google_dir = download(requires["google"]["repo_id"], requires["google"]["revision"], cache_dir)
|
|
69
|
+
if g2p_dir is None:
|
|
70
|
+
g2p_dir = download(requires["g2p"]["repo_id"], requires["g2p"]["revision"], cache_dir)
|
|
71
|
+
return cls(model_dir, google_dir, g2p_dir)
|
|
72
|
+
|
|
73
|
+
def _check_companion(self, key: str, directory: PathLike, expected_format: str) -> None:
|
|
74
|
+
required = self.config.get("requires", {}).get(key, {})
|
|
75
|
+
root, _ = read_config(directory, expected_format)
|
|
76
|
+
if required.get("sha256") and sha256(root / WEIGHTS) != required["sha256"]:
|
|
77
|
+
raise ArtifactError(f"{root} is not the {key} encoder this model was trained with")
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def thresholds(self) -> Dict[float, float]:
|
|
81
|
+
"""Available operating points: development target FAR -> score threshold."""
|
|
82
|
+
return dict(self._thresholds)
|
|
83
|
+
|
|
84
|
+
def keyword(self, text: str) -> Keyword:
|
|
85
|
+
"""Precompute a keyword's text features; reuse the result across clips."""
|
|
86
|
+
return Keyword(normalize_keyword(text), self.text_encoder(text))
|
|
87
|
+
|
|
88
|
+
@torch.inference_mode()
|
|
89
|
+
def detect(self, waveform: Any, keyword: Union[str, Keyword], *, sample_rate: int = SAMPLE_RATE,
|
|
90
|
+
far: float = 0.01) -> Prediction:
|
|
91
|
+
"""Score one clip against a keyword string or a :meth:`keyword` result.
|
|
92
|
+
|
|
93
|
+
``waveform`` is a 1-D float32 tensor or array of 0.5-2 s mono 16 kHz
|
|
94
|
+
audio scaled into [-1, 1]. ``far`` selects an operating point from
|
|
95
|
+
:attr:`thresholds`.
|
|
96
|
+
"""
|
|
97
|
+
if not isinstance(keyword, Keyword):
|
|
98
|
+
keyword = self.keyword(keyword)
|
|
99
|
+
wave = waveform_tensor(waveform, sample_rate)
|
|
100
|
+
features = {
|
|
101
|
+
"keyword_mel": self._frontend(wave),
|
|
102
|
+
"google": self.google_encoder(wave, sample_rate=sample_rate),
|
|
103
|
+
"text": keyword.features,
|
|
104
|
+
}
|
|
105
|
+
return self.predict(features, far=far)
|
|
106
|
+
|
|
107
|
+
@torch.inference_mode()
|
|
108
|
+
def predict(self, features: Mapping[str, Any], *, far: float = 0.01) -> Prediction:
|
|
109
|
+
"""Score precomputed ``keyword_mel`` [T,40], ``google`` [G,96] and ``text`` [P,256] features."""
|
|
110
|
+
if far not in self._thresholds:
|
|
111
|
+
choices = ", ".join(str(v) for v in sorted(self._thresholds))
|
|
112
|
+
raise ValueError(f"far must be one of the calibrated operating points: {choices}")
|
|
113
|
+
missing = {"keyword_mel", "google", "text"} - set(features.keys())
|
|
114
|
+
if missing:
|
|
115
|
+
raise ValueError("Missing features: " + ", ".join(sorted(missing)))
|
|
116
|
+
mel = feature_tensor(features["keyword_mel"], "keyword_mel", 40, 50, 200)
|
|
117
|
+
google = feature_tensor(features["google"], "google", 96, 6, 25)
|
|
118
|
+
text = feature_tensor(features["text"], "text", 256, 1, 128)
|
|
119
|
+
if not 8 * google.shape[1] <= mel.shape[1] <= 8 * google.shape[1] + 8:
|
|
120
|
+
raise ValueError("keyword_mel and google features describe different clip lengths")
|
|
121
|
+
logits = self._model(mel, google, text)
|
|
122
|
+
if logits.shape != (1,) or not torch.isfinite(logits).all():
|
|
123
|
+
raise RuntimeError("Model returned an invalid keyword logit")
|
|
124
|
+
score = float(logits.sigmoid()[0])
|
|
125
|
+
threshold = self._thresholds[far]
|
|
126
|
+
return Prediction(model=self.name, task=self.task, score=score, threshold=threshold,
|
|
127
|
+
accepted=score >= threshold, target_far=far,
|
|
128
|
+
details={"keyword_logit": float(logits[0])})
|
naptrap/registry.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Model registry: maps a family name to the function that loads it."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Callable, Dict, Tuple
|
|
6
|
+
|
|
7
|
+
from .types import KeywordModel
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _phonmatchnet(**kwargs) -> KeywordModel:
|
|
11
|
+
from .models.phonmatchnet import PhonMatchNet
|
|
12
|
+
return PhonMatchNet.from_pretrained(**kwargs)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
_FACTORIES: Dict[str, Callable[..., KeywordModel]] = {"phonmatchnet": _phonmatchnet}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def available_models() -> Tuple[str, ...]:
|
|
19
|
+
return tuple(sorted(_FACTORIES))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def register_model(name: str, factory: Callable[..., KeywordModel]) -> None:
|
|
23
|
+
"""Register an additional model family under a new lowercase name."""
|
|
24
|
+
if not isinstance(name, str) or not name or name != name.strip().lower():
|
|
25
|
+
raise ValueError("Model names must be nonempty, lowercase and whitespace-trimmed")
|
|
26
|
+
if not callable(factory):
|
|
27
|
+
raise TypeError("A model factory must be callable")
|
|
28
|
+
if name in _FACTORIES:
|
|
29
|
+
raise ValueError("Model is already registered: " + name)
|
|
30
|
+
_FACTORIES[name] = factory
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def load_model(name: str = "phonmatchnet", **kwargs) -> KeywordModel:
|
|
34
|
+
"""Load a registered model family; keyword arguments go to its loader.
|
|
35
|
+
|
|
36
|
+
For ``phonmatchnet`` see :meth:`naptrap.PhonMatchNet.from_pretrained`.
|
|
37
|
+
"""
|
|
38
|
+
try:
|
|
39
|
+
factory = _FACTORIES[name]
|
|
40
|
+
except KeyError as error:
|
|
41
|
+
raise ValueError(f"Unknown model {name!r}; available: {', '.join(available_models())}") from error
|
|
42
|
+
return factory(**kwargs)
|
naptrap/text.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Keyword text features: a PyTorch port of the g2p_en neural decoder states.
|
|
2
|
+
|
|
3
|
+
PhonMatchNet consumes the hidden states of the g2p_en grapheme-to-phoneme
|
|
4
|
+
decoder (Kyubyong Park & Jongseok Kim, Apache-2.0), not phoneme strings. Each
|
|
5
|
+
word is encoded with the grapheme GRU, then decoded greedily; every emitted
|
|
6
|
+
decoder state becomes one 256-D feature row, and words are separated by the
|
|
7
|
+
decoder's padding embedding. This mirrors ``G2p.embedding()`` from the
|
|
8
|
+
PhonMatchNet repository without NumPy, NLTK or dictionary lookups.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
import unicodedata
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import torch
|
|
18
|
+
from torch import nn
|
|
19
|
+
|
|
20
|
+
from .artifacts import load_artifact
|
|
21
|
+
|
|
22
|
+
FORMAT = "naptrap-g2p-en-decoder-v1"
|
|
23
|
+
GRAPHEMES = ["<pad>", "<unk>", "</s>"] + list("abcdefghijklmnopqrstuvwxyz")
|
|
24
|
+
_START, _END, _MAX_STEPS = 2, 3, 20
|
|
25
|
+
_TOKENS = re.compile(r"[a-z]+(?:'[a-z]+)*|[0-9]+")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def normalize_keyword(text: str) -> str:
|
|
29
|
+
"""Lowercase, strip accents and punctuation; the policy used during training."""
|
|
30
|
+
if not isinstance(text, str):
|
|
31
|
+
raise TypeError("keyword must be a string")
|
|
32
|
+
text = unicodedata.normalize("NFKD", text.replace("’", "'"))
|
|
33
|
+
text = "".join(c for c in text if not unicodedata.combining(c)).lower()
|
|
34
|
+
words = _TOKENS.findall(text)
|
|
35
|
+
if any(word.isdigit() for word in words):
|
|
36
|
+
raise ValueError("Spell out numbers in the keyword, e.g. 'route sixty six'")
|
|
37
|
+
if not words:
|
|
38
|
+
raise ValueError("keyword contains no English letters")
|
|
39
|
+
return " ".join(words)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class _GRUCell(nn.Module):
|
|
43
|
+
def __init__(self, size: int):
|
|
44
|
+
super().__init__()
|
|
45
|
+
self.w_ih = nn.Parameter(torch.zeros(3 * size, size))
|
|
46
|
+
self.w_hh = nn.Parameter(torch.zeros(3 * size, size))
|
|
47
|
+
self.b_ih = nn.Parameter(torch.zeros(3 * size))
|
|
48
|
+
self.b_hh = nn.Parameter(torch.zeros(3 * size))
|
|
49
|
+
|
|
50
|
+
def forward(self, x: torch.Tensor, h: torch.Tensor) -> torch.Tensor:
|
|
51
|
+
# Same gate order and arithmetic as g2p_en's NumPy grucell (r, z | n).
|
|
52
|
+
ih = x @ self.w_ih.T + self.b_ih
|
|
53
|
+
hh = h @ self.w_hh.T + self.b_hh
|
|
54
|
+
split = ih.shape[-1] * 2 // 3
|
|
55
|
+
r, z = torch.sigmoid(ih[:, :split] + hh[:, :split]).chunk(2, dim=-1)
|
|
56
|
+
n = torch.tanh(ih[:, split:] + r * hh[:, split:])
|
|
57
|
+
return (1 - z) * n + z * h
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class G2PTextEncoder(nn.Module):
|
|
61
|
+
"""Keyword string -> ``[positions, 256]`` float32 decoder features."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, size: int = 256, phonemes: int = 74):
|
|
64
|
+
super().__init__()
|
|
65
|
+
self.size = size
|
|
66
|
+
self.enc_emb = nn.Parameter(torch.zeros(len(GRAPHEMES), size))
|
|
67
|
+
self.encoder = _GRUCell(size)
|
|
68
|
+
self.dec_emb = nn.Parameter(torch.zeros(phonemes, size))
|
|
69
|
+
self.decoder = _GRUCell(size)
|
|
70
|
+
self.fc_w = nn.Parameter(torch.zeros(phonemes, size))
|
|
71
|
+
self.fc_b = nn.Parameter(torch.zeros(phonemes))
|
|
72
|
+
self._index = {g: i for i, g in enumerate(GRAPHEMES)}
|
|
73
|
+
self.requires_grad_(False)
|
|
74
|
+
self.eval()
|
|
75
|
+
|
|
76
|
+
@classmethod
|
|
77
|
+
def from_pretrained(cls, directory: str | Path) -> "G2PTextEncoder":
|
|
78
|
+
config, state = load_artifact(directory, FORMAT)
|
|
79
|
+
model = cls(size=int(config["hidden_size"]), phonemes=int(config["phonemes"]))
|
|
80
|
+
model.load_state_dict(state, strict=True)
|
|
81
|
+
return model
|
|
82
|
+
|
|
83
|
+
def _word(self, word: str) -> torch.Tensor:
|
|
84
|
+
unknown = self._index["<unk>"]
|
|
85
|
+
ids = [self._index.get(c, unknown) for c in word] + [self._index["</s>"]]
|
|
86
|
+
h = torch.zeros(1, self.size)
|
|
87
|
+
for index in ids:
|
|
88
|
+
h = self.encoder(self.enc_emb[index:index + 1], h)
|
|
89
|
+
token, states = _START, []
|
|
90
|
+
for _ in range(_MAX_STEPS):
|
|
91
|
+
h = self.decoder(self.dec_emb[token:token + 1], h)
|
|
92
|
+
token = int((h @ self.fc_w.T + self.fc_b).argmax())
|
|
93
|
+
if token == _END:
|
|
94
|
+
break
|
|
95
|
+
states.append(h)
|
|
96
|
+
return torch.cat(states) if states else h.new_zeros(0, self.size)
|
|
97
|
+
|
|
98
|
+
@torch.inference_mode()
|
|
99
|
+
def forward(self, keyword: str) -> torch.Tensor:
|
|
100
|
+
rows = []
|
|
101
|
+
for word in normalize_keyword(keyword).split():
|
|
102
|
+
rows += [self._word(word), self.dec_emb[0:1]]
|
|
103
|
+
features = torch.cat(rows[:-1])
|
|
104
|
+
if features.shape[0] < 1:
|
|
105
|
+
raise ValueError("keyword produced no phonetic features")
|
|
106
|
+
return features.contiguous()
|
naptrap/types.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Common result and model interfaces for naptrap backends."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any, Dict, Mapping, Protocol
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Keyword:
|
|
14
|
+
"""A keyword's normalized text and its precomputed text features."""
|
|
15
|
+
|
|
16
|
+
text: str
|
|
17
|
+
features: torch.Tensor = field(repr=False, compare=False)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Prediction:
|
|
22
|
+
"""One clip's keyword decision at a fixed operating point.
|
|
23
|
+
|
|
24
|
+
``score`` is model specific; for PhonMatchNet it is the keyword-match
|
|
25
|
+
probability. ``target_far`` names the calibration target the threshold was
|
|
26
|
+
fitted for on development data. It is not a guaranteed false-accept rate on
|
|
27
|
+
other audio.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
model: str
|
|
31
|
+
task: str
|
|
32
|
+
score: float
|
|
33
|
+
threshold: float
|
|
34
|
+
accepted: bool
|
|
35
|
+
target_far: float
|
|
36
|
+
details: Mapping[str, float] = field(default_factory=dict)
|
|
37
|
+
|
|
38
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
39
|
+
return {
|
|
40
|
+
"model": self.model,
|
|
41
|
+
"task": self.task,
|
|
42
|
+
"score": self.score,
|
|
43
|
+
"threshold": self.threshold,
|
|
44
|
+
"accepted": self.accepted,
|
|
45
|
+
"target_far": self.target_far,
|
|
46
|
+
"details": dict(self.details),
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class KeywordModel(Protocol):
|
|
51
|
+
"""Interface every backend implements; inputs are documented per backend."""
|
|
52
|
+
|
|
53
|
+
def keyword(self, text: str) -> Keyword:
|
|
54
|
+
...
|
|
55
|
+
|
|
56
|
+
def detect(self, waveform: Any, keyword: "str | Keyword", *, sample_rate: int = 16000,
|
|
57
|
+
far: float = 0.01) -> Prediction:
|
|
58
|
+
...
|
|
59
|
+
|
|
60
|
+
def predict(self, features: Mapping[str, Any], *, far: float = 0.01) -> Prediction:
|
|
61
|
+
...
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: naptrap
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Local, text-defined wake word and keyword detection in PyTorch
|
|
5
|
+
Author-email: Drew Bednar <drew@runcible.io>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/androiddrew/naptrap
|
|
8
|
+
Project-URL: Issues, https://github.com/androiddrew/naptrap/issues
|
|
9
|
+
Project-URL: Models, https://huggingface.co/androiddrew/naptrap-phonmatchnet-en
|
|
10
|
+
Keywords: wake word,keyword spotting,speech,phonmatchnet,pytorch,kws
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
License-File: NOTICE
|
|
23
|
+
License-File: licenses/PhonMatchNet-BSD-3-Clause.txt
|
|
24
|
+
Requires-Dist: torch>=1.13
|
|
25
|
+
Requires-Dist: safetensors>=0.4
|
|
26
|
+
Provides-Extra: hub
|
|
27
|
+
Requires-Dist: huggingface_hub>=0.20; extra == "hub"
|
|
28
|
+
Provides-Extra: test
|
|
29
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
30
|
+
Requires-Dist: numpy; extra == "test"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# naptrap
|
|
34
|
+
|
|
35
|
+
**Local, text-defined wake word detection in PyTorch.** Type a keyword, give
|
|
36
|
+
naptrap a short audio clip, and it tells you whether the keyword was spoken.
|
|
37
|
+
New wake words need no recordings or training.
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from naptrap import load_model, load_wav
|
|
41
|
+
|
|
42
|
+
model = load_model("phonmatchnet") # downloads the model on first use
|
|
43
|
+
result = model.detect(load_wav("clip.wav"), "hey computer")
|
|
44
|
+
|
|
45
|
+
print(result.score) # keyword-match probability, 0-1
|
|
46
|
+
print(result.accepted) # score >= the model's calibrated threshold
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The first model is an independently trained
|
|
50
|
+
[PhonMatchNet](https://huggingface.co/androiddrew/naptrap-phonmatchnet-en)
|
|
51
|
+
(Lee & Cho, Interspeech 2023) for English. Inference runs on the CPU with
|
|
52
|
+
**PyTorch as the only heavy dependency**. There is no TensorFlow, NumPy,
|
|
53
|
+
torchaudio or NLTK, and no cloud API.
|
|
54
|
+
|
|
55
|
+
## Install
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
pip install "naptrap[hub]"
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Python 3.9+ and PyTorch 1.13+ are required. If you want a CPU-only or
|
|
62
|
+
CUDA-specific PyTorch build, install it first; see
|
|
63
|
+
[pytorch.org](https://pytorch.org/get-started/locally/). The `hub` extra adds
|
|
64
|
+
`huggingface_hub` for automatic model downloads. Without it, `pip install
|
|
65
|
+
naptrap` works with model directories you download yourself.
|
|
66
|
+
|
|
67
|
+
## Models
|
|
68
|
+
|
|
69
|
+
`load_model("phonmatchnet")` fetches three Hugging Face repositories (about
|
|
70
|
+
6 MB in total), pinned to revision `v1`, and caches them locally:
|
|
71
|
+
|
|
72
|
+
| Repository | Role | License |
|
|
73
|
+
|---|---|---|
|
|
74
|
+
| [`androiddrew/naptrap-phonmatchnet-en`](https://huggingface.co/androiddrew/naptrap-phonmatchnet-en) | keyword matcher | Apache-2.0 |
|
|
75
|
+
| [`androiddrew/google-speech-embedding-pytorch`](https://huggingface.co/androiddrew/google-speech-embedding-pytorch) | frozen audio encoder | Apache-2.0 |
|
|
76
|
+
| [`androiddrew/g2p-en-decoder-pytorch`](https://huggingface.co/androiddrew/g2p-en-decoder-pytorch) | frozen keyword text encoder | Apache-2.0 |
|
|
77
|
+
|
|
78
|
+
To work offline, download them once and pass the directories:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
hf download androiddrew/naptrap-phonmatchnet-en --revision v1 --local-dir models/phonmatchnet
|
|
82
|
+
hf download androiddrew/google-speech-embedding-pytorch --revision v1 --local-dir models/google
|
|
83
|
+
hf download androiddrew/g2p-en-decoder-pytorch --revision v1 --local-dir models/g2p
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
model = load_model("phonmatchnet", model_dir="models/phonmatchnet",
|
|
88
|
+
google_dir="models/google", g2p_dir="models/g2p")
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Every weight file is checked against the SHA-256 recorded in its `config.json`.
|
|
92
|
+
The keyword model also pins the exact encoders it was trained with.
|
|
93
|
+
|
|
94
|
+
## Usage
|
|
95
|
+
|
|
96
|
+
### Audio
|
|
97
|
+
|
|
98
|
+
`detect()` scores **one mono 16 kHz clip of 0.5–2 seconds**, given as a 1-D
|
|
99
|
+
float32 tensor or array with values in [-1, 1]. `load_wav()` reads 16-bit PCM
|
|
100
|
+
WAV files using only the standard library. Convert other files first:
|
|
101
|
+
|
|
102
|
+
```bash
|
|
103
|
+
ffmpeg -i input.m4a -ac 1 -ar 16000 -sample_fmt s16 clip.wav
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
naptrap does not resample, trim or rescale audio for you.
|
|
107
|
+
|
|
108
|
+
### Reusing a keyword
|
|
109
|
+
|
|
110
|
+
Converting the keyword text is cheap, but if you score many clips against the
|
|
111
|
+
same keyword you can do it once:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
wake = model.keyword("hey computer")
|
|
115
|
+
for clip in clips:
|
|
116
|
+
if model.detect(clip, wake).accepted:
|
|
117
|
+
...
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Keywords are English words; accents and punctuation are removed. Spell out
|
|
121
|
+
numbers ("route sixty six").
|
|
122
|
+
|
|
123
|
+
### Operating points and thresholds
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
model.thresholds # {0.01: 0.7149..., 0.1: 0.0025...}
|
|
127
|
+
model.detect(clip, "hey computer", far=0.1) # more sensitive
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Each threshold was fitted on held-out development speakers to target a
|
|
131
|
+
per-clip false-accept rate (FAR) of 1% or 10%. **These targets do not hold on
|
|
132
|
+
other audio.** On phonetically confusable phrases, the 1% threshold accepted
|
|
133
|
+
31% of negatives. For a real product, record some positive and negative clips
|
|
134
|
+
in your setting and choose your own threshold on `result.score`. See the
|
|
135
|
+
[model card](https://huggingface.co/androiddrew/naptrap-phonmatchnet-en) for
|
|
136
|
+
the evaluation.
|
|
137
|
+
|
|
138
|
+
### Command line
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
naptrap detect clip.wav "hey computer"
|
|
142
|
+
naptrap detect clip.wav "hey computer" --far 0.1 --model-dir models/phonmatchnet \
|
|
143
|
+
--google-dir models/google --g2p-dir models/g2p
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
The command prints the prediction as JSON. It exits with 0 if the keyword was
|
|
147
|
+
accepted, 1 if it was rejected and 2 on error. `python -m naptrap` works the
|
|
148
|
+
same way.
|
|
149
|
+
|
|
150
|
+
### Precomputed features
|
|
151
|
+
|
|
152
|
+
`model.predict({"keyword_mel": ..., "google": ..., "text": ...})` scores
|
|
153
|
+
features you computed yourself: `[T, 40]`, `[T/8, 96]` and `[P, 256]` float32.
|
|
154
|
+
The encoders are exposed as `naptrap.GoogleSpeechEmbedding` and
|
|
155
|
+
`naptrap.G2PTextEncoder`.
|
|
156
|
+
|
|
157
|
+
## Limitations
|
|
158
|
+
|
|
159
|
+
- **Single clips, not a streaming listener (yet).** To watch a microphone you
|
|
160
|
+
must window the audio yourself, e.g. 1.5 s windows every 0.25 s, and add
|
|
161
|
+
your own debouncing.
|
|
162
|
+
- **English only**, trained on read audiobook speech (LibriSpeech). Expect
|
|
163
|
+
lower accuracy with noise, far-field microphones, accents or children.
|
|
164
|
+
- **No speaker verification.** Anyone saying the keyword triggers it.
|
|
165
|
+
- Similar-sounding phrases are often confused.
|
|
166
|
+
- CPU inference is the supported path; other devices have not been validated.
|
|
167
|
+
- Not for security or safety-critical use.
|
|
168
|
+
|
|
169
|
+
## Adding model families
|
|
170
|
+
|
|
171
|
+
Backends implement `keyword()`, `detect()` and `predict()`, and return a
|
|
172
|
+
`Prediction`. Register a loader under a new name:
|
|
173
|
+
|
|
174
|
+
```python
|
|
175
|
+
from naptrap import register_model, load_model
|
|
176
|
+
|
|
177
|
+
register_model("my-model", MyModel.from_pretrained)
|
|
178
|
+
model = load_model("my-model", model_dir="...")
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## Development
|
|
182
|
+
|
|
183
|
+
```bash
|
|
184
|
+
pip install -e ".[test]"
|
|
185
|
+
pytest
|
|
186
|
+
# Also run the real-model tests against downloaded model directories:
|
|
187
|
+
NAPTRAP_TEST_MODELS=path/to/models pytest
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
`NAPTRAP_TEST_MODELS` must point at a directory holding the three model
|
|
191
|
+
repositories in subdirectories named `naptrap-phonmatchnet-en`,
|
|
192
|
+
`google-speech-embedding-pytorch` and `g2p-en-decoder-pytorch`.
|
|
193
|
+
|
|
194
|
+
## License and attribution
|
|
195
|
+
|
|
196
|
+
naptrap is licensed under the [Apache License 2.0](LICENSE). The network
|
|
197
|
+
follows the PhonMatchNet design and NCSOFT's BSD-3-Clause reference code (see
|
|
198
|
+
[NOTICE](NOTICE) and [licenses/](licenses/)). The PhonMatchNet weights were
|
|
199
|
+
trained independently. **naptrap is not affiliated with or endorsed by NCSOFT
|
|
200
|
+
or the PhonMatchNet authors.** See
|
|
201
|
+
[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for every component.
|
|
202
|
+
|
|
203
|
+
If naptrap's PhonMatchNet model is useful in your research, please cite:
|
|
204
|
+
|
|
205
|
+
```bibtex
|
|
206
|
+
@inproceedings{lee23phonmatchnet,
|
|
207
|
+
title = {PhonMatchNet: Phoneme-Guided Zero-Shot Keyword Spotting for User-Defined Keywords},
|
|
208
|
+
author = {Lee, Yong-Hyeok and Cho, Namhyun},
|
|
209
|
+
booktitle = {Proc. INTERSPEECH 2023},
|
|
210
|
+
pages = {3964--3968},
|
|
211
|
+
year = {2023}
|
|
212
|
+
}
|
|
213
|
+
```
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
naptrap/__init__.py,sha256=e9ngGAehjTutdhti-MQeGeikdp5MykvZ-RVxSiKO3kw,628
|
|
2
|
+
naptrap/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
|
|
3
|
+
naptrap/artifacts.py,sha256=0YjP9o8_MVeqO9AsjNtuOMjVaoHDhG70LKQ8QJR-TKQ,1811
|
|
4
|
+
naptrap/audio.py,sha256=YTVwSxfJy-wVCM0g8EAdoN_daYFrDsShABUfPyTlqRs,897
|
|
5
|
+
naptrap/cli.py,sha256=vziRdOX42RuSdmAKBqiQ2tPoCTTWHSWPRuXxmVUhVec,1706
|
|
6
|
+
naptrap/features.py,sha256=PRgf00IyGQ3NiRklJgkbs25tHqbaOBK2fwzlrbHLnDk,3047
|
|
7
|
+
naptrap/google.py,sha256=h0bdBqclqetX1FcHNRkOzNkKbJfup1d7pNX7Ru9O9RE,4197
|
|
8
|
+
naptrap/hub.py,sha256=3AYHrbudtJjk-Wn96JxZiVEj3AhCmiToGkfcb4UYPL8,896
|
|
9
|
+
naptrap/registry.py,sha256=OqkA_CBnYGmcAhmxC0XwKqOiVFcwFXUMD6s-Xahj4i4,1475
|
|
10
|
+
naptrap/text.py,sha256=lW0tbqmb66CykRZ64tAzsyF_mmgNB0T6vddlq76J43U,4313
|
|
11
|
+
naptrap/types.py,sha256=eMzr2ZgUZyjKmUPo9yREdBY2n4E-p65Ja3e6MSopOEU,1690
|
|
12
|
+
naptrap/models/__init__.py,sha256=xPIbVlXQtopgkj6c-NkA7yH6mYHN6bY59gHTSZk6AhI,105
|
|
13
|
+
naptrap/models/network.py,sha256=_m6rxZZoHMoyG1oRfHKvSKkaqfcKiQBTuWkrhRo8arE,2466
|
|
14
|
+
naptrap/models/phonmatchnet.py,sha256=wZUzaG0AKVjRWtKV1uHR6x2LYRorZS6xYUD3WAPMebo,6437
|
|
15
|
+
naptrap-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
16
|
+
naptrap-0.1.0.dist-info/licenses/NOTICE,sha256=Hw8PSK2Ue5e7MgQC4zkDuAjsseiP4vdmCh5L-df9sK4,879
|
|
17
|
+
naptrap-0.1.0.dist-info/licenses/licenses/PhonMatchNet-BSD-3-Clause.txt,sha256=K5PxNqW-JnzVVahI3K4TI1MXxBQgVWxu8K-8zxhcgMA,1534
|
|
18
|
+
naptrap-0.1.0.dist-info/METADATA,sha256=c8zA_g3UjqSaRUoh9lFVfywKc7oWuxTA3ESyYfcWOxs,7952
|
|
19
|
+
naptrap-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
20
|
+
naptrap-0.1.0.dist-info/entry_points.txt,sha256=cqZp15lOsP1ZtVBj1UehLR0G0V2MmCQdqfGY7K_9794,45
|
|
21
|
+
naptrap-0.1.0.dist-info/top_level.txt,sha256=mTShbwf71nvzi8nL6YoBXsUFxtatajbl_wkKrwfYgng,8
|
|
22
|
+
naptrap-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
naptrap
|
|
2
|
+
Copyright 2026 Drew Bednar
|
|
3
|
+
|
|
4
|
+
This product is licensed under the Apache License, Version 2.0 (LICENSE).
|
|
5
|
+
|
|
6
|
+
src/naptrap/models/network.py implements the PhonMatchNet architecture
|
|
7
|
+
(Yong-Hyeok Lee and Namhyun Cho, Interspeech 2023) after NCSOFT's
|
|
8
|
+
BSD-3-Clause PyTorch implementation, https://github.com/ncsoft/PhonMatchNet.
|
|
9
|
+
NCSOFT's copyright notice and license: licenses/PhonMatchNet-BSD-3-Clause.txt.
|
|
10
|
+
naptrap is not affiliated with or endorsed by NCSOFT or the PhonMatchNet authors.
|
|
11
|
+
|
|
12
|
+
src/naptrap/text.py reimplements the decoder-state "embedding" computation of
|
|
13
|
+
g2p_en by Kyubyong Park and Jongseok Kim (Apache-2.0),
|
|
14
|
+
https://github.com/Kyubyong/g2p.
|
|
15
|
+
|
|
16
|
+
src/naptrap/google.py reimplements Google's speech_embedding/1 model
|
|
17
|
+
(Apache-2.0) in PyTorch. naptrap is not affiliated with or endorsed by Google.
|
|
18
|
+
|
|
19
|
+
Model weights are not included in this package; see THIRD_PARTY_NOTICES.md.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
© 2024 NCSOFT Corporation. All Rights Reserved.
|
|
2
|
+
|
|
3
|
+
BSD 3-Clause "New" or "Revised" License
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
list of conditions and the following disclaimer.
|
|
10
|
+
|
|
11
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
contributors may be used to endorse or promote products derived from
|
|
17
|
+
this software without specific prior written permission.
|
|
18
|
+
|
|
19
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
naptrap
|