This repository has been archived on 2026-07-22. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
Hitonabi d4aa7eb8cf feat(v9): Phase 8 — Cockpit zeigt Lernen & Aktivität
- hermes_control.py: learned_profile() liest USER.md (Curator-Nutzerprofil,
  § -getrennt) + MEMORY.md; insights() zieht Sessions/Tokens/Tool-Calls +
  Top-Tools aus `hermes insights` (Regex, best effort).
- routers/hermes.py: GET /api/hermes/{learned,insights}.
- HermesPanel-Cockpit: Kachel "Aktivität" (Kennzahlen + Top-Tool-Balken) und
  "Was Hermes über dich gelernt hat" (USER.md-Fakten) — beantwortet sichtbar,
  dass der Agent automatisch mitlernt.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 17:06:51 +02:00

239 lines
7.9 KiB
Python

"""
Hermes Router — Voice-Endpoints, Status & Cockpit-Reads.
Der Chat selbst ist in das eingebettete Hermes-Web-Dashboard umgezogen
(siehe `routers/hermes_ui.py`); der fruehere Eigenbau-Chat-WS/Proxy entfiel.
Endpunkte:
POST /api/hermes/transcribe — Audio → Text (Whisper)
POST /api/hermes/tts — Text → Audio WAV (Piper)
GET /api/hermes/status — Komponentenstatus (Hermes, Whisper, Piper, SSH)
GET /api/hermes/{agent,cron,skills} — Cockpit-Reads (Phase 4)
GET /api/hermes/pubkey — Bosgame SSH-Public-Key fuer Windows-Setup
"""
import asyncio
import hashlib
import subprocess
import tempfile
import threading
from pathlib import Path
from typing import Optional
import httpx
from fastapi import APIRouter, Depends, UploadFile, File
from fastapi.responses import Response, JSONResponse
from auth import auth
from config import (
PIPER_BIN, PIPER_VOICE, WHISPER_MODEL_SIZE,
HERMES_WINDOWS_HOST, HERMES_WINDOWS_USER, HERMES_SSH_KEY,
HERMES_API_URL,
)
router = APIRouter(prefix="/api")
# ---------------------------------------------------------------------------
# Whisper (lazy-loaded, einmalig in RAM)
# ---------------------------------------------------------------------------
_whisper_model = None
_whisper_loading = False
_whisper_lock = threading.Lock()
def _get_whisper():
global _whisper_model, _whisper_loading
with _whisper_lock:
if _whisper_model is not None:
return _whisper_model
if _whisper_loading:
return None
_whisper_loading = True
try:
from faster_whisper import WhisperModel
model = WhisperModel(WHISPER_MODEL_SIZE, device="cpu", compute_type="int8")
with _whisper_lock:
_whisper_model = model
return model
except Exception:
return None
finally:
with _whisper_lock:
_whisper_loading = False
# ---------------------------------------------------------------------------
# TTS-Cache (in-memory, max 64 Eintraege)
# ---------------------------------------------------------------------------
_tts_cache: dict[str, bytes] = {}
def _tts(text: str) -> Optional[bytes]:
key = hashlib.md5(text.encode()).hexdigest()
if key in _tts_cache:
return _tts_cache[key]
if not PIPER_BIN.exists() or not PIPER_VOICE.exists():
return None
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
wav_path = f.name
try:
result = subprocess.run(
[str(PIPER_BIN), "--model", str(PIPER_VOICE), "--output_file", wav_path],
input=text, capture_output=True, text=True, timeout=30
)
if result.returncode != 0:
print(f"[Piper] Fehler: {result.stderr or 'exit '+str(result.returncode)}")
return None
audio = Path(wav_path).read_bytes()
if len(_tts_cache) >= 64:
_tts_cache.pop(next(iter(_tts_cache)))
_tts_cache[key] = audio
return audio
except Exception:
return None
finally:
Path(wav_path).unlink(missing_ok=True)
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@router.post("/hermes/transcribe", dependencies=[Depends(auth)])
async def transcribe_audio(audio: UploadFile = File(...)):
"""Audio-Datei (webm/ogg/wav) per Whisper transkribieren."""
model = _get_whisper()
if model is None:
return JSONResponse(
status_code=503,
content={"error": "Whisper nicht verfuegbar. Bitte faster-whisper installieren."}
)
with tempfile.NamedTemporaryFile(suffix=".webm", delete=False) as f:
tmp = Path(f.name)
tmp.write_bytes(await audio.read())
try:
segments, _ = await asyncio.get_running_loop().run_in_executor(
None, lambda: model.transcribe(str(tmp), language="de")
)
text = " ".join(s.text.strip() for s in segments).strip()
return {"text": text}
except Exception as exc:
return JSONResponse(status_code=500, content={"error": str(exc)})
finally:
tmp.unlink(missing_ok=True)
@router.post("/hermes/tts", dependencies=[Depends(auth)])
async def text_to_speech(body: dict):
"""Text zu WAV-Audio per Piper TTS konvertieren."""
text = (body.get("text") or "").strip()
if not text:
return JSONResponse(status_code=400, content={"error": "Kein Text angegeben."})
audio = await asyncio.get_running_loop().run_in_executor(None, lambda: _tts(text))
if audio is None:
return JSONResponse(
status_code=503,
content={"error": "Piper TTS nicht verfuegbar. Bitte Piper Binary + Stimme installieren."}
)
return Response(content=audio, media_type="audio/wav")
@router.get("/hermes/status", dependencies=[Depends(auth)])
def hermes_status():
"""Status aller Hermes-Komponenten."""
# Whisper
try:
from faster_whisper import WhisperModel # noqa
whisper = "ready" if _whisper_model else "installed"
except ImportError:
whisper = "not_installed"
# Piper
piper = "ready" if (PIPER_BIN.exists() and PIPER_VOICE.exists()) else "not_installed"
# SSH
ssh_configured = bool(HERMES_WINDOWS_HOST) and HERMES_SSH_KEY.exists()
ssh_ok = False
if ssh_configured:
try:
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
HERMES_WINDOWS_HOST,
username=HERMES_WINDOWS_USER,
key_filename=str(HERMES_SSH_KEY),
timeout=3,
)
c.close()
ssh_ok = True
except Exception:
ssh_ok = False
# Hermes-Agent-Server (:8642) — erreichbar?
try:
httpx.get(HERMES_API_URL.rsplit("/v1", 1)[0] + "/", timeout=2)
hermes = "ready"
except Exception:
hermes = "offline"
return {
"hermes": hermes,
"whisper": whisper,
"piper": piper,
"ssh_configured": ssh_configured,
"ssh_ok": ssh_ok,
"windows_host": HERMES_WINDOWS_HOST or None,
}
@router.get("/hermes/agent", dependencies=[Depends(auth)])
def hermes_agent_status():
"""Phase 4 — Live-Status des Hermes-Agent-Gateways + Cron-Tickers."""
from hermes_control import agent_status
return agent_status()
@router.get("/hermes/cron", dependencies=[Depends(auth)])
def hermes_cron():
"""Phase 4 — geplante Cron-Jobs des Hermes-Agenten (inkl. pausierter)."""
from hermes_control import cron_jobs
return {"jobs": cron_jobs()}
@router.get("/hermes/skills", dependencies=[Depends(auth)])
def hermes_skills():
"""Phase 4 — installierte Skills des Hermes-Agenten + Nutzungszaehler."""
from hermes_control import skills
return {"skills": skills()}
@router.get("/hermes/learned", dependencies=[Depends(auth)])
def hermes_learned():
"""Phase 8 — was Hermes ueber den Nutzer gelernt hat (USER.md/MEMORY.md)."""
from hermes_control import learned_profile
return learned_profile()
@router.get("/hermes/insights", dependencies=[Depends(auth)])
def hermes_insights():
"""Phase 8 — Aktivitaets-Kennzahlen (Sessions/Tokens/Top-Tools)."""
from hermes_control import insights
return insights()
@router.get("/hermes/pubkey", dependencies=[Depends(auth)])
def hermes_pubkey():
"""Gibt den SSH-Public-Key des Hermes Agent zurueck (fuer Windows authorized_keys)."""
pub = Path(str(HERMES_SSH_KEY) + ".pub")
if not pub.exists():
return JSONResponse(
status_code=404,
content={"error": "Kein SSH-Key gefunden. Bitte auf dem Bosgame generieren: "
"ssh-keygen -t ed25519 -C 'hermes-agent@bosgame' "
f"-f {HERMES_SSH_KEY} -N ''"}
)
return {"pubkey": pub.read_text().strip()}