lipilekhika 1.0.4

A transliteration library for Indian Brahmic scripts
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use criterion::{Criterion, black_box, criterion_group, criterion_main};
use lipilekhika::transliterate;
use lipilekhika::typing::{TypingContextOptions, emulate_typing};
use serde::Deserialize;
use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::thread;
use std::time::{Duration, Instant};

// ----------------------------
// YAML schemas (mirrors JS + existing Rust YAML tests)
// ----------------------------

fn de_index<'de, D>(deserializer: D) -> Result<String, D::Error>
where
  D: serde::Deserializer<'de>,
{
  struct IndexVisitor;

  impl serde::de::Visitor<'_> for IndexVisitor {
    type Value = String;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
      formatter.write_str("a yaml index (number or string)")
    }

    fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
    where
      E: serde::de::Error,
    {
      Ok(v.to_string())
    }

    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
    where
      E: serde::de::Error,
    {
      Ok(v.to_string())
    }

    fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
    where
      E: serde::de::Error,
    {
      Ok(v.to_string())
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
      E: serde::de::Error,
    {
      Ok(v.to_string())
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
      E: serde::de::Error,
    {
      Ok(v)
    }
  }

  deserializer.deserialize_any(IndexVisitor)
}

#[derive(Clone, Debug, Deserialize)]
struct TransliterationTestCase {
  #[serde(deserialize_with = "de_index")]
  #[allow(dead_code)]
  index: String,
  from: String,
  to: String,
  input: String,
  #[serde(default)]
  options: Option<HashMap<String, bool>>,
  #[serde(default)]
  todo: Option<bool>,
}

#[derive(Clone, Debug, Deserialize, Default)]
struct TypingOptionsYaml {
  #[serde(rename = "useNativeNumerals")]
  #[serde(default)]
  use_native_numerals: Option<bool>,

  #[serde(rename = "includeInherentVowel")]
  #[serde(default)]
  include_inherent_vowel: Option<bool>,

  #[serde(rename = "autoContextTClearTimeMs")]
  #[serde(default)]
  auto_context_clear_time_ms: Option<u64>,
}

#[derive(Clone, Debug, Deserialize)]
struct TypingTestCase {
  #[allow(dead_code)]
  index: i64,
  text: String,
  #[allow(dead_code)]
  output: String,
  script: String,
  #[serde(default)]
  todo: bool,
  #[serde(default)]
  options: Option<TypingOptionsYaml>,
}

fn build_typing_options(opts: &Option<TypingOptionsYaml>) -> Option<TypingContextOptions> {
  let some_opts = match opts {
    None => return None,
    Some(o) => o,
  };

  let mut rust_opts = TypingContextOptions::default();
  if let Some(v) = some_opts.use_native_numerals {
    rust_opts.use_native_numerals = v;
  }
  if let Some(v) = some_opts.include_inherent_vowel {
    rust_opts.include_inherent_vowel = v;
  }
  if let Some(v) = some_opts.auto_context_clear_time_ms {
    rust_opts.auto_context_clear_time_ms = v;
  }

  Some(rust_opts)
}

// ----------------------------
// Data loading
// ----------------------------

fn transliteration_test_data_root() -> PathBuf {
  // `packages/rust` -> `../../test_data/transliteration`
  let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
  manifest_dir
    .join("..")
    .join("..")
    .join("test_data")
    .join("transliteration")
}

fn typing_test_data_root() -> PathBuf {
  // `packages/rust` -> `../../test_data/typing`
  let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
  manifest_dir
    .join("..")
    .join("..")
    .join("test_data")
    .join("typing")
}

fn list_yaml_files_recursive(dir: &Path, out: &mut Vec<PathBuf>) -> std::io::Result<()> {
  for entry in fs::read_dir(dir)? {
    let entry = entry?;
    let path = entry.path();
    if path.is_dir() {
      list_yaml_files_recursive(&path, out)?;
    } else if path.extension().is_some_and(|e| e == "yaml") {
      out.push(path);
    }
  }
  Ok(())
}

fn list_yaml_files_typing(dir: &Path, out: &mut Vec<PathBuf>) -> std::io::Result<()> {
  for entry in fs::read_dir(dir)? {
    let entry = entry?;
    let path = entry.path();
    if path.is_dir() {
      if path
        .file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|n| n == "context")
      {
        continue;
      }
      list_yaml_files_typing(&path, out)?;
    } else if path.extension().and_then(|e| e.to_str()) == Some("yaml") {
      out.push(path);
    }
  }
  Ok(())
}

