From aaaf863a78e60a8cab28249111c8db2e3bdab2cd Mon Sep 17 00:00:00 2001 From: guy Date: Tue, 17 Nov 2026 01:07:16 -0300 Subject: [PATCH] OrbiSubs panel: Engines tab (Whisper, LLM, gpu02 GPU, this host) with alerts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tarea 080 y su agregado. El backend sondea gpu02 cada 15-30 s (solo GET /health, /slots, /props, /v1/models y el nvidia_gpu_exporter :9835), una vez para todas las pestañas. Los tiempos y fallas salen de los pedidos reales de cada canal: orbisubs.py y orbisubs_tr.py ahora escriben t, audio_s y error en sus .jsonl, y el panel los guarda 7 días en engine_reqs. Avisos en Eventos y punto en el menú: motor sin respuesta dos sondeos seguidos, p95 de 15 min sobre el umbral (3 s) y VRAM libre de la 3060 bajo 512 MiB. --- README.md | 22 ++ orbisubs.py | 23 +- orbisubs_tr.py | 10 +- panel/src/db.js | 40 ++- panel/src/engine/motores.js | 483 ++++++++++++++++++++++++++++++++++++ panel/src/public/app.js | 2 + panel/src/public/engines.js | 267 ++++++++++++++++++++ panel/src/public/i18n.js | 85 +++++++ panel/src/public/index.html | 56 +++++ panel/src/public/subs.css | 33 +++ panel/src/routes/engines.js | 20 ++ panel/src/server.js | 7 + panel/test/motores.test.js | 93 +++++++ 13 files changed, 1131 insertions(+), 10 deletions(-) create mode 100644 panel/src/engine/motores.js create mode 100644 panel/src/public/engines.js create mode 100644 panel/src/routes/engines.js create mode 100644 panel/test/motores.test.js diff --git a/README.md b/README.md index 1747621..80ea823 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,28 @@ cp deploy/orbisubs-panel.service /etc/systemd/system/ systemctl daemon-reload && systemctl enable --now orbisubs-panel ``` +### Pestaña Motores (tarea 080) + +Estado de lo que usa OrbiSubs en gpu02, sondeado **desde el backend** cada 15–30 s (una sola +consulta aunque haya varias pestañas abiertas). Solo hace GET, nunca `/load`: + +| Tarjeta | De dónde sale | +|---|---| +| Whisper | `GET :8004/health`; el modelo y la placa se **declaran** en Configuración (whisper.cpp no los informa) | +| LLM | `GET :8001/health`, `/slots` (ocupado, también por otros, como batman) y, cada ~10 sondeos, `/props` y `/v1/models` | +| GPU de gpu02 | `nvidia_gpu_exporter` en `:9835/metrics`: uso, VRAM, temperatura y consumo por placa, con la 3060 resaltada | +| Este equipo | cgroup del CT (CPU y RAM), `/var/www/hls`, uptime y versiones (OrbiSubs sale de `/opt/orbisubs/VERSION`) | + +Los tiempos y las fallas son los de los pedidos reales de cada canal: `orbisubs.py` y +`orbisubs_tr.py` escriben `t`, `http_s`/`qwen_s`, `audio_s` y `error` en sus `.jsonl`, y el panel +los guarda en su base (`engine_reqs`, 7 días). Avisos en Eventos y punto en el menú: + +- un motor no responde dos sondeos seguidos (rojo); +- p95 de 15 min arriba del umbral (3 s por defecto) (amarillo); +- VRAM libre de la 3060 debajo de 512 MiB (amarillo). + +Al deployar, escribir la versión: `git describe --always --dirty > /opt/orbisubs/VERSION`. + ## Archivos | Archivo | Qué es | diff --git a/orbisubs.py b/orbisubs.py index f60b97e..12c915f 100755 --- a/orbisubs.py +++ b/orbisubs.py @@ -128,11 +128,15 @@ class MotorHTTP: if prompt: data["prompt"] = prompt t = time.time() - r = self.s.post(self.url, files={"file": ("a.wav", b.getvalue(), "audio/wav")}, data=data, - timeout=self.timeout) - r.raise_for_status() - d = r.json() - self.ultimo = {"http_s": round(time.time() - t, 3)} + try: + r = self.s.post(self.url, files={"file": ("a.wav", b.getvalue(), "audio/wav")}, data=data, + timeout=self.timeout) + r.raise_for_status() + d = r.json() + finally: + # Tiempo del pedido y segundos de audio enviados, aunque falle: el panel + # (pestaña Motores, tarea 080) saca de acá el RTF y el tiempo de las fallas. + self.ultimo = {"http_s": round(time.time() - t, 3), "audio_s": round(len(audio) / SR, 2)} out = [] for seg in d.get("segments") or []: # whisper.cpp sin VAD alucina con música/silencio ("¡Gracias!", "Subtítulos por…"): @@ -327,9 +331,13 @@ def main(): continue info[seq] = (uri, dur, pdt, p0, p0 + dur) tr.agregar(p0, muestras) + err = None + if hasattr(motor, "ultimo"): + motor.ultimo = {} # sin pedido (menos de 1 s pendiente): sin http_s try: conf, dt = tr.paso() except Exception as e: + err = str(e)[:200] # Motor caído o lento: el canal sigue sin texto (el tope de 2 segmentos # publica igual) y el audio pendiente se descarta para no acumular. log("asr_error", seq=seq, err=str(e)[:200]) @@ -395,7 +403,10 @@ def main(): "held_segments": seq - publicado, "channel_extra_s": round(sum(info[k][1] for k in range(publicado + 1, seq + 1) if k in info) + (fin_wall - llegada[seq]), 2), - "text": " | ".join(c[2] for c in nuevos_cues)} + "text": " | ".join(c[2] for c in nuevos_cues), + "t": round(time.time(), 2)} + if err: + m["error"] = err log("segment", **m) if met: met.write(json.dumps(m, ensure_ascii=False) + "\n") diff --git a/orbisubs_tr.py b/orbisubs_tr.py index 71ef0ef..b1568f7 100644 --- a/orbisubs_tr.py +++ b/orbisubs_tr.py @@ -40,6 +40,7 @@ class Traductor: msgs += [{"role": "user", "content": self.prev_es}, {"role": "assistant", "content": self.prev_en}] msgs.append({"role": "user", "content": es}) t = time.time() + self.error = None try: r = self.s.post(self.url, json={"model": self.modelo, "temperature": 0, "max_tokens": 160, "chat_template_kwargs": {"enable_thinking": False}, @@ -48,7 +49,8 @@ class Traductor: en = r.json()["choices"][0]["message"]["content"].strip().strip('"').strip() except Exception as e: self.fallas += 1 - log("translate_error", err=str(e)[:200]) + self.error = str(e)[:200] + log("translate_error", err=self.error) return None, time.time() - t dt = time.time() - t self.tiempos.append(dt) @@ -145,8 +147,10 @@ def main(): nuevos = repartir(frase[0][0], frase[-1][1], en) en_cues = (en_cues + nuevos)[-300:] if met: - met.write(json.dumps({"t": round(time.time(), 2), "t0": round(frase[0][0], 2), "es": es, "en": en, - "qwen_s": round(dt, 3)}, ensure_ascii=False) + "\n") + m = {"t": round(time.time(), 2), "t0": round(frase[0][0], 2), "es": es, "en": en, "qwen_s": round(dt, 3)} + if tr.error: + m["error"] = tr.error # para la pestaña Motores del panel (080) + met.write(json.dumps(m, ensure_ascii=False) + "\n") met.flush() # El inglés está listo hasta el comienzo de lo que falta traducir. diff --git a/panel/src/db.js b/panel/src/db.js index aa62164..1cb43a4 100644 --- a/panel/src/db.js +++ b/panel/src/db.js @@ -46,6 +46,37 @@ CREATE TABLE IF NOT EXISTS events ( message TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_events_ts ON events(ts); +-- Pestaña Motores (tarea 080): configuración, pedidos a los motores sacados de las +-- métricas de cada canal y sondeos de /health y /slots. 7 días como máximo. +CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL -- JSON +); +CREATE TABLE IF NOT EXISTS engine_reqs ( + ts REAL NOT NULL, -- epoch s (hora en que terminó el pedido) + kind TEXT NOT NULL, -- asr | llm + url TEXT NOT NULL, + channel TEXT NOT NULL, + dur_s REAL, -- tiempo del pedido HTTP + audio_s REAL, -- segundos de audio enviados (solo asr) + ok INTEGER NOT NULL, + error TEXT +); +CREATE INDEX IF NOT EXISTS idx_engine_reqs ON engine_reqs(kind, url, ts); +CREATE TABLE IF NOT EXISTS engine_polls ( + ts REAL NOT NULL, + kind TEXT NOT NULL, + url TEXT NOT NULL, + up INTEGER NOT NULL, + busy INTEGER -- llm: algún slot procesando (de cualquiera) +); +CREATE INDEX IF NOT EXISTS idx_engine_polls ON engine_polls(kind, url, ts); +CREATE TABLE IF NOT EXISTS gpu_samples ( -- exporter de gpu02 (080-agregado) + ts REAL NOT NULL, + idx INTEGER NOT NULL, -- índice de nvidia-smi (0 = 3080, 1 = 3060) + util REAL, mem_used REAL, mem_total REAL, temp REAL, power REAL +); +CREATE INDEX IF NOT EXISTS idx_gpu_samples ON gpu_samples(ts); `); function event(level, message, { channel = null, username = null } = {}) { @@ -54,4 +85,11 @@ function event(level, message, { channel = null, username = null } = {}) { db.prepare('DELETE FROM events WHERE id <= (SELECT MAX(id) - 2000 FROM events)').run(); } -module.exports = { db, DATA_DIR, event }; +const getSetting = (key, def) => { + const r = db.prepare('SELECT value FROM settings WHERE key = ?').get(key); + if (!r) return def; + try { return JSON.parse(r.value); } catch { return def; } +}; +const setSetting = (key, value) => db.prepare('INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, JSON.stringify(value)); + +module.exports = { db, DATA_DIR, event, getSetting, setSetting }; diff --git a/panel/src/engine/motores.js b/panel/src/engine/motores.js new file mode 100644 index 0000000..3403c6c --- /dev/null +++ b/panel/src/engine/motores.js @@ -0,0 +1,483 @@ +'use strict'; +// motores.js — estado de los motores de gpu02 (whisper.cpp y el LLM) para la pestaña +// Motores (tarea 080: "no veo nada de info de estado del llm, q usamos (whisper)"). +// +// Dos fuentes: +// - Lo que medimos nosotros: cada pedido que hacen orbisubs.py y orbisubs_tr.py queda +// en /var/log/orbisubs/.jsonl y -en.jsonl. Se leen solo las líneas +// nuevas y se guardan en engine_reqs (7 días como máximo). +// - Un sondeo desde este backend cada 15–30 s: GET /health (los dos), /slots y, de vez +// en cuando, /props y /v1/models (el LLM). Es una sola consulta aunque haya varias +// pestañas abiertas: los browsers leen lo guardado acá, nunca le pegan a gpu02. +// gpu02 es compartido: solo esos GET, nunca /load ni nada que le cambie el estado. +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { execFile } = require('child_process'); +const { db, event, getSetting, setSetting } = require('../db'); +const { LOG_DIR, HLS_DIR } = require('./status'); + +const KEEP_S = 7 * 86400; +const DEFAULTS = { + poll_s: 20, + // whisper.cpp no informa el modelo ni la versión: esto lo declara quien lo instaló. + asr: { model: 'large-v3-turbo', hw: 'RTX 3060 en gpu02', p95_warn_s: 3 }, + llm: { p95_warn_s: 3 }, + // GPU de gpu02 (080-agregado): nvidia_gpu_exporter que instaló Jorge. Qué corre en cada + // placa es un dato declarado (el exporter no lo sabe). + gpu: { + url: 'http://192.168.2.10:9835/metrics', + main_index: 1, // la 3060: Whisper y Qwen-VL + vram_warn_mib: 512, + roles: { + 0: 'Qwen3.5-9B (texto, :8001) · Real-ESRGAN de ESPER (:8010)', + 1: 'Qwen3-VL-8B (:8002) · Whisper large-v3-turbo (:8004)', + }, + }, +}; +const DEFAULT_URL = { asr: 'http://192.168.2.10:8004', llm: 'http://192.168.2.10:8001' }; +const NAME = { asr: 'Whisper', llm: 'LLM' }; +const SLOW_WINDOW_S = 900; // el p95 del aviso se mira en los últimos 15 min +const SLOW_MIN_N = 8; // con menos pedidos que esto no se avisa (un pico no es tendencia) + +function config() { + const c = getSetting('engines', {}); + return { + poll_s: c.poll_s ?? DEFAULTS.poll_s, + asr: { ...DEFAULTS.asr, ...(c.asr || {}) }, + llm: { ...DEFAULTS.llm, ...(c.llm || {}) }, + gpu: { ...DEFAULTS.gpu, ...(c.gpu || {}), roles: { ...DEFAULTS.gpu.roles, ...((c.gpu || {}).roles || {}) } }, + }; +} + +function setConfig(b) { + const c = config(); + const num = (v, lo, hi, what) => { + const n = Number(v); + if (!Number.isFinite(n) || n < lo || n > hi) { const e = new Error(`${what}: entre ${lo} y ${hi}`); e.status = 400; throw e; } + return n; + }; + const str = (v, max) => String(v ?? '').trim().slice(0, max); + if (b.poll_s != null) c.poll_s = Math.round(num(b.poll_s, 15, 30, 'Sondeo (s)')); + if (b.asr) { + if (b.asr.model != null) c.asr.model = str(b.asr.model, 80); + if (b.asr.hw != null) c.asr.hw = str(b.asr.hw, 80); + if (b.asr.p95_warn_s != null) c.asr.p95_warn_s = num(b.asr.p95_warn_s, 0.5, 60, 'Umbral de p95 de Whisper (s)'); + } + if (b.llm && b.llm.p95_warn_s != null) c.llm.p95_warn_s = num(b.llm.p95_warn_s, 0.5, 60, 'Umbral de p95 del LLM (s)'); + if (b.gpu && b.gpu.vram_warn_mib != null) c.gpu.vram_warn_mib = Math.round(num(b.gpu.vram_warn_mib, 64, 16384, 'Aviso de VRAM libre (MiB)')); + setSetting('engines', c); + return c; +} + +const normUrl = u => String(u || '').trim().replace(/\/+$/, ''); + +// Los motores son las URL que usan los canales: si un canal apunta a otra URL (la +// prueba de caída de la 080 la pone en :8999), aparece su tarjeta. +function engineList(channels) { + const out = []; + for (const kind of ['asr', 'llm']) { + const urls = new Map(); + for (const ch of channels) { + if (kind === 'llm' && !(ch.cfg.tr && ch.cfg.tr.langs && ch.cfg.tr.langs.length)) continue; + const u = normUrl(kind === 'asr' ? ch.cfg.asr.url : ch.cfg.tr.url); + if (!u) continue; + if (!urls.has(u)) urls.set(u, []); + urls.get(u).push(ch.slug); + } + if (!urls.size) urls.set(DEFAULT_URL[kind], []); + for (const [url, chans] of urls) out.push({ key: `${kind}|${url}`, kind, url, channels: chans }); + } + return out; +} + +/* ---------- números ---------- */ +function quantile(arr, q) { + if (!arr.length) return null; + const s = [...arr].sort((a, b) => a - b); + const pos = (s.length - 1) * q, lo = Math.floor(pos), hi = Math.ceil(pos); + return s[lo] + (s[hi] - s[lo]) * (pos - lo); +} +const r3 = v => (v == null ? null : Math.round(v * 1000) / 1000); + +function statsOf(rows) { + const ok = rows.filter(r => r.ok && r.dur_s != null); + const d = ok.map(r => r.dur_s); + const rtf = ok.filter(r => r.audio_s > 0).map(r => r.dur_s / r.audio_s); + return { + n: rows.length, + fails: rows.length - ok.length, + median_s: r3(quantile(d, 0.5)), + p95_s: r3(quantile(d, 0.95)), + rtf: r3(quantile(rtf, 0.5)), + }; +} + +// Sparkline: mediana y máximo por minuto de la última hora (60 puntos como mucho). +function buckets(rows, now, span = 3600, step = 60) { + const n = Math.ceil(span / step), out = []; + const by = Array.from({ length: n }, () => ({ d: [], fails: 0 })); + for (const r of rows) { + const i = Math.floor((r.ts - (now - span)) / step); + if (i < 0 || i >= n) continue; + if (r.ok && r.dur_s != null) by[i].d.push(r.dur_s); else by[i].fails++; + } + by.forEach((b, i) => out.push({ t: Math.round(now - span + i * step), med: r3(quantile(b.d, 0.5)), max: r3(b.d.length ? Math.max(...b.d) : null), n: b.d.length, fails: b.fails })); + return out; +} + +/* ---------- lectura de las métricas de los canales ---------- */ +// Una línea del .jsonl del ASR o del traductor → un pedido, o null si no hubo pedido. +function parseLine(kind, r) { + if (!r || typeof r.t !== 'number') return null; // líneas de antes de la 080: sin hora + if (kind === 'asr') { + if (typeof r.http_s !== 'number') return null; // ese segmento no pidió nada (menos de 1 s pendiente) + return { ts: r.t, dur_s: r.http_s, audio_s: r.audio_s ?? null, ok: r.error ? 0 : 1, error: r.error || null }; + } + if (!('es' in r) || typeof r.qwen_s !== 'number') return null; + const fail = !!r.error || r.en == null; + return { ts: r.t, dur_s: r.qwen_s, audio_s: null, ok: fail ? 0 : 1, error: fail ? (r.error || 'sin traducción') : null }; +} + +const insReq = db.prepare('INSERT INTO engine_reqs (ts, kind, url, channel, dur_s, audio_s, ok, error) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'); + +// Lee lo nuevo de un archivo desde el último offset guardado (sobrevive un reinicio). +function ingestFile(file, kind, url, channel) { + const key = `off:${file}`; + let st; + try { st = fs.statSync(file); } catch { return 0; } + let { ino, off } = getSetting(key, { ino: null, off: 0 }); + if (ino !== st.ino || st.size < off) off = 0; // rotado o truncado + if (st.size === off) return 0; + const len = Math.min(st.size - off, 8 << 20); + const buf = Buffer.alloc(len); + const fd = fs.openSync(file, 'r'); + try { fs.readSync(fd, buf, 0, len, off); } finally { fs.closeSync(fd); } + const lastNl = buf.lastIndexOf(10); + if (lastNl < 0) return 0; // línea a medias: se lee la próxima vez + const cutoff = Date.now() / 1000 - KEEP_S; + let n = 0; + const tx = db.transaction(lines => { + for (const l of lines) { + if (!l.trim()) continue; + let r; try { r = JSON.parse(l); } catch { continue; } + const q = parseLine(kind, r); + if (!q || q.ts < cutoff) continue; + insReq.run(q.ts, kind, url, channel, q.dur_s, q.audio_s, q.ok, q.error); n++; + } + }); + tx(buf.subarray(0, lastNl).toString('utf8').split('\n')); + setSetting(key, { ino: st.ino, off: off + lastNl + 1 }); + return n; +} + +function ingest(channels) { + for (const ch of channels) { + ingestFile(path.join(LOG_DIR, `${ch.slug}.jsonl`), 'asr', normUrl(ch.cfg.asr.url), ch.slug); + ingestFile(path.join(LOG_DIR, `${ch.slug}-en.jsonl`), 'llm', normUrl(ch.cfg.tr.url), ch.slug); + } +} + +/* ---------- sondeo ---------- */ +async function get(url, timeoutMs = 4000) { + const r = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), headers: { 'User-Agent': 'OrbiSubs-panel' } }); + if (!r.ok) throw new Error(`HTTP ${r.status}`); + return r.json(); +} +const errText = e => (e && e.cause && e.cause.code) || (e && e.name === 'TimeoutError' ? 'sin respuesta en 4 s' : (e && e.message) || String(e)); + +const state = new Map(); // key → estado del motor (también en settings, para sobrevivir un reinicio) +let pollN = 0, polledAt = null; +const insPoll = db.prepare('INSERT INTO engine_polls (ts, kind, url, up, busy) VALUES (?, ?, ?, ?, ?)'); + +function stOf(key) { + if (!state.has(key)) state.set(key, getSetting(`st:${key}`, { fails: 0, last_ok: null, down_since: null, last_err: null, alerted_down: false, slow: false, info: null })); + return state.get(key); +} +const fmtDur = s => (s < 90 ? `${Math.round(s)} s` : s < 5400 ? `${Math.round(s / 60)} min` : `${(s / 3600).toFixed(1)} h`); + +async function probe(e) { + const s = stOf(e.key); + const now = Date.now(); + let busy = null; + try { + const h = await get(`${e.url}/health`); + if (h && h.status && h.status !== 'ok') throw new Error(`health: ${h.status}`); + if (e.kind === 'llm') { + const slots = await get(`${e.url}/slots`); + if (Array.isArray(slots)) { + busy = slots.some(x => x.is_processing) ? 1 : 0; + s.slots = { total: slots.length, busy: slots.filter(x => x.is_processing).length }; + } + // /props y /v1/models casi no cambian: cada ~10 sondeos o si falta el dato. + if (!s.info || pollN % 10 === 0) { + const p = await get(`${e.url}/props`).catch(() => null); + const m = await get(`${e.url}/v1/models`).catch(() => null); + if (p || m) { + s.info = { + model_path: p && p.model_path || null, + model_ftype: p && p.model_ftype || null, + n_ctx: p && ((p.default_generation_settings && p.default_generation_settings.n_ctx) ?? p.n_ctx) || null, + total_slots: p && p.total_slots || null, + build: p && p.build_info || null, + published: (m && m.data && m.data[0] && m.data[0].id) || (p && p.model_alias) || null, + read_at: now, + }; + } + } + } + if (s.alerted_down) { + event('info', `${NAME[e.kind]} volvió a responder (${e.url}) después de ${fmtDur((now - s.down_since) / 1000)} caído`); + } + Object.assign(s, { fails: 0, last_ok: now, down_since: null, alerted_down: false, last_err: null }); + insPoll.run(now / 1000, e.kind, e.url, 1, busy); + } catch (err) { + s.fails++; + s.last_err = errText(err); + if (!s.down_since) s.down_since = now; + if (s.fails >= 2 && !s.alerted_down) { + s.alerted_down = true; + event('error', `${NAME[e.kind]} no responde (${e.url}): ${s.last_err}. Dos sondeos seguidos sin respuesta`); + } + insPoll.run(now / 1000, e.kind, e.url, 0, null); + } + s.last_check = now; +} + +// Aviso de lentitud: p95 de los últimos 15 min contra el umbral de la configuración. +function checkSlow(e, cfg) { + const s = stOf(e.key); + const since = Date.now() / 1000 - SLOW_WINDOW_S; + const rows = db.prepare('SELECT dur_s FROM engine_reqs WHERE kind = ? AND url = ? AND ts >= ? AND ok = 1').all(e.kind, e.url, since).map(r => r.dur_s); + const p95 = rows.length >= SLOW_MIN_N ? quantile(rows, 0.95) : null; + const thr = cfg[e.kind].p95_warn_s; + s.p95_15m = r3(p95); + if (p95 != null && p95 > thr && !s.slow) { + s.slow = true; + event('warn', `${NAME[e.kind]} lento (${e.url}): p95 de ${p95.toFixed(2)} s en 15 min, umbral ${thr} s`); + } else if (s.slow && (p95 == null || p95 <= thr * 0.9)) { + s.slow = false; + event('info', `${NAME[e.kind]} (${e.url}) volvió a tiempos normales${p95 != null ? `: p95 de ${p95.toFixed(2)} s` : ''}`); + } +} + +/* ---------- GPU de gpu02 (exporter Prometheus, 080-agregado) ---------- */ +// Texto Prometheus → { uuid: { métrica: valor, ...labels de gpu_info } }. +function parseProm(text) { + const by = {}; + for (const line of String(text).split('\n')) { + const m = /^nvidia_smi_(\w+)\{([^}]*)\}\s+(\S+)/.exec(line); + if (!m) continue; + const labels = {}; + for (const l of m[2].matchAll(/(\w+)="([^"]*)"/g)) labels[l[1]] = l[2]; + if (!labels.uuid) continue; + const g = by[labels.uuid] || (by[labels.uuid] = {}); + if (m[1] === 'gpu_info') Object.assign(g, { name: labels.name, driver: labels.driver_version, cuda: labels.cuda_version, index: Number(labels.index) }); + // nvidia_smi_name e index también vienen como métrica numérica ("3060"): mandan los labels de gpu_info. + else if (m[1] === 'name') continue; + else if (m[1] === 'index') { if (g.index == null) g.index = Number(m[3]); } + else g[m[1]] = Number(m[3]); + } + return Object.values(by).filter(g => Number.isFinite(g.index)).map(g => ({ + index: g.index, name: g.name || null, driver: g.driver || null, cuda: g.cuda || null, + util: g.utilization_gpu_ratio ?? null, mem_used: g.memory_used_bytes ?? null, mem_total: g.memory_total_bytes ?? null, + mem_free: g.memory_free_bytes ?? null, temp: g.temperature_gpu ?? null, power: g.power_draw_watts ?? null, + })).sort((a, b) => a.index - b.index); +} + +const gpu = { fails: 0, last_ok: null, down_since: null, err: null, gpus: [], alerted_down: false, vram_low: false }; +const insGpu = db.prepare('INSERT INTO gpu_samples (ts, idx, util, mem_used, mem_total, temp, power) VALUES (?, ?, ?, ?, ?, ?, ?)'); +async function probeGpu(cfg) { + const now = Date.now(); + try { + const r = await fetch(cfg.gpu.url, { signal: AbortSignal.timeout(4000), headers: { 'User-Agent': 'OrbiSubs-panel' } }); + if (!r.ok) throw new Error(`HTTP ${r.status}`); + const gs = parseProm(await r.text()); + if (!gs.length) throw new Error('el exporter no trae placas'); + db.transaction(() => { for (const g of gs) insGpu.run(now / 1000, g.index, g.util, g.mem_used, g.mem_total, g.temp, g.power); })(); + if (gpu.alerted_down) event('info', `Exporter de GPU de gpu02 volvió a responder (${cfg.gpu.url})`); + Object.assign(gpu, { fails: 0, last_ok: now, down_since: null, err: null, gpus: gs, alerted_down: false }); + // Aviso: VRAM libre de la placa principal (la 3060) por debajo del umbral. + const main = gs.find(g => g.index === cfg.gpu.main_index); + if (main && main.mem_free != null) { + const freeMiB = main.mem_free / 1048576, thr = cfg.gpu.vram_warn_mib; + if (freeMiB < thr && !gpu.vram_low) { + gpu.vram_low = true; + event('warn', `VRAM libre de la ${main.name || `GPU ${main.index}`} en gpu02: ${Math.round(freeMiB)} MiB, menos de ${thr} MiB`); + } else if (gpu.vram_low && freeMiB > thr * 1.25) { + gpu.vram_low = false; + event('info', `VRAM libre de la ${main.name || `GPU ${main.index}`} en gpu02 de vuelta en ${Math.round(freeMiB)} MiB`); + } + } + } catch (err) { + gpu.fails++; gpu.err = errText(err); + if (!gpu.down_since) gpu.down_since = now; + if (gpu.fails >= 2 && !gpu.alerted_down) { + gpu.alerted_down = true; + event('warn', `Exporter de GPU de gpu02 no responde (${cfg.gpu.url}): ${gpu.err}`); + } + } +} + +function gpuView(cfg, nowS) { + const rows = db.prepare('SELECT ts, idx, util FROM gpu_samples WHERE ts >= ? ORDER BY ts').all(nowS - 3600); + return { + url: cfg.gpu.url, main_index: cfg.gpu.main_index, vram_warn_mib: cfg.gpu.vram_warn_mib, roles: cfg.gpu.roles, + state: gpu.fails >= 2 ? 'down' : gpu.fails === 1 ? 'doubt' : (gpu.last_ok ? 'up' : 'unknown'), + last_ok: gpu.last_ok, down_since: gpu.down_since, err: gpu.err, vram_low: gpu.vram_low, + gpus: gpu.gpus.map(g => { + const mine = rows.filter(r => r.idx === g.index).map(r => ({ ts: r.ts, ok: 1, dur_s: r.util })); + // buckets() saca mediana y máximo por minuto; acá el "tiempo" es el uso (0–1). + return { ...g, spark: buckets(mine, nowS) }; + }), + }; +} + +let lastPrune = 0; +async function tick(getChannels) { + const channels = getChannels(); + const cfg = config(); + try { ingest(channels); } catch (err) { console.error('[motores] ingest', err); } + const engines = engineList(channels); + for (const e of engines) { // de a uno: gpu02 compartido, nada en paralelo + await probe(e); + try { checkSlow(e, cfg); } catch (err) { console.error('[motores] slow', err); } + setSetting(`st:${e.key}`, stOf(e.key)); + } + await probeGpu(cfg); + pollN++; polledAt = Date.now(); + sampleCpu(); + if (Date.now() - lastPrune > 3600e3) { + const cut = Date.now() / 1000 - KEEP_S; + db.prepare('DELETE FROM engine_reqs WHERE ts < ?').run(cut); + db.prepare('DELETE FROM engine_polls WHERE ts < ?').run(cut); + db.prepare('DELETE FROM gpu_samples WHERE ts < ?').run(cut); + lastPrune = Date.now(); + } +} + +let timer = null; +function start(getChannels) { + const loop = async () => { + try { await tick(getChannels); } catch (err) { console.error('[motores]', err); } + timer = setTimeout(loop, config().poll_s * 1000); + }; + timer = setTimeout(loop, 2000); +} + +/* ---------- lo que ve el panel ---------- */ +function engineView(e, cfg, now) { + const s = stOf(e.key); + const nowS = now / 1000; + const rows24 = db.prepare('SELECT ts, channel, dur_s, audio_s, ok, error FROM engine_reqs WHERE kind = ? AND url = ? AND ts >= ? ORDER BY ts').all(e.kind, e.url, nowS - 86400); + const rows1 = rows24.filter(r => r.ts >= nowS - 3600); + const lastErr = db.prepare('SELECT ts, channel, error FROM engine_reqs WHERE kind = ? AND url = ? AND ok = 0 ORDER BY ts DESC LIMIT 1').get(e.kind, e.url); + const polls = db.prepare('SELECT up, busy FROM engine_polls WHERE kind = ? AND url = ? AND ts >= ?').all(e.kind, e.url, nowS - 3600); + const chans = [...new Set(rows1.map(r => r.channel).concat(e.channels))]; + const v = { + key: e.key, kind: e.kind, url: e.url, name: NAME[e.kind], channels: e.channels, + state: s.fails >= 2 ? 'down' : s.fails === 1 ? 'doubt' : (s.last_ok ? 'up' : 'unknown'), + last_ok: s.last_ok, down_since: s.down_since, last_check: s.last_check || null, last_err: s.last_err, + slow: !!s.slow, p95_15m: s.p95_15m ?? null, p95_warn_s: cfg[e.kind].p95_warn_s, + h1: statsOf(rows1), h24: statsOf(rows24), + last_error: lastErr ? { ts: lastErr.ts, channel: lastErr.channel, error: lastErr.error } : null, + spark: buckets(rows1, nowS), + by_channel: chans.map(c => ({ channel: c, ...statsOf(rows1.filter(r => r.channel === c)) })), + uptime_1h: polls.length ? r3(polls.filter(p => p.up).length / polls.length) : null, + }; + if (e.kind === 'asr') v.declared = { model: cfg.asr.model, hw: cfg.asr.hw }; + if (e.kind === 'llm') { + v.info = s.info || null; + v.slots = s.fails ? null : (s.slots || null); + const b = polls.filter(p => p.busy != null); + v.busy_pct_1h = b.length ? r3(b.filter(p => p.busy).length / b.length) : null; + v.busy_polls_1h = b.length; + } + return v; +} + +function alertLevel(engines) { + if (engines.some(e => e.state === 'down')) return 'red'; + if (engines.some(e => e.slow || e.state === 'doubt') || gpu.vram_low || gpu.fails >= 2) return 'amber'; + return null; +} + +function view(channels) { + const cfg = config(), now = Date.now(); + const engines = engineList(channels).map(e => engineView(e, cfg, now)); + return { config: cfg, polled_at: polledAt, engines, gpu: gpuView(cfg, now / 1000), alert: alertLevel(engines), host: hostInfo() }; +} + +function alert(channels) { + const engines = engineList(channels).map(e => { + const s = stOf(e.key); + return { state: s.fails >= 2 ? 'down' : s.fails === 1 ? 'doubt' : 'up', slow: !!s.slow }; + }); + return alertLevel(engines); +} + +/* ---------- este equipo (CT 176) ---------- */ +// CPU del CT por su cgroup (v2): /proc/stat en un LXC puede mostrar el host. +let cpuPrev = null, cpuPct = null; +function readCg(f) { try { return fs.readFileSync(`/sys/fs/cgroup/${f}`, 'utf8'); } catch { return null; } } +function sampleCpu() { + const t = readCg('cpu.stat'); + const m = t && /usage_usec (\d+)/.exec(t); + if (!m) return; + const cur = { u: Number(m[1]), w: process.hrtime.bigint() }; + if (cpuPrev) { + const du = cur.u - cpuPrev.u, dw = Number(cur.w - cpuPrev.w) / 1000; + if (dw > 0) cpuPct = r3(du / dw / os.cpus().length); + } + cpuPrev = cur; +} + +const versions = { node: process.version }; +function sh(cmd, args) { + return new Promise(res => execFile(cmd, args, { timeout: 5000 }, (err, out, errOut) => res(String(out || '') + String(errOut || '')))); +} +async function loadVersions() { + versions.ffmpeg = ((await sh('ffmpeg', ['-hide_banner', '-version'])).match(/ffmpeg version (\S+)/) || [])[1] || null; + versions.srt = ((await sh('srt-live-transmit', ['-version'])).match(/SRT Library version: ([\d.]+)/) || [])[1] || null; + // La versión de OrbiSubs es el commit que se instaló (lo escribe el deploy en VERSION). + for (const f of [process.env.ORBISUBS_VERSION_FILE, '/opt/orbisubs/VERSION', path.join(__dirname, '..', '..', 'VERSION')]) { + if (!f) continue; + try { versions.orbisubs = fs.readFileSync(f, 'utf8').trim(); break; } catch { /* sigue */ } + } +} + +let hlsSize = { at: 0, bytes: null }; +function dirBytes(dir, depth = 0) { + let n = 0; + if (depth > 4) return 0; + let ents; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return 0; } + for (const d of ents) { + const p = path.join(dir, d.name); + if (d.isDirectory()) n += dirBytes(p, depth + 1); + else if (d.isFile()) { try { n += fs.statSync(p).size; } catch { /* se borró recién */ } } + } + return n; +} + +function hostInfo() { + const memCur = Number(readCg('memory.current')), memMaxRaw = (readCg('memory.max') || '').trim(); + const total = memMaxRaw && memMaxRaw !== 'max' ? Number(memMaxRaw) : os.totalmem(); + const used = Number.isFinite(memCur) && memCur > 0 ? memCur : os.totalmem() - os.freemem(); + let disk = null; + try { + const st = fs.statfsSync(HLS_DIR); + disk = { total: st.blocks * st.bsize, free: st.bavail * st.bsize }; + } catch { /* sin /var/www/hls */ } + if (Date.now() - hlsSize.at > 300e3) hlsSize = { at: Date.now(), bytes: dirBytes(HLS_DIR) }; + return { + // Sin loadavg: en el LXC /proc/loadavg es el del host (pve7), no el del CT. + hostname: os.hostname(), cores: os.cpus().length, cpu: cpuPct, + mem: { used, total }, disk, hls_bytes: hlsSize.bytes, uptime_s: Math.round(os.uptime()), versions, + }; +} + +module.exports = { + start, view, alert, config, setConfig, loadVersions, tick, + // para los tests + engineList, parseLine, statsOf, buckets, quantile, ingestFile, normUrl, parseProm, +}; diff --git a/panel/src/public/app.js b/panel/src/public/app.js index 63c944a..f958795 100644 --- a/panel/src/public/app.js +++ b/panel/src/public/app.js @@ -104,7 +104,9 @@ function route() { $$('.nav a').forEach(a => a.classList.toggle('active', a.dataset.route === r)); clearInterval(pollTimer); if (r === 'events') { loadEvents(); pollTimer = setInterval(loadEvents, 10000); } + else if (r === 'engines') { loadEngines(); pollTimer = setInterval(loadEngines, 10000); } else { loadChannels(); pollTimer = setInterval(loadChannels, 5000); } + loadEngineAlert(); } window.addEventListener('hashchange', route); diff --git a/panel/src/public/engines.js b/panel/src/public/engines.js new file mode 100644 index 0000000..4e08970 --- /dev/null +++ b/panel/src/public/engines.js @@ -0,0 +1,267 @@ +/* engines.js — pestaña Motores (tarea 080): Whisper, LLM, GPU de gpu02 y este equipo. + * Todo sale de /api/engines: el backend sondea gpu02 y guarda los pedidos de los canales. */ +'use strict'; + +let enginesData = null; +const fmtS = v => (v == null ? '—' : `${Number(v).toFixed(2)} s`); +const fmtPct = v => (v == null ? '—' : `${Math.round(v * 100)} %`); +const fmtBytes = b => { + if (b == null) return '—'; + const u = ['B', 'KB', 'MB', 'GB', 'TB']; let i = 0; + while (b >= 1024 && i < u.length - 1) { b /= 1024; i++; } + return `${b.toFixed(b < 10 && i ? 1 : 0)} ${u[i]}`; +}; +const fmtAgo = ms => { + if (!ms) return '—'; + const s = Math.max(0, (Date.now() - ms) / 1000); + if (s < 90) return t('hace {n} s', { n: Math.round(s) }); + if (s < 5400) return t('hace {n} min', { n: Math.round(s / 60) }); + if (s < 172800) return t('hace {n} h', { n: (s / 3600).toFixed(1) }); + return t('hace {n} días', { n: Math.round(s / 86400) }); +}; +const fmtTime = ms => (ms ? new Date(ms).toLocaleTimeString(OrbiLang.locale(), { hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '—'); +const fmtUptime = s => { + const d = Math.floor(s / 86400), h = Math.floor(s % 86400 / 3600), m = Math.floor(s % 3600 / 60); + return d ? `${d} d ${h} h` : h ? `${h} h ${m} min` : `${m} min`; +}; +const chName = slug => { const c = (typeof channels !== 'undefined' ? channels : []).find(x => x.slug === slug); return c ? c.name : slug; }; + +async function loadEngineAlert() { + try { const r = await api('GET', '/api/engines/alert'); setEngineDot(r.alert); } catch { /* banner o login */ } +} +function setEngineDot(level) { + const d = $('#nav-engines-dot'); + d.classList.toggle('hidden', !level); + d.classList.toggle('red', level === 'red'); + d.classList.toggle('amber', level === 'amber'); + d.title = level === 'red' ? t('Un motor no responde') : level === 'amber' ? t('Un motor anda lento o no respondió el último sondeo') : ''; +} +setInterval(() => { if (me) loadEngineAlert(); }, 15000); + +async function loadEngines() { + try { + if (!channels.length) { const r = await api('GET', '/api/channels'); channels = r.channels; } + enginesData = await api('GET', '/api/engines'); + } catch { return; } + setEngineDot(enginesData.alert); + renderEngines(); +} + +const STATE_E = { + up: ['running', 'vivo'], down: ['error', 'caído'], doubt: ['connecting', 'sin respuesta'], unknown: ['stopped', 'sin datos'], +}; + +// Sparkline SVG: mediana por minuto (línea) y máximo (área tenue); fallas como marcas rojas. +function sparkline(points, warn) { + const W = 300, H = 54, P = 3; + const vals = points.flatMap(p => [p.med, p.max]).filter(v => v != null); + if (!vals.length) return `
${t('sin pedidos en la última hora')}
`; + const top = Math.max(...vals, warn || 0) * 1.1 || 1; + const x = i => P + i * (W - 2 * P) / Math.max(1, points.length - 1); + const y = v => H - P - v / top * (H - 2 * P); + const path = k => { + let d = '', pen = false; + points.forEach((p, i) => { + if (p[k] == null) { pen = false; return; } + d += `${pen ? 'L' : 'M'}${x(i).toFixed(1)},${y(p[k]).toFixed(1)}`; pen = true; + }); + return d; + }; + const fails = points.map((p, i) => (p.fails ? `` : '')).join(''); + const warnLine = warn && warn < top ? `` : ''; + return ` + ${fails}${warnLine} +
${t('mediana por minuto')}${t('máximo')}${warn ? `${t('umbral {s} s', { s: warn })}` : ''}${t('escala 0–{s}', { s: fmtS(top) })}
`; +} + +function row(label, value, cls = '') { return `
${label}${value}
`; } + +function statsTable(e) { + const h = [e.h1, e.h24]; + const r = (lbl, f) => `${lbl}${h.map(x => `${f(x)}`).join('')}`; + return ` + ${r(t('Pedidos'), x => x.n)} + ${r(t('Fallas'), x => (x.fails ? `${x.fails}` : 0))} + ${r(t('Mediana'), x => fmtS(x.median_s))} + ${r('p95', x => fmtS(x.p95_s))} + ${e.kind === 'asr' ? r(t('RTF (mediana)'), x => (x.rtf == null ? '—' : x.rtf.toFixed(3))) : ''} +
${t('1 h')}${t('24 h')}
`; +} + +function byChannel(e) { + if (!e.by_channel.length) return ''; + return ` + ${e.by_channel.map(c => ``).join('')} +
${t('Canal (última hora)')}${t('Pedidos')}${t('Fallas')}${t('Mediana')}p95
${esc(chName(c.channel))} ${esc(c.channel)}${c.n}${c.fails ? `${c.fails}` : 0}${fmtS(c.median_s)}${fmtS(c.p95_s)}
`; +} + +function aliveRows(e) { + const out = []; + if (e.state === 'down' || e.state === 'doubt') { + out.push(row(t('Caído desde'), `${fmtTime(e.down_since)} (${fmtAgo(e.down_since)})`)); + out.push(row(t('Error del sondeo'), `${esc(e.last_err || '—')}`)); + } + out.push(row(t('Último OK'), e.last_ok ? `${fmtTime(e.last_ok)} (${fmtAgo(e.last_ok)})` : '—')); + out.push(row(t('Responde (1 h)'), fmtPct(e.uptime_1h))); + return out.join(''); +} + +function lastErrorRow(e) { + if (!e.last_error) return row(t('Último error de un pedido'), `${t('ninguno guardado')}`); + const le = e.last_error; + return row(t('Último error de un pedido'), `${esc(le.error || '—')}
${new Date(le.ts * 1000).toLocaleString(OrbiLang.locale())} · ${esc(chName(le.channel))}
`); +} + +function cardHead(title, sub, stateKey, extra = '') { + const [cls, label] = STATE_E[stateKey] || STATE_E.unknown; + return `

${title}

${sub}
${extra}${t(label)}
`; +} + +function whisperCard(e) { + const slow = e.slow ? `${t('lento')}` : ''; + return `
+ ${cardHead(t('Whisper (reconocimiento)'), `${esc(e.url)}`, e.state, slow)} + ${row(t('Modelo'), `${esc(e.declared.model || '—')} ${t('declarado')}`)} + ${row(t('Equipo'), `${esc(e.declared.hw || '—')} ${t('declarado')}`)} + ${aliveRows(e)} +

${t('Compartido: batman (10.100.101.101) también usa este motor por un túnel SSH inverso.')}

+ ${statsTable(e)} + ${lastErrorRow(e)} +
${t('Tiempo por pedido, última hora')}
+ ${sparkline(e.spark, e.p95_warn_s)} + ${byChannel(e)} +
`; +} + +function llmCard(e) { + const i = e.info || {}; + const slow = e.slow ? `${t('lento')}` : ''; + const busyNow = e.slots + ? (e.slots.busy ? `${t('ocupado: {b} de {n} slots', { b: e.slots.busy, n: e.slots.total })}` : t('libre ({n} slots)', { n: e.slots.total })) + : '—'; + const model = i.model_path ? `${esc(i.model_path.split('/').pop())}${i.model_ftype ? ` ${esc(i.model_ftype)}` : ''}` : '—'; + return `
+ ${cardHead(t('LLM (traducción)'), `${esc(e.url)}`, e.state, slow)} + ${row(t('Modelo'), i.model_path ? `${model} ${t('leído')}` : model)} + ${row(t('Nombre publicado'), i.published ? `${esc(i.published)} ${t('leído')}` : '—')} + ${row('n_ctx', i.n_ctx ? i.n_ctx.toLocaleString(OrbiLang.locale()) : '—')} + ${row(t('Versión (build)'), i.build ? `${esc(i.build)}` : '—')} + ${row(t('Ahora'), busyNow)} + ${row(t('Ocupado (1 h, sondeado)'), `${fmtPct(e.busy_pct_1h)} ${t('de {n} sondeos, incluye a otros usuarios', { n: e.busy_polls_1h || 0 })}`)} +

${t('Compartido: batman (10.100.101.101) también usa este motor por un túnel SSH inverso, así que "ocupado" puede ser batman y no OrbiSubs.')}

+ ${aliveRows(e)} + ${statsTable(e)} + ${lastErrorRow(e)} +
${t('Tiempo por pedido, última hora')}
+ ${sparkline(e.spark, e.p95_warn_s)} + ${byChannel(e)} +
`; +} + +// Sparkline de uso de GPU: escala fija 0–100 %. +function utilSpark(points) { + const W = 300, H = 40, P = 3; + if (!points.some(p => p.med != null)) return `
${t('sin muestras en la última hora')}
`; + const x = i => P + i * (W - 2 * P) / Math.max(1, points.length - 1); + const y = v => H - P - v * (H - 2 * P); + const path = k => { let d = '', pen = false; points.forEach((p, i) => { if (p[k] == null) { pen = false; return; } d += `${pen ? 'L' : 'M'}${x(i).toFixed(1)},${y(p[k]).toFixed(1)}`; pen = true; }); return d; }; + return ``; +} + +function gpuCard(gv) { + if (!gv || (!gv.gpus.length && gv.state !== 'down' && gv.state !== 'doubt')) { + return `
${cardHead(t('GPU de gpu02'), gv ? `${esc(gv.url)}` : '', 'unknown')}
${t('Esperando el primer sondeo del exporter.')}
`; + } + const down = gv.state === 'down' || gv.state === 'doubt'; + const vram = gv.vram_low ? `${t('poca VRAM')}` : ''; + const first = gv.gpus[0] || {}; + const rows = gv.gpus.map(g => { + const main = g.index === gv.main_index; + const free = g.mem_free != null ? g.mem_free / 1048576 : null; + const low = main && free != null && free < gv.vram_warn_mib; + return `
+
${esc(String(g.name || `GPU ${g.index}`).replace('NVIDIA GeForce ', ''))} GPU ${g.index}${main ? ` ${t('la que usamos')}` : ''}
+
${esc(gv.roles[g.index] || '—')} ${t('declarado')}
+
+ ${t('Uso')} ${fmtPct(g.util)} + VRAM ${fmtBytes(g.mem_used)} / ${fmtBytes(g.mem_total)}${free != null ? ` (${t('{m} MiB libres', { m: Math.round(free) })})` : ''} + ${t('Temp.')} ${g.temp != null ? `${g.temp} °C` : '—'} + ${t('Consumo')} ${g.power != null ? `${Math.round(g.power)} W` : '—'} +
+ ${utilSpark(g.spark)} +
`; + }).join(''); + return `
+ ${cardHead(t('GPU de gpu02'), `${esc(gv.url)}`, gv.state, vram)} + ${down ? row(t('Caído desde'), `${fmtTime(gv.down_since)} ${esc(gv.err || '')}`) : ''} + ${row(t('Driver / CUDA'), first.driver ? `${esc(first.driver)} / ${esc(first.cuda || '—')}` : '—')} + ${row(t('Último dato'), gv.last_ok ? `${fmtTime(gv.last_ok)} (${fmtAgo(gv.last_ok)})` : '—')} + ${rows} +

${t('Uso por minuto de la última hora (mediana y máximo). Aviso si la VRAM libre de la placa resaltada baja de {m} MiB.', { m: gv.vram_warn_mib })}

+
`; +} + +function hostCard(h) { + const v = h.versions || {}; + const memPct = h.mem.total ? h.mem.used / h.mem.total : null; + const diskUsed = h.disk ? h.disk.total - h.disk.free : null; + return `
+ ${cardHead(t('Este equipo'), `${esc(h.hostname)}`, 'up')} + ${row('CPU', `${fmtPct(h.cpu)} ${t('de {n} cores, medido en el cgroup del CT', { n: h.cores })}`)} + ${row('RAM', `${fmtBytes(h.mem.used)} / ${fmtBytes(h.mem.total)} (${fmtPct(memPct)})`)} + ${row(t('Disco de /var/www/hls'), h.disk ? `${fmtBytes(diskUsed)} / ${fmtBytes(h.disk.total)} ${t('{b} en HLS', { b: fmtBytes(h.hls_bytes) })}` : '—')} + ${row(t('Encendido hace'), fmtUptime(h.uptime_s))} + ${row('OrbiSubs', v.orbisubs ? `${esc(v.orbisubs)}` : '—')} + ${row('ffmpeg', `${esc(v.ffmpeg || '—')}`)} + ${row('Node', `${esc(v.node || '—')}`)} + ${row('srt-live-transmit', `${esc(v.srt || '—')}`)} +
`; +} + +function renderEngines() { + const d = enginesData; + if (!d) return; + $('#engines-sub').textContent = t('Sondeo cada {s} s · último {a}', { s: d.config.poll_s, a: d.polled_at ? fmtTime(d.polled_at) : '—' }); + const cards = [ + ...d.engines.filter(e => e.kind === 'asr').map(whisperCard), + ...d.engines.filter(e => e.kind === 'llm').map(llmCard), + gpuCard(d.gpu), hostCard(d.host), + ]; + $('#engines-cards').innerHTML = cards.join(''); +} + +/* ---------- configuración ---------- */ +$('#btn-engines-cfg').onclick = () => { + const c = (enginesData && enginesData.config) || {}; + const f = $('#engines-form'); + f.asr_model.value = c.asr ? c.asr.model : ''; + f.asr_hw.value = c.asr ? c.asr.hw : ''; + f.asr_p95.value = c.asr ? c.asr.p95_warn_s : 3; + f.llm_p95.value = c.llm ? c.llm.p95_warn_s : 3; + f.poll_s.value = c.poll_s || 20; + f.vram_warn.value = c.gpu ? c.gpu.vram_warn_mib : 512; + $('#engines-form-error').classList.add('hidden'); + $('#engines-modal').classList.remove('hidden'); +}; +$('#engines-modal-close').onclick = $('#engines-cancel').onclick = () => $('#engines-modal').classList.add('hidden'); +$('#engines-form').addEventListener('submit', async e => { + e.preventDefault(); + const f = e.target; + const n = (v, lo, hi) => { const x = Number(v); return Number.isFinite(x) && x >= lo && x <= hi; }; + let bad = null; + if (!n(f.asr_p95.value, 0.5, 60) || !n(f.llm_p95.value, 0.5, 60)) bad = t('Umbral de p95: entre 0,5 y 60 s'); + else if (!n(f.poll_s.value, 15, 30)) bad = t('Sondeo: entre 15 y 30 s'); + else if (!n(f.vram_warn.value, 64, 16384)) bad = t('Aviso de VRAM: entre 64 y 16384 MiB'); + if (bad) { $('#engines-form-error').textContent = bad; $('#engines-form-error').classList.remove('hidden'); return; } + try { + await api('PUT', '/api/engines/config', { + poll_s: Number(f.poll_s.value), + asr: { model: f.asr_model.value, hw: f.asr_hw.value, p95_warn_s: Number(f.asr_p95.value) }, + llm: { p95_warn_s: Number(f.llm_p95.value) }, + gpu: { vram_warn_mib: Number(f.vram_warn.value) }, + }); + $('#engines-modal').classList.add('hidden'); + loadEngines(); + } catch (err) { $('#engines-form-error').textContent = err.message; $('#engines-form-error').classList.remove('hidden'); } +}); +window.addEventListener('orbi-lang', () => { if (me && enginesData) renderEngines(); }); diff --git a/panel/src/public/i18n.js b/panel/src/public/i18n.js index 1895595..74a3d09 100644 --- a/panel/src/public/i18n.js +++ b/panel/src/public/i18n.js @@ -170,4 +170,89 @@ OrbiLang.add({ en: { 'La passphrase tenía un %-escape inválido; se copió tal cual.': 'The passphrase had an invalid %-escape; it was copied as is.', 'La passphrase tiene {n} caracteres; SRT exige entre 10 y 79.': 'The passphrase has {n} characters; SRT requires between 10 and 79.', 'Se dejaron en la URL: {list}.': 'Left in the URL: {list}.', + // ---- Motores (080) ---- + "Motores": "Engines", + "Configuración": "Settings", + "El panel consulta gpu02 desde el servidor (GET /health, /slots, /props, /v1/models y el exporter de GPU en :9835), una sola vez por sondeo aunque haya varias pestañas abiertas. Los tiempos y las fallas son los de los pedidos de los canales, guardados 7 días.": "The panel queries gpu02 from the server (GET /health, /slots, /props, /v1/models and the GPU exporter on :9835), once per poll no matter how many tabs are open. Times and failures come from the channels' own requests, kept for 7 days.", + "Configuración de motores": "Engine settings", + "whisper.cpp no informa el modelo ni el equipo: estos dos datos se declaran acá y el panel los muestra como declarados.": "whisper.cpp does not report its model or hardware: these two values are declared here and shown as declared.", + "Modelo (declarado)": "Model (declared)", + "Equipo (declarado)": "Hardware (declared)", + "Aviso si el p95 pasa (s)": "Warn when p95 exceeds (s)", + "p95 de los últimos 15 min. Con segmentos de 6 s, 3 s deja margen.": "p95 over the last 15 min. With 6 s segments, 3 s leaves headroom.", + "Sondeo cada (s)": "Poll every (s)", + "Entre 15 y 30 s. Vale para los dos motores.": "Between 15 and 30 s. Applies to both engines.", + "Las URL de los motores son las de cada canal (Reconocimiento y Traducción, en el modal del canal).": "Engine URLs are the ones set in each channel (Recognition and Translation, in the channel dialog).", + "Guardar": "Save", + "hace {n} s": "{n} s ago", + "hace {n} min": "{n} min ago", + "hace {n} h": "{n} h ago", + "hace {n} días": "{n} days ago", + "Un motor no responde": "An engine is not responding", + "Un motor anda lento o no respondió el último sondeo": "An engine is slow or missed the last poll", + "vivo": "up", + "caído": "down", + "sin respuesta": "no answer", + "sin datos": "no data", + "sin pedidos en la última hora": "no requests in the last hour", + "Tiempo por pedido, última hora": "Time per request, last hour", + "mediana por minuto": "median per minute", + "máximo": "max", + "umbral {s} s": "threshold {s} s", + "escala 0–{s}": "scale 0–{s}", + "1 h": "1 h", + "24 h": "24 h", + "Pedidos": "Requests", + "Fallas": "Failures", + "Mediana": "Median", + "RTF (mediana)": "RTF (median)", + "Canal (última hora)": "Channel (last hour)", + "Caído desde": "Down since", + "Error del sondeo": "Poll error", + "Último OK": "Last OK", + "Responde (1 h)": "Answering (1 h)", + "Último error de un pedido": "Last request error", + "ninguno guardado": "none stored", + "lento": "slow", + "p95 de 15 min: {s}": "15-min p95: {s}", + "Whisper (reconocimiento)": "Whisper (recognition)", + "Modelo": "Model", + "whisper.cpp no lo informa: es lo que dice la configuración del panel": "whisper.cpp does not report it: this is what the panel settings say", + "declarado": "declared", + "Equipo": "Hardware", + "leído": "read", + "ocupado: {b} de {n} slots": "busy: {b} of {n} slots", + "libre ({n} slots)": "idle ({n} slots)", + "LLM (traducción)": "LLM (translation)", + "Nombre publicado": "Published name", + "Versión (build)": "Version (build)", + "Ahora": "Now", + "Ocupado (1 h, sondeado)": "Busy (1 h, polled)", + "de {n} sondeos, incluye a otros usuarios": "of {n} polls, includes other users", + "GPU de gpu02": "gpu02 GPU", + "Este equipo": "This host", + "de {n} cores, medido en el cgroup del CT": "of {n} cores, measured on the CT cgroup", + "Disco de /var/www/hls": "/var/www/hls disk", + "{b} en HLS": "{b} in HLS", + "Encendido hace": "Up for", + "Sondeo cada {s} s · último {a}": "Polled every {s} s · last {a}", + "Umbral de p95: entre 0,5 y 60 s": "p95 threshold: between 0.5 and 60 s", + "Sondeo: entre 15 y 30 s": "Poll: between 15 and 30 s", + "Configuración de motores cambiada": "Engine settings changed", + "sin muestras en la última hora": "no samples in the last hour", + "Uso de la GPU, última hora": "GPU usage, last hour", + "Esperando el primer sondeo del exporter.": "Waiting for the first exporter poll.", + "poca VRAM": "low VRAM", + "la que usamos": "the one we use", + "Uso": "Usage", + "{m} MiB libres": "{m} MiB free", + "Temp.": "Temp.", + "Consumo": "Power", + "Driver / CUDA": "Driver / CUDA", + "Último dato": "Last sample", + "Uso por minuto de la última hora (mediana y máximo). Aviso si la VRAM libre de la placa resaltada baja de {m} MiB.": "Usage per minute over the last hour (median and max). Warns when free VRAM on the highlighted card drops below {m} MiB.", + "Compartido: batman (10.100.101.101) también usa este motor por un túnel SSH inverso, así que \"ocupado\" puede ser batman y no OrbiSubs.": "Shared: batman (10.100.101.101) also uses this engine through a reverse SSH tunnel, so \"busy\" may be batman rather than OrbiSubs.", + "Compartido: batman (10.100.101.101) también usa este motor por un túnel SSH inverso.": "Shared: batman (10.100.101.101) also uses this engine through a reverse SSH tunnel.", + "Aviso de VRAM: entre 64 y 16384 MiB": "VRAM warning: between 64 and 16384 MiB", + "Aviso si la VRAM libre de la 3060 baja de (MiB)": "Warn when free 3060 VRAM drops below (MiB)", } }); diff --git a/panel/src/public/index.html b/panel/src/public/index.html index 278b7d7..9f90794 100644 --- a/panel/src/public/index.html +++ b/panel/src/public/index.html @@ -61,6 +61,7 @@ @@ -264,6 +275,50 @@ + + +