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 EUROSAT_PACK: Pack = Pack {
name: "eurosat",
version: "2.0.0",
license: "unspecified",
files: &[PackFile {
name: "EuroSAT.zip",
size: 94_280_567,
shake256: "f5de71ab8ac0daa31ce263897fa79ede9071d555a167015621f8653ad294048c",
urls: &["https://huggingface.co/datasets/torchgeo/eurosat/resolve/main/EuroSAT.zip"],
}],
};
#[derive(Clone, Debug, Default)]
pub struct EurosatConfig {
pub size: Option<(u32, u32)>,
pub cache_dir: Option<PathBuf>,
}
impl EurosatConfig {
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
impl super::Eurosat {
#[inline]
pub fn load(config: &EurosatConfig) -> Result<Self> {
Self::load_on(&Engine::current()?, config)
}
#[inline]
pub fn load_on(engine: &Engine, config: &EurosatConfig) -> Result<Self> {
Self::load_with_progress_on(engine, config, &mut |_| true)
}
#[inline]
pub fn load_with_progress(
config: &EurosatConfig,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Self> {
Self::load_with_progress_on(&Engine::current()?, config, progress)
}
}
pub struct Eurosat {
paths: Vec<PathBuf>,
labels: Matrix,
classes: Vec<String>,
size: Option<(u32, u32)>,
engine: Engine,
}
impl Eurosat {
pub fn decode(config: &EurosatConfig) -> Result<Decoded> {
Self::decode_with_progress(config, &mut |_| true)
}
pub fn decode_with_progress(
config: &EurosatConfig,
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: &EurosatConfig,
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("eurosat 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: &EurosatConfig) -> Result<PathBuf> {
let root = match &config.cache_dir {
Some(dir) => dir.clone(),
None => pack::data_root()?,
};
Ok(root.join("eurosat").join("2.0.0"))
}
fn extracted_dir(config: &EurosatConfig) -> Result<PathBuf> {
Ok(Self::pack_dir(config)?.join("extracted"))
}
fn materialize(
config: &EurosatConfig,
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(&EUROSAT_PACK, &root, progress)?;
let extracted = dir.join("extracted");
let done = extracted.join(".done_all");
if done.exists() {
return Ok(extracted);
}
let members: &[&str] = &["EuroSAT.zip"];
for member in members {
folder::extract_images(&dir.join(member), &extracted)?;
}
std::fs::write(&done, b"done")
.map_err(|error| Error::io("write eurosat extract marker", error))?;
Ok(extracted)
}
fn index_of(_config: &EurosatConfig, extracted: &Path) -> Result<ImageIndex> {
let index_root = extracted.join("2750");
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 eurosat class table", error))?;
}
Ok(index)
}
}
impl Dataset for Eurosat {
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))
}
}