use std::path::{Path, PathBuf};
use oa::data::{Dataset, Sample};
use oa::image::{Image, InterpolationMode};
use oa::matrix::{self, Matrix};
use oa::{Engine, Error, Result};
use crate::core::decode::Decoded;
use crate::core::pack::{self, FetchProgress, Pack, PackFile};
use crate::image::folder::{self, ImageIndex};
pub(crate) const ROCK_PAPER_SCISSORS_PACK: Pack = Pack {
name: "rock_paper_scissors",
version: "1.0.0",
license: "unspecified",
files: &[
PackFile {
name: "rps.zip",
size: 200_682_221,
shake256: "b07c00df6ffc0e76130c9cc56a0fb88bd15c89432eb3f7f68fc1a67224056558",
urls: &["https://storage.googleapis.com/download.tensorflow.org/data/rps.zip"],
},
PackFile {
name: "rps-test-set.zip",
size: 29_516_758,
shake256: "345f7182a40148959b4d2796930c99af61b040927353dcac8cba016e336c334b",
urls: &["https://storage.googleapis.com/download.tensorflow.org/data/rps-test-set.zip"],
},
],
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RockPaperScissorsSplit {
#[default]
Train,
Test,
}
#[derive(Clone, Debug)]
pub struct RockPaperScissorsConfig {
pub split: RockPaperScissorsSplit,
pub size: Option<(u32, u32)>,
pub cache_dir: Option<PathBuf>,
}
impl Default for RockPaperScissorsConfig {
fn default() -> Self {
Self {
split: RockPaperScissorsSplit::Train,
size: None,
cache_dir: None,
}
}
}
impl RockPaperScissorsConfig {
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
impl super::RockPaperScissors {
#[inline]
pub fn load(config: &RockPaperScissorsConfig) -> Result<Self> {
Self::load_on(&Engine::current()?, config)
}
#[inline]
pub fn load_on(engine: &Engine, config: &RockPaperScissorsConfig) -> Result<Self> {
Self::load_with_progress_on(engine, config, &mut |_| true)
}
#[inline]
pub fn load_with_progress(
config: &RockPaperScissorsConfig,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Self> {
Self::load_with_progress_on(&Engine::current()?, config, progress)
}
}
pub struct RockPaperScissors {
paths: Vec<PathBuf>,
labels: Matrix,
classes: Vec<String>,
size: Option<(u32, u32)>,
engine: Engine,
}
impl RockPaperScissors {
pub fn decode(config: &RockPaperScissorsConfig) -> Result<Decoded> {
Self::decode_with_progress(config, &mut |_| true)
}
pub fn decode_with_progress(
config: &RockPaperScissorsConfig,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Decoded> {
let extracted = Self::materialize(config, progress)?;
let index = Self::index_of(config, &extracted)?;
Ok(Decoded {
matrices: vec![index.labels()?],
text: Some(index.paths_text(&extracted)?),
seq_len: 0,
})
}
pub fn load_with_progress_on(
engine: &Engine,
config: &RockPaperScissorsConfig,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Self> {
let decoded = Self::decode_with_progress(config, progress)?;
let labels = decoded.upload("labels", engine)?;
let index = Self::index_of(config, &Self::extracted_dir(config)?)?;
Ok(Self {
paths: index.paths,
labels,
classes: index.classes,
size: config.size,
engine: engine.clone(),
})
}
#[must_use]
pub fn classes(&self) -> &[String] {
&self.classes
}
#[must_use]
pub const fn labels(&self) -> &Matrix {
&self.labels
}
#[must_use]
pub fn count(&self) -> usize {
self.paths.len()
}
pub fn path(&self, index: i64) -> Result<&Path> {
if index < 0 || index >= self.paths.len() as i64 {
return Err(Error::out_of_range(
"rock_paper_scissors index is outside the dataset",
));
}
Ok(&self.paths[index as usize])
}
pub fn image(&self, index: i64) -> Result<Image> {
let image = folder::decode(&self.engine, self.path(index)?)?;
match self.size {
Some((width, height)) => {
oa::image::resize(&image, width, height, InterpolationMode::Bilinear)
}
None => Ok(image),
}
}
fn pack_dir(config: &RockPaperScissorsConfig) -> Result<PathBuf> {
let root = match &config.cache_dir {
Some(dir) => dir.clone(),
None => pack::data_root()?,
};
Ok(root.join("rock_paper_scissors").join("1.0.0"))
}
fn extracted_dir(config: &RockPaperScissorsConfig) -> Result<PathBuf> {
Ok(Self::pack_dir(config)?.join("extracted"))
}
fn materialize(
config: &RockPaperScissorsConfig,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<PathBuf> {
let root = match &config.cache_dir {
Some(dir) => dir.clone(),
None => pack::data_root()?,
};
let dir = pack::ensure_pack_with_progress(&ROCK_PAPER_SCISSORS_PACK, &root, progress)?;
let extracted = dir.join("extracted");
let split_key = match config.split {
RockPaperScissorsSplit::Train => "train",
RockPaperScissorsSplit::Test => "test",
};
let done = extracted.join(format!(".done_{split_key}"));
if done.exists() {
return Ok(extracted);
}
let members: &[&str] = match config.split {
RockPaperScissorsSplit::Train => &["rps.zip"],
RockPaperScissorsSplit::Test => &["rps-test-set.zip"],
};
let target = extracted.join(split_key);
for member in members {
folder::extract_images(&dir.join(member), &target)?;
}
std::fs::write(&done, b"done")
.map_err(|error| Error::io("write rock_paper_scissors extract marker", error))?;
Ok(extracted)
}
fn index_of(config: &RockPaperScissorsConfig, extracted: &Path) -> Result<ImageIndex> {
let index_root = extracted.join(match config.split {
RockPaperScissorsSplit::Train => "train/rps",
RockPaperScissorsSplit::Test => "test/rps-test-set",
});
let index = ImageIndex::class_dirs(&index_root)?;
let split_key = match config.split {
RockPaperScissorsSplit::Train => "train",
RockPaperScissorsSplit::Test => "test",
};
let classes = extracted.join(format!(".classes_{split_key}"));
if !classes.exists() {
std::fs::create_dir_all(extracted)
.map_err(|error| Error::io("create extracted root", error))?;
std::fs::write(&classes, index.classes.join("\n"))
.map_err(|error| Error::io("write rock_paper_scissors class table", error))?;
}
Ok(index)
}
}
impl Dataset for RockPaperScissors {
fn len(&self) -> i64 {
i64::try_from(self.paths.len()).unwrap_or(i64::MAX)
}
fn get_item(&self, index: i64) -> Result<Matrix> {
self.image(index)?.into_matrix().squeeze(0)
}
fn get_sample(&self, index: i64) -> Result<Sample> {
let x = self.get_item(index)?;
let y = matrix::slice(&self.labels, 0, index, index + 1)?;
Ok(Sample::new_with_label(x, y))
}
}