shlesha 0.5.7

High-performance extensible transliteration library with hub-and-spoke architecture
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Optimization Generator Module
//!
//! This module generates optimized lookup tables from profile data by:
//! - Running actual conversions to build mappings
//! - Creating multi-character sequence optimizations
//! - Building common word dictionaries
//! - Generating efficient data structures for runtime lookup

use super::{ConversionProfile, OptimizedLookupTable};
use crate::Shlesha;
use rustc_hash::FxHashMap;
use std::time::Instant;

/// Optimization generator that creates lookup tables from profiles
pub struct OptimizationGenerator {
    transliterator: Shlesha,
}

impl Default for OptimizationGenerator {
    fn default() -> Self {
        Self::new()
    }
}

impl OptimizationGenerator {
    /// Create a new optimization generator
    pub fn new() -> Self {
        Self {
            transliterator: Shlesha::new(),
        }
    }

    /// Generate optimized lookup table from a conversion profile
    pub fn generate_from_profile(
        &self,
        profile: &ConversionProfile,
        top_sequences: &[(String, u64)],
    ) -> Result<OptimizedLookupTable, Box<dyn std::error::Error>> {
        let mut sequence_mappings = FxHashMap::default();
        let mut word_mappings = FxHashMap::default();

        // Process each sequence and generate its mapping
        for (sequence, _count) in top_sequences {
            // Skip if we've already processed this as part of a longer sequence
            if sequence_mappings.contains_key(sequence) {
                continue;
            }

            // Convert the sequence
            match self.transliterator.transliterate(
                sequence,
                &profile.from_script,
                &profile.to_script,
            ) {
                Ok(converted) => {
                    // Determine if this is a word or sequence
                    if sequence.contains(char::is_whitespace) || sequence.chars().count() > 4 {
                        word_mappings.insert(sequence.clone(), converted);
                    } else {
                        sequence_mappings.insert(sequence.clone(), converted);
                    }
                }
                Err(_) => {
                    // Skip sequences that can't be converted
                    continue;
                }
            }
        }

        // Generate common Sanskrit/Hindi word optimizations
        self.add_common_words(&mut word_mappings, &profile.from_script, &profile.to_script);

        let total_count = sequence_mappings.len() + word_mappings.len();

        Ok(OptimizedLookupTable {
            from_script: profile.from_script.clone(),
            to_script: profile.to_script.clone(),
            sequence_mappings,
            word_mappings,
            metadata: super::OptimizationMetadata {
                generated_at: std::time::SystemTime::now(),
                sequence_count: total_count,
                min_frequency: 0, // Will be set by profiler
                profile_stats: super::ProfileStats {
                    total_sequences_profiled: profile.total_conversions,
                    unique_sequences: profile.sequences.len(),
                    top_sequences: top_sequences.to_vec(),
                },
            },
        })
    }

