feat: stream speech audio in supported formats
This commit is contained in:
@ -58,6 +58,7 @@ pub async fn speech(
|
|||||||
correlation,
|
correlation,
|
||||||
started,
|
started,
|
||||||
body,
|
body,
|
||||||
|
false,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
@ -82,6 +83,7 @@ pub(crate) async fn forward(
|
|||||||
correlation,
|
correlation,
|
||||||
started,
|
started,
|
||||||
body,
|
body,
|
||||||
|
false,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
@ -105,6 +107,7 @@ pub(crate) async fn forward_speech(
|
|||||||
correlation,
|
correlation,
|
||||||
started,
|
started,
|
||||||
body,
|
body,
|
||||||
|
true,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
@ -120,9 +123,37 @@ async fn forward_to(
|
|||||||
correlation: String,
|
correlation: String,
|
||||||
started: std::time::Instant,
|
started: std::time::Instant,
|
||||||
body: Bytes,
|
body: Bytes,
|
||||||
|
playground_pcm: bool,
|
||||||
) -> Result<Response, ApiError> {
|
) -> Result<Response, ApiError> {
|
||||||
let mut request: Value = serde_json::from_slice(&body)
|
let mut request: Value = serde_json::from_slice(&body)
|
||||||
.map_err(|e| ApiError::bad_request(format!("Der Body ist kein gültiges JSON: {e}")))?;
|
.map_err(|e| ApiError::bad_request(format!("Der Body ist kein gültiges JSON: {e}")))?;
|
||||||
|
// Das Studio unterstützt mehr Formate als die öffentliche Schnittstelle. Vor dem
|
||||||
|
// Start validieren und den Standard explizit senden. Der Playground fordert
|
||||||
|
// intern PCM an; das ist kein öffentlich unterstütztes Format. Wer eine
|
||||||
|
// Datei braucht, liest denselben Strom bis zum Ende.
|
||||||
|
let audio_type = if path == "/v1/audio/speech" {
|
||||||
|
let format = match request.get("response_format") {
|
||||||
|
None => "mp3",
|
||||||
|
Some(Value::String(format)) => format.as_str(),
|
||||||
|
Some(_) => "",
|
||||||
|
};
|
||||||
|
let content_type = match format {
|
||||||
|
"mp3" => "audio/mpeg",
|
||||||
|
"wav" => "audio/wav",
|
||||||
|
"opus" => "audio/ogg", // Das Studio liefert Opus im Ogg-Container.
|
||||||
|
"flac" => "audio/flac",
|
||||||
|
"pcm" if playground_pcm => "audio/pcm",
|
||||||
|
_ => {
|
||||||
|
return Err(ApiError::bad_request(
|
||||||
|
"Unbekanntes Audioformat. Unterstützt werden mp3, wav, opus und flac.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
request["response_format"] = Value::String(format.to_string());
|
||||||
|
Some(content_type)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
let model = request
|
let model = request
|
||||||
.get("model")
|
.get("model")
|
||||||
.and_then(Value::as_str)
|
.and_then(Value::as_str)
|
||||||
@ -164,6 +195,9 @@ async fn forward_to(
|
|||||||
request["model"] = Value::String(name.clone());
|
request["model"] = Value::String(name.clone());
|
||||||
Bytes::from(serde_json::to_vec(&request).map_err(|_| ApiError::internal())?)
|
Bytes::from(serde_json::to_vec(&request).map_err(|_| ApiError::internal())?)
|
||||||
}
|
}
|
||||||
|
None if audio_type.is_some() => {
|
||||||
|
Bytes::from(serde_json::to_vec(&request).map_err(|_| ApiError::internal())?)
|
||||||
|
}
|
||||||
None => body,
|
None => body,
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -238,10 +272,17 @@ async fn forward_to(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
let mut response = Response::builder().status(status);
|
let mut response = Response::builder().status(status);
|
||||||
for name in [CONTENT_TYPE, CACHE_CONTROL] {
|
if status.is_success() {
|
||||||
if let Some(value) = response_headers.get(&name) {
|
if let Some(content_type) = audio_type {
|
||||||
response = response.header(name, value);
|
response = response.header(CONTENT_TYPE, content_type);
|
||||||
|
} else if let Some(value) = response_headers.get(CONTENT_TYPE) {
|
||||||
|
response = response.header(CONTENT_TYPE, value);
|
||||||
}
|
}
|
||||||
|
} else if let Some(value) = response_headers.get(CONTENT_TYPE) {
|
||||||
|
response = response.header(CONTENT_TYPE, value);
|
||||||
|
}
|
||||||
|
if let Some(value) = response_headers.get(CACHE_CONTROL) {
|
||||||
|
response = response.header(CACHE_CONTROL, value);
|
||||||
}
|
}
|
||||||
if effort_ignored {
|
if effort_ignored {
|
||||||
response = response.header("x-nexus-reasoning-effort", "ignored");
|
response = response.header("x-nexus-reasoning-effort", "ignored");
|
||||||
@ -281,11 +322,17 @@ type ResponseStream = BoxStream<'static, Result<Bytes, reqwest::Error>>;
|
|||||||
/// Grund zurück; sonst der Strom samt erstem Stück. Kommt nach 60 s noch nichts (langsames Laden des
|
/// Grund zurück; sonst der Strom samt erstem Stück. Kommt nach 60 s noch nichts (langsames Laden des
|
||||||
/// Modells), wird die Antwort trotzdem weitergereicht: Das ist kein Fehler.
|
/// Modells), wird die Antwort trotzdem weitergereicht: Das ist kein Fehler.
|
||||||
async fn first_chunk(mut upstream: ResponseStream) -> Result<ResponseStream, &'static str> {
|
async fn first_chunk(mut upstream: ResponseStream) -> Result<ResponseStream, &'static str> {
|
||||||
match tokio::time::timeout(std::time::Duration::from_secs(60), upstream.next()).await {
|
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(60);
|
||||||
Ok(Some(Ok(chunk))) => Ok(stream::once(async { Ok(chunk) }).chain(upstream).boxed()),
|
loop {
|
||||||
Ok(Some(Err(_))) => Err("abgebrochen"),
|
match tokio::time::timeout_at(deadline, upstream.next()).await {
|
||||||
Ok(None) => Err("leer"),
|
Ok(Some(Ok(chunk))) if chunk.is_empty() => continue,
|
||||||
Err(_) => Ok(upstream),
|
Ok(Some(Ok(chunk))) => {
|
||||||
|
return Ok(stream::once(async { Ok(chunk) }).chain(upstream).boxed());
|
||||||
|
}
|
||||||
|
Ok(Some(Err(_))) => return Err("abgebrochen"),
|
||||||
|
Ok(None) => return Err("leer"),
|
||||||
|
Err(_) => return Ok(upstream),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -188,10 +188,30 @@ async fn fake_backend() -> u16 {
|
|||||||
.body(Body::empty())
|
.body(Body::empty())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
let format = req["response_format"].as_str().unwrap_or("FEHLT");
|
||||||
|
let content_type = match format {
|
||||||
|
"mp3" => "audio/mpeg",
|
||||||
|
"opus" => "audio/ogg",
|
||||||
|
"flac" => "audio/flac",
|
||||||
|
"pcm" => "audio/pcm",
|
||||||
|
_ => "audio/wav",
|
||||||
|
};
|
||||||
|
if req["input"] == "STROM" {
|
||||||
|
let chunks = ["ERSTES", "ZWEITES", "DRITTES"];
|
||||||
|
let audio = stream::unfold(0usize, move |index| async move {
|
||||||
|
let chunk = chunks.get(index)?;
|
||||||
|
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||||
|
Some((Ok::<_, Infallible>(Bytes::from(*chunk)), index + 1))
|
||||||
|
});
|
||||||
|
return Response::builder()
|
||||||
|
.header(CONTENT_TYPE, content_type)
|
||||||
|
.body(Body::from_stream(audio))
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
Response::builder()
|
Response::builder()
|
||||||
.header(CONTENT_TYPE, "audio/wav")
|
.header(CONTENT_TYPE, content_type)
|
||||||
.body(Body::from(format!(
|
.body(Body::from(format!(
|
||||||
"RIFF|{}|{}",
|
"RIFF|{}|{}|{format}",
|
||||||
req["model"].as_str().unwrap_or(""),
|
req["model"].as_str().unwrap_or(""),
|
||||||
req["input"].as_str().unwrap_or("")
|
req["input"].as_str().unwrap_or("")
|
||||||
)))
|
)))
|
||||||
@ -536,7 +556,9 @@ async fn chat_ohne_streaming_startet_die_instanz_und_reicht_die_antwort_durch()
|
|||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn sprachausgabe_reicht_audio_durch_und_verlangt_key_und_modell() {
|
async fn sprachausgabe_reicht_audio_durch_und_verlangt_key_und_modell() {
|
||||||
let gw = gateway(0, false).await;
|
let gw = gateway(0, false).await;
|
||||||
let body = json!({"model": "bonsai", "input": "Hallo", "voice": "Vivian"}).to_string();
|
let body =
|
||||||
|
json!({"model": "bonsai", "input": "Hallo", "voice": "Vivian", "response_format": "wav"})
|
||||||
|
.to_string();
|
||||||
let post = |key: Option<&str>, body: String| {
|
let post = |key: Option<&str>, body: String| {
|
||||||
let mut req = gw
|
let mut req = gw
|
||||||
.client
|
.client
|
||||||
@ -552,7 +574,7 @@ async fn sprachausgabe_reicht_audio_durch_und_verlangt_key_und_modell() {
|
|||||||
assert_eq!(resp.status(), 200);
|
assert_eq!(resp.status(), 200);
|
||||||
assert_eq!(resp.headers()[CONTENT_TYPE], "audio/wav");
|
assert_eq!(resp.headers()[CONTENT_TYPE], "audio/wav");
|
||||||
// Die Attrappe gibt zurück, was sie gesehen hat: Modellname und Text unverändert.
|
// Die Attrappe gibt zurück, was sie gesehen hat: Modellname und Text unverändert.
|
||||||
assert_eq!(resp.text().await.unwrap(), "RIFF|bonsai|Hallo");
|
assert_eq!(resp.text().await.unwrap(), "RIFF|bonsai|Hallo|wav");
|
||||||
assert_eq!(gw.engine.starts.load(Ordering::SeqCst), 1);
|
assert_eq!(gw.engine.starts.load(Ordering::SeqCst), 1);
|
||||||
|
|
||||||
assert_eq!(post(None, body.clone()).await.status(), 401);
|
assert_eq!(post(None, body.clone()).await.status(), 401);
|
||||||
@ -564,6 +586,91 @@ async fn sprachausgabe_reicht_audio_durch_und_verlangt_key_und_modell() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn sprachausgabe_formate_standard_und_unbekanntes_format() {
|
||||||
|
let gw = gateway(0, false).await;
|
||||||
|
for (format, expected_type) in [
|
||||||
|
(None, "audio/mpeg"),
|
||||||
|
(Some("mp3"), "audio/mpeg"),
|
||||||
|
(Some("wav"), "audio/wav"),
|
||||||
|
(Some("opus"), "audio/ogg"),
|
||||||
|
(Some("flac"), "audio/flac"),
|
||||||
|
] {
|
||||||
|
let mut body = json!({"model": "bonsai", "input": "Ton", "voice": "Vivian"});
|
||||||
|
if let Some(format) = format {
|
||||||
|
body["response_format"] = json!(format);
|
||||||
|
}
|
||||||
|
let resp = gw
|
||||||
|
.client
|
||||||
|
.post(format!("{}/v1/audio/speech", gw.base))
|
||||||
|
.bearer_auth(&gw.key)
|
||||||
|
.header(CONTENT_TYPE, "application/json")
|
||||||
|
.body(body.to_string())
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(resp.status(), 200, "{format:?}");
|
||||||
|
assert_eq!(resp.headers()[CONTENT_TYPE], expected_type, "{format:?}");
|
||||||
|
assert_eq!(
|
||||||
|
resp.text().await.unwrap(),
|
||||||
|
format!("RIFF|bonsai|Ton|{}", format.unwrap_or("mp3"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for format in [
|
||||||
|
json!("aac"),
|
||||||
|
json!("pcm"),
|
||||||
|
json!("unbekannt"),
|
||||||
|
json!(null),
|
||||||
|
json!(42),
|
||||||
|
] {
|
||||||
|
let resp = gw.client.post(format!("{}/v1/audio/speech", gw.base))
|
||||||
|
.bearer_auth(&gw.key)
|
||||||
|
.header(CONTENT_TYPE, "application/json")
|
||||||
|
.body(json!({"model": "bonsai", "input": "Ton", "voice": "Vivian", "response_format": format}).to_string())
|
||||||
|
.send().await.unwrap();
|
||||||
|
assert_eq!(resp.status(), 400);
|
||||||
|
let body: Value = serde_json::from_str(&resp.text().await.unwrap()).unwrap();
|
||||||
|
assert!(
|
||||||
|
body["error"]["message"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.contains("Audioformat")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn sprachausgabe_strom_kommt_stueckweise_und_ist_als_datei_lesbar() {
|
||||||
|
let gw = gateway(0, false).await;
|
||||||
|
let started = Instant::now();
|
||||||
|
let mut resp = gw
|
||||||
|
.client
|
||||||
|
.post(format!("{}/v1/audio/speech", gw.base))
|
||||||
|
.bearer_auth(&gw.key)
|
||||||
|
.header(CONTENT_TYPE, "application/json")
|
||||||
|
.body(json!({"model": "bonsai", "input": "STROM", "voice": "Vivian"}).to_string())
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(resp.status(), 200);
|
||||||
|
assert_eq!(resp.headers()[CONTENT_TYPE], "audio/mpeg");
|
||||||
|
let first = resp.chunk().await.unwrap().unwrap();
|
||||||
|
assert_eq!(first, "ERSTES");
|
||||||
|
assert!(
|
||||||
|
started.elapsed() < Duration::from_millis(500),
|
||||||
|
"Antwort wartet nicht auf das Ende der Erzeugung"
|
||||||
|
);
|
||||||
|
let mut file = first.to_vec();
|
||||||
|
while let Some(chunk) = resp.chunk().await.unwrap() {
|
||||||
|
file.extend_from_slice(&chunk);
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
started.elapsed() >= Duration::from_millis(400),
|
||||||
|
"Stücke wurden gepuffert"
|
||||||
|
);
|
||||||
|
assert_eq!(file, b"ERSTESZWEITESDRITTES");
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn sprachausgabe_ohne_ton_wird_zu_502_statt_leerem_200() {
|
async fn sprachausgabe_ohne_ton_wird_zu_502_statt_leerem_200() {
|
||||||
let gw = gateway(0, false).await;
|
let gw = gateway(0, false).await;
|
||||||
@ -2359,10 +2466,10 @@ async fn playground_liest_vor_nur_mit_sprachmodell_und_sitzung() {
|
|||||||
let gut = json!({"model": "sprecher", "input": "Hallo", "voice": "Ryan"});
|
let gut = json!({"model": "sprecher", "input": "Hallo", "voice": "Ryan"});
|
||||||
let resp = sprechen(cookie.clone(), Some(csrf.clone()), gut.clone()).await;
|
let resp = sprechen(cookie.clone(), Some(csrf.clone()), gut.clone()).await;
|
||||||
assert_eq!(resp.status(), 200);
|
assert_eq!(resp.status(), 200);
|
||||||
assert_eq!(resp.headers()[CONTENT_TYPE], "audio/wav");
|
assert_eq!(resp.headers()[CONTENT_TYPE], "audio/pcm");
|
||||||
// Die Attrappe gibt zurück, was sie gesehen hat (die Umschreibung des Modellnamens auf den des
|
// Die Attrappe gibt zurück, was sie gesehen hat (die Umschreibung des Modellnamens auf den des
|
||||||
// Studios macht `StudioEngine::endpoint`, getestet im Adapter, nicht die FixedEngine).
|
// Studios macht `StudioEngine::endpoint`, getestet im Adapter, nicht die FixedEngine).
|
||||||
assert_eq!(resp.text().await.unwrap(), "RIFF|sprecher|Hallo");
|
assert_eq!(resp.text().await.unwrap(), "RIFF|sprecher|Hallo|pcm");
|
||||||
// Ohne Token 403, ohne Sitzung 401, ein Chatmodell ist kein Sprachmodell.
|
// Ohne Token 403, ohne Sitzung 401, ein Chatmodell ist kein Sprachmodell.
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
sprechen(cookie.clone(), None, gut.clone()).await.status(),
|
sprechen(cookie.clone(), None, gut.clone()).await.status(),
|
||||||
|
|||||||
Reference in New Issue
Block a user