oscar_io/common/
identification.rs

1/*! Identifier trait
2
3All identifiers should implement [Identifier] to be useable in processing and pipelines.
4!*/
5use std::ops::Deref;
6
7use crate::error::Error;
8
9use oxilangtag::{LanguageTag, LanguageTagParseError};
10
11use serde::{Deserialize, Serialize};
12
13#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
14pub struct Identification<T: Deref<Target = str> + Clone> {
15    label: LanguageTag<T>,
16    prob: f32,
17}
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20struct IdentificationSer {
21    label: String,
22    prob: f32,
23}
24
25impl<T> From<Identification<T>> for IdentificationSer
26where
27    T: Deref<Target = str> + Clone,
28{
29    fn from(i: Identification<T>) -> Self {
30        Self {
31            label: i.label.to_string(),
32            prob: i.prob,
33        }
34    }
35}
36impl TryFrom<IdentificationSer> for Identification<String> {
37    type Error = LanguageTagParseError;
38    fn try_from(i: IdentificationSer) -> Result<Self, Self::Error> {
39        Ok(Self {
40            label: LanguageTag::parse(i.label)?,
41            prob: i.prob,
42        })
43    }
44}
45
46impl<T: Deref<Target = str> + Clone> Identification<T> {
47    pub fn new(label: LanguageTag<T>, prob: f32) -> Self {
48        Self { label, prob }
49    }
50    /// Get a reference to the identification's label.
51    pub fn label(&self) -> &LanguageTag<T> {
52        &self.label
53    }
54
55    /// Get a reference to the identification's prob.
56    pub fn prob(&self) -> &f32 {
57        &self.prob
58    }
59}
60
61pub trait Identifier<T: Deref<Target = str> + Clone> {
62    /// returns a language identification token (from [crate::lang::LANG]).
63    fn identify(&self, sentence: T) -> Result<Option<Identification<T>>, Error>;
64}
65
66#[cfg(test)]
67mod tests {
68    // TODO tests
69}