torsh-text 0.1.2

Natural language processing utilities for ToRSh deep learning framework
Documentation
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use scirs2_core::random::Random;
use std::io::{self, Write};
use torsh_text::prelude::*;
use torsh_text::TextAnalyzer;

#[derive(Debug)]
enum Command {
    Tokenize {
        text: String,
        method: String,
    },
    Preprocess {
        text: String,
        options: PreprocessingOptions,
    },
    Analyze {
        text: String,
    },
    Similarity {
        text1: String,
        text2: String,
    },
    Generate {
        prompt: String,
        length: usize,
    },
    Help,
    Quit,
}

#[derive(Debug)]
struct PreprocessingOptions {
    normalize: bool,
    clean_urls: bool,
    clean_emails: bool,
    clean_html: bool,
    lowercase: bool,
}

impl Default for PreprocessingOptions {
    fn default() -> Self {
        Self {
            normalize: true,
            clean_urls: true,
            clean_emails: true,
            clean_html: true,
            lowercase: true,
        }
    }
}

fn parse_command(input: &str) -> Command {
    let parts: Vec<&str> = input.trim().split_whitespace().collect();

    if parts.is_empty() {
        return Command::Help;
    }

    match parts[0].to_lowercase().as_str() {
        "tokenize" | "tok" => {
            if parts.len() < 3 {
                println!("Usage: tokenize <method> <text>");
                println!("Methods: whitespace, char, bpe");
                return Command::Help;
            }
            Command::Tokenize {
                method: parts[1].to_string(),
                text: parts[2..].join(" "),
            }
        }
        "preprocess" | "prep" => {
            if parts.len() < 2 {
                println!("Usage: preprocess <text>");
                return Command::Help;
            }
            Command::Preprocess {
                text: parts[1..].join(" "),
                options: PreprocessingOptions::default(),
            }
        }
        "analyze" | "stats" => {
            if parts.len() < 2 {
                println!("Usage: analyze <text>");
                return Command::Help;
            }
            Command::Analyze {
                text: parts[1..].join(" "),
            }
        }
        "similarity" | "sim" => {
            if parts.len() < 3 {
                println!("Usage: similarity <text1> | <text2>");
                println!("Use | to separate the two texts");
                return Command::Help;
            }
            let full_text = parts[1..].join(" ");
            let texts: Vec<&str> = full_text.split(" | ").collect();
            if texts.len() != 2 {
                println!("Please separate texts with ' | '");
                return Command::Help;
            }
            Command::Similarity {
                text1: texts[0].trim().to_string(),
                text2: texts[1].trim().to_string(),
            }
        }
        "generate" | "gen" => {
            if parts.len() < 3 {
                println!("Usage: generate <length> <prompt>");
                return Command::Help;
            }
            if let Ok(length) = parts[1].parse::<usize>() {
                Command::Generate {
                    length,
                    prompt: parts[2..].join(" "),
                }
            } else {
                println!("Invalid length parameter");
                Command::Help
            }
        }
        "help" | "h" | "?" => Command::Help,
        "quit" | "exit" | "q" => Command::Quit,
        _ => {
            println!("Unknown command: {}", parts[0]);
            Command::Help
        }
    }
}

fn execute_tokenize(text: &str, method: &str) -> Result<()> {
    println!("\n🔤 Tokenizing with method: {}", method);
    println!("📝 Input: {}", text);

    let tokens = match method.to_lowercase().as_str() {
        "whitespace" | "ws" => {
            let tokenizer = WhitespaceTokenizer::new();
            tokenizer.tokenize(text)?
        }
        "char" | "character" => {
            let tokenizer = CharTokenizer::new(None);
            tokenizer.tokenize(text)?
        }
        "bpe" => {
            let tokenizer = BPETokenizer::new();
            tokenizer.tokenize(text)?
        }
        _ => {
            println!("❌ Unknown tokenization method: {}", method);
            println!("Available methods: whitespace, char, bpe");
            return Ok(());
        }
    };

    println!("🎯 Tokens ({} total):", tokens.len());
    for (i, token) in tokens.iter().enumerate() {
        println!("  {}. '{}'", i + 1, token);
    }

    Ok(())
}

