Skip to content

Commit de518c3

Browse files
committed
baidu & youdao api
1 parent bd0d43f commit de518c3

File tree

11 files changed

+249
-141
lines changed

11 files changed

+249
-141
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "translators"
3-
version = "0.1.7"
3+
version = "0.1.8"
44
edition = "2021"
55

66
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

env_example

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,7 @@ DEEPL_TOKEN=token
33
LIBRE_TOKEN=token
44
GPT_PROXY=https://...
55
GPT_OLD_PROXY=https://...
6-
6+
YOUDAO_KEY=token
7+
YOUDAO_SECRET=token
8+
BAIDU_APPID=token
9+
BAIDU_KEY=token

src/error.rs

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,53 @@
1+
use crate::translators::api::baidu::BaiduApiError;
2+
13
#[derive(Clone, Debug)]
24
#[allow(dead_code)]
3-
pub struct Error {
5+
pub enum Error {
6+
Text(TextError),
7+
Fetch(String),
8+
BaiduError(String),
9+
MissingToken(String),
10+
}
11+
12+
#[derive(Clone, Debug)]
13+
pub struct TextError {
414
pub message: String,
5-
error: Option<String>,
15+
pub error: Option<String>,
616
}
717

818
impl Error {
919
pub fn new(message: impl ToString, error: impl ToString) -> Self {
10-
Error {
20+
Error::Text(TextError {
1121
message: message.to_string(),
1222
error: Some(error.to_string()),
13-
}
23+
})
1424
}
1525

1626
pub fn new_option(message: impl ToString) -> Self {
17-
Error {
27+
Error::Text(TextError {
1828
message: message.to_string(),
1929
error: None,
20-
}
30+
})
31+
}
32+
33+
pub fn fetch(error: reqwest::Error) -> Self {
34+
Error::Fetch(error.to_string())
35+
}
36+
37+
pub fn baidu_error(message: BaiduApiError) -> Self {
38+
Self::BaiduError(format!(
39+
"Baidu error: Code: {}, Message: {}, Solution: {}, Data: {:?}",
40+
message.code,
41+
message.msg,
42+
message.solution(),
43+
message.data
44+
))
45+
}
46+
47+
pub fn missing_token(token: impl ToString) -> Self {
48+
Error::MissingToken(format!(
49+
"Missing token: {}. Add token to .env",
50+
token.to_string()
51+
))
2152
}
2253
}

src/lib.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,13 @@ pub mod translators;
99

1010
#[cfg(test)]
1111
mod tests {
12+
#[cfg(not(feature = "offline_req"))]
13+
use std::collections::HashMap;
14+
1215
use dotenv::dotenv;
1316
#[cfg(feature = "offline_req")]
1417
use model_manager::model_manager::ModelManager;
1518
use reqwest::Client;
16-
#[cfg(not(feature = "offline_req"))]
17-
use std::collections::HashMap;
1819

1920
use crate::detector;
2021
use crate::detector::Detectors;
@@ -44,7 +45,9 @@ mod tests {
4445
#[cfg(feature = "offline_req")]
4546
use crate::translators::translator_structure::TranslatorCTranslate;
4647
use crate::translators::translator_structure::TranslatorLanguages;
47-
use crate::translators::{Translator, Translators};
48+
use crate::translators::Translator;
49+
#[cfg(not(feature = "offline_req"))]
50+
use crate::translators::Translators;
4851

4952
#[tokio::test]
5053
#[cfg(feature = "offline_req")]

src/translators/api/baidu.rs

Lines changed: 92 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,89 @@
11
//https://docs.rs/crate/translation-api-cn/latest/source/src/baidu.rs
22

3+
use crate::error::Error;
4+
use crate::languages::Language;
5+
use crate::translators::translator_structure::{
6+
TranslationOutput, TranslationVecOutput, TranslatorNoContext,
7+
};
8+
use async_trait::async_trait;
39
use reqwest::Client;
410
use serde::{Deserialize, Serialize};
511
use serde_json::Value;
12+
use std::str::FromStr;
613

714
#[allow(dead_code)]
8-
struct BaiduApiTranslator {
15+
pub struct BaiduApiTranslator {
916
url: String,
17+
app_id: String,
18+
key: String,
1019
}
1120

12-
#[allow(dead_code)]
13-
impl BaiduApiTranslator {
14-
pub fn new() -> Self {
15-
Self {
16-
url: "https://fanyi-api.baidu.com/api/trans/vip/translate".to_string(),
17-
}
18-
}
19-
20-
pub async fn translate(
21+
#[async_trait]
22+
impl TranslatorNoContext for BaiduApiTranslator {
23+
async fn translate(
2124
&self,
2225
client: &Client,
2326
query: &str,
24-
from: &str,
25-
to: &str,
26-
key: &str,
27-
appid: &str,
28-
) {
29-
let form = Form::new(appid, query, "0", key, from, to);
30-
let resp = client
27+
from: Option<Language>,
28+
to: &Language,
29+
) -> Result<TranslationOutput, Error> {
30+
let form = Form::new(
31+
&self.app_id,
32+
query,
33+
"0",
34+
&self.key,
35+
&from
36+
.map(|v| v.to_baidu_str())
37+
.unwrap_or_else(|| Ok("auto".to_string()))?,
38+
&to.to_baidu_str()?,
39+
);
40+
let resp: Response = client
3141
.post(&self.url)
3242
.form(&form)
3343
.send()
3444
.await
35-
.unwrap()
36-
.text()
45+
.map_err(Error::fetch)?
46+
.json()
3747
.await
38-
.unwrap();
39-
print!("{}", resp);
48+
.map_err(Error::fetch)?;
49+
let resp = match resp {
50+
Response::Ok(v) => v,
51+
Response::Err(v) => return Err(Error::baidu_error(v)),
52+
};
53+
Ok(TranslationOutput {
54+
text: resp
55+
.trans_result
56+
.iter()
57+
.map(|v| v.dst.to_string())
58+
.collect::<Vec<_>>()
59+
.join("\n"),
60+
lang: Language::from_str(&resp.from).unwrap_or(Language::Unknown),
61+
})
62+
}
63+
64+
async fn translate_vec(
65+
&self,
66+
client: &Client,
67+
query: &[String],
68+
from: Option<Language>,
69+
to: &Language,
70+
) -> Result<TranslationVecOutput, Error> {
71+
let v = self.translate(client, &query.join("\n"), from, to).await?;
72+
Ok(TranslationVecOutput {
73+
text: v.text.split('\n').map(|v| v.to_string()).collect(),
74+
lang: v.lang,
75+
})
76+
}
77+
}
78+
79+
#[allow(dead_code)]
80+
impl BaiduApiTranslator {
81+
pub fn new(app_id: &str, key: &str) -> Self {
82+
Self {
83+
url: "https://fanyi-api.baidu.com/api/trans/vip/translate".to_string(),
84+
app_id: app_id.to_string(),
85+
key: key.to_string(),
86+
}
4087
}
4188
}
4289

@@ -67,30 +114,25 @@ impl Form {
67114
}
68115

69116
/// Response information. Either return the translation result, or return an error message.
70-
#[derive(Debug, Deserialize)]
117+
#[derive(Deserialize)]
71118
#[serde(untagged)]
72-
pub enum Response {
73-
Ok {
74-
from: String,
75-
to: String,
76-
/// Multiple translated texts separated by `\n` in the original text.
77-
#[serde(rename = "trans_result")]
78-
res: Vec<Value>,
79-
},
80-
Err(Error),
119+
enum Response {
120+
Ok(TranslationResponse),
121+
Err(BaiduApiError),
81122
}
82123

83124
/// Error handling / error code
84125
#[derive(Debug, Clone, Deserialize)]
85-
pub struct Error {
126+
pub struct BaiduApiError {
86127
#[serde(rename = "error_code")]
87128
pub code: String,
88129
#[serde(rename = "error_msg")]
89130
pub msg: String,
131+
pub data: Option<Value>,
90132
}
91133

92-
impl std::error::Error for Error {}
93-
impl std::fmt::Display for Error {
134+
impl std::error::Error for BaiduApiError {}
135+
impl std::fmt::Display for BaiduApiError {
94136
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95137
write!(f,
96138
"Error code: `{}`\nError message: `{}`\nError meaning: {}\nThe above content is returned by Baidu translation API",
@@ -100,7 +142,7 @@ impl std::fmt::Display for Error {
100142
}
101143
}
102144

103-
impl Error {
145+
impl BaiduApiError {
104146
///Reference: [Error Code List](https://fanyi-api.baidu.com/doc/21)
105147
pub fn solution(&self) -> &str {
106148
match self.code.as_bytes() {
@@ -123,3 +165,18 @@ impl Error {
123165
}
124166
}
125167
}
168+
169+
#[derive(Deserialize)]
170+
#[allow(dead_code)]
171+
struct Sentence {
172+
pub src: String,
173+
pub dst: String,
174+
}
175+
176+
#[derive(Deserialize)]
177+
#[allow(dead_code)]
178+
struct TranslationResponse {
179+
pub from: String,
180+
pub to: String,
181+
pub trans_result: Vec<Sentence>,
182+
}

src/translators/api/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
mod baidu;
1+
pub mod baidu;
22
#[cfg(feature = "chatgpt")]
33
pub mod chatgpt;
44
#[cfg(feature = "deepl")]
@@ -8,5 +8,5 @@ pub mod google;
88
pub mod libretranslate;
99
#[cfg(feature = "mymemory")]
1010
pub mod mymemory;
11-
mod papago;
12-
mod youdao;
11+
pub mod papago;
12+
pub mod youdao;

0 commit comments

Comments
 (0)