Merge feature/modellseite: Modellarten und Stimmenfreigabe

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GmHhg5PTXgibMTZUHzfLYM
This commit is contained in:
2026-11-18 20:35:59 +01:00
11 changed files with 429 additions and 15 deletions

View File

@ -0,0 +1,30 @@
// Der Testsatz kommt ausschließlich vom Server; hier wird nur die Stimme gewählt.
(() => {
const status = document.getElementById('probe-status');
const csrf = document.querySelector('input[name=csrf]')?.value;
document.querySelectorAll('button.probe').forEach(button => button.addEventListener('click', async () => {
const select = button.parentElement.querySelector('.stimmen-modell');
const saved = button.dataset.gespeichert === '1';
const matches = o => o.dataset.art === (saved ? 'gespeichert' : 'eingebaut') || o.dataset.art === 'alle';
const model = matches(select.selectedOptions[0]) ? select.selectedOptions[0] : Array.from(select.options).find(matches);
if (!model) { status.textContent = 'Kein passendes installiertes Sprachmodell verfügbar.'; return; }
button.disabled = true;
status.textContent = 'Probehören wird geladen …';
try {
const response = await fetch('/ui/modelle/probe', {method: 'POST', headers: {'Content-Type': 'application/json', 'X-CSRF-Token': csrf}, credentials: 'same-origin', body: JSON.stringify({model: model.value, voice: button.dataset.stimme})});
if (!response.ok) throw new Error('Die Stimme konnte nicht probegehört werden.');
// PCM 24 kHz / 16 Bit / Mono, wie bei der bestehenden Vorlese-Route.
const pcm = await response.arrayBuffer();
const samples = new Int16Array(pcm);
const ctx = new AudioContext({sampleRate: 24000});
await ctx.resume();
const buffer = ctx.createBuffer(1, samples.length, 24000);
const channel = buffer.getChannelData(0);
for (let i = 0; i < samples.length; i++) channel[i] = samples[i] / 32768;
const source = ctx.createBufferSource(); source.buffer = buffer; source.connect(ctx.destination);
source.onended = () => ctx.close(); source.start();
status.textContent = 'Probehören läuft.';
} catch (_) { status.textContent = 'Die Stimme konnte nicht probegehört werden.'; }
finally { button.disabled = false; }
}));
})();

View File

