dptran 2.4.0

A tool to run DeepL translations on command line written by Rust.
Documentation
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
use core::fmt;

use crate::deeplapi::DeeplAPIMessage;

use super::DpTran;

use super::connection;
use connection::ConnectionError;
use super::DeeplAPIError;
use super::ApiKeyType;

use serde::{Deserialize, Serialize};

pub const DEEPL_API_GLOSSARIES: &str = "https://api-free.deepl.com/v3/glossaries";
pub const DEEPL_API_GLOSSARIES_PRO: &str = "https://api.deepl.com/v3/glossaries";
pub const DEEPL_API_GLOSSARIES_PAIRS: &str = "https://api-free.deepl.com/v2/glossary-language-pairs";
pub const DEEPL_API_GLOSSARIES_PRO_PAIRS: &str = "https://api.deepl.com/v2/glossary-language-pairs";

#[derive(Debug, PartialEq)]
pub enum GlossariesApiError {
    ConnectionError(ConnectionError),
    JsonError(String, String),
    CouldNotCreateGlossary,
    QuotaExceeded,
}
impl fmt::Display for GlossariesApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GlossariesApiError::ConnectionError(e) => write!(f, "Connection error: {}", e),
            GlossariesApiError::JsonError(e, j) => write!(f, "JSON error: {}\nJSON: {}", e, j),
            GlossariesApiError::CouldNotCreateGlossary => write!(f, "Could not create glossary on DeepL API by some reason"),
            GlossariesApiError::QuotaExceeded => write!(f, "Glossary quota exceeded on DeepL API"),
        }
    }
}

/// Glossary file format  
/// TSV: Tab-Separated Values  
/// CSV: Comma-Separated Values
#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq)]
pub enum GlossariesApiFormat {
    Tsv,
    Csv,
}
impl fmt::Display for GlossariesApiFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GlossariesApiFormat::Tsv => write!(f, "tsv"),
            GlossariesApiFormat::Csv => write!(f, "csv"),
        }
    }
}

/// Data structures for glossary API.
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug)]
pub struct GlossariesApiDictionaryPostData {
    source_lang: String,
    target_lang: String,
    entries: String,
    entries_format: String,
}

/// Response data structures for glossary API.
#[derive(serde::Deserialize, serde::Serialize)]
pub struct GlossariesApiDictionaryResponseData {
    pub source_lang: String,
    pub target_lang: String,
    pub entry_count: u64,
}

/// Glossary post data structure.  
/// Used to create a glossary via the DeepL API.  
/// You need to create an instance of this struct to send a glossary creation request.
#[derive(serde::Deserialize, serde::Serialize)]
pub struct GlossariesApiPostData {
    name: String,
    dictionaries: Vec<GlossariesApiDictionaryPostData>,
}

/// Response data structure for glossary creation via DeepL API.  
/// Returned when a glossary is successfully created.
#[derive(serde::Deserialize, serde::Serialize)]
pub struct GlossariesApiResponseData {
    pub glossary_id: String,
    pub name: String,
    pub dictionaries: Vec<GlossariesApiDictionaryResponseData>,
    pub creation_time: String,
}

/// List of glossaries registered in the DeepL API.
#[derive(serde::Deserialize, serde::Serialize)]
pub struct GlossariesApiList {
    pub glossaries: Vec<GlossariesApiResponseData>,
}

/// An entry of supported languages by Glossaries API.
#[derive(serde::Deserialize, serde::Serialize)]
pub struct GlossariesApiSupportedLanguageEntry {
    pub source_lang: String,
    pub target_lang: String,
}

/// List of supported languages by Glossaries API.
#[derive(serde::Deserialize, serde::Serialize)]
pub struct GlossariesApiSupportedLanguages {
    pub supported_languages: Vec<GlossariesApiSupportedLanguageEntry>,
}

impl GlossariesApiPostData {
    /// Create a glossary post data.
    pub fn new(glossary_name: String, dictionaries: Vec<GlossariesApiDictionaryPostData>) -> Self {
        let post_data = GlossariesApiPostData {
            name: glossary_name,
            dictionaries,
        };
        post_data
    }

