use oa::data::{Dataset, MatrixDataset, Sample};
use oa::matrix::Matrix;
use oa::{Engine, Error, Result};
use crate::core::decode::{Decoded, MatrixData};
use crate::core::extract;
use crate::core::pack::{self, FetchProgress};
use crate::core::wav;
#[path = "mini_speech_commands.gen.rs"]
mod generated;
pub(crate) use generated::MINI_SPEECH_COMMANDS_PACK;
pub use generated::{CLIP_SAMPLE_RATE, CLIP_SAMPLES, COMMANDS, MiniSpeechCommandsConfig};
pub struct MiniSpeechCommands {
dataset: MatrixDataset,
}
impl MiniSpeechCommands {
pub fn decode(config: &MiniSpeechCommandsConfig) -> Result<Decoded> {
Self::decode_with_progress(config, &mut |_| true)
}
pub fn decode_with_progress(
config: &MiniSpeechCommandsConfig,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Decoded> {
let root = match &config.cache_dir {
Some(dir) => dir.clone(),
None => pack::data_root()?,
};
let dir = pack::ensure_pack_with_progress(&MINI_SPEECH_COMMANDS_PACK, &root, progress)?;
let zip = std::fs::read(dir.join("mini_speech_commands.zip"))
.map_err(|error| Error::io("read speech commands archive", error))?;
let scale = if config.normalize {
1.0_f32 / 32_768.0
} else {
1.0
};
let mut waveforms = Vec::new();
let mut label_values = Vec::new();
extract::walk_zip(&zip, |name, data| {
let Some(rest) = name.strip_prefix("mini_speech_commands/") else {
return Ok(());
};
let Some((label, file)) = rest.split_once('/') else {
return Ok(());
};
if !file.ends_with(".wav") {
return Ok(());
}
let Some(index) = COMMANDS.iter().position(|command| *command == label) else {
return Err(Error::data_loss(format!(
"speech commands archive carries unknown label directory '{label}'"
)));
};
let clip = wav::parse(data)?;
if clip.channels != 1 || clip.sample_rate != CLIP_SAMPLE_RATE || clip.bits_per_sample != 16 {
return Err(Error::data_loss(format!(
"{name}: expected mono {CLIP_SAMPLE_RATE} Hz s16 wav"
)));
}
let base = waveforms.len();
for &[lo, hi] in clip.pcm.as_chunks::<2>().0.iter().take(CLIP_SAMPLES) {
waveforms.push(i16::from_le_bytes([lo, hi]) as f32 * scale);
}
waveforms.resize(base + CLIP_SAMPLES, 0.0);
label_values.push(index as f32);
Ok(())
})?;
let count = label_values.len();
if count == 0 {
return Err(Error::data_loss(
"speech commands archive holds no command clips",
));
}
Ok(Decoded {
matrices: vec![
MatrixData {
name: "samples",
shape: vec![count, 1, CLIP_SAMPLES],
values: waveforms,
},
MatrixData {
name: "labels",
shape: vec![count],
values: label_values,
},
],
text: None,
seq_len: 0,
})
}
pub fn load_with_progress_on(
engine: &Engine,
config: &MiniSpeechCommandsConfig,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Self> {
let decoded = Self::decode_with_progress(config, progress)?;
Ok(Self {
dataset: MatrixDataset::new(
decoded.upload("samples", engine)?,
decoded.upload("labels", engine)?,
)?,
})
}
pub fn new(samples: Matrix, labels: Matrix) -> Result<Self> {
let shape = samples.shape();
if shape.len() != 3 || shape[1] != 1 || shape[2] != CLIP_SAMPLES {
return Err(Error::invalid_argument(format!(
"mini_speech_commands requires [N, 1, {CLIP_SAMPLES}] samples"
)));
}
Ok(Self {
dataset: MatrixDataset::new(samples, labels)?,
})
}
#[must_use]
pub const fn samples(&self) -> &Matrix {
self.dataset.x()
}
#[must_use]
pub const fn labels(&self) -> &Matrix {
self.dataset.y()
}
}
impl Dataset for MiniSpeechCommands {
fn len(&self) -> i64 {
self.dataset.len()
}
fn get_item(&self, index: i64) -> Result<Matrix> {
self.dataset.get_item(index)
}
fn get_sample(&self, index: i64) -> Result<Sample> {
self.dataset.get_sample(index)
}
}