summaryrefslogtreecommitdiff
path: root/autofeur_db/src/inference.rs
blob: f681cd06a0287dc6617b44f2df8cdf7325921fad (plain)
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
use std::{env, ops::Add};

use anyhow::anyhow;
use hypher::hyphenate;
use itertools::Itertools;

use crate::save::Save;

async fn call_inference_service(word: &str) -> anyhow::Result<String> {
    let server: Result<String, anyhow::Error> =
        env::var("PHONEMIZER").or_else(|_| Ok("http://localhost:8000/".to_string()));
    Ok(
        reqwest::get(format!("{}?grapheme={}", server.unwrap(), word))
            .await?
            .text()
            .await?,
    )
}

impl Save<'_> {
    pub async fn inference(&self, prefix: &str) -> anyhow::Result<String> {
        let phonemes = call_inference_service(prefix).await?;
        let source_word_syllabes: Vec<&str> = hyphenate(prefix, hypher::Lang::French)
            .into_iter()
            .collect_vec();
        println!("syl: [{}]", source_word_syllabes.join(","));

        let completion = self
            .trie
            .random_starting_with(&phonemes)
            .ok_or_else(|| anyhow!("no matches"))?;

        let infered = phonemes.clone().add(&completion);
        let word = self.reverse_index.get(&infered).ok_or_else(|| {
            anyhow!(
                "matched value is not in dictionary {} {}",
                infered,
                phonemes
            )
        })?;

        println!("Matching {} by adding {}", word, completion);

        let mut completed_syllabes: Vec<&str> = hyphenate(word, hypher::Lang::French)
            .into_iter()
            .collect_vec();

        // input:           test
        // output found:    testames
        // out syl:         tes - tames
        // output expect:   tames
        // we just need to remove the prefix

        println!(
            "[{}] cmp [{}]",
            source_word_syllabes.join(","),
            completed_syllabes.join(",")
        );
        let mut i = 0;
        let maxindex = source_word_syllabes.len() - 1;
        for (index, syl) in completed_syllabes.iter().enumerate() {
            if maxindex < index {
                break;
            }

            let phon1 = &source_word_syllabes[index].to_lowercase();
            let phon2 = &(**syl).to_lowercase();

            println!("comparing syllab {} vs {}", phon1, phon2);

            if strsim::levenshtein(phon1, phon2) < 2 {
                i = index
            } else {
                println!("found scyl break at {}", i);
                break;
            }
        }

        // we finally just need to compute the end of the word which matches the sound
        let found = completed_syllabes.drain(i+1..).join("");
        println!("{} is equivalent to {}", completion, found);

        Ok(format!("{} ({})", found, word))
    }
}