    /// Create a curl session.
    pub fn send(&self, api: &DpTran) -> Result<GlossariesApiResponseData, GlossariesApiError> {
        let url = if api.api_key_type == ApiKeyType::Free {
            api.api_urls.glossaries_for_free.clone()
        } else {
            api.api_urls.glossaries_for_pro.clone()
        };
        
        // Prepare headers
        let header_auth_key = format!("Authorization: DeepL-Auth-Key {}", api.api_key);
        let header_content_type = "Content-Type: application/json";
        let headers = vec![header_auth_key, header_content_type.to_string()];
        let post_data_json = serde_json::to_string(self).unwrap();
        
        // Send request
        let ret = connection::post_with_headers(url, post_data_json, &headers);

        // Handle response
        match ret {
            Ok(res) => {
                // Error check
                let ret: Result<DeeplAPIMessage, serde_json::Error> = serde_json::from_str(&res);
                if let Ok(ret) = ret {
                    if ret.message == "Quota exceeded" {
                        return Err(GlossariesApiError::QuotaExceeded);
                    } else {
                        return Err(GlossariesApiError::CouldNotCreateGlossary);
                    }
                }

                // If there is no error, the response is GlossaryResponseData.
                // Parse response
                let ret: GlossariesApiResponseData = serde_json::from_str(&res).map_err(|e| GlossariesApiError::JsonError(e.to_string(), res.clone()))?;
                Ok(ret)
            },
            Err(e) => Err(GlossariesApiError::ConnectionError(e)),
        }
    }

    /// Get glossary dictionaries.
    pub fn get_dictionaries(&self) -> Vec<GlossariesApiDictionaryPostData> {
        self.dictionaries.clone()
    }
}

impl GlossariesApiResponseData {
    /// Get glossary details by glossary ID.
    /// `api`: DpTran instance
    /// `glossary_id`: Glossary ID
    pub fn get_glossary_details(api: &DpTran, glossary_id: &super::GlossaryID) -> Result<Self, DeeplAPIError> {
        let url = if api.api_key_type == ApiKeyType::Free {
            format!("{}/{}", api.api_urls.glossaries_for_free.clone(), glossary_id)
        } else {
            format!("{}/{}", api.api_urls.glossaries_for_pro.clone(), glossary_id)
        };

        // Prepare headers
        let header_auth_key = format!("Authorization: DeepL-Auth-Key {}", api.api_key);
        let headers = vec![header_auth_key];

        // Send request
        let ret = connection::get_with_headers(url, &headers);

        // Handle response
        match ret {
            Ok(res) => {
                let ret: GlossariesApiResponseData = serde_json::from_str(&res).map_err(|e| DeeplAPIError::JsonError(e.to_string(), res.clone()))?;
                Ok(ret)
            },
            Err(e) => Err(DeeplAPIError::ConnectionError(e)),
        }
    }
}

impl GlossariesApiDictionaryPostData {
    /// Make a new GlossariesApiDictionaryPostData.
    pub fn new(source_lang: &String, target_lang: &String, entries: &String, entries_format: &String) -> Self {
        GlossariesApiDictionaryPostData {
            source_lang: source_lang.clone(),
            target_lang: target_lang.clone(),
            entries: entries.clone(),
            entries_format: entries_format.clone(),
        }
    }

    /// Retrive entries from DeepL API.
    /// 
    /// `api`: DpTran instance
    /// `glossary_id`: GlossaryID
    pub fn retrieve_entries(&mut self, api: &DpTran, glossary_id: &String) -> Result<Self, DeeplAPIError> {
        let url = if api.api_key_type == ApiKeyType::Free {
            format!("{}/{}/entries?source_lang={}&target_lang={}", api.api_urls.glossaries_for_free.clone(), glossary_id, self.source_lang, self.target_lang)
        } else {
            format!("{}/{}/entries?source_lang={}&target_lang={}", api.api_urls.glossaries_for_pro.clone(), glossary_id, self.source_lang, self.target_lang)
        };

        // Prepare headers
        let header_auth_key = format!("Authorization: DeepL-Auth-Key {}", api.api_key);
        let headers = vec![header_auth_key];

        // Send request
        let ret = connection::get_with_headers(url, &headers);

        // Handle response
        match ret {
            Ok(res) => {
                // Parse response
                // For now, DeepL API returns the entries as a child object of "dictionaries" (not documented.. why??), so we need to extract it.
                #[derive(serde::Deserialize, Debug)]
                struct EntriesResponse {
                    dictionaries: Vec<GlossariesApiDictionaryPostData>,
                }
                let ret: EntriesResponse = serde_json::from_str(&res).map_err(|e| DeeplAPIError::JsonError(e.to_string(), res.clone()))?;
                let dictionary = &ret.dictionaries[0];
                Ok(dictionary.clone())
            },
            Err(e) => Err(DeeplAPIError::ConnectionError(e)),
        }
    }

