oadsrust 0.3.0

Content-addressed dataset packs and loaders for OA
// @generated by tool/gen/ds/generate.py — edit tool/gen/ds/schema/packs.json instead.
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 DTD_PACK: Pack = Pack {
	name: "dtd",
	version: "3.0.1",
	license: "unspecified",
	files: &[PackFile {
		name: "dtd-r1.0.1.tar.gz",
		size: 625_239_812,
		shake256: "c05c7979757057d80016b74c5926df4ac3bd5e0e09042767d4388b139d346f51",
		urls: &[
			"https://thor.robots.ox.ac.uk/dtd/dtd-r1.0.1.tar.gz",
			"https://www.robots.ox.ac.uk/~vgg/data/dtd/download/dtd-r1.0.1.tar.gz",
		],
	}],
};

/// Official DTD fold-1 split selection.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DtdSplit {
	/// `labels/train1.txt` members (1,880 images).
	#[default]
	Train,
	/// `labels/val1.txt` members
	/// (1,880 images).
	Validation,
	/// `labels/test1.txt` members
	/// (1,880 images).
	Test,
}

/// Load options for [`Dtd`][crate::image::dtd::Dtd].
#[derive(Clone, Debug)]
pub struct DtdConfig {
	/// Which official split to materialize.
	pub split: DtdSplit,
	/// Resize each decoded image to `(width, height)` via bilinear
	/// sampling; `None` keeps the native extent per sample.
	pub size: Option<(u32, u32)>,
	/// Cache root override. `None` resolves `OA_DATA_DIR`, then the platform
	/// cache directory; see [`data_root`](crate::pack::data_root).
	pub cache_dir: Option<PathBuf>,
}

impl Default for DtdConfig {
	fn default() -> Self {
		Self {
			split: DtdSplit::Train,
			size: None,
			cache_dir: None,
		}
	}
}

impl DtdConfig {
	/// Construct the record with its default state.
	#[inline]
	#[must_use]
	pub fn new() -> Self {
		Self::default()
	}
}

impl super::Dtd {
	/// Decode the selected split and upload it on this thread's
	/// default engine.
	///
	/// # Errors
	///
	/// Returns an error when the default engine cannot be
	/// initialized, plus the errors of
	/// [`load_on`](Self::load_on).
	#[inline]
	pub fn load(config: &DtdConfig) -> Result<Self> {
		Self::load_on(&Engine::current()?, config)
	}

	/// Decode the selected split and upload it on `engine`.
	///
	/// This is the [`load`](Self::load) contract evaluated on
	/// `engine` instead of this thread's default engine.
	///
	/// # Errors
	///
	/// Returns the errors of
	/// [`load_with_progress_on`](Self::load_with_progress_on).
	#[inline]
	pub fn load_on(engine: &Engine, config: &DtdConfig) -> Result<Self> {
		Self::load_with_progress_on(engine, config, &mut |_| true)
	}

	/// [`load`](Self::load) with a fetch progress callback.
	///
	/// # Errors
	///
	/// Returns an error when the default engine cannot be
	/// initialized, plus the errors of
	/// [`load_with_progress_on`](Self::load_with_progress_on).
	#[inline]
	pub fn load_with_progress(
		config: &DtdConfig,
		progress: &mut impl FnMut(FetchProgress) -> bool,
	) -> Result<Self> {
		Self::load_with_progress_on(&Engine::current()?, config, progress)
	}
}

/// Device-resident dtd dataset implementing [`oa::data::Dataset`].
///
/// Members stay in the extracted pack cache; `get_item` lazily decodes
/// one `[1, 3, H, W]` F32 NCHW image through [`oa::image`], resized to
/// `config.size` when set. `labels()` is the resident `[N]` F32 class
/// index matrix into [`classes`](Self::classes).
pub struct Dtd {
	paths: Vec<PathBuf>,
	labels: Matrix,
	classes: Vec<String>,
	size: Option<(u32, u32)>,
	engine: Engine,
}

impl Dtd {
	/// Fetch, verify, extract, and index the pack on the host.
	///
	/// # Errors
	///
	/// Returns pack fetch/verification errors, archive decode errors,
	/// and I/O errors while materializing the extracted cache.
	pub fn decode(config: &DtdConfig) -> Result<Decoded> {
		Self::decode_with_progress(config, &mut |_| true)
	}

	/// [`decode`](Self::decode) with a fetch progress callback.
	///
	/// # Errors
	///
	/// Returns the errors of [`decode`](Self::decode), plus
	/// `Cancelled` when `progress` aborts the fetch.
	pub fn decode_with_progress(
		config: &DtdConfig,
		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,
		})
	}

	/// [`load_on`](Self::load_on) with a fetch progress callback.
	///
	/// # Errors
	///
	/// Returns the errors of [`load_on`](Self::load_on), plus
	/// `Cancelled` when `progress` aborts the fetch.
	pub fn load_with_progress_on(
		engine: &Engine,
		config: &DtdConfig,
		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(),
		})
	}

	/// Class names in label-index order.
	#[must_use]
	pub fn classes(&self) -> &[String] {
		&self.classes
	}

	/// `[N]` F32 class-index matrix on the owning engine.
	#[must_use]
	pub const fn labels(&self) -> &Matrix {
		&self.labels
	}

	/// Number of indexed samples.
	#[must_use]
	pub fn count(&self) -> usize {
		self.paths.len()
	}

	/// Extracted image path for row `index`.
	///
	/// # Errors
	///
	/// Returns `out_of_range` when `index` is outside the dataset.
	pub fn path(&self, index: i64) -> Result<&Path> {
		if index < 0 || index >= self.paths.len() as i64 {
			return Err(Error::out_of_range("dtd index is outside the dataset"));
		}
		Ok(&self.paths[index as usize])
	}

	/// Lazily decode image `index` to a `[1, 3, H, W]` F32 NCHW
	/// image on the owning engine, resized to `config.size` when
	/// set.
	///
	/// # Errors
	///
	/// Returns `out_of_range` for an out-of-range index and the
	/// [`oa::image`] decode/resize errors for the member.
	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: &DtdConfig) -> Result<PathBuf> {
		let root = match &config.cache_dir {
			Some(dir) => dir.clone(),
			None => pack::data_root()?,
		};
		Ok(root.join("dtd").join("3.0.1"))
	}

	fn extracted_dir(config: &DtdConfig) -> Result<PathBuf> {
		Ok(Self::pack_dir(config)?.join("extracted"))
	}

	fn materialize(
		config: &DtdConfig,
		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(&DTD_PACK, &root, progress)?;
		let extracted = dir.join("extracted");
		let done = extracted.join(".done_all");
		if done.exists() {
			return Ok(extracted);
		}
		let members: &[&str] = &["dtd-r1.0.1.tar.gz"];
		for member in members {
			folder::extract_images(&dir.join(member), &extracted)?;
		}
		std::fs::write(&done, b"done").map_err(|error| Error::io("write dtd extract marker", error))?;
		Ok(extracted)
	}

	fn index_of(config: &DtdConfig, extracted: &Path) -> Result<ImageIndex> {
		let index_root = extracted.join(match config.split {
			DtdSplit::Train => "dtd",
			DtdSplit::Validation => "dtd",
			DtdSplit::Test => "dtd",
		});
		let index = super::index(&index_root, config)?;
		let split_key = match config.split {
			DtdSplit::Train => "train",
			DtdSplit::Validation => "validation",
			DtdSplit::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 dtd class table", error))?;
		}
		Ok(index)
	}
}

impl Dataset for Dtd {
	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))
	}
}