Skip to main content

agentai_audio/
voice_store.rs

1//! Storage for cloned voices, for providers that keep the sample themselves.
2
3use crate::provider::{VoiceId, VoiceInfo, VoiceOrigin};
4use agentai_core::message::Media;
5use agentai_core::storage::StorageError;
6use async_trait::async_trait;
7use std::sync::{Arc, Mutex};
8
9/// A cloned voice: a name, a sample and what is said in it.
10#[derive(Debug, Clone, PartialEq)]
11#[non_exhaustive]
12pub struct StoredVoice {
13    /// Name of the voice.
14    pub name: String,
15    /// Description of the voice.
16    pub description: Option<String>,
17    /// Recording of the voice.
18    pub sample: Media,
19    /// What is said in the sample.
20    pub transcript: Option<String>,
21    /// The language of the voice (a BCP-47 code such as `pl`).
22    pub language: Option<String>,
23}
24
25impl StoredVoice {
26    /// Creates a voice with its name and sample.
27    pub fn new(name: impl Into<String>, sample: Media) -> Self {
28        Self {
29            name: name.into(),
30            description: None,
31            sample,
32            transcript: None,
33            language: None,
34        }
35    }
36
37    /// Sets the description.
38    pub fn with_description(mut self, description: impl Into<String>) -> Self {
39        self.description = Some(description.into());
40        self
41    }
42
43    /// Sets the language of the voice.
44    pub fn with_language(mut self, language: impl Into<String>) -> Self {
45        self.language = Some(language.into());
46        self
47    }
48
49    /// Sets the transcript of the sample.
50    pub fn with_transcript(mut self, transcript: impl Into<String>) -> Self {
51        self.transcript = Some(transcript.into());
52        self
53    }
54}
55
56impl StoredVoice {
57    /// The voice as [`VoiceInfo`], with its sample as the preview.
58    pub(crate) fn into_info(self, id: VoiceId) -> VoiceInfo {
59        let mut info = VoiceInfo::new(id, self.name, VoiceOrigin::Store).with_preview(self.sample);
60        info.description = self.description;
61        info.language = self.language;
62        info
63    }
64}
65
66/// Saves cloned voices and chooses their IDs.
67#[async_trait]
68pub trait VoiceStore: Send + Sync + 'static {
69    /// Stores the voice and returns its ID, for
70    /// [`SpeechRequest::with_voice`](crate::SpeechRequest::with_voice).
71    async fn save(&self, voice: StoredVoice) -> Result<VoiceId, StorageError>;
72
73    /// Returns the voice stored under `id`, or `None`.
74    ///
75    /// `id` may be arbitrary untrusted text, for example what a model wrote as a voice. An
76    /// implementation backed by files or a database must return `Ok(None)` for anything that is
77    /// not a valid ID (no path traversal, no query injection).
78    async fn get(&self, id: &str) -> Result<Option<StoredVoice>, StorageError>;
79
80    /// Returns every voice with its ID, in the order they were saved.
81    async fn list(&self) -> Result<Vec<(VoiceId, StoredVoice)>, StorageError>;
82}
83
84/// [`VoiceStore`] in memory, with the IDs `voice-1`, `voice-2`, ...
85///
86/// Clones share the same voices.
87#[derive(Debug, Clone, Default)]
88pub struct MemoryVoiceStore {
89    voices: Arc<Mutex<Vec<(VoiceId, StoredVoice)>>>,
90}
91
92impl MemoryVoiceStore {
93    /// Creates an empty store.
94    pub fn new() -> Self {
95        Self::default()
96    }
97}
98
99#[async_trait]
100impl VoiceStore for MemoryVoiceStore {
101    async fn save(&self, voice: StoredVoice) -> Result<VoiceId, StorageError> {
102        let mut voices = self.voices.lock().unwrap();
103        let id = format!("voice-{}", voices.len() + 1);
104        voices.push((id.clone(), voice));
105        Ok(id)
106    }
107
108    async fn get(&self, id: &str) -> Result<Option<StoredVoice>, StorageError> {
109        let voices = self.voices.lock().unwrap();
110        Ok(voices.iter().find(|(i, _)| i == id).map(|(_, v)| v.clone()))
111    }
112
113    async fn list(&self) -> Result<Vec<(VoiceId, StoredVoice)>, StorageError> {
114        Ok(self.voices.lock().unwrap().clone())
115    }
116}