Głos: STT (whisper-cli przez PTT) + TTS (piper) z konfiguracją w GUI
This commit is contained in:
1 parent
19dfb84e81
commit
6e5cc6b414
1 file changed
+159
@@ -19,6 +19,8 @@ WAZNE (bezpieczenstwo watkow):
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from XPPython3 import xp
|
||||
from XPPython3.xp_imgui import Window as ImguiWindow
|
||||
@@ -57,6 +59,17 @@ DEFAULT_CONFIG = {
|
||||
"include_flight_context": True,
|
||||
"no_think": True, # dodaje /no_think do promptu (modele Qwen3 z reasoningiem)
|
||||
"window_always_on_top": True,
|
||||
# --- Glos (whisper / piper) ---
|
||||
"voice_enabled": True,
|
||||
"voice_ptt_mode": "hold", # "hold" = przytrzymaj PTT, mowisz, puszczasz; "toggle" = wcisnij aby zaczac/konczyc
|
||||
"whisper_cli": "/usr/bin/whisper-cli",
|
||||
"whisper_model": "/home/pali112/models/ggml-small.bin",
|
||||
"whisper_language": "auto",
|
||||
"record_cmd": ["parecord", "--format=s16le", "--rate=16000", "--channels=1"],
|
||||
"piper": "/opt/piper-tts/piper",
|
||||
"piper_model": "/home/pali112/.local/share/piper-voices/en_US-lessac-medium.onnx",
|
||||
"play_cmd": ["aplay", "-q"],
|
||||
"tts_enabled": True,
|
||||
}
|
||||
|
||||
# Dataref -> (nazwa kontekstu, mnoznik, jednostka)
|
||||
@@ -132,6 +145,11 @@ class XSayATC:
|
||||
# VR
|
||||
self._last_vr = None
|
||||
|
||||
# Glos (STT / TTS)
|
||||
self._recording = False
|
||||
self._record_proc = None
|
||||
self._ptt_toggled = False # dla trybu "toggle"
|
||||
|
||||
# ---------------------------- Config ----------------------------
|
||||
def _load_config(self):
|
||||
cfg = dict(DEFAULT_CONFIG)
|
||||
@@ -427,6 +445,11 @@ class XSayATC:
|
||||
self.messages[-1]["text"] = f"(blad: {e})"
|
||||
finally:
|
||||
self.streaming = False
|
||||
# Odczytaj odpowiedz glosem (TTS) w osobnym watku
|
||||
if self.config.get("tts_enabled", True) and self.messages:
|
||||
last_text = self.messages[-1].get("text", "")
|
||||
if last_text and last_text not in ("(brak odpowiedzi)",):
|
||||
threading.Thread(target=self._speak, args=(last_text,), daemon=True).start()
|
||||
|
||||
def send(self, text):
|
||||
"""Wywolywane na glownym watku (przycisk / PTT). Zbiera kontekst tu, bo tu wolno."""
|
||||
@@ -451,6 +474,111 @@ class XSayATC:
|
||||
def stop(self):
|
||||
self._stop_event.set()
|
||||
|
||||
# ---------------------------- Glos (STT / TTS) ----------------------------
|
||||
def _voice_enabled(self):
|
||||
return bool(self.config.get("voice_enabled", True))
|
||||
|
||||
def _start_recording(self):
|
||||
"""Rozpoczyna nagrywanie mikrofonu do pliku tymczasowego."""
|
||||
if self._recording:
|
||||
return
|
||||
import tempfile
|
||||
self._record_file = tempfile.mktemp(suffix=".wav", prefix="xsayatc_")
|
||||
cmd = list(self.config.get("record_cmd", ["parecord", "--format=s16le", "--rate=16000", "--channels=1"]))
|
||||
cmd.append(self._record_file)
|
||||
try:
|
||||
self._record_proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
self._recording = True
|
||||
self.status = "Nagrywanie... (pusc PTT aby wyslac)"
|
||||
except Exception as e:
|
||||
xp.log(f"[XSayATC] Blad nagrywania: {e}")
|
||||
self._record_proc = None
|
||||
|
||||
def _stop_recording_and_send(self):
|
||||
"""Konczy nagrywanie, transkrybuje whisperem i wysyla tekst."""
|
||||
if not self._recording:
|
||||
return
|
||||
self._recording = False
|
||||
if self._record_proc is not None:
|
||||
try:
|
||||
self._record_proc.terminate()
|
||||
try:
|
||||
self._record_proc.wait(timeout=3)
|
||||
except Exception:
|
||||
self._record_proc.kill()
|
||||
except Exception:
|
||||
pass
|
||||
self._record_proc = None
|
||||
|
||||
wav = getattr(self, "_record_file", None)
|
||||
if not wav or not os.path.exists(wav):
|
||||
self.status = "Blad: brak nagrania"
|
||||
return
|
||||
|
||||
self.status = "Transkrybuje (whisper)..."
|
||||
text = self._transcribe(wav)
|
||||
try:
|
||||
os.remove(wav)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if text:
|
||||
self.send(text)
|
||||
else:
|
||||
self.status = "Nie rozpoznano mowy."
|
||||
|
||||
def _transcribe(self, wav_path):
|
||||
"""Uruchamia whisper-cli i zwraca rozpoznany tekst."""
|
||||
import tempfile
|
||||
out_file = tempfile.mktemp(suffix="", prefix="xsayatc_stt_")
|
||||
cli = self.config.get("whisper_cli", "/usr/bin/whisper-cli")
|
||||
model = self.config.get("whisper_model", "")
|
||||
lang = self.config.get("whisper_language", "auto")
|
||||
cmd = [cli, "-m", model, "-l", lang, "-otxt", "-of", out_file, "-f", wav_path, "-np"]
|
||||
try:
|
||||
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=60)
|
||||
txt_file = out_file + ".txt"
|
||||
if os.path.exists(txt_file):
|
||||
with open(txt_file, "r", encoding="utf-8") as f:
|
||||
text = f.read().strip()
|
||||
try:
|
||||
os.remove(txt_file)
|
||||
except Exception:
|
||||
pass
|
||||
return text
|
||||
return ""
|
||||
except Exception as e:
|
||||
xp.log(f"[XSayATC] Blad whisper: {e}")
|
||||
return ""
|
||||
|
||||
def _speak(self, text):
|
||||
"""Synteza mowy (piper) i odtworzenie (aplay). Watek roboczy."""
|
||||
if not self.config.get("tts_enabled", True):
|
||||
return
|
||||
text = (text or "").strip()
|
||||
if not text:
|
||||
return
|
||||
piper = self.config.get("piper", "/opt/piper-tts/piper")
|
||||
model = self.config.get("piper_model", "")
|
||||
import tempfile
|
||||
wav = tempfile.mktemp(suffix=".wav", prefix="xsayatc_tts_")
|
||||
try:
|
||||
# piper czyta tekst ze stdin, zapisuje WAV
|
||||
with open(wav, "wb") as out:
|
||||
p = subprocess.Popen(
|
||||
[piper, "-m", model, "-f", wav],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
p.communicate(input=text.encode("utf-8"), timeout=60)
|
||||
if os.path.exists(wav):
|
||||
play_cmd = list(self.config.get("play_cmd", ["aplay", "-q"]))
|
||||
subprocess.run(play_cmd + [wav], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=60)
|
||||
try:
|
||||
os.remove(wav)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
xp.log(f"[XSayATC] Blad TTS: {e}")
|
||||
|
||||
# ---------------------------- VR ----------------------------
|
||||
def _vr_flight_loop(self, lastCall, elapsed, counter, refCon):
|
||||
"""Co 1s sprawdza stan VR i ustawia tryb pozycjonowania okien (glowny watek)."""
|
||||
@@ -538,6 +666,17 @@ class XSayATC:
|
||||
_, self.config["include_flight_context"] = imgui.checkbox(
|
||||
"Dolacz kontekst lotu", self.config["include_flight_context"])
|
||||
|
||||
imgui.separator()
|
||||
imgui.text("Glos (whisper / piper):")
|
||||
_, self.config["voice_enabled"] = imgui.checkbox(
|
||||
"Glos wlaczony (STT)", self.config["voice_enabled"])
|
||||
_, self.config["tts_enabled"] = imgui.checkbox(
|
||||
"Odczytywanie odpowiedzi (TTS)", self.config["tts_enabled"])
|
||||
_, self.config["whisper_model"] = imgui.input_text(
|
||||
"Model whisper", self.config["whisper_model"], 512)
|
||||
_, self.config["piper_model"] = imgui.input_text(
|
||||
"Model piper", self.config["piper_model"], 512)
|
||||
|
||||
imgui.separator()
|
||||
imgui.text("System prompt (instrukcje ATC):")
|
||||
_, self.config["system_prompt"] = imgui.input_text_multiline(
|
||||
@@ -631,6 +770,26 @@ class XSayATC:
|
||||
|
||||
# ---------------------------- Handlery ----------------------------
|
||||
def _ptt_handler(self, cmdRef, phase, refCon):
|
||||
# Glos: PTT steruje nagrywaniem
|
||||
if self._voice_enabled():
|
||||
mode = self.config.get("voice_ptt_mode", "hold")
|
||||
if mode == "toggle":
|
||||
if phase == xp.CommandBegin:
|
||||
if self._recording:
|
||||
self._stop_recording_and_send()
|
||||
else:
|
||||
self._start_recording()
|
||||
return 0
|
||||
else: # "hold"
|
||||
if phase == xp.CommandBegin:
|
||||
self._start_recording()
|
||||
return 0
|
||||
elif phase == xp.CommandEnd:
|
||||
self._stop_recording_and_send()
|
||||
return 0
|
||||
return 1
|
||||
|
||||
# Tryb tekstowy (bez glosu)
|
||||
if phase == xp.CommandBegin:
|
||||
text = self.pending_text.strip()
|
||||
if text:
|
||||
|
||||
Reference in new issue
Block a user