use oa::data::{Dataset, MatrixDataset, Sample};
use oa::matrix::Matrix;
use oa::{Engine, Error, Result};
use crate::core::csv;
use crate::core::decode::Decoded;
use crate::core::extract;
use crate::core::idx::IdxSplit;
use crate::core::pack::{self, FetchProgress};
use crate::text::document;
#[path = "yelp_polarity.gen.rs"]
mod generated;
pub(crate) use generated::YELP_POLARITY_PACK;
pub use generated::{YelpPolarityConfig, YelpPolaritySplit};
pub struct YelpPolarity {
dataset: MatrixDataset,
split: YelpPolaritySplit,
text_len: usize,
}
impl YelpPolarity {
pub fn decode(config: &YelpPolarityConfig) -> Result<Decoded> {
Self::decode_with_progress(config, &mut |_| true)
}
pub fn decode_with_progress(
config: &YelpPolarityConfig,
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(&YELP_POLARITY_PACK, &root, progress)?;
let tar = extract::gunzip(&dir.join("yelp_review_polarity_csv.tgz"))?;
let member = match config.split {
IdxSplit::Train => "train.csv",
IdxSplit::Test => "test.csv",
IdxSplit::Validation => {
return Err(Error::invalid_argument(
"yelp_polarity carries no validation split",
));
}
};
let records = csv::parse("yelp_polarity", extract::tar_member(&tar, member)?)?;
let mut documents = Vec::with_capacity(records.len());
for record in records {
if record.len() < 2 {
continue;
}
let label = record[0].parse::<f32>().unwrap_or(0.0) - 1.0;
documents.push((label, record[1].clone().into_bytes()));
}
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: &YelpPolarityConfig,
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) -> YelpPolaritySplit {
self.split
}
pub const fn text_len(&self) -> usize {
self.text_len
}
}
impl Dataset for YelpPolarity {
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)
}
}