1use crate::{dataset::Dataset, transforms::Transform};
4use torsh_core::error::{Result, TorshError};
5use torsh_tensor::Tensor;
6
7#[cfg(not(feature = "std"))]
8use alloc::{boxed::Box, collections::BTreeMap as HashMap, string::String, vec::Vec};
9#[cfg(feature = "std")]
10use std::collections::HashMap;
11use std::path::{Path, PathBuf};
12
13#[derive(Debug, Clone)]
15pub struct TextSequence {
16 pub text: String,
17 pub tokens: Option<Vec<String>>,
18 pub token_ids: Option<Vec<usize>>,
19}
20
21impl TextSequence {
22 pub fn new(text: String) -> Self {
23 Self {
24 text,
25 tokens: None,
26 token_ids: None,
27 }
28 }
29
30 pub fn with_tokens(mut self, tokens: Vec<String>) -> Self {
31 self.tokens = Some(tokens);
32 self
33 }
34
35 pub fn with_token_ids(mut self, token_ids: Vec<usize>) -> Self {
36 self.token_ids = Some(token_ids);
37 self
38 }
39
40 pub fn len(&self) -> usize {
41 if let Some(ref tokens) = self.tokens {
42 tokens.len()
43 } else if let Some(ref token_ids) = self.token_ids {
44 token_ids.len()
45 } else {
46 self.text.split_whitespace().count()
47 }
48 }
49
50 pub fn is_empty(&self) -> bool {
51 self.text.is_empty()
52 }
53}
54
55#[derive(Debug, Clone)]
57pub struct Vocabulary {
58 token_to_id: HashMap<String, usize>,
59 id_to_token: Vec<String>,
60 special_tokens: HashMap<String, usize>,
61}
62
63impl Vocabulary {
64 pub fn new() -> Self {
65 Self {
66 token_to_id: HashMap::new(),
67 id_to_token: Vec::new(),
68 special_tokens: HashMap::new(),
69 }
70 }
71
72 pub fn build_from_texts(&mut self, texts: &[String], min_freq: usize) -> Result<()> {
74 let mut token_counts = HashMap::new();
76
77 for text in texts {
78 for token in Self::simple_tokenize(text) {
79 *token_counts.entry(token).or_insert(0) += 1;
80 }
81 }
82
83 self.add_special_token("<UNK>".to_string());
85 self.add_special_token("<PAD>".to_string());
86 self.add_special_token("<SOS>".to_string());
87 self.add_special_token("<EOS>".to_string());
88
89 let mut sorted_tokens: Vec<(String, usize)> = token_counts.into_iter().collect();
91 sorted_tokens.sort_by(|a, b| b.1.cmp(&a.1)); for (token, count) in sorted_tokens {
94 if count >= min_freq && !self.token_to_id.contains_key(&token) {
95 self.add_token(token);
96 }
97 }
98
99 Ok(())
100 }
101
102 pub fn add_token(&mut self, token: String) {
104 if !self.token_to_id.contains_key(&token) {
105 let id = self.id_to_token.len();
106 self.token_to_id.insert(token.clone(), id);
107 self.id_to_token.push(token);
108 }
109 }
110
111 pub fn add_special_token(&mut self, token: String) {
113 if !self.token_to_id.contains_key(&token) {
114 let id = self.id_to_token.len();
115 self.token_to_id.insert(token.clone(), id);
116 self.special_tokens.insert(token.clone(), id);
117 self.id_to_token.push(token);
118 }
119 }
120
121 pub fn token_to_id(&self, token: &str) -> usize {
123 self.token_to_id
124 .get(token)
125 .copied()
126 .unwrap_or_else(|| self.unk_id())
127 }
128
129 pub fn id_to_token(&self, id: usize) -> Option<&str> {
131 self.id_to_token.get(id).map(|s| s.as_str())
132 }
133
134 pub fn unk_id(&self) -> usize {
136 self.special_tokens.get("<UNK>").copied().unwrap_or(0)
137 }
138
139 pub fn pad_id(&self) -> usize {
141 self.special_tokens.get("<PAD>").copied().unwrap_or(1)
142 }
143
144 pub fn sos_id(&self) -> usize {
146 self.special_tokens.get("<SOS>").copied().unwrap_or(2)
147 }
148
149 pub fn eos_id(&self) -> usize {
151 self.special_tokens.get("<EOS>").copied().unwrap_or(3)
152 }
153
154 pub fn len(&self) -> usize {
156 self.id_to_token.len()
157 }
158
159 pub fn is_empty(&self) -> bool {
160 self.id_to_token.is_empty()
161 }
162
163 fn simple_tokenize(text: &str) -> Vec<String> {
165 text.split_whitespace().map(|s| s.to_lowercase()).collect()
166 }
167
168 pub fn encode(&self, text: &str) -> Vec<usize> {
170 Self::simple_tokenize(text)
171 .into_iter()
172 .map(|token| self.token_to_id(&token))
173 .collect()
174 }
175
176 pub fn decode(&self, ids: &[usize]) -> String {
178 ids.iter()
179 .filter_map(|&id| self.id_to_token(id))
180 .filter(|&token| !self.special_tokens.contains_key(token) || token == "<UNK>")
181 .collect::<Vec<_>>()
182 .join(" ")
183 }
184}
185
186impl Default for Vocabulary {
187 fn default() -> Self {
188 Self::new()
189 }
190}
191
192pub struct TextClassificationDataset {
194 texts: Vec<String>,
195 labels: Vec<usize>,
196 vocabulary: Vocabulary,
197 max_length: Option<usize>,
198 transform: Option<Box<dyn Transform<TextSequence, Output = Tensor<f32>>>>,
199}
200
201impl TextClassificationDataset {
202 pub fn new(texts: Vec<String>, labels: Vec<usize>) -> Result<Self> {
204 if texts.len() != labels.len() {
205 return Err(TorshError::InvalidArgument(
206 "Number of texts must match number of labels".to_string(),
207 ));
208 }
209
210 let mut vocabulary = Vocabulary::new();
211 vocabulary.build_from_texts(&texts, 1)?;
212
213 Ok(Self {
214 texts,
215 labels,
216 vocabulary,
217 max_length: None,
218 transform: None,
219 })
220 }
221
222 pub fn with_max_length(mut self, max_length: usize) -> Self {
224 self.max_length = Some(max_length);
225 self
226 }
227
228 pub fn with_transform<T>(mut self, transform: T) -> Self
230 where
231 T: Transform<TextSequence, Output = Tensor<f32>> + 'static,
232 {
233 self.transform = Some(Box::new(transform));
234 self
235 }
236
237 pub fn vocabulary(&self) -> &Vocabulary {
239 &self.vocabulary
240 }
241
242 pub fn num_classes(&self) -> usize {
244 self.labels.iter().max().map(|&x| x + 1).unwrap_or(0)
245 }
246}
247
248impl Dataset for TextClassificationDataset {
249 type Item = (Tensor<f32>, usize);
250
251 fn len(&self) -> usize {
252 self.texts.len()
253 }
254
255 fn get(&self, index: usize) -> Result<Self::Item> {
256 if index >= self.texts.len() {
257 return Err(TorshError::IndexError {
258 index,
259 size: self.texts.len(),
260 });
261 }
262
263 let text = &self.texts[index];
264 let label = self.labels[index];
265
266 let token_ids = self.vocabulary.encode(text);
268 let tokens = Vocabulary::simple_tokenize(text);
269
270 let mut sequence = TextSequence::new(text.clone())
271 .with_tokens(tokens)
272 .with_token_ids(token_ids);
273
274 if let Some(max_len) = self.max_length {
276 if let Some(ref mut token_ids) = sequence.token_ids {
277 if token_ids.len() > max_len {
278 token_ids.truncate(max_len);
279 } else {
280 let pad_id = self.vocabulary.pad_id();
282 token_ids.resize(max_len, pad_id);
283 }
284 }
285 }
286
287 let tensor = if let Some(ref transform) = self.transform {
288 transform.transform(sequence)?
289 } else {
290 TokenIdsToTensor.transform(sequence)?
292 };
293
294 Ok((tensor, label))
295 }
296}
297
298pub struct TextFileDataset {
300 files: Vec<(PathBuf, usize)>,
301 classes: Vec<String>,
302 vocabulary: Vocabulary,
303 max_length: Option<usize>,
304 transform: Option<Box<dyn Transform<TextSequence, Output = Tensor<f32>>>>,
305}
306
307impl TextFileDataset {
308 pub fn new<P: AsRef<Path>>(root: P) -> Result<Self> {
310 let root = root.as_ref().to_path_buf();
311
312 if !root.exists() {
313 return Err(TorshError::IoError(format!(
314 "Directory does not exist: {root:?}"
315 )));
316 }
317
318 let mut classes = Vec::new();
319 let mut files = Vec::new();
320 let mut all_texts = Vec::new();
321
322 for entry in std::fs::read_dir(&root).map_err(|e| TorshError::IoError(e.to_string()))? {
324 let entry = entry.map_err(|e| TorshError::IoError(e.to_string()))?;
325 let path = entry.path();
326
327 if path.is_dir() {
328 let class_name = path
329 .file_name()
330 .and_then(|n| n.to_str())
331 .ok_or_else(|| TorshError::IoError("Invalid class directory name".to_string()))?
332 .to_string();
333
334 let class_idx = classes.len();
335 classes.push(class_name);
336
337 for file_entry in
339 std::fs::read_dir(&path).map_err(|e| TorshError::IoError(e.to_string()))?
340 {
341 let file_entry = file_entry.map_err(|e| TorshError::IoError(e.to_string()))?;
342 let file_path = file_entry.path();
343
344 if Self::is_text_file(&file_path) {
345 files.push((file_path.clone(), class_idx));
346
347 if let Ok(content) = std::fs::read_to_string(&file_path) {
349 all_texts.push(content);
350 }
351 }
352 }
353 }
354 }
355
356 let mut vocabulary = Vocabulary::new();
358 vocabulary.build_from_texts(&all_texts, 2)?;
359
360 Ok(Self {
361 files,
362 classes,
363 vocabulary,
364 max_length: None,
365 transform: None,
366 })
367 }
368
369 fn is_text_file(path: &Path) -> bool {
371 if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) {
372 matches!(
373 extension.to_lowercase().as_str(),
374 "txt" | "text" | "md" | "rst" | "csv" | "json"
375 )
376 } else {
377 false
378 }
379 }
380
381 pub fn with_max_length(mut self, max_length: usize) -> Self {
383 self.max_length = Some(max_length);
384 self
385 }
386
387 pub fn with_transform<T>(mut self, transform: T) -> Self
389 where
390 T: Transform<TextSequence, Output = Tensor<f32>> + 'static,
391 {
392 self.transform = Some(Box::new(transform));
393 self
394 }
395
396 pub fn classes(&self) -> &[String] {
398 &self.classes
399 }
400
401 pub fn vocabulary(&self) -> &Vocabulary {
403 &self.vocabulary
404 }
405}
406
407impl Dataset for TextFileDataset {
408 type Item = (Tensor<f32>, usize);
409
410 fn len(&self) -> usize {
411 self.files.len()
412 }
413
414 fn get(&self, index: usize) -> Result<Self::Item> {
415 if index >= self.files.len() {
416 return Err(TorshError::IndexError {
417 index,
418 size: self.files.len(),
419 });
420 }
421
422 let (ref path, class_idx) = self.files[index];
423
424 let text = std::fs::read_to_string(path)
426 .map_err(|e| TorshError::IoError(format!("Failed to read file {path:?}: {e}")))?;
427
428 let token_ids = self.vocabulary.encode(&text);
430 let tokens = Vocabulary::simple_tokenize(&text);
431
432 let mut sequence = TextSequence::new(text)
433 .with_tokens(tokens)
434 .with_token_ids(token_ids);
435
436 if let Some(max_len) = self.max_length {
438 if let Some(ref mut token_ids) = sequence.token_ids {
439 if token_ids.len() > max_len {
440 token_ids.truncate(max_len);
441 } else {
442 let pad_id = self.vocabulary.pad_id();
444 token_ids.resize(max_len, pad_id);
445 }
446 }
447 }
448
449 let tensor = if let Some(ref transform) = self.transform {
450 transform.transform(sequence)?
451 } else {
452 TokenIdsToTensor.transform(sequence)?
454 };
455
456 Ok((tensor, class_idx))
457 }
458}
459
460pub struct TokenIdsToTensor;
462
463impl Transform<TextSequence> for TokenIdsToTensor {
464 type Output = Tensor<f32>;
465
466 fn transform(&self, input: TextSequence) -> Result<Self::Output> {
467 if let Some(token_ids) = input.token_ids {
468 let len = token_ids.len();
470 let data: Vec<f32> = token_ids.into_iter().map(|id| id as f32).collect();
471 Tensor::from_data(data, vec![len], torsh_core::device::DeviceType::Cpu)
472 } else {
473 Err(TorshError::InvalidArgument(
474 "TextSequence must have token_ids for tensor conversion".to_string(),
475 ))
476 }
477 }
478}
479
480pub mod transforms {
482 use super::*;
483 use crate::transforms::Transform;
484
485 pub struct ToLowercase;
487
488 impl Transform<TextSequence> for ToLowercase {
489 type Output = TextSequence;
490
491 fn transform(&self, mut input: TextSequence) -> Result<Self::Output> {
492 input.text = input.text.to_lowercase();
493 if let Some(ref mut tokens) = input.tokens {
494 for token in tokens.iter_mut() {
495 *token = token.to_lowercase();
496 }
497 }
498 Ok(input)
499 }
500 }
501
502 pub struct RemovePunctuation;
504
505 impl Transform<TextSequence> for RemovePunctuation {
506 type Output = TextSequence;
507
508 fn transform(&self, mut input: TextSequence) -> Result<Self::Output> {
509 input.text = input
510 .text
511 .chars()
512 .filter(|c| c.is_alphanumeric() || c.is_whitespace())
513 .collect();
514
515 if let Some(ref mut tokens) = input.tokens {
516 for token in tokens.iter_mut() {
517 *token = token.chars().filter(|c| c.is_alphanumeric()).collect();
518 }
519 tokens.retain(|token| !token.is_empty());
521 }
522 Ok(input)
523 }
524 }
525
526 pub struct FixedLength {
528 length: usize,
529 pad_token_id: usize,
530 }
531
532 impl FixedLength {
533 pub fn new(length: usize, pad_token_id: usize) -> Self {
534 Self {
535 length,
536 pad_token_id,
537 }
538 }
539 }
540
541 impl Transform<TextSequence> for FixedLength {
542 type Output = TextSequence;
543
544 fn transform(&self, mut input: TextSequence) -> Result<Self::Output> {
545 if let Some(ref mut token_ids) = input.token_ids {
546 if token_ids.len() > self.length {
547 token_ids.truncate(self.length);
548 } else {
549 token_ids.resize(self.length, self.pad_token_id);
550 }
551 }
552
553 if let Some(ref mut tokens) = input.tokens {
554 if tokens.len() > self.length {
555 tokens.truncate(self.length);
556 } else {
557 tokens.resize(self.length, "<PAD>".to_string());
558 }
559 }
560
561 Ok(input)
562 }
563 }
564
565 pub struct AddSpecialTokens {
567 sos_token_id: usize,
568 eos_token_id: usize,
569 }
570
571 impl AddSpecialTokens {
572 pub fn new(sos_token_id: usize, eos_token_id: usize) -> Self {
573 Self {
574 sos_token_id,
575 eos_token_id,
576 }
577 }
578 }
579
580 impl Transform<TextSequence> for AddSpecialTokens {
581 type Output = TextSequence;
582
583 fn transform(&self, mut input: TextSequence) -> Result<Self::Output> {
584 if let Some(ref mut token_ids) = input.token_ids {
585 token_ids.insert(0, self.sos_token_id);
586 token_ids.push(self.eos_token_id);
587 }
588
589 if let Some(ref mut tokens) = input.tokens {
590 tokens.insert(0, "<SOS>".to_string());
591 tokens.push("<EOS>".to_string());
592 }
593
594 Ok(input)
595 }
596 }
597
598 pub struct NGrams {
600 n: usize,
601 }
602
603 impl NGrams {
604 pub fn new(n: usize) -> Self {
608 assert!(n > 0, "n must be positive");
609 Self { n }
610 }
611
612 pub fn try_new(n: usize) -> Result<Self> {
615 crate::utils::validate_positive(n, "n")?;
616 Ok(Self { n })
617 }
618 }
619
620 impl Transform<TextSequence> for NGrams {
621 type Output = TextSequence;
622
623 fn transform(&self, input: TextSequence) -> Result<Self::Output> {
624 let tokens = if let Some(tokens) = input.tokens {
625 tokens
626 } else {
627 Vocabulary::simple_tokenize(&input.text)
628 };
629
630 let mut ngrams = Vec::new();
631 for window in tokens.windows(self.n) {
632 let ngram = window.join("_");
633 ngrams.push(ngram);
634 }
635
636 let ngram_text = ngrams.join(" ");
637 Ok(TextSequence::new(ngram_text).with_tokens(ngrams))
638 }
639 }
640
641 pub struct CharTokenizer;
643
644 impl Transform<TextSequence> for CharTokenizer {
645 type Output = TextSequence;
646
647 fn transform(&self, input: TextSequence) -> Result<Self::Output> {
648 let chars: Vec<String> = input.text.chars().map(|c| c.to_string()).collect();
649 Ok(input.with_tokens(chars))
650 }
651 }
652
653 pub struct SimpleBPE {
655 #[allow(dead_code)]
656 vocab_size: usize,
657 }
658
659 impl SimpleBPE {
660 pub fn new(vocab_size: usize) -> Self {
661 Self { vocab_size }
662 }
663 }
664
665 impl Transform<TextSequence> for SimpleBPE {
666 type Output = TextSequence;
667
668 fn transform(&self, input: TextSequence) -> Result<Self::Output> {
669 let mut tokens = Vec::new();
672
673 for word in input.text.split_whitespace() {
674 if word.len() <= 3 {
676 tokens.push(word.to_string());
677 } else {
678 let chars: Vec<char> = word.chars().collect();
680 for chunk in chars.chunks(2) {
681 let subword: String = chunk.iter().collect();
682 tokens.push(subword);
683 }
684 }
685 }
686
687 Ok(input.with_tokens(tokens))
688 }
689 }
690}
691
692pub mod datasets {
694 use super::*;
695
696 pub struct IMDB {
704 root: PathBuf,
705 split: String,
706 vocabulary: Vocabulary,
707 samples: Vec<(String, usize)>, transform: Option<Box<dyn Transform<TextSequence, Output = Tensor<f32>>>>,
709 }
710
711 impl IMDB {
712 pub fn new<P: AsRef<Path>>(root: P, split: &str) -> Result<Self> {
722 let root = root.as_ref().to_path_buf();
723 let split_dir = root.join(split);
724
725 if !split_dir.is_dir() {
726 return Err(TorshError::IoError(format!(
727 "IMDB: split directory not found: {split_dir:?} (expected aclImdb layout \
728 <root>/<split>/{{pos,neg}}/*.txt)"
729 )));
730 }
731
732 let mut samples: Vec<(String, usize)> = Vec::new();
733 for (class_dir_name, label) in [("pos", 1usize), ("neg", 0usize)] {
734 let class_dir = split_dir.join(class_dir_name);
735 if !class_dir.is_dir() {
736 continue;
739 }
740
741 let mut review_paths: Vec<PathBuf> = std::fs::read_dir(&class_dir)
742 .map_err(|e| TorshError::IoError(format!("Failed to read {class_dir:?}: {e}")))?
743 .filter_map(|entry| entry.ok().map(|e| e.path()))
744 .filter(|p| p.extension().and_then(|ext| ext.to_str()) == Some("txt"))
745 .collect();
746 review_paths.sort();
748
749 for path in review_paths {
750 let text = std::fs::read_to_string(&path).map_err(|e| {
751 TorshError::IoError(format!("Failed to read {path:?}: {e}"))
752 })?;
753 samples.push((text, label));
754 }
755 }
756
757 if samples.is_empty() {
758 return Err(TorshError::IoError(format!(
759 "IMDB: no .txt review files found under {split_dir:?}/{{pos,neg}}; \
760 download the aclImdb corpus and point `root` at its extracted directory"
761 )));
762 }
763
764 let texts: Vec<String> = samples.iter().map(|(text, _)| text.clone()).collect();
765 let mut vocabulary = Vocabulary::new();
766 vocabulary.build_from_texts(&texts, 1)?;
767
768 Ok(Self {
769 root,
770 split: split.to_string(),
771 vocabulary,
772 samples,
773 transform: None,
774 })
775 }
776
777 pub fn root(&self) -> &Path {
779 &self.root
780 }
781
782 pub fn split(&self) -> &str {
784 &self.split
785 }
786
787 pub fn with_transform<T>(mut self, transform: T) -> Self
789 where
790 T: Transform<TextSequence, Output = Tensor<f32>> + 'static,
791 {
792 self.transform = Some(Box::new(transform));
793 self
794 }
795
796 pub fn vocabulary(&self) -> &Vocabulary {
798 &self.vocabulary
799 }
800 }
801
802 impl Dataset for IMDB {
803 type Item = (Tensor<f32>, usize);
804
805 fn len(&self) -> usize {
806 self.samples.len()
807 }
808
809 fn get(&self, index: usize) -> Result<Self::Item> {
810 if index >= self.samples.len() {
811 return Err(TorshError::IndexError {
812 index,
813 size: self.samples.len(),
814 });
815 }
816
817 let (ref text, label) = self.samples[index];
818
819 let token_ids = self.vocabulary.encode(text);
821 let tokens = Vocabulary::simple_tokenize(text);
822
823 let sequence = TextSequence::new(text.clone())
824 .with_tokens(tokens)
825 .with_token_ids(token_ids);
826
827 let tensor = if let Some(ref transform) = self.transform {
828 transform.transform(sequence)?
829 } else {
830 TokenIdsToTensor.transform(sequence)?
831 };
832
833 Ok((tensor, label))
834 }
835 }
836}
837
838#[cfg(test)]
839mod tests {
840 use super::*;
841
842 #[test]
843 fn test_vocabulary() {
844 let texts = vec![
845 "hello world".to_string(),
846 "world hello".to_string(),
847 "foo bar".to_string(),
848 ];
849
850 let mut vocab = Vocabulary::new();
851 vocab.build_from_texts(&texts, 1).unwrap();
852
853 assert!(vocab.len() >= 6); let ids = vocab.encode("hello world");
858 let decoded = vocab.decode(&ids);
859 assert_eq!(decoded, "hello world");
860 }
861
862 #[test]
863 fn test_text_sequence() {
864 let seq = TextSequence::new("hello world".to_string())
865 .with_tokens(vec!["hello".to_string(), "world".to_string()])
866 .with_token_ids(vec![1, 2]);
867
868 assert_eq!(seq.len(), 2);
869 assert!(!seq.is_empty());
870 }
871
872 #[test]
873 fn test_text_classification_dataset() {
874 let texts = vec![
875 "positive example".to_string(),
876 "negative example".to_string(),
877 ];
878 let labels = vec![1, 0];
879
880 let dataset = TextClassificationDataset::new(texts, labels).unwrap();
881 assert_eq!(dataset.len(), 2);
882 assert_eq!(dataset.num_classes(), 2);
883
884 let (tensor, label) = dataset.get(0).unwrap();
885 assert_eq!(label, 1);
886 assert!(tensor.ndim() > 0);
887 }
888
889 #[test]
890 fn test_token_ids_to_tensor() {
891 let seq = TextSequence::new("test".to_string()).with_token_ids(vec![1, 2, 3]);
892
893 let transform = TokenIdsToTensor;
894 let result = transform.transform(seq).unwrap();
895
896 assert_eq!(result.shape().dims(), &[3]);
897 let data = result.to_vec().unwrap();
898 assert_eq!(data, vec![1.0, 2.0, 3.0]);
899 }
900
901 #[test]
902 fn test_text_transforms() {
903 use transforms::*;
904
905 let seq = TextSequence::new("Hello, World!".to_string())
906 .with_tokens(vec!["Hello,".to_string(), "World!".to_string()]);
907
908 let lowercase = ToLowercase;
910 let result = lowercase.transform(seq.clone()).unwrap();
911 assert_eq!(result.text, "hello, world!");
912
913 let remove_punct = RemovePunctuation;
915 let result = remove_punct.transform(seq.clone()).unwrap();
916 assert_eq!(result.text, "Hello World");
917
918 let seq_with_ids = seq.with_token_ids(vec![1, 2]);
920 let fixed_len = FixedLength::new(4, 0);
921 let result = fixed_len.transform(seq_with_ids).unwrap();
922 assert_eq!(result.token_ids.unwrap(), vec![1, 2, 0, 0]);
923
924 let add_special = AddSpecialTokens::new(100, 101);
926 let seq_with_ids = TextSequence::new("test".to_string()).with_token_ids(vec![1, 2]);
927 let result = add_special.transform(seq_with_ids).unwrap();
928 assert_eq!(result.token_ids.unwrap(), vec![100, 1, 2, 101]);
929 }
930
931 #[test]
932 fn test_ngrams() {
933 use transforms::*;
934
935 let seq = TextSequence::new("the quick brown fox".to_string()).with_tokens(vec![
936 "the".to_string(),
937 "quick".to_string(),
938 "brown".to_string(),
939 "fox".to_string(),
940 ]);
941
942 let bigrams = NGrams::new(2);
943 let result = bigrams.transform(seq).unwrap();
944
945 let expected_tokens = vec![
946 "the_quick".to_string(),
947 "quick_brown".to_string(),
948 "brown_fox".to_string(),
949 ];
950 assert_eq!(result.tokens.unwrap(), expected_tokens);
951 }
952
953 #[test]
954 fn test_imdb_dataset() {
955 use datasets::*;
956
957 let tmp = tempfile::tempdir().expect("failed to create temp dir");
961 let train_dir = tmp.path().join("train");
962 let pos_dir = train_dir.join("pos");
963 let neg_dir = train_dir.join("neg");
964 std::fs::create_dir_all(&pos_dir).expect("create pos dir");
965 std::fs::create_dir_all(&neg_dir).expect("create neg dir");
966
967 std::fs::write(pos_dir.join("0_9.txt"), "This movie is great!").expect("write pos review");
968 std::fs::write(
969 pos_dir.join("1_10.txt"),
970 "Amazing cinematography and acting.",
971 )
972 .expect("write pos review");
973 std::fs::write(neg_dir.join("0_1.txt"), "Terrible film, waste of time.")
974 .expect("write neg review");
975 std::fs::write(neg_dir.join("1_2.txt"), "Boring and predictable plot.")
976 .expect("write neg review");
977
978 let dataset = IMDB::new(tmp.path(), "train").unwrap();
979 assert_eq!(dataset.len(), 4);
980 assert_eq!(dataset.root(), tmp.path());
981 assert_eq!(dataset.split(), "train");
982
983 let (tensor, label) = dataset.get(0).unwrap();
985 assert_eq!(label, 1); assert!(tensor.ndim() > 0);
987
988 let (_, last_label) = dataset.get(dataset.len() - 1).unwrap();
990 assert_eq!(last_label, 0);
991 }
992
993 #[test]
994 fn test_imdb_dataset_missing_layout_errors() {
995 use datasets::*;
996
997 let tmp = tempfile::tempdir().expect("failed to create temp dir");
1000 let result = IMDB::new(tmp.path(), "train");
1001 assert!(result.is_err());
1002 }
1003
1004 #[test]
1005 fn test_char_tokenizer() {
1006 use transforms::*;
1007
1008 let seq = TextSequence::new("abc".to_string());
1009 let char_tokenizer = CharTokenizer;
1010 let result = char_tokenizer.transform(seq).unwrap();
1011
1012 assert_eq!(
1013 result.tokens.unwrap(),
1014 vec!["a".to_string(), "b".to_string(), "c".to_string()]
1015 );
1016 }
1017
1018 #[test]
1019 fn test_simple_bpe() {
1020 use transforms::*;
1021
1022 let seq = TextSequence::new("hello world".to_string());
1023 let bpe = SimpleBPE::new(1000);
1024 let result = bpe.transform(seq).unwrap();
1025
1026 assert!(result.tokens.is_some());
1028 assert!(!result.tokens.unwrap().is_empty());
1029 }
1030}