import subprocess
import numpy as np
import whisper
import requests
import time

MISTY_IP = "192.168.68.57"
RTSP_URL = f"rtsp://{MISTY_IP}:1936"

print("Lade Whisper (tiny)...")
model = whisper.load_model("tiny")

def set_misty_led(r, g, b):
    try:
        requests.post(f"http://{MISTY_IP}/api/led", json={"red": r, "green": g, "blue": b}, timeout=1)
    except: pass

ffmpeg_cmd = [
    'ffmpeg', '-rtsp_transport', 'tcp', '-i', RTSP_URL,
    '-vn', '-f', 's16le', '-ac', '1', '-ar', '16000', '-'
]

process = subprocess.Popen(ffmpeg_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
set_misty_led(0, 255, 0) # Startet Grün
print(">>> MONITORING LÄUFT. Sprich jetzt!")

try:
    # 3-Sekunden-Fenster
    chunk_size = 16000 * 2 * 3
    while True:
        data = process.stdout.read(chunk_size)
        if not data: break
        
        audio = np.frombuffer(data, dtype=np.int16).astype(np.float32) / 32768.0
        result = model.transcribe(audio, fp16=False, language="de")
        text = result["text"].strip().lower()
        
        if text:
            print(f"Erkannt: {text}")
            if any(w in text for w in ["äh", "ähm", "halt", "quasi"]):
                print("⚠️  FÜLLWORT!")
                set_misty_led(255, 0, 0) # Rot bei Fehler
                time.sleep(1)
                set_misty_led(0, 255, 0) # Zurück zu Grün
except KeyboardInterrupt:
    process.terminate()
