scriptrs 0.5.0__cp311-abi3-win_amd64.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.
scriptrs/__init__.py ADDED
@@ -0,0 +1,251 @@
1
+ """Fast NVIDIA Parakeet TDT speech-to-text, on Core ML (macOS) and CUDA (Linux and Windows).
2
+
3
+ Pick a model when you load the pipeline, then transcribe files or 16 kHz mono
4
+ samples::
5
+
6
+ import scriptrs
7
+
8
+ pipeline = scriptrs.Pipeline.from_pretrained("parakeet/v2") # or "parakeet/v3" for 25 languages
9
+ result = pipeline.transcribe_file("meeting.wav")
10
+ print(result.text)
11
+
12
+ Inference runs in Rust with the GIL released, so other Python threads keep
13
+ running while a call is in progress.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections.abc import Sequence
19
+ from enum import Enum
20
+ from importlib import metadata
21
+ from os import PathLike
22
+ from pathlib import Path
23
+ from typing import TYPE_CHECKING, Literal
24
+
25
+ from . import _cuda, _native
26
+ from ._errors import ScriptrsError
27
+ from ._native import (
28
+ ALL_LANGUAGES,
29
+ BACKEND,
30
+ TimedToken,
31
+ TranscriptChunk,
32
+ TranscriptionResult,
33
+ )
34
+
35
+ if TYPE_CHECKING:
36
+ from typing import Any, Protocol
37
+
38
+ from typing_extensions import Buffer
39
+
40
+ class _ArrayInterface(Protocol):
41
+ # NumPy only declares __buffer__ for Python 3.12+, so match its array
42
+ # interface too
43
+ @property
44
+ def __array_interface__(self) -> dict[str, Any]: ...
45
+
46
+ Samples = Buffer | _ArrayInterface | Sequence[float]
47
+
48
+ try:
49
+ __version__ = metadata.version("scriptrs")
50
+ except metadata.PackageNotFoundError: # pragma: no cover - source checkout without install
51
+ __version__ = "0.0.0"
52
+
53
+
54
+ class Model(str, Enum):
55
+ """Which model to run.
56
+
57
+ Values are ``"<family>/<version>"``, so other model families can be added
58
+ beside Parakeet. Anywhere a model is taken, its value, such as
59
+ ``"parakeet/v3"``, or the upstream model id, such as
60
+ ``"nvidia/parakeet-tdt-0.6b-v3"``, works too.
61
+ """
62
+
63
+ PARAKEET_V2 = "parakeet/v2"
64
+ """NVIDIA Parakeet TDT 0.6B v2: English only, slightly more accurate on English."""
65
+ PARAKEET_V3 = "parakeet/v3"
66
+ """NVIDIA Parakeet TDT 0.6B v3: 25 European languages, detected automatically."""
67
+
68
+ @property
69
+ def languages(self) -> list[str]:
70
+ """ISO 639-1 codes of the languages this model transcribes."""
71
+ return _native.languages(self.value)
72
+
73
+
74
+ ModelName = Model | Literal["parakeet/v2", "parakeet/v3"] | str
75
+ """A :class:`Model`, its value, or its upstream model id."""
76
+
77
+ Precision = Literal["fp16", "tf32", "fp32"]
78
+ """Precision of the CUDA encoder's matrix multiplies; Core ML ignores it.
79
+
80
+ ``"fp16"`` is the default and the fastest. ``"tf32"`` keeps the weights in FP32,
81
+ and ``"fp32"`` matches NVIDIA NeMo's FP32 output token for token.
82
+ """
83
+
84
+ StrPath = str | PathLike[str]
85
+
86
+ # upstream model ids, so a name copied from Hugging Face or NeMo works as is
87
+ _UPSTREAM_IDS = {
88
+ "nvidia/parakeet-tdt-0.6b-v2": "parakeet/v2",
89
+ "nvidia/parakeet-tdt-0.6b-v3": "parakeet/v3",
90
+ }
91
+ _PRECISIONS = ("fp16", "tf32", "fp32")
92
+
93
+
94
+ def _model(model: ModelName) -> Model:
95
+ if isinstance(model, Model):
96
+ return model
97
+ name = str(model).strip().lower()
98
+ try:
99
+ return Model(_UPSTREAM_IDS.get(name, name))
100
+ except ValueError:
101
+ known = ", ".join(repr(known.value) for known in Model)
102
+ raise ValueError(f"unknown model {model!r}; use one of {known}") from None
103
+
104
+
105
+ def _precision(precision: str) -> str:
106
+ # checked before the driver check and any download, on every platform
107
+ if precision not in _PRECISIONS:
108
+ raise ValueError(f"unknown precision {precision!r}; use one of {', '.join(_PRECISIONS)}")
109
+ return precision
110
+
111
+
112
+ class Pipeline:
113
+ """A loaded Parakeet model.
114
+
115
+ Audio of any length works: a recording longer than one model window is split
116
+ into overlapping windows and the transcripts are merged. Calls on one
117
+ pipeline run one at a time.
118
+ """
119
+
120
+ def __init__(self, native: _native._Pipeline) -> None:
121
+ """Use :meth:`from_pretrained` or :meth:`from_dir` instead."""
122
+ self._native = native
123
+
124
+ @classmethod
125
+ def from_pretrained(
126
+ cls,
127
+ model: ModelName = Model.PARAKEET_V2,
128
+ *,
129
+ vad: bool = False,
130
+ precision: Precision = "fp16",
131
+ cache_dir: StrPath | None = None,
132
+ ) -> Pipeline:
133
+ """Download ``model`` from Hugging Face if needed, then load it.
134
+
135
+ The first call downloads the model, about 0.6 GB of Core ML models on
136
+ macOS or 2.5 GB of weights on Linux and Windows, into ``cache_dir`` when
137
+ given, else the Hugging Face hub cache that ``HF_HUB_CACHE`` or ``HF_HOME`` sets, else
138
+ ``~/.cache/huggingface/hub``; later calls load from the cache. Setting
139
+ ``SCRIPTRS_MODELS_DIR`` loads a local directory instead, as
140
+ :meth:`from_dir` does.
141
+ With ``vad``, the Silero VAD v5 and v6 models are downloaded too, and long
142
+ recordings are split at speech instead of at fixed intervals, which helps
143
+ when most of a recording is silence or noise. Each window counts as speech
144
+ when the higher of its v5 and v6 speech probabilities is at least 0.6.
145
+
146
+ Raises :class:`ScriptrsError` with code ``model_download`` when a
147
+ download fails, or ``cuda`` when Linux or Windows has no NVIDIA driver.
148
+ """
149
+ model = _model(model)
150
+ precision = _precision(precision)
151
+ _cuda.prepare()
152
+ cache = None if cache_dir is None else Path(cache_dir)
153
+ return cls(_native._from_pretrained(model.value, vad, precision, cache))
154
+
155
+ @classmethod
156
+ def from_dir(
157
+ cls,
158
+ path: StrPath,
159
+ model: ModelName = Model.PARAKEET_V2,
160
+ *,
161
+ vad: bool = False,
162
+ precision: Precision = "fp16",
163
+ ) -> Pipeline:
164
+ """Load ``model`` from a local directory instead of downloading it.
165
+
166
+ On macOS the directory holds Core ML models, and on Linux and Windows
167
+ native weights, in the layouts the scriptrs README describes.
168
+ """
169
+ model = _model(model)
170
+ precision = _precision(precision)
171
+ _cuda.prepare()
172
+ return cls(_native._from_dir(Path(path), model.value, vad, precision))
173
+
174
+ @property
175
+ def model(self) -> Model:
176
+ """The loaded model."""
177
+ return Model(self._native.model)
178
+
179
+ @property
180
+ def languages(self) -> list[str]:
181
+ """ISO 639-1 codes of the languages the loaded model transcribes."""
182
+ return self._native.languages
183
+
184
+ @property
185
+ def vad(self) -> bool:
186
+ """Whether long recordings are split at speech detected by VAD."""
187
+ return self._native.vad
188
+
189
+ @property
190
+ def max_chunk_seconds(self) -> float:
191
+ """Longest input transcribed as one window.
192
+
193
+ Longer audio still works through :meth:`transcribe`, which splits it into
194
+ windows of this length: 15 s on Core ML, and 30 s on CUDA, where the
195
+ model accepts 40 s but shorter windows are more accurate.
196
+ """
197
+ return self._native.max_chunk_seconds
198
+
199
+ def transcribe(self, samples: Samples, *, language: str | None = None) -> TranscriptionResult:
200
+ """Transcribe 16 kHz mono audio.
201
+
202
+ ``samples`` is a 1-D float32 buffer, such as a NumPy array, or a sequence
203
+ of floats; it is copied before the GIL is released. ``language`` is an
204
+ ISO 639-1 code from :attr:`languages`, such as ``"de"``; without it,
205
+ Parakeet v3 detects the language and v2 transcribes English.
206
+ """
207
+ return self._native.transcribe(samples, language)
208
+
209
+ def transcribe_file(self, path: StrPath, *, language: str | None = None) -> TranscriptionResult:
210
+ """Decode an audio file, resample it to 16 kHz mono, and transcribe it.
211
+
212
+ WAV, FLAC, MP3, Ogg Vorbis, and AAC in MP4/M4A are supported. The whole
213
+ file is decoded into memory.
214
+ """
215
+ return self._native.transcribe_file(Path(path), language)
216
+
217
+ def transcribe_many(
218
+ self,
219
+ inputs: Sequence[Samples],
220
+ *,
221
+ language: str | None = None,
222
+ max_batch: int = 32,
223
+ ) -> list[TranscriptionResult]:
224
+ """Transcribe many 16 kHz mono clips faster than calling :meth:`transcribe` in a loop.
225
+
226
+ Every clip goes through a scheduler that prepares the next windows while
227
+ the model runs. On CUDA it encodes up to ``max_batch`` (1 to 64) windows of
228
+ a similar length in one pass, from any of the clips, short or long, and
229
+ decodes them together. Each clip is transcribed as :meth:`transcribe`
230
+ would, though batching can change a rare token. Results keep input order.
231
+ If any clip fails, the whole call raises :class:`ScriptrsError` naming that
232
+ clip's index.
233
+ """
234
+ return self._native.transcribe_many(list(inputs), language, max_batch)
235
+
236
+ def __repr__(self) -> str:
237
+ return f"Pipeline(model={self.model.value!r}, backend={BACKEND!r}, vad={self.vad})"
238
+
239
+
240
+ __all__ = [
241
+ "ALL_LANGUAGES",
242
+ "BACKEND",
243
+ "Model",
244
+ "ModelName",
245
+ "Pipeline",
246
+ "Precision",
247
+ "ScriptrsError",
248
+ "TimedToken",
249
+ "TranscriptChunk",
250
+ "TranscriptionResult",
251
+ ]
scriptrs/_cuda.py ADDED
@@ -0,0 +1,97 @@
1
+ """Find the NVIDIA driver and make pip-installed cuBLAS visible to the CUDA backend.
2
+
3
+ The native CUDA backend opens the driver and cuBLAS at run time by name:
4
+ ``libcuda.so.1`` and ``libcublas.so.12`` on Linux, and ``nvcuda.dll`` and
5
+ ``cublas64_12.dll`` on Windows, then the CUDA 13 names. The
6
+ ``nvidia-cublas-cu12`` wheel installs cuBLAS inside site-packages, where neither
7
+ loader looks, so it is loaded here first. Both loaders reuse a library the
8
+ process already holds under the name they ask for: glibc matches the
9
+ ``libcublas.so.12`` lookup to the loaded copy's soname, and on Windows the
10
+ backend checks for a loaded module of that name before it searches. The wheel's
11
+ copy therefore wins over a CUDA toolkit's, which ships the same names.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import ctypes
17
+ import sys
18
+ import threading
19
+ from pathlib import Path
20
+
21
+ from ._errors import ScriptrsError
22
+ from ._native import BACKEND
23
+
24
+ _WINDOWS = sys.platform == "win32"
25
+ # the driver's library, which the NVIDIA driver installs on the loader's own path
26
+ DRIVER = "nvcuda.dll" if _WINDOWS else "libcuda.so.1"
27
+ # the library directory inside the wheel's ``nvidia`` namespace package, and its
28
+ # libraries with dependencies before dependents, since libcublas links against
29
+ # libcublasLt by name and each load finds what it links against already loaded
30
+ _CUBLAS: tuple[tuple[str, ...], tuple[str, ...]] = (
31
+ (("cublas", "bin"), ("cublasLt64_12.dll", "cublas64_12.dll"))
32
+ if _WINDOWS
33
+ else (("cublas", "lib"), ("libcublasLt.so.12", "libcublas.so.12"))
34
+ )
35
+ _prepared = False
36
+ # a second thread must wait for the first to finish loading, not skip ahead
37
+ _lock = threading.Lock()
38
+
39
+
40
+ def prepare() -> None:
41
+ """Check for the driver and load cuBLAS once, before the first model loads.
42
+
43
+ The driver check runs before any download, so a machine without an NVIDIA
44
+ GPU fails fast instead of after fetching a model it cannot run.
45
+ """
46
+ global _prepared
47
+ if BACKEND != "cuda":
48
+ return
49
+ with _lock:
50
+ if not _prepared:
51
+ _check_driver()
52
+ _load_cublas()
53
+ _prepared = True
54
+
55
+
56
+ def _driver_path() -> str:
57
+ """The driver to load: System32's copy on Windows, the loader's soname elsewhere."""
58
+ if sys.platform != "win32":
59
+ return DRIVER
60
+ # a full System32 path, as the backend loads the driver, since a bare name would
61
+ # also search the interpreter's directory for a planted nvcuda.dll
62
+ buffer = ctypes.create_unicode_buffer(260)
63
+ length = ctypes.windll.kernel32.GetSystemDirectoryW(buffer, len(buffer))
64
+ if not 0 < length < len(buffer):
65
+ raise OSError("could not find the System32 directory")
66
+ return str(Path(buffer.value) / DRIVER)
67
+
68
+
69
+ def _check_driver() -> None:
70
+ try:
71
+ ctypes.CDLL(_driver_path())
72
+ except OSError:
73
+ raise ScriptrsError(
74
+ "cuda",
75
+ f"no NVIDIA driver found ({DRIVER}); on Linux and Windows scriptrs runs on NVIDIA GPUs only",
76
+ ) from None
77
+
78
+
79
+ def _load_cublas() -> None:
80
+ try:
81
+ import nvidia # namespace package shared by the nvidia-* wheels
82
+ except ImportError:
83
+ return
84
+
85
+ subdir, names = _CUBLAS
86
+ for root in getattr(nvidia, "__path__", []):
87
+ lib_dir = Path(root).joinpath(*subdir)
88
+ for name in names:
89
+ path = lib_dir / name
90
+ if path.is_file():
91
+ try:
92
+ # Windows ignores the mode; an absolute path there also searches the
93
+ # DLL's own directory for its imports
94
+ ctypes.CDLL(str(path), mode=ctypes.RTLD_GLOBAL)
95
+ except OSError:
96
+ # a broken install falls back to the system search path
97
+ pass
scriptrs/_errors.py ADDED
@@ -0,0 +1,30 @@
1
+ """The exception type raised for scriptrs failures."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class ScriptrsError(Exception):
7
+ """A scriptrs operation failed; invalid arguments raise ``ValueError`` or ``TypeError`` instead.
8
+
9
+ ``code`` is one of the stable values below, so callers can branch on it
10
+ without parsing messages: ``configuration``, ``unsupported_language``,
11
+ ``unsupported_platform``, ``model_download``, ``missing_model``,
12
+ ``invalid_model``, ``empty_audio``, ``audio_too_long``, ``invalid_audio``,
13
+ ``audio_decode``, ``io``, ``cuda``, ``coreml``, ``scheduler``, ``transcription``.
14
+ """
15
+
16
+ def __init__(self, code: str, message: str) -> None:
17
+ super().__init__(code, message)
18
+
19
+ @property
20
+ def code(self) -> str:
21
+ """Stable failure code."""
22
+ return self.args[0]
23
+
24
+ @property
25
+ def message(self) -> str:
26
+ """Human-readable description."""
27
+ return self.args[1]
28
+
29
+ def __str__(self) -> str:
30
+ return f"{self.message} [{self.code}]"
scriptrs/_native.pyd ADDED
Binary file
scriptrs/_native.pyi ADDED
@@ -0,0 +1,80 @@
1
+ from collections.abc import Sequence
2
+ from pathlib import Path
3
+ from typing import Any, final
4
+
5
+ BACKEND: str | None
6
+ """Backend compiled into this build: ``"coreml"``, ``"cuda"``, or ``None``."""
7
+ ALL_LANGUAGES: list[str]
8
+ """ISO 639-1 codes of every language a model transcribes."""
9
+
10
+ def languages(model: str) -> list[str]: ...
11
+
12
+ @final
13
+ class TimedToken:
14
+ """One token with its timing and confidence."""
15
+
16
+ @property
17
+ def token_id(self) -> int:
18
+ """Token id in the model vocabulary."""
19
+ @property
20
+ def text(self) -> str:
21
+ """Token text, with a leading space where a word starts."""
22
+ @property
23
+ def start(self) -> float:
24
+ """Start time in seconds."""
25
+ @property
26
+ def end(self) -> float:
27
+ """End time in seconds."""
28
+ @property
29
+ def confidence(self) -> float:
30
+ """Model confidence between 0 and 1."""
31
+
32
+ @final
33
+ class TranscriptChunk:
34
+ """A timed span of the transcript."""
35
+
36
+ @property
37
+ def start(self) -> float:
38
+ """Start time in seconds."""
39
+ @property
40
+ def end(self) -> float:
41
+ """End time in seconds."""
42
+ @property
43
+ def text(self) -> str:
44
+ """Text of this span."""
45
+
46
+ @final
47
+ class TranscriptionResult:
48
+ """A finished transcription; ``str(result)`` is its text."""
49
+
50
+ @property
51
+ def text(self) -> str:
52
+ """Full transcript text."""
53
+ @property
54
+ def chunks(self) -> list[TranscriptChunk]:
55
+ """Timed spans of the transcript."""
56
+ @property
57
+ def tokens(self) -> list[TimedToken]:
58
+ """Every token with its timing and confidence."""
59
+ @property
60
+ def duration_seconds(self) -> float:
61
+ """Length of the input audio in seconds."""
62
+
63
+ @final
64
+ class _Pipeline:
65
+ @property
66
+ def model(self) -> str: ...
67
+ @property
68
+ def vad(self) -> bool: ...
69
+ @property
70
+ def languages(self) -> list[str]: ...
71
+ @property
72
+ def max_chunk_seconds(self) -> float: ...
73
+ def transcribe(self, samples: Any, language: str | None = None) -> TranscriptionResult: ...
74
+ def transcribe_file(self, path: Path, language: str | None = None) -> TranscriptionResult: ...
75
+ def transcribe_many(
76
+ self, inputs: Sequence[Any], language: str | None = None, max_batch: int = 32
77
+ ) -> list[TranscriptionResult]: ...
78
+
79
+ def _from_pretrained(model: str, vad: bool, precision: str, cache_dir: Path | None = None) -> _Pipeline: ...
80
+ def _from_dir(path: Path, model: str, vad: bool, precision: str) -> _Pipeline: ...
scriptrs/cli.py ADDED
@@ -0,0 +1,103 @@
1
+ """The ``scriptrs`` command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from collections.abc import Sequence
9
+ from pathlib import Path
10
+
11
+ from . import Model, Pipeline, ScriptrsError, TranscriptionResult, __version__
12
+
13
+
14
+ def main(argv: Sequence[str] | None = None) -> int:
15
+ """Run the command line and return the exit status."""
16
+ parser = argparse.ArgumentParser(prog="scriptrs", description="Speech-to-text with NVIDIA Parakeet TDT.")
17
+ parser.add_argument("--version", action="version", version=f"scriptrs {__version__}")
18
+ commands = parser.add_subparsers(dest="command", required=True)
19
+
20
+ transcribe = commands.add_parser(
21
+ "transcribe",
22
+ help="transcribe audio files",
23
+ description="Transcribe audio files and print each transcript to stdout. With several files, each transcript follows a ==> FILE <== header, as head does.",
24
+ )
25
+ transcribe.add_argument("audio", type=Path, nargs="+", help="audio files (WAV, FLAC, MP3, Ogg, M4A)")
26
+ transcribe.add_argument(
27
+ "--model",
28
+ default=Model.PARAKEET_V2.value,
29
+ help="parakeet/v2 (English, the default) or parakeet/v3 (25 European languages)",
30
+ )
31
+ transcribe.add_argument("--language", help="ISO 639-1 code such as en or de (default: detect)")
32
+ transcribe.add_argument(
33
+ "--vad",
34
+ action="store_true",
35
+ help="split long recordings at detected speech; helps when most of the audio is not speech",
36
+ )
37
+ transcribe.add_argument(
38
+ "--precision",
39
+ default="fp16",
40
+ choices=["fp16", "tf32", "fp32"],
41
+ help="CUDA matrix multiply precision (default: fp16)",
42
+ )
43
+ transcribe.add_argument(
44
+ "--model-dir", type=Path, help="load the model from this directory instead of downloading it"
45
+ )
46
+ transcribe.add_argument("--cache-dir", type=Path, help="model download cache (default: the Hugging Face hub cache)")
47
+ transcribe.add_argument(
48
+ "--json",
49
+ action="store_true",
50
+ help="print one JSON object per file, with timed chunks and tokens",
51
+ )
52
+ args = parser.parse_args(argv)
53
+
54
+ try:
55
+ if args.model_dir is not None:
56
+ pipeline = Pipeline.from_dir(args.model_dir, args.model, vad=args.vad, precision=args.precision)
57
+ else:
58
+ pipeline = Pipeline.from_pretrained(
59
+ args.model, vad=args.vad, precision=args.precision, cache_dir=args.cache_dir
60
+ )
61
+ # a single transcript stays bare so it pipes cleanly; several get headers
62
+ # the way head and tail label several files
63
+ headers = not args.json and len(args.audio) > 1
64
+ for index, path in enumerate(args.audio):
65
+ result = pipeline.transcribe_file(path, language=args.language)
66
+ if args.json:
67
+ print(json.dumps(_as_json(path, result), ensure_ascii=False))
68
+ continue
69
+
70
+ if headers:
71
+ if index:
72
+ print()
73
+ print(f"==> {path} <==")
74
+ print(result.text, flush=True)
75
+ except (ScriptrsError, ValueError) as error:
76
+ print(f"error: {getattr(error, 'message', error)}", file=sys.stderr)
77
+ return 1
78
+ except KeyboardInterrupt:
79
+ return 130
80
+
81
+ return 0
82
+
83
+
84
+ def _as_json(path: Path, result: TranscriptionResult) -> dict[str, object]:
85
+ return {
86
+ "file": str(path),
87
+ "text": result.text,
88
+ "duration_seconds": result.duration_seconds,
89
+ "chunks": [{"start": chunk.start, "end": chunk.end, "text": chunk.text} for chunk in result.chunks],
90
+ "tokens": [
91
+ {
92
+ "text": token.text,
93
+ "start": token.start,
94
+ "end": token.end,
95
+ "confidence": token.confidence,
96
+ }
97
+ for token in result.tokens
98
+ ],
99
+ }
100
+
101
+
102
+ if __name__ == "__main__":
103
+ raise SystemExit(main())
scriptrs/py.typed ADDED
File without changes