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 CARS196_PACK: Pack = Pack {
	name: "cars196",
	version: "1.0.0",
	license: "unspecified",
	files: &[
		PackFile {
			name: "cars196_train.zip",
			size: 980_441_497,
			shake256: "877a4094a8c776221aa06392d91e49f552dba314a5de04a7ef8f15a681988b92",
			urls: &[
				"https://huggingface.co/datasets/haodoz0118/cars196-img/resolve/main/cars196_train.zip",
			],
		},
		PackFile {
			name: "cars196_test.zip",
			size: 978_487_588,
			shake256: "d333fb077e31ef8d3407b93c820a21b552457eb0ca0f7bf0d0a82b88f1630f55",
			urls: &[
				"https://huggingface.co/datasets/haodoz0118/cars196-img/resolve/main/cars196_test.zip",
			],
		},
	],
};

/// Official Cars-196 split selection.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Cars196Split {
	/// `cars196_train.zip` members (8,144 images).
	#[default]
	Train,
	/// `cars196_test.zip` members (8,041 images).
	Test,
}

/// Load options for [`Cars196`][crate::image::cars196::Cars196].
#[derive(Clone, Debug)]
pub struct Cars196Config {
	/// Which official split to materialize.
	pub split: Cars196Split,
	/// 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 Cars196Config {
	fn default() -> Self {
		Self {
			split: Cars196Split::Train,
			size: None,
			cache_dir: None,
		}
	}
}

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

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

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

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

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

	fn materialize(
		config: &Cars196Config,
		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(&CARS196_PACK, &root, progress)?;
		let extracted = dir.join("extracted");
		let split_key = match config.split {
			Cars196Split::Train => "train",
			Cars196Split::Test => "test",
		};
		let done = extracted.join(format!(".done_{split_key}"));
		if done.exists() {
			return Ok(extracted);
		}
		let members: &[&str] = match config.split {
			Cars196Split::Train => &["cars196_train.zip"],
			Cars196Split::Test => &["cars196_test.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 cars196 extract marker", error))?;
		Ok(extracted)
	}

	fn index_of(config: &Cars196Config, extracted: &Path) -> Result<ImageIndex> {
		let index_root = extracted.join(match config.split {
			Cars196Split::Train => "train/cars196_train",
			Cars196Split::Test => "test/cars196_test",
		});
		let index = super::index(&index_root, config)?;
		let split_key = match config.split {
			Cars196Split::Train => "train",
			Cars196Split::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 cars196 class table", error))?;
		}
		Ok(index)
	}
}

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