DeepLApi

Struct DeepLApi 

Source
pub struct DeepLApi { /* private fields */ }
Expand description

A struct that contains necessary data for runtime. Data is stored in Arc, so it is cheap to clone in your App’s code.

§Example

// simple API creation
let deepl = DeepLApi::with("Your DeepL Key").new();

// **OR** customize it
let duration = std::time::Duration::from_secs(30);
let client = reqwest::Client::builder()
        .timeout(duration)
        .build()
        .unwrap();

// use the pro version API, and a custom client with
// 30 secs timeout
let deepl = DeepLApi::with("Your DeepL Key")
                .is_pro(true)
                .client(client)
                .new();

Implementations§

Source§

impl DeepLApi

Source

pub fn upload_document( &self, fp: impl Into<PathBuf>, target_lang: Lang, ) -> UploadDocumentRequester<'_>

Upload document to DeepL API server, return UploadDocumentResp for querying the translation status and to download the translated document once translation is complete.

§Example
use deepl::DeepLApi;

let key = std::env::var("DEEPL_API_KEY").unwrap();
let deepl = DeepLApi::with(&key).new();

// Upload the file to DeepL
let filepath = std::path::PathBuf::from("./hamlet.txt");
let response = deepl.upload_document(&filepath, Lang::ZH)
        .source_lang(Lang::EN)
        .filename("Hamlet.txt".to_string())
        .formality(Formality::Default)
        .glossary_id("def3a26b-3e84-45b3-84ae-0c0aaf3525f7".to_string())
        .await
        .unwrap();

Read the example upload_document in repository for detailed usage

Source

pub async fn check_document_status( &self, ident: &UploadDocumentResp, ) -> Result<DocumentStatusResp, Error>

Check the status of document, returning DocumentStatusResp if success.

Source

pub async fn download_document<O: AsRef<Path>>( &self, ident: &UploadDocumentResp, output: O, ) -> Result<PathBuf, Error>

Download the possibly translated document. Downloaded document will store to the given output path.

Return downloaded file’s path if success

Source§

impl DeepLApi

Source

pub fn create_glossary( &self, name: impl ToString, ) -> CreateGlossaryBuilder<'_, ((&'_ DeepLApi,), (String,), (), (), (), ())>

API for endpoint: https://www.deepl.com/de/docs-api/glossaries/create-glossary. The function for creating a glossary returns a JSON object containing the ID of the newly created glossary and a boolean flag that indicates if the created glossary can already be used in translate requests.

§Example
use crate::{glossary::EntriesFormat, DeepLApi, Lang};

let key = std::env::var("DEEPL_API_KEY").unwrap();
let deepl = DeepLApi::with(&key).new();

let _: CreateGlossaryResp = deepl
    .create_glossary("My Glossary")
    .source("Hello", Lang::EN)
    .target("Guten Tag", Lang::DE)
    .format(EntriesFormat::CSV) // This field is optional, we will use TSV as default.
    .send()
    .await
    .unwrap();
Source

pub async fn list_all_glossaries(&self) -> Result<Vec<GlossaryResp>, Error>

List all glossaries and their meta-information, but not the glossary entries.

Source

pub async fn retrieve_glossary_details( &self, id: impl ToString, ) -> Result<GlossaryResp, Error>

Retrieve meta information for a single glossary, omitting the glossary entries. Require a unique ID assigned to the glossary.

Source

pub async fn delete_glossary(&self, id: impl ToString) -> Result<(), Error>

Deletes the specified glossary.

Source

pub async fn retrieve_glossary_entries( &self, id: impl ToString, ) -> Result<Vec<(String, String)>, Error>

List the entries of a single glossary in the format specified by the Accept header. Currently, support TSV(tab separated value) only.

Source

pub async fn list_glossary_language_pairs( &self, ) -> Result<Vec<GlossaryLanguagePair>, Error>

Retrieve the list of language pairs supported by the glossary feature.

Source§

impl DeepLApi

Source

pub async fn languages( &self, lang_type: LangType, ) -> Result<Vec<LangInfo>, Error>

Retrieve supported languages for a given LangType

§Example
let target_langs = deepl.languages(LangType::Target).await.unwrap();
assert!(!target_langs.is_empty());

let lang = target_langs.first().unwrap();
println!("{}", lang.language); // BG
println!("{}", lang.name); // Bulgarian
Source§

impl DeepLApi

Source

pub fn translate_text( &self, text: impl ToString, target_lang: Lang, ) -> TranslateRequester<'_>

Translate the given text with specific target language.

§Error

Return Error if the http request fail

§Example
  • Simple translation
use deepl::{DeepLApi, Lang};

let key = std::env::var("DEEPL_API_KEY").unwrap();
let deepl = DeepLApi::with(&key).new();

let response = deepl.translate_text("Hello World", Lang::ZH).await.unwrap();
assert!(!response.translations.is_empty());
  • Translation with XML tag enabled
use deepl::{DeepLApi, Lang};

let key = std::env::var("DEEPL_API_KEY").unwrap();
let deepl = DeepLApi::with(&key).new();

let str = "Hello World <keep>This will stay exactly the way it was</keep>";
let response = deepl
    .translate_text(str, Lang::DE)
    .source_lang(Lang::EN)
    .ignore_tags(vec!["keep".to_owned()])
    .tag_handling(TagHandling::Xml)
    .await
    .unwrap();

let translated_results = response.translations;
let should = "Hallo Welt <keep>This will stay exactly the way it was</keep>";
assert_eq!(translated_results[0].text, should);
Source§

impl DeepLApi

Source

pub async fn get_usage(&self) -> Result<UsageResponse, Error>

Get the current DeepL API usage

§Example
use deepl::DeepLApi;

let key = std::env::var("DEEPL_API_KEY").unwrap();
let deepl = DeepLApi::with(&key).new();
let response = deepl.get_usage().await.unwrap();

assert_ne!(response.character_count, 0);
Source§

impl DeepLApi

Source

pub fn with(key: &str) -> DeepLApiBuilder

Create a new api instance with auth key.

Trait Implementations§

Source§

impl Clone for DeepLApi

Source§

fn clone(&self) -> DeepLApi

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DeepLApi

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more