Add automatic Speaches container lifecycle management

This commit is contained in:
2026-11-23 21:17:16 +03:00
parent 5c5827d241
commit 115fb5acb9
2 changed files with 128 additions and 2 deletions
+36
View File
@@ -339,9 +339,45 @@ def system_power(action):
) )
return 0 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(): def main():
if len(sys.argv) != 3: return 2 if len(sys.argv) != 3: return 2
action, value = sys.argv[1:] action, value = sys.argv[1:]
if action == "speaches-control":
return speaches_control(value)
if action == 'hostname': 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 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 run('/usr/bin/hostnamectl', 'set-hostname', value); return 0
+92 -2
View File
@@ -34,6 +34,7 @@ class TranscriptionQueue:
self.model = model self.model = model
self.max_upload_bytes = max_upload_bytes self.max_upload_bytes = max_upload_bytes
self.allowed_extensions = allowed_extensions self.allowed_extensions = allowed_extensions
self.helper_path = "/opt/ai-station-portal/ai-station-portal-admin"
self.queue: asyncio.Queue[str] = asyncio.Queue() self.queue: asyncio.Queue[str] = asyncio.Queue()
self.worker_task: asyncio.Task | None = None self.worker_task: asyncio.Task | None = None
@@ -139,6 +140,11 @@ class TranscriptionQueue:
pass pass
self.worker_task = None 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") logger.info("Transcription queue stopped")
async def submit(self, filename: str, content: bytes, language: str): async def submit(self, filename: str, content: bytes, language: str):
@@ -351,16 +357,98 @@ class TranscriptionQueue:
"not_found": not_found, "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): async def _worker(self):
while self.running: 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: try:
await self._process_job(job_id) await self._process_job(job_id)
except asyncio.CancelledError: except asyncio.CancelledError:
raise raise
except Exception: except Exception:
logger.exception("Unexpected queue worker error for %s", job_id) logger.exception(
"Unexpected queue worker error for %s", job_id
)
finally: finally:
self.queue.task_done() self.queue.task_done()
@@ -454,7 +542,9 @@ class TranscriptionQueue:
audio_path = files[0] audio_path = files[0]
try: try:
# Free LLM VRAM first, then start the transcription service.
await self._unload_llama_models() await self._unload_llama_models()
await self._ensure_speaches_running()
data = { data = {
"model": self.model, "model": self.model,