fn load_transliteration_cases() -> Vec<TransliterationTestCase> {
  use serde_yaml_ng as yaml;

  let root = transliteration_test_data_root();
  let mut files: Vec<PathBuf> = Vec::new();
  list_yaml_files_recursive(&root, &mut files)
    .unwrap_or_else(|e| panic!("Failed listing YAML files in `{}`: {e}", root.display()));
  files.sort();

  assert!(
    !files.is_empty(),
    "No YAML transliteration test files found in `{}`",
    root.display()
  );

  let mut all: Vec<TransliterationTestCase> = Vec::new();
  for file in files {
    let yaml_text = fs::read_to_string(&file)
      .unwrap_or_else(|e| panic!("Failed reading `{}`: {e}", file.display()));
    let mut cases: Vec<TransliterationTestCase> = yaml::from_str(&yaml_text)
      .unwrap_or_else(|e| panic!("Failed parsing `{}`: {e}", file.display()));
    all.append(&mut cases);
  }
  all
}

fn load_typing_cases() -> Vec<TypingTestCase> {
  use serde_yaml_ng as yaml;

  let root = typing_test_data_root();
  let mut files: Vec<PathBuf> = Vec::new();
  list_yaml_files_typing(&root, &mut files)
    .unwrap_or_else(|e| panic!("Failed listing YAML files in `{}`: {e}", root.display()));
  files.sort();

  assert!(
    !files.is_empty(),
    "No YAML typing test files found in `{}`",
    root.display()
  );

  let mut all: Vec<TypingTestCase> = Vec::new();
  for file in files {
    let yaml_text = fs::read_to_string(&file)
      .unwrap_or_else(|e| panic!("Failed reading `{}`: {e}", file.display()));
    let mut cases: Vec<TypingTestCase> = yaml::from_str(&yaml_text)
      .unwrap_or_else(|e| panic!("Failed parsing `{}`: {e}", file.display()));
    all.append(&mut cases);
  }
  all
}

static TRANSLIT_CASES: OnceLock<Vec<TransliterationTestCase>> = OnceLock::new();
static TYPING_CASES: OnceLock<Vec<TypingTestCase>> = OnceLock::new();

fn translit_cases() -> &'static [TransliterationTestCase] {
  TRANSLIT_CASES
    .get_or_init(load_transliteration_cases)
    .as_slice()
}

fn typing_cases() -> &'static [TypingTestCase] {
  TYPING_CASES.get_or_init(load_typing_cases).as_slice()
}

// ----------------------------
// Workloads (mirrors `packages/js/src/scripts/benchmark.ts`)
// ----------------------------

const TOTAL_THREADS: usize = 40;

fn run_transliteration_pass(cases: &[TransliterationTestCase]) {
  let mut handles = Vec::with_capacity(TOTAL_THREADS);
  let total_cases = cases.len();
  let chunk_size = total_cases / TOTAL_THREADS;

  for thread_id in 0..TOTAL_THREADS {
    let start = thread_id * chunk_size;
    let end = if thread_id == TOTAL_THREADS - 1 {
      total_cases // Last thread handles any remainder
    } else {
      (thread_id + 1) * chunk_size
    };

    let cases_chunk: Vec<_> = cases[start..end].to_vec();
    let handle = thread::spawn(move || {
      for case in cases_chunk {
        if case.todo.unwrap_or(false) {
          continue;
        }
        let out = transliterate(&case.input, &case.from, &case.to, case.options.as_ref());
        black_box(out).ok();
      }
    });
    handles.push(handle);
  }

  // Join all threads
  for handle in handles {
    handle.join().expect("Thread panicked");
  }
}

fn run_typing_normal_to_others_pass(cases: &[TransliterationTestCase]) {
  let mut handles = Vec::with_capacity(TOTAL_THREADS);
  let total_cases = cases.len();
  let chunk_size = total_cases / TOTAL_THREADS;

  for thread_id in 0..TOTAL_THREADS {
    let start = thread_id * chunk_size;
    let end = if thread_id == TOTAL_THREADS - 1 {
      total_cases // Last thread handles any remainder
    } else {
      (thread_id + 1) * chunk_size
    };

    let cases_chunk: Vec<_> = cases[start..end].to_vec();
    let handle = thread::spawn(move || {
      for case in cases_chunk {
        if case.todo.unwrap_or(false) {
          continue;
        }
        if case.from != "Normal" {
          continue;
        }
        let out = emulate_typing(&case.input, &case.to, None);
        black_box(out).ok();
      }
    });
    handles.push(handle);
  }

  // Join all threads
  for handle in handles {
    handle.join().expect("Thread panicked");
  }
}

