use oa::data::{Dataset, MatrixDataset, Sample};
use oa::matrix::Matrix;
use oa::{Engine, Result};
use crate::csv;
use crate::decode::Decoded;
use crate::extract;
use crate::idx::IdxSplit;
use crate::pack::{self, FetchProgress};
use crate::text::document;
#[path = "ag_news.gen.rs"]
mod generated;
pub(crate) use generated::AG_NEWS_PACK;
pub use generated::{AgNewsConfig, AgNewsSplit};
pub struct AgNews {
dataset: MatrixDataset,
split: AgNewsSplit,
text_len: usize,
}
impl AgNews {
pub fn decode(config: &AgNewsConfig) -> Result<Decoded> {
Self::decode_with_progress(config, &mut |_| true)
}
pub fn decode_with_progress(
config: &AgNewsConfig,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Decoded> {
let root = match &config.cache_dir {
Some(dir) => dir.clone(),
None => pack::data_root()?,
};
let dir = pack::ensure_pack_with_progress(&AG_NEWS_PACK, &root, progress)?;
let tar = extract::gunzip(&dir.join("ag_news_csv.tgz"))?;
let member = match config.split {
IdxSplit::Train => "train.csv",
IdxSplit::Test => "test.csv",
};
let records = csv::parse("ag_news", extract::tar_member(&tar, member)?)?;
let mut documents = Vec::with_capacity(records.len());
for record in records {
if record.len() < 3 {
continue;
}
let label = record[0].parse::<f32>().unwrap_or(0.0) - 1.0;
let mut text = record[1].clone().into_bytes();
text.push(b'\n');
text.extend_from_slice(record[2].as_bytes());
documents.push((label, text));
}
let (text, labels) = document::encode("text", &documents, config.text_len, config.normalize)?;
Ok(Decoded {
matrices: vec![text, labels],
text: None,
seq_len: 0,
})
}
pub fn load_with_progress_on(
engine: &Engine,
config: &AgNewsConfig,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Self> {
let decoded = Self::decode_with_progress(config, progress)?;
Ok(Self {
dataset: MatrixDataset::new(
decoded.upload("text", engine)?,
decoded.upload("labels", engine)?,
)?,
split: config.split,
text_len: config.text_len,
})
}
pub const fn text(&self) -> &Matrix {
self.dataset.x()
}
pub const fn labels(&self) -> &Matrix {
self.dataset.y()
}
pub const fn split(&self) -> AgNewsSplit {
self.split
}
pub const fn text_len(&self) -> usize {
self.text_len
}
}
impl Dataset for AgNews {
fn len(&self) -> i64 {
self.dataset.len()
}
fn get_item(&self, index: i64) -> Result<Matrix> {
self.dataset.get_item(index)
}
fn get_sample(&self, index: i64) -> Result<Sample> {
self.dataset.get_sample(index)
}
}