feat(voice): add isolated Local S2S v3 candidate and acceptance evidence

Extract the provider boundary while retaining OpenAI/Gemini contracts. Add
an opt-in isolated Local S2S adapter, pinned engine extension, bounded
component gateway and frozen effective configuration profiles.

Enforce request token limits, zero retries, local asset validation,
connection deadlines, disconnect ownership, bounded cleanup and signals.
Include regression coverage, pinned source fixtures, operator guidance,
asset fingerprints and guarded disposable PostgreSQL acceptance tooling.
Preserve immutable fixture bytes across Git line-ending conversion.

Validation recorded in the reports:
- 74 repair, 107 combined and 242 preservation checks passed.
- Fresh PostgreSQL local checks: 2 passed.
- Expanded PostgreSQL: 57 passed, 6 documented baseline failures.
- Compose configurations, staged whitespace and fixture hashes passed.

Phase 1 live listening and Phase 2 complete engine/SDK/POSIX, real component
audio and Persian browser acceptance remain pending. No operational switch,
paid call, model download or Phase 3 implementation is included.
This commit is contained in:
amirhosein mazaheri
2026-10-15 12:28:17 +03:30
parent 872e5f25cb
commit 8d348f0ba1
56 changed files with 8802 additions and 44 deletions
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [2024] [The HuggingFace Inc. team]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
File diff suppressed because it is too large Load Diff
+389
View File
@@ -0,0 +1,389 @@
from __future__ import annotations
import json
import logging
import time
from collections.abc import Iterator
from typing import Any, cast
from openai import Stream
from openai.types.chat import (
ChatCompletionChunk,
ChatCompletionContentPartImageParam,
ChatCompletionContentPartParam,
ChatCompletionContentPartTextParam,
ChatCompletionNamedToolChoiceParam,
ChatCompletionToolChoiceOptionParam,
ChatCompletionToolParam,
)
from openai.types.chat.chat_completion_content_part_image_param import ImageURL
from openai.types.chat.chat_completion_named_tool_choice_param import Function as NamedToolChoiceFunction
from openai.types.realtime.realtime_conversation_item_assistant_message import (
Content as AssistantContent,
)
from openai.types.responses import ResponseFunctionToolCall
from openai.types.shared_params import FunctionDefinition
from speech_to_speech.LLM.base_openai_compatible_language_model import (
WARMUP_MAX_RETRIES,
AssistantMessage,
BaseOpenAICompatibleHandler,
ProviderEvent,
ProviderResponseEnd,
TextDelta,
ToolCall,
Usage,
)
from speech_to_speech.LLM.chat import Chat
from speech_to_speech.LLM.compaction_prompt import CompactGenerateFn
from speech_to_speech.utils.utils import _generate_id
logger = logging.getLogger(__name__)
def _to_chat_tools(req_tools: Any) -> list[ChatCompletionToolParam] | None:
"""Convert Responses-API function tools to Chat-Completions tool format.
Responses tools are flat ``{type:"function", name, description, parameters}``;
Chat Completions nests them under a ``function`` key. Items already in the
nested form (or non-function tools) are passed through untouched.
"""
if not req_tools:
return None
chat_tools: list[ChatCompletionToolParam] = []
for t in req_tools:
d = t if isinstance(t, dict) else t.model_dump(exclude_none=True)
if d.get("type") == "function" and "function" not in d:
fn = FunctionDefinition(name=d["name"])
if d.get("description") is not None:
fn["description"] = d["description"]
if d.get("parameters") is not None:
fn["parameters"] = d["parameters"]
chat_tools.append(ChatCompletionToolParam(type="function", function=fn))
else:
chat_tools.append(cast("ChatCompletionToolParam", d))
return chat_tools
def _to_chat_tool_choice(tool_choice: Any) -> ChatCompletionToolChoiceOptionParam:
"""Convert a Responses-API tool_choice to Chat-Completions form.
The string forms ("auto"/"required"/"none") are identical across both APIs;
only the forced-function object differs (flat ``name`` vs nested ``function``).
"""
if isinstance(tool_choice, dict) and tool_choice.get("type") == "function" and "name" in tool_choice:
return ChatCompletionNamedToolChoiceParam(
type="function", function=NamedToolChoiceFunction(name=tool_choice["name"])
)
if tool_choice is not None and not isinstance(tool_choice, (str, dict)):
d = tool_choice.model_dump(exclude_none=True)
if d.get("type") == "function" and "name" in d:
return ChatCompletionNamedToolChoiceParam(type="function", function=NamedToolChoiceFunction(name=d["name"]))
return cast("ChatCompletionToolChoiceOptionParam", d)
return cast("ChatCompletionToolChoiceOptionParam", tool_choice)
def _build_chat_optional_kwargs(req_tools: Any, req_tool_choice: Any) -> dict[str, Any]:
"""Build Chat Completions tool arguments from the Responses-style session config."""
optional_kwargs: dict[str, Any] = {}
chat_tools = _to_chat_tools(req_tools)
if chat_tools is not None:
optional_kwargs["tools"] = chat_tools
if req_tool_choice is not None:
optional_kwargs["tool_choice"] = _to_chat_tool_choice(req_tool_choice)
return optional_kwargs
def _to_chat_content_part(
part: dict[str, Any],
audio_content_type: str = "input_audio",
) -> ChatCompletionContentPartParam:
"""Convert one Realtime/transformers content part to Chat Completions shape."""
ptype = part.get("type")
if ptype == "input_text":
return ChatCompletionContentPartTextParam(type="text", text=part.get("text") or "")
if ptype == "input_image":
raw_url: Any = part.get("image_url")
if isinstance(raw_url, dict):
image_url = cast("ImageURL", raw_url)
else:
image_url = ImageURL(url=raw_url)
detail = part.get("detail")
if detail is not None:
image_url["detail"] = detail
return ChatCompletionContentPartImageParam(type="image_url", image_url=image_url)
if ptype == "input_audio":
audio_b64 = part.get("audio") or ""
if audio_content_type == "audio_url":
return cast(
"ChatCompletionContentPartParam",
{
"type": "audio_url",
"audio_url": {
"url": f"data:audio/wav;base64,{audio_b64}",
},
},
)
return cast(
"ChatCompletionContentPartParam",
{
"type": "input_audio",
"input_audio": {
"data": audio_b64,
"format": "wav",
},
},
)
return cast("ChatCompletionContentPartParam", part)
def _chat_messages(
chat: Chat,
audio_content_type: str = "input_audio",
) -> list[dict[str, Any]]:
"""Serialise chat history, including media and tool messages, for Chat Completions."""
messages = chat.to_transformers_chat()
for message in messages:
for tool_call in message.get("tool_calls") or []:
fn = tool_call.get("function")
if fn is not None and not isinstance(fn.get("arguments"), str):
fn["arguments"] = json.dumps(fn.get("arguments") or {}, ensure_ascii=False)
content = message.get("content")
if isinstance(content, list):
message["content"] = [
_to_chat_content_part(part, audio_content_type=audio_content_type) for part in content
]
if message.get("role") == "tool":
message.pop("name", None)
return messages
def _request_chat_completions(
*,
client: Any,
model_name: str,
messages: list[dict[str, Any]],
stream: bool,
extra_body: dict[str, Any] | None,
timeout: Any,
optional_kwargs: dict[str, Any],
) -> Any:
"""Issue a Chat Completions request with consistent streaming usage accounting."""
create_kwargs = dict(optional_kwargs)
if stream:
create_kwargs["stream_options"] = {"include_usage": True}
return client.chat.completions.create(
model=model_name,
messages=messages,
stream=stream,
extra_body=extra_body,
timeout=timeout,
**create_kwargs,
)
def _tool_calls_from_accum(tool_accum: dict[int, dict[str, str]]) -> Iterator[ToolCall]:
"""Turn accumulated Chat Completions tool deltas into normalized tool-call events."""
for index in sorted(tool_accum):
entry = tool_accum[index]
if not entry["name"]:
continue
yield ToolCall(
item=ResponseFunctionToolCall(
type="function_call",
name=entry["name"],
arguments=entry["args"] or "{}",
call_id=_generate_id("call"),
id=_generate_id("fc"),
status="completed",
)
)
def _chat_response_end(finish_reason: str) -> ProviderResponseEnd:
if finish_reason == "length":
return ProviderResponseEnd(status="incomplete", reason="max_output_tokens")
if finish_reason == "content_filter":
return ProviderResponseEnd(status="incomplete", reason="content_filter")
return ProviderResponseEnd()
def _iter_chat_stream_events(api_response: Stream[ChatCompletionChunk]) -> Iterator[ProviderEvent]:
"""Normalize a streaming Chat Completions response."""
tool_accum: dict[int, dict[str, str]] = {}
usage: Usage | None = None
text_segment = ""
ending: ProviderResponseEnd | None = None
def flush_tools() -> Iterator[ProviderEvent]:
nonlocal text_segment
if text_segment:
yield AssistantMessage(content=[AssistantContent(type="output_text", text=text_segment)])
text_segment = ""
yield from _tool_calls_from_accum(tool_accum)
tool_accum.clear()
def accumulate_tools(tool_calls: Any) -> None:
for tool_call in tool_calls or []:
entry = tool_accum.setdefault(tool_call.index, {"name": "", "args": "", "id": ""})
if tool_call.id:
entry["id"] = tool_call.id
if tool_call.function is not None:
if tool_call.function.name:
entry["name"] = tool_call.function.name
if tool_call.function.arguments:
entry["args"] += tool_call.function.arguments
for chunk in api_response:
if chunk.usage is not None:
usage = Usage(
input_tokens=chunk.usage.prompt_tokens or 0,
output_tokens=chunk.usage.completion_tokens or 0,
)
if not chunk.choices:
continue
finish_reason = getattr(chunk.choices[0], "finish_reason", None)
if finish_reason is not None:
ending = _chat_response_end(finish_reason)
yield ending
delta = chunk.choices[0].delta
text_piece = delta.content or getattr(delta, "refusal", None)
continuing_tool = bool(tool_accum)
if continuing_tool:
accumulate_tools(delta.tool_calls)
if text_piece:
if continuing_tool:
yield from flush_tools()
text_segment += text_piece
yield TextDelta(text=text_piece)
if not continuing_tool:
accumulate_tools(delta.tool_calls)
if ending is None:
logger.warning("Chat Completions stream ended without a finish_reason")
if tool_accum and (ending is None or ending.status == "completed"):
yield from flush_tools()
if text_segment:
yield AssistantMessage(content=[AssistantContent(type="output_text", text=text_segment)])
if usage is not None:
yield usage
def _iter_chat_response_events(api_response: Any) -> Iterator[ProviderEvent]:
"""Normalize a non-streaming Chat Completions response."""
usage = api_response.usage
if usage:
yield Usage(input_tokens=usage.prompt_tokens or 0, output_tokens=usage.completion_tokens or 0)
if api_response.choices:
finish_reason = getattr(api_response.choices[0], "finish_reason", None)
if finish_reason is not None:
yield _chat_response_end(finish_reason)
message = api_response.choices[0].message if api_response.choices else None
if message is None:
return
raw_content = message.content or getattr(message, "refusal", None)
if raw_content:
yield AssistantMessage(content=[AssistantContent(type="output_text", text=raw_content)])
yield TextDelta(text=raw_content)
tool_accum: dict[int, dict[str, str]] = {}
for tool_call in message.tool_calls or []:
tool_accum[len(tool_accum)] = {
"name": tool_call.function.name or "",
"args": tool_call.function.arguments or "",
"id": tool_call.id or "",
}
yield from _tool_calls_from_accum(tool_accum)
class ChatCompletionsApiModelHandler(BaseOpenAICompatibleHandler):
"""LLM handler that talks to an OpenAI-compatible ``/v1/chat/completions`` server.
Functionally mirrors :class:`ResponsesApiModelHandler` but uses the mature
Chat Completions streaming tool-call protocol (``choices[].delta.tool_calls``)
instead of ``/v1/responses``. This is the robust path for vLLM + Qwen tool
calling. The conversation is serialised with :meth:`Chat.to_transformers_chat`,
which already emits OpenAI chat messages including ``tool_calls``/``tool`` roles.
"""
def warmup(self) -> None:
logger.info(f"Warming up {self.__class__.__name__}")
start = time.time()
self.client.with_options(max_retries=WARMUP_MAX_RETRIES).chat.completions.create(
model=self.model_name,
messages=[
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "Hello"},
],
extra_body=self._extra_body,
timeout=self.request_timeout,
)
end = time.time()
logger.info(f"{self.__class__.__name__}: warmed up! time: {(end - start):.3f} s")
def _build_compaction_generate_fn(self) -> CompactGenerateFn:
"""Return a generate fn that calls Chat Completions for compaction."""
client = self.client
model_name = self.model_name
timeout = self.request_timeout
extra_body = self._extra_body
def generate(system: str, user: str) -> str:
response = client.chat.completions.create(
model=model_name,
messages=[
{"role": "system", "content": system},
{"role": "user", "content": user},
],
extra_body=extra_body,
timeout=timeout,
)
return response.choices[0].message.content or ""
return generate
@staticmethod
def _to_chat_content_part(
part: dict[str, Any],
audio_content_type: str = "input_audio",
) -> ChatCompletionContentPartParam:
return _to_chat_content_part(part, audio_content_type=audio_content_type)
@classmethod
def _chat_messages(
cls,
chat: Chat,
audio_content_type: str = "input_audio",
) -> list[dict[str, Any]]:
return _chat_messages(chat, audio_content_type=audio_content_type)
# ── base hooks ──────────────────────────────────────────────────────────--
def _serialize(self, active_chat: Chat) -> list[dict[str, Any]]:
return self._chat_messages(active_chat, audio_content_type=self.audio_content_type)
def _build_optional_kwargs(self, req_tools: Any, req_tool_choice: Any) -> dict[str, Any]:
return _build_chat_optional_kwargs(req_tools, req_tool_choice)
def _request(self, api_input: list[dict[str, Any]], optional_kwargs: dict[str, Any]) -> Any:
return _request_chat_completions(
client=self.client,
model_name=self.model_name,
messages=api_input,
stream=self.stream,
extra_body=self._extra_body,
timeout=self.request_timeout,
optional_kwargs=optional_kwargs,
)
def _iter_stream_events(self, api_response: Stream[ChatCompletionChunk]) -> Iterator[ProviderEvent]:
yield from _iter_chat_stream_events(api_response)
def _iter_response_events(self, api_response: Any) -> Iterator[ProviderEvent]:
yield from _iter_chat_response_events(api_response)
@staticmethod
def _tool_calls_from_accum(tool_accum: dict[int, dict[str, str]]) -> Iterator[ToolCall]:
yield from _tool_calls_from_accum(tool_accum)
def on_session_end(self) -> None:
logger.debug("Chat Completions API language model session state reset")
+389
View File
@@ -0,0 +1,389 @@
"""Explicit configured construction and lifecycle. Construction can load models."""
from __future__ import annotations
import asyncio
import logging
import signal
from copy import deepcopy
from dataclasses import fields
from ipaddress import ip_address
from threading import Event, RLock, Thread, current_thread
from time import monotonic
from typing import TYPE_CHECKING, Any, Literal
from speech_to_speech.config import ConfigurationError, ResolvedConfig
if TYPE_CHECKING:
from speech_to_speech.api.openai_realtime.audio_client import RealtimeAudioClientConfig
from speech_to_speech.api.openai_realtime.pipeline_unit import PipelineUnit
from speech_to_speech.s2s_pipeline import ParsedArguments
logger = logging.getLogger(__name__)
_JOIN_TIMEOUT_S = 5.0
class ConfiguredRuntimeError(RuntimeError):
"""A runtime error that does not include provider diagnostics or credentials."""
def _explicit(config: ResolvedConfig, *path: str) -> bool:
return config.sources.get(path, "default") != "default"
def _cleanup(resource: Any) -> None:
try:
cleanup = getattr(resource, "cleanup", None) or getattr(resource, "reset", None)
if cleanup is None and hasattr(resource, "diarizer"):
cleanup = resource.diarizer.reset
if cleanup is not None:
cleanup()
except Exception:
logger.warning("Configured resource cleanup failed")
def _validate_counts(config: ResolvedConfig) -> None:
if not config.pipelines:
raise ConfigurationError("Select at least one pipeline definition.")
for pipeline in config.pipelines.values():
if type(pipeline.num_pipelines) is not int or pipeline.num_pipelines < 1:
raise ConfigurationError("Use positive integer pipeline instance counts.")
def _adapt(config: ResolvedConfig) -> dict[str, ParsedArguments]:
from speech_to_speech import s2s_pipeline as pipeline_module
from speech_to_speech.arguments_classes.local_audio_arguments import LocalAudioArguments
from speech_to_speech.arguments_classes.module_arguments import ModuleArguments
from speech_to_speech.arguments_classes.realtime_server_arguments import RealtimeServerArguments
from speech_to_speech.arguments_classes.vad_arguments import VADHandlerArguments
from speech_to_speech.backend_registry import LLM_BACKENDS, STT_BACKENDS, TTS_BACKENDS, BackendSelection
adapted = {}
for name, pipeline in config.pipelines.items():
options = deepcopy(pipeline.options)
preset = (
pipeline_module._mac_preset_defaults(pipeline.stages["llm"].backend)
if options.get("mac_optimal_settings")
else {}
)
for key, value in preset.items():
if key in options and not _explicit(config, "pipelines", name, "options", key):
options[key] = value
options.update(
stt=pipeline.stages["stt"].backend,
llm_backend=pipeline.stages["llm"].backend,
tts=pipeline.stages["tts"].backend,
num_pipelines=pipeline.num_pipelines,
log_level=config.runtime.get("log_level", "info"),
log_transcripts=config.runtime.get("log_transcripts", False),
torch_num_threads=config.runtime.get("torch_num_threads"),
)
if options.get("diarization") and options.get("diarization_model_name") is None:
options["diarization_model_name"] = "nvidia/Nemotron-3-Diarization"
selections = {}
for kind, registry in (("stt", STT_BACKENDS), ("llm", LLM_BACKENDS), ("tts", TTS_BACKENDS)):
stage = pipeline.stages[kind]
spec = registry[stage.backend]
settings = deepcopy(stage.settings)
for key in {field.name for field in fields(spec.config_type)} & preset.keys():
if not _explicit(config, "blocks", stage.block_id, "settings", key):
settings[key] = deepcopy(preset[key])
selections[kind] = BackendSelection(spec, spec.normalize(spec.config_type(**settings)))
args = pipeline_module.ParsedArguments(
module_kwargs=ModuleArguments(**options),
realtime_server_kwargs=RealtimeServerArguments(**deepcopy(config.runtime.get("server", {}))),
local_audio_kwargs=LocalAudioArguments(),
vad_handler_kwargs=VADHandlerArguments(**deepcopy(pipeline.stages["vad"].settings)),
stt_backend=selections["stt"],
llm_backend=selections["llm"],
tts_backend=selections["tts"],
)
try:
pipeline_module.prepare_all_args(args)
except ValueError:
raise ConfigurationError("The selected pipeline settings are incompatible.") from None
adapted[name] = args
if pipeline_module.platform == "darwin" and sum(p.num_pipelines for p in config.pipelines.values()) > 1:
for args in adapted.values():
args.module_kwargs.enable_live_transcription = False
return adapted
def build_configured_client(config: ResolvedConfig, *, local: bool = False) -> RealtimeAudioClientConfig:
"""Build independent packaged client settings and load explicitly selected tools."""
from speech_to_speech.api.openai_realtime.audio_client import (
RealtimeAudioClientConfig,
build_session_update,
load_realtime_tool_module,
)
settings = deepcopy(config.client or {})
module = settings.pop("tool_module", None)
process_explicit = _explicit(config, "runtime", "log_transcripts")
client_explicit = _explicit(config, "runtime", "client", "log_transcripts")
process_log = config.runtime.get("log_transcripts", False)
if process_explicit and client_explicit and settings.get("log_transcripts", False) != process_log:
raise ConfigurationError("Process and client transcript settings must agree.")
if process_explicit or not client_explicit:
settings["log_transcripts"] = process_log
if module and _explicit(config, "runtime", "client", "tools"):
raise ConfigurationError("Use either a tool module or explicit client tools.")
if local:
if len(config.pipelines) != 1:
raise ConfigurationError("Local startup requires exactly one pipeline definition.")
server = config.runtime.get("server", {})
host = server.get("host", "127.0.0.1")
try:
loopback = host == "localhost" or ip_address(host).is_loopback
except ValueError:
loopback = False
if _explicit(config, "runtime", "server", "host") and not loopback:
raise ConfigurationError("Local startup requires a loopback server host.")
url = f"ws://127.0.0.1:{server.get('port', 8765)}/v1/realtime"
if _explicit(config, "runtime", "client", "url") and settings.get("url") != url:
raise ConfigurationError("Local client URL must match the loopback server port.")
settings["url"] = url
if not _explicit(config, "runtime", "client", "playback_buffer_ms"):
pipeline = next(iter(config.pipelines.values()))
settings["playback_buffer_ms"] = 196.0 if pipeline.stages["tts"].backend == "openai" else 0.0
if module:
tools, executor, create_response = load_realtime_tool_module(module)
settings.update(tools=tools, tool_executor=executor)
if not _explicit(config, "runtime", "client", "tool_response_create"):
settings["tool_response_create"] = create_response
try:
client = RealtimeAudioClientConfig(**settings)
build_session_update(client)
except ValueError:
raise ConfigurationError("Invalid packaged client settings or tool contract.") from None
return client
class ConfiguredRuntime:
"""Own named worker pools and optional server/client resources without installing signals.
Running means managed threads have started. It does not indicate listener readiness.
"""
def __init__(self, stop_event: Event) -> None:
self.pools: dict[str, list[PipelineUnit]] = {}
self.server: Any = None
self.client: Any = None
self.state = "constructed"
self._caller_stop = stop_event
self._stop = Event()
self._events: list[Event] = []
self._resources: list[Any] = []
self._handlers: list[Any] = []
self._threads: list[Thread] = []
self._started: set[int] = set()
self._monitor: Thread | None = None
self._failure: str | None = None
self._lock = RLock()
def _signal_stop(self) -> None:
self._stop.set()
for event in self._events:
event.set()
def _run(self, handler: Any) -> None:
try:
if handler is self.client:
from speech_to_speech.api.openai_realtime.audio_client import listen_and_play_realtime
asyncio.run(listen_and_play_realtime(handler.config, stop_event=handler.stop_event))
else:
handler.run()
except BaseException:
self._failure = "A configured worker, listener, or client failed."
self._signal_stop()
finally:
if handler is self.server or handler is self.client:
self._signal_stop()
def _watch(self) -> None:
while not self._stop.wait(0.05):
if self._caller_stop.is_set() or any(event.is_set() for event in self._events):
self._signal_stop()
def start(self) -> None:
with self._lock:
if self.state == "running":
return
if self.state != "constructed":
raise ConfiguredRuntimeError("A stopped or failed configured runtime cannot restart.")
if self._caller_stop.is_set():
self.stop()
return
try:
for handler in self._handlers:
if self._stop.is_set():
raise ConfiguredRuntimeError("Configured startup stopped before completion.")
thread = Thread(target=self._run, args=(handler,))
thread.start()
self._threads.append(thread)
self._started.add(id(handler))
monitor = Thread(target=self._watch, daemon=True)
monitor.start()
self._monitor = monitor
self.state = "running"
except BaseException:
self._failure = "Configured thread startup failed."
self.stop()
raise ConfiguredRuntimeError(self._failure) from None
def stop(self) -> None:
with self._lock:
if self.state in {"stopped", "failed"}:
return
self.state = "stopping"
self._signal_stop()
deadline = monotonic() + _JOIN_TIMEOUT_S
for thread in self._threads:
if thread is not current_thread():
thread.join(max(0.0, deadline - monotonic()))
if self._monitor is not None and self._monitor is not current_thread():
self._monitor.join(max(0.0, deadline - monotonic()))
survivors = sum(thread.is_alive() for thread in self._threads)
if self._monitor is not None and self._monitor.is_alive():
survivors += 1
if survivors:
logger.warning("Configured shutdown has %d surviving threads", survivors)
raise ConfiguredRuntimeError("Configured shutdown has threads still running.")
for resource in reversed(self._resources):
if id(resource) not in self._started:
_cleanup(resource)
self.pools.clear()
self.server = self.client = None
self._resources.clear()
self._handlers.clear()
self._threads.clear()
self._started.clear()
self._events.clear()
self._monitor = None
self.state = "failed" if self._failure else "stopped"
def wait(self) -> None:
if self.state == "constructed":
return
while self.state == "running" and any(thread.is_alive() for thread in self._threads):
if self._caller_stop.wait(0.05) or self._stop.is_set():
break
self.stop()
if self._failure:
raise ConfiguredRuntimeError(self._failure)
def build_configured_runtime(config: ResolvedConfig, stop_event: Event) -> ConfiguredRuntime:
"""Construct independent named workers. Models can initialize before start()."""
_validate_counts(config)
return _build_runtime(_adapt(config), stop_event)
def _build_runtime(arguments: dict[str, ParsedArguments], stop_event: Event) -> ConfiguredRuntime:
from speech_to_speech.s2s_pipeline import _build_pipeline_unit
result = ConfiguredRuntime(stop_event)
index = 0
try:
for name, args in arguments.items():
event = Event()
result._events.append(event)
result.pools[name] = []
for _ in range(args.module_kwargs.num_pipelines):
unit = _build_pipeline_unit(
index=index,
stop_event=event,
module_kwargs=deepcopy(args.module_kwargs),
vad_handler_kwargs=deepcopy(args.vad_handler_kwargs),
stt_backend=args.stt_backend.copy_for_pipeline(),
llm_backend=args.llm_backend.copy_for_pipeline(),
tts_backend=args.tts_backend.copy_for_pipeline(),
resource_ledger=result._resources,
)
result.pools[name].append(unit)
result._handlers.extend(unit.handlers)
index += 1
except BaseException as exc:
result._failure = f"Configured pipeline {name} construction failed."
result.stop()
raise ConfiguredRuntimeError(result._failure) from exc
return result
def build_configured_server(config: ResolvedConfig, stop_event: Event, *, local: bool = False) -> ConfiguredRuntime:
"""Publish one definition through a server, with an optional loopback client."""
_validate_counts(config)
if len(config.pipelines) != 1:
raise ConfigurationError("Serving requires exactly one selected pipeline definition.")
client_config = build_configured_client(config, local=True) if local else None
arguments = _adapt(config)
result = _build_runtime(arguments, stop_event)
try:
from speech_to_speech.api.openai_realtime.audio_client import RealtimeAudioClient
from speech_to_speech.api.openai_realtime.server import RealtimeServer
from speech_to_speech.s2s_pipeline import build_llm_proxy_config
args = next(iter(arguments.values()))
event = result._events[0]
result.server = RealtimeServer(
stop_event=event,
pool=next(iter(result.pools.values())),
host="127.0.0.1" if local else args.realtime_server_kwargs.host,
port=args.realtime_server_kwargs.port,
llm_proxy_config=build_llm_proxy_config(args.module_kwargs, args.llm_backend)
if args.module_kwargs.enable_llm_proxy
else None,
)
result._resources.append(result.server)
result._handlers.append(result.server)
if client_config is not None:
result.client = RealtimeAudioClient(event, client_config)
result._resources.append(result.client)
result._handlers.append(result.client)
except BaseException as exc:
result._failure = "Configured server construction failed."
result.stop()
raise ConfiguredRuntimeError(result._failure) from exc
return result
def run_configured_command(command: Literal["serve", "local", "talk"], config: ResolvedConfig) -> None:
"""Own CLI signal handlers and always stop constructed resources."""
from speech_to_speech.pipeline.transcript_logging import set_log_transcripts, warn_if_log_transcripts_enabled
stop_event = Event()
result: ConfiguredRuntime | None = None
previous = {sig: signal.getsignal(sig) for sig in (signal.SIGINT, signal.SIGTERM)}
try:
for sig in previous:
signal.signal(sig, lambda *_: stop_event.set())
if command == "talk":
from speech_to_speech.api.openai_realtime.audio_client import listen_and_play_realtime
client = build_configured_client(config)
logging.basicConfig(level=config.runtime.get("log_level", "info").upper())
set_log_transcripts(client.log_transcripts)
warn_if_log_transcripts_enabled()
asyncio.run(listen_and_play_realtime(client, stop_event=stop_event))
else:
from speech_to_speech.s2s_pipeline import setup_logger
setup_logger(config.runtime.get("log_level", "info"))
result = build_configured_server(config, stop_event, local=command == "local")
set_log_transcripts(
result.client.config.log_transcripts
if command == "local"
else config.runtime.get("log_transcripts", False)
)
warn_if_log_transcripts_enabled()
result.start()
result.wait()
finally:
stop_event.set()
try:
if result is not None:
result.stop()
finally:
for sig, handler in previous.items():
signal.signal(sig, handler)
+25
View File
@@ -0,0 +1,25 @@
{
"commit": "619e3fe4f71d1c6f35c15870d588a3638de34722",
"files": {
"chat.py.source": {
"path": "src/speech_to_speech/LLM/chat_completions_language_model.py",
"sha256": "ce5e0c05881288f20e236c549cc7b85ae08603667b50dab38d21a23636ed1015"
},
"base.py.source": {
"path": "src/speech_to_speech/LLM/base_openai_compatible_language_model.py",
"sha256": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609"
},
"pipeline.py.source": {
"path": "src/speech_to_speech/s2s_pipeline.py",
"sha256": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7"
},
"lifecycle.py.source": {
"path": "src/speech_to_speech/configured_runtime.py",
"sha256": "7d3408991b9cc8d20c20051521e5d106f4831d018251c92a71c8ba75243613a6"
},
"LICENSE": {
"path": "LICENSE",
"sha256": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46"
}
}
}
+843
View File
@@ -0,0 +1,843 @@
import argparse
import json
import logging
import os
import signal
import sys
from copy import deepcopy
from dataclasses import dataclass, fields, replace
from pathlib import Path
from queue import Queue
from sys import modules, platform
from threading import Event
from types import FrameType
from typing import Any, Literal, Optional, Sequence
import nltk
import torch
from rich.console import Console
from transformers import HfArgumentParser
from speech_to_speech.api.openai_realtime.pipeline_unit import PipelineUnit
from speech_to_speech.arguments_classes.language_model_arguments import MLX_DEFAULT_LM_MODEL
from speech_to_speech.arguments_classes.local_audio_arguments import LocalAudioArguments
from speech_to_speech.arguments_classes.module_arguments import ModuleArguments
from speech_to_speech.arguments_classes.realtime_server_arguments import (
LocalRealtimeServerArguments,
RealtimeServerArguments,
)
from speech_to_speech.arguments_classes.vad_arguments import VADHandlerArguments
from speech_to_speech.backend_registry import (
LLM_BACKENDS,
STT_BACKENDS,
TTS_BACKENDS,
BackendSelection,
BackendSpec,
HandlerContext,
create_backend_handler,
)
from speech_to_speech.pipeline.cancel_scope import CancelScope
from speech_to_speech.pipeline.queue_types import (
AudioInItem,
AudioOutItem,
LMOutItem,
STTOutItem,
TextEventItem,
TextPromptItem,
TTSInItem,
VADOutItem,
)
from speech_to_speech.pipeline.speculative_turns import SpeculativeTurnTracker
from speech_to_speech.pipeline.transcript_logging import (
set_log_transcripts,
warn_if_log_transcripts_enabled,
)
from speech_to_speech.pipeline.turn_latency import TurnLatencyStore
from speech_to_speech.STT.transcription_notifier import TranscriptionNotifier
from speech_to_speech.utils.thread_manager import ThreadManager
from speech_to_speech.utils.utils import resolve_device
from speech_to_speech.VAD.vad_handler import VADHandler
# Ensure that the necessary NLTK resources are available
try:
nltk.data.find("tokenizers/punkt_tab")
except (LookupError, OSError):
nltk.download("punkt_tab")
try:
nltk.data.find("taggers/averaged_perceptron_tagger_eng")
except (LookupError, OSError):
nltk.download("averaged_perceptron_tagger_eng")
# caching allows ~50% compilation time reduction
# see https://docs.google.com/document/d/1y5CRfMLdwEoF1nTk9q8qEu1mgMUuUtvhklPKJ2emLU8/edit#heading=h.o2asbxsrp1ma
CURRENT_DIR = Path(__file__).resolve().parent
os.environ["TORCHINDUCTOR_CACHE_DIR"] = os.path.join(CURRENT_DIR, "tmp")
console = Console()
logger = logging.getLogger(__name__)
logging.getLogger("numba").setLevel(logging.WARNING) # quiet down numba logs
OPENAI_TTS_PLAYBACK_BUFFER_MS = 196.0
def _mac_preset_defaults(llm_backend: str) -> dict[str, Any]:
"""Return macOS parser defaults, leaving explicit arguments free to override them."""
defaults: dict[str, Any] = {
"stt": "parakeet-tdt",
"llm_backend": "mlx-lm",
"tts": "qwen3",
"stt_device": "mps",
"diarization_device": "mps",
"paraformer_stt_device": "mps",
"facebook_mms_device": "mps",
"qwen3_tts_device": "mps",
}
if llm_backend not in {"responses-api", "chat-completions"}:
defaults["llm_device"] = "mps"
if llm_backend == "mlx-lm":
defaults["model_name"] = MLX_DEFAULT_LM_MODEL
return defaults
@dataclass
class ParsedArguments:
module_kwargs: ModuleArguments
realtime_server_kwargs: RealtimeServerArguments
local_audio_kwargs: LocalAudioArguments
vad_handler_kwargs: VADHandlerArguments
stt_backend: BackendSelection
llm_backend: BackendSelection
tts_backend: BackendSelection
def build_llm_proxy_config(
module_kwargs: ModuleArguments,
llm_backend: BackendSelection,
) -> Any:
"""Build proxy settings from the selected LLM's normalized configuration."""
from speech_to_speech.api.openai_realtime.llm_proxy import LLMProxyConfig
if not llm_backend.spec.capabilities.supports_llm_proxy:
supported = ", ".join(name for name, spec in LLM_BACKENDS.items() if spec.capabilities.supports_llm_proxy)
raise ValueError(
f"The LLM proxy requires a backend with proxy support; choose one of: {supported}. "
f"Got {llm_backend.name!r}."
)
config = llm_backend.config
return LLMProxyConfig(
enabled=module_kwargs.enable_llm_proxy,
llm_backend=module_kwargs.llm_backend,
upstream_base_url=config["base_url"],
upstream_api_key=config["api_key"],
model_name=config["model_name"],
connect_timeout_s=module_kwargs.llm_proxy_connect_timeout_s,
)
def _parse_selected_cli_configs(
parser: HfArgumentParser,
pipeline_args: list[str],
selected_specs: Sequence[BackendSpec],
) -> tuple[Any, ...]:
"""Parse selected configs while accepting legacy options for inactive backends."""
*parsed, remaining = parser.parse_args_into_dataclasses(
args=pipeline_args,
return_remaining_strings=True,
)
if not remaining:
return tuple(parsed)
selected_types = {spec.config_type for spec in selected_specs}
inactive_types: list[type[Any]] = []
for registry in (STT_BACKENDS, LLM_BACKENDS, TTS_BACKENDS):
for spec in registry.values():
if spec.config_type not in selected_types and spec.config_type not in inactive_types:
inactive_types.append(spec.config_type)
compatibility_parser = HfArgumentParser(
tuple(inactive_types), # type: ignore[arg-type]
add_help=False,
allow_abbrev=False,
conflict_handler="resolve",
)
known_options = compatibility_parser._option_string_actions
_, unknown = compatibility_parser.parse_known_args(remaining)
if unknown:
raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {unknown}")
ignored_options = sorted({token.split("=", 1)[0] for token in remaining if token.split("=", 1)[0] in known_options})
logger.warning(
"Ignoring options for inactive backends: %s",
", ".join(ignored_options),
)
return tuple(parsed)
def parse_arguments(
argv: Sequence[str] | None = None,
*,
command: Literal["serve", "local"] = "serve",
) -> ParsedArguments:
module_defaults = ModuleArguments()
assert module_defaults.stt is not None
assert module_defaults.llm_backend is not None
assert module_defaults.tts is not None
pipeline_args = list(sys.argv[1:] if argv is None else argv)
_is_json = len(pipeline_args) == 1 and pipeline_args[0].endswith(".json")
pipeline_json: dict[str, Any] | None = None
if _is_json:
with open(pipeline_args[0]) as _f:
pipeline_json = json.load(_f)
_mac_preset_enabled = bool(pipeline_json.get("mac_optimal_settings", False))
_llm_name = pipeline_json.get("llm_backend") or (
"mlx-lm" if _mac_preset_enabled else module_defaults.llm_backend
)
if _mac_preset_enabled:
pipeline_json = {**_mac_preset_defaults(_llm_name), **pipeline_json}
_stt_name = pipeline_json.get("stt") or module_defaults.stt
_tts_name = pipeline_json.get("tts") or module_defaults.tts
else:
_pre = argparse.ArgumentParser(prog=f"speech-to-speech {command}", add_help=False)
_pre.add_argument("--mac-optimal-settings", action="store_true")
_pre.add_argument("--stt", choices=tuple(STT_BACKENDS))
_pre.add_argument("--llm_backend", "--llm-backend", choices=tuple(LLM_BACKENDS))
_pre.add_argument("--tts", choices=tuple(TTS_BACKENDS))
_pre_args = _pre.parse_known_args(pipeline_args)[0]
_mac_preset_enabled = _pre_args.mac_optimal_settings
_stt_name = _pre_args.stt or module_defaults.stt
_llm_name = _pre_args.llm_backend or ("mlx-lm" if _mac_preset_enabled else module_defaults.llm_backend)
_tts_name = _pre_args.tts or module_defaults.tts
selected_specs = []
for registry, name in (
(STT_BACKENDS, _stt_name),
(LLM_BACKENDS, _llm_name),
(TTS_BACKENDS, _tts_name),
):
try:
selected_specs.append(registry[name])
except KeyError as exc:
choices = ", ".join(registry)
raise ValueError(f"Unsupported backend {name!r}; choose one of: {choices}.") from exc
logger.debug(
"Backend pre-parse: stt=%s, llm=%s, tts=%s",
_stt_name,
_llm_name,
_tts_name,
)
server_arguments_class = RealtimeServerArguments if command == "serve" else LocalRealtimeServerArguments
argument_classes: list[type[Any]] = [
ModuleArguments,
server_arguments_class,
]
if command == "local":
argument_classes.append(LocalAudioArguments)
argument_classes.extend(
[
VADHandlerArguments,
*(spec.config_type for spec in selected_specs),
]
)
parser = HfArgumentParser(tuple(argument_classes), prog=f"speech-to-speech {command}") # type: ignore[arg-type]
mac_action = parser._option_string_actions.pop("--mac_optimal_settings")
mac_action.option_strings = [option for option in mac_action.option_strings if option != "--mac_optimal_settings"]
if _mac_preset_enabled:
parser.set_defaults(**_mac_preset_defaults(_llm_name))
if _is_json:
assert pipeline_json is not None
parsed = parser.parse_dict(pipeline_json, allow_extra_keys=True)
else:
parsed = _parse_selected_cli_configs(parser, pipeline_args, selected_specs)
# Build a {type: instance} lookup so field assignment is order-independent.
by_type: dict[type, Any] = {type(obj): obj for obj in parsed}
logger.debug("Parsed %d argument classes: %s", len(by_type), [t.__name__ for t in by_type])
if command == "serve":
realtime_server_kwargs = by_type[RealtimeServerArguments]
else:
realtime_server_kwargs = RealtimeServerArguments(
host="127.0.0.1",
port=by_type[LocalRealtimeServerArguments].port,
)
module_kwargs = by_type[ModuleArguments]
if module_kwargs.diarization and module_kwargs.diarization_model_name is None:
module_kwargs.diarization_model_name = "nvidia/Nemotron-3-Diarization"
module_kwargs.stt = _stt_name
module_kwargs.llm_backend = _llm_name
module_kwargs.tts = _tts_name
args = ParsedArguments(
module_kwargs=module_kwargs,
realtime_server_kwargs=realtime_server_kwargs,
local_audio_kwargs=by_type.get(LocalAudioArguments, LocalAudioArguments()),
vad_handler_kwargs=by_type[VADHandlerArguments],
stt_backend=BackendSelection(
selected_specs[0], selected_specs[0].normalize(by_type[selected_specs[0].config_type])
),
llm_backend=BackendSelection(
selected_specs[1], selected_specs[1].normalize(by_type[selected_specs[1].config_type])
),
tts_backend=BackendSelection(
selected_specs[2], selected_specs[2].normalize(by_type[selected_specs[2].config_type])
),
)
return args
def setup_logger(log_level: str) -> None:
global logger
from speech_to_speech.pipeline.log_context import PipelineLogFilter
logging.basicConfig(
level=log_level.upper(),
format="%(asctime)s - %(pipeline_prefix)s%(name)s - %(levelname)s - %(message)s",
)
# Attach the filter to every existing handler so each LogRecord gets a
# `pipeline_prefix` attribute (matching the format string above).
pipeline_filter = PipelineLogFilter()
for h in logging.getLogger().handlers:
h.addFilter(pipeline_filter)
logger = logging.getLogger(__name__)
# torch compile logs
if log_level == "debug":
torch._logging.set_logs(graph_breaks=True, recompiles=True, cudagraphs=True)
def check_mac_settings(module_kwargs: ModuleArguments) -> None:
if platform == "darwin":
if module_kwargs.device == "cuda":
raise ValueError("Cannot use CUDA on macOS. Please set the device to 'cpu' or 'mps'.")
if module_kwargs.llm_backend != "mlx-lm":
logger.warning(
"For macOS users, it is recommended to use mlx-lm. You can activate it by passing --llm_backend mlx-lm."
)
if module_kwargs.tts not in ("pocket", "kokoro", "omnivoice", "qwen3"):
logger.warning(
"For macOS users, it is recommended to use qwen3 for TTS "
"(pocket, kokoro, and omnivoice are also valid options)."
)
def validate_torch_num_threads(value: Any) -> None:
if value is not None and (type(value) is not int or value < 1):
raise ValueError(f"--torch_num_threads must be a positive integer; got {value!r}.")
def apply_torch_num_threads(module_kwargs: ModuleArguments) -> None:
"""Apply an explicit --torch_num_threads; with it unset, leave PyTorch's thread count alone."""
if module_kwargs.torch_num_threads is not None:
torch.set_num_threads(module_kwargs.torch_num_threads)
def prepare_module_args(module_kwargs: ModuleArguments, llm_backend: BackendSelection) -> None:
validate_torch_num_threads(module_kwargs.torch_num_threads)
if module_kwargs.diarization_model_name and module_kwargs.stt == "none":
raise ValueError("Speaker-aware conversation requires an STT backend; --stt none does not produce transcripts.")
if module_kwargs.diarization_model_name and not 0 < module_kwargs.diarization_threshold < 1:
raise ValueError("--diarization_threshold must be between 0 and 1.")
if module_kwargs.tts is None:
module_kwargs.tts = "qwen3"
if module_kwargs.stt == "none" and not llm_backend.spec.capabilities.supports_audio_input:
supported = ", ".join(name for name, spec in LLM_BACKENDS.items() if spec.capabilities.supports_audio_input)
raise ValueError(f"--stt none requires an audio-input LLM backend; choose one of: {supported}.")
if module_kwargs.enable_llm_proxy and not llm_backend.spec.capabilities.supports_llm_proxy:
supported = ", ".join(name for name, spec in LLM_BACKENDS.items() if spec.capabilities.supports_llm_proxy)
raise ValueError(
f"The LLM proxy requires a backend with proxy support; choose one of: {supported}. "
f"Got {llm_backend.name!r}."
)
if platform == "darwin":
check_mac_settings(module_kwargs)
def prepare_all_args(args: ParsedArguments) -> None:
"""Validate selectors and apply the global device to selected configs only."""
prepare_module_args(args.module_kwargs, args.llm_backend)
if args.module_kwargs.device is None:
return
for field_name in ("stt_backend", "llm_backend", "tts_backend"):
selection = getattr(args, field_name)
if "device" not in selection.config:
continue
config = {**selection.config, "device": args.module_kwargs.device}
setattr(args, field_name, replace(selection, config=config))
def _build_handlers(
*,
stop_event: Event,
should_listen: Event,
recv_audio_chunks_queue: Queue[AudioInItem],
spoken_prompt_queue: Queue[VADOutItem],
stt_output_queue: Queue[STTOutItem],
text_prompt_queue: Queue[TextPromptItem],
lm_response_queue: Queue[LMOutItem],
lm_processed_queue: Queue[TTSInItem],
send_audio_chunks_queue: Queue[AudioOutItem],
text_output_queue: Queue[TextEventItem],
module_kwargs: ModuleArguments,
vad_handler_kwargs: VADHandlerArguments,
stt_backend: BackendSelection,
llm_backend: BackendSelection,
tts_backend: BackendSelection,
speculative_turns: SpeculativeTurnTracker,
cancel_scope: CancelScope,
pipeline_index: int,
resource_ledger: list[Any] | None = None,
) -> list[Any]:
"""Build a handler chain: VAD → STT/AudioInput → LM → TTS."""
from speech_to_speech.LLM.lm_output_processor import LMOutputProcessor
vad = VADHandler(
stop_event,
queue_in=recv_audio_chunks_queue,
queue_out=spoken_prompt_queue,
setup_args=(should_listen,),
setup_kwargs={
**{
config_field.name: deepcopy(getattr(vad_handler_kwargs, config_field.name))
for config_field in fields(vad_handler_kwargs)
},
"text_output_queue": text_output_queue,
"speculative_turns": speculative_turns,
},
)
if resource_ledger is not None:
resource_ledger.append(vad)
# Loading Silero sets PyTorch to one thread for the whole process. Re-apply an explicit
# --torch_num_threads after every VAD build, before the other models load and warm up.
apply_torch_num_threads(module_kwargs)
side_handlers: list[Any] = []
if module_kwargs.diarization_model_name:
from speech_to_speech.diarization import StreamingDiarizer
from speech_to_speech.diarization.streaming import DIARIZATION_DEVICES
from speech_to_speech.diarization.worker import DiarizationWorker
diarization_device = resolve_device(
module_kwargs.device or module_kwargs.diarization_device,
DIARIZATION_DEVICES,
"Nemotron diarization",
)
if diarization_device == "cpu":
logger.warning(
"Diarization is using CPU; sustained speech can outpace inference and disable speaker labels "
"until reconnect. CUDA or MPS is recommended for live sessions."
)
diarizer = StreamingDiarizer.from_pretrained(
module_kwargs.diarization_model_name,
revision=module_kwargs.diarization_revision,
device=diarization_device,
dtype=module_kwargs.diarization_dtype,
streaming_mode=module_kwargs.diarization_streaming_mode,
threshold=module_kwargs.diarization_threshold,
)
if resource_ledger is not None:
resource_ledger.append(diarizer)
if diarizer.sample_rate != vad_handler_kwargs.sample_rate:
raise ValueError("Diarization and VAD must use the same audio sample rate.")
diarizer.warmup()
logger.info(
"Diarization ready: device=%s mode=%s; speaker labels will accompany completed transcriptions",
diarization_device,
module_kwargs.diarization_streaming_mode,
)
vad.diarization_worker = DiarizationWorker(diarizer, stop_event)
if resource_ledger is not None:
# The worker takes ownership after all model preparation succeeds.
resource_ledger.remove(diarizer)
resource_ledger.append(vad.diarization_worker)
side_handlers.append(vad.diarization_worker)
needs_notifier = not stt_backend.spec.capabilities.bypasses_transcription_notifier
stt_queue_out: Queue[Any] = stt_output_queue if needs_notifier else text_prompt_queue
stt_context = HandlerContext(
stop_event=stop_event,
queue_in=spoken_prompt_queue,
queue_out=stt_queue_out,
text_output_queue=text_output_queue,
should_listen=should_listen,
cancel_scope=cancel_scope,
speculative_turns=speculative_turns,
pipeline_index=pipeline_index,
sample_rate=vad_handler_kwargs.sample_rate,
enable_live_transcription=module_kwargs.enable_live_transcription,
live_transcription_update_interval=module_kwargs.live_transcription_update_interval,
)
stt_handler = create_backend_handler(stt_backend, stt_context)
if resource_ledger is not None:
resource_ledger.append(stt_handler)
if stt_backend.spec.capabilities.streams_audio_chunks:
vad.streaming_stt_sink = stt_handler
speech_input_handlers = [stt_handler]
if needs_notifier:
transcription_notifier = TranscriptionNotifier(
stop_event,
queue_in=stt_output_queue,
queue_out=text_prompt_queue, # type: ignore[arg-type]
setup_kwargs={
"text_output_queue": text_output_queue,
"should_listen": should_listen,
},
)
if resource_ledger is not None:
resource_ledger.append(transcription_notifier)
speech_input_handlers.append(transcription_notifier)
def handler_context(queue_in: Queue[Any], queue_out: Queue[Any]) -> HandlerContext:
return HandlerContext(
stop_event=stop_event,
queue_in=queue_in,
queue_out=queue_out,
text_output_queue=text_output_queue,
should_listen=should_listen,
cancel_scope=cancel_scope,
speculative_turns=speculative_turns,
pipeline_index=pipeline_index,
sample_rate=vad_handler_kwargs.sample_rate,
enable_live_transcription=module_kwargs.enable_live_transcription,
live_transcription_update_interval=module_kwargs.live_transcription_update_interval,
detect_llm_output_language=module_kwargs.detect_llm_output_language,
)
lm_context = handler_context(text_prompt_queue, lm_response_queue)
lm = create_backend_handler(
llm_backend,
lm_context,
)
if resource_ledger is not None:
resource_ledger.append(lm)
lm_processor = LMOutputProcessor(
stop_event,
queue_in=lm_response_queue,
queue_out=lm_processed_queue,
setup_kwargs={
"speculative_turns": speculative_turns,
"text_output_queue": text_output_queue,
"detect_llm_output_language": module_kwargs.detect_llm_output_language,
},
)
if resource_ledger is not None:
resource_ledger.append(lm_processor)
tts_output_queue: Queue[AudioOutItem] = Queue() if module_kwargs.enable_visemes else send_audio_chunks_queue
tts_context = handler_context(lm_processed_queue, tts_output_queue)
tts = create_backend_handler(
tts_backend,
tts_context,
)
if resource_ledger is not None:
resource_ledger.append(tts)
handlers = [vad, *side_handlers, *speech_input_handlers, lm, lm_processor, tts]
if module_kwargs.enable_visemes:
from speech_to_speech.STV.w2v_stv_handler import Wav2Vec2STVHandler
handlers.append(
Wav2Vec2STVHandler(
stop_event,
queue_in=tts_output_queue,
queue_out=send_audio_chunks_queue,
setup_kwargs={
"model_name": module_kwargs.stv_model_name,
"device": module_kwargs.device or module_kwargs.stv_device,
"cancel_scope": cancel_scope,
},
)
)
if resource_ledger is not None:
resource_ledger.append(handlers[-1])
return handlers
def _stt_session_languages(selection: BackendSelection, handler: Any) -> set[str] | None:
if selection.name == "nemotron-streaming" and getattr(handler, "_is_farsi", False):
return {"fa"}
if selection.name == "faster-whisper":
supported = getattr(getattr(handler, "model", None), "supported_languages", None)
return set(supported) if supported is not None else None
if selection.name == "whisper":
generation_config = getattr(getattr(handler, "model", None), "generation_config", None)
# Transformers rejects any language argument for an English-only checkpoint.
return set() if getattr(generation_config, "is_multilingual", None) is False else None
if selection.name == "qwen3-asr":
return set(modules[type(handler).__module__].SUPPORTED_LANGUAGES)
if selection.name in {"parakeet-tdt", "parakeet-unified", "paraformer", "openai-realtime", "vllm-realtime"}:
return set()
return None
def _build_pipeline_unit(
*,
index: int,
stop_event: Event,
module_kwargs: ModuleArguments,
vad_handler_kwargs: VADHandlerArguments,
stt_backend: BackendSelection,
llm_backend: BackendSelection,
tts_backend: BackendSelection,
resource_ledger: list[Any] | None = None,
) -> "PipelineUnit":
"""Build one isolated pipeline with its own state and queues.
Returns a PipelineUnit that lives inside RealtimeServer's pool. Handler instances
are returned in `unit.handlers`; the caller threads them via ThreadManager. No uvicorn
is created here — the single server is owned by RealtimeServer.
"""
from speech_to_speech.api.openai_realtime.service import RealtimeService
# Per-unit copies isolate any setup-time mutation performed by third-party libraries.
vad_kw = deepcopy(vad_handler_kwargs)
stt_selection = stt_backend.copy_for_pipeline()
llm_selection = llm_backend.copy_for_pipeline()
tts_selection = tts_backend.copy_for_pipeline()
should_listen = Event()
response_playing = Event()
cancel_scope = CancelScope()
speculative_turns = SpeculativeTurnTracker()
turn_latency_store = TurnLatencyStore()
speculative_turns.wait_observer = turn_latency_store.record_smart_wait
recv_audio_chunks_queue: Queue[AudioInItem] = Queue()
send_audio_chunks_queue: Queue[AudioOutItem] = Queue()
spoken_prompt_queue: Queue[VADOutItem] = Queue()
stt_output_queue: Queue[STTOutItem] = Queue()
text_prompt_queue: Queue[TextPromptItem] = Queue()
lm_response_queue: Queue[LMOutItem] = Queue()
lm_processed_queue: Queue[TTSInItem] = Queue()
text_output_queue: Queue[TextEventItem] = Queue()
chat_size = llm_selection.config.get("chat_size", 10)
default_instructions = llm_selection.config.get("init_chat_prompt")
service = RealtimeService(
text_prompt_queue=text_prompt_queue,
should_listen=should_listen,
chat_size=chat_size,
speculative_turns=speculative_turns,
turn_latency_store=turn_latency_store,
default_instructions=default_instructions,
)
if module_kwargs.enable_live_transcription and not stt_selection.spec.capabilities.streams_audio_chunks:
vad_kw.enable_realtime_transcription = True
vad_kw.realtime_processing_pause = module_kwargs.live_transcription_update_interval
handlers = _build_handlers(
stop_event=stop_event,
should_listen=should_listen,
recv_audio_chunks_queue=recv_audio_chunks_queue,
spoken_prompt_queue=spoken_prompt_queue,
stt_output_queue=stt_output_queue,
text_prompt_queue=text_prompt_queue,
lm_response_queue=lm_response_queue,
lm_processed_queue=lm_processed_queue,
send_audio_chunks_queue=send_audio_chunks_queue,
text_output_queue=text_output_queue,
module_kwargs=module_kwargs,
vad_handler_kwargs=vad_kw,
stt_backend=stt_selection,
llm_backend=llm_selection,
tts_backend=tts_selection,
speculative_turns=speculative_turns,
cancel_scope=cancel_scope,
pipeline_index=index,
**({"resource_ledger": resource_ledger} if resource_ledger is not None else {}),
)
for h in handlers:
h.pipeline_index = index
h.turn_latency_store = turn_latency_store
# Validate only against language sets already known to the active backends.
# Faster Whisper reports the loaded checkpoint's actual language set.
service.stt_supported_languages = _stt_session_languages(stt_selection, handlers[1])
setup_language = stt_selection.config.get("language")
service.stt_auto_reset_supported = not (
stt_selection.name == "openai-realtime" and isinstance(setup_language, str) and bool(setup_language.strip())
)
tts_handler = handlers[-2] if module_kwargs.enable_visemes else handlers[-1]
tts_module = modules[type(tts_handler).__module__]
if tts_selection.name == "kokoro":
service.tts_supported_languages = {"en", "ja", "zh", "fr", "es", "it", "pt", "hi"}
elif tts_selection.name == "facebookMMS":
service.tts_supported_languages = set(tts_module.WHISPER_LANGUAGE_TO_FACEBOOK_LANGUAGE)
elif tts_selection.name == "supertonic":
service.tts_supported_languages = set(tts_module.SUPERTONIC_LANGUAGE_CODES)
elif tts_selection.name == "qwen3":
service.tts_supported_languages = {code for code in tts_module.QWEN3_LANGUAGE_ALIASES if len(code) == 2}
elif tts_selection.name in {"chatTTS", "pocket"}:
service.tts_supported_languages = set()
return PipelineUnit(
index=index,
service=service,
cancel_scope=cancel_scope,
should_listen=should_listen,
response_playing=response_playing,
input_queue=recv_audio_chunks_queue,
output_queue=send_audio_chunks_queue,
text_output_queue=text_output_queue,
text_prompt_queue=text_prompt_queue,
handlers=handlers,
)
def build_pipeline(
args: ParsedArguments,
stop_event: Event,
*,
host: str | None = None,
) -> ThreadManager:
"""Build a pool of pipeline units behind one server."""
from speech_to_speech.api.openai_realtime.server import RealtimeServer
module_kwargs = args.module_kwargs
pool = [
_build_pipeline_unit(
index=index,
stop_event=stop_event,
module_kwargs=module_kwargs,
vad_handler_kwargs=args.vad_handler_kwargs,
stt_backend=args.stt_backend,
llm_backend=args.llm_backend,
tts_backend=args.tts_backend,
)
for index in range(module_kwargs.num_pipelines)
]
server = RealtimeServer(
stop_event=stop_event,
pool=pool,
host=host or args.realtime_server_kwargs.host,
port=args.realtime_server_kwargs.port,
llm_proxy_config=(
build_llm_proxy_config(module_kwargs, args.llm_backend) if module_kwargs.enable_llm_proxy else None
),
)
handlers: list[Any] = []
for unit in pool:
handlers.extend(unit.handlers)
handlers.append(server)
return ThreadManager(handlers)
def build_local_pipeline(args: ParsedArguments, stop_event: Event) -> ThreadManager:
"""Compose the canonical server and audio client over a forced loopback URL."""
from speech_to_speech.api.openai_realtime.audio_client import (
RealtimeAudioClient,
RealtimeAudioClientConfig,
load_realtime_tool_module,
)
local_audio = args.local_audio_kwargs
playback_buffer_ms = local_audio.local_audio_playback_buffer_ms
if playback_buffer_ms is None:
playback_buffer_ms = OPENAI_TTS_PLAYBACK_BUFFER_MS if args.tts_backend.name == "openai" else 0.0
tools: list[dict[str, Any]] = []
tool_executor = None
tool_response_create = True
if local_audio.local_audio_tool_module:
tools, tool_executor, tool_response_create = load_realtime_tool_module(local_audio.local_audio_tool_module)
server_manager = build_pipeline(args, stop_event, host="127.0.0.1")
client = RealtimeAudioClient(
stop_event,
RealtimeAudioClientConfig(
url=f"ws://127.0.0.1:{args.realtime_server_kwargs.port}/v1/realtime",
api_key="local",
chunk_size=local_audio.local_audio_chunk_size,
playback_buffer_ms=playback_buffer_ms,
input_device=local_audio.local_audio_input_device,
output_device=local_audio.local_audio_output_device,
print_json=local_audio.local_audio_print_json,
block_mic_during_playback=local_audio.local_audio_block_mic_during_playback,
tools=tools,
tool_executor=tool_executor,
tool_response_create=tool_response_create,
),
)
return ThreadManager([*server_manager.handlers, client])
def run_pipeline_command(command: Literal["serve", "local"], argv: Sequence[str]) -> None:
"""Run the server alone or compose it with the loopback audio client."""
args = parse_arguments(argv, command=command)
setup_logger(args.module_kwargs.log_level)
# Set the transcript gate and warn before any conversation is processed, so an operator
# sees the notice ahead of the first turn rather than after content is already logged.
set_log_transcripts(args.module_kwargs.log_transcripts)
warn_if_log_transcripts_enabled()
if args.module_kwargs.num_pipelines < 1:
raise ValueError(f"--num_pipelines must be >= 1, got {args.module_kwargs.num_pipelines}")
prepare_all_args(args)
# On Apple Silicon, all MLX inference serializes through a global lock (utils/mlx_lock.py).
# The progressive STT path uses a short timeout and drops work under contention, producing
# a flood of warnings without affecting final transcripts. With a pool, pre-emptively turn
# it off so logs stay readable; the final STT path is unaffected. Non-darwin platforms
# don't share this lock, so leave their live transcription alone.
if args.module_kwargs.num_pipelines > 1 and platform == "darwin" and args.module_kwargs.enable_live_transcription:
logger.info(
"MLX contention: --num_pipelines=%d > 1 on Apple Silicon → disabling live transcription "
"(progressive STT contends on the global MLX lock)",
args.module_kwargs.num_pipelines,
)
args.module_kwargs.enable_live_transcription = False
stop_event = Event()
pipeline_manager = (
build_local_pipeline(args, stop_event) if command == "local" else build_pipeline(args, stop_event)
)
# Set up graceful shutdown handler
shutdown_requested = [False] # Use list for nonlocal mutation
def signal_handler(_sig: int, _frame: Optional[FrameType]) -> None:
if not shutdown_requested[0]:
shutdown_requested[0] = True
console.print("\n[yellow]Shutting down gracefully...[/yellow]")
pipeline_manager.stop()
console.print("[green]✓ Pipeline stopped successfully[/green]")
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
try:
pipeline_manager.start()
pipeline_manager.wait()
except KeyboardInterrupt:
if not shutdown_requested[0]:
console.print("\n[yellow]Shutting down gracefully...[/yellow]")
pipeline_manager.stop()
console.print("[green]✓ Pipeline stopped successfully[/green]")
def main() -> None:
"""Compatibility entry point for direct module execution."""
from speech_to_speech.cli import main as cli_main
cli_main()
if __name__ == "__main__":
main()