    /// Add common Sanskrit/Hindi words to the optimization table
    fn add_common_words(
        &self,
        word_mappings: &mut FxHashMap<String, String>,
        from_script: &str,
        to_script: &str,
    ) {
        // Common Sanskrit/Hindi words that appear frequently
        let common_words = match from_script {
            "devanagari" => vec![
                // Sanskrit religious/philosophical terms
                "धर्म",
                "कर्म",
                "योग",
                "वेद",
                "मन्त्र",
                "तन्त्र",
                "यन्त्र",
                "आत्मा",
                "ब्रह्म",
                "मोक्ष",
                "निर्वाण",
                "समाधि",
                "ध्यान",
                "प्राण",
                "चक्र",
                "गुरु",
                "शिष्य",
                "साधना",
                "सिद्धि",
                // Common words
                "नमस्ते",
                "नमस्कार",
                "श्री",
                "",
                "स्वामी",
                "महा",
                "राज",
                "देव",
                "देवी",
                "मन्दिर",
                "पूजा",
                "आरती",
                "प्रसाद",
                // Texts and scriptures
                "रामायण",
                "महाभारत",
                "गीता",
                "उपनिषद्",
                "पुराण",
                "सूत्र",
                "शास्त्र",
                "वेदान्त",
                "संस्कृत",
                "हिन्दी",
                "भारत",
                "भाषा",
                // Common verbs/actions
                "करना",
                "होना",
                "जाना",
                "आना",
                "देना",
                "लेना",
                "कहना",
                "सुनना",
                "देखना",
                "समझना",
                "पढ़ना",
                "लिखना",
            ],
            "iast" | "iso15919" => vec![
                // Sanskrit terms in Roman
                "dharma",
                "karma",
                "yoga",
                "veda",
                "mantra",
                "tantra",
                "yantra",
                "ātmā",
                "ātman",
                "brahma",
                "brahman",
                "mokṣa",
                "nirvāṇa",
                "samādhi",
                "dhyāna",
                "prāṇa",
                "cakra",
                "guru",
                "śiṣya",
                "sādhanā",
                "siddhi",
                // Common words
                "namaste",
                "namaskāra",
                "śrī",
                "oṁ",
                "om",
                "svāmī",
                "mahā",
                "deva",
                "devī",
                "mandira",
                "pūjā",
                "āratī",
                "prasāda",
                // Texts
                "rāmāyaṇa",
                "mahābhārata",
                "gītā",
                "upaniṣad",
                "purāṇa",
                "sūtra",
                "śāstra",
                "vedānta",
                "saṃskṛta",
                "hindī",
                "bhārata",
                "bhāṣā",
            ],
            _ => vec![],
        };

        // Convert and add common words
        for word in common_words {
            if let Ok(converted) = self
                .transliterator
                .transliterate(word, from_script, to_script)
            {
                word_mappings.insert(word.to_string(), converted);
            }
        }

        // Add common bigrams and trigrams for Sanskrit
        if from_script == "devanagari" {
            let common_sequences = vec![
                // Common consonant clusters
                "क्ष",
                "ज्ञ",
                "त्र",
                "श्र",
                "स्व",
                "द्व",
                "त्व",
                "स्थ",
                "प्र",
                "ब्र",
                "क्र",
                "ग्र",
                "द्र",
                "फ्र",
                "श्व",
                "ह्व",
                // Common syllables
                "नि",
                "अनु",
                "प्रति",
                "सम्",
                "उप",
                "अधि",
                "अभि",
                "वि",
                // Common endings
                "ता",
                "त्व",
                "आनि",
                "एषु",
                "स्य",
                "तः",
                "भिः",
                "भ्यः",
            ];

            for seq in common_sequences {
                if let Ok(converted) =
                    self.transliterator
                        .transliterate(seq, from_script, to_script)
                {
                    word_mappings.insert(seq.to_string(), converted);
                }
            }
        }
    }

    /// Benchmark the effectiveness of an optimization table
    pub fn benchmark_optimization(
        &self,
        optimization: &OptimizedLookupTable,
        test_text: &str,
    ) -> OptimizationBenchmark {
        let start = Instant::now();
        let _baseline_result = self
            .transliterator
            .transliterate(
                test_text,
                &optimization.from_script,
                &optimization.to_script,
            )
            .unwrap_or_default();
        let baseline_time = start.elapsed();

        // Simulate optimized conversion
        let start = Instant::now();
        let _optimized_result = self.simulate_optimized_conversion(test_text, optimization);
        let optimized_time = start.elapsed();

        OptimizationBenchmark {
            baseline_time_ns: baseline_time.as_nanos() as u64,
            optimized_time_ns: optimized_time.as_nanos() as u64,
            speedup_factor: baseline_time.as_secs_f64() / optimized_time.as_secs_f64(),
            cache_hits: self.count_cache_hits(test_text, optimization),
            total_sequences: test_text.chars().count(),
        }
    }

