1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
//! For identifying text / analyzing files
#[cfg(not(target_arch = "wasm32"))]
use {
rayon::iter::{IntoParallelRefIterator, ParallelIterator},
std::{fs, str},
};
pub mod bytes;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::Serialize;
use crate::Data;
use crate::DATA;
// this is REGEX_DATA and BOUNDARYLESS_REGEX_DATA
include!(concat!(env!("OUT_DIR"), "/regex_data.rs"));
/// structure containing the text and it's possible identification.
#[derive(Serialize, Debug)]
pub struct Match {
pub text: String,
pub data: Data,
}
impl Match {
pub fn new(text: String, data: Data) -> Match {
Match { text, data }
}
}
pub struct Identifier {
/// Keep Data having minimum Rarity of supplied `min_rarity`
pub min_rarity: f32,
/// Keep Data having maximum Rarity of supplied `max_rarity`
pub max_rarity: f32,
/// Only include the Data which have at least one of the specified `tags`
pub tags: Vec<String>,
/// Only include Data which doesn't have any of the `excluded_tags`
pub exclude_tags: Vec<String>,
/// Use boundaryless regex
pub boundaryless: bool,
/// Scan files having supplied text as filename
pub file_support: bool,
}
impl Identifier {
#[inline]
pub fn min_rarity(mut self, rarity: f32) -> Self {
self.min_rarity = rarity;
self
}
#[inline]
pub fn max_rarity(mut self, rarity: f32) -> Self {
self.max_rarity = rarity;
self
}
#[inline]
pub fn include_tags(mut self, tags: &[String]) -> Self {
self.tags.extend_from_slice(tags);
self
}
#[inline]
pub fn exclude_tags(mut self, tags: &[String]) -> Self {
self.exclude_tags.extend_from_slice(tags);
self
}
#[inline]
pub fn boundaryless(mut self, boundaryless: bool) -> Self {
self.boundaryless = boundaryless;
self
}
#[inline]
pub fn file_support(mut self, support: bool) -> Self {
self.file_support = support;
self
}
}
impl Default for Identifier {
fn default() -> Self {
Identifier {
min_rarity: 0.0,
max_rarity: 1.0,
tags: vec![],
exclude_tags: vec![],
boundaryless: false,
file_support: false,
}
}
}
// Identifier implementation
#[cfg(not(target_arch = "wasm32"))]
impl Identifier {
/// Identify the given text.
///
/// This will read strings from file with text as filename if `file_support` is `true` and the file exists
///
/// Finds all possible identifications.
///
/// # Arguments
///
/// * text: &str - text which we want to identify
///
/// # Examples
///
/// ```
/// let identifier = lemmeknow::Identifier::default();
/// let result = identifier.identify("UC11L3JDgDQMyH8iolKkVZ4w");
/// assert_eq!(result[0].data.name, "YouTube Channel ID");
/// ```
///
pub fn identify(&self, text: &str) -> Vec<Match> {
let regexes = if self.boundaryless {
&BOUNDARYLESS_REGEX
} else {
®EX
};
if self.file_support && is_file(text) {
let strings = read_file_to_strings(text);
strings
.par_iter()
.map(|text| {
DATA.iter()
.enumerate()
.filter_map(|(i, e)| {
if is_valid_filter(self, e) && regexes[i].is_match(text) {
Some(Match::new(text.to_owned(), e.clone()))
} else {
None
}
})
.collect::<Vec<Match>>()
})
.flatten()
.collect()
} else {
// iter has almost same or sometimes better performance than par_iter for single text!
DATA.iter()
.enumerate()
.filter_map(|(i, e)| {
if is_valid_filter(self, e) && regexes[i].is_match(text) {
Some(Match::new(text.to_owned(), e.clone()))
} else {
None
}
})
.collect::<Vec<Match>>()
}
}
/// This returns the first identification.
///
/// Due to how data is stored, this means that the returned result has the highest `rarity`.
///
/// # Arguments
///
/// * text: &str - text which we want to identify
///
/// # Examples
///
/// ```
/// let identifier = lemmeknow::Identifier::default();
/// let some_result = identifier.first_match("8888888888");
/// let not_gonna_find = identifier.first_match("a friend for swanandx");
///
/// assert_eq!(some_result.unwrap().data.name, "Phone Number");
/// assert!(not_gonna_find.is_none());
/// ```
///
pub fn first_match(&self, text: &str) -> Option<Match> {
let regexes = if self.boundaryless {
&BOUNDARYLESS_REGEX
} else {
®EX
};
for (i, x) in DATA
.iter()
.enumerate()
.filter(|(_, x)| is_valid_filter(self, x))
{
// only consider the regex which compiles!
if regexes[i].is_match(text) {
return Some(Match::new(text.to_owned(), x.clone()));
}
}
None
}
}
// Identifier implementation for wasm
#[cfg(target_arch = "wasm32")]
impl Identifier {
// There is no file system on the web, so we are not reading strings from file.
// let the user perform the I/O and read the file, then pass the content of it.
pub fn identify(&self, text: &[String]) -> Vec<Match> {
let regexes = if self.boundaryless {
&BOUNDARYLESS_REGEX
} else {
®EX
};
DATA.iter()
.enumerate()
.filter_map(|(i, e)| {
if is_valid_filter(self, e) && regexes[i].is_match(text) {
Some(Match::new(text.to_owned(), e.clone()))
} else {
None
}
})
.collect::<Vec<Match>>()
}
}
// Output Implementation
impl Identifier {
/// Convert [`Vec<Match>`] to JSON
///
/// Returns prettified JSON string.
///
/// Helpful if you want to convert possible identifications to JSON
/// for using in web APIs or something else.
///
/// # Arguments
///
/// * result: &[Match] - Reference to `Vec<Match>`.
///
/// # Examples
///
/// ```
/// use lemmeknow::Identifier;
/// let identifier = Identifier::default();
/// let result = identifier.identify("UC11L3JDgDQMyH8iolKkVZ4w");
/// let result_in_json = Identifier::to_json(&result);
/// println!("{result_in_json}");
/// ```
///
#[inline]
pub fn to_json(result: &[Match]) -> String {
serde_json::to_string_pretty(result).unwrap_or_default()
}
}
// helper functions
// TODO: try #[inline]
#[cfg(not(target_arch = "wasm32"))]
fn is_file(name: &str) -> bool {
if let Ok(s) = fs::metadata(name) {
s.is_file()
} else {
false
}
}
fn is_valid_filter(configs: &Identifier, regex_data: &Data) -> bool {
if regex_data.rarity < configs.min_rarity {
return false;
}
if regex_data.rarity > configs.max_rarity {
return false;
}
if configs
.tags
.iter()
.any(|y| !regex_data.tags.iter().any(|x| x == y))
{
return false;
}
if configs
.exclude_tags
.iter()
.any(|y| regex_data.tags.iter().any(|x| x == y))
{
return false;
}
true
}
#[cfg(not(target_arch = "wasm32"))]
fn read_file_to_strings(filename: &str) -> Vec<String> {
let file = fs::read(filename).expect("File not found");
let mut printable_text: Vec<String> = Vec::new();
let mut buffer: Vec<u8> = Vec::new();
let mut use_current_buffer = false;
//we only need the human readable strings from the file.
for character in file {
if character.is_ascii_graphic() {
// Doesn't consider whitespace as a graphic!
use_current_buffer = true;
buffer.push(character);
} else if use_current_buffer {
// If the char isn't ascii graphic, that means this is the end for our string which we are interested in
// string with length less than 4 most likely won't be of our use.
// If it has length more than 4, then push it to our `printable_text`
if buffer.len() >= 4 {
printable_text.push(
String::from_utf8(buffer.clone()).expect("failed to convert u8 to string"),
);
}
// Clear the buffer so that current contents of it won't affect the next string.
buffer.clear();
// We set this to false because we don't want to use buffer until we get a ascii graphic!
use_current_buffer = false;
}
}
printable_text.push(String::from_utf8(buffer).expect("failed to convert u8 to string"));
printable_text
}