Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(voice): add support for custom voice provider configuration

Steven Enamakelb5c7492477cc
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index 6d0480b241..c65b829eea 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -164,7 +164,7 @@ tinyinference-embeddings = { path = "../../vendor/tinyagents/vendor/tinyinferenc
tinyinference-llm = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm" }
tinyinference-local = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-local" }
tinyinference-providers = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-providers" }
-tinyinference-voice = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-voice" }
+tinyinference-voice = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-voice", features = ["schemars"] }
# TinyTools — the tool vocabulary: the `Tool` trait, `ToolResult`, and the
# permission / scope / timeout classifications this host enforces around a call.
#
diff --git a/crates/openhuman-core/src/config/schema/voice_providers.rs b/crates/openhuman-core/src/config/schema/voice_providers.rs
index 0de7267ae3..b1df572346 100644
--- a/crates/openhuman-core/src/config/schema/voice_providers.rs
+++ b/crates/openhuman-core/src/config/schema/voice_providers.rs
@@ -44,31 +44,10 @@ impl VoiceCapability {
}
}
-/// API style for STT requests. Different providers use incompatible request
-/// shapes; the factory dispatches based on this discriminator.
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
-#[serde(rename_all = "lowercase")]
-pub enum SttApiStyle {
- /// OpenAI-compatible: multipart POST to `/audio/transcriptions`.
- #[default]
- OpenaiAudio,
- /// Deepgram: POST binary audio to `/listen?model=<model>`.
- Deepgram,
- /// ElevenLabs Scribe: multipart POST to `/speech-to-text` with `model_id`
- /// and an `xi-api-key` header.
- ElevenLabs,
-}
-
-/// API style for TTS requests.
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
-#[serde(rename_all = "lowercase")]
-pub enum TtsApiStyle {
- /// OpenAI-compatible: POST JSON `{ model, voice, input }` to `/audio/speech`.
- #[default]
- OpenaiAudio,
- /// ElevenLabs: POST JSON `{ text, model_id }` to `/text-to-speech/<voice_id>`.
- ElevenLabs,
-}
+// The API-style enums live with the HTTP clients that dispatch on them; the
+// TOML shape (`rename_all = "lowercase"`) and JSON schema are unchanged.
+pub use tinyinference_voice::external_stt::SttApiStyle;
+pub use tinyinference_voice::external_tts::TtsApiStyle;
/// Endpoint config for one voice (STT/TTS) provider.
///
diff --git a/crates/openhuman-core/src/inference/host_runtime/service/mod.rs b/crates/openhuman-core/src/inference/host_runtime/service/mod.rs
index 1734cfaba9..7bf5890975 100644
--- a/crates/openhuman-core/src/inference/host_runtime/service/mod.rs
+++ b/crates/openhuman-core/src/inference/host_runtime/service/mod.rs
@@ -1,7 +1,6 @@
//! OpenHuman-owned speech bindings around TinyInference's local runtime.
mod speech;
-pub(crate) mod transcription;
pub use speech::{transcribe, transcribe_with_prompt, tts};
pub use tinyinference_local::service::LocalAiService;
diff --git a/crates/openhuman-core/src/inference/host_runtime/service/speech.rs b/crates/openhuman-core/src/inference/host_runtime/service/speech.rs
index 3f13b546d6..e35bbdb6e3 100644
--- a/crates/openhuman-core/src/inference/host_runtime/service/speech.rs
+++ b/crates/openhuman-core/src/inference/host_runtime/service/speech.rs
@@ -13,21 +13,6 @@ use super::LocalAiService;
const LOG_PREFIX: &str = "[speech]";
-/// MIME hint sent to the backend for a given file extension. The backend
-/// forwards the blob to its STT provider, which sniffs the container; a wrong
-/// hint only costs a re-sniff, so an unknown extension falls back to WAV.
-fn mime_for_extension(ext: &str) -> &'static str {
- match ext {
- "wav" => "audio/wav",
- "mp3" => "audio/mpeg",
- "m4a" | "mp4" => "audio/mp4",
- "ogg" | "opus" => "audio/ogg",
- "webm" => "audio/webm",
- "flac" => "audio/flac",
- _ => "audio/wav",
- }
-}
-
pub async fn transcribe(
service: &LocalAiService,
config: &Config,
@@ -69,7 +54,7 @@ pub async fn transcribe_with_prompt(
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase();
- let mime = mime_for_extension(&ext);
+ let mime = tinyinference_voice::mime::mime_for_extension(&ext);
let file_name = path
.file_name()
.and_then(|n| n.to_str())
diff --git a/crates/openhuman-core/src/inference/host_runtime/service/transcription.rs b/crates/openhuman-core/src/inference/host_runtime/service/transcription.rs
deleted file mode 100644
index 1a4c77733f..0000000000
--- a/crates/openhuman-core/src/inference/host_runtime/service/transcription.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-//! Provider-neutral transcription result type.
-//!
-//! Inert and dependency-free: it carries whatever confidence metadata an STT
-//! engine can report, without naming one. It outlived the bundled whisper.cpp
-//! engine that first introduced it — that engine is gone (STT is now
-//! cloud/engine-configurable via `voice_server.stt_engine`), but the shape is
-//! still the contract between an STT backend and the channel host adapter
-//! (`channels::host::adapters`), so it stays here rather than being folded
-//! into any one provider.
-
-/// Result of a transcription call, including confidence metadata.
-#[derive(Debug, Clone)]
-pub struct TranscriptionResult {
- /// The transcribed text (may be empty if all segments were rejected).
- pub text: String,
- /// Average log-probability across accepted segments (higher = more confident).
- /// `None` when the engine reports no per-segment confidence.
- pub avg_logprob: Option<f32>,
- /// Number of segments accepted / total segments produced by the engine.
- pub segments_accepted: usize,
- pub segments_total: usize,
-}
diff --git a/crates/openhuman-core/src/voice/factory/helpers.rs b/crates/openhuman-core/src/voice/factory/helpers.rs
index 4e70a3e96d..32cc0f9e50 100644
--- a/crates/openhuman-core/src/voice/factory/helpers.rs
+++ b/crates/openhuman-core/src/voice/factory/helpers.rs
@@ -198,15 +198,3 @@ pub(super) fn base64_decode(input: &str) -> Result<Vec<u8>, String> {
.decode(input)
.map_err(|e| format!("[voice-factory] base64 decode error: {e}"))
}
-
-pub(super) fn extension_for_mime(mime: &str) -> &str {
- match mime {
- "audio/wav" | "audio/x-wav" => "wav",
- "audio/mpeg" | "audio/mp3" => "mp3",
- "audio/ogg" => "ogg",
- "audio/webm" => "webm",
- "audio/flac" => "flac",
- "audio/mp4" | "audio/m4a" => "m4a",
- _ => "wav",
- }
-}
diff --git a/crates/openhuman-core/src/voice/factory/stt_providers.rs b/crates/openhuman-core/src/voice/factory/stt_providers.rs
index fc9bc35444..645963924f 100644
--- a/crates/openhuman-core/src/voice/factory/stt_providers.rs
+++ b/crates/openhuman-core/src/voice/factory/stt_providers.rs
@@ -7,16 +7,16 @@
use async_trait::async_trait;
use log::debug;
-use serde::Deserialize;
use super::super::cloud_transcribe::{
transcribe_cloud, CloudTranscribeOptions, CloudTranscribeResult,
};
-use super::helpers::{base64_decode, extension_for_mime};
+use super::helpers::base64_decode;
use super::traits::{SttProvider, SttResult};
use crate::config::schema::voice_providers::SttApiStyle;
use crate::config::Config;
use crate::core::Outcome;
+use tinyinference_voice::external_stt::ExternalSttClient;
const LOG_PREFIX: &str = "[voice-factory]";
@@ -79,13 +79,12 @@ impl SttProvider for CloudSttProvider {
// ---------------------------------------------------------------------------
/// Third-party STT provider dispatched via the voice provider registry.
-/// Supports OpenAI-compatible, Deepgram, and ElevenLabs API styles.
+/// Supports OpenAI-compatible, Deepgram, and ElevenLabs API styles; the HTTP
+/// clients live in `tinyinference_voice::external_stt`.
pub struct ExternalSttProvider {
slug: String,
- model: String,
- endpoint: String,
- api_key: String,
api_style: SttApiStyle,
+ client: ExternalSttClient,
}
impl ExternalSttProvider {
@@ -98,10 +97,14 @@ impl ExternalSttProvider {
) -> Self {
Self {
slug: slug.into(),
- model: model.into(),
- endpoint: endpoint.into(),
- api_key: api_key.into(),
api_style,
+ client: ExternalSttClient::new(
+ reqwest::Client::new(),
+ model,
+ endpoint,
+ api_key,
+ api_style,
+ ),
}
}
}
@@ -123,32 +126,21 @@ impl SttProvider for ExternalSttProvider {
debug!(
"{LOG_PREFIX} external STT dispatch slug={} model={} style={:?} bytes_b64={}",
self.slug,
- self.model,
+ self.client.model(),
self.api_style,
audio_base64.len()
);
let audio_bytes = base64_decode(audio_base64)?;
let mime = mime_type.unwrap_or("audio/wav");
-
- let result = match self.api_style {
- SttApiStyle::OpenaiAudio => {
- self.transcribe_openai_compat(&audio_bytes, mime, file_name, language)
- .await?
- }
- SttApiStyle::Deepgram => {
- self.transcribe_deepgram(&audio_bytes, mime, language)
- .await?
- }
- SttApiStyle::ElevenLabs => {
- self.transcribe_elevenlabs(&audio_bytes, mime, file_name, language)
- .await?
- }
- };
+ let text = self
+ .client
+ .transcribe(&audio_bytes, mime, file_name, language)
+ .await?;
Ok(Outcome::single_log(
SttResult {
- text: result,
+ text,
provider: self.slug.clone(),
},
format!("voice-factory: external STT completed via {}", self.slug),
@@ -157,176 +149,7 @@ impl SttProvider for ExternalSttProvider {
#[cfg(test)]
fn configured_model(&self) -> Option<&str> {
- Some(&self.model)
- }
-}
-
-impl ExternalSttProvider {
- async fn transcribe_openai_compat(
- &self,
- audio_bytes: &[u8],
- mime: &str,
- file_name: Option<&str>,
- language: Option<&str>,
- ) -> Result<String, String> {
- let url = format!(
- "{}/audio/transcriptions",
- self.endpoint.trim_end_matches('/')
- );
- let ext = extension_for_mime(mime);
- let default_fname = format!("audio.{ext}");
- let fname = file_name.unwrap_or(&default_fname);
-
- let file_part = reqwest::multipart::Part::bytes(audio_bytes.to_vec())
- .file_name(fname.to_string())
- .mime_str(mime)
- .map_err(|e| format!("[voice-stt] mime error: {e}"))?;
-
- let mut form = reqwest::multipart::Form::new()
- .text("model", self.model.clone())
- .part("file", file_part);
-
- if let Some(lang) = language {
- form = form.text("language", lang.to_string());
- }
-
- let client = reqwest::Client::new();
- let resp = client
- .post(&url)
- .header("Authorization", format!("Bearer {}", self.api_key))
- .multipart(form)
- .send()
- .await
- .map_err(|e| format!("[voice-stt] external STT request failed: {e}"))?;
-
- if !resp.status().is_success() {
- let status = resp.status();
- let body = resp.text().await.unwrap_or_default();
- return Err(format!("[voice-stt] external STT error {status}: {body}"));
- }
-
- #[derive(Deserialize)]
- struct TranscriptionResp {
- text: String,
- }
- let parsed: TranscriptionResp = resp
- .json()
- .await
- .map_err(|e| format!("[voice-stt] failed to parse response: {e}"))?;
- Ok(parsed.text)
- }
-
- async fn transcribe_deepgram(
- &self,
- audio_bytes: &[u8],
- mime: &str,
- language: Option<&str>,
- ) -> Result<String, String> {
- let mut url = format!(
- "{}/listen?model={}",
- self.endpoint.trim_end_matches('/'),
- self.model
- );
- if let Some(lang) = language {
- url.push_str(&format!("&language={lang}"));
- }
-
- let client = reqwest::Client::new();
- let resp = client
- .post(&url)
- .header("Authorization", format!("Token {}", self.api_key))
- .header("Content-Type", mime)
- .body(audio_bytes.to_vec())
- .send()
- .await
- .map_err(|e| format!("[voice-stt] deepgram request failed: {e}"))?;
-
- if !resp.status().is_success() {
- let status = resp.status();
- let body = resp.text().await.unwrap_or_default();
- return Err(format!("[voice-stt] deepgram error {status}: {body}"));
- }
-
- #[derive(Deserialize)]
- struct DeepgramChannel {
- alternatives: Vec<DeepgramAlt>,
- }
- #[derive(Deserialize)]
- struct DeepgramAlt {
- transcript: String,
- }
- #[derive(Deserialize)]
- struct DeepgramResult {
- channels: Vec<DeepgramChannel>,
- }
- #[derive(Deserialize)]
- struct DeepgramResp {
- results: DeepgramResult,
- }
-
- let parsed: DeepgramResp = resp
- .json()
- .await
- .map_err(|e| format!("[voice-stt] deepgram parse error: {e}"))?;
-
- let text = parsed
- .results
- .channels
- .first()
- .and_then(|ch| ch.alternatives.first())
- .map(|a| a.transcript.clone())
- .unwrap_or_default();
- Ok(text)
- }
-
- async fn transcribe_elevenlabs(
- &self,
- audio_bytes: &[u8],
- mime: &str,
- file_name: Option<&str>,
- language: Option<&str>,
- ) -> Result<String, String> {
- let url = format!("{}/speech-to-text", self.endpoint.trim_end_matches('/'));
- let ext = extension_for_mime(mime);
- let default_fname = format!("audio.{ext}");
- let fname = file_name.unwrap_or(&default_fname);
-
- let file_part = reqwest::multipart::Part::bytes(audio_bytes.to_vec())
- .file_name(fname.to_string())
- .mime_str(mime)
- .map_err(|e| format!("[voice-stt] mime error: {e}"))?;
- let mut form = reqwest::multipart::Form::new()
- .text("model_id", self.model.clone())
- .part("file", file_part);
-
- if let Some(lang) = language {
- form = form.text("language_code", lang.to_string());
- }
-
- let client = reqwest::Client::new();
- let resp = client
- .post(&url)
- .header("xi-api-key", &self.api_key)
- .multipart(form)
- .send()
- .await
- .map_err(|e| format!("[voice-stt] elevenlabs request failed: {e}"))?;
-
- if !resp.status().is_success() {
- let status = resp.status();
- let body = resp.text().await.unwrap_or_default();
- return Err(format!("[voice-stt] elevenlabs error {status}: {body}"));
- }
-
- #[derive(Deserialize)]
- struct TranscriptionResp {
- text: String,
- }
- let parsed: TranscriptionResp = resp
- .json()
- .await
- .map_err(|e| format!("[voice-stt] elevenlabs parse error: {e}"))?;
- Ok(parsed.text)
+ Some(self.client.model())
}
}
diff --git a/crates/openhuman-core/src/voice/factory/tts_providers.rs b/crates/openhuman-core/src/voice/factory/tts_providers.rs
index dc78ed01ae..7da204262c 100644
--- a/crates/openhuman-core/src/voice/factory/tts_providers.rs
+++ b/crates/openhuman-core/src/voice/factory/tts_providers.rs
@@ -9,6 +9,7 @@ use super::traits::TtsProvider;
use crate::config::schema::voice_providers::TtsApiStyle;
use crate::config::Config;
use crate::core::Outcome;
+use tinyinference_voice::external_tts::ExternalTtsClient;
const LOG_PREFIX: &str = "[voice-factory]";
@@ -118,13 +119,13 @@ impl TtsProvider for PiperTtsProvider {
// ---------------------------------------------------------------------------
/// Third-party TTS provider dispatched via the voice provider registry.
-/// Supports OpenAI-compatible and ElevenLabs API styles.
+/// Supports OpenAI-compatible and ElevenLabs API styles; the HTTP clients
+/// live in `tinyinference_voice::external_tts`.
pub struct ExternalTtsProvider {
slug: String,
default_voice: String,
- endpoint: String,
- api_key: String,
api_style: TtsApiStyle,
+ client: ExternalTtsClient,
}
impl ExternalTtsProvider {
@@ -138,9 +139,8 @@ impl ExternalTtsProvider {
Self {
slug: slug.into(),
default_voice: default_voice.into(),
- endpoint: endpoint.into(),
- api_key: api_key.into(),
api_style,
+ client: ExternalTtsClient::new(reqwest::Client::new(), endpoint, api_key, api_style),
}
}
}
@@ -169,10 +169,7 @@ impl TtsProvider for ExternalTtsProvider {
text.len()
);
- let (audio_bytes, audio_mime) = match self.api_style {
- TtsApiStyle::OpenaiAudio => self.synthesize_openai_compat(text, resolved_voice).await?,
- TtsApiStyle::ElevenLabs => self.synthesize_elevenlabs(text, resolved_voice).await?,
- };
+ let (audio_bytes, audio_mime) = self.client.synthesize(text, resolved_voice).await?;
use base64::Engine;
let audio_base64 = base64::engine::general_purpose::STANDARD.encode(&audio_bytes);
@@ -193,96 +190,3 @@ impl TtsProvider for ExternalTtsProvider {
Some(&self.default_voice)
}
}
-
-impl ExternalTtsProvider {
- async fn synthesize_openai_compat(
- &self,
- text: &str,
- voice: &str,
- ) -> Result<(Vec<u8>, String), String> {
- let url = format!("{}/audio/speech", self.endpoint.trim_end_matches('/'));
-
- let body = serde_json::json!({
- "model": "tts-1",
- "voice": voice,
- "input": text,
- });
-
- let client = reqwest::Client::new();
- let resp = client
- .post(&url)
- .header("Authorization", format!("Bearer {}", self.api_key))
- .header("Content-Type", "application/json")
- .body(body.to_string())
- .send()
- .await
- .map_err(|e| format!("[voice-tts] external TTS request failed: {e}"))?;
-
- if !resp.status().is_success() {
- let status = resp.status();
- let body = resp.text().await.unwrap_or_default();
- return Err(format!("[voice-tts] external TTS error {status}: {body}"));
- }
-
- let content_type = resp
- .headers()
- .get("content-type")
- .and_then(|v| v.to_str().ok())
- .unwrap_or("audio/mpeg")
- .to_string();
-
- let bytes = resp
- .bytes()
- .await
- .map_err(|e| format!("[voice-tts] failed to read audio: {e}"))?;
-
- Ok((bytes.to_vec(), content_type))
- }
-
- async fn synthesize_elevenlabs(
- &self,
- text: &str,
- voice_id: &str,
- ) -> Result<(Vec<u8>, String), String> {
- let url = format!(
- "{}/text-to-speech/{}",
- self.endpoint.trim_end_matches('/'),
- voice_id
- );
-
- let body = serde_json::json!({
- "text": text,
- "model_id": "eleven_multilingual_v2",
- });
-
- let client = reqwest::Client::new();
- let resp = client
- .post(&url)
- .header("xi-api-key", &self.api_key)
- .header("Content-Type", "application/json")
- .body(body.to_string())
- .send()
- .await
- .map_err(|e| format!("[voice-tts] elevenlabs request failed: {e}"))?;
-
- if !resp.status().is_success() {
- let status = resp.status();
- let body = resp.text().await.unwrap_or_default();
- return Err(format!("[voice-tts] elevenlabs error {status}: {body}"));
- }
-
- let content_type = resp
- .headers()
- .get("content-type")
- .and_then(|v| v.to_str().ok())
- .unwrap_or("audio/mpeg")
- .to_string();
-
- let bytes = resp
- .bytes()
- .await
- .map_err(|e| format!("[voice-tts] failed to read elevenlabs audio: {e}"))?;
-
- Ok((bytes.to_vec(), content_type))
- }
-}
diff --git a/crates/openhuman-core/src/voice/reply_speech.rs b/crates/openhuman-core/src/voice/reply_speech.rs
index 9294d8af28..0e879ff3e7 100644
--- a/crates/openhuman-core/src/voice/reply_speech.rs
+++ b/crates/openhuman-core/src/voice/reply_speech.rs
@@ -17,7 +17,6 @@
use log::{debug, warn};
use reqwest::Method;
-use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::backend::BackendClient;
@@ -71,35 +70,12 @@ pub mod test_seam {
}
}
-/// One frame on the viseme timeline. `viseme` is an Oculus / Microsoft
-/// 15-set code (`sil, PP, FF, TH, DD, kk, CH, SS, nn, RR, aa, E, I, O, U`).
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct VisemeFrame {
- pub viseme: String,
- pub start_ms: u64,
- pub end_ms: u64,
-}
-
-/// Char-level timing returned by some backends (e.g. ElevenLabs alignment).
-/// Not directly rendered, but kept so the UI can derive a fallback timeline
-/// when the backend does not ship visemes.
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct AlignmentFrame {
- pub char: String,
- pub start_ms: u64,
- pub end_ms: u64,
-}
-
-/// Normalized response handed to the UI — matches the existing TS shape so
-/// the frontend swap is a one-line change.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ReplySpeechResult {
- pub audio_base64: String,
- pub audio_mime: String,
- pub visemes: Vec<VisemeFrame>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub alignment: Option<Vec<AlignmentFrame>>,
-}
+// The response types and the tolerant-shape parsers live in
+// `tinyinference_voice::reply`; the UI contract is unchanged.
+pub use tinyinference_voice::reply::{
+ normalize_response, AlignmentFrame, ReplySpeech as ReplySpeechResult,
+};
+pub use tinyinference_voice::VisemeFrame;
/// Caller-tunable knobs.
#[derive(Debug, Default, Clone)]
@@ -234,140 +210,6 @@ pub async fn synthesize_reply(
))
}
-/// Translate the backend's tolerant response shape into the UI contract.
-/// Accepts `visemes` / `cues` / `viseme_cues`, and per-frame
-/// `start_ms`+`end_ms` or `time_ms`+`duration_ms`.
-fn normalize_response(raw: &Value) -> ReplySpeechResult {
- let audio_base64 = raw
- .get("audio_base64")
- .or_else(|| raw.get("audio"))
- .and_then(Value::as_str)
- .unwrap_or("")
- .to_string();
- let audio_mime = raw
- .get("audio_mime")
- .or_else(|| raw.get("mime"))
- .and_then(Value::as_str)
- .unwrap_or("audio/mpeg")
- .to_string();
-
- let cues = raw
- .get("visemes")
- .or_else(|| raw.get("cues"))
- .or_else(|| raw.get("viseme_cues"));
- let visemes = cues
- .and_then(Value::as_array)
- .map(|arr| arr.iter().filter_map(parse_cue).collect::<Vec<_>>())
- .unwrap_or_default();
-
- let alignment = raw
- .get("alignment")
- .or_else(|| raw.get("characters"))
- .and_then(Value::as_array)
- .map(|arr| arr.iter().filter_map(parse_alignment).collect::<Vec<_>>());
-
- ReplySpeechResult {
- audio_base64,
- audio_mime,
- visemes,
- alignment,
- }
-}
-
-fn parse_cue(v: &Value) -> Option<VisemeFrame> {
- let viseme = v
- .get("viseme")
- .or_else(|| v.get("v"))
- .or_else(|| v.get("code"))
- .and_then(Value::as_str)?
- .to_string();
- if viseme.is_empty() {
- return None;
- }
- // Accept millisecond keys, or seconds keys (`startSeconds`/`endSeconds`, the
- // shape the cloud backend actually ships) converted to ms. Without the
- // seconds keys every frame collapsed to start=0/end=80 — the mascot mouth
- // then froze on the first viseme because the whole track had no real timing.
- let start = read_ms(
- v,
- &["start_ms", "time_ms", "t"],
- &["startSeconds", "start_seconds", "startSec"],
- )
- .unwrap_or(0);
- let end = read_ms(v, &["end_ms"], &["endSeconds", "end_seconds", "endSec"])
- .or_else(|| {
- let t = read_ms(
- v,
- &["time_ms", "t"],
- &["startSeconds", "start_seconds", "startSec"],
- )?;
- let d = read_ms(
- v,
- &["duration_ms", "d"],
- &["durationSeconds", "duration_seconds", "durationSec"],
- )?;
- Some(t + d)
- })
- .unwrap_or(start + 80);
- if end <= start {
- return None;
- }
- Some(VisemeFrame {
- viseme,
- start_ms: start,
- end_ms: end,
- })
-}
-
-fn parse_alignment(v: &Value) -> Option<AlignmentFrame> {
- let ch = v.get("char").and_then(Value::as_str)?.to_string();
- let start = read_ms(v, &["start_ms"], &["startSeconds", "start_seconds"])?;
- let end = read_ms(v, &["end_ms"], &["endSeconds", "end_seconds"])?;
- if end <= start {
- return None;
- }
- Some(AlignmentFrame {
- char: ch,
- start_ms: start,
- end_ms: end,
- })
-}
-
-fn read_u64(v: &Value, keys: &[&str]) -> Option<u64> {
- for k in keys {
- if let Some(n) = v.get(*k).and_then(Value::as_u64) {
- return Some(n);
- }
- if let Some(f) = v.get(*k).and_then(Value::as_f64) {
- if f.is_finite() && f >= 0.0 {
- return Some(f as u64);
- }
- }
- }
- None
-}
-
-/// Read a time value in milliseconds. Tries `ms_keys` first (integer or float
-/// ms), then `sec_keys` interpreted as seconds and converted to ms. This lets
-/// the parser tolerate both the `*_ms` contract and the backend's
-/// `*Seconds` shape without the caller caring which arrived.
-fn read_ms(v: &Value, ms_keys: &[&str], sec_keys: &[&str]) -> Option<u64> {
- if let Some(ms) = read_u64(v, ms_keys) {
- return Some(ms);
- }
- for k in sec_keys {
- if let Some(f) = v.get(*k).and_then(Value::as_f64) {
- if f.is_finite() && f >= 0.0 {
- return Some((f * 1000.0).round() as u64);
- }
- }
- if let Some(n) = v.get(*k).and_then(Value::as_u64) {
- return Some(n.saturating_mul(1000));
- }
- }
- None
-}
-
#[cfg(test)]
#[path = "reply_speech_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/voice/reply_speech_tests.rs b/crates/openhuman-core/src/voice/reply_speech_tests.rs
index aa4d696d86..2c7fee8d01 100644
--- a/crates/openhuman-core/src/voice/reply_speech_tests.rs
+++ b/crates/openhuman-core/src/voice/reply_speech_tests.rs
@@ -1,138 +1,6 @@
use super::*;
use serde_json::json;
-#[test]
-fn normalize_canonical_shape() {
- let raw = json!({
- "audio_base64": "AAA=",
- "audio_mime": "audio/mpeg",
- "visemes": [
- { "viseme": "sil", "start_ms": 0, "end_ms": 100 },
- { "viseme": "aa", "start_ms": 100, "end_ms": 250 },
- ],
- });
- let r = normalize_response(&raw);
- assert_eq!(r.audio_base64, "AAA=");
- assert_eq!(r.audio_mime, "audio/mpeg");
- assert_eq!(r.visemes.len(), 2);
- assert_eq!(r.visemes[1].viseme, "aa");
- assert_eq!(r.visemes[1].end_ms, 250);
-}
-
-#[test]
-fn normalize_accepts_cues_and_short_keys() {
- let raw = json!({
- "audio": "BBB=",
- "mime": "audio/wav",
- "cues": [{ "v": "PP", "t": 0, "d": 80 }],
- });
- let r = normalize_response(&raw);
- assert_eq!(r.audio_base64, "BBB=");
- assert_eq!(r.audio_mime, "audio/wav");
- assert_eq!(
- r.visemes,
- vec![VisemeFrame {
- viseme: "PP".into(),
- start_ms: 0,
- end_ms: 80
- }]
- );
-}
-
-#[test]
-fn normalize_accepts_seconds_keys() {
- // The cloud backend ships per-frame timing as seconds (`startSeconds`/
- // `endSeconds`); the parser must convert to ms rather than dropping it
- // (which collapsed every frame to start=0/end=80 and froze the mouth).
- let raw = json!({
- "audio_base64": "AAA=",
- "visemes": [
- { "viseme": "sil", "startSeconds": 0.0, "endSeconds": 0.12 },
- { "viseme": "aa", "startSeconds": 0.12, "endSeconds": 0.45 },
- // A gap before the next cue (0.45 → 0.90) is a real pause: the
- // mouth rests there. Preserved because we keep the true ends.
- { "viseme": "PP", "startSeconds": 0.9, "endSeconds": 1.05 },
- ],
- "alignment": [
- { "char": "h", "startSeconds": 0.0, "endSeconds": 0.05 },
- ],
- });
- let r = normalize_response(&raw);
- assert_eq!(r.visemes.len(), 3);
- assert_eq!(
- r.visemes[0],
- VisemeFrame {
- viseme: "sil".into(),
- start_ms: 0,
- end_ms: 120
- }
- );
- assert_eq!(
- r.visemes[1],
- VisemeFrame {
- viseme: "aa".into(),
- start_ms: 120,
- end_ms: 450
- }
- );
- assert_eq!(
- r.visemes[2],
- VisemeFrame {
- viseme: "PP".into(),
- start_ms: 900,
- end_ms: 1050
- }
- );
- let alignment = r.alignment.expect("alignment present");
- assert_eq!(alignment.len(), 1);
- assert_eq!(alignment[0].start_ms, 0);
- assert_eq!(alignment[0].end_ms, 50);
-}
-
-#[test]
-fn normalize_accepts_short_seconds_duration_aliases() {
- let raw = json!({
- "audio_base64": "AAA=",
- "visemes": [
- { "viseme": "aa", "startSec": 1.2, "durationSec": 0.15 },
- ],
- });
- let r = normalize_response(&raw);
- assert_eq!(
- r.visemes,
- vec![VisemeFrame {
- viseme: "aa".into(),
- start_ms: 1200,
- end_ms: 1350
- }]
- );
-}
-
-#[test]
-fn normalize_drops_malformed_cues() {
- let raw = json!({
- "audio_base64": "CCC=",
- "visemes": [
- { "viseme": "aa", "start_ms": 0, "end_ms": 100 },
- { "viseme": "", "start_ms": 100, "end_ms": 200 },
- { "viseme": "PP", "start_ms": 200, "end_ms": 200 },
- ],
- });
- let r = normalize_response(&raw);
- assert_eq!(r.visemes.len(), 1);
- assert_eq!(r.visemes[0].viseme, "aa");
-}
-
-#[test]
-fn normalize_passes_through_alignment() {
- let raw = json!({
- "audio_base64": "DDD=",
- "alignment": [{ "char": "h", "start_ms": 0, "end_ms": 50 }],
- });
- let r = normalize_response(&raw);
- assert_eq!(r.alignment.as_deref().unwrap()[0].char, "h");
-}
-
#[test]
fn tts_unauthorized_flattens_to_session_expiry_not_hard_error() {
// TAURI-RUST-8X1: a lapsed-session 401 on the TTS endpoint