transcribe-cpp 0.4.2__tar.gz → 0.5.1__tar.gz

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.
Files changed (37) hide show
  1. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/PKG-INFO +26 -3
  2. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/README.md +23 -0
  3. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/_generate/check_version_sync.py +28 -7
  4. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/pyproject.toml +3 -3
  5. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/src/transcribe_cpp/__init__.py +234 -14
  6. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/src/transcribe_cpp/_generated.py +60 -1
  7. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/conftest.py +30 -0
  8. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_compute_lock.py +134 -2
  9. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_streaming.py +12 -0
  10. transcribe_cpp-0.5.1/tests/test_turn.py +267 -0
  11. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/uv.lock +261 -259
  12. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/.gitignore +0 -0
  13. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/LICENSE +0 -0
  14. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/_generate/README.md +0 -0
  15. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/_generate/generate.py +0 -0
  16. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/examples/stream_wav.py +0 -0
  17. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/examples/transcribe_wav.py +0 -0
  18. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/src/transcribe_cpp/_abi.py +0 -0
  19. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/src/transcribe_cpp/_library.py +0 -0
  20. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/src/transcribe_cpp/errors.py +0 -0
  21. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/src/transcribe_cpp/py.typed +0 -0
  22. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_abi.py +0 -0
  23. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_backends.py +0 -0
  24. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_device_select.py +0 -0
  25. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_diarize.py +0 -0
  26. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_errors.py +0 -0
  27. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_example.py +0 -0
  28. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_family_ext.py +0 -0
  29. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_langid.py +0 -0
  30. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_lifetime.py +0 -0
  31. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_pcm.py +0 -0
  32. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_prompting.py +0 -0
  33. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_provider_discovery.py +0 -0
  34. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_text_controls.py +0 -0
  35. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_transcribe.py +0 -0
  36. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_utf8_paths.py +0 -0
  37. {transcribe_cpp-0.4.2 → transcribe_cpp-0.5.1}/tests/test_vad.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: transcribe-cpp
3
- Version: 0.4.2
3
+ Version: 0.5.1
4
4
  Summary: Python bindings for transcribe.cpp
5
5
  Project-URL: Homepage, https://github.com/handy-computer/transcribe.cpp
6
6
  Project-URL: Repository, https://github.com/handy-computer/transcribe.cpp
@@ -21,9 +21,9 @@ Classifier: Programming Language :: Python :: 3.13
21
21
  Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
22
22
  Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
23
  Requires-Python: >=3.9
24
- Requires-Dist: transcribe-cpp-native==0.4.2.*
24
+ Requires-Dist: transcribe-cpp-native==0.5.1.*
25
25
  Provides-Extra: cu12
26
- Requires-Dist: transcribe-cpp-native-cu12==0.4.2.*; extra == 'cu12'
26
+ Requires-Dist: transcribe-cpp-native-cu12==0.5.1.*; extra == 'cu12'
27
27
  Provides-Extra: test
28
28
  Requires-Dist: numpy; extra == 'test'
29
29
  Requires-Dist: pytest>=7; extra == 'test'
@@ -167,6 +167,29 @@ with model.vad_session() as vad:
167
167
  probs.extend(vad.stream_flush().probs)
168
168
  ```
169
169
 
170
+ ### End-of-turn detection
171
+
172
+ Models whose `model.roles` include `Role.TURN` (Smart Turn v3.2, SAVA) score
173
+ whether the speaker has finished talking through a turn session. `run()`
174
+ scores one clip and returns a `TurnResult` with `p` and `ended`
175
+ (`p >= threshold`; `threshold=` overrides `model.turn_info.threshold`). On a
176
+ streaming model (`model.turn_info.frame_samples > 0`, e.g. SAVA)
177
+ `stream_feed()` returns a turn probability per completed frame (`probs`, from
178
+ `first_frame`) and a speech probability per judged frame (`speech_probs`, from
179
+ `speech_first_frame`; these may trail); `stream_flush()` and `stream_reset()`
180
+ work as for VAD. A clip-only model raises `NotImplementedByModel`.
181
+ `TurnSession.stream_feed_batch([(session, pcm), ...])` feeds many sessions of
182
+ one model in one compute call, each ending as after its own `stream_feed()`.
183
+ Like the VAD stream, a turn stream does not take the ASR stream lease.
184
+
185
+ ```python
186
+ with model.turn_session() as turn:
187
+ if turn.run(turn_pcm).ended: # the audio since the user started talking
188
+ answer()
189
+
190
+ results = transcribe_cpp.TurnSession.stream_feed_batch(list(zip(sessions, chunks)))
191
+ ```
192
+
170
193
  ## Backends
171
194
 
172
195
  `Model(backend=...)` applies a backend policy (`"auto"` uses the best
@@ -136,6 +136,29 @@ with model.vad_session() as vad:
136
136
  probs.extend(vad.stream_flush().probs)
137
137
  ```
138
138
 
139
+ ### End-of-turn detection
140
+
141
+ Models whose `model.roles` include `Role.TURN` (Smart Turn v3.2, SAVA) score
142
+ whether the speaker has finished talking through a turn session. `run()`
143
+ scores one clip and returns a `TurnResult` with `p` and `ended`
144
+ (`p >= threshold`; `threshold=` overrides `model.turn_info.threshold`). On a
145
+ streaming model (`model.turn_info.frame_samples > 0`, e.g. SAVA)
146
+ `stream_feed()` returns a turn probability per completed frame (`probs`, from
147
+ `first_frame`) and a speech probability per judged frame (`speech_probs`, from
148
+ `speech_first_frame`; these may trail); `stream_flush()` and `stream_reset()`
149
+ work as for VAD. A clip-only model raises `NotImplementedByModel`.
150
+ `TurnSession.stream_feed_batch([(session, pcm), ...])` feeds many sessions of
151
+ one model in one compute call, each ending as after its own `stream_feed()`.
152
+ Like the VAD stream, a turn stream does not take the ASR stream lease.
153
+
154
+ ```python
155
+ with model.turn_session() as turn:
156
+ if turn.run(turn_pcm).ended: # the audio since the user started talking
157
+ answer()
158
+
159
+ results = transcribe_cpp.TurnSession.stream_feed_batch(list(zip(sessions, chunks)))
160
+ ```
161
+
139
162
  ## Backends
