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
//! # Translate text
//!
//! To translate text all we need is to specify a target language and a chunk of text to translate.
//! In addition, the [`TextOptions`] type exposes a number of methods used to control formatting,
//! set a desired formality, or tell the server how to handle HTML or XML tags.
//!
//! ## Example
//! ```
//! // Translate text with some options
//! use deeprl::*;
//!
//! let dl = DeepL::new(
//! &std::env::var("DEEPL_API_KEY").unwrap()
//! );
//!
//! let text = vec![
//! "you are nice \nthe red crab".to_string(),
//! ];
//!
//! let opt = TextOptions::new(Language::FR)
//! .split_sentences(SplitSentences::None)
//! .preserve_formatting(true)
//! .formality(Formality::PreferLess);
//!
//! let result = dl.translate(opt, text).unwrap();
//! let translation = &result.translations[0];
//!
//! assert_eq!(
//! translation.text,
//! "tu es gentil le crabe rouge"
//! );
//! ```
//! ```
//! // Translate text inside HTML. Note we can skip translation
//! // for tags with a special attribute.
//! use deeprl::*;
//!
//! let dl = DeepL::new(
//! &std::env::var("DEEPL_API_KEY").unwrap()
//! );
//!
//! let html = r#"
//! <h2 class="notranslate">good morning</h2>
//! <p>good morning</p>"#
//! .to_string();
//!
//! let text = vec![html];
//! let opt = TextOptions::new(Language::ES)
//! .tag_handling(TagHandling::Html)
//! .outline_detection(false);
//!
//! let result = dl.translate(opt, text).unwrap();
//! let translation = &result.translations[0];
//!
//! assert!(translation.text.contains("good morning"));
//! assert!(translation.text.contains("buenos días"));
//! ```
use super::*;
use crate::lang::Language;
use serde::Deserialize;
/// Sets whether the translation engine should first split the input into sentences
#[derive(Copy, Clone)]
pub enum SplitSentences {
/// No splitting
None,
/// By default, split on punctuation and newlines
Default,
/// Split on punctuation only
NoNewlines,
}
/// Sets whether the translation engine should lean towards formal or informal language
#[derive(Copy, Clone)]
pub enum Formality {
/// Default formality
Default,
/// More formal
More,
/// Less formal
Less,
/// More formal if supported by target language, else default
PreferMore,
/// Less formal if supported by target language, else default
PreferLess,
}
/// Sets which kind of tags should be handled
#[derive(Copy, Clone)]
pub enum TagHandling {
/// Enable XML tag handling
Xml,
/// Enable HTML tag handling
Html,
}
/// An individual translation
#[derive(Debug, Deserialize)]
pub struct Translation {
/// Detected source language
pub detected_source_language: String,
/// Translated text
pub text: String,
}
/// Translation result
#[derive(Debug, Deserialize)]
pub struct TranslateTextResult {
/// List of translations
pub translations: Vec<Translation>,
}
impl AsRef<str> for SplitSentences {
fn as_ref(&self) -> &str {
match self {
Self::None => "0",
Self::Default => "1",
Self::NoNewlines => "nonewlines",
}
}
}
impl AsRef<str> for Formality {
fn as_ref(&self) -> &str {
match self {
Self::Default => "default",
Self::More => "more",
Self::Less => "less",
Self::PreferMore => "prefer_more",
Self::PreferLess => "prefer_less",
}
}
}
impl std::str::FromStr for Formality {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let fm = match s {
"more" => Self::More,
"less" => Self::Less,
"prefer_more" => Self::PreferMore,
"prefer_less" => Self::PreferLess,
_ => Self::Default,
};
Ok(fm)
}
}
impl AsRef<str> for TagHandling {
fn as_ref(&self) -> &str {
match self {
Self::Xml => "xml",
Self::Html => "html",
}
}
}
// TextOptions builder
builder! {
Text {
@must{
target_lang: Language,
};
@optional{
source_lang: Language,
split_sentences: SplitSentences,
preserve_formatting: bool,
formality: Formality,
glossary_id: String,
tag_handling: TagHandling,
non_splitting_tags: String,
outline_detection: bool,
splitting_tags: String,
ignore_tags: String,
};
}
}
impl TextOptions {
/// Creates a map of request params from an instance of `TextOptions`
fn into_form(self) -> Vec<(&'static str, String)> {
let mut form = vec![];
form.push(("target_lang", self.target_lang.to_string()));
if let Some(src) = self.source_lang {
form.push(("source_lang", src.as_ref().to_string()));
}
if let Some(ss) = self.split_sentences {
form.push(("split_sentences", ss.as_ref().to_string()));
}
if let Some(pf) = self.preserve_formatting {
if pf {
form.push(("preserve_formatting", "1".to_string()));
}
}
if let Some(fm) = self.formality {
form.push(("formality", fm.as_ref().to_string()));
}
if let Some(g) = self.glossary_id {
form.push(("glossary_id", g));
}
if let Some(th) = self.tag_handling {
form.push(("tag_handling", th.as_ref().to_string()));
}
if let Some(non) = self.non_splitting_tags {
form.push(("non_splitting_tags", non));
}
if let Some(od) = self.outline_detection {
if !od {
form.push(("outline_detection", "0".to_string()));
}
}
if let Some(sp) = self.splitting_tags {
form.push(("splitting_tags", sp));
}
if let Some(ig) = self.ignore_tags {
form.push(("ignore_tags", ig));
}
form
}
}
impl DeepL {
/// POST /translate
///
/// Translate one or more text strings
pub fn translate(&self, opt: TextOptions, text: Vec<String>) -> Result<TranslateTextResult> {
if text.is_empty() || text[0].is_empty() {
return Err(Error::Client("empty text parameter".to_string()));
}
let url = format!("{}/translate", self.url);
let mut params = opt.into_form();
for t in text {
params.push(("text", t));
}
let resp = self.post(url)
.form(¶ms)
.send()
.map_err(|_| Error::InvalidRequest)?;
if !resp.status().is_success() {
return super::convert(resp);
}
resp.json().map_err(|_| Error::Deserialize)
}
}