fn execute_preprocess(text: &str, options: &PreprocessingOptions) -> Result<()> {
    println!("\n🧹 Preprocessing text...");
    println!("📝 Input: {}", text);

    let mut pipeline = TextPreprocessingPipeline::new();

    if options.normalize {
        pipeline = pipeline.with_normalization(TextNormalizer::default());
    }

    if options.clean_urls || options.clean_emails || options.clean_html {
        let cleaner = TextCleaner::new()
            .remove_urls(options.clean_urls)
            .remove_emails(options.clean_emails)
            .remove_html(options.clean_html);
        pipeline = pipeline.with_cleaning(cleaner);
    }

    if options.lowercase {
        pipeline = pipeline.add_custom_step(Box::new(CustomStep::new(
            |text: &str| text.to_lowercase(),
            "lowercase".to_string(),
        )));
    }

    let processed = pipeline.process_text(text)?;

    println!("✨ Processed: {}", processed);
    println!("📊 Options used:");
    println!("   • Normalize: {}", options.normalize);
    println!("   • Clean URLs: {}", options.clean_urls);
    println!("   • Clean emails: {}", options.clean_emails);
    println!("   • Clean HTML: {}", options.clean_html);
    println!("   • Lowercase: {}", options.lowercase);

    Ok(())
}

fn execute_analyze(text: &str) -> Result<()> {
    println!("\n📊 Analyzing text...");
    println!("📝 Input: {}", text);

    let analyzer = TextAnalyzer::default();
    let stats = analyzer.analyze(text)?;

    println!("📈 Text Statistics:");
    println!("   • Character count: {}", stats.char_count);
    println!("   • Word count: {}", stats.word_count);
    println!("   • Sentence count: {}", stats.sentence_count);
    println!("   • Average word length: {:.2}", stats.avg_word_length);
    println!(
        "   • Average sentence length: {:.2}",
        stats.avg_sentence_length
    );

    println!("   • Type-token ratio: {:.3}", stats.type_token_ratio);

    // N-gram analysis
    let extractor = NgramExtractor::new(2);
    let bigrams = extractor.extract_word_ngrams(text);

    if !bigrams.is_empty() {
        println!("🔗 Most common bigrams:");
        let mut bigram_counts: Vec<_> = bigrams.into_iter().collect();
        bigram_counts.sort_by(|a, b| b.1.cmp(&a.1));

        for (bigram, count) in bigram_counts.iter().take(5) {
            println!("   • '{}': {} times", bigram, count);
        }
    }

    Ok(())
}

fn execute_similarity(text1: &str, text2: &str) -> Result<()> {
    println!("\n🔍 Calculating text similarity...");
    println!("📝 Text 1: {}", text1);
    println!("📝 Text 2: {}", text2);

    let jaccard = TextSimilarity::jaccard_similarity(text1, text2);
    let dice = TextSimilarity::dice_similarity(text1, text2);
    let overlap = TextSimilarity::overlap_similarity(text1, text2);

    println!("📊 Similarity Scores:");
    println!("   • Jaccard similarity: {:.3}", jaccard);
    println!("   • Dice similarity: {:.3}", dice);
    println!("   • Overlap similarity: {:.3}", overlap);

    // Interpretation
    let avg_similarity = (jaccard + dice + overlap) / 3.0;
    let interpretation = match avg_similarity {
        x if x >= 0.8 => "Very High",
        x if x >= 0.6 => "High",
        x if x >= 0.4 => "Moderate",
        x if x >= 0.2 => "Low",
        _ => "Very Low",
    };

    println!(
        "🎯 Overall similarity: {:.3} ({})",
        avg_similarity, interpretation
    );

    Ok(())
}

fn execute_generate(prompt: &str, length: usize) -> Result<()> {
    println!("\n🎲 Generating text...");
    println!("📝 Prompt: {}", prompt);
    println!("📏 Target length: {} tokens", length);

    // Simple text generation (this is a demo - real generation would need a trained model)
    let words = vec![
        "the", "and", "to", "of", "a", "in", "is", "it", "you", "that", "he", "was", "for", "on",
        "are", "as", "with", "his", "they", "at", "be", "this", "have", "from", "or", "one", "had",
        "by", "word", "but", "what", "some", "we", "can", "out", "other", "were", "all", "there",
        "when",
    ];

    let mut generated = prompt.to_string();
    let mut rng = Random::seed(42);

    for _ in 0..length {
        let word = words[rng.gen_range(0..words.len())];
        generated.push(' ');
        generated.push_str(word);
    }

    println!("✨ Generated text:");
    println!("{}", generated);
    println!("\n⚠️  Note: This is a simple demo generator. For real text generation,");
    println!("   you would need a trained language model.");

    Ok(())
}

