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 PLACES365_SMALL_PACK: Pack = Pack {
name: "places365_small",
version: "1.0.0",
license: "MIT",
files: &[PackFile {
name: "places365standard_easyformat.tar",
size: 26_686_689_280,
shake256: "72f2962b8df80ae77996da795176d7e125d6546d785774f05f0fa141cf80a1b1",
urls: &["https://data.csail.mit.edu/places/places365/places365standard_easyformat.tar"],
}],
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Places365SmallSplit {
#[default]
Train,
Validation,
}
#[derive(Clone, Debug)]
pub struct Places365SmallConfig {
pub split: Places365SmallSplit,
pub size: Option<(u32, u32)>,
pub cache_dir: Option<PathBuf>,
}
impl Default for Places365SmallConfig {
fn default() -> Self {
Self {
split: Places365SmallSplit::Train,
size: None,
cache_dir: None,
}
}
}
impl Places365SmallConfig {
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
impl super::Places365Small {
#[inline]
pub fn load(config: &Places365SmallConfig) -> Result<Self> {
Self::load_on(&Engine::current()?, config)
}
#[inline]
pub fn load_on(engine: &Engine, config: &Places365SmallConfig) -> Result<Self> {
Self::load_with_progress_on(engine, config, &mut |_| true)
}
#[inline]
pub fn load_with_progress(
config: &Places365SmallConfig,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Self> {
Self::load_with_progress_on(&Engine::current()?, config, progress)
}
}
pub struct Places365Small {
paths: Vec<PathBuf>,
labels: Matrix,
classes: Vec<String>,
size: Option<(u32, u32)>,
engine: Engine,
}
impl Places365Small {
pub fn decode(config: &Places365SmallConfig) -> Result<Decoded> {
Self::decode_with_progress(config, &mut |_| true)
}
pub fn decode_with_progress(
config: &Places365SmallConfig,
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: &Places365SmallConfig,
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(
"places365_small 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: &Places365SmallConfig) -> Result<PathBuf> {
let root = match &config.cache_dir {
Some(dir) => dir.clone(),
None => pack::data_root()?,
};
Ok(root.join("places365_small").join("1.0.0"))
}
fn extracted_dir(config: &Places365SmallConfig) -> Result<PathBuf> {
Ok(Self::pack_dir(config)?.join("extracted"))
}
fn materialize(
config: &Places365SmallConfig,
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(&PLACES365_SMALL_PACK, &root, progress)?;
let extracted = dir.join("extracted");
let done = extracted.join(".done_all");
if done.exists() {
return Ok(extracted);
}
let members: &[&str] = &["places365standard_easyformat.tar"];
for member in members {
folder::extract_images(&dir.join(member), &extracted)?;
}
std::fs::write(&done, b"done")
.map_err(|error| Error::io("write places365_small extract marker", error))?;
Ok(extracted)
}
fn index_of(config: &Places365SmallConfig, extracted: &Path) -> Result<ImageIndex> {
let index_root = extracted.join(match config.split {
Places365SmallSplit::Train => "places365_standard/train",
Places365SmallSplit::Validation => "places365_standard/val",
});
let index = ImageIndex::class_dirs(&index_root)?;
let split_key = match config.split {
Places365SmallSplit::Train => "train",
Places365SmallSplit::Validation => "validation",
};
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 places365_small class table", error))?;
}
Ok(index)
}
}
impl Dataset for Places365Small {
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))
}
}