use ahash::{HashMap, HashMapExt, HashSet, HashSetExt};
use dashmap::DashMap;
#[cfg(feature = "progress-bars")]
use indicatif::ParallelProgressIterator;
use rayon::prelude::*;
use smallvec::SmallVec;
use crate::NGRAM_CONST_KEY;
pub type NgramKey = SmallVec<[u32; NGRAM_CONST_KEY]>;
pub fn count_ngrams(tokens: &[u32], ngram_range: &[usize]) -> HashMap<NgramKey, usize> {
let max_possible_ngrams: usize = ngram_range
.iter()
.map(|&n| tokens.len().saturating_sub(n.saturating_sub(1)))
.sum();
let estimated_capacity = (max_possible_ngrams / 3).max(16);
let mut ngram_counter = HashMap::with_capacity(estimated_capacity);
for &n in ngram_range {
if n == 0 || n > tokens.len() {
continue;
}
for window in tokens.windows(n) {
let key = SmallVec::from_slice(window);
ngram_counter
.entry(key)
.and_modify(|count| *count += 1)
.or_insert(1);
}
}
ngram_counter
}
pub fn unique_ngrams(tokens: &[u32], ngram_range: &[usize]) -> HashSet<NgramKey> {
let max_possible_ngrams: usize = ngram_range
.iter()
.map(|&n| tokens.len().saturating_sub(n.saturating_sub(1)))
.sum();
let estimated_capacity = (max_possible_ngrams / 2).max(16);
let mut unique = HashSet::with_capacity(estimated_capacity);
for &n in ngram_range {
if n == 0 || n > tokens.len() {
continue;
}
for window in tokens.windows(n) {
unique.insert(SmallVec::from_slice(window));
}
}
unique
}
#[cfg(feature = "progress-bars")]
pub fn build_vocabulary(
tokenized_texts: &[Vec<u32>],
ngram_range: &[usize],
) -> DashMap<NgramKey, usize, ahash::RandomState> {
let vocab_df = DashMap::with_hasher(ahash::RandomState::default());
tokenized_texts.par_iter().progress().for_each(|tokens| {
let ngrams = unique_ngrams(tokens, ngram_range);
for ngram_key in ngrams {
vocab_df
.entry(ngram_key)
.and_modify(|df| *df += 1)
.or_insert(1);
}
});
vocab_df
}
#[cfg(not(feature = "progress-bars"))]
pub fn build_vocabulary(
tokenized_texts: &[Vec<u32>],
ngram_range: &[usize],
) -> DashMap<NgramKey, usize, ahash::RandomState> {
let vocab_df = DashMap::with_hasher(ahash::RandomState::default());
tokenized_texts.par_iter().for_each(|tokens| {
let ngrams = unique_ngrams(tokens, ngram_range);
for ngram_key in ngrams {
vocab_df
.entry(ngram_key)
.and_modify(|df| *df += 1)
.or_insert(1);
}
});
vocab_df
}