Skip to main content

kaeso_kpp/
audio.rs

1use serde::{Deserialize, Serialize};
2
3use crate::block::Source;
4use crate::error::KppError;
5use crate::extras::Extras;
6use crate::request::{AudioFormat, StreamMode};
7use crate::response::Usage;
8
9/// What a request for generated audio asks for.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[serde(rename_all = "snake_case")]
12#[non_exhaustive]
13pub enum SpeechOperation {
14    /// Speech from text, in one voice.
15    #[default]
16    Speech,
17    /// A dialogue: lines of text, each in its own voice.
18    Dialogue,
19    /// A sound effect from a description.
20    SoundEffect,
21    /// Music from a description.
22    Music,
23    /// Speech from given audio, in another voice.
24    VoiceChange,
25}
26
27impl SpeechOperation {
28    /// The operation's name in logs and messages.
29    pub const fn as_str(self) -> &'static str {
30        match self {
31            SpeechOperation::Speech => "speech",
32            SpeechOperation::Dialogue => "dialogue",
33            SpeechOperation::SoundEffect => "sound_effect",
34            SpeechOperation::Music => "music",
35            SpeechOperation::VoiceChange => "voice_change",
36        }
37    }
38}
39
40/// The voice to speak in: one of the provider's named voices, or a voice by its id.
41#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43#[non_exhaustive]
44pub enum Voice {
45    /// A voice the provider names, such as OpenAI's `alloy` or Gemini's `Kore`.
46    Named(String),
47    /// A voice by its id at the provider, such as a custom voice or an ElevenLabs voice id.
48    Id(String),
49}
50
51impl Voice {
52    /// The name or id as written.
53    pub fn as_str(&self) -> &str {
54        match self {
55            Voice::Named(s) | Voice::Id(s) => s,
56        }
57    }
58}
59
60/// One line of a dialogue.
61#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
62#[non_exhaustive]
63pub struct DialogueLine {
64    pub text: String,
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub voice: Option<Voice>,
67    #[serde(default, skip_serializing_if = "Extras::is_empty")]
68    pub extras: Extras,
69}
70
71impl DialogueLine {
72    pub fn new(text: impl Into<String>, voice: Option<Voice>) -> Self {
73        DialogueLine {
74            text: text.into(),
75            voice,
76            extras: Extras::default(),
77        }
78    }
79}
80
81/// Audio a request sends: inline bytes, a URL or a provider file id.
82#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
83#[non_exhaustive]
84pub struct AudioInput {
85    pub source: Source,
86    /// The file name an upload carried.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub filename: Option<String>,
89    #[serde(default, skip_serializing_if = "Extras::is_empty")]
90    pub extras: Extras,
91}
92
93impl AudioInput {
94    pub fn new(source: Source) -> Self {
95        AudioInput {
96            source,
97            filename: None,
98            extras: Extras::default(),
99        }
100    }
101
102    #[must_use]
103    pub fn with_filename(mut self, filename: impl Into<String>) -> Self {
104        self.filename = Some(filename.into());
105        self
106    }
107
108    /// The size of inline bytes; `None` for a link or a file id.
109    pub fn byte_len(&self) -> Option<u64> {
110        match &self.source {
111            Source::Base64(b) => Some(b.data.len() as u64),
112            _ => None,
113        }
114    }
115}
116
117/// A request for generated audio: speech, a dialogue, a sound effect, music, or speech in
118/// another voice.
119#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
120#[non_exhaustive]
121pub struct SpeechRequest {
122    pub model: String,
123    #[serde(default)]
124    pub operation: SpeechOperation,
125    /// The text to speak, or the description of a sound effect or of music.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub input: Option<String>,
128    /// The lines of a dialogue.
129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
130    pub dialogue: Vec<DialogueLine>,
131    /// The audio to speak again in another voice.
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub audio: Option<AudioInput>,
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub voice: Option<Voice>,
136    /// How to speak: tone, pace, accent, as free text.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub instructions: Option<String>,
139    /// The container and codec of the audio.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub format: Option<AudioFormat>,
142    /// The sample rate in hertz.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub sample_rate: Option<u32>,
145    /// The bit rate in kilobits per second, for compressed formats.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub bitrate: Option<u32>,
148    /// The speaking rate, where 1 is the voice's usual pace.
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub speed: Option<f64>,
151    /// The language of the text, as an ISO 639 code.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub language: Option<String>,
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub seed: Option<i64>,
156    /// The length of a sound effect or of music, in seconds.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub duration: Option<f64>,
159    /// Whether the reply also gives the time at which each character is spoken.
160    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
161    pub timestamps: bool,
162    /// `On` asks for audio events; `Off` for the audio itself, which a provider may still send
163    /// as it is made.
164    #[serde(default, skip_serializing_if = "StreamMode::is_off")]
165    pub stream: StreamMode,
166    #[serde(default, skip_serializing_if = "Extras::is_empty")]
167    pub extras: Extras,
168}
169
170impl SpeechRequest {
171    pub fn new(model: impl Into<String>, operation: SpeechOperation) -> Self {
172        SpeechRequest {
173            model: model.into(),
174            operation,
175            ..SpeechRequest::default()
176        }
177    }
178
179    #[must_use]
180    pub fn with_input(mut self, input: impl Into<String>) -> Self {
181        self.input = Some(input.into());
182        self
183    }
184
185    #[must_use]
186    pub fn with_voice(mut self, voice: Voice) -> Self {
187        self.voice = Some(voice);
188        self
189    }
190
191    /// The characters of text the request asks to speak, which providers bill by.
192    pub fn characters(&self) -> u64 {
193        let input = self.input.as_deref().map_or(0, |s| s.chars().count());
194        let lines: usize = self.dialogue.iter().map(|l| l.text.chars().count()).sum();
195        (input + lines) as u64
196    }
197
198    /// Checks what every request for audio needs, whatever its format.
199    pub fn validate(&self) -> Result<(), KppError> {
200        let invalid = |message: &str, param: &str| {
201            Err(KppError::invalid_request(message.to_owned()).with_param(param.to_owned()))
202        };
203        if self.model.is_empty() {
204            return invalid("`model` must not be empty.", "model");
205        }
206        let input = self.input.as_deref().is_some_and(|s| !s.is_empty());
207        match self.operation {
208            SpeechOperation::Speech | SpeechOperation::SoundEffect if !input => {
209                return invalid("`input` must not be empty.", "input");
210            }
211            SpeechOperation::Dialogue if self.dialogue.is_empty() => {
212                return invalid("Send at least one line of dialogue.", "inputs");
213            }
214            SpeechOperation::VoiceChange if self.audio.is_none() => {
215                return invalid("Send the audio to speak in another voice.", "audio");
216            }
217            _ => {}
218        }
219        if self.speed.is_some_and(|s| !(s.is_finite() && s > 0.0)) {
220            return invalid("`speed` must be a positive number.", "speed");
221        }
222        if self.duration.is_some_and(|d| !(d.is_finite() && d > 0.0)) {
223            return invalid(
224                "The duration must be a positive number of seconds.",
225                "duration",
226            );
227        }
228        Ok(())
229    }
230
231    /// What a model must be able to do to serve the request.
232    pub fn required_capabilities(&self) -> crate::Capabilities {
233        crate::Capabilities {
234            audio_input: self.audio.is_some(),
235            audio_output: true,
236            streaming: !self.stream.is_off(),
237            ..crate::Capabilities::default()
238        }
239    }
240}
241
242/// When each character of spoken text starts and ends, in seconds from the start of the audio.
243#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
244#[non_exhaustive]
245pub struct SpeechAlignment {
246    pub characters: Vec<String>,
247    pub starts: Vec<f64>,
248    pub ends: Vec<f64>,
249}
250
251impl SpeechAlignment {
252    pub fn new(characters: Vec<String>, starts: Vec<f64>, ends: Vec<f64>) -> Self {
253        SpeechAlignment {
254            characters,
255            starts,
256            ends,
257        }
258    }
259}
260
261/// The reply to a request for audio.
262#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
263#[non_exhaustive]
264pub struct SpeechResponse {
265    pub model: String,
266    /// The audio, base64-encoded with its media type.
267    pub audio: Source,
268    /// When each character is spoken, for a request that asked for timestamps.
269    #[serde(default, skip_serializing_if = "Option::is_none")]
270    pub alignment: Option<SpeechAlignment>,
271    /// The characters the provider billed, when it says.
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub characters: Option<u64>,
274    pub usage: Usage,
275    #[serde(default, skip_serializing_if = "Extras::is_empty")]
276    pub extras: Extras,
277}
278
279impl SpeechResponse {
280    pub fn new(model: impl Into<String>, audio: Source) -> Self {
281        SpeechResponse {
282            model: model.into(),
283            audio,
284            alignment: None,
285            characters: None,
286            usage: Usage::default(),
287            extras: Extras::default(),
288        }
289    }
290}
291
292/// One event of streamed audio: a piece of the audio, or the end with its usage.
293#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
294#[non_exhaustive]
295pub struct SpeechEvent {
296    /// A piece of the audio, base64-encoded.
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub audio: Option<String>,
299    /// The media type of the audio, on the first piece when the provider names it.
300    #[serde(default, skip_serializing_if = "Option::is_none")]
301    pub media_type: Option<String>,
302    /// When each character of this piece is spoken.
303    #[serde(default, skip_serializing_if = "Option::is_none")]
304    pub alignment: Option<SpeechAlignment>,
305    /// Whether the audio is complete.
306    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
307    pub done: bool,
308    #[serde(default, skip_serializing_if = "Option::is_none")]
309    pub usage: Option<Usage>,
310    #[serde(default, skip_serializing_if = "Option::is_none")]
311    pub characters: Option<u64>,
312    #[serde(default, skip_serializing_if = "Extras::is_empty")]
313    pub extras: Extras,
314}
315
316impl SpeechEvent {
317    /// A piece of audio, base64-encoded.
318    pub fn audio(data: impl Into<String>) -> Self {
319        SpeechEvent {
320            audio: Some(data.into()),
321            ..SpeechEvent::default()
322        }
323    }
324
325    /// The end of the audio.
326    pub fn done(usage: Option<Usage>) -> Self {
327        SpeechEvent {
328            done: true,
329            usage,
330            ..SpeechEvent::default()
331        }
332    }
333}
334
335/// What a transcription request asks for.
336#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
337#[serde(rename_all = "snake_case")]
338#[non_exhaustive]
339pub enum TranscriptionOperation {
340    /// The text in the language spoken.
341    #[default]
342    Transcribe,
343    /// The text in English, whatever the language spoken.
344    Translate,
345}
346
347impl TranscriptionOperation {
348    pub const fn as_str(self) -> &'static str {
349        match self {
350            TranscriptionOperation::Transcribe => "transcribe",
351            TranscriptionOperation::Translate => "translate",
352        }
353    }
354}
355
356wire_enum!(
357    /// The form of a transcript: JSON with the text, plain text, subtitles, or JSON with
358    /// segments, words or speakers.
359    TranscriptFormat {
360        Json = "json",
361        Text = "text",
362        Srt = "srt",
363        VerboseJson = "verbose_json",
364        Vtt = "vtt",
365        DiarizedJson = "diarized_json",
366    }
367);
368
369impl TranscriptFormat {
370    /// Whether the transcript is plain text rather than JSON.
371    pub fn is_text(&self) -> bool {
372        matches!(
373            self,
374            TranscriptFormat::Text | TranscriptFormat::Srt | TranscriptFormat::Vtt
375        )
376    }
377
378    /// Whether the form needs the time of each segment.
379    pub fn needs_timing(&self) -> bool {
380        matches!(
381            self,
382            TranscriptFormat::Srt
383                | TranscriptFormat::Vtt
384                | TranscriptFormat::VerboseJson
385                | TranscriptFormat::DiarizedJson
386        )
387    }
388}
389
390wire_enum!(
391    /// How finely a transcript is timed.
392    TimestampGranularity {
393        Word = "word",
394        Segment = "segment",
395    }
396);
397
398/// A request to transcribe or translate audio.
399#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
400#[non_exhaustive]
401pub struct TranscriptionRequest {
402    pub model: String,
403    #[serde(default)]
404    pub operation: TranscriptionOperation,
405    pub audio: AudioInput,
406    /// The language spoken, as an ISO 639 code.
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub language: Option<String>,
409    /// Text that guides the transcript's spelling and style.
410    #[serde(default, skip_serializing_if = "Option::is_none")]
411    pub prompt: Option<String>,
412    #[serde(default, skip_serializing_if = "Option::is_none")]
413    pub format: Option<TranscriptFormat>,
414    #[serde(default, skip_serializing_if = "Option::is_none")]
415    pub temperature: Option<f64>,
416    #[serde(default, skip_serializing_if = "Vec::is_empty")]
417    pub timestamps: Vec<TimestampGranularity>,
418    /// Whether to tell the speakers apart.
419    #[serde(default, skip_serializing_if = "Option::is_none")]
420    pub diarize: Option<bool>,
421    /// The most speakers the audio holds.
422    #[serde(default, skip_serializing_if = "Option::is_none")]
423    pub speakers: Option<u32>,
424    #[serde(default, skip_serializing_if = "StreamMode::is_off")]
425    pub stream: StreamMode,
426    #[serde(default, skip_serializing_if = "Extras::is_empty")]
427    pub extras: Extras,
428}
429
430impl TranscriptionRequest {
431    pub fn new(
432        model: impl Into<String>,
433        operation: TranscriptionOperation,
434        audio: AudioInput,
435    ) -> Self {
436        TranscriptionRequest {
437            model: model.into(),
438            operation,
439            audio,
440            language: None,
441            prompt: None,
442            format: None,
443            temperature: None,
444            timestamps: Vec::new(),
445            diarize: None,
446            speakers: None,
447            stream: StreamMode::Off,
448            extras: Extras::default(),
449        }
450    }
451
452    /// The transcript's form, `json` when the request names none.
453    pub fn format_or_default(&self) -> TranscriptFormat {
454        self.format.clone().unwrap_or(TranscriptFormat::Json)
455    }
456
457    /// Checks what every transcription request needs, whatever its format.
458    pub fn validate(&self) -> Result<(), KppError> {
459        let invalid = |message: &str, param: &str| {
460            Err(KppError::invalid_request(message.to_owned()).with_param(param.to_owned()))
461        };
462        if self.model.is_empty() {
463            return invalid("`model` must not be empty.", "model");
464        }
465        if self
466            .temperature
467            .is_some_and(|t| !(t.is_finite() && (0.0..=2.0).contains(&t)))
468        {
469            return invalid("`temperature` must be between 0 and 2.", "temperature");
470        }
471        if self.speakers == Some(0) {
472            return invalid("The number of speakers must be at least 1.", "num_speakers");
473        }
474        Ok(())
475    }
476
477    /// What a model must be able to do to serve the request.
478    pub fn required_capabilities(&self) -> crate::Capabilities {
479        crate::Capabilities {
480            audio_input: true,
481            streaming: !self.stream.is_off(),
482            ..crate::Capabilities::default()
483        }
484    }
485}
486
487/// A timed stretch of a transcript.
488#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
489#[non_exhaustive]
490pub struct TranscriptSegment {
491    #[serde(default, skip_serializing_if = "Option::is_none")]
492    pub id: Option<String>,
493    /// The start, in seconds from the start of the audio.
494    pub start: f64,
495    pub end: f64,
496    pub text: String,
497    #[serde(default, skip_serializing_if = "Option::is_none")]
498    pub speaker: Option<String>,
499    #[serde(default, skip_serializing_if = "Extras::is_empty")]
500    pub extras: Extras,
501}
502
503impl TranscriptSegment {
504    pub fn new(start: f64, end: f64, text: impl Into<String>) -> Self {
505        TranscriptSegment {
506            start,
507            end,
508            text: text.into(),
509            ..TranscriptSegment::default()
510        }
511    }
512}
513
514/// A timed word of a transcript.
515#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
516#[non_exhaustive]
517pub struct TranscriptWord {
518    pub text: String,
519    pub start: f64,
520    pub end: f64,
521    #[serde(default, skip_serializing_if = "Option::is_none")]
522    pub speaker: Option<String>,
523    #[serde(default, skip_serializing_if = "Extras::is_empty")]
524    pub extras: Extras,
525}
526
527impl TranscriptWord {
528    pub fn new(text: impl Into<String>, start: f64, end: f64) -> Self {
529        TranscriptWord {
530            text: text.into(),
531            start,
532            end,
533            ..TranscriptWord::default()
534        }
535    }
536}
537
538/// The reply to a transcription request.
539#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
540#[non_exhaustive]
541pub struct TranscriptionResponse {
542    pub model: String,
543    /// The transcript: plain text, or the subtitles of `format`.
544    pub text: String,
545    /// The form `text` came in.
546    #[serde(default, skip_serializing_if = "Option::is_none")]
547    pub format: Option<TranscriptFormat>,
548    /// The language detected, as the provider names it.
549    #[serde(default, skip_serializing_if = "Option::is_none")]
550    pub language: Option<String>,
551    /// The length of the audio in seconds.
552    #[serde(default, skip_serializing_if = "Option::is_none")]
553    pub duration: Option<f64>,
554    #[serde(default, skip_serializing_if = "Vec::is_empty")]
555    pub segments: Vec<TranscriptSegment>,
556    #[serde(default, skip_serializing_if = "Vec::is_empty")]
557    pub words: Vec<TranscriptWord>,
558    pub usage: Usage,
559    /// The seconds of audio the provider billed, for providers that bill by duration.
560    #[serde(default, skip_serializing_if = "Option::is_none")]
561    pub usage_seconds: Option<f64>,
562    #[serde(default, skip_serializing_if = "Extras::is_empty")]
563    pub extras: Extras,
564}
565
566impl TranscriptionResponse {
567    pub fn new(model: impl Into<String>, text: impl Into<String>) -> Self {
568        TranscriptionResponse {
569            model: model.into(),
570            text: text.into(),
571            ..TranscriptionResponse::default()
572        }
573    }
574
575    /// The length of the audio, from the reply's duration, its billed seconds or its last
576    /// timed segment or word.
577    pub fn audio_seconds(&self) -> Option<f64> {
578        self.duration.or(self.usage_seconds).or_else(|| {
579            let segments = self.segments.iter().map(|s| s.end);
580            let words = self.words.iter().map(|w| w.end);
581            segments.chain(words).reduce(f64::max)
582        })
583    }
584}
585
586/// One event of a streamed transcript: a piece of text, a finished segment, or the end.
587#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
588#[non_exhaustive]
589pub struct TranscriptEvent {
590    /// More text of the transcript.
591    #[serde(default, skip_serializing_if = "Option::is_none")]
592    pub delta: Option<String>,
593    /// The segment the text belongs to, for providers that name it.
594    #[serde(default, skip_serializing_if = "Option::is_none")]
595    pub segment_id: Option<String>,
596    /// A finished segment, with its time and speaker.
597    #[serde(default, skip_serializing_if = "Option::is_none")]
598    pub segment: Option<TranscriptSegment>,
599    /// The whole transcript, at the end.
600    #[serde(default, skip_serializing_if = "Option::is_none")]
601    pub done: Option<Box<TranscriptionResponse>>,
602    #[serde(default, skip_serializing_if = "Extras::is_empty")]
603    pub extras: Extras,
604}
605
606impl TranscriptEvent {
607    pub fn delta(text: impl Into<String>) -> Self {
608        TranscriptEvent {
609            delta: Some(text.into()),
610            ..TranscriptEvent::default()
611        }
612    }
613
614    pub fn segment(segment: TranscriptSegment) -> Self {
615        TranscriptEvent {
616            segment: Some(segment),
617            ..TranscriptEvent::default()
618        }
619    }
620
621    pub fn done(transcript: TranscriptionResponse) -> Self {
622        TranscriptEvent {
623            done: Some(Box::new(transcript)),
624            ..TranscriptEvent::default()
625        }
626    }
627}
628
629#[cfg(test)]
630mod tests {
631    use super::*;
632
633    fn wav() -> AudioInput {
634        AudioInput::new(Source::base64("audio/wav", "UklGRg==").unwrap()).with_filename("a.wav")
635    }
636
637    #[test]
638    fn speech_requests_need_what_their_operation_needs() {
639        let param = |r: &SpeechRequest| r.validate().unwrap_err().param.unwrap();
640        assert_eq!(
641            param(&SpeechRequest::new("", SpeechOperation::Speech)),
642            "model"
643        );
644        assert_eq!(
645            param(&SpeechRequest::new("m", SpeechOperation::Speech)),
646            "input"
647        );
648        let ok = SpeechRequest::new("m", SpeechOperation::Speech).with_input("Hi");
649        ok.validate().unwrap();
650        assert_eq!(
651            param(&SpeechRequest::new("m", SpeechOperation::Dialogue)),
652            "inputs"
653        );
654        let mut dialogue = SpeechRequest::new("m", SpeechOperation::Dialogue);
655        dialogue
656            .dialogue
657            .push(DialogueLine::new("Hi", Some(Voice::Id("v1".into()))));
658        dialogue.validate().unwrap();
659        assert_eq!(
660            param(&SpeechRequest::new("m", SpeechOperation::VoiceChange)),
661            "audio"
662        );
663        SpeechRequest::new("m", SpeechOperation::Music)
664            .validate()
665            .unwrap();
666        let mut fast = ok.clone();
667        fast.speed = Some(0.0);
668        assert_eq!(param(&fast), "speed");
669        let mut long = ok.clone();
670        long.duration = Some(f64::NAN);
671        assert_eq!(param(&long), "duration");
672        let mut change = SpeechRequest::new("m", SpeechOperation::VoiceChange);
673        change.audio = Some(wav());
674        let caps = change.required_capabilities();
675        assert!(caps.audio_input && caps.audio_output && !caps.streaming);
676        assert_eq!(dialogue.characters() + ok.characters(), 4);
677        assert_eq!(SpeechOperation::SoundEffect.as_str(), "sound_effect");
678        assert_eq!(Voice::Named("alloy".into()).as_str(), "alloy");
679    }
680
681    #[test]
682    fn transcription_requests_check_their_ranges() {
683        let ok = TranscriptionRequest::new("m", TranscriptionOperation::Transcribe, wav());
684        ok.validate().unwrap();
685        assert_eq!(ok.format_or_default(), TranscriptFormat::Json);
686        let param = |r: &TranscriptionRequest| r.validate().unwrap_err().param.unwrap();
687        let mut hot = ok.clone();
688        hot.temperature = Some(3.0);
689        assert_eq!(param(&hot), "temperature");
690        let mut none = ok.clone();
691        none.speakers = Some(0);
692        assert_eq!(param(&none), "num_speakers");
693        let mut nameless = ok.clone();
694        nameless.model.clear();
695        assert_eq!(param(&nameless), "model");
696        assert!(ok.required_capabilities().audio_input);
697        assert_eq!(wav().byte_len(), Some(4));
698        assert_eq!(
699            AudioInput::new(Source::Url("https://example.com/a.mp3".into())).byte_len(),
700            None
701        );
702        assert_eq!(TranscriptionOperation::Translate.as_str(), "translate");
703    }
704
705    #[test]
706    fn transcript_formats_round_trip_and_know_their_kind() {
707        for s in [
708            "json",
709            "text",
710            "srt",
711            "verbose_json",
712            "vtt",
713            "diarized_json",
714            "tsv",
715        ] {
716            assert_eq!(TranscriptFormat::from_wire(s).as_wire(), s);
717        }
718        assert!(TranscriptFormat::Srt.is_text() && !TranscriptFormat::Json.is_text());
719        assert!(TranscriptFormat::Vtt.needs_timing() && !TranscriptFormat::Text.needs_timing());
720        assert_eq!(
721            TimestampGranularity::from_wire("word"),
722            TimestampGranularity::Word
723        );
724    }
725
726    #[test]
727    fn the_audio_length_comes_from_the_best_field_the_reply_has() {
728        let mut r = TranscriptionResponse::new("m", "hi");
729        assert_eq!(r.audio_seconds(), None);
730        r.words.push(TranscriptWord::new("hi", 0.0, 0.5));
731        r.segments.push(TranscriptSegment::new(0.0, 0.4, "hi"));
732        assert_eq!(r.audio_seconds(), Some(0.5));
733        r.usage_seconds = Some(2.0);
734        assert_eq!(r.audio_seconds(), Some(2.0));
735        r.duration = Some(1.5);
736        assert_eq!(r.audio_seconds(), Some(1.5));
737    }
738
739    #[test]
740    fn events_have_small_stable_forms() {
741        let json = serde_json::to_string(&SpeechEvent::audio("AAAA")).unwrap();
742        assert_eq!(json, r#"{"audio":"AAAA"}"#);
743        let json = serde_json::to_string(&SpeechEvent::done(None)).unwrap();
744        assert_eq!(json, r#"{"done":true}"#);
745        let json = serde_json::to_string(&TranscriptEvent::delta("Hel")).unwrap();
746        assert_eq!(json, r#"{"delta":"Hel"}"#);
747        let seg = TranscriptEvent::segment(TranscriptSegment::new(0.0, 1.0, "Hi"));
748        assert!(serde_json::to_string(&seg).unwrap().contains("\"segment\""));
749        let done = TranscriptEvent::done(TranscriptionResponse::new("m", "Hi"));
750        assert_eq!(done.done.unwrap().text, "Hi");
751        let r = SpeechResponse::new("m", Source::base64("audio/mpeg", "AA==").unwrap());
752        let back: SpeechResponse =
753            serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap();
754        assert_eq!(back, r);
755    }
756}