    /// Get source language.
    pub fn get_source_lang(&self) -> &String {
        &self.source_lang
    }

    /// Get target language.
    pub fn get_target_lang(&self) -> &String {
        &self.target_lang
    }

    /// Get entries vector.
    pub fn get_entries_iter(&self) -> impl Iterator<Item = (String, String)> + '_ {
        let lines = self.entries.lines();
        lines.filter_map(|line| {
            let mut parts = if self.entries_format == "tsv" {
                line.split('\t')
            } else {
                line.split(',')
            };
            if let (Some(source), Some(target)) = (parts.next(), parts.next()) {
                Some((source.to_string(), target.to_string()))
            } else {
                None
            }
        })
    }
}

impl GlossariesApiList {
    /// Get a list of glossaries from the API server.
    pub fn get_registered_dictionaries(api: &DpTran) -> Result<Self, DeeplAPIError> {
        let url = if api.api_key_type == ApiKeyType::Free {
            api.api_urls.glossaries_for_free.clone()
        } else {
            api.api_urls.glossaries_for_pro.clone()
        };

        // Prepare headers
        let header_auth_key = format!("Authorization: DeepL-Auth-Key {}", api.api_key);
        let headers = vec![header_auth_key];

        // Send request
        let ret = connection::get_with_headers(url, &headers);

        // Handle response
        match ret {
            Ok(res) => {
                let ret: GlossariesApiList = serde_json::from_str(&res).map_err(|e| DeeplAPIError::JsonError(e.to_string(), res.clone()))?;
                Ok(ret)
            },
            Err(e) => Err(DeeplAPIError::ConnectionError(e)),
        }
    }
}

/// Delete the glossary via DeepL API.
pub fn delete_glossary(api: &DpTran, glossary_id: &String) -> Result<(), GlossariesApiError> {
    let url = if api.api_key_type == ApiKeyType::Free {
        format!("{}/{}", api.api_urls.glossaries_for_free.clone(), glossary_id)
    } else {
        format!("{}/{}", api.api_urls.glossaries_for_pro.clone(), glossary_id)
    };

    // Prepare headers
    let header_auth_key = format!("Authorization: DeepL-Auth-Key {}", api.api_key);
    let headers = vec![header_auth_key];

    // Send request
    let ret = connection::delete_with_headers(url, &headers);
    match ret {
        Ok(_) => Ok(()),
        Err(e) => Err(GlossariesApiError::ConnectionError(e)),
    }
}

/// Patch the glossary via DeepL API.
pub fn patch_glossary(api: &DpTran, glossary_id: &String, patch_data: &GlossariesApiPostData) -> Result<(), GlossariesApiError> {
    let url = if api.api_key_type == ApiKeyType::Free {
        format!("{}/{}", api.api_urls.glossaries_for_free.clone(), glossary_id)
    } else {
        format!("{}/{}", api.api_urls.glossaries_for_pro.clone(), glossary_id)
    };

    // Prepare headers
    let header_auth_key = format!("Authorization: DeepL-Auth-Key {}", api.api_key);
    let header_content_type = "Content-Type: application/json";
    let headers = vec![header_auth_key, header_content_type.to_string()];
    let patch_data_json = serde_json::to_string(patch_data).unwrap();
    // Send request
    let ret = connection::patch_with_headers(url, patch_data_json, &headers);
    match ret {
        Ok(_) => Ok(()),
        Err(e) => Err(GlossariesApiError::ConnectionError(e)),
    }
}

impl GlossariesApiSupportedLanguages {
    /// Get supported languages for Glossaries API.
    pub fn get(api: &DpTran) -> Result<GlossariesApiSupportedLanguages, GlossariesApiError> {
        let url = if api.api_key_type == ApiKeyType::Free {
            api.api_urls.glossaries_language_pairs_for_free.clone()
        } else {
            api.api_urls.glossaries_language_pairs_for_pro.clone()
        };
        
        // Prepare headers
        let header_auth_key = format!("Authorization: DeepL-Auth-Key {}", api.api_key);
        let headers = vec![header_auth_key];
        
        // Send request
        let ret = connection::get_with_headers(url, &headers);

        // Handle response
        match ret {
            Ok(res) => {
                let ret: GlossariesApiSupportedLanguages = serde_json::from_str(&res).map_err(|e| GlossariesApiError::JsonError(e.to_string(), res.clone()))?;
                Ok(ret)
            },
            Err(e) => Err(GlossariesApiError::ConnectionError(e)),
        }
    }