fn run_typing_others_to_normal_pass(cases: &[TypingTestCase]) {
  let mut handles = Vec::with_capacity(TOTAL_THREADS);
  let total_cases = cases.len();
  let chunk_size = total_cases / TOTAL_THREADS;

  for thread_id in 0..TOTAL_THREADS {
    let start = thread_id * chunk_size;
    let end = if thread_id == TOTAL_THREADS - 1 {
      total_cases // Last thread handles any remainder
    } else {
      (thread_id + 1) * chunk_size
    };

    let cases_chunk: Vec<_> = cases[start..end].to_vec();
    let handle = thread::spawn(move || {
      for case in cases_chunk {
        if case.todo {
          continue;
        }
        let opts = build_typing_options(&case.options);
        let out = emulate_typing(&case.text, &case.script, opts);
        black_box(out).ok();
      }
    });
    handles.push(handle);
  }

  // Join all threads
  for handle in handles {
    handle.join().expect("Thread panicked");
  }
}

// ----------------------------
// Report output: `test_log/benchmark.txt`
// ----------------------------

fn benchmark_log_path() -> PathBuf {
  // keep logs beside the Rust crate (`packages/rust/test_log/benchmark.txt`)
  PathBuf::from(env!("CARGO_MANIFEST_DIR"))
    .join("test_log")
    .join("benchmark.txt")
}

fn fmt_ms(d: Duration) -> String {
  format!("{:.3}", d.as_secs_f64() * 1000.0)
}

fn write_benchmark_report() {
  let translit = translit_cases();
  let typing = typing_cases();

  const ITERATIONS: u32 = 3;
  let mut translit_total_d = Duration::ZERO;
  let mut typing_normal_to_others_total_d = Duration::ZERO;
  let mut typing_others_to_normal_total_d = Duration::ZERO;

  for _ in 0..ITERATIONS {
    let t0 = Instant::now();
    run_transliteration_pass(translit);
    translit_total_d += t0.elapsed();

    let t1 = Instant::now();
    run_typing_normal_to_others_pass(translit);
    typing_normal_to_others_total_d += t1.elapsed();

    let t2 = Instant::now();
    run_typing_others_to_normal_pass(typing);
    typing_others_to_normal_total_d += t2.elapsed();
  }

  let translit_avg = translit_total_d / ITERATIONS;
  let typing_normal_avg = typing_normal_to_others_total_d / ITERATIONS;
  let typing_others_avg = typing_others_to_normal_total_d / ITERATIONS;

  let translit_total = translit.iter().filter(|c| !c.todo.unwrap_or(false)).count();
  let normal_to_others_total = translit
    .iter()
    .filter(|c| !c.todo.unwrap_or(false) && c.from == "Normal")
    .count();
  let others_to_normal_total = typing.iter().filter(|c| !c.todo).count();

  let total_avg_d = translit_avg + typing_normal_avg + typing_others_avg;

  let path = benchmark_log_path();
  if let Some(parent) = path.parent() {
    fs::create_dir_all(parent)
      .unwrap_or_else(|e| panic!("Failed creating dir `{}`: {e}", parent.display()));
  }

  let mut f =
    fs::File::create(&path).unwrap_or_else(|e| panic!("Failed writing `{}`: {e}", path.display()));

  writeln!(
    f,
    "Lipilekhika Rust benchmark (averaged over {} iterations)",
    ITERATIONS
  )
  .ok();
  writeln!(
    f,
    "Transliteration Cases: cases={}, avg_time_ms={}",
    translit_total,
    fmt_ms(translit_avg)
  )
  .ok();
  writeln!(
    f,
    "Typing Emulation (Normal -> others): cases={}, avg_time_ms={}",
    normal_to_others_total,
    fmt_ms(typing_normal_avg)
  )
  .ok();
  writeln!(
    f,
    "Typing Emulation (others -> Normal): cases={}, avg_time_ms={}",
    others_to_normal_total,
    fmt_ms(typing_others_avg)
  )
  .ok();
  writeln!(f, "Total Average: time_ms={}", fmt_ms(total_avg_d)).ok();
}

// ----------------------------
// Criterion entrypoint (`cargo bench`)
// ----------------------------

fn criterion_benchmark(c: &mut Criterion) {
  // Write the requested output file once per `cargo bench` invocation.
  write_benchmark_report();

  let translit = translit_cases();
  let typing = typing_cases();

  c.bench_function("transliteration_all_cases", |b| {
    b.iter(|| run_transliteration_pass(black_box(translit)))
  });

  c.bench_function("typing_emulation_normal_to_others", |b| {
    b.iter(|| run_typing_normal_to_others_pass(black_box(translit)))
  });

  c.bench_function("typing_emulation_others_to_normal", |b| {
    b.iter(|| run_typing_others_to_normal_pass(black_box(typing)))
  });
}

criterion_group! {
    name = benches;
    config = Criterion::default()
        .sample_size(30);
    targets = criterion_benchmark
}
criterion_main!(benches);