runner.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  1. # -*- coding: utf-8 -*-
  2. """
  3. InstallRunner — Fuehrt Installationsschritte aus.
  4. Steuert Progress, Logging und Abbruch.
  5. """
  6. from __future__ import annotations
  7. import asyncio
  8. import os
  9. import shutil
  10. from typing import Callable
  11. from .config import InstallerConfig
  12. from .steps import InstallationStep, get_steps
  13. class InstallRunner:
  14. """
  15. Fuehrt Installationsschritte sequentiell aus.
  16. Bietet gewichtete Progress-Updates und Echtzeit-Log.
  17. """
  18. def __init__(
  19. self,
  20. config: InstallerConfig,
  21. log_callback: Callable[[str], None],
  22. progress_callback: Callable[[float, str], None],
  23. ) -> None:
  24. self._config = config
  25. self._log = log_callback
  26. self._progress = progress_callback
  27. self._cancelled = False
  28. self._current_process: asyncio.subprocess.Process | None = None
  29. def cancel(self) -> None:
  30. """Bricht die Installation ab."""
  31. self._cancelled = True
  32. if self._current_process and self._current_process.returncode is None:
  33. self._current_process.terminate()
  34. async def run(self) -> bool:
  35. """
  36. Fuehrt alle Schritte aus.
  37. Returns:
  38. True bei Erfolg, False bei Fehler/Abbruch.
  39. """
  40. steps = get_steps(self._config.mode)
  41. total_weight = sum(s.weight for s in steps)
  42. completed_weight = 0
  43. self._log(f"=== Trixy {self._config.mode.title()} Installation ===")
  44. self._log(f"Version: {self._config.version}")
  45. self._log(f"Ziel: {self._config.install_path}")
  46. self._log("")
  47. # Sudo-Rechte vorab sicherstellen
  48. needs_sudo = any(
  49. s.command_fn in (
  50. "step_apt_packages", "step_hostname", "step_wifi_ap",
  51. "step_directories", "step_systemd",
  52. )
  53. for s in steps
  54. )
  55. if needs_sudo:
  56. self._log("Pruefe sudo-Rechte...")
  57. code, _ = await self._run_cmd("sudo", "-v", check=False)
  58. if code != 0:
  59. self._log(" FEHLER: sudo-Rechte benoetigt aber nicht verfuegbar.")
  60. self._log(" Bitte Installer mit 'sudo ./install-{mode}.sh' starten")
  61. self._log(" oder den Benutzer zur sudoers-Gruppe hinzufuegen.")
  62. return False
  63. self._log(" -> sudo verfuegbar\n")
  64. for i, step in enumerate(steps, 1):
  65. if self._cancelled:
  66. self._log("\n[ABBRUCH] Installation wurde abgebrochen.")
  67. return False
  68. self._log(f"[{i}/{len(steps)}] {step.name}...")
  69. self._progress(completed_weight / total_weight, step.name)
  70. method = getattr(self, step.command_fn, None)
  71. if method is None:
  72. self._log(f" WARNUNG: Methode {step.command_fn} nicht implementiert")
  73. completed_weight += step.weight
  74. continue
  75. try:
  76. success = await method()
  77. if not success:
  78. self._log(f" FEHLER bei Schritt: {step.name}")
  79. return False
  80. except Exception as e:
  81. self._log(f" FEHLER: {e}")
  82. return False
  83. completed_weight += step.weight
  84. self._progress(completed_weight / total_weight, step.name)
  85. self._log(f" -> {step.name} abgeschlossen\n")
  86. self._progress(1.0, "Fertig")
  87. self._log("=== Installation erfolgreich abgeschlossen ===")
  88. return True
  89. # --- Hilfsmethoden ---
  90. _ANSI_RE = None # Lazy-compiled Regex
  91. @staticmethod
  92. def _clean_ansi(text: str) -> str:
  93. """Entfernt ANSI Escape-Sequenzen aus Text."""
  94. import re
  95. if InstallRunner._ANSI_RE is None:
  96. InstallRunner._ANSI_RE = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]")
  97. return InstallRunner._ANSI_RE.sub("", text)
  98. async def _run_cmd(self, *args: str, check: bool = True) -> tuple[int, str]:
  99. """Fuehrt einen Befehl aus und loggt die Ausgabe."""
  100. self._log(f" $ {' '.join(args)}")
  101. # TMPDIR auf Installationspfad umleiten (tmpfs auf Pi zu klein fuer pip)
  102. env = os.environ.copy()
  103. tmp_dir = f"{self._config.install_path}/tmp"
  104. os.makedirs(tmp_dir, exist_ok=True)
  105. env["TMPDIR"] = tmp_dir
  106. env["PIP_CACHE_DIR"] = f"{self._config.install_path}/pip-cache"
  107. proc = await asyncio.create_subprocess_exec(
  108. *args,
  109. stdout=asyncio.subprocess.PIPE,
  110. stderr=asyncio.subprocess.STDOUT,
  111. env=env,
  112. )
  113. self._current_process = proc
  114. output_lines: list[str] = []
  115. assert proc.stdout is not None
  116. while True:
  117. line = await proc.stdout.readline()
  118. if not line:
  119. break
  120. decoded = line.decode("utf-8", errors="replace").rstrip()
  121. # \r-basierte Progress-Zeilen: nur letzten Teil nehmen
  122. if "\r" in decoded:
  123. decoded = decoded.rsplit("\r", 1)[-1].strip()
  124. # ANSI-Codes entfernen
  125. decoded = self._clean_ansi(decoded)
  126. if not decoded:
  127. continue
  128. output_lines.append(decoded)
  129. self._log(f" {decoded}")
  130. if self._cancelled:
  131. proc.terminate()
  132. await proc.wait()
  133. return -1, "Abgebrochen"
  134. await proc.wait()
  135. self._current_process = None
  136. output = "\n".join(output_lines)
  137. if check and proc.returncode != 0:
  138. self._log(f" Befehl fehlgeschlagen (Exit-Code: {proc.returncode})")
  139. return proc.returncode or 0, output
  140. async def _run_sudo(self, *args: str, check: bool = True) -> tuple[int, str]:
  141. """Fuehrt einen Befehl mit sudo aus."""
  142. return await self._run_cmd("sudo", *args, check=check)
  143. # --- Installations-Schritte ---
  144. async def step_extract(self) -> bool:
  145. """Entpackt das Quellarchiv nach source/."""
  146. archive = self._config.source_archive
  147. source = self._config.source_path # install_path/source
  148. if not os.path.isfile(archive):
  149. self._log(f" Archiv nicht gefunden: {archive}")
  150. return False
  151. # source-Verzeichnis erstellen
  152. code, _ = await self._run_sudo("mkdir", "-p", source)
  153. if code != 0:
  154. return False
  155. # Besitzer setzen
  156. await self._run_sudo("chown", self._config.username, self._config.install_path)
  157. # Entpacken — strip-components=1 entfernt den Prefix (trixy-server-1.0.0/)
  158. self._log(f" Entpacke nach {source}...")
  159. code, _ = await self._run_cmd(
  160. "tar", "xzf", archive, "-C", source, "--strip-components=1",
  161. )
  162. return code == 0
  163. # Paketnamen pro Paketmanager
  164. # Schluessel = kanonischer Name, Werte = {pm: paketname}
  165. _PKG_MAP: dict[str, dict[str, str]] = {
  166. "python3": {"apt": "python3", "dnf": "python3", "pacman": "python", "zypper": "python3"},
  167. "python3-venv": {"apt": "python3-venv", "dnf": "python3-venv", "pacman": "python", "zypper": "python3-venv"},
  168. "python3-pip": {"apt": "python3-pip", "dnf": "python3-pip", "pacman": "python-pip", "zypper": "python3-pip"},
  169. "python3-dev": {"apt": "python3-dev", "dnf": "python3-devel", "pacman": "python", "zypper": "python3-devel"},
  170. "git": {"apt": "git", "dnf": "git", "pacman": "git", "zypper": "git"},
  171. "curl": {"apt": "curl", "dnf": "curl", "pacman": "curl", "zypper": "curl"},
  172. "wget": {"apt": "wget", "dnf": "wget", "pacman": "wget", "zypper": "wget"},
  173. "alsa-utils": {"apt": "alsa-utils", "dnf": "alsa-utils", "pacman": "alsa-utils", "zypper": "alsa-utils"},
  174. "ffmpeg": {"apt": "ffmpeg", "dnf": "ffmpeg-free", "pacman": "ffmpeg", "zypper": "ffmpeg"},
  175. "portaudio-dev": {"apt": "portaudio19-dev", "dnf": "portaudio-devel", "pacman": "portaudio", "zypper": "portaudio-devel"},
  176. "alsa-dev": {"apt": "libasound2-dev", "dnf": "alsa-lib-devel", "pacman": "alsa-lib", "zypper": "alsa-devel"},
  177. "openblas-dev": {"apt": "libopenblas-dev", "dnf": "openblas-devel", "pacman": "openblas", "zypper": "openblas-devel"},
  178. "lapack-dev": {"apt": "liblapack-dev", "dnf": "lapack-devel", "pacman": "lapack", "zypper": "lapack-devel"},
  179. "gfortran": {"apt": "gfortran", "dnf": "gcc-gfortran", "pacman": "gcc-fortran", "zypper": "gcc-fortran"},
  180. "ffi-dev": {"apt": "libffi-dev", "dnf": "libffi-devel", "pacman": "libffi", "zypper": "libffi-devel"},
  181. "ssl-dev": {"apt": "libssl-dev", "dnf": "openssl-devel", "pacman": "openssl", "zypper": "libopenssl-devel"},
  182. "hostapd": {"apt": "hostapd", "dnf": "hostapd", "pacman": "hostapd", "zypper": "hostapd"},
  183. "dnsmasq": {"apt": "dnsmasq", "dnf": "dnsmasq", "pacman": "dnsmasq", "zypper": "dnsmasq"},
  184. "iptables": {"apt": "iptables", "dnf": "iptables", "pacman": "iptables", "zypper": "iptables"},
  185. "cmake": {"apt": "cmake", "dnf": "cmake", "pacman": "cmake", "zypper": "cmake"},
  186. "g++": {"apt": "g++", "dnf": "gcc-c++", "pacman": "gcc", "zypper": "gcc-c++"},
  187. "evtest": {"apt": "evtest", "dnf": "evtest", "pacman": "evtest", "zypper": "evtest"},
  188. "input-utils": {"apt": "input-utils", "dnf": "input-utils", "pacman": "input-utils", "zypper": "input-utils"},
  189. }
  190. def _detect_pkg_manager(self) -> tuple[str, list[str], list[str], list[str]]:
  191. """
  192. Erkennt den Paketmanager.
  193. Returns:
  194. (name, update_cmd, install_cmd, check_cmd)
  195. install_cmd hat Platzhalter — Pakete werden angehaengt.
  196. """
  197. managers = [
  198. ("apt", ["apt-get", "update", "-qq"], ["apt-get", "install", "-y", "-qq"], ["dpkg", "-s"]),
  199. ("dnf", ["dnf", "check-update"], ["dnf", "install", "-y", "-q"], ["rpm", "-q"]),
  200. ("pacman", ["pacman", "-Sy"], ["pacman", "-S", "--noconfirm", "--needed"], ["pacman", "-Q"]),
  201. ("zypper", ["zypper", "refresh", "-q"], ["zypper", "install", "-y", "-q"], ["rpm", "-q"]),
  202. ]
  203. for name, update, install, check in managers:
  204. if shutil.which(install[0]):
  205. return name, update, install, check
  206. return "", [], [], []
  207. def _resolve_pkg(self, canonical: str, pm: str) -> str:
  208. """Loest einen kanonischen Paketnamen fuer den erkannten Paketmanager auf."""
  209. mapping = self._PKG_MAP.get(canonical, {})
  210. return mapping.get(pm, canonical)
  211. async def _install_pkg_group(
  212. self, name: str, canonical_names: list[str], required: bool = True,
  213. ) -> bool:
  214. """Installiert eine Paketgruppe mit dem erkannten Paketmanager."""
  215. pm_name, _, install_cmd, _ = self._detect_pkg_manager()
  216. if not pm_name:
  217. self._log(f" FEHLER: Kein unterstuetzter Paketmanager gefunden (apt/dnf/pacman/zypper)")
  218. return not required
  219. # Paketnamen aufloesen
  220. packages = []
  221. for canonical in canonical_names:
  222. resolved = self._resolve_pkg(canonical, pm_name)
  223. if resolved not in packages:
  224. packages.append(resolved)
  225. self._log(f" {name} ({pm_name}): {', '.join(packages)}")
  226. code, _ = await self._run_sudo(*install_cmd, *packages)
  227. if code != 0:
  228. # Einzeln versuchen
  229. self._log(f" Gruppeninstallation fehlgeschlagen — installiere einzeln...")
  230. failed = []
  231. for pkg in packages:
  232. c, _ = await self._run_sudo(*install_cmd, pkg)
  233. if c != 0:
  234. failed.append(pkg)
  235. if failed:
  236. self._log(f" WARNUNG: Nicht verfuegbar: {', '.join(failed)}")
  237. if required:
  238. return False
  239. return True
  240. async def step_apt_packages(self) -> bool:
  241. """Installiert System-Pakete in Gruppen."""
  242. pm_name, update_cmd, _, _ = self._detect_pkg_manager()
  243. if not pm_name:
  244. self._log(" FEHLER: Kein unterstuetzter Paketmanager gefunden")
  245. self._log(" Unterstuetzt: apt (Debian/Ubuntu), dnf (Fedora/RHEL),")
  246. self._log(" pacman (Arch), zypper (openSUSE)")
  247. self._log(" Bitte Pakete manuell installieren.")
  248. return False
  249. self._log(f" Paketmanager: {pm_name}")
  250. self._log(f" Aktualisiere Paketlisten...")
  251. # dnf check-update gibt Exit 100 bei verfuegbaren Updates — das ist OK
  252. code, _ = await self._run_sudo(*update_cmd, check=False)
  253. if code != 0 and pm_name != "dnf":
  254. self._log(f" WARNUNG: Paketlisten-Update fehlgeschlagen")
  255. # Runtime-Pakete (immer benoetigt)
  256. runtime = ["python3", "python3-venv", "python3-pip", "git", "curl", "wget"]
  257. if not await self._install_pkg_group("Runtime", runtime):
  258. return False
  259. # Audio-Runtime
  260. audio = ["alsa-utils", "ffmpeg"]
  261. if not await self._install_pkg_group("Audio", audio):
  262. return False
  263. # Build-Abhaengigkeiten (optional auf x86_64 mit Wheels)
  264. build = [
  265. "python3-dev", "portaudio-dev", "alsa-dev",
  266. "openblas-dev", "lapack-dev", "gfortran",
  267. "ffi-dev", "ssl-dev",
  268. ]
  269. await self._install_pkg_group("Build-Abhaengigkeiten", build, required=False)
  270. # HID / Input-Tools (Client/Standalone — Konferenzmikrofone, Headsets)
  271. if self._config.mode in ("client", "standalone"):
  272. hid = ["evtest", "input-utils"]
  273. await self._install_pkg_group("HID/Input", hid, required=False)
  274. # WiFi-Hotspot (nur Server)
  275. if self._config.mode == "server" and self._config.wifi_enabled:
  276. wifi = ["hostapd", "dnsmasq", "iptables"]
  277. if not await self._install_pkg_group("WiFi-Hotspot", wifi):
  278. return False
  279. return True
  280. async def step_hostname(self) -> bool:
  281. """Setzt den Hostnamen."""
  282. code, _ = await self._run_sudo(
  283. "hostnamectl", "set-hostname", self._config.hostname,
  284. )
  285. return code == 0
  286. async def step_wifi_connect(self) -> bool:
  287. """Konfiguriert WLAN-Verbindung (Client/Standalone).
  288. Unterstuetzt:
  289. - Primaeres Netz mit hoher Prioritaet (100)
  290. - Optionales Fallback-Netz mit niedriger Prioritaet (10)
  291. - Auto-Rueckwechsel via systemd-Timer wenn Fallback genutzt
  292. """
  293. if not self._config.wifi_connect:
  294. self._log(" Keine WLAN-Aenderung — uebersprungen")
  295. return True
  296. cfg = self._config
  297. primary_ssid = cfg.wifi_connect_ssid
  298. primary_pw = cfg.wifi_connect_password
  299. if not shutil.which("nmcli"):
  300. self._log(" FEHLER: nmcli nicht gefunden — NetworkManager erforderlich")
  301. self._log(" Hinweis: Raspberry Pi OS Bookworm nutzt NetworkManager als Standard")
  302. return False
  303. self._log(" Verwende NetworkManager (nmcli)...")
  304. # Primaeres Netz konfigurieren (Prioritaet 100)
  305. if not await self._nmcli_add_connection(
  306. ssid=primary_ssid, password=primary_pw, priority=100,
  307. ):
  308. self._log(f" FEHLER: Primaere Verbindung '{primary_ssid}' konnte nicht angelegt werden")
  309. return False
  310. self._log(f" Primaeres Netz angelegt: {primary_ssid} (Prioritaet 100)")
  311. # Fallback-Netz konfigurieren wenn aktiviert
  312. fallback_ssid = ""
  313. if cfg.wifi_fallback_enabled:
  314. fallback_ssid = cfg.wifi_fallback_ssid
  315. if await self._nmcli_add_connection(
  316. ssid=fallback_ssid, password=cfg.wifi_fallback_password, priority=10,
  317. ):
  318. self._log(f" Fallback-Netz angelegt: {fallback_ssid} (Prioritaet 10)")
  319. else:
  320. self._log(f" WARNUNG: Fallback-Verbindung '{fallback_ssid}' konnte nicht angelegt werden")
  321. fallback_ssid = ""
  322. # Auf primaeres Netz verbinden (mit Retry)
  323. connected = await self._nmcli_try_connect(primary_ssid, max_wait=30)
  324. if connected:
  325. self._log(f" -> Verbunden mit primaerem Netz: {primary_ssid}")
  326. elif fallback_ssid:
  327. self._log(f" Primaeres Netz nicht erreichbar — versuche Fallback: {fallback_ssid}")
  328. if await self._nmcli_try_connect(fallback_ssid, max_wait=15):
  329. self._log(f" -> Verbunden mit Fallback-Netz: {fallback_ssid}")
  330. else:
  331. self._log(f" WARNUNG: Weder primaeres noch Fallback-Netz erreichbar")
  332. else:
  333. self._log(f" WARNUNG: {primary_ssid} aktuell nicht erreichbar — wird beim naechsten Verbinden aktiviert")
  334. # Failover-Script + Timer installieren (wenn Fallback + Auto-Switchback)
  335. if cfg.wifi_fallback_enabled and cfg.wifi_auto_switchback:
  336. if await self._install_wifi_failover_service(
  337. primary_ssid=primary_ssid,
  338. fallback_ssid=fallback_ssid or cfg.wifi_fallback_ssid,
  339. interval=cfg.wifi_switchback_interval,
  340. ):
  341. self._log(f" -> Auto-Rueckwechsel aktiviert (alle {cfg.wifi_switchback_interval}s)")
  342. else:
  343. self._log(" WARNUNG: Auto-Rueckwechsel konnte nicht installiert werden")
  344. return True
  345. # --- nmcli Helper ---
  346. async def _nmcli_add_connection(
  347. self, ssid: str, password: str, priority: int,
  348. ) -> bool:
  349. """Legt eine NetworkManager WLAN-Verbindung an (oder aktualisiert sie)."""
  350. con_name = f"trixy-{ssid}"
  351. # Bestehende Verbindung mit gleichem Namen entfernen (idempotent)
  352. await self._run_sudo(
  353. "nmcli", "connection", "delete", con_name, check=False,
  354. )
  355. # Connection anlegen
  356. code, _ = await self._run_sudo(
  357. "nmcli", "connection", "add",
  358. "type", "wifi",
  359. "con-name", con_name,
  360. "ifname", "wlan0",
  361. "ssid", ssid,
  362. )
  363. if code != 0:
  364. return False
  365. # Passwort, Prioritaet, Auto-Connect konfigurieren
  366. code, _ = await self._run_sudo(
  367. "nmcli", "connection", "modify", con_name,
  368. "wifi-sec.key-mgmt", "wpa-psk",
  369. "wifi-sec.psk", password,
  370. "connection.autoconnect", "yes",
  371. "connection.autoconnect-priority", str(priority),
  372. "connection.autoconnect-retries", "0",
  373. )
  374. return code == 0
  375. async def _nmcli_try_connect(self, ssid: str, max_wait: int = 30) -> bool:
  376. """Versucht eine Connection zu aktivieren, mit Rescan-Retry.
  377. Wartet bis das Netz sichtbar ist und aktiviert die Verbindung.
  378. """
  379. con_name = f"trixy-{ssid}"
  380. waited = 0
  381. # Rescan erzwingen
  382. await self._run_sudo("nmcli", "device", "wifi", "rescan", check=False)
  383. while waited < max_wait:
  384. # Ist das Netz im Scan sichtbar?
  385. code, output = await self._run_cmd(
  386. "nmcli", "-t", "-f", "SSID", "device", "wifi", "list",
  387. check=False,
  388. )
  389. if code == 0 and ssid in output.splitlines():
  390. # Verbinden
  391. code, _ = await self._run_sudo(
  392. "nmcli", "connection", "up", con_name, check=False,
  393. )
  394. if code == 0:
  395. return True
  396. await asyncio.sleep(2)
  397. waited += 2
  398. await self._run_sudo("nmcli", "device", "wifi", "rescan", check=False)
  399. return False
  400. async def _install_wifi_failover_service(
  401. self, primary_ssid: str, fallback_ssid: str, interval: int,
  402. ) -> bool:
  403. """Installiert ein Failover-Script + systemd-Timer fuer Auto-Switchback.
  404. Prueft periodisch ob das primaere Netz wieder erreichbar ist, und
  405. wechselt dann von Fallback zurueck zum primaeren Netz.
  406. """
  407. primary_con = f"trixy-{primary_ssid}"
  408. fallback_con = f"trixy-{fallback_ssid}"
  409. # Shell-Escape fuer SSIDs (verhindert Injection)
  410. def sh_escape(s: str) -> str:
  411. return s.replace("\\", "\\\\").replace('"', '\\"').replace("$", "\\$")
  412. script_content = f"""#!/usr/bin/env bash
  413. # ============================================================================
  414. # Trixy WLAN Auto-Switchback
  415. # Generiert vom Trixy-Installer — NICHT manuell editieren
  416. #
  417. # Prueft periodisch ob das primaere Netz erreichbar ist und wechselt zurueck
  418. # wenn der Client aktuell am Fallback-Netz haengt.
  419. # ============================================================================
  420. set -u
  421. PRIMARY_CON="{sh_escape(primary_con)}"
  422. PRIMARY_SSID="{sh_escape(primary_ssid)}"
  423. FALLBACK_CON="{sh_escape(fallback_con)}"
  424. FALLBACK_SSID="{sh_escape(fallback_ssid)}"
  425. # Aktuell aktive Verbindung auf wlan0 ermitteln
  426. current=$(nmcli -t -f NAME,DEVICE connection show --active \\
  427. | awk -F':' '$2 == "wlan0" {{ print $1; exit }}')
  428. # Bereits am primaeren Netz? -> fertig
  429. if [[ "${{current}}" == "${{PRIMARY_CON}}" ]]; then
  430. exit 0
  431. fi
  432. # Nur handeln wenn wir am Fallback haengen
  433. if [[ "${{current}}" != "${{FALLBACK_CON}}" ]]; then
  434. exit 0
  435. fi
  436. # Scan erzwingen
  437. nmcli device wifi rescan >/dev/null 2>&1 || true
  438. sleep 3
  439. # Ist das primaere Netz wieder sichtbar?
  440. if ! nmcli -t -f SSID device wifi list | grep -qxF "${{PRIMARY_SSID}}"; then
  441. exit 0
  442. fi
  443. # Wechsel versuchen
  444. logger -t trixy-wifi "Primaeres Netz ${{PRIMARY_SSID}} wieder sichtbar — wechsle zurueck"
  445. if nmcli connection up "${{PRIMARY_CON}}" >/dev/null 2>&1; then
  446. logger -t trixy-wifi "Wechsel erfolgreich"
  447. else
  448. logger -t trixy-wifi "Wechsel fehlgeschlagen — bleibe auf Fallback"
  449. fi
  450. """
  451. service_content = """[Unit]
  452. Description=Trixy WLAN Auto-Switchback
  453. After=NetworkManager.service
  454. Wants=NetworkManager.service
  455. [Service]
  456. Type=oneshot
  457. ExecStart=/usr/local/bin/trixy-wifi-switchback.sh
  458. """
  459. timer_content = f"""[Unit]
  460. Description=Trixy WLAN Auto-Switchback Timer
  461. [Timer]
  462. OnBootSec=2min
  463. OnUnitActiveSec={interval}s
  464. Unit=trixy-wifi-switchback.service
  465. [Install]
  466. WantedBy=timers.target
  467. """
  468. # Script schreiben
  469. if not await self._write_file_sudo(
  470. "/usr/local/bin/trixy-wifi-switchback.sh", script_content, mode="755",
  471. ):
  472. return False
  473. # Service schreiben
  474. if not await self._write_file_sudo(
  475. "/etc/systemd/system/trixy-wifi-switchback.service", service_content,
  476. ):
  477. return False
  478. # Timer schreiben
  479. if not await self._write_file_sudo(
  480. "/etc/systemd/system/trixy-wifi-switchback.timer", timer_content,
  481. ):
  482. return False
  483. # Systemd reload
  484. await self._run_sudo("systemctl", "daemon-reload", check=False)
  485. # Timer aktivieren und starten
  486. code, _ = await self._run_sudo(
  487. "systemctl", "enable", "--now", "trixy-wifi-switchback.timer",
  488. check=False,
  489. )
  490. return code == 0
  491. async def _write_file_sudo(
  492. self, path: str, content: str, mode: str = "644",
  493. ) -> bool:
  494. """Schreibt eine Datei mit sudo tee und setzt die Berechtigungen."""
  495. proc = await asyncio.create_subprocess_exec(
  496. "sudo", "tee", path,
  497. stdin=asyncio.subprocess.PIPE,
  498. stdout=asyncio.subprocess.DEVNULL,
  499. stderr=asyncio.subprocess.DEVNULL,
  500. )
  501. await proc.communicate(content.encode())
  502. if proc.returncode != 0:
  503. return False
  504. code, _ = await self._run_sudo("chmod", mode, path, check=False)
  505. return code == 0
  506. async def step_wifi_ap(self) -> bool:
  507. """Konfiguriert WiFi Access Point."""
  508. if not self._config.wifi_enabled:
  509. self._log(" WiFi-Hotspot deaktiviert — uebersprungen")
  510. return True
  511. cfg = self._config
  512. # hostapd konfigurieren
  513. hostapd_conf = f"""# Trixy Access Point
  514. interface=wlan0
  515. driver=nl80211
  516. ssid={cfg.wifi_ssid}
  517. hw_mode=g
  518. channel={cfg.wifi_channel}
  519. wmm_enabled=0
  520. macaddr_acl=0
  521. auth_algs=1
  522. ignore_broadcast_ssid=0
  523. wpa=2
  524. wpa_passphrase={cfg.wifi_password}
  525. wpa_key_mgmt=WPA-PSK
  526. wpa_pairwise=TKIP
  527. rsn_pairwise=CCMP
  528. country_code=DE
  529. ieee80211n=1
  530. ieee80211d=1
  531. """
  532. # Ueber tee schreiben (braucht sudo)
  533. proc = await asyncio.create_subprocess_exec(
  534. "sudo", "tee", "/etc/hostapd/hostapd.conf",
  535. stdin=asyncio.subprocess.PIPE,
  536. stdout=asyncio.subprocess.DEVNULL,
  537. )
  538. await proc.communicate(hostapd_conf.encode())
  539. # dnsmasq konfigurieren
  540. dnsmasq_conf = f"""# Trixy DHCP-Server
  541. interface=wlan0
  542. bind-interfaces
  543. dhcp-range={cfg.dhcp_range_start},{cfg.dhcp_range_end},255.255.255.0,12h
  544. server=8.8.8.8
  545. server=8.8.4.4
  546. address=/{cfg.wifi_ssid}/{cfg.ap_ip}
  547. """
  548. proc = await asyncio.create_subprocess_exec(
  549. "sudo", "tee", "/etc/dnsmasq.conf",
  550. stdin=asyncio.subprocess.PIPE,
  551. stdout=asyncio.subprocess.DEVNULL,
  552. )
  553. await proc.communicate(dnsmasq_conf.encode())
  554. # dhcpcd — statische IP
  555. dhcpcd_block = f"""
  556. # Trixy AP — wlan0 statische IP
  557. interface wlan0
  558. static ip_address={cfg.ap_ip}/24
  559. nohook wpa_supplicant
  560. """
  561. proc = await asyncio.create_subprocess_exec(
  562. "sudo", "tee", "-a", "/etc/dhcpcd.conf",
  563. stdin=asyncio.subprocess.PIPE,
  564. stdout=asyncio.subprocess.DEVNULL,
  565. )
  566. await proc.communicate(dhcpcd_block.encode())
  567. # IP-Forwarding und NAT
  568. await self._run_sudo("sysctl", "-w", "net.ipv4.ip_forward=1")
  569. await self._run_sudo(
  570. "iptables", "-t", "nat", "-A", "POSTROUTING", "-o", "eth0", "-j", "MASQUERADE",
  571. )
  572. # Services aktivieren
  573. await self._run_sudo("systemctl", "unmask", "hostapd")
  574. await self._run_sudo("systemctl", "enable", "hostapd")
  575. await self._run_sudo("systemctl", "enable", "dnsmasq")
  576. return True
  577. @staticmethod
  578. def _parse_requirements(path: str) -> list[str]:
  579. """
  580. Liest eine requirements.txt und gibt aktive Paketnamen zurueck.
  581. Ignoriert leere Zeilen, Kommentare (#) und Options-Zeilen (--, -r).
  582. """
  583. packages: list[str] = []
  584. try:
  585. with open(path) as f:
  586. for line in f:
  587. line = line.strip()
  588. # Leer, Kommentar, Option
  589. if not line or line.startswith("#") or line.startswith("-"):
  590. continue
  591. # Inline-Kommentar entfernen: "numpy # Array-Verarbeitung"
  592. if " #" in line:
  593. line = line.split(" #")[0].strip()
  594. if line:
  595. packages.append(line)
  596. except OSError:
  597. pass
  598. return packages
  599. async def _pip_install_packages(
  600. self, pip: str, packages: list[str], label: str = "",
  601. ) -> tuple[int, int]:
  602. """
  603. Installiert Pakete einzeln via pip.
  604. Jedes Paket wird separat installiert — so bleibt /tmp sauber
  605. und der Fortschritt ist sichtbar.
  606. Args:
  607. pip: Pfad zu pip im venv
  608. packages: Liste der zu installierenden Pakete
  609. label: Kontext-Label fuer Log (z.B. "Kern" oder Plugin-Name)
  610. Returns:
  611. (erfolgreich, fehlgeschlagen)
  612. """
  613. success = 0
  614. failed = 0
  615. total = len(packages)
  616. for i, pkg in enumerate(packages, 1):
  617. if self._cancelled:
  618. return success, failed
  619. prefix = f" [{i}/{total}]" if total > 1 else " "
  620. self._log(f"{prefix} {pkg}...")
  621. code, _ = await self._run_cmd(pip, "install", pkg)
  622. if code == 0:
  623. success += 1
  624. else:
  625. failed += 1
  626. self._log(f" WARNUNG: {pkg} fehlgeschlagen")
  627. return success, failed
  628. async def step_venv(self) -> bool:
  629. """Erstellt Python venv und installiert Requirements einzeln."""
  630. venv = self._config.venv_path
  631. source = self._config.source_path
  632. # venv erstellen
  633. self._log(" Erstelle Python venv...")
  634. code, _ = await self._run_cmd("python3", "-m", "venv", venv)
  635. if code != 0:
  636. return False
  637. # pip aktualisieren
  638. pip = f"{venv}/bin/pip"
  639. self._log(" Aktualisiere pip...")
  640. code, _ = await self._run_cmd(pip, "install", "--upgrade", "pip", "setuptools", "wheel")
  641. if code != 0:
  642. return False
  643. # Kern-Requirements einzeln installieren
  644. req_file = f"{source}/requirements.txt"
  645. packages = self._parse_requirements(req_file)
  646. if not packages:
  647. self._log(" Keine Requirements gefunden")
  648. return True
  649. self._log(f" Installiere {len(packages)} Kern-Pakete...\n")
  650. ok, fail = await self._pip_install_packages(pip, packages, "Kern")
  651. self._log(f"\n Ergebnis: {ok} installiert, {fail} fehlgeschlagen")
  652. if fail > 0:
  653. self._log(" WARNUNG: Einige Pakete konnten nicht installiert werden")
  654. # Nicht abbrechen — manche Pakete sind optional (z.B. kenlm)
  655. return True
  656. # Zusaetzliche pip-Pakete pro Plugin die nicht in requirements.txt stehen
  657. # (weil sie auskommentiert sind oder backend-abhaengig)
  658. _PLUGIN_EXTRA_DEPS: dict[str, list[str]] = {
  659. "stt_vosk": ["vosk"],
  660. "stt_whisper": ["openai-whisper"],
  661. "tts_coqui": ["TTS"],
  662. "tts_piper": ["piper-tts"],
  663. "tts_google": ["google-cloud-texttospeech"],
  664. "nlp_classifier": ["sentence-transformers", "onnxruntime", "transformers"],
  665. }
  666. # apt/system-Pakete die vor pip install noetig sind (fuer Kompilierung)
  667. _PLUGIN_SYSTEM_DEPS: dict[str, list[str]] = {
  668. "nlp_llm": ["cmake"], # llama-cpp-python braucht cmake zum Bauen
  669. }
  670. async def step_plugin_deps(self) -> bool:
  671. """Installiert Plugin-Abhaengigkeiten einzeln inkl. Backend-spezifischer Pakete."""
  672. pip = f"{self._config.venv_path}/bin/pip"
  673. source = self._config.source_path
  674. cfg = self._config
  675. total_ok = 0
  676. total_fail = 0
  677. for plugin in cfg.selected_plugins:
  678. if self._cancelled:
  679. return False
  680. # 1. requirements.txt parsen und einzeln installieren
  681. req_file = f"{source}/plugins/{plugin}/requirements.txt"
  682. packages = self._parse_requirements(req_file)
  683. # 2. Zusaetzliche Pakete hinzufuegen
  684. extras = self._PLUGIN_EXTRA_DEPS.get(plugin, [])
  685. packages.extend(extras)
  686. if not packages:
  687. continue
  688. self._log(f"\n Plugin: {plugin} ({len(packages)} Pakete)")
  689. ok, fail = await self._pip_install_packages(pip, packages, plugin)
  690. total_ok += ok
  691. total_fail += fail
  692. # 3. NLP Backend — spezielle Behandlung
  693. if "nlp_llm" in cfg.selected_plugins:
  694. await self._install_nlp_backend()
  695. if total_ok > 0 or total_fail > 0:
  696. self._log(f"\n Plugin-Pakete: {total_ok} installiert, {total_fail} fehlgeschlagen")
  697. return True
  698. async def _install_nlp_backend(self) -> None:
  699. """Installiert das gewaehlte NLP-Backend."""
  700. pip = f"{self._config.venv_path}/bin/pip"
  701. source = self._config.source_path
  702. backend = self._config.nlp_backend
  703. self._log(f" NLP Backend: {backend}")
  704. if backend == "llama_cpp":
  705. # cmake als System-Dep (fuer C++ Kompilierung)
  706. pm_name, _, install_cmd, _ = self._detect_pkg_manager()
  707. if pm_name:
  708. cmake_pkg = self._resolve_pkg("cmake", pm_name) if "cmake" in self._PKG_MAP else "cmake"
  709. self._log(f" Installiere cmake (Build-Abhaengigkeit)...")
  710. await self._run_sudo(*install_cmd, cmake_pkg, check=False)
  711. # llama-cpp-python installieren (kann auf ARM lange dauern)
  712. self._log(f" Installiere llama-cpp-python (kann 10-30 Min dauern auf ARM)...")
  713. code, _ = await self._run_cmd(
  714. pip, "install", "llama-cpp-python",
  715. )
  716. if code != 0:
  717. self._log(f" FEHLER: llama-cpp-python Installation fehlgeschlagen")
  718. self._log(f" Alternativ: Backend auf 'ollama' umstellen")
  719. else:
  720. self._log(f" -> llama-cpp-python installiert")
  721. elif backend in ("ollama", "ollama_remote"):
  722. # aiohttp fuer Ollama REST-API
  723. self._log(f" Installiere aiohttp (Ollama Client)...")
  724. code, _ = await self._run_cmd(pip, "install", "aiohttp")
  725. if code != 0:
  726. self._log(f" WARNUNG: aiohttp fehlgeschlagen")
  727. if backend == "ollama":
  728. # Lokales Ollama — pruefen ob installiert
  729. if not shutil.which("ollama"):
  730. self._log(f" WARNUNG: Ollama nicht gefunden!")
  731. self._log(f" Installieren mit: curl -fsSL https://ollama.com/install.sh | sh")
  732. self._log(f" Danach: ollama pull qwen2.5:1.5b")
  733. else:
  734. self._log(f" -> Ollama gefunden: {shutil.which('ollama')}")
  735. else:
  736. # Externer Ollama-Server
  737. host = self._config.ollama_host
  738. self._log(f" Externer Ollama-Server: {host}")
  739. self._log(f" Stelle sicher dass der Server erreichbar ist und")
  740. self._log(f" das Modell geladen wurde (ollama pull qwen2.5:1.5b)")
  741. # 4. Config anpassen
  742. # ollama_remote wird intern als "ollama" gespeichert (selbes Backend, anderer Host)
  743. config_backend = "ollama" if backend == "ollama_remote" else backend
  744. config_file = f"{source}/plugins/nlp_llm/config.json"
  745. if os.path.isfile(config_file):
  746. try:
  747. import json
  748. with open(config_file) as f:
  749. nlp_cfg = json.load(f)
  750. nlp_cfg["backend"] = config_backend
  751. nlp_cfg["ollama_host"] = self._config.ollama_host
  752. if config_backend == "ollama":
  753. nlp_cfg["model_name"] = nlp_cfg.get("model_name", "qwen2.5:1.5b")
  754. with open(config_file, "w") as f:
  755. json.dump(nlp_cfg, f, indent=4, ensure_ascii=False)
  756. self._log(f" -> config.json: backend={config_backend}, host={self._config.ollama_host}")
  757. except Exception as e:
  758. self._log(f" WARNUNG: Config-Update fehlgeschlagen: {e}")
  759. async def step_directories(self) -> bool:
  760. """Erstellt Verzeichnisse und setzt Berechtigungen."""
  761. source = self._config.source_path
  762. mode = self._config.mode
  763. # Basis-Verzeichnisse (alle Modi)
  764. dirs = [
  765. "data",
  766. "logs",
  767. "cache",
  768. "certs",
  769. ]
  770. # Modell-Verzeichnisse — exakte Struktur, verhindert Tippfehler
  771. model_dirs = [
  772. "models",
  773. "models/wakeword",
  774. "models/wakeword/trixy",
  775. "models/wakeword/system_command",
  776. "models/wakeword/alexa",
  777. "models/wakeword/hey_jarvis",
  778. "models/wakeword/hey_mycroft",
  779. "models/piper",
  780. "models/nlp",
  781. "models/symspell",
  782. ]
  783. # Server/Standalone-spezifisch
  784. if mode in ("server", "standalone"):
  785. dirs.extend([
  786. "satellites",
  787. "sync_data",
  788. "assets",
  789. "assets/default",
  790. ])
  791. # Plugin-Modell-Verzeichnisse
  792. for plugin in self._config.selected_plugins:
  793. dirs.append(f"plugins/{plugin}/models")
  794. # Client-spezifisch
  795. if mode == "client":
  796. dirs.extend([
  797. "assets",
  798. ])
  799. # Trainer-Verzeichnisse (Server/Standalone)
  800. if mode in ("server", "standalone"):
  801. dirs.extend([
  802. "trainer/data/raw",
  803. "trainer/data/processed",
  804. "trainer/cache",
  805. "trainer/assets",
  806. ])
  807. all_dirs = dirs + model_dirs
  808. self._log(f" Erstelle {len(all_dirs)} Verzeichnisse...")
  809. for d in all_dirs:
  810. path = f"{source}/{d}"
  811. await self._run_sudo("mkdir", "-p", path)
  812. # Shell-Scripte ausfuehrbar machen
  813. scripts = [
  814. "run_linux.sh",
  815. "install_linux.sh",
  816. "install_requirements.sh",
  817. "bash/update_linux.sh",
  818. "bash/prepare_linux.sh",
  819. ]
  820. made_exec = 0
  821. for script in scripts:
  822. path = f"{source}/{script}"
  823. if os.path.isfile(path):
  824. await self._run_cmd("chmod", "+x", path)
  825. made_exec += 1
  826. # User zur 'input'-Gruppe hinzufuegen (fuer HID Media Keys / /dev/input/event*)
  827. if mode in ("client", "standalone"):
  828. code, _ = await self._run_sudo(
  829. "usermod", "-aG", "input", self._config.username, check=False,
  830. )
  831. if code == 0:
  832. self._log(f" -> User '{self._config.username}' zur Gruppe 'input' hinzugefuegt (HID)")
  833. # Besitzer setzen
  834. await self._run_sudo(
  835. "chown", "-R",
  836. f"{self._config.username}:{self._config.username}",
  837. self._config.install_path,
  838. )
  839. self._log(f" -> {len(all_dirs)} Verzeichnisse erstellt, {made_exec} Scripte ausfuehrbar")
  840. return True
  841. async def step_systemd(self) -> bool:
  842. """Erstellt den systemd-Service und aktiviert ihn bei Bedarf."""
  843. cfg = self._config
  844. if not cfg.install_service:
  845. self._log(" Service-Installation deaktiviert — uebersprungen")
  846. return True
  847. service_name = f"trixy-{cfg.mode}"
  848. # ExecStart zusammenbauen
  849. # run_linux.sh fuehrt Update + Bereinigung + Start durch
  850. run_script = f"{cfg.source_path}/run_linux.sh"
  851. exec_args = ["/bin/bash", run_script]
  852. if cfg.mode == "client":
  853. exec_args.extend([
  854. "client",
  855. "--host", cfg.server_host,
  856. "--port", str(cfg.server_port),
  857. "--room", cfg.room,
  858. "--alias", cfg.alias,
  859. ])
  860. else:
  861. exec_args.append(cfg.mode)
  862. if cfg.auto_regist and cfg.mode in ("server", "standalone"):
  863. exec_args.append("--auto-regist")
  864. exec_args.append("--debug")
  865. exec_start = " ".join(exec_args)
  866. # After-Deps fuer Server mit WiFi-AP
  867. after_deps = "network-online.target"
  868. if cfg.mode == "server" and cfg.wifi_enabled:
  869. after_deps = "network-online.target hostapd.service dnsmasq.service"
  870. service_content = f"""[Unit]
  871. Description=Trixy Voice Assistant ({cfg.mode.title()})
  872. After={after_deps}
  873. Wants=network-online.target
  874. [Service]
  875. Type=simple
  876. User={cfg.username}
  877. Group={cfg.username}
  878. WorkingDirectory={cfg.source_path}
  879. ExecStart={exec_start}
  880. Restart=on-failure
  881. RestartSec=5
  882. StartLimitIntervalSec=60
  883. StartLimitBurst=5
  884. Environment=PYTHONUNBUFFERED=1
  885. Environment=HOME=/home/{cfg.username}
  886. StandardOutput=journal
  887. StandardError=journal
  888. SyslogIdentifier=trixy
  889. [Install]
  890. WantedBy=multi-user.target
  891. """
  892. # Service-Datei schreiben
  893. proc = await asyncio.create_subprocess_exec(
  894. "sudo", "tee", f"/etc/systemd/system/{service_name}.service",
  895. stdin=asyncio.subprocess.PIPE,
  896. stdout=asyncio.subprocess.DEVNULL,
  897. )
  898. await proc.communicate(service_content.encode())
  899. await self._run_sudo("systemctl", "daemon-reload")
  900. # Autostart je nach Einstellung
  901. if cfg.autostart:
  902. await self._run_sudo("systemctl", "enable", f"{service_name}.service")
  903. self._log(f" -> {service_name}.service aktiviert (Autostart)")
  904. else:
  905. await self._run_sudo("systemctl", "disable", f"{service_name}.service")
  906. self._log(f" -> {service_name}.service erstellt (kein Autostart)")
  907. self._log(f" Manuell starten: sudo systemctl start {service_name}")
  908. return True
  909. def _get_model_downloads(self) -> list[tuple[str, str, str, bool, str | None]]:
  910. """
  911. Gibt die Download-Liste basierend auf Hardware-Empfehlung zurueck.
  912. Returns:
  913. Liste von (name, url, ziel_relativ_zu_source, entpacken?, plugin_name).
  914. plugin_name ist None fuer Core-Modelle.
  915. """
  916. from .system_info import detect_system, get_model_recommendations
  917. info = detect_system()
  918. recs = get_model_recommendations(info, self._config.selected_plugins)
  919. downloads: list[tuple[str, str, str, bool, str | None]] = []
  920. # Empfohlene Modelle ermitteln
  921. rec_names = {r.name for r in recs if r.recommended}
  922. self._log(f" Hardware: {info.ram_total_mb}MB RAM, {info.disk_free_mb}MB frei")
  923. if info.gpu.cuda_available:
  924. self._log(f" GPU: {info.gpu.name} ({info.gpu.vram_mb}MB VRAM)")
  925. else:
  926. self._log(" GPU: Keine CUDA-GPU erkannt")
  927. self._log(f" {len(rec_names)} empfohlene Modelle erkannt")
  928. self._log("")
  929. # --- STT Vosk ---
  930. if "stt_vosk" in self._config.selected_plugins:
  931. if "Vosk STT (Deutsch, gross)" in rec_names:
  932. downloads.append((
  933. "Vosk STT (Deutsch, gross)",
  934. "https://alphacephei.com/vosk/models/vosk-model-de-0.21.zip",
  935. "plugins/stt_vosk/models",
  936. True, "stt_vosk",
  937. ))
  938. elif "Vosk STT (Deutsch, klein)" in rec_names:
  939. downloads.append((
  940. "Vosk STT (Deutsch, klein)",
  941. "https://alphacephei.com/vosk/models/vosk-model-small-de-0.15.zip",
  942. "plugins/stt_vosk/models",
  943. True, "stt_vosk",
  944. ))
  945. # --- STT Whisper ---
  946. if "stt_whisper" in self._config.selected_plugins:
  947. # Bestes empfohlenes Whisper-Modell waehlen
  948. whisper_priority = ["medium", "small", "base", "tiny"]
  949. for model_name in whisper_priority:
  950. full_name = f"Whisper STT ({model_name})"
  951. if full_name in rec_names:
  952. self._log(f" Whisper: {model_name} empfohlen (wird beim Start geladen)")
  953. break
  954. # --- TTS Piper ---
  955. if "tts_piper" in self._config.selected_plugins:
  956. if "Piper TTS (thorsten-medium)" in rec_names:
  957. downloads.append((
  958. "Piper TTS (thorsten-medium, onnx)",
  959. "https://huggingface.co/rhasspy/piper-voices/resolve/main/"
  960. "de/de_DE/thorsten/medium/de_DE-thorsten-medium.onnx",
  961. "models/piper/de_DE-thorsten-medium.onnx",
  962. False, None,
  963. ))
  964. downloads.append((
  965. "Piper TTS (thorsten-medium, config)",
  966. "https://huggingface.co/rhasspy/piper-voices/resolve/main/"
  967. "de/de_DE/thorsten/medium/de_DE-thorsten-medium.onnx.json",
  968. "models/piper/de_DE-thorsten-medium.onnx.json",
  969. False, None,
  970. ))
  971. # --- NLP LLM ---
  972. if "nlp_llm" in self._config.selected_plugins:
  973. if "Qwen 2.5 1.5B (Q4_K_M)" in rec_names:
  974. downloads.append((
  975. "Qwen 2.5 1.5B (Q4_K_M)",
  976. "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/"
  977. "qwen2.5-1.5b-instruct-q4_k_m.gguf",
  978. "models/nlp/qwen2.5-1.5b-instruct-q4_k_m.gguf",
  979. False, None,
  980. ))
  981. return downloads
  982. async def step_download_models(self) -> bool:
  983. """Laedt ML-Modelle basierend auf Hardware-Empfehlung herunter."""
  984. if not self._config.download_models:
  985. self._log(" Modell-Download deaktiviert — uebersprungen")
  986. return True
  987. source = self._config.source_path
  988. downloads = self._get_model_downloads()
  989. if not downloads:
  990. self._log(" Keine Modelle zum Herunterladen (keine passenden Empfehlungen)")
  991. return True
  992. downloaded = 0
  993. total_size = 0
  994. for name, url, target_rel, extract, plugin in downloads:
  995. if self._cancelled:
  996. return False
  997. target = f"{source}/{target_rel}"
  998. # Pruefen ob bereits vorhanden
  999. if not extract and os.path.isfile(target):
  1000. self._log(f" {name} — bereits vorhanden")
  1001. continue
  1002. if extract and os.path.isdir(target) and os.listdir(target):
  1003. self._log(f" {name} — bereits vorhanden")
  1004. continue
  1005. self._log(f" Lade herunter: {name}...")
  1006. if extract:
  1007. # ZIP herunterladen und entpacken
  1008. zip_path = "/tmp/trixy_model_download.zip"
  1009. code, _ = await self._run_cmd(
  1010. "wget", "-q", "--show-progress", "-O", zip_path, url,
  1011. )
  1012. if code != 0:
  1013. self._log(f" WARNUNG: Download fehlgeschlagen — {name}")
  1014. continue
  1015. await self._run_sudo("mkdir", "-p", target)
  1016. code, _ = await self._run_cmd(
  1017. "unzip", "-q", "-o", zip_path, "-d", target,
  1018. )
  1019. if os.path.exists(zip_path):
  1020. os.unlink(zip_path)
  1021. if code != 0:
  1022. self._log(f" WARNUNG: Entpacken fehlgeschlagen — {name}")
  1023. continue
  1024. else:
  1025. # Direkt herunterladen
  1026. target_dir = os.path.dirname(target)
  1027. await self._run_sudo("mkdir", "-p", target_dir)
  1028. code, _ = await self._run_cmd(
  1029. "wget", "-q", "--show-progress", "-O", target, url,
  1030. )
  1031. if code != 0:
  1032. self._log(f" WARNUNG: Download fehlgeschlagen — {name}")
  1033. continue
  1034. # Groesse ermitteln
  1035. if os.path.isfile(target):
  1036. total_size += os.path.getsize(target) // (1024 * 1024)
  1037. elif os.path.isdir(target):
  1038. for dirpath, _, filenames in os.walk(target):
  1039. for f in filenames:
  1040. total_size += os.path.getsize(os.path.join(dirpath, f)) // (1024 * 1024)
  1041. downloaded += 1
  1042. self._log(f" -> {name} installiert")
  1043. self._log(f" {downloaded} Modell(e) heruntergeladen ({total_size} MB)")
  1044. return True
  1045. async def step_verify(self) -> bool:
  1046. """Verifiziert die Installation."""
  1047. checks = ["ffmpeg", "python3"]
  1048. all_ok = True
  1049. for cmd in checks:
  1050. path = shutil.which(cmd)
  1051. if path:
  1052. self._log(f" OK: {cmd} ({path})")
  1053. else:
  1054. self._log(f" FEHLT: {cmd}")
  1055. all_ok = False
  1056. # venv pruefen
  1057. venv_python = f"{self._config.venv_path}/bin/python"
  1058. if os.path.isfile(venv_python):
  1059. self._log(f" OK: venv ({venv_python})")
  1060. else:
  1061. self._log(f" FEHLT: venv ({venv_python})")
  1062. all_ok = False
  1063. # Temporaere Verzeichnisse aufraeumen (pip-Cache, TMPDIR)
  1064. for tmp_name in ("tmp", "pip-cache"):
  1065. tmp_path = f"{self._config.install_path}/{tmp_name}"
  1066. if os.path.isdir(tmp_path):
  1067. await self._run_sudo("rm", "-rf", tmp_path)
  1068. self._log(f" Aufgeraeumt: {tmp_name}")
  1069. return all_ok