    /// Is the language pair supported?
    pub fn is_lang_pair_supported(&self, source_lang: &String, target_lang: &String) -> bool {
        for pair in &self.supported_languages {
            if pair.source_lang.to_ascii_uppercase() == source_lang.to_ascii_uppercase() 
                && pair.target_lang.to_ascii_uppercase() == target_lang.to_ascii_uppercase() {
                return true;
            }
        }
        false
    }
}

/// To run these tests, you need to set the environment variable `DPTRAN_DEEPL_API_KEY` to your DeepL API key.  
/// You should run these tests with ``cargo test -- --test-threads=1`` because the DeepL API has a limit on the number of requests per second.
/// And also, you need to run the dummy server for the DeepL API to test the API endpoints.
///   $ pip3 install -r requirements.txt
///   $ uvicorn dummy_api_server.main:app --reload
#[cfg(test)]
pub mod tests {
    use super::*;

    #[test]
    fn impl_glossaries_dictionary() {
        let dict = GlossariesApiDictionaryPostData::new(&"EN".to_string(), &"FR".to_string(), &"Hello\tBonjour\nGoodbye\tAu revoir".to_string(), &"tsv".to_string());
        assert_eq!(dict.get_source_lang(), &"EN".to_string());
    }

    #[test]
    fn impl_glossaries_post_data() {
        let dict1 = GlossariesApiDictionaryPostData::new(&"EN".to_string(), &"FR".to_string(), &"Hello\tBonjour\nGoodbye\tAu revoir".to_string(), &"tsv".to_string());
        let dict2 = GlossariesApiDictionaryPostData::new(&"DE".to_string(), &"EN".to_string(), &"Hallo\tHello\nTschüss\tGoodbye".to_string(), &"tsv".to_string());
        let glossaries_post_data = GlossariesApiPostData::new("MyGlossary".to_string(), vec![dict1.clone(), dict2.clone()]);
        let dictionaries = glossaries_post_data.get_dictionaries();
        assert_eq!(dictionaries.len(), 2);
        assert_eq!(dictionaries[0].get_source_lang(), &"EN".to_string());
    }

    #[test]
    fn api_glossaries_post_send() {
        // Send glossary creation request to DeepL API
        let api_key = std::env::var("DPTRAN_DEEPL_API_KEY").unwrap();
        let api = DpTran::with_endpoint(&api_key, &ApiKeyType::Free, super::super::super::tests::get_endpoint());
        let dict = GlossariesApiDictionaryPostData::new(&"EN".to_string(), &"FR".to_string(), &"Hello\tBonjour\nGoodbye\tAu revoir".to_string(), &"tsv".to_string());
        let glossaries = vec![dict];
        let post_data = GlossariesApiPostData::new("MyGlossary".to_string(), glossaries);
        let res = post_data.send(&api);
        assert!(res.is_ok());
        
        // Retrieve response data
        let glossary_response = GlossariesApiList::get_registered_dictionaries(&api);
        assert!(glossary_response.is_ok());

        let glossary_response = glossary_response.unwrap();
        assert!(glossary_response.glossaries.len() > 0);

        let created_glossary = &glossary_response.glossaries[0];
        assert_eq!(created_glossary.name, "MyGlossary".to_string());
        assert_eq!(created_glossary.dictionaries.len(), 1);
        assert_eq!(created_glossary.dictionaries[0].source_lang.to_uppercase(), "EN".to_string());
        assert_eq!(created_glossary.dictionaries[0].target_lang.to_uppercase(), "FR".to_string());
        assert_eq!(created_glossary.dictionaries[0].entry_count, 2);

        // Delete the created glossary
        let delete_res = delete_glossary(&api, &created_glossary.glossary_id);
        assert!(delete_res.is_ok());
    }

    #[test]
    fn api_glossaries_get_registered_dictionaries() {
        let api_key = std::env::var("DPTRAN_DEEPL_API_KEY").unwrap();
        let api = DpTran::with_endpoint(&api_key, &ApiKeyType::Free, super::super::super::tests::get_endpoint());
        let res = GlossariesApiList::get_registered_dictionaries(&api);
        assert!(res.is_ok());
    }

