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 LFW_PACK: Pack = Pack {
	name: "lfw",
	version: "0.4.0",
	license: "unspecified",
	files: &[PackFile {
		name: "lfw-funneled.tgz",
		size: 243_346_528,
		shake256: "564aa87a6cdd9a2d27bc31b7938c6454ca8bdade1b3cb38fc6d92e9dda942bbf",
		urls: &["https://ndownloader.figshare.com/files/5976015"],
	}],
};

/// Load options for [`Lfw`][crate::image::lfw::Lfw].
#[derive(Clone, Debug, Default)]
pub struct LfwConfig {
	/// 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 LfwConfig {
	/// Construct the record with its default state.
	#[inline]
	#[must_use]
	pub fn new() -> Self {
		Self::default()
	}
}

impl super::Lfw {
	/// 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: &LfwConfig) -> 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: &LfwConfig) -> 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: &LfwConfig,
		progress: &mut impl FnMut(FetchProgress) -> bool,
	) -> Result<Self> {
		Self::load_with_progress_on(&Engine::current()?, config, progress)
	}
}

/// Device-resident lfw 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 Lfw {
	paths: Vec<PathBuf>,
	labels: Matrix,
	classes: Vec<String>,
	size: Option<(u32, u32)>,
	engine: Engine,
}

impl Lfw {
	/// 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: &LfwConfig) -> 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: &LfwConfig,
		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: &LfwConfig,
		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("lfw 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: &LfwConfig) -> Result<PathBuf> {
		let root = match &config.cache_dir {
			Some(dir) => dir.clone(),
			None => pack::data_root()?,
		};
		Ok(root.join("lfw").join("0.4.0"))
	}

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

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

	fn index_of(_config: &LfwConfig, extracted: &Path) -> Result<ImageIndex> {
		let index_root = extracted.join("lfw_funneled");
		let index = ImageIndex::class_dirs(&index_root)?;
		let split_key = "all";
		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 lfw class table", error))?;
		}
		Ok(index)
	}
}

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