@ -49,6 +49,7 @@ mod engines;
mod faehigkeiten;
mod logs;
mod startprofiles;
mod stimmen;
mod verwaltung;
const COOKIE_NAME: &str = "nexus_ui";
@ -125,6 +126,9 @@ pub fn routes() -> Router<Arc<AppState>> {
.route("/ui/benutzer/entfernen", post(benutzer::user_remove))
.route("/ui/benutzer/update-pruefen", post(benutzer::update_check))
.route("/ui/modelle", get(verwaltung::models_page))
.route("/ui/modelle/stimme", post(stimmen::save))
.route("/ui/modelle/probe", post(chat::preview))
.route("/ui/stimmen.js", get(stimmen::script))
.route("/ui/teil/modelle", get(verwaltung::models_fragment))
.route("/ui/modelle/laden", post(verwaltung::model_load))
.route("/ui/modelle/entladen", post(verwaltung::model_unload))

View File

@ -281,6 +281,51 @@ pub(super) async fn speak(
Ok(request) => request,
Err(message) => return bad(message),
};
speak_request(state, slot, correlation, started, viewer, request, false).await
}
/// Getrennter Weg für Probehören: Text wird serverseitig festgelegt.
pub(super) async fn preview(
State(state): State<Arc<AppState>>,
Extension(slot): Extension<AccessSlot>,
Extension(RequestId(correlation)): Extension<RequestId>,
Extension(StartedAt(started)): Extension<StartedAt>,
headers: HeaderMap,
body: Bytes,
) -> Response {
let viewer = match json_viewer(&state, &headers, &slot) {
Ok(v) => v,
Err(response) => return response,
};
let Ok(input) = serde_json::from_slice::<Value>(&body) else {
return bad("Die Anfrage ist kein gültiges JSON.");
};
if input
.get("voice")
.and_then(Value::as_str)
.is_none_or(str::is_empty)
{
return bad("Die Stimme fehlt.");
}
const TESTSATZ: &str = "Guten Tag, ich bin eine Stimme von Nexus.";
let request = match build_speech_request(&json!({
"model": input.get("model"), "voice": input.get("voice"), "input": TESTSATZ
})) {
Ok(request) => request,
Err(message) => return bad(message),
};
speak_request(state, slot, correlation, started, viewer, request, true).await
}
async fn speak_request(
state: Arc<AppState>,
slot: AccessSlot,
correlation: String,
started: std::time::Instant,
viewer: super::Viewer,
request: Value,
preview: bool,
) -> Response {
let model = request["model"].as_str().unwrap_or_default();
let plan = match state.store().start_plan(model) {
Ok(Some(plan)) if plan.engine_name == "tts" && viewer.key.rights.allows(model) => plan,
@ -294,6 +339,28 @@ pub(super) async fn speak(
if !speech_offered(&state.runtime, &plan.model_path.to_string_lossy()) {
return ApiError::speech_model_not_installed().into_response();
}
let voice = request["voice"].as_str().unwrap_or_default();
let kind = voice_art(&plan.model_path.to_string_lossy());
let known = state
.runtime
.engine_voices("tts")
.await
.into_iter()
.any(|v| {
v.id == voice
&& (kind == "alle" || (kind == "gespeichert") == v.saved)
&& (preview
|| state
.store()
.voice_approved(voice, v.saved, &viewer.user)
.unwrap_or(false))
});
if !known {
return super::refused(
StatusCode::FORBIDDEN,
"Die Stimme ist nicht freigegeben oder nicht verfügbar.",
);
}
let Ok(bytes) = serde_json::to_vec(&request) else {
return ApiError::internal().into_response();
};
@ -361,10 +428,15 @@ pub(super) async fn voices(
.engine_voices(&plan.engine_name)
.await
.into_iter()
.filter(|v| match art {
"gespeichert" => v.saved,
"eingebaut" => !v.saved,
_ => true,
.filter(|v| {
(match art {
"gespeichert" => v.saved,
"eingebaut" => !v.saved,
_ => true,
}) && state
.store()
.voice_approved(&v.id, v.saved, &user.user)
.unwrap_or(false)
})
.map(|v| json!({ "id": v.id, "name": v.name, "gespeichert": v.saved }))
.collect();

View File

@ -0,0 +1,119 @@
//! Sprachmodelle und Freigabe der Stimmen in Nexus; Audio bleibt beim Studio.
use super::{audit, csrf_field, esc, form_field, guard, redirect};
use crate::state::AppState;
use axum::{
body::Bytes,
extract::State,
http::{HeaderMap, StatusCode},
response::Response,
};
use std::sync::Arc;
pub(super) async fn page(state: &AppState, user: &super::Viewer) -> String {
let models: String = state.store().list_models(false).unwrap_or_default().into_iter()
.filter_map(|m| {
let details = state.store().model_details(&m.name).ok().flatten()?;
if details.engine != "tts" { return None; }
let installed = crate::ui::chat::speech_offered(&state.runtime, &details.path);
let mode = match super::chat::voice_art(&details.path) {
"gespeichert" => "klonen", "eingebaut" => "eingebaut", _ => "entwerfen",
};
Some(format!("<tr><td>{}</td><td>Deutsch und weitere (Studio)</td><td>{mode}</td><td>{}</td></tr>",
esc(&m.name), if installed { "ja" } else { "nein" }))
}).collect();
let mut body = format!(
"<section class=\"card\"><h2>Sprachmodelle</h2><div class=\"breit\"><table><thead><tr><th>Modell</th><th>Sprachen</th><th>Modus</th><th>Installiert</th></tr></thead><tbody>{models}</tbody></table></div><p class=\"klein\">Die genaue Sprachenliste meldet das Studio derzeit nicht je Modell.</p></section>"
);
let voices = state.runtime.engine_voices("tts").await;
let options: String = state
.store()
.list_models(true)
.unwrap_or_default()
.into_iter()
.filter_map(|m| {
let d = state.store().model_details(&m.name).ok().flatten()?;
if d.engine != "tts" || !crate::ui::chat::speech_offered(&state.runtime, &d.path) {
return None;
}
Some(format!(
"<option value=\"{}\" data-art=\"{}\">{}</option>",
esc(&m.name),
super::chat::voice_art(&d.path),
esc(&m.name)
))
})
.collect();
body.push_str("<section class=\"card\"><h2>Stimmen</h2><p class=\"klein\">Eine Stimme darf ohne Freigabe nur probegehört werden. Die erste Freigabe beansprucht die Stimme für diesen Benutzer.</p>");
if options.is_empty() {
body.push_str("<p class=\"leer\">Kein installiertes Sprachmodell verfügbar.</p>");
}
for v in voices {
let approved = state
.store()
.voice_approved(&v.id, v.saved, &user.user)
.unwrap_or(false);
let art = if v.saved { "gespeichert" } else { "eingebaut" };
body.push_str(&format!("<div class=\"zeile\"><strong>{}</strong><span class=\"klein\">({art})</span><select aria-label=\"Sprachmodell für {}\" class=\"stimmen-modell\">{options}</select><button type=\"button\" class=\"sm probe\" data-stimme=\"{}\" data-gespeichert=\"{}\">Probehören</button><form method=\"post\" action=\"/ui/modelle/stimme\">{}<input type=\"hidden\" name=\"stimme\" value=\"{}\"><input type=\"hidden\" name=\"gespeichert\" value=\"{}\"><input type=\"hidden\" name=\"freigabe\" value=\"{}\"><button class=\"sm\" type=\"submit\">{}</button></form></div>",
esc(&v.name), esc(&v.name), esc(&v.id), if v.saved { "1" } else { "0" }, csrf_field(user), esc(&v.id), if v.saved { "1" } else { "0" }, if approved { "0" } else { "1" }, if approved { "Freigabe zurücknehmen" } else { "Freigeben" }));
}
body.push_str("<p id=\"probe-status\" role=\"status\"></p></section><script src=\"/ui/stimmen.js\"></script>");
body
}
pub(super) async fn save(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
body: Bytes,
) -> Response {
let user = match guard(
&state,
&headers,
form_field(&body, "csrf").as_deref(),
false,
) {
Ok(user) => user,
Err(r) => return *r,
};
let voice = form_field(&body, "stimme").unwrap_or_default();
let saved = form_field(&body, "gespeichert").as_deref() == Some("1");
let approved = form_field(&body, "freigabe").as_deref() == Some("1");
if voice.is_empty()
|| !state
.runtime
.engine_voices("tts")
.await
.iter()
.any(|v| v.id == voice && v.saved == saved)
{
return super::refused(StatusCode::BAD_REQUEST, "Die Stimme ist nicht verfügbar.");
}
match state
.store()
.set_voice_approval(&voice, saved, &user.user, approved)
{
Ok(true) => {
audit(&state, &user, "voice.approval", &voice);
redirect("/ui/modelle?art=sprache")
}
Ok(false) => super::refused(
StatusCode::FORBIDDEN,
"Nur der Besitzer kann diese Stimme freigeben.",
),
Err(_) => super::refused(
StatusCode::INTERNAL_SERVER_ERROR,
"Die Freigabe konnte nicht gespeichert werden.",
),
}
}
pub(super) async fn script() -> Response {
super::secure(Response::builder())
.header(
axum::http::header::CONTENT_TYPE,
"text/javascript; charset=utf-8",
)
.body(axum::body::Body::from(include_str!(
"../../assets/stimmen.js"
)))
.unwrap_or_default()
}

View File

@ -16,7 +16,7 @@ use nexus_core::Priority;
use nexus_store::Rights;
use super::{Viewer, audit, csrf_field, esc, form_field, guard, html, layout, mb, notice, opt};
use super::{redirect, viewer};
use super::{redirect, stimmen, viewer};
use crate::runtime::{SchedulerView, UnloadRefusal};
use crate::state::AppState;
@ -80,6 +80,8 @@ struct ModelRow {
engine: Option<String>,
gpus: String,
context: Option<u32>,
quantization: Option<String>,
size_bytes: Option<i64>,
path: String,
declared_mb: Option<i64>,
measured_mb: Option<i64>,
@ -111,6 +113,8 @@ fn model_rows(state: &AppState) -> Vec<ModelRow> {
})
.unwrap_or_default(),
context: details.as_ref().and_then(|d| d.context),
quantization: details.as_ref().and_then(|d| d.quantization.clone()),
size_bytes: details.as_ref().and_then(|d| d.size_bytes),
path: details.as_ref().map(|d| d.path.clone()).unwrap_or_default(),
declared_mb: p.and_then(|p| p.1),
measured_mb: p.and_then(|p| p.2),
@ -129,6 +133,25 @@ fn idle_text(secs: Option<i64>) -> String {
}
}
fn model_art(engine: Option<&str>) -> &'static str {
if engine == Some("tts") {
"sprache"
} else {
"llm"
}
}
#[cfg(test)]
mod art_tests {
use super::model_art;
#[test]
fn art_kommt_von_der_engine() {
assert_eq!(model_art(Some("tts")), "sprache");
assert_eq!(model_art(Some("llama.cpp")), "llm");
assert_eq!(model_art(Some("strata")), "llm");
}
}
fn models_table(state: &AppState, viewer: &Viewer) -> String {
let rows = model_rows(state);
if rows.is_empty() {
@ -145,6 +168,7 @@ fn models_table(state: &AppState, viewer: &Viewer) -> String {
.collect();
let body: String = rows
.iter()
.filter(|m| model_art(m.engine.as_deref()) == "llm")
.map(|m| {
let inst = view.instances.iter().find(|i| i.model == m.name);
let waiting = view.waiting.iter().filter(|w| w.model == m.name).count();
@ -226,7 +250,7 @@ fn models_table(state: &AppState, viewer: &Viewer) -> String {
let row_id = format!("modell-{}", dialog_id(&m.name));
format!(
"<tr id=\"{row_id}\"><td class=\"name\">{}</td><td>{}</td><td>{}</td>{faehig}<td>{}</td><td class=\"num\"{context_attr}>{context}</td>\
<td class=\"num\"{memory_attr}>{memory}</td><td data-sort=\"{state_sort}\">{state_chip}</td>{actions}</tr>",
<td class=\"num\"{memory_attr}>{memory}</td><td>{}</td><td>{}</td><td data-sort=\"{state_sort}\">{state_chip}</td>{actions}</tr>",
esc(&m.name),
m.engine
.as_ref()
@ -242,12 +266,14 @@ fn models_table(state: &AppState, viewer: &Viewer) -> String {
} else {
super::faehigkeiten::gpu_symbole(&m.gpus)
},
m.quantization.as_deref().map(esc).unwrap_or_else(|| "–".to_string()),
m.size_bytes.map(|v| format!("{:.1} GiB", v as f64 / 1073741824.0)).unwrap_or_else(|| "–".to_string()),
)
})
.collect();
format!(
"<div class=\"breit\"><table data-filtern=\"modelle\"><thead><tr><th data-spalte=\"name\">Name</th><th data-spalte=\"engine\" data-filter>Engine</th><th data-spalte=\"status\" data-filter>Status</th><th>Kann</th><th>GPUs</th>\
<th class=\"num\" data-spalte=\"kontext\" data-zahl>Kontext</th><th class=\"num\" data-spalte=\"speicher\" data-zahl>Speicher</th><th data-spalte=\"zustand\" data-filter>Zustand</th>{}</tr></thead><tbody>{body}</tbody></table></div>\
<th class=\"num\" data-spalte=\"kontext\" data-zahl>Kontext</th><th class=\"num\" data-spalte=\"speicher\" data-zahl>Speicher</th><th>Quantisierung</th><th>Größe</th><th data-spalte=\"zustand\" data-filter>Zustand</th>{}</tr></thead><tbody>{body}</tbody></table></div>\
<p class=\"klein\">Kann: Symbole auf gefüllter Kachel sind aus den Dateien des Modells erkannt (zum Beispiel eine Bild-Zusatzdatei), Symbole mit gestricheltem Umriss sind Fähigkeiten der Engine, für das einzelne Modell nicht geprüft. Chat, Streaming und Completions können alle Modelle einer Engine und stehen auf der Seite „Engines“.</p>",
if viewer.admin() { "<th></th>" } else { "" }
)
@ -384,11 +410,17 @@ pub(super) async fn models_page(
let Some(viewer) = viewer(&state, &headers) else {
return redirect("/ui/login");
};
let mut body = format!(
"{}<section class=\"card\" data-refresh=\"/ui/teil/modelle\" data-interval=\"3000\">{}</section>",
notice(query.as_deref()),
models_table(&state, &viewer)
);
let art = query
.as_deref()
.and_then(|q| form_field(q.as_bytes(), "art"))
.unwrap_or_default();
let nav = "<nav class=\"zeile\" aria-label=\"Modellarten\"><a href=\"/ui/modelle\">LLM</a><a href=\"/ui/modelle?art=sprache\">Sprache</a><a href=\"/ui/modelle?art=bild\">Bild</a><a href=\"/ui/modelle?art=musik\">Musik</a></nav>";
let content = match art.as_str() {
"sprache" => stimmen::page(&state, &viewer).await,
"bild" | "musik" => "<section class=\"card\"><h2>Workflows</h2><p class=\"leer\">Noch keine Workflows: ComfyUI ist noch nicht gebaut.</p></section>".to_string(),
_ => format!("<section class=\"card\" data-refresh=\"/ui/teil/modelle\" data-interval=\"3000\">{}</section><p class=\"klein\">Denkstufe: von der Engine abhängig, je Modell noch nicht erfasst.</p>", models_table(&state, &viewer)),
};
let mut body = format!("{}{nav}{content}", notice(query.as_deref()));
if viewer.admin() {
for m in model_rows(&state) {
body.push_str(&edit_dialog(&state, &viewer, &m));

View File

@ -49,6 +49,13 @@ impl Engine for FixedEngine {
capabilities: Capabilities::default(),
}
}
async fn voices(&self) -> Vec<nexus_adapter::Voice> {
vec![nexus_adapter::Voice {
id: "Ryan".into(),
name: "Ryan".into(),
saved: true,
}]
}
async fn discover(&self) -> Result<Vec<DiscoveredArtifact>, AdapterError> {
// Ein schon registriertes Modell (bonsai) und ein neues.
Ok(["bonsai", "neu-gefunden"]
@ -2576,6 +2583,37 @@ async fn playground_liest_vor_nur_mit_sprachmodell_und_sitzung() {
async move { req.send().await.unwrap() }
};
let gut = json!({"model": "sprecher", "input": "Hallo", "voice": "Ryan"});
assert_eq!(
sprechen(cookie.clone(), Some(csrf.clone()), gut.clone())
.await
.status(),
403
);
let (_, _, stimmen) = ui_get(&gw, "/ui/chat/stimmen?modell=sprecher", Some(&cookie)).await;
assert!(
!stimmen.contains("Ryan"),
"Ohne Freigabe nicht im Playground"
);
let probe = gw
.client
.post(format!("{}/ui/modelle/probe", gw.base))
.header("origin", &gw.base)
.header("cookie", &cookie)
.header("x-csrf-token", &csrf)
.header(CONTENT_TYPE, "application/json")
.body(json!({"model":"sprecher", "voice":"Ryan"}).to_string())
.send()
.await
.unwrap();
assert_eq!(probe.status(), 200, "Probehören braucht keine Freigabe");
assert_eq!(
probe.text().await.unwrap(),
"RIFF|sprecher|Guten Tag, ich bin eine Stimme von Nexus.|pcm"
);
gw.state
.store()
.set_voice_approved("Ryan", true, TEST_ADMIN, true)
.unwrap();
let resp = sprechen(cookie.clone(), Some(csrf.clone()), gut.clone()).await;
assert_eq!(resp.status(), 200);
assert_eq!(resp.headers()[CONTENT_TYPE], "audio/pcm");