From 115fb5acb9d598edd53dcdafd03fae41eca7f12a Mon Sep 17 00:00:00 2001 From: Alex Date: Mon, 23 Nov 2026 21:17:16 +0300 Subject: [PATCH] Add automatic Speaches container lifecycle management --- ai-station-portal-admin | 36 ++++++++++++++++ transcription_queue.py | 94 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 128 insertions(+), 2 deletions(-) diff --git a/ai-station-portal-admin b/ai-station-portal-admin index c52daab..43f21f6 100755 --- a/ai-station-portal-admin +++ b/ai-station-portal-admin @@ -339,9 +339,45 @@ def system_power(action): ) return 0 +def speaches_control(action): + """Manage only the dedicated Speaches container.""" + if action not in {"start", "stop"}: + return 2 + + docker = "/usr/bin/docker" + container = "speaches" + + state = run( + docker, + "inspect", + "--format", + "{{.State.Running}}", + container, + timeout=10, + ).stdout.strip().lower() + + if state not in {"true", "false"}: + raise RuntimeError(f"Unexpected Speaches container state: {state}") + + if action == "start": + if state == "true": + return 0 + run(docker, "start", container, timeout=60) + return 0 + + if state == "false": + return 0 + + run(docker, "stop", "--time", "10", container, timeout=30) + return 0 + + def main(): if len(sys.argv) != 3: return 2 action, value = sys.argv[1:] + + if action == "speaches-control": + return speaches_control(value) if action == 'hostname': if len(value) > 63 or not re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', value): return 2 run('/usr/bin/hostnamectl', 'set-hostname', value); return 0 diff --git a/transcription_queue.py b/transcription_queue.py index 8719655..28f81ca 100644 --- a/transcription_queue.py +++ b/transcription_queue.py @@ -34,6 +34,7 @@ class TranscriptionQueue: self.model = model self.max_upload_bytes = max_upload_bytes self.allowed_extensions = allowed_extensions + self.helper_path = "/opt/ai-station-portal/ai-station-portal-admin" self.queue: asyncio.Queue[str] = asyncio.Queue() self.worker_task: asyncio.Task | None = None @@ -139,6 +140,11 @@ class TranscriptionQueue: pass self.worker_task = None + try: + await self._speaches_control("stop") + except Exception: + logger.exception("Failed to stop Speaches during queue shutdown") + logger.info("Transcription queue stopped") async def submit(self, filename: str, content: bytes, language: str): @@ -351,16 +357,98 @@ class TranscriptionQueue: "not_found": not_found, } + async def _speaches_control(self, action: str): + if action not in {"start", "stop"}: + raise ValueError("Unsupported Speaches action") + + process = await asyncio.create_subprocess_exec( + "sudo", + "-n", + self.helper_path, + "speaches-control", + action, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + + try: + stdout, stderr = await asyncio.wait_for( + process.communicate(), + timeout=45, + ) + except asyncio.TimeoutError: + if process.returncode is None: + process.kill() + await process.communicate() + raise RuntimeError(f"Speaches {action} helper timed out") + except asyncio.CancelledError: + if process.returncode is None: + process.kill() + await process.communicate() + raise + + if process.returncode != 0: + detail = stderr.decode(errors="replace").strip() + if not detail: + detail = stdout.decode(errors="replace").strip() + raise RuntimeError( + f"Speaches {action} failed: {detail or process.returncode}" + ) + + logger.info("Speaches container action completed: %s", action) + + async def _ensure_speaches_running(self): + await self._speaches_control("start") + + deadline = asyncio.get_running_loop().time() + 90 + last_error = "health endpoint did not respond" + + async with httpx.AsyncClient( + timeout=httpx.Timeout(5.0, connect=2.0) + ) as client: + while asyncio.get_running_loop().time() < deadline: + try: + response = await client.get( + f"{self.speaches_url}/health" + ) + response.raise_for_status() + logger.info("Speaches API is ready") + return + except httpx.HTTPError as exc: + last_error = str(exc) + + await asyncio.sleep(2) + + raise RuntimeError( + f"Speaches did not become ready within 90 seconds: {last_error}" + ) + async def _worker(self): while self.running: - job_id = await self.queue.get() + # No pending jobs: release the GPU before waiting for new work. + if self.queue.empty(): + try: + await self._speaches_control("stop") + except asyncio.CancelledError: + raise + except Exception: + logger.exception( + "Failed to stop idle Speaches container" + ) + + try: + job_id = await self.queue.get() + except asyncio.CancelledError: + raise try: await self._process_job(job_id) except asyncio.CancelledError: raise except Exception: - logger.exception("Unexpected queue worker error for %s", job_id) + logger.exception( + "Unexpected queue worker error for %s", job_id + ) finally: self.queue.task_done() @@ -454,7 +542,9 @@ class TranscriptionQueue: audio_path = files[0] try: + # Free LLM VRAM first, then start the transcription service. await self._unload_llama_models() + await self._ensure_speaches_running() data = { "model": self.model,