    /// Simulate conversion using optimization table
    fn simulate_optimized_conversion(
        &self,
        text: &str,
        optimization: &OptimizedLookupTable,
    ) -> String {
        let mut result = String::new();
        let chars: Vec<char> = text.chars().collect();
        let mut i = 0;

        while i < chars.len() {
            let mut matched = false;

            // Try to match longest sequences first
            for len in (1..=5).rev() {
                if i + len > chars.len() {
                    continue;
                }

                let sequence: String = chars[i..i + len].iter().collect();

                // Check word mappings first (for multi-word sequences)
                if let Some(mapped) = optimization.word_mappings.get(&sequence) {
                    result.push_str(mapped);
                    i += len;
                    matched = true;
                    break;
                }

                // Then check sequence mappings
                if let Some(mapped) = optimization.sequence_mappings.get(&sequence) {
                    result.push_str(mapped);
                    i += len;
                    matched = true;
                    break;
                }
            }

            if !matched {
                // Fallback to regular conversion for this character
                let ch_str = chars[i].to_string();
                if let Ok(converted) = self.transliterator.transliterate(
                    &ch_str,
                    &optimization.from_script,
                    &optimization.to_script,
                ) {
                    result.push_str(&converted);
                } else {
                    result.push(chars[i]);
                }
                i += 1;
            }
        }

        result
    }

    /// Count how many sequences would hit the optimization cache
    fn count_cache_hits(&self, text: &str, optimization: &OptimizedLookupTable) -> usize {
        let mut hits = 0;
        let chars: Vec<char> = text.chars().collect();
        let mut i = 0;

        while i < chars.len() {
            let mut matched = false;

            for len in (1..=5).rev() {
                if i + len > chars.len() {
                    continue;
                }

                let sequence: String = chars[i..i + len].iter().collect();

                if optimization.word_mappings.contains_key(&sequence)
                    || optimization.sequence_mappings.contains_key(&sequence)
                {
                    hits += 1;
                    i += len;
                    matched = true;
                    break;
                }
            }

            if !matched {
                i += 1;
            }
        }

        hits
    }
}

/// Benchmark results for an optimization
#[derive(Debug, Clone)]
pub struct OptimizationBenchmark {
    pub baseline_time_ns: u64,
    pub optimized_time_ns: u64,
    pub speedup_factor: f64,
    pub cache_hits: usize,
    pub total_sequences: usize,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::modules::profiler::ConversionProfile;
    use rustc_hash::FxHashMap;
    use std::time::SystemTime;

    #[test]
    fn test_optimization_generation() {
        let generator = OptimizationGenerator::new();

        let profile = ConversionProfile {
            from_script: "devanagari".to_string(),
            to_script: "iast".to_string(),
            sequences: FxHashMap::default(),
            total_conversions: 100,
            created_at: SystemTime::now(),
            updated_at: SystemTime::now(),
        };

        // Add some test sequences
        let sequences = vec![
            ("धर्म".to_string(), 50),
            ("योग".to_string(), 30),
            ("कर्म".to_string(), 25),
        ];

        let optimization = generator
            .generate_from_profile(&profile, &sequences)
            .unwrap();

        assert_eq!(optimization.from_script, "devanagari");
        assert_eq!(optimization.to_script, "iast");
        assert!(optimization.sequence_mappings.contains_key("धर्म"));
        assert!(optimization.sequence_mappings.contains_key("योग"));
    }

    #[test]
    fn test_common_words_addition() {
        let generator = OptimizationGenerator::new();
        let mut word_mappings = FxHashMap::default();

        generator.add_common_words(&mut word_mappings, "devanagari", "iast");

        // Should have added common Sanskrit words
        assert!(word_mappings.contains_key("धर्म"));
        assert!(word_mappings.contains_key("नमस्ते"));
        assert!(word_mappings.contains_key("योग"));
    }
}