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:
@@ -0,0 +1,17 @@
|
||||
# Dependency resolution and the base digest are explicit preparation gates.
|
||||
# See README.md; this Dockerfile does not fetch weights or use an operational image.
|
||||
ARG ENGINE_BASE_IMAGE
|
||||
FROM ${ENGINE_BASE_IMAGE}
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
|
||||
WORKDIR /app
|
||||
COPY .local-s2s-build/requirements.lock /build/requirements.lock
|
||||
RUN pip install --no-cache-dir --require-hashes -r /build/requirements.lock
|
||||
COPY .local-s2s-build/upstream /opt/speech-to-speech
|
||||
RUN pip install --no-deps --no-build-isolation /opt/speech-to-speech
|
||||
COPY pyproject.toml alembic.ini /app/
|
||||
COPY app /app/app
|
||||
COPY services/local_s2s /app/services/local_s2s
|
||||
COPY migrations /app/migrations
|
||||
COPY .local-s2s-build/build-manifest.json /app/engine-build-manifest.json
|
||||
RUN pip install --no-deps --no-build-isolation -e /app
|
||||
CMD ["python", "-m", "services.local_s2s.engine", "--allow-paid-startup"]
|
||||
@@ -0,0 +1,17 @@
|
||||
**
|
||||
!pyproject.toml
|
||||
!alembic.ini
|
||||
!app/
|
||||
!app/**
|
||||
!migrations/
|
||||
!migrations/**
|
||||
!services/
|
||||
!services/local_s2s/
|
||||
!services/local_s2s/**
|
||||
!.local-s2s-build/
|
||||
!.local-s2s-build/**
|
||||
**/.git
|
||||
**/.venv
|
||||
**/__pycache__
|
||||
**/.env
|
||||
**/*.pyc
|
||||
@@ -0,0 +1,298 @@
|
||||
# Phase 2 local engine (development only)
|
||||
|
||||
This stack is isolated from operational OpenAI. Phase 1 live acceptance is still
|
||||
pending. Do not activate this candidate until that prerequisite is accepted and
|
||||
a bounded live run is authorized. Offline tests do not prove real Persian voice.
|
||||
|
||||
## Offline result now
|
||||
|
||||
From the repository root:
|
||||
|
||||
```powershell
|
||||
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py -q -p no:cacheprovider
|
||||
.venv/Scripts/python -m app.local_s2s_smoke --output temp/local-s2s-stub.wav
|
||||
```
|
||||
|
||||
Use a fresh output name when re-running. Play the WAV in any audio player. It is
|
||||
an explicit 440 Hz **test tone**, not synthesized Persian. No network or paid
|
||||
requests occur in stub mode. Both multipart and JSON STT framing are covered by
|
||||
HTTP fixtures. `--live` is a separate opt-in and never a health check.
|
||||
|
||||
## Build preparation (not executed in this checkpoint)
|
||||
|
||||
1. Obtain an authorized clean source checkout at
|
||||
`619e3fe4f71d1c6f35c15870d588a3638de34722`. Obtain a Python 3.11 slim **registry
|
||||
digest** and a separately provisioned local Silero source/model bundle. The
|
||||
launcher refuses remote Torch Hub model loading and disables Smart Turn.
|
||||
2. Prepare immutable source/dependency inputs:
|
||||
|
||||
```powershell
|
||||
.venv/Scripts/python services/local_s2s/prepare_build.py --checkout <clean-upstream-checkout> --base-image python:3.11-slim@sha256:<registry-digest>
|
||||
```
|
||||
|
||||
3. In an authorized dependency-resolution environment with `uv` installed, create
|
||||
a Linux hash lock; do not resolve it from the Windows virtualenv:
|
||||
|
||||
```text
|
||||
uv pip compile .local-s2s-build/requirements.in --python-version 3.11 --python-platform x86_64-unknown-linux-gnu --generate-hashes -o .local-s2s-build/requirements.lock
|
||||
```
|
||||
|
||||
Review dependency size/licensing and CPU PyTorch selection before installing.
|
||||
Source pinning alone is not a dependency lock. No lock/base digest is claimed
|
||||
in this checkpoint. Keep the resolved lock and resulting image digest as
|
||||
evaluation provenance. The recipe installs hashes and performs no weight fetch.
|
||||
4. Build the separate image (after build/download authorization):
|
||||
|
||||
```text
|
||||
docker build -f services/local_s2s/Dockerfile --build-arg ENGINE_BASE_IMAGE=python:3.11-slim@sha256:<same-digest> -t rag-local-s2s-candidate:phase2 .
|
||||
```
|
||||
|
||||
A Dockerfile-specific ignore file excludes `.env`, operational data and tests.
|
||||
The same image runs the separate engine and application API. The engine receives
|
||||
no database credential or application identity. No operational image is rebuilt.
|
||||
|
||||
## Activation and browser demonstration (still pending)
|
||||
|
||||
Use **only** `docker-compose.local-s2s-test.yml`; it never extends the operational
|
||||
Compose file. `docker compose ... config --quiet` is a safe syntax check; do not
|
||||
print rendered configuration when secrets are set.
|
||||
|
||||
Set explicit model/voice identities and a preprovisioned VAD path. Current catalogue
|
||||
inspection found `openai/whisper-large-v3` and `openai/gpt-4.1-mini`. The configured
|
||||
TTS candidate is `google/gemini-3.8-flash-lite-tts`, voice `Kore`; its Persian quality
|
||||
and 24 kHz PCM compatibility have not been measured. OpenAI TTS IDs were absent
|
||||
from the observed speech catalogue. Do not silently fall back if a model fails.
|
||||
|
||||
`LOCAL_S2S_ENABLE_CANDIDATE=true` enables the development API. Set
|
||||
`LOCAL_S2S_ALLOW_PAID_STARTUP=true` **only after authorization**: upstream STT, LLM
|
||||
and TTS initialization can make paid warmup/probe requests. Their counts are printed
|
||||
at startup/close. They are separate from the smoke command's three requests.
|
||||
`OPENROUTER_API_KEY` belongs only in the engine process environment; an optional
|
||||
`LOCAL_S2S_TOKEN` authenticates API-to-engine access and must match both services.
|
||||
Never put keys in a profile, command-line argument, browser or committed file.
|
||||
|
||||
After the gates above:
|
||||
|
||||
```text
|
||||
docker compose -f docker-compose.local-s2s-test.yml up -d candidate_db candidate_migrations local-s2s-engine candidate_api
|
||||
docker compose -f docker-compose.local-s2s-test.yml exec -it candidate_api python -m app.bootstrap --organization-name Local-S2S-Test --username local-s2s-admin --assistant-name Local-S2S-Test --instruction "Answer briefly in Persian"
|
||||
```
|
||||
|
||||
Bootstrap prompts for a **new test-only password**. It does not copy an operational
|
||||
account. API URL: `http://127.0.0.2:8091`; use a fresh browser profile. Repoint the
|
||||
existing Angular client's backend/proxy to this isolated URL using its own checkout's
|
||||
configuration. That Angular source is not present in this repository, so no
|
||||
frontend build/repointing was performed here. Ensure the browser uses the trusted
|
||||
Origin `http://127.0.0.2:8091`, or configure the explicit isolated frontend Origin
|
||||
and Host in the candidate only. Cookies are not isolated by port.
|
||||
|
||||
The configured embedding endpoint deliberately refuses inference: this is a
|
||||
**greeting/transport-only** candidate, not a RAG quality demo. It cannot reuse
|
||||
operational documents, sessions or calibrated search credentials. Phase 3 owns
|
||||
shared RAG acceptance and exact interruption repair. Until then, interruption
|
||||
requiring cleanup closes the local session; it does not continue unsafely.
|
||||
|
||||
For a separately consented real-stage WAV (three requests, no automatic retries):
|
||||
|
||||
```text
|
||||
python -m app.local_s2s_smoke --live --input <consented-mono24k-PCM16.wav> --output <new-evaluation.wav> --save-evaluation-audio
|
||||
```
|
||||
|
||||
The input is limited to 10 seconds, the LLM to 128 output tokens/300 answer
|
||||
characters, and retained PCM to 10 seconds. Stream cutoff bounds local data;
|
||||
it cannot prove remote compute/billing stopped. Meter actual usage separately.
|
||||
No default conversation logging or automatic speech artifact collection exists.
|
||||
|
||||
## Limits and provenance
|
||||
|
||||
One initialized pipeline; final-only STT; 10-second VAD segments; bounded pipeline
|
||||
queues (256 items each, overflow stops the candidate); component gateway admits
|
||||
at most three requests with four pending sockets; request/response byte bounds
|
||||
are in `components.py`; HTTP deadline defaults to 30 seconds; no SDK/transport
|
||||
retry. Partial/oversized streams omit the final HTTP chunk so consumers observe
|
||||
failure. Component startup counts are not a monetary cost measurement.
|
||||
|
||||
The extension confirms component identities from initialized handlers and projects
|
||||
post-application native session state onto the setup contract. It never treats a
|
||||
request echo as proof of active global models. Credentials must be configured and
|
||||
startup probes succeed before admission. A configuration mismatch prevents setup;
|
||||
no history receipt is fabricated. Engine construction/conformance against the real
|
||||
pinned dependencies remains unexecuted and may reveal compatibility repairs.
|
||||
|
||||
Stop only this candidate with `docker compose -f docker-compose.local-s2s-test.yml stop`.
|
||||
Do not run `compose down`, delete volumes or stop/rebuild either preserved OpenAI
|
||||
container. A candidate container rollback is not a data rollback.
|
||||
|
||||
|
||||
## Phase 2 repair checkpoint: extension v2
|
||||
|
||||
`rag-local-s2s-phase2-v2` changes the local extension behavior. New profiles pin
|
||||
v2; existing v1 reservations are never rewritten and cannot silently use v2.
|
||||
The private browser PCM/events, canonical retrieval, identities and unsupported
|
||||
interruption policy are unchanged. No live acceptance or deployment switch occurred.
|
||||
|
||||
The request client policy is installed **before handler construction**. It puts
|
||||
`max_tokens=LOCAL_S2S_MAX_OUTPUT_TOKENS` on every Chat Completions request, including
|
||||
normal STT-derived text turns and the constructor's warmup, and forces zero retries
|
||||
even when pinned warmup asks `with_options(max_retries=6)` (see the provenance
|
||||
correction below; the earlier isolated harness supplied 10). The configured request
|
||||
deadline also enters the actual base setup before warmup; attestation reads the
|
||||
active client policy, not `gen_kwargs` (unused by that upstream text path).
|
||||
|
||||
Provision tokenizer assets in a separate, explicitly authorized staging environment.
|
||||
Copy unpacked `punkt_tab` English data and `averaged_perceptron_tagger_eng` into
|
||||
`LOCAL_S2S_NLTK_SOURCE`. Required relative files:
|
||||
|
||||
- `tokenizers/punkt_tab/english/{abbrev_types.txt,collocations.tab,sent_starters.txt,ortho_context.tab}`
|
||||
- `taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.{weights,classes,tagdict}.json`
|
||||
|
||||
The local Silero bundle must contain `hubconf.py`,
|
||||
`src/silero_vad/data/silero_vad.jit`, and all source files its hub entry point uses.
|
||||
The whole supplied bundle is fingerprinted. No symlinks or unlisted extra files
|
||||
are accepted (Git metadata and Python caches are ignored). Neither this repair
|
||||
nor engine startup downloads any of these resources. Original NLTK sentence/POS
|
||||
functions are retained; there is no fallback tokenizer.
|
||||
|
||||
Fingerprint already-provisioned local assets, placing the manifest outside both roots:
|
||||
|
||||
```text
|
||||
python -m services.local_s2s.assets --nltk-root <unpacked-nltk-data> --vad-root <local-silero-bundle> --output <new-assets.json>
|
||||
```
|
||||
|
||||
Review/archive the printed SHA-256 and manifest, then set the three Compose host
|
||||
path variables and `LOCAL_S2S_ASSET_MANIFEST_SHA256`. The engine mounts the resources
|
||||
at `/assets/nltk`, `/vad/silero-vad`, and manifest `/assets/assets.json`, read-only.
|
||||
Preflight verifies every file and the expected manifest SHA, then actually loads
|
||||
NLTK sentence/POS resources **before the gateway or paid probes exist**. Missing,
|
||||
corrupt or unusable assets produce `LOCAL_ENGINE_ASSET_VALIDATION_FAILED` and zero
|
||||
provider calls. Runtime NLTK downloader entry points are blocked. Build preparation
|
||||
removes upstream's import-time download blocks and replaces them with local
|
||||
validation. Previously prepared build inputs must be freshly prepared for v2;
|
||||
do not reuse an old v1 source tree/image under the new revision.
|
||||
|
||||
Gateway bounds now start at connection acceptance. At most three connections own
|
||||
slots; headers are capped at 16 KiB and must finish within `min(5 s, total)`. Body
|
||||
reads, upstream headers/reads and downstream drains have that same inactivity
|
||||
bound. A separate total deadline (default 30 s) covers the entire exchange;
|
||||
small trickled SSE/PCM is forwarded without 8192-byte accumulation and cannot
|
||||
extend it. Unsupported content encoding fails before decoding. On timeout or
|
||||
disconnect, the downstream socket closes immediately, upstream work is cancelled,
|
||||
and closure has at most a further 0.5 s per owned transport. Failed partial
|
||||
responses omit the terminating HTTP chunk, so consumers observe an incomplete stream.
|
||||
Local cancellation is not proof that remote inference/billing stopped.
|
||||
|
||||
Construction/probes have a 90 s owner deadline; the asset fingerprint walk has a
|
||||
30 s check budget, 4096 files and 512 MiB total limits. Probe counters count one
|
||||
admitted attempt even on provider failure. Runtime stop, gateway shutdown, socket
|
||||
close and joining are independently guarded (2 s each); a stop exception or hang
|
||||
cannot skip later cleanup or the final numeric counters. Nonzero cleanup outcomes
|
||||
fail the process. SIGINT/SIGTERM handlers signal the owned stop event and previous
|
||||
handlers are restored. Pinned upstream `wait()` can itself call `stop()` and raise;
|
||||
the independent final cleanup still runs in that case.
|
||||
|
||||
Offline repair conformance (no providers/models/dependency installs):
|
||||
|
||||
```text
|
||||
python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider
|
||||
```
|
||||
|
||||
The harness executes hash-checked pinned setup, normal text `process`, request,
|
||||
warmup and stop methods with isolated I/O/history dependencies. Outgoing HTTPX JSON
|
||||
payloads and attempt counts are inspected. This is stronger than attribute-only
|
||||
fixtures, but the complete OpenAI SDK/ML engine image remains unbuilt/unverified.
|
||||
Windows signal tests dispatch the installed handlers; they do not claim OS-level
|
||||
POSIX signal delivery. Real engine, component audio and isolated Persian browser
|
||||
greeting/transcripts/normal close evidence are still required for live acceptance.
|
||||
|
||||
|
||||
## Phase 2 remaining repairs: extension v3
|
||||
|
||||
Current behavior is `rag-local-s2s-phase2-v3`, with the v1 private contract shape.
|
||||
Fresh profiles and prepared build manifests use v3; v1/v2 reservations remain
|
||||
frozen and fail revision mismatch instead of being rewritten. Preserve earlier
|
||||
build inputs and prepare a fresh workspace for v3. The five v2 repairs remain.
|
||||
No browser events, PCM24k, retrieval authority or interruption capability changed.
|
||||
|
||||
After the complete request body, an owned downstream watcher runs concurrently
|
||||
with upstream header acquisition and streaming. It does not need response data
|
||||
or a failed write to notice closure. Ordinary downstream EOF/reset cancels the
|
||||
upstream operation. Response/client closure and task joining share a **one-second
|
||||
cleanup window**, followed by slot release; stalled close operations are cancelled
|
||||
and the downstream transport is aborted when that window expires. Existing total
|
||||
and inactivity limits remain. Failed partial responses never gain a successful
|
||||
terminal HTTP chunk. Cancellation does not prove remote inference/billing stopped.
|
||||
|
||||
TCP FIN alone cannot reveal whether a peer fully closed or only called SHUT_WR.
|
||||
The private component gateway therefore defines the following explicit policy:
|
||||
|
||||
- Ordinary clients keep their send side open until completion. EOF is cancellation
|
||||
by contract, even when that peer could still receive. SDK requests follow this path.
|
||||
- A client intentionally stopping its send side while retaining its receive side
|
||||
must send `X-Local-S2S-Half-Close: receive-response` before the body. After a complete
|
||||
body, FIN then allows the bounded response to finish. A reset/transport error still
|
||||
cancels. A subsequent graceful full close is indistinguishable from the declared
|
||||
half-close and remains bounded by the original request deadlines.
|
||||
- Other header values fail before provider admission; extra request bytes/pipelining
|
||||
are unsupported. The half-close header is private, is not forwarded upstream and
|
||||
does not change the browser protocol. The gateway closes its send side at completion.
|
||||
|
||||
Real loopback tests exercise both downstream and upstream TCP sockets for disconnect
|
||||
before headers and after headers with no further upstream output. They assert local
|
||||
upstream socket closure, HTTP transport closure and slot release within the cleanup
|
||||
window plus scheduling tolerance, before the five-second test request deadline.
|
||||
Separate tests cover normal success, declared half-close success, undeclared FIN
|
||||
cancellation and a stalled transport close. They require no external services.
|
||||
|
||||
The local identifier validator now has a distinct method name so VoiceSettings
|
||||
inherits it alongside its existing OpenAI/Gemini validator. All four local model/
|
||||
voice fields reject whitespace, controls and non-ASCII before assets, construction
|
||||
or probes. Valid identifiers and existing provider validation are retained.
|
||||
|
||||
Provenance correction: the hash-checked pinned `base.py.source` defines
|
||||
`WARMUP_MAX_RETRIES = 6` at line 66; Chat Completions imports that constant. The v2
|
||||
harness injected 10 as an isolated override and incorrectly described it as the
|
||||
pinned value. Its historical 31/107/242 execution results remain unchanged, but
|
||||
that description was wrong. Current warmup tests read 6 from the verified source
|
||||
AST and test both retryable HTTP and connection failures with exactly one attempt.
|
||||
The full OpenAI SDK/ML engine still has not been executed.
|
||||
|
||||
Final offline checks for v3: **74 repair, 107 combined and 242 preservation tests
|
||||
passed**, using `-p no:cacheprovider`. Compose configuration validation and
|
||||
`git diff --check` passed. Exact commands/timings and the scoped patch are in the
|
||||
[Phase 2 report](../../docs/evaluation/local-s2s/phase-02.md#remaining-defect-repair-checkpoint-extension-v3).
|
||||
No paid calls, downloads, image builds, operational changes or PostgreSQL acceptance
|
||||
were performed here. Phase 2 remains in_progress/live acceptance pending until
|
||||
real-engine, component-audio and isolated Persian browser greeting/transcripts/
|
||||
normal-close evidence exists, alongside the existing Phase 1 prerequisite.
|
||||
|
||||
|
||||
## Acceptance runbook and newly located resources
|
||||
|
||||
See the [acceptance checklist](../../docs/evaluation/local-s2s/phase-02-acceptance-checklist.md)
|
||||
for exact preparation/live commands, isolation boundaries, proposed request ceilings,
|
||||
stop rules and actual outcomes. The checklist separates already authorized offline
|
||||
preparation/DB tests from unapproved downloads/builds/paid calls; its examples are
|
||||
not permission. v3 implementation and behavior are unchanged.
|
||||
|
||||
A 201-file local NLTK/Silero manifest now exists, SHA-256
|
||||
`8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8`.
|
||||
NLTK 3.10.3 sentence/POS loading passed in the existing sibling Windows environment
|
||||
with downloads blocked. These host assets still need review and Linux validation.
|
||||
The immutable Linux Python base is cached; full pinned source, reviewed dependency
|
||||
lock and candidate image are still absent. Do not use the dirty sibling engine
|
||||
checkout at a different revision as a substitute.
|
||||
|
||||
The sibling Angular checkout was located at
|
||||
`D:/raymand/projects/faq_chatbot_frontend`; its original LAN proxy/package edit were
|
||||
preserved. The prepared browser override uses Origin http://127.0.0.2:4201 and a
|
||||
separate proxy file, retaining same-origin browser API/WS calls. Nothing was launched.
|
||||
The Phase 1 override can run changed API source read-only on a cached immutable
|
||||
image using isolated candidate DB/storage and masked inherited data, without an
|
||||
engine build. Actual OpenAI listening still requires bounded live consent.
|
||||
|
||||
Fresh DB checks: 2 local passed; expanded 57 passed/6 existing baseline failures,
|
||||
all with --require-postgres against a verified disposable DB. The guarded runner
|
||||
restored its stopped state. No runtime assertion was relaxed. Phase 2 remains
|
||||
NOT ACCEPTED until complete engine/SDK/POSIX, component audio and Persian browser
|
||||
evidence exists along with Phase 1 acceptance. There were no paid calls, downloads,
|
||||
image builds or operational changes in this preparation checkpoint.
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Preflight local tokenizer/VAD resources. No runtime downloader is permitted."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
REQUIRED_NLTK = (
|
||||
'tokenizers/punkt_tab/english/abbrev_types.txt',
|
||||
'tokenizers/punkt_tab/english/collocations.tab',
|
||||
'tokenizers/punkt_tab/english/sent_starters.txt',
|
||||
'tokenizers/punkt_tab/english/ortho_context.tab',
|
||||
'taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.weights.json',
|
||||
'taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.classes.json',
|
||||
'taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.tagdict.json',
|
||||
)
|
||||
REQUIRED_VAD = ('hubconf.py', 'src/silero_vad/data/silero_vad.jit')
|
||||
|
||||
|
||||
class AssetError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def validate_assets(nltk_root, vad_root, manifest_path):
|
||||
try:
|
||||
roots = {'nltk': Path(nltk_root).resolve(strict=True), 'vad': Path(vad_root).resolve(strict=True)}
|
||||
manifest_path = Path(manifest_path)
|
||||
if manifest_path.stat().st_size > 1048576:
|
||||
raise ValueError()
|
||||
manifest_bytes = manifest_path.read_bytes()
|
||||
manifest = json.loads(manifest_bytes)
|
||||
if not isinstance(manifest, dict) or not isinstance(manifest.get('files'), dict):
|
||||
raise ValueError()
|
||||
files = manifest['files']
|
||||
required = {'nltk/' + p for p in REQUIRED_NLTK} | {'vad/' + p for p in REQUIRED_VAD}
|
||||
if manifest['schema'] != 1 or not required <= files.keys() or not 0 < len(files) <= 4096:
|
||||
raise ValueError()
|
||||
found = set()
|
||||
deadline = time.monotonic() + 30
|
||||
total = 0
|
||||
for kind, root in roots.items():
|
||||
for path in root.rglob('*'):
|
||||
if time.monotonic() >= deadline:
|
||||
raise ValueError()
|
||||
if '.git' in path.parts or '__pycache__' in path.parts:
|
||||
continue
|
||||
if path.is_symlink():
|
||||
raise ValueError()
|
||||
if not path.is_file():
|
||||
continue
|
||||
name = kind + '/' + path.relative_to(root).as_posix()
|
||||
found.add(name)
|
||||
if len(found) > 4096 or name not in files:
|
||||
raise ValueError()
|
||||
total += path.stat().st_size
|
||||
if total > 536870912:
|
||||
raise ValueError()
|
||||
digest = hashlib.sha256()
|
||||
with path.open('rb') as source:
|
||||
while part := source.read(1048576):
|
||||
if time.monotonic() >= deadline:
|
||||
raise ValueError()
|
||||
digest.update(part)
|
||||
if digest.hexdigest() != files[name]:
|
||||
raise ValueError()
|
||||
if found != set(files):
|
||||
raise ValueError()
|
||||
return hashlib.sha256(manifest_bytes).hexdigest()
|
||||
except (ValueError, OSError, KeyError, TypeError):
|
||||
raise AssetError('LOCAL_ENGINE_ASSET_VALIDATION_FAILED') from None
|
||||
|
||||
|
||||
def forbid_download(*args, **kwargs):
|
||||
raise AssetError('LOCAL_ENGINE_ASSET_DOWNLOAD_FORBIDDEN')
|
||||
|
||||
|
||||
def configure_nltk(nltk, root):
|
||||
nltk.data.path[:] = [str(Path(root).resolve())]
|
||||
nltk.download = forbid_download
|
||||
# Also block alternate public download entry points before upstream import.
|
||||
if hasattr(nltk, 'downloader'):
|
||||
nltk.downloader.download = forbid_download
|
||||
nltk.downloader.Downloader.download = forbid_download
|
||||
validate_nltk(nltk)
|
||||
|
||||
|
||||
def validate_nltk(nltk):
|
||||
try:
|
||||
nltk.data.find('tokenizers/punkt_tab/english/')
|
||||
nltk.data.find('taggers/averaged_perceptron_tagger_eng/')
|
||||
nltk.sent_tokenize('Local asset verification.')
|
||||
nltk.pos_tag(['verification'], lang='eng')
|
||||
except Exception:
|
||||
raise AssetError('LOCAL_ENGINE_ASSET_VALIDATION_FAILED') from None
|
||||
|
||||
|
||||
def patch_pipeline_source(source):
|
||||
start = source.index('# Ensure that the necessary NLTK resources are available')
|
||||
end = source.index('# caching allows', start)
|
||||
return source[:start] + 'from services.local_s2s.assets import validate_nltk\nvalidate_nltk(nltk)\n\n' + source[end:]
|
||||
|
||||
def main():
|
||||
"""Fingerprint an already-provisioned local bundle; never fetch resources."""
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(description=main.__doc__)
|
||||
parser.add_argument('--nltk-root', type=Path, required=True)
|
||||
parser.add_argument('--vad-root', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
roots = {'nltk': args.nltk_root.resolve(strict=True), 'vad': args.vad_root.resolve(strict=True)}
|
||||
if args.output.exists() or any(root == args.output.resolve() or root in args.output.resolve().parents for root in roots.values()):
|
||||
raise ValueError()
|
||||
files, total = {}, 0
|
||||
for kind, root in roots.items():
|
||||
for path in root.rglob('*'):
|
||||
if '.git' in path.parts or '__pycache__' in path.parts:
|
||||
continue
|
||||
if path.is_symlink():
|
||||
raise ValueError()
|
||||
if path.is_file():
|
||||
total += path.stat().st_size
|
||||
if len(files) >= 4096 or total > 536870912:
|
||||
raise ValueError()
|
||||
with path.open('rb') as source:
|
||||
files[kind + '/' + path.relative_to(root).as_posix()] = hashlib.file_digest(source, 'sha256').hexdigest()
|
||||
required = {'nltk/' + p for p in REQUIRED_NLTK} | {'vad/' + p for p in REQUIRED_VAD}
|
||||
if not required <= files.keys():
|
||||
raise ValueError()
|
||||
with args.output.open('x', encoding='utf-8') as target:
|
||||
json.dump(dict(schema=1, files=files), target, indent=2, sort_keys=True)
|
||||
target.write('\n')
|
||||
digest = validate_assets(roots['nltk'], roots['vad'], args.output)
|
||||
except (ValueError, OSError):
|
||||
parser.exit(1, 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED\n')
|
||||
print(json.dumps(dict(manifest_sha256=digest, files=len(files))))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,225 @@
|
||||
"""Owned local HTTP gateway: total connection deadlines and bounded async I/O."""
|
||||
import asyncio
|
||||
from collections import Counter
|
||||
import socket
|
||||
from threading import Event, Thread
|
||||
import httpx
|
||||
|
||||
# One shared wall-clock window for cancellation, transport closure and slot release.
|
||||
CLEANUP_WINDOW_SECONDS = 1.0
|
||||
HALF_CLOSE_HEADER = 'x-local-s2s-half-close'
|
||||
|
||||
LIMITS = {'/v1/audio/transcriptions': (1100000, 65536),
|
||||
'/v1/chat/completions': (1048576, 1048576),
|
||||
'/v1/audio/speech': (16384, 1440000)}
|
||||
|
||||
|
||||
class ComponentServer:
|
||||
def __init__(self, key, *, port=8766, transport=None, timeout=30, inactivity=None):
|
||||
if not key or not key.isascii() or any(c.isspace() for c in key):
|
||||
raise ValueError('LOCAL_COMPONENT_CREDENTIAL_REQUIRED')
|
||||
self.key, self.transport, self.timeout = key, transport, timeout
|
||||
self.inactivity = min(timeout, 5) if inactivity is None else min(timeout, inactivity)
|
||||
if self.timeout <= 0 or self.inactivity <= 0:
|
||||
raise ValueError('LOCAL_COMPONENT_DEADLINE_REQUIRED')
|
||||
self.counts = Counter()
|
||||
self.socket = socket.socket()
|
||||
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self.socket.bind(('127.0.0.1', port))
|
||||
self.socket.listen(4)
|
||||
self.socket.setblocking(False)
|
||||
self.server_port = self.socket.getsockname()[1]
|
||||
self.ready, self.done = Event(), Event()
|
||||
self.loop = self.stopping = None
|
||||
self.requests = {}
|
||||
|
||||
def serve_forever(self):
|
||||
try:
|
||||
asyncio.run(self._run())
|
||||
finally:
|
||||
self.socket.close()
|
||||
self.done.set()
|
||||
|
||||
async def _run(self):
|
||||
self.loop, self.stopping = asyncio.get_running_loop(), asyncio.Event()
|
||||
server = await asyncio.start_server(self._accept, sock=self.socket, limit=16384)
|
||||
self.ready.set()
|
||||
try:
|
||||
await self.stopping.wait()
|
||||
finally:
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
tasks = list(self.requests)
|
||||
for task, writer in list(self.requests.items()):
|
||||
writer.close()
|
||||
task.cancel()
|
||||
if tasks:
|
||||
await asyncio.wait(tasks, timeout=1)
|
||||
self.counts['shutdown_pending'] = sum(not t.done() for t in tasks)
|
||||
|
||||
def _accept(self, reader, writer):
|
||||
accepted = self.loop.time()
|
||||
if self.stopping.is_set() or len(self.requests) >= 3:
|
||||
self.counts['rejected'] += 1
|
||||
writer.close()
|
||||
return
|
||||
writer.transport.set_write_buffer_limits(high=16384, low=4096)
|
||||
task = self.loop.create_task(self._serve(reader, writer, accepted + self.timeout))
|
||||
self.requests[task] = writer
|
||||
self.counts['accepted'] += 1
|
||||
task.add_done_callback(self._finished)
|
||||
|
||||
def _finished(self, task):
|
||||
self.requests.pop(task, None)
|
||||
self.counts['released'] += 1
|
||||
if not task.cancelled():
|
||||
task.exception()
|
||||
|
||||
async def _write(self, writer, data):
|
||||
writer.write(data)
|
||||
await asyncio.wait_for(writer.drain(), self.inactivity)
|
||||
|
||||
async def _error(self, writer, status):
|
||||
await self._write(writer, f'HTTP/1.1 {status} Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n'.encode())
|
||||
|
||||
async def _watch_downstream(self, reader, writer, receive_only):
|
||||
# FIN cannot distinguish full close from SHUT_WR. By contract it cancels
|
||||
# ordinary requests; explicit receive-only clients may still read a reply.
|
||||
try:
|
||||
extra = await reader.read(1)
|
||||
if not extra and receive_only:
|
||||
await writer.wait_closed() # still observe a reset/transport loss
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
|
||||
async def _forward(self, client, writer, path, fields, body, response):
|
||||
request = client.build_request('POST', 'https://openrouter.ai/api' + path,
|
||||
headers={'Authorization': 'Bearer ' + self.key,
|
||||
'Content-Type': fields.get('content-type', 'application/json'), 'Accept-Encoding': 'identity'},
|
||||
content=bytes(body))
|
||||
# The owner closes the response independently, even if cancellation or a
|
||||
# stalled stream prevents this operation from reaching normal completion.
|
||||
result = await client.send(request, stream=True)
|
||||
response.append(result)
|
||||
if result.status_code != 200:
|
||||
await self._error(writer, 502)
|
||||
return
|
||||
media = result.headers.get('content-type', '').split(';')[0]
|
||||
expected = ('audio/pcm', 'application/octet-stream') if path.endswith('/speech') else ('application/json', 'text/event-stream')
|
||||
if media not in expected or result.headers.get('content-encoding', 'identity') != 'identity':
|
||||
await self._error(writer, 502)
|
||||
return
|
||||
await self._write(writer, ('HTTP/1.1 200 OK\r\nContent-Type: ' + media +
|
||||
'\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n').encode('ascii'))
|
||||
total = 0
|
||||
# No 8192-byte accumulation: small SSE/PCM arrivals stay observable.
|
||||
async for raw in result.aiter_bytes():
|
||||
total += len(raw)
|
||||
if total > LIMITS[path][1]:
|
||||
raise ValueError('Response capacity')
|
||||
for offset in range(0, len(raw), 8192):
|
||||
part = raw[offset:offset + 8192]
|
||||
await self._write(writer, f'{len(part):x}\r\n'.encode() + part + b'\r\n')
|
||||
if not total:
|
||||
raise ValueError('Empty component response')
|
||||
await self._write(writer, b'0\r\n\r\n')
|
||||
|
||||
async def _close_owned(self, writer, tasks, client, response):
|
||||
writer.close()
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
# Close all transports independently; one stalled close must not defer
|
||||
# another. asyncio.wait bounds the entire cleanup, including task joins.
|
||||
closing = [asyncio.create_task(writer.wait_closed())]
|
||||
if client is not None:
|
||||
closing.append(asyncio.create_task(client.aclose()))
|
||||
closing.extend(asyncio.create_task(result.aclose()) for result in response)
|
||||
done, pending = await asyncio.wait(set(tasks) | set(closing), timeout=CLEANUP_WINDOW_SECONDS)
|
||||
for task in done:
|
||||
if not task.cancelled():
|
||||
error = task.exception()
|
||||
if task in closing and error is not None:
|
||||
self.counts['close_errors'] += 1
|
||||
if pending:
|
||||
self.counts['close_errors'] += len(pending)
|
||||
writer.transport.abort()
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
task.add_done_callback(lambda t: None if t.cancelled() else t.exception())
|
||||
|
||||
async def _serve(self, reader, writer, deadline):
|
||||
client, tasks, response = None, [], []
|
||||
try:
|
||||
async with asyncio.timeout_at(deadline):
|
||||
# Header acquisition has its own short bound, including partial headers.
|
||||
header = await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), self.inactivity)
|
||||
lines = header.decode('ascii').split('\r\n')
|
||||
method, path, version = lines[0].split(' ')
|
||||
fields = {}
|
||||
for line in lines[1:-2]:
|
||||
key, value = line.split(':', 1)
|
||||
key = key.lower()
|
||||
if key in fields:
|
||||
raise ValueError('Repeated header')
|
||||
fields[key] = value.strip()
|
||||
if method != 'POST' or path not in LIMITS or version not in ('HTTP/1.0', 'HTTP/1.1'):
|
||||
await self._error(writer, 403)
|
||||
return
|
||||
request_limit, _ = LIMITS[path]
|
||||
size = int(fields.get('content-length', '-1'))
|
||||
if 'transfer-encoding' in fields or not 0 < size <= request_limit:
|
||||
await self._error(writer, 413)
|
||||
return
|
||||
body = bytearray()
|
||||
while len(body) < size:
|
||||
part = await asyncio.wait_for(reader.read(min(8192, size - len(body))), self.inactivity)
|
||||
if not part:
|
||||
raise ValueError('Incomplete request')
|
||||
body.extend(part)
|
||||
if fields.get('authorization') != 'Bearer local-components':
|
||||
await self._error(writer, 403)
|
||||
return
|
||||
half_close = fields.get(HALF_CLOSE_HEADER)
|
||||
if half_close not in (None, 'receive-response'):
|
||||
await self._error(writer, 400)
|
||||
return
|
||||
self.counts[path] += 1 # one admitted provider attempt, including failed probes
|
||||
client = httpx.AsyncClient(transport=self.transport, timeout=httpx.Timeout(self.inactivity, connect=self.inactivity),
|
||||
follow_redirects=False, trust_env=False)
|
||||
forwarding = asyncio.create_task(self._forward(client, writer, path, fields, body, response))
|
||||
watching = asyncio.create_task(self._watch_downstream(reader, writer, half_close == 'receive-response'))
|
||||
tasks.extend((forwarding, watching))
|
||||
done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
||||
if forwarding in done:
|
||||
forwarding.result()
|
||||
else:
|
||||
self.counts['disconnected'] += 1
|
||||
except TimeoutError:
|
||||
self.counts['expired'] += 1
|
||||
except asyncio.CancelledError:
|
||||
self.counts['cancelled'] += 1
|
||||
raise
|
||||
except (ValueError, OSError, UnicodeError, asyncio.IncompleteReadError,
|
||||
asyncio.LimitOverrunError, httpx.HTTPError):
|
||||
self.counts['failures'] += 1
|
||||
finally:
|
||||
# No successful terminal chunk is fabricated on any failure path.
|
||||
await self._close_owned(writer, tasks, client, response)
|
||||
|
||||
def shutdown(self):
|
||||
if self.loop is not None and self.loop.is_running():
|
||||
self.loop.call_soon_threadsafe(self.stopping.set)
|
||||
self.done.wait(2)
|
||||
|
||||
def server_close(self):
|
||||
self.socket.close()
|
||||
|
||||
|
||||
def start_components(key, timeout=30):
|
||||
server = ComponentServer(key, timeout=timeout)
|
||||
thread = Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
if not server.ready.wait(5):
|
||||
server.server_close()
|
||||
raise ValueError('LOCAL_COMPONENT_STARTUP_DEADLINE')
|
||||
return server, thread
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Development engine launcher; local asset preflight precedes every paid probe."""
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def build_runtime(config, stop):
|
||||
from services.local_s2s.extension import active_components, install_session_proof, FailClosedQueue, EngineTokenGuard
|
||||
from services.local_s2s.request_policy import install_client_policy
|
||||
from app.modules.voice.local_s2s import setup_session
|
||||
from speech_to_speech.config import load_config, resolve_config
|
||||
from speech_to_speech.configured_runtime import build_configured_server
|
||||
from speech_to_speech.api.openai_realtime.handlers.session import SessionHandler
|
||||
import speech_to_speech.s2s_pipeline as pipeline
|
||||
import speech_to_speech.LLM.base_openai_compatible_language_model as base_llm
|
||||
import speech_to_speech.api.openai_realtime.server as server_module
|
||||
import torch
|
||||
source = Path(os.environ.get('LOCAL_S2S_SILERO_SOURCE', '/vad/silero-vad'))
|
||||
native_load = torch.hub.load
|
||||
def local_vad(repo, *args, **kwargs):
|
||||
if repo != 'snakers4/silero-vad:master':
|
||||
raise ValueError('LOCAL_ENGINE_UNEXPECTED_MODEL_DOWNLOAD')
|
||||
kwargs['source'] = 'local'
|
||||
return native_load(str(source), *args, **kwargs)
|
||||
torch.hub.load = local_vad
|
||||
pipeline.Queue = lambda *args, **kwargs: FailClosedQueue(stop)
|
||||
# Base setup invokes warmup from inside construction; install before it runs.
|
||||
install_client_policy(base_llm, config)
|
||||
resolved = resolve_config(load_config(Path(__file__).with_name('pipeline.yaml')), names=['local'])
|
||||
runtime = build_configured_server(resolved, stop)
|
||||
try:
|
||||
units = runtime.server.pool
|
||||
if len(units) != 1:
|
||||
raise ValueError('LOCAL_ENGINE_SINGLE_PIPELINE_REQUIRED')
|
||||
components = {id(unit.service): active_components(unit, config.components()) for unit in units}
|
||||
install_session_proof(SessionHandler, components, setup_session(config))
|
||||
create_app = server_module.create_app
|
||||
def guarded_app(*args, **kwargs):
|
||||
return EngineTokenGuard(create_app(*args, **kwargs), config.local_s2s_token.get_secret_value())
|
||||
server_module.create_app = guarded_app
|
||||
return runtime
|
||||
except BaseException:
|
||||
from services.local_s2s.lifecycle import bounded_call
|
||||
bounded_call(runtime.stop, 2)
|
||||
raise
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--allow-paid-startup', action='store_true')
|
||||
args = parser.parse_args()
|
||||
if not args.allow_paid_startup or os.environ.get('LOCAL_S2S_ALLOW_PAID_STARTUP') != 'true':
|
||||
parser.error('Engine initialization performs paid component probes; authorize before starting.')
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
from services.local_s2s.assets import validate_assets, configure_nltk, AssetError
|
||||
from services.local_s2s.lifecycle import run_owned
|
||||
try:
|
||||
config = VoiceSettings(_env_file=None, provider='local_s2s')
|
||||
config.require_voice()
|
||||
root = os.environ.get('LOCAL_S2S_NLTK_DATA', '/assets/nltk')
|
||||
fingerprint = validate_assets(root, os.environ.get('LOCAL_S2S_SILERO_SOURCE', '/vad/silero-vad'),
|
||||
os.environ.get('LOCAL_S2S_ASSET_MANIFEST', '/assets/assets.json'))
|
||||
if fingerprint != os.environ.get('LOCAL_S2S_ASSET_MANIFEST_SHA256'):
|
||||
raise AssetError('LOCAL_ENGINE_ASSET_VALIDATION_FAILED')
|
||||
import nltk
|
||||
configure_nltk(nltk, root)
|
||||
except (ValueError, OSError, ImportError):
|
||||
print(json.dumps(dict(status='failed', category='LOCAL_ENGINE_ASSET_VALIDATION_FAILED')), flush=True)
|
||||
return 1
|
||||
logging.disable(logging.CRITICAL)
|
||||
os.environ['HF_HUB_OFFLINE'] = '1'
|
||||
os.environ['NLTK_DATA'] = root
|
||||
key = os.environ.get('OPENROUTER_API_KEY', '')
|
||||
if not key:
|
||||
parser.error('OPENROUTER_API_KEY is required in the engine only.')
|
||||
return run_owned(lambda stop: build_runtime(config, stop), key, config.local_s2s_request_timeout_seconds)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Versioned extension for the pinned engine; no history-repair capability."""
|
||||
from copy import deepcopy
|
||||
from queue import Queue, Full
|
||||
from app.modules.voice.local_s2s import effective_identity
|
||||
|
||||
|
||||
class FailClosedQueue(Queue):
|
||||
"""Saturation stops the candidate rather than blocking a teardown producer."""
|
||||
def __init__(self, stop_event, maxsize=256):
|
||||
super().__init__(maxsize=maxsize)
|
||||
self.stop_event = stop_event
|
||||
|
||||
def put(self, item, block=True, timeout=None):
|
||||
try:
|
||||
return super().put(item, block=False)
|
||||
except Full:
|
||||
self.stop_event.set()
|
||||
raise RuntimeError('LOCAL_ENGINE_QUEUE_CAPACITY') from None
|
||||
|
||||
|
||||
def active_components(unit, expected):
|
||||
"""Read initialized handlers, not session.update model/voice echoes."""
|
||||
handlers = unit.handlers
|
||||
stt = next(h for h in handlers if type(h).__module__.endswith('.STT.openai_compatible_handler'))
|
||||
tts = next(h for h in handlers if type(h).__module__.endswith('.TTS.openai_compatible_handler'))
|
||||
llm = next(h for h in handlers if hasattr(h, 'model_name') and hasattr(h, 'client'))
|
||||
actual = dict(stt=dict(backend='openai', model=stt.model, language=stt.language,
|
||||
response_format=stt.response_format, final_only=True),
|
||||
llm=dict(backend='chat-completions', model=llm.model_name,
|
||||
max_output_tokens=getattr(llm.client, 'token_limit', None)),
|
||||
tts=dict(backend='openai', model=tts.model, voice=tts.voice,
|
||||
response_format=tts.response_format, sample_rate=tts.sample_rate),
|
||||
request_timeout_seconds=stt.timeout)
|
||||
if (actual != expected or tts.timeout != stt.timeout or llm.request_timeout_s != stt.timeout
|
||||
or stt.base_url != 'http://127.0.0.1:8766/v1' or tts.base_url != stt.base_url
|
||||
or str(llm.client.base_url).rstrip('/') != stt.base_url
|
||||
or stt.api_key != 'local-components' or tts.api_key != stt.api_key
|
||||
or llm.client.api_key != stt.api_key):
|
||||
raise ValueError('LOCAL_ENGINE_COMPONENT_MISMATCH')
|
||||
# Startup configuration fixes these values; refuse any unsupported handler layout.
|
||||
vad = handlers[0]
|
||||
if getattr(vad, 'enable_realtime_transcription', None) is not False:
|
||||
raise ValueError('LOCAL_ENGINE_FINAL_ONLY_REQUIRED')
|
||||
if llm.client.max_retries != 0:
|
||||
raise ValueError('LOCAL_ENGINE_RETRY_POLICY_MISMATCH')
|
||||
return actual
|
||||
|
||||
|
||||
def install_session_proof(handler_class, service_components, session_template):
|
||||
original = handler_class.build_session_updated
|
||||
def build_session_updated(self, conn_id):
|
||||
result = original(self, conn_id)
|
||||
cfg = self._state(conn_id).runtime_config
|
||||
# Project the actual post-update state onto the requested contract shape.
|
||||
# Extra SDK defaults do not change the effective contract fingerprint.
|
||||
actual = cfg.session.model_dump(mode='json')
|
||||
def project(value, shape):
|
||||
if isinstance(shape, dict):
|
||||
return {k: project(value[k], v) for k, v in shape.items()}
|
||||
if isinstance(shape, list):
|
||||
if not isinstance(value, list) or len(value) != len(shape):
|
||||
raise ValueError('LOCAL_ENGINE_SESSION_LAYOUT')
|
||||
return [project(a, b) for a, b in zip(value, shape)]
|
||||
return value
|
||||
session = project(actual, session_template)
|
||||
components = service_components[id(self._service)]
|
||||
identity = effective_identity(components, session)
|
||||
return result.model_copy(update={'session': result.session.model_copy(update={'s2s_effective': identity})})
|
||||
handler_class.build_session_updated = build_session_updated
|
||||
return original
|
||||
|
||||
class EngineTokenGuard:
|
||||
def __init__(self, app, token):
|
||||
self.app, self.token = app, token
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
import hmac
|
||||
if scope['type'] in ('http', 'websocket') and self.token:
|
||||
header = dict(scope.get('headers', [])).get(b'authorization', b'')
|
||||
if not hmac.compare_digest(header, ('Bearer ' + self.token).encode('ascii')):
|
||||
if scope['type'] == 'websocket':
|
||||
await send({'type': 'websocket.close', 'code': 1008})
|
||||
else:
|
||||
await send({'type': 'http.response.start', 'status': 401, 'headers': []})
|
||||
await send({'type': 'http.response.body', 'body': b''})
|
||||
return
|
||||
await self.app(scope, receive, send)
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Independent bounded cleanup and owned process signal lifecycle."""
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import signal
|
||||
from threading import Event, Lock, Thread
|
||||
import time
|
||||
from services.local_s2s.components import start_components
|
||||
|
||||
|
||||
@contextmanager
|
||||
def termination_signals(stop):
|
||||
previous = {sig: signal.getsignal(sig) for sig in (signal.SIGINT, signal.SIGTERM)}
|
||||
try:
|
||||
for sig in previous:
|
||||
signal.signal(sig, lambda *_: stop.set())
|
||||
yield
|
||||
finally:
|
||||
for sig, handler in previous.items():
|
||||
signal.signal(sig, handler)
|
||||
|
||||
|
||||
def bounded_call(action, timeout):
|
||||
finished, result = Event(), []
|
||||
def run():
|
||||
try:
|
||||
action()
|
||||
result.append(0)
|
||||
except BaseException:
|
||||
result.append(1)
|
||||
finally:
|
||||
finished.set()
|
||||
Thread(target=run, daemon=True).start()
|
||||
return result[0] if finished.wait(timeout) else 2
|
||||
|
||||
|
||||
def cleanup(runtime, guard, thread, stop, *, timeout=2, emit=print):
|
||||
stop.set()
|
||||
counters = {}
|
||||
# Every operation is independent; a failed or wedged stop cannot skip I/O cleanup.
|
||||
for name, action in (
|
||||
('runtime_stop', runtime.stop if runtime is not None else lambda: None),
|
||||
('gateway_shutdown', guard.shutdown),
|
||||
('gateway_close', guard.server_close),
|
||||
('gateway_join', lambda: thread.join(timeout)),
|
||||
):
|
||||
counters[name] = bounded_call(action, timeout)
|
||||
counters['gateway_alive'] = int(thread.is_alive())
|
||||
emit(json.dumps(dict(stage='close', cleanup=counters, request_counts=dict(guard.counts))), flush=True)
|
||||
return any(counters.values())
|
||||
|
||||
|
||||
def run_owned(build, key, request_timeout, *, startup_timeout=90, cleanup_timeout=2, emit=print):
|
||||
stop, constructed, finished, abandoned, lock = Event(), Event(), Event(), Event(), Lock()
|
||||
runtime = None
|
||||
result = {}
|
||||
with termination_signals(stop):
|
||||
guard, thread = start_components(key, request_timeout)
|
||||
def drive():
|
||||
nonlocal runtime
|
||||
if stop.is_set():
|
||||
return 1
|
||||
def construct():
|
||||
try:
|
||||
value = build(stop)
|
||||
with lock:
|
||||
if not abandoned.is_set():
|
||||
result['runtime'] = value
|
||||
else:
|
||||
bounded_call(value.stop, cleanup_timeout)
|
||||
except BaseException:
|
||||
result['failed'] = True
|
||||
finally:
|
||||
constructed.set()
|
||||
Thread(target=construct, daemon=True).start()
|
||||
deadline = time.monotonic() + startup_timeout
|
||||
while not constructed.wait(.01):
|
||||
if stop.is_set() or time.monotonic() >= deadline:
|
||||
with lock:
|
||||
abandoned.set()
|
||||
emit(json.dumps(dict(status='failed', category='LOCAL_ENGINE_STARTUP_DEADLINE')), flush=True)
|
||||
return 1
|
||||
runtime = result.get('runtime')
|
||||
if runtime is None or stop.is_set():
|
||||
emit(json.dumps(dict(status='failed', category='LOCAL_ENGINE_STARTUP_OR_RUNTIME_FAILURE')), flush=True)
|
||||
return 1
|
||||
emit(json.dumps(dict(stage='startup', request_counts=dict(guard.counts))), flush=True)
|
||||
def serve():
|
||||
try:
|
||||
runtime.start()
|
||||
runtime.wait()
|
||||
except BaseException:
|
||||
result['failed'] = True
|
||||
finally:
|
||||
finished.set()
|
||||
Thread(target=serve, daemon=True).start()
|
||||
while not finished.wait(.02) and not stop.is_set():
|
||||
pass
|
||||
return int(bool(result.get('failed')))
|
||||
try:
|
||||
outcome = drive()
|
||||
finally:
|
||||
# Fetch a construction result which raced the deadline before abandoning it.
|
||||
with lock:
|
||||
abandoned.set()
|
||||
runtime = runtime or result.get('runtime')
|
||||
cleanup_failed = cleanup(runtime, guard, thread, stop, timeout=cleanup_timeout, emit=emit)
|
||||
return int(outcome or cleanup_failed)
|
||||
@@ -0,0 +1,58 @@
|
||||
schema_version: 1
|
||||
blocks:
|
||||
vad:
|
||||
kind: vad
|
||||
backend: silero
|
||||
settings:
|
||||
smart_turn: false
|
||||
max_speech_ms: 10000
|
||||
min_silence_ms: 500
|
||||
speech_pad_ms: 300
|
||||
enable_realtime_transcription: false
|
||||
stt:
|
||||
kind: stt
|
||||
backend: openai
|
||||
settings:
|
||||
openai_stt_base_url: http://127.0.0.1:8766/v1
|
||||
openai_stt_api_key: local-components
|
||||
openai_stt_model: {env: LOCAL_S2S_STT_MODEL}
|
||||
openai_stt_language: fa
|
||||
openai_stt_response_format: json
|
||||
openai_stt_timeout: {env: LOCAL_S2S_REQUEST_TIMEOUT_SECONDS}
|
||||
llm:
|
||||
kind: llm
|
||||
backend: chat-completions
|
||||
settings:
|
||||
model_name: {env: LOCAL_S2S_LLM_MODEL}
|
||||
responses_api_base_url: http://127.0.0.1:8766/v1
|
||||
responses_api_api_key: local-components
|
||||
responses_api_stream: true
|
||||
responses_api_disable_thinking: false
|
||||
responses_api_reasoning_effort: null
|
||||
compact_history: false
|
||||
chat_size: 10
|
||||
tts:
|
||||
kind: tts
|
||||
backend: openai
|
||||
settings:
|
||||
openai_tts_base_url: http://127.0.0.1:8766/v1
|
||||
openai_tts_api_key: local-components
|
||||
openai_tts_model: {env: LOCAL_S2S_TTS_MODEL}
|
||||
openai_tts_voice: {env: LOCAL_S2S_TTS_VOICE}
|
||||
openai_tts_sample_rate: 24000
|
||||
openai_tts_response_format: pcm
|
||||
openai_tts_stream: false
|
||||
openai_tts_timeout: {env: LOCAL_S2S_REQUEST_TIMEOUT_SECONDS}
|
||||
pipelines:
|
||||
local:
|
||||
num_pipelines: 1
|
||||
stages: {vad: vad, stt: stt, llm: llm, tts: tts}
|
||||
options:
|
||||
device: cpu
|
||||
enable_live_transcription: false
|
||||
enable_llm_proxy: false
|
||||
runtime:
|
||||
log_level: critical
|
||||
log_transcripts: false
|
||||
torch_num_threads: 1
|
||||
server: {host: 0.0.0.0, port: 8765}
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Prepare immutable engine build inputs from an already-authorized clean checkout.
|
||||
|
||||
Does not fetch source, resolve dependencies, build images or download weights.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tomllib
|
||||
|
||||
PIN = '619e3fe4f71d1c6f35c15870d588a3638de34722'
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--checkout', type=Path, required=True)
|
||||
parser.add_argument('--base-image', required=True, help='python:3.11-slim@sha256:...')
|
||||
args = parser.parse_args()
|
||||
if not re.fullmatch(r'python:3\.11-slim@sha256:[0-9a-f]{64}', args.base_image):
|
||||
parser.error('An immutable Python 3.11 base image digest is required.')
|
||||
source = args.checkout.resolve()
|
||||
sha = subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip()
|
||||
dirty = subprocess.check_output(['git', '-C', str(source), 'status', '--porcelain'], text=True).strip()
|
||||
if sha != PIN or dirty:
|
||||
parser.error('Requires a clean checkout of the Phase 1 upstream pin.')
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
target = root / '.local-s2s-build'
|
||||
if target.exists():
|
||||
parser.error('.local-s2s-build exists; preserve it and choose a fresh workspace.')
|
||||
dependencies = ['setuptools>=77.0.3', 'wheel']
|
||||
for manifest in (source / 'pyproject.toml', root / 'pyproject.toml'):
|
||||
data = tomllib.loads(manifest.read_text(encoding='utf-8'))
|
||||
dependencies.extend(data['project']['dependencies'])
|
||||
if manifest.parent == root:
|
||||
for extra in ('api', 'voice', 'embedding'):
|
||||
dependencies.extend(data['project']['optional-dependencies'][extra])
|
||||
target.mkdir()
|
||||
shutil.copytree(source, target / 'upstream', ignore=shutil.ignore_patterns('.git', '.venv', '__pycache__'))
|
||||
from sys import path as import_path
|
||||
import_path.insert(0, str(root))
|
||||
from services.local_s2s.assets import patch_pipeline_source
|
||||
pipeline = target / 'upstream/src/speech_to_speech/s2s_pipeline.py'
|
||||
pipeline.write_text(patch_pipeline_source(pipeline.read_text(encoding='utf-8')), encoding='utf-8')
|
||||
(target / 'requirements.in').write_text('\n'.join(sorted(set(dependencies))) + '\n', encoding='utf-8')
|
||||
(target / 'build-manifest.json').write_text(json.dumps(dict(upstream=PIN, base_image=args.base_image,
|
||||
upstream_pyproject_sha256=hashlib.sha256((source / 'pyproject.toml').read_bytes()).hexdigest(),
|
||||
patch_revision='rag-local-s2s-phase2-v3', built=False), indent=2) + '\n', encoding='utf-8')
|
||||
print('Prepared source and dependency inputs. Resolve a Linux hash lock before building; no downloads performed.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Fixed Chat Completions policy, applied before upstream setup/warmup."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
|
||||
class LimitedChatClient:
|
||||
def __init__(self, client, token_limit):
|
||||
self._client, self.token_limit = client, token_limit
|
||||
self.max_retries = 0
|
||||
self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._create))
|
||||
|
||||
def _create(self, **kwargs):
|
||||
kwargs.pop('max_completion_tokens', None)
|
||||
kwargs['max_tokens'] = self.token_limit
|
||||
return self._client.chat.completions.create(**kwargs)
|
||||
|
||||
def with_options(self, **kwargs):
|
||||
# Pinned warmup explicitly asks for WARMUP_MAX_RETRIES. Never honor it.
|
||||
kwargs['max_retries'] = 0
|
||||
return LimitedChatClient(self._client.with_options(**kwargs), self.token_limit)
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._client, name)
|
||||
|
||||
|
||||
def install_client_policy(base_module, config):
|
||||
import httpx
|
||||
native = base_module.OpenAI
|
||||
def create(*args, **kwargs):
|
||||
kwargs['max_retries'] = 0
|
||||
kwargs['timeout'] = httpx.Timeout(config.local_s2s_request_timeout_seconds, connect=5)
|
||||
return LimitedChatClient(native(*args, **kwargs), config.local_s2s_max_output_tokens)
|
||||
base_module.OpenAI = create
|
||||
# The pinned base defaults to 20 seconds. Apply the configured deadline
|
||||
# before setup computes request_timeout and invokes its warmup.
|
||||
base = base_module.BaseOpenAICompatibleHandler
|
||||
native_setup = base.setup
|
||||
def setup(self, *args, **kwargs):
|
||||
kwargs['request_timeout_s'] = config.local_s2s_request_timeout_seconds
|
||||
return native_setup(self, *args, **kwargs)
|
||||
base.setup = setup
|
||||
return native
|
||||
Reference in New Issue
Block a user