Basic API request to DeepL
This commit is contained in:
parent
3a9f283e99
commit
d2892b1f82
12 changed files with 1401 additions and 70 deletions
19
endolingual-macro/Cargo.toml
Normal file
19
endolingual-macro/Cargo.toml
Normal file
|
@ -0,0 +1,19 @@
|
|||
[package]
|
||||
name = "endolingual-macro"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
description = "Procedural macros for endolingual"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
proc-macro2 = "1.0"
|
||||
quote = "1.0"
|
||||
syn = { version = "2.0", features = ["full"] }
|
||||
reqwest = { version = "0.12.9", features = ["blocking", "json", "rustls-tls"], default-features = false }
|
||||
serde_json = "1.0"
|
||||
|
||||
[dev-dependencies]
|
||||
endolingual = { path = "../endolingual", version = "0.1.0" }
|
40
endolingual-macro/src/lib.rs
Normal file
40
endolingual-macro/src/lib.rs
Normal file
|
@ -0,0 +1,40 @@
|
|||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{parse_macro_input, LitStr};
|
||||
|
||||
#[proc_macro]
|
||||
pub fn translate(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as LitStr);
|
||||
let text = input.value();
|
||||
|
||||
let api_key =
|
||||
std::env::var("DEEPL_API_KEY").expect("Environment variable `DEEPL_API_KEY` must be set");
|
||||
|
||||
let client = reqwest::blocking::Client::new();
|
||||
let response = client
|
||||
.post("https://api.deepl.com/v2/translate")
|
||||
.header("Authorization", format!("DeepL-Auth-Key {}", api_key))
|
||||
.header("Content-Type", "application/json")
|
||||
.json(&serde_json::json!({
|
||||
"text": [text],
|
||||
"target_lang": "FR"
|
||||
}))
|
||||
.send()
|
||||
.expect("Failed to send request to DeepL API");
|
||||
|
||||
let translation = response
|
||||
.json::<serde_json::Value>()
|
||||
.expect("Failed to parse DeepL API response");
|
||||
|
||||
let translated_text = translation["translations"][0]["text"]
|
||||
.as_str()
|
||||
.expect("Failed to extract translated text");
|
||||
|
||||
quote! {
|
||||
TranslationSet {
|
||||
en: #text,
|
||||
fr: #translated_text,
|
||||
}
|
||||
}
|
||||
.into()
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue