sophia_interfaces/
lib.rs

1#![allow(warnings)]
2use serde::{Serialize, Deserialize};
3use libloading::{Library, Symbol};
4
5pub use self::interpreter::{InterpretedOutput, OutputPhrase, OutputNoun, OutputNounModifier, OutputNounSibling, OutputVerb, OutputVerbModifier, OutputAdjective, OutputAuditPhrase, OutputAuditItem, OutputVerbSibling};
6pub use self::tokenizer::{TokenizedOutput, OutputToken, OutputCategory};
7
8mod interpreter;
9mod tokenizer;
10
11pub trait SophiaInterface {
12    fn tokenize(&self, input: &str) -> TokenizedOutput;
13    fn interpret(&self, input: &str) -> InterpretedOutput;
14    fn get_token(&self, index: i32) -> Option<OutputToken>;
15    fn get_word(&self, word: &str) -> Option<OutputToken>;
16    fn get_category(&self, category_path: &str) -> Option<OutputCategory>;
17}
18
19pub trait SophiaProInterface {
20    fn import_words(&self, dirname: &str, datadir: &str, dupe_action: u8) -> (u8, String);
21    fn export_words(&self, dirname: &str, datadir: &str);
22    fn purge_words(&self, datadir: &str) -> bool;
23    fn import_selectors(&self, dirname: &str, datadir: &str);
24    fn export_selectors(&self, dirname: &str, datadir: &str);
25    fn purge_selectors(&self, datadir: &str) -> bool;
26    fn run_selector(&self, selector: &str, user_input: &str) -> SelectorResponse;
27}
28
29#[derive(Default, Debug, Clone, Serialize, Deserialize)]
30pub struct SelectorResponse {
31    pub answer: String,
32    pub confidence: f32,
33    pub intent: String,
34    pub intent_score: f32
35}
36
37pub struct SophiaSharedLibrary {
38    pub ptr: *const dyn SophiaInterface,
39    pub symbols: Library
40}
41
42impl SophiaSharedLibrary {
43
44    pub fn tokenize(&self, input: &str) -> Result<TokenizedOutput, Box<dyn std::error::Error>> {
45        unsafe {
46            let output = self.ptr.as_ref().unwrap().tokenize(&input);
47            return Ok(output);
48        }
49        Err(Box::from("Unexpected error while communicating with shared library, please reload and try again."))
50    }
51
52    pub fn interpret(&self, input: &str) -> Result<InterpretedOutput, Box<dyn std::error::Error>> {
53        unsafe {
54            let output = self.ptr.as_ref().unwrap().interpret(&input);
55            return Ok(output);
56        }
57        Err(Box::from("Unexpected error while communicating with shared library, please reload and try again."))
58    }
59
60}
61
62impl Drop for SophiaSharedLibrary {
63    fn drop(&mut self) {
64        unsafe {
65            let destroy_func: Symbol<unsafe extern fn(*mut dyn SophiaInterface)> = self.symbols.get(b"destroy").expect("Failed to get free_plugin symbol");
66            destroy_func(self.ptr as *mut dyn SophiaInterface);
67        }
68    }
69}
70
71
72
73