Files
rag-technical-docs-assistant/services/local_s2s/engine.py
T
amirhosein mazaheri 42400495af feat(backend): integrate document deletion and grounded speech providers
Enable replay-safe document deletion and public deployment model identifiers with the forward voice-model schema revision.

Add GapGPT dialogue and ElevenLabs speech routing, strict extractive grounding, ten-source retrieval and regression coverage.

Validation: 199 targeted provider-free tests passed. The full provider-free run stalled and was interrupted; PostgreSQL acceptance was not run because TEST_DATABASE_URL is unset.
2026-10-20 09:00:37 +03:30

117 lines
6.1 KiB
Python

"""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
from speech_to_speech.pipeline.language_detection import warm_language_detector
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
class PipelineQueue(FailClosedQueue):
# Upstream uses Queue both as a constructor and in Queue[Any] annotations.
def __init__(self, *args, **kwargs):
super().__init__(stop)
pipeline.Queue = PipelineQueue
# Base setup invokes warmup from inside construction; install before it runs.
install_client_policy(base_llm, config)
import speech_to_speech.TTS.openai_compatible_handler as native_tts
from services.local_s2s.request_policy import install_tts_speed
install_tts_speed(native_tts, config.local_s2s_tts_speed)
if config.local_s2s_responsive and config.local_s2s_stt_provider == 'upstream':
import speech_to_speech.STT.openai_compatible_handler as native_stt
from services.local_s2s.responsiveness import install_stt_policy
install_stt_policy(native_stt)
# The pinned output processor also detects language for fixed session configs.
# Its first lazy Lingua preload can hold the GIL beyond the media send deadline.
# Prime the same cache before exposing the listener, within the startup budget.
warm_language_detector()
resolved = resolve_config(load_config(Path(__file__).with_name('pipeline.yaml')), names=['local'])
if config.local_s2s_retain_interrupted_answers:
from services.local_s2s.history import install_retained_history
install_retained_history()
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 engine_credential(name, parser):
credential_file = os.environ.get(name + '_FILE')
try:
key = Path(credential_file).read_text().strip() if credential_file else os.environ.get(name, '')
except OSError:
parser.error(name + '_FILE is unreadable.')
if not key:
parser.error(name + ' is required in the engine only.')
return key
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
credential = 'GAPGPT_API_KEY' if config.local_s2s_component_provider == 'gapgpt' else 'OPENROUTER_API_KEY'
key = engine_credential(credential, parser)
eleven_key = engine_credential('ELEVENLABS_API_KEY', parser) if 'elevenlabs' in (config.local_s2s_tts_provider, config.local_s2s_stt_provider) else None
return run_owned(lambda stop: build_runtime(config, stop), key, config.local_s2s_request_timeout_seconds,
component_options={'responsive': config.local_s2s_responsive, 'provider': config.local_s2s_component_provider,
'tts_provider': config.local_s2s_tts_provider, 'tts_key': eleven_key,
'stt_provider': config.local_s2s_stt_provider, 'stt_key': eleven_key,
'strict_grounding': config.local_s2s_strict_grounding})
if __name__ == '__main__':
raise SystemExit(main())