google_api_rust_client_unoffical/services/translate_service/
translate_text.rs

1use std::collections::HashMap;
2
3use super::{TranslateServiceV2Type, TranslateService, TRANSLATE_SERVICE_BASE_URL};
4
5use serde::{Serialize, Deserialize};
6use anyhow::Result;
7use reqwest::{Client, Url};
8use serde_json::Value;
9
10impl TranslateService {
11
12    /// Translates text into the target language. <br>
13    /// See https://g.co/cloud/translate/v2/translate-reference#supported_languages
14    /// https://cloud.google.com/translate/docs/reference/rest/v2/translate
15    /// https://cloud.google.com/translate/docs/basic/translating-text#translate_translate_text-drest
16    ///
17    /// * `text` -  an array of strings to be translated.
18    /// * `target` - The language to use for translation of the input text.
19    /// * `params` - Optional Additional Parameter. Keys accepted are the following.
20    ///     * `format` - The format of the source text, in either HTML (default) or plain-text. A value of html indicates HTML and a value of text indicates plain-text.
21    ///     * `source` - The language of the source text.
22    ///     * `model` - The translation model. Cloud Translation - Basic offers only the nmt Neural Machine Translation (NMT) model. If the model is base, the request is translated by using the NMT model.
23    pub async fn translate(&mut self, text: Vec<&str>, target: &str, params: Option<HashMap<String, Value>>) -> Result<TranslateTextResponse>{
24        let request_body =TranslateTextRequest::new(text, target, params)?;
25        self.post_translate_request(request_body).await
26    }
27
28    async fn post_translate_request(&mut self, request_body: TranslateTextRequest) -> Result<TranslateTextResponse> {
29
30        let base_url = Url::parse(&format!("{}/v2/{}", TRANSLATE_SERVICE_BASE_URL, TranslateServiceV2Type::Translate.path()))?;
31        let headers = self.base.create_headers().await?;
32        let builder = Client::new().post(base_url)
33                .headers(headers)
34                .body(serde_json::to_string(&request_body)?);
35
36        let body = self.base.make_request(builder).await?;
37
38        Ok(serde_json::from_str::<TranslateTextResponse>(&body)?)
39
40    }
41}
42
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
45#[serde(rename_all = "camelCase")]
46struct TranslateTextRequest {
47    q: Vec<String>,
48    target: String,
49
50    #[serde(skip_serializing_if = "Option::is_none", flatten)]
51    params: Option<TranslateTextRequestOptionalParams>
52}
53
54
55#[derive(Debug, Clone, Serialize, Deserialize)]
56#[serde(rename_all = "camelCase")]
57struct TranslateTextRequestOptionalParams {
58    #[serde(skip_serializing_if = "Option::is_none")]
59    format: Option<String>,
60    #[serde(skip_serializing_if = "Option::is_none")]
61    source: Option<String>,
62    #[serde(skip_serializing_if = "Option::is_none")]
63    model: Option<String>
64}
65
66impl TranslateTextRequest {
67
68    fn new(text: Vec<&str>, target: &str, params: Option<HashMap<String, Value>>) -> Result<Self> {
69        let additional_params: Option<TranslateTextRequestOptionalParams> = if let Some(params) = params {
70            let additional_params_string = serde_json::to_string(&params)?;
71            serde_json::from_str(&additional_params_string)?
72        } else {
73            None
74        };
75        Ok(Self{
76            q: text.into_iter().map(|s| s.to_owned()).collect(),
77            target: target.to_owned(),
78            params: additional_params
79        })
80    }
81}
82
83
84#[derive(Debug, Clone, Serialize, Deserialize)]
85#[serde(rename_all = "camelCase")]
86pub struct TranslateTextResponse {
87    pub data: TranslateTextResponseData
88}
89
90
91#[derive(Debug, Clone, Serialize, Deserialize)]
92#[serde(rename_all = "camelCase")]
93pub struct TranslateTextResponseData {
94    pub translations: Vec<TranslateTextResponseTranslation>
95}
96
97#[derive(Debug, Clone, Serialize, Deserialize)]
98#[serde(rename_all = "camelCase")]
99pub struct TranslateTextResponseTranslation {
100    pub translated_text: String,
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub model: Option<String>,
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub detected_source_language: Option<String>,
105}