    #[test]
    fn api_glossaries_supported_languages() {
        let api_key = std::env::var("DPTRAN_DEEPL_API_KEY").unwrap();
        let api = DpTran::with_endpoint(&api_key, &ApiKeyType::Free, super::super::super::tests::get_endpoint());
        let res = GlossariesApiSupportedLanguages::get(&api);
        assert!(res.is_ok());
        let supported_languages = res.unwrap();
        assert!(supported_languages.is_lang_pair_supported(&"EN".to_string(), &"FR".to_string()));
        assert!(!supported_languages.is_lang_pair_supported(&"EN".to_string(), &"XX".to_string()));
    }

    #[test]
    fn api_glossaries_patch_glossary() {
        // Send glossary creation request to DeepL API
        let api_key = std::env::var("DPTRAN_DEEPL_API_KEY").unwrap();
        let api = DpTran::with_endpoint(&api_key, &ApiKeyType::Free, super::super::super::tests::get_endpoint());
        let dict = GlossariesApiDictionaryPostData::new(&"EN".to_string(), &"FR".to_string(), &"Hello\tBonjour\nGoodbye\tAu revoir".to_string(), &"tsv".to_string());
        let glossaries = vec![dict];
        let post_data = GlossariesApiPostData::new("MyGlossary".to_string(), glossaries);
        let res = post_data.send(&api);
        assert!(res.is_ok());

        // Retrieve response data
        let glossary_response = GlossariesApiList::get_registered_dictionaries(&api);
        assert!(glossary_response.is_ok());
        let glossary_response = glossary_response.unwrap();
        let created_glossary = &glossary_response.glossaries[0];
        
        // Patch the created glossary
        let new_dict = GlossariesApiDictionaryPostData::new(&"EN".to_string(), &"FR".to_string(), &"Hello\tBonjour!\nGoodbye\tAu revoir!".to_string(), &"tsv".to_string());
        let patch_data = GlossariesApiPostData::new("MyGlossaryUpdated".to_string(), vec![new_dict]);
        let patch_res = patch_glossary(&api, &created_glossary.glossary_id, &patch_data);
        assert!(patch_res.is_ok());

        // Retrieve updated glossary data
        let updated_glossary_response = GlossariesApiList::get_registered_dictionaries(&api);
        assert!(updated_glossary_response.is_ok());
        let updated_glossary_response = updated_glossary_response.unwrap();
        let updated_glossary = &updated_glossary_response.glossaries[0];
        assert_eq!(updated_glossary.name, "MyGlossaryUpdated".to_string());
        assert_eq!(updated_glossary.dictionaries.len(), 1);
        assert_eq!(updated_glossary.dictionaries[0].source_lang.to_uppercase(), "EN".to_string());
        assert_eq!(updated_glossary.dictionaries[0].target_lang.to_uppercase(), "FR".to_string());
        assert_eq!(updated_glossary.dictionaries[0].entry_count, 2);

        // Delete the created glossary
        let delete_res = delete_glossary(&api, &created_glossary.glossary_id);
        assert!(delete_res.is_ok());
    }

    #[test]
    fn impl_glossaries_api_format_debug() {
        let format_tsv = GlossariesApiFormat::Tsv;
        let format_csv = GlossariesApiFormat::Csv;
        assert_eq!(format!("{:?}", format_tsv), "Tsv");
        assert_eq!(format!("{:?}", format_csv), "Csv");
    }

    #[test]
    fn impl_get_entries_iter() {
        let tsv_data = "Hello\tこんにちは\nWorld\t世界";
        let dict_post_data = GlossariesApiDictionaryPostData::new(&"EN".to_string(), &"JA".to_string(), &tsv_data.to_string(), &"tsv".to_string());
        let mut iter = dict_post_data.get_entries_iter();
        let first = iter.next().unwrap();
        assert_eq!(first.0, "Hello".to_string());
        assert_eq!(first.1, "こんにちは".to_string());
        let second = iter.next().unwrap();
        assert_eq!(second.0, "World".to_string());
        assert_eq!(second.1, "世界".to_string());

        let csv_data = "Hello,こんにちは\nWorld,世界";
        let dict_post_data_csv = GlossariesApiDictionaryPostData::new(&"EN".to_string(), &"JA".to_string(), &csv_data.to_string(), &"csv".to_string());
        let mut iter_csv = dict_post_data_csv.get_entries_iter();
        let first_csv = iter_csv.next().unwrap();
        assert_eq!(first_csv.0, "Hello".to_string());
        assert_eq!(first_csv.1, "こんにちは".to_string());
        let second_csv = iter_csv.next().unwrap();
        assert_eq!(second_csv.0, "World".to_string());
        assert_eq!(second_csv.1, "世界".to_string());
    }
}