fn print_help() {
    println!("\n🚀 ToRSh Text Processing CLI");
    println!("===========================");
    println!("Available commands:");
    println!("  tokenize <method> <text>     - Tokenize text (methods: whitespace, char, bpe)");
    println!("  preprocess <text>            - Preprocess text with default options");
    println!("  analyze <text>               - Analyze text statistics and patterns");
    println!("  similarity <text1> | <text2> - Calculate similarity between two texts");
    println!("  generate <length> <prompt>   - Generate text from prompt (demo only)");
    println!("  help                         - Show this help message");
    println!("  quit                         - Exit the CLI");
    println!("\nExamples:");
    println!("  tokenize whitespace \"Hello world!\"");
    println!("  preprocess \"Visit https://example.com for more info!\"");
    println!("  analyze \"The quick brown fox jumps over the lazy dog.\"");
    println!("  similarity \"Hello world\" | \"Hello there\"");
    println!("  generate 5 \"Once upon a time\"");
}

fn print_welcome() {
    println!("🚀 Welcome to ToRSh Text Processing CLI!");
    println!("========================================");
    println!("This interactive tool demonstrates the capabilities of the torsh-text library.");
    println!("Type 'help' to see available commands or 'quit' to exit.");
    println!();
}

fn main() -> Result<()> {
    print_welcome();

    loop {
        print!("torsh-text> ");
        io::stdout().flush().unwrap();

        let mut input = String::new();
        match io::stdin().read_line(&mut input) {
            Ok(_) => {
                let command = parse_command(&input);

                match command {
                    Command::Tokenize { text, method } => {
                        if let Err(e) = execute_tokenize(&text, &method) {
                            println!("❌ Error: {}", e);
                        }
                    }
                    Command::Preprocess { text, options } => {
                        if let Err(e) = execute_preprocess(&text, &options) {
                            println!("❌ Error: {}", e);
                        }
                    }
                    Command::Analyze { text } => {
                        if let Err(e) = execute_analyze(&text) {
                            println!("❌ Error: {}", e);
                        }
                    }
                    Command::Similarity { text1, text2 } => {
                        if let Err(e) = execute_similarity(&text1, &text2) {
                            println!("❌ Error: {}", e);
                        }
                    }
                    Command::Generate { prompt, length } => {
                        if let Err(e) = execute_generate(&prompt, length) {
                            println!("❌ Error: {}", e);
                        }
                    }
                    Command::Help => print_help(),
                    Command::Quit => {
                        println!("👋 Goodbye! Thanks for using ToRSh Text Processing CLI!");
                        break;
                    }
                }
            }
            Err(e) => {
                println!("❌ Error reading input: {}", e);
            }
        }

        println!(); // Add spacing between commands
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_tokenize_command() {
        let cmd = parse_command("tokenize whitespace hello world");
        match cmd {
            Command::Tokenize { method, text } => {
                assert_eq!(method, "whitespace");
                assert_eq!(text, "hello world");
            }
            _ => panic!("Expected Tokenize command"),
        }
    }

    #[test]
    fn test_parse_help_command() {
        let cmd = parse_command("help");
        match cmd {
            Command::Help => {}
            _ => panic!("Expected Help command"),
        }
    }

    #[test]
    fn test_parse_quit_command() {
        let cmd = parse_command("quit");
        match cmd {
            Command::Quit => {}
            _ => panic!("Expected Quit command"),
        }
    }

    #[test]
    fn test_execute_tokenize() -> Result<()> {
        // This would be more comprehensive with actual tokenizers
        execute_tokenize("hello world", "whitespace")?;
        Ok(())
    }

    #[test]
    fn test_execute_analyze() -> Result<()> {
        execute_analyze("The quick brown fox jumps over the lazy dog.")?;
        Ok(())
    }
}