"""Admin-only Kronic UI -> Balroc and Whisper backend proxy. No secrets sent to browsers.""" from __future__ import annotations import base64 import binascii import subprocess import tempfile from pathlib import Path import json import os import urllib.request import urllib.error import uuid class BridgeError(Exception): def __init__(self, message, status=502): super().__init__(message) self.status=status def status(): return {"configured": bool(os.getenv("KRONIC_BALROC_URL", "http://172.22.1.161:8182")), "whisper_configured": bool(os.getenv("KRONIC_WHISPER_TRANSCRIBE_URL", "")), "tts_configured": False} def _post(url, content, headers, timeout=90): if not url.startswith(("http://", "https://")): raise BridgeError("Invalid backend URL", 500) req=urllib.request.Request(url, data=content, headers=headers, method="POST") try: with urllib.request.urlopen(req, timeout=timeout) as response: return response.read(2_000_000) except urllib.error.HTTPError as exc: detail=exc.read(500).decode("utf-8", "replace") raise BridgeError(f"Backend returned HTTP {exc.code}: {detail}", 502) from exc except (urllib.error.URLError, TimeoutError) as exc: raise BridgeError(f"Backend unavailable: {exc}", 502) from exc def chat(body): message=str(body.get("message", "")).strip() if not message or len(message)>6000: raise BridgeError("Message is empty or too long",400) api=os.getenv("KRONIC_BALROC_URL", "http://172.22.1.161:8182").rstrip("/") session=str(body.get("session_id") or "").strip() if len(session)>128: raise BridgeError("Invalid session ID", 400) payload={"message":message,"use_tools":bool(body.get("use_tools",False))} if session: payload["session_id"]=session headers={"Content-Type":"application/json"} secret=os.getenv("KRONIC_BALROC_CONTROL_KEY", "") if secret: headers["X-Balroc-Control-Key"]=secret raw=_post(api+"/api/chat",json.dumps(payload).encode(),headers,timeout=120) try: result=json.loads(raw) except ValueError as exc: raise BridgeError("Balroc returned invalid JSON") from exc return {"reply":result.get("reply", ""), "session_id":result.get("session_id") or result.get("conversation_id") or session, "tool_calls": [str(x.get("name", "")) for x in result.get("tool_calls", []) if isinstance(x,dict)], "error":result.get("detail") or result.get("error")} def _convert_audio_to_wav(audio: bytes) -> bytes: """Decode browser microphone audio to a standard, seekable PCM WAV file. whisper.cpp's /inference rejects Opus-in-WebM on many builds. We use a temporary file only for FFmpeg's WAV output so its RIFF length is valid; the file is removed immediately afterward. """ with tempfile.TemporaryDirectory(prefix="kronic-whisper-") as temporary: wav_path = Path(temporary) / "speech.wav" command = [ "ffmpeg", "-hide_banner", "-loglevel", "error", "-nostdin", "-i", "pipe:0", "-map", "0:a:0", "-vn", "-sn", "-dn", "-t", "90", "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", "-f", "wav", str(wav_path), ] try: result = subprocess.run( command, input=audio, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=45, check=False, ) except FileNotFoundError as exc: raise BridgeError("FFmpeg is not installed on the Kronic server", 503) from exc except subprocess.TimeoutExpired as exc: raise BridgeError("Audio conversion timed out", 504) from exc if result.returncode != 0 or not wav_path.is_file(): detail = result.stderr.decode("utf-8", "replace")[-400:].strip() raise BridgeError(f"Could not decode microphone recording: {detail or 'FFmpeg failed'}", 422) wav = wav_path.read_bytes() if not wav.startswith(b"RIFF") or wav[8:12] != b"WAVE" or len(wav) < 48: raise BridgeError("FFmpeg produced an invalid WAV file", 502) if len(wav) > 6_000_000: raise BridgeError("Recording is too long; please use a shorter clip", 413) return wav def transcribe(body): endpoint = os.getenv("KRONIC_WHISPER_TRANSCRIBE_URL", "").strip() if not endpoint: raise BridgeError("Whisper endpoint not configured: set KRONIC_WHISPER_TRANSCRIBE_URL", 503) encoded = body.get("audio_base64", "") if not isinstance(encoded, str) or len(encoded) > 8_000_000: raise BridgeError("Invalid or oversized audio", 413) try: audio = base64.b64decode(encoded, validate=True) except (ValueError, binascii.Error) as exc: raise BridgeError("Invalid base64 audio", 400) from exc if not audio or len(audio) > 5_000_000: raise BridgeError("Audio must be between 1 byte and 5 MB", 413) wav = _convert_audio_to_wav(audio) boundary = "KronicBalroc" + uuid.uuid4().hex parts = [] def field(name, value): parts.append( f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode() ) field("response_format", "json") parts.append( (f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="speech.wav"\r\n' 'Content-Type: audio/wav\r\n\r\n').encode() + wav + b"\r\n" ) parts.append(f"--{boundary}--\r\n".encode()) raw = _post( endpoint, b"".join(parts), {"Content-Type": f"multipart/form-data; boundary={boundary}"}, timeout=100, ) try: result = json.loads(raw) except ValueError as exc: raise BridgeError("Whisper response must be JSON") from exc transcript = str(result.get("text", "") or "").strip() if not transcript: raise BridgeError("Whisper returned no transcription", 422) return {"text": transcript} def clients(): """Read all live Jellyfin clients via Balroc; no tokens reach the browser.""" url = os.getenv('KRONIC_BALROC_URL', 'http://172.22.1.161:8182').strip().rstrip('/') if not url.startswith(('http://','https://')): raise BridgeError('Invalid Balroc backend URL', 500) request = urllib.request.Request(url+'/api/jellyfin/clients', headers={'Accept':'application/json'}) try: with urllib.request.urlopen(request, timeout=12) as response: data = json.loads(response.read(1000000)) except (urllib.error.URLError, TimeoutError, ValueError) as exc: raise BridgeError('Jellyfin client discovery failed: '+str(exc), 502) from exc if not isinstance(data,dict) or not isinstance(data.get('clients'),list): raise BridgeError('Balroc did not return a client list', 502) return data def approve_client(device_id): '''Approve exactly one active client using Balroc's secured API.''' if not device_id or len(device_id)>200: raise BridgeError('Invalid Jellyfin device ID',400) secret=os.getenv('KRONIC_BALROC_CONTROL_KEY','').strip() if not secret: raise BridgeError('Kronic Balroc control key not configured',503) url=os.getenv('KRONIC_BALROC_URL','http://172.22.1.161:8182').rstrip('/') payload=json.dumps({'device_id':device_id}).encode() raw=_post(url+'/api/jellyfin/approve-client',payload, {'Content-Type':'application/json','X-Balroc-Control-Key':secret},timeout=20) try: return json.loads(raw) except ValueError as exc: raise BridgeError('Invalid Balroc approval response') from exc