140
163
 
141
164
  `Model(backend=...)` applies a backend policy (`"auto"` uses the best
@@ -10,9 +10,9 @@ against the *loaded* library at runtime; this script is the static, build-time
10
10
  counterpart so a forgotten bump fails CI before anything is published.
11
11
 
12
12
  This covers every §1b spot in ``notes/releasing.md`` — including the ones that
13
- used to be §1c blind spots: the ``transcribe-cpp-sys`` dependency *pin*, both
14
- ``Cargo.lock`` entries, both ``package-lock.json`` spots, and Swift
15
- ``compiledVersion``. (Lockfile *internal* consistency — a stale lock silently
13
+ used to be §1c blind spots: the ``transcribe-cpp-sys`` and (exact)
14
+ ``transcribe-cpp-types`` dependency *pins*, the three ``Cargo.lock`` entries,
15
+ both ``package-lock.json`` spots, and Swift ``compiledVersion``. (Lockfile *internal* consistency — a stale lock silently
16
16
  rewritten by an unlocked command — is still the job of the locked-command
17
17
  checks, ``cargo metadata --locked`` / ``npm ci``, run in release-preflight.)
18
18
 
@@ -39,6 +39,7 @@ PYPROJECT = REPO / "bindings" / "python" / "pyproject.toml"
39
39
  INIT = REPO / "bindings" / "python" / "src" / "transcribe_cpp" / "__init__.py"
40
40
  TS_PACKAGE_JSON = REPO / "bindings" / "typescript" / "package.json"
41
41
  RUST_SAFE_CARGO = REPO / "bindings" / "rust" / "transcribe-cpp" / "Cargo.toml"
42
+ RUST_TYPES_CARGO = REPO / "bindings" / "rust" / "transcribe-cpp-types" / "Cargo.toml"
42
43
  CARGO_LOCK = REPO / "Cargo.lock"
43
44
  PACKAGE_LOCK = REPO / "bindings" / "typescript" / "package-lock.json"
44
45
  SWIFT_SOURCE = REPO / "bindings" / "swift" / "Sources" / "TranscribeCpp" / "TranscribeCpp.swift"
@@ -55,9 +56,11 @@ BINDING_MANIFESTS = [
55
56
  # The Rust crates are real (0.0.1), so they're version-locked. The sys
56
57
  # crate's manifest is the repo-root Cargo.toml (it carries the whole C++
57
58
  # tree); the safe wrapper is the sibling member at
58
- # bindings/rust/transcribe-cpp/.
59
+ # bindings/rust/transcribe-cpp/, and its pure-Rust plain-data types crate
60
+ # at bindings/rust/transcribe-cpp-types/ (released in lockstep).
59
61
  ("Cargo.toml", "cargo", True),
60
62
  ("bindings/rust/transcribe-cpp/Cargo.toml", "cargo", True),
63
+ ("bindings/rust/transcribe-cpp-types/Cargo.toml", "cargo", True),
61
64
  ("bindings/typescript/package.json", "npm", True),
62
65
  ]
63
66
 
@@ -143,13 +146,28 @@ def cargo_sys_pin(text: str) -> str | None:
143
146
  return m.group(1) if m else None
144
147
 
145
148
 
149
+ def cargo_types_pin(text: str) -> str | None:
150
+ # The safe crate's dependency pin on the types crate. It must be EXACT
151
+ # (`=X.Y.Z`): transcribe-cpp's conversions of the types crate's
152
+ # #[non_exhaustive] enums are only complete for the lockstep version. A
153
+ # non-exact pin is reported as unlocatable (None), a hard error.
154
+ # transcribe-cpp-types = { version = "=X.Y.Z", path = "../transcribe-cpp-types" }
155
+ m = re.search(
156
+ r'transcribe-cpp-types\s*=\s*\{[^}]*?\bversion\s*=\s*"([^"]+)"', text
157
+ )
158
+ if not m:
159
+ return None
160
+ pin = m.group(1)
161
+ return pin[1:] if pin.startswith("=") and not pin.startswith("==") else None
162
+
163
+
146
164
  def cargo_lock_versions(text: str) -> "dict[str, str | None]":
147
- # The two workspace crates pinned in Cargo.lock. cargo writes name then
165
+ # The three workspace crates pinned in Cargo.lock. cargo writes name then
148
166
  # version on consecutive lines within each [[package]] block; the closing
149
167
  # quote in the name match keeps "transcribe-cpp" from also matching
150
- # "transcribe-cpp-sys".
168
+ # "transcribe-cpp-sys" / "transcribe-cpp-types".
151
169
  out: dict[str, str | None] = {}
152
- for name in ("transcribe-cpp", "transcribe-cpp-sys"):
170
+ for name in ("transcribe-cpp", "transcribe-cpp-sys", "transcribe-cpp-types"):
153
171
  m = re.search(rf'name = "{re.escape(name)}"\nversion = "([^"]+)"', text)
154
172
  out[f"Cargo.lock ({name})"] = m.group(1) if m else None
155
173
  return out
@@ -193,6 +211,9 @@ def main() -> int:
193
211
  sources["Cargo.toml (sys dep pin)"] = (
194
212
  cargo_sys_pin(RUST_SAFE_CARGO.read_text()) if RUST_SAFE_CARGO.exists() else None
195
213
  )
214
+ sources["Cargo.toml (types dep pin, exact)"] = (
215
+ cargo_types_pin(RUST_SAFE_CARGO.read_text()) if RUST_SAFE_CARGO.exists() else None
216
+ )
196
217
  if CARGO_LOCK.exists():
197
218
  sources.update(cargo_lock_versions(CARGO_LOCK.read_text()))
198
219
  else:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "transcribe-cpp"
7
- version = "0.4.2"
7
+ version = "0.5.1"
8
8
  description = "Python bindings for transcribe.cpp"
9
9
  readme = "README.md"
10
10
  # 3.8 is EOL (2024-10); 3.9 is the floor. The binding is ctypes-only, so there
@@ -34,13 +34,13 @@ classifiers = [
34
34
  # packaging fix still resolves); the import-time version/header-hash check in
35
35
  # _library.py is the runtime backstop. check_version_sync.py gates this pin
36
36
  # against include/transcribe.h.
37
- dependencies = ["transcribe-cpp-native==0.4.2.*"]
37
+ dependencies = ["transcribe-cpp-native==0.5.1.*"]
38
38
 
39
39
  [project.optional-dependencies]
40
40
  # Opt-in accelerator providers — ADDITIVE: they install alongside the default
41
41
  # provider and the best one wins at runtime. Same base-version pin contract
42
42
  # as the hard dependency (gated by check_version_sync.py).
43
- cu12 = ["transcribe-cpp-native-cu12==0.4.2.*"]
43
+ cu12 = ["transcribe-cpp-native-cu12==0.5.1.*"]
44
44
  # Test-only deps. Run with: uv run --extra test pytest (from bindings/python).
45
45
  # numpy is here so the numpy PCM-input tests run in every lane instead of
46
46
  # silently skipping wherever numpy happens to be absent.
@@ -55,7 +55,7 @@ from .errors import (
55
55
  raise_for_status,
56
56
  )
57
57
 
58
- __version__ = "0.4.2"
58
+ __version__ = "0.5.1"
59
59
 
60
60
  # String-enum types, exported so callers (and type checkers) can name them.
61
61
  Backend = Literal["auto", "cpu", "metal", "vulkan", "cpu_accel", "cuda", "rocm"]
@@ -88,6 +88,9 @@ __all__ = [
88
88
  "VadInfo",
89
89
  "VadResult",
90
90
  "VadSegment",
91
+ "TurnSession",
92
+ "TurnInfo",
93
+ "TurnResult",
91
94
  "Role",
92
95
  "Result",
93
96
  "Segment",
@@ -205,6 +208,7 @@ _LangIdCandidate = _generated.transcribe_langid_candidate
205
208
  _LangIdResult = _generated.transcribe_langid_result
206
209
  _VadResult = _generated.transcribe_vad_result
207
210
  _VadSegment = _generated.transcribe_vad_segment
211
+ _TurnResult = _generated.transcribe_turn_result
208
212
  _Word = _generated.transcribe_word
209
213
  _Token = _generated.transcribe_token
210
214
  _StreamParams = _generated.transcribe_stream_params
@@ -578,12 +582,14 @@ class Capabilities:
578
582
  class Role(enum.Enum):
579
583
  """What a model serves (``Model.roles``): ASR is ``Model.session()``,
580
584
  DIARIZE is ``Model.diarize_session()``, LANGID is
581
- ``Model.langid_session()``, VAD is ``Model.vad_session()``."""
585
+ ``Model.langid_session()``, VAD is ``Model.vad_session()``, TURN is
586
+ ``Model.turn_session()``."""
582
587
 
583
588
  ASR = _generated.TRANSCRIBE_ROLE_ASR
584
589
  DIARIZE = _generated.TRANSCRIBE_ROLE_DIARIZE
585
590
  LANGID = _generated.TRANSCRIBE_ROLE_LANGID
586
591
  VAD = _generated.TRANSCRIBE_ROLE_VAD
592
+ TURN = _generated.TRANSCRIBE_ROLE_TURN
587
593
 
588
594
 
589
595
  @dataclass(frozen=True)
@@ -655,6 +661,36 @@ class VadResult:
655
661
  segments: tuple[VadSegment, ...]
656
662
 
657
663
 
664
+ @dataclass(frozen=True)
665
+ class TurnInfo:
666
+ sample_rate: int
667
+ max_audio_ms: int # run() scores the last max_audio_ms of longer input; 0 = no limit
668
+ frame_samples: int # samples per streamed frame; 0 = clip only (no stream)
669
+ has_speech: bool # the model also scores speech per frame
670
+ threshold: float # the model's default cut-off for ``ended``
671
+
672
+
673
+ @dataclass(frozen=True)
674
+ class TurnResult:
675
+ """The last run, feed or flush. After ``run()``: ``p`` is the probability
676
+ that the turn has ended at the end of the clip and ``ended`` is
677
+ ``p >= threshold``; after a feed or flush they are 0.0 and False.
678
+
679
+ ``probs[i]`` is the turn probability at the end of frame
680
+ ``first_frame + i`` (streaming models only; ``run()`` fills every frame of
681
+ the clip). ``speech_probs[i]`` is the speech probability of frame
682
+ ``speech_first_frame + i`` (``has_speech`` models only); during a stream
683
+ it may trail the turn probabilities. Frame ``f`` starts at sample
684
+ ``f * frame_samples``; both counters are 0 after ``run()``."""
685
+
686
+ p: float
687
+ ended: bool
688
+ probs: tuple[float, ...]
689
+ first_frame: int
690
+ speech_probs: tuple[float, ...]
691
+ speech_first_frame: int
692
+
693
+
658
694
  @dataclass(frozen=True)
659
695
  class SessionLimits:
660
696
  """Effective per-session limits (model bound narrowed by session params).
@@ -1037,18 +1073,19 @@ class Model:
1037
1073
  The native library allows one compute call in flight across ALL sessions
1038
1074
  of a model, so ``Session.run()`` / ``run_batch()`` / ``stream()``,
1039
1075
  ``Stream.feed()`` / ``finalize()`` / ``reset()``, ``DiarizeSession.run()``,
1040
- ``LangIdSession.run()`` and ``VadSession.run()`` / ``stream_feed()`` /
1041
- ``stream_flush()`` / ``stream_reset()`` hold a model-wide lock for the
1076
+ ``LangIdSession.run()``, ``VadSession.run()`` / ``stream_feed()`` /
1077
+ ``stream_flush()`` / ``stream_reset()`` and the same ``TurnSession`` calls
1078
+ plus ``TurnSession.stream_feed_batch()`` hold a model-wide lock for the
1042
1079
  native call and its copy-out. Calls from other threads wait; a
1043
1080
  ``cancel()`` on a queued call is kept, and it aborts at its first poll
1044
1081
  after acquiring the lock. Load one Model per worker for parallelism. An
1045
1082
  active stream holds the model's stream lease from ``stream()`` until it is
1046
1083
  finalized, reset, fails, is garbage-collected or its session/model is
1047
1084
  closed. Meanwhile ``run()``, ``run_batch()``, ``stream()``, diarize and
1048
- langid ``run()`` and VAD ``run()`` / ``stream_feed()`` /
1085
+ langid ``run()`` and VAD / turn ``run()`` / ``stream_feed()`` /
1049
1086
  ``stream_flush()`` on any session raise :class:`Busy` once they hold the
1050
- lock; the stream's own calls proceed. A VAD stream is session state, not
1051
- a lease.
1087
+ lock; the stream's own calls proceed. A VAD or turn stream is session
1088
+ state, not a lease.
1052
1089
  ``close()`` and GC never wait for the lock: the handle is closed at once
1053
1090
  and the native free runs right after any in-flight call.
1054
1091
 
@@ -1370,6 +1407,23 @@ class Model:
1370
1407
  """Raises :class:`UnsupportedRole` without the VAD role."""
1371
1408
  return VadSession(self, n_threads=n_threads)
1372
1409
 
1410
+ @property
1411
+ def turn_info(self) -> TurnInfo:
1412
+ """Raises :class:`UnsupportedRole` without the TURN role."""
1413
+ info = _generated.transcribe_turn_info()
1414
+ _lib.transcribe_turn_info_init(_byref(info))
1415
+ _check(_lib.transcribe_turn_get_info(self._h, _byref(info)),
1416
+ "reading turn info")
1417
+ return TurnInfo(sample_rate=info.sample_rate,
1418
+ max_audio_ms=info.max_audio_ms,
1419
+ frame_samples=info.frame_samples,
1420
+ has_speech=bool(info.has_speech),
1421
+ threshold=info.threshold)
1422
+
1423
+ def turn_session(self, *, n_threads: int = 0) -> "TurnSession":
1424
+ """Raises :class:`UnsupportedRole` without the TURN role."""
1425
+ return TurnSession(self, n_threads=n_threads)
1426
+
1373
1427
  def close(self) -> None:
1374
1428
  """Free the model. Any session still open on it is closed first —
1375
1429
  the C contract forbids freeing a model before its sessions, so this
@@ -1410,8 +1464,8 @@ _S = TypeVar("_S", bound="_SessionBase")
1410
1464
 
1411
1465
  class _SessionBase:
1412
1466
  """Handle, cancellation and close plumbing shared by Session,
1413
- DiarizeSession, LangIdSession and VadSession. Subclasses name their
1414
- native free in ``_free_fn``."""
1467
+ DiarizeSession, LangIdSession, VadSession and TurnSession. Subclasses
1468
+ name their native free in ``_free_fn``."""
1415
1469
 
1416
1470
  _free_fn = ""
1417
1471
 
@@ -1463,8 +1517,9 @@ class _SessionBase:
1463
1517
  """Request cancellation of an in-flight call from another thread: it
1464
1518
  aborts at the next chunk/decode boundary and raises ``Aborted`` (with
1465
1519
  ``partial_result`` where available). The flag is cleared when the next
1466
- run / run_batch / stream / diarize or langid run / VAD run, stream_feed
1467
- or stream_flush starts, before it waits for the lock, so a cancel()
1520
+ run / run_batch / stream / diarize or langid run / VAD or turn run,
1521
+ stream_feed or stream_flush (or a turn stream_feed_batch listing this
1522
+ session) starts, before it waits for the lock, so a cancel()
1468
1523
  while queued still aborts it. Lock-free."""
1469
1524
  self._cancel.set()
1470
1525
 
@@ -2115,8 +2170,8 @@ class LangIdSession(_SessionBase):
2115
2170
  return _timings_from(tm)
2116
2171
 
2117
2172
 
2118
- def _vad_option(name: str, value, integer: bool):
2119
- """Check a VAD run option before ctypes would wrap or reject it."""
2173
+ def _check_option(name: str, value, integer: bool):
2174
+ """Check a VAD or TURN option before ctypes would wrap or reject it."""
2120
2175
  if integer:
2121
2176
  if (isinstance(value, bool) or not isinstance(value, numbers.Integral)
2122
2177
  or not -2**31 <= value <= _INT_MAX):
@@ -2208,7 +2263,7 @@ class VadSession(_SessionBase):
2208
2263
  ("speech_pad_ms", speech_pad_ms, True),
2209
2264
  ("max_speech_ms", max_speech_ms, True)):
2210
2265
  if value is not None:
2211
- setattr(params, name, _vad_option(name, value, integer))
2266
+ setattr(params, name, _check_option(name, value, integer))
2212
2267
  with self._model._exclusive(
2213
2268
  "vad_run", busy="a stream is active on this model; "
2214
2269
  "finish or drop it before vad run()"):
@@ -2263,6 +2318,171 @@ class VadSession(_SessionBase):
2263
2318
  return _timings_from(tm)
2264
2319
 
2265
2320
 
2321
+ _TURN_BUSY = "a stream is active on this model; finish or drop it before turn {}()"
2322
+
2323
+
2324
+ class TurnSession(_SessionBase):
2325
+ """An end-of-turn detection context on a model with the TURN role.
2326
+ Compute locking and ``Busy`` rules: see ``Model``.
2327
+
2328
+ ``run()`` scores one clip: has the turn ended at its end?
2329
+ ``stream_feed()`` / ``stream_flush()`` / ``stream_reset()`` drive this
2330
+ session's own frame stream on models with ``TurnInfo.frame_samples > 0``
2331
+ (others raise :class:`NotImplementedByModel`); like a VAD stream it does
2332
+ not take the model's stream lease."""
2333
+
2334
+ _free_fn = "transcribe_turn_session_free"
2335
+
2336
+ def __init__(self, model: Model, *, n_threads: int = 0):
2337
+ self._model = model # keep the model alive for the session's lifetime
2338
+ params = _generated.transcribe_turn_session_params()
2339
+ _lib.transcribe_turn_session_params_init(_byref(params))
2340
+ params.n_threads = n_threads
2341
+
2342
+ handle = ctypes.c_void_p()
2343
+ _check(_lib.transcribe_turn_session_init(model._h, _byref(params), _byref(handle)),
2344
+ "opening turn session")
2345
+ if not handle.value:
2346
+ raise TranscribeError("turn session init returned a null handle")
2347
+ self._handle = handle
2348
+ self._arm_abort(_lib.transcribe_turn_set_abort_callback)
2349
+
2350
+ @staticmethod
2351
+ def _copy_result(h) -> TurnResult:
2352
+ """Copy the last call's result out. Caller holds the compute lock:
2353
+ the buffers are session-owned and replaced by the next call."""
2354
+ res = _TurnResult()
2355
+ _lib.transcribe_turn_result_init(_byref(res))
2356
+ _check(_lib.transcribe_turn_get_result(h, _byref(res)),
2357
+ "transcribe_turn_get_result")
2358
+
2359
+ def floats(n: int, getter, what: str) -> tuple[float, ...]:
2360
+ if n <= 0:
2361
+ return ()
2362
+ ptr = getter(h)
2363
+ if not ptr:
2364
+ raise TranscribeError(f"turn result has {what} but no buffer")
2365
+ return tuple(ptr[:n])
2366
+
2367
+ return TurnResult(
2368
+ p=res.p, ended=bool(res.ended),
2369
+ probs=floats(res.n_probs, _lib.transcribe_turn_probs, "probabilities"),
2370
+ first_frame=res.first_frame,
2371
+ speech_probs=floats(res.n_speech_probs, _lib.transcribe_turn_speech_probs,
2372
+ "speech probabilities"),
2373
+ speech_first_frame=res.speech_first_frame)
2374
+
2375
+ def run(self, pcm: PCMLike, *, threshold: float | None = None) -> TurnResult:
2376
+ """Score one clip (16 kHz mono float32 PCM of the current turn, from
2377
+ where the speaker started) from a fresh state; ends any stream in
2378
+ progress. Input longer than ``TurnInfo.max_audio_ms`` is scored on its
2379
+ tail. ``threshold`` (cut-off for ``ended``): None or negative is the
2380
+ model's ``TurnInfo.threshold``, otherwise in [0, 1].
2381
+
2382
+ Raises :class:`InvalidArgument` for an out-of-range threshold,
2383
+ :class:`Aborted` after :meth:`cancel`, and :class:`Busy` if a stream
2384
+ is active on this model."""
2385
+ self._cancel.clear() # before the lock wait, as in Session.run()
2386
+ array, n_samples = _pcm_to_carray(pcm)
2387
+ params = _generated.transcribe_turn_params()
2388
+ _lib.transcribe_turn_params_init(_byref(params))
2389
+ if threshold is not None:
2390
+ params.threshold = _check_option("threshold", threshold, False)
2391
+ with self._model._exclusive("turn_run", busy=_TURN_BUSY.format("run")):
2392
+ h = self._h # captured under the lock; close() defers its free
2393
+ _check(_lib.transcribe_turn_run(h, array, n_samples, _byref(params)),
2394
+ "transcribe_turn_run")
2395
+ return self._copy_result(h)
2396
+
2397
+ def stream_feed(self, pcm: PCMLike) -> TurnResult:
2398
+ """Append audio (possibly empty) to the stream and return the turn
2399
+ probabilities of the frames it completed and the speech probabilities
2400
+ of the frames the model judged; a partial frame waits for the next
2401
+ feed. After :meth:`stream_reset`, :meth:`stream_flush` or :meth:`run`
2402
+ the next feed starts at frame 0. Rejected input leaves the stream
2403
+ unchanged; an abort or processing error resets it. Raises
2404
+ :class:`NotImplementedByModel` on a model that cannot stream, else
2405
+ like :meth:`run`."""
2406
+ self._cancel.clear()
2407
+ array, n_samples = _pcm_to_carray(pcm, allow_empty=True)
2408
+ with self._model._exclusive("turn_feed", busy=_TURN_BUSY.format("stream_feed")):
2409
+ h = self._h
2410
+ _check(_lib.transcribe_turn_stream_feed(h, array, n_samples),
2411
+ "transcribe_turn_stream_feed")
2412
+ return self._copy_result(h)
2413
+
2414
+ @staticmethod
2415
+ def stream_feed_batch(
2416
+ feeds: "Sequence[tuple[TurnSession, PCMLike]]") -> list[TurnResult]:
2417
+ """Feed several streams of ONE model in one compute call, much faster
2418
+ than one :meth:`stream_feed` per session. ``feeds`` is a non-empty
2419
+ list of ``(session, pcm)`` pairs, each session of the same model and
2420
+ listed once (:class:`InvalidArgument` otherwise); each ends as after
2421
+ ``session.stream_feed(pcm)``, and the results are in ``feeds`` order.
2422
+ Uses the first session's thread count and aborts if any listed
2423
+ session is cancelled. Rejected input leaves every stream unchanged;
2424
+ an abort or processing error resets every listed stream. A closed
2425
+ session (also one closed while the batch waits for the lock) raises
2426
+ :class:`TranscribeError`; otherwise raises like :meth:`stream_feed`."""
2427
+ feeds = list(feeds)
2428
+ if not feeds:
2429
+ raise InvalidArgument("stream_feed_batch needs at least one (session, pcm) pair")
2430
+ sessions: list[TurnSession] = []
2431
+ arrays = [] # the c_float arrays stay referenced here until the call returns
2432
+ for i, pair in enumerate(feeds):
2433
+ try:
2434
+ session, pcm = pair
2435
+ except (TypeError, ValueError):
2436
+ session = None
2437
+ if not isinstance(session, TurnSession):
2438
+ raise InvalidArgument(f"feeds[{i}] must be a (TurnSession, pcm) pair")
2439
+ # One model, one compute lock (the library rejects repeats).
2440
+ if session._model is not feeds[0][0]._model:
2441
+ raise InvalidArgument(f"feeds[{i}] session belongs to a different model")
2442
+ sessions.append(session)
2443
+ arrays.append(_pcm_to_carray(pcm, allow_empty=True))
2444
+ for session in sessions: # before the lock wait, as in stream_feed()
2445
+ session._cancel.clear()
2446
+ n = len(sessions)
2447
+ with sessions[0]._model._exclusive("turn_feed_batch",
2448
+ busy=_TURN_BUSY.format("stream_feed_batch")):
2449
+ handles = [s._h for s in sessions] # raises if any is closed
2450
+ c_sessions = (ctypes.c_void_p * n)(*(h.value for h in handles))
2451
+ c_pcm = (ctypes.POINTER(ctypes.c_float) * n)(
2452
+ *(ctypes.cast(a, ctypes.POINTER(ctypes.c_float)) for a, _ in arrays))
2453
+ c_n = (ctypes.c_int * n)(*(k for _, k in arrays))
2454
+ _check(_lib.transcribe_turn_stream_feed_batch(c_sessions, c_pcm, c_n, n),
2455
+ "transcribe_turn_stream_feed_batch")
2456
+ return [TurnSession._copy_result(h) for h in handles]
2457
+
2458
+ def stream_flush(self) -> TurnResult:
2459
+ """End the stream: score the buffered partial frame zero padded (one
2460
+ turn probability, or none) and return the speech probabilities of
2461
+ every frame not yet judged. The next feed starts at frame 0. Raises
2462
+ like :meth:`stream_feed`."""
2463
+ self._cancel.clear()
2464
+ with self._model._exclusive("turn_flush", busy=_TURN_BUSY.format("stream_flush")):
2465
+ h = self._h
2466
+ _check(_lib.transcribe_turn_stream_flush(h), "transcribe_turn_stream_flush")
2467
+ return self._copy_result(h)
2468
+
2469
+ def stream_reset(self) -> None:
2470
+ """Drop the stream without scoring; keeps the last result. Never
2471
+ raises ``Busy``."""
2472
+ with self._model._exclusive("turn_reset"):
2473
+ _lib.transcribe_turn_stream_reset(self._h)
2474
+
2475
+ @property
2476
+ def timings(self) -> Timings:
2477
+ """Load time plus the last call's mel (Smart Turn's log-mel; else 0)
2478
+ and encode time. Not locked, like ``Session.limits``."""
2479
+ tm = _Timings()
2480
+ _lib.transcribe_timings_init(_byref(tm))
2481
+ _check(_lib.transcribe_turn_get_timings(self._h, _byref(tm)),
2482
+ "transcribe_turn_get_timings")
2483
+ return _timings_from(tm)
2484
+
2485
+
2266
2486
  def transcribe(
2267
2487
  model: Model | str | os.PathLike,
2268
2488
  pcm: PCMLike,
@@ -13,7 +13,7 @@ import ctypes as _c
13
13
  # Stable digest of the ABI surface below (structs, enums, macros, layout,
14
14
  # prototypes). A native provider package echoes this back so the API
15
15
  # package can reject an ABI-mismatched provider before dlopen.
16
- PUBLIC_HEADER_HASH = "f99ad4169374b8f3"
16
+ PUBLIC_HEADER_HASH = "4393f89c866cc70d"
17
17
 
18
18
  # === enum constants ===
19
19
  TRANSCRIBE_OK = 0
@@ -67,6 +67,10 @@ TRANSCRIBE_ABI_VAD_SESSION_PARAMS = 25
67
67
  TRANSCRIBE_ABI_VAD_PARAMS = 26
68
68
  TRANSCRIBE_ABI_VAD_RESULT = 27
69
69
  TRANSCRIBE_ABI_VAD_SEGMENT = 28
70
+ TRANSCRIBE_ABI_TURN_INFO = 29
71
+ TRANSCRIBE_ABI_TURN_SESSION_PARAMS = 30
72
+ TRANSCRIBE_ABI_TURN_PARAMS = 31
73
+ TRANSCRIBE_ABI_TURN_RESULT = 32
70
74
  TRANSCRIBE_LOG_LEVEL_NONE = 0
71
75
  TRANSCRIBE_LOG_LEVEL_INFO = 1
72
76
  TRANSCRIBE_LOG_LEVEL_WARN = 2
@@ -111,6 +115,7 @@ TRANSCRIBE_ROLE_ASR = 1
111
115
  TRANSCRIBE_ROLE_DIARIZE = 2
112
116
  TRANSCRIBE_ROLE_LANGID = 4
113
117
  TRANSCRIBE_ROLE_VAD = 8
118
+ TRANSCRIBE_ROLE_TURN = 16
114
119
  TRANSCRIBE_FEATURE_INITIAL_PROMPT = 0
115
120
  TRANSCRIBE_FEATURE_TEMPERATURE_FALLBACK = 1
116
121
  TRANSCRIBE_FEATURE_LONG_FORM = 2
@@ -208,6 +213,14 @@ class transcribe_parakeet_buffered_stream_ext(_c.Structure):
208
213
  pass
209
214
  class transcribe_sortformer_diarize_ext(_c.Structure):
210
215
  pass
216
+ class transcribe_turn_info(_c.Structure):
217
+ pass
218
+ class transcribe_turn_session_params(_c.Structure):
219
+ pass
220
+ class transcribe_turn_params(_c.Structure):
221
+ pass
222
+ class transcribe_turn_result(_c.Structure):
223
+ pass
211
224
  class transcribe_vad_info(_c.Structure):
212
225
  pass
213
226
  class transcribe_vad_session_params(_c.Structure):
@@ -253,6 +266,10 @@ transcribe_moonshine_streaming_stream_ext._fields_ = [("ext", transcribe_ext), (
253
266
  transcribe_parakeet_stream_ext._fields_ = [("ext", transcribe_ext), ("att_context_right", _c.c_int32)]
254
267
  transcribe_parakeet_buffered_stream_ext._fields_ = [("ext", transcribe_ext), ("left_ms", _c.c_int32), ("chunk_ms", _c.c_int32), ("right_ms", _c.c_int32)]
255
268
  transcribe_sortformer_diarize_ext._fields_ = [("ext", transcribe_ext), ("preset", _c.c_int)]
269
+ transcribe_turn_info._fields_ = [("struct_size", _c.c_uint64), ("sample_rate", _c.c_int32), ("max_audio_ms", _c.c_int32), ("frame_samples", _c.c_int32), ("has_speech", _c.c_bool), ("threshold", _c.c_double)]
270
+ transcribe_turn_session_params._fields_ = [("struct_size", _c.c_uint64), ("n_threads", _c.c_int32)]
271
+ transcribe_turn_params._fields_ = [("struct_size", _c.c_uint64), ("threshold", _c.c_double)]
272
+ transcribe_turn_result._fields_ = [("struct_size", _c.c_uint64), ("p", _c.c_float), ("ended", _c.c_bool), ("n_probs", _c.c_int32), ("first_frame", _c.c_int64), ("n_speech_probs", _c.c_int32), ("speech_first_frame", _c.c_int64)]
256
273
  transcribe_vad_info._fields_ = [("struct_size", _c.c_uint64), ("sample_rate", _c.c_int32), ("frame_samples", _c.c_int32)]
257
274
  transcribe_vad_session_params._fields_ = [("struct_size", _c.c_uint64), ("n_threads", _c.c_int32)]
258
275
  transcribe_vad_params._fields_ = [("struct_size", _c.c_uint64), ("threshold", _c.c_double), ("neg_threshold", _c.c_double), ("min_speech_ms", _c.c_int32), ("min_silence_ms", _c.c_int32), ("speech_pad_ms", _c.c_int32), ("max_speech_ms", _c.c_int32)]
@@ -289,6 +306,10 @@ ABI_STRUCT_IDS = {
289
306
  'transcribe_langid_params': 21,
290
307
  'transcribe_langid_result': 22,
291
308
  'transcribe_langid_candidate': 23,
309
+ 'transcribe_turn_info': 29,
310
+ 'transcribe_turn_session_params': 30,
311
+ 'transcribe_turn_params': 31,
312
+ 'transcribe_turn_result': 32,
292
313
  'transcribe_vad_info': 24,
293
314
  'transcribe_vad_session_params': 25,
294
315
  'transcribe_vad_params': 26,
@@ -326,6 +347,10 @@ STRUCT_LAYOUT = {
326
347
  'transcribe_parakeet_stream_ext': {'size': 24, 'align': 8, 'offsets': {'ext': 0, 'att_context_right': 16}},
327
348
  'transcribe_parakeet_buffered_stream_ext': {'size': 32, 'align': 8, 'offsets': {'ext': 0, 'left_ms': 16, 'chunk_ms': 20, 'right_ms': 24}},
328
349
  'transcribe_sortformer_diarize_ext': {'size': 24, 'align': 8, 'offsets': {'ext': 0, 'preset': 16}},
350
+ 'transcribe_turn_info': {'size': 32, 'align': 8, 'offsets': {'struct_size': 0, 'sample_rate': 8, 'max_audio_ms': 12, 'frame_samples': 16, 'has_speech': 20, 'threshold': 24}},
351
+ 'transcribe_turn_session_params': {'size': 16, 'align': 8, 'offsets': {'struct_size': 0, 'n_threads': 8}},
352
+ 'transcribe_turn_params': {'size': 16, 'align': 8, 'offsets': {'struct_size': 0, 'threshold': 8}},
353
+ 'transcribe_turn_result': {'size': 48, 'align': 8, 'offsets': {'struct_size': 0, 'p': 8, 'ended': 12, 'n_probs': 16, 'first_frame': 24, 'n_speech_probs': 32, 'speech_first_frame': 40}},
329
354
  'transcribe_vad_info': {'size': 16, 'align': 8, 'offsets': {'struct_size': 0, 'sample_rate': 8, 'frame_samples': 12}},
330
355
  'transcribe_vad_session_params': {'size': 16, 'align': 8, 'offsets': {'struct_size': 0, 'n_threads': 8}},
331
356
  'transcribe_vad_params': {'size': 40, 'align': 8, 'offsets': {'struct_size': 0, 'threshold': 8, 'neg_threshold': 16, 'min_speech_ms': 24, 'min_silence_ms': 28, 'speech_pad_ms': 32, 'max_speech_ms': 36}},
@@ -583,6 +608,40 @@ def configure(lib):
583
608
  lib.transcribe_token_init.argtypes = [_c.POINTER(transcribe_token)]
584
609
  lib.transcribe_tokenize.restype = _c.c_int
585
610
  lib.transcribe_tokenize.argtypes = [_c.c_void_p, _c.c_char_p, _c.POINTER(_c.c_int32), _c.c_size_t]
611
+ lib.transcribe_turn_get_info.restype = _c.c_int
612
+ lib.transcribe_turn_get_info.argtypes = [_c.c_void_p, _c.POINTER(transcribe_turn_info)]
613
+ lib.transcribe_turn_get_result.restype = _c.c_int
614
+ lib.transcribe_turn_get_result.argtypes = [_c.c_void_p, _c.POINTER(transcribe_turn_result)]
615
+ lib.transcribe_turn_get_timings.restype = _c.c_int
616
+ lib.transcribe_turn_get_timings.argtypes = [_c.c_void_p, _c.POINTER(transcribe_timings)]
617
+ lib.transcribe_turn_info_init.restype = None
618
+ lib.transcribe_turn_info_init.argtypes = [_c.POINTER(transcribe_turn_info)]
619
+ lib.transcribe_turn_params_init.restype = None
620
+ lib.transcribe_turn_params_init.argtypes = [_c.POINTER(transcribe_turn_params)]
621
+ lib.transcribe_turn_probs.restype = _c.POINTER(_c.c_float)
622
+ lib.transcribe_turn_probs.argtypes = [_c.c_void_p]
623
+ lib.transcribe_turn_result_init.restype = None
624
+ lib.transcribe_turn_result_init.argtypes = [_c.POINTER(transcribe_turn_result)]
625
+ lib.transcribe_turn_run.restype = _c.c_int
626
+ lib.transcribe_turn_run.argtypes = [_c.c_void_p, _c.POINTER(_c.c_float), _c.c_int, _c.POINTER(transcribe_turn_params)]
627
+ lib.transcribe_turn_session_free.restype = None
628
+ lib.transcribe_turn_session_free.argtypes = [_c.c_void_p]
629
+ lib.transcribe_turn_session_init.restype = _c.c_int
630
+ lib.transcribe_turn_session_init.argtypes = [_c.c_void_p, _c.POINTER(transcribe_turn_session_params), _c.POINTER(_c.c_void_p)]
631
+ lib.transcribe_turn_session_params_init.restype = None
632
+ lib.transcribe_turn_session_params_init.argtypes = [_c.POINTER(transcribe_turn_session_params)]
633
+ lib.transcribe_turn_set_abort_callback.restype = None
634
+ lib.transcribe_turn_set_abort_callback.argtypes = [_c.c_void_p, _c.CFUNCTYPE(_c.c_bool, _c.c_void_p), _c.c_void_p]
635
+ lib.transcribe_turn_speech_probs.restype = _c.POINTER(_c.c_float)
636
+ lib.transcribe_turn_speech_probs.argtypes = [_c.c_void_p]
637
+ lib.transcribe_turn_stream_feed.restype = _c.c_int
638
+ lib.transcribe_turn_stream_feed.argtypes = [_c.c_void_p, _c.POINTER(_c.c_float), _c.c_int]
639
+ lib.transcribe_turn_stream_feed_batch.restype = _c.c_int
640
+ lib.transcribe_turn_stream_feed_batch.argtypes = [_c.POINTER(_c.c_void_p), _c.POINTER(_c.POINTER(_c.c_float)), _c.POINTER(_c.c_int), _c.c_int]
641
+ lib.transcribe_turn_stream_flush.restype = _c.c_int
642
+ lib.transcribe_turn_stream_flush.argtypes = [_c.c_void_p]
643
+ lib.transcribe_turn_stream_reset.restype = None
644
+ lib.transcribe_turn_stream_reset.argtypes = [_c.c_void_p]
586
645
  lib.transcribe_vad_get_info.restype = _c.c_int
587
646
  lib.transcribe_vad_get_info.argtypes = [_c.c_void_p, _c.POINTER(transcribe_vad_info)]
588
647
  lib.transcribe_vad_get_result.restype = _c.c_int