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 OXFORD_FLOWERS102_PACK: Pack = Pack {
name: "oxford_flowers102",
version: "2.0.0",
license: "unspecified",
files: &[
PackFile {
name: "102flowers.tgz",
size: 344_862_509,
shake256: "0a61d14cf90a5fd624614f712486b50c2f6fae35c4a978df35c760f994e2ed85",
urls: &["https://thor.robots.ox.ac.uk/flowers/102/102flowers.tgz"],
},
PackFile {
name: "imagelabels.mat",
size: 502,
shake256: "910a7201cff39a946020ddae2391fb76b613465fa4b709ce4351e8ef67db0a8e",
urls: &["https://thor.robots.ox.ac.uk/flowers/102/imagelabels.mat"],
},
PackFile {
name: "setid.mat",
size: 14_989,
shake256: "6a4a3e0beb57d7e0b66c6e7b183760be5231964f1aa89644e4fc243e8b45b3f7",
urls: &["https://thor.robots.ox.ac.uk/flowers/102/setid.mat"],
},
],
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OxfordFlowers102Split {
#[default]
Train,
Validation,
Test,
}
#[derive(Clone, Debug)]
pub struct OxfordFlowers102Config {
pub split: OxfordFlowers102Split,
pub size: Option<(u32, u32)>,
pub cache_dir: Option<PathBuf>,
}
impl Default for OxfordFlowers102Config {
fn default() -> Self {
Self {
split: OxfordFlowers102Split::Train,
size: None,
cache_dir: None,
}
}
}
impl OxfordFlowers102Config {
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
impl super::OxfordFlowers102 {
#[inline]
pub fn load(config: &OxfordFlowers102Config) -> Result<Self> {
Self::load_on(&Engine::current()?, config)
}
#[inline]
pub fn load_on(engine: &Engine, config: &OxfordFlowers102Config) -> Result<Self> {
Self::load_with_progress_on(engine, config, &mut |_| true)
}
#[inline]
pub fn load_with_progress(
config: &OxfordFlowers102Config,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Self> {
Self::load_with_progress_on(&Engine::current()?, config, progress)
}
}
pub struct OxfordFlowers102 {
paths: Vec<PathBuf>,
labels: Matrix,
classes: Vec<String>,
size: Option<(u32, u32)>,
engine: Engine,
}
impl OxfordFlowers102 {
pub fn decode(config: &OxfordFlowers102Config) -> Result<Decoded> {
Self::decode_with_progress(config, &mut |_| true)
}
pub fn decode_with_progress(
config: &OxfordFlowers102Config,
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: &OxfordFlowers102Config,
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(
"oxford_flowers102 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: &OxfordFlowers102Config) -> Result<PathBuf> {
let root = match &config.cache_dir {
Some(dir) => dir.clone(),
None => pack::data_root()?,
};
Ok(root.join("oxford_flowers102").join("2.0.0"))
}
fn extracted_dir(config: &OxfordFlowers102Config) -> Result<PathBuf> {
Ok(Self::pack_dir(config)?.join("extracted"))
}
fn materialize(
config: &OxfordFlowers102Config,
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(&OXFORD_FLOWERS102_PACK, &root, progress)?;
let extracted = dir.join("extracted");
let done = extracted.join(".done_all");
if done.exists() {
return Ok(extracted);
}
let members: &[&str] = &["102flowers.tgz"];
for member in members {
folder::extract_images(&dir.join(member), &extracted)?;
}
std::fs::write(&done, b"done")
.map_err(|error| Error::io("write oxford_flowers102 extract marker", error))?;
Ok(extracted)
}
fn index_of(config: &OxfordFlowers102Config, extracted: &Path) -> Result<ImageIndex> {
let index_root = extracted.join("jpg");
let index = super::index(&index_root, config)?;
let split_key = match config.split {
OxfordFlowers102Split::Train => "train",
OxfordFlowers102Split::Validation => "validation",
OxfordFlowers102Split::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 oxford_flowers102 class table", error))?;
}
Ok(index)
}
}
impl Dataset for OxfordFlowers102 {
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))
}
}