Class: DeepL::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/deepl/client.rb

Overview

Client for the DeepL API. Every client owns its configuration and HTTP connection: two clients never share options, and nothing is read from environment variables.

client = DeepL::Client.new(ENV.fetch('DEEPL_AUTH_KEY'), app_info: { app_name: 'my-app',
                                                                    app_version: '1.2.3' })

All methods may raise a DeepL::Exceptions::Error or a subclass.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(auth_key, server_url: nil, headers: {}, max_retries: 5, timeout: 10, proxy: nil, send_platform_info: true, app_info: nil, http_client_options: nil, logger: nil) ⇒ Client

A keyword argument given as nil takes its default, like an omitted one.

Parameters:

  • auth_key (String) —

    Authentication key, surrounding whitespace is removed.

  • server_url (String, nil) (defaults to: nil) —

    Base URL of the DeepL API, an absolute http or https URL with a host; a port and a path prefix are kept, trailing slashes are removed. Defaults to https://api-free.deepl.com for Free keys (ending in :fx), else https://api.deepl.com.

  • headers (Hash) (defaults to: {}) —

    HTTP headers sent with every DeepL API request (pre-signed storage URLs get only a User-Agent). A header of the same name in any casing replaces the library's, Authorization and User-Agent included, except the technical headers Content-Type, Content-Length, Transfer-Encoding and Host.

  • max_retries (Integer, nil) (defaults to: 5) —

    Number of retries after the first attempt, for HTTP 429, any 5xx and transient network failures (not TLS failures or malformed responses). Requests that create a resource (glossaries, spoken terms, style rule lists and custom instructions, style profiles, document uploads, translation memory import and export jobs) are retried only after HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake, when the request was not processed.

  • timeout (Numeric, nil) (defaults to: 10) —

    Timeout of each attempt in seconds, applied to opening the connection, reading and writing. A longer backoff interval takes precedence.

  • proxy (String, URI, Hash, nil) (defaults to: nil) —

    Proxy URL (+http+ or https scheme) as a String or URI, e.g. http://user:[email protected]:8080, or a hash with proxy_addr and proxy_port (string or symbol keys, both required), which is a plain HTTP proxy. An https proxy is connected to over TLS and needs net-http 0.5.0 or later (bundled from Ruby 3.4) and an https server URL.

  • send_platform_info (Boolean, nil) (defaults to: true) —

    Whether to add the OS and Ruby versions to the User-Agent.

  • app_info (DeepL::AppInfo, Hash, nil) (defaults to: nil) —

    Your application's app_name and app_version, added to the User-Agent.

  • http_client_options (DeepL::HTTPClientOptions, nil) (defaults to: nil) —

    Proxy, certificate, SSL verification and per-phase timeouts. Its timeouts take precedence over timeout.

  • logger (Logger, nil) (defaults to: nil) —

    Logger for requests and retries.

Raises:

  • (ArgumentError) —

    If auth_key is empty, server_url is not an absolute http or https URL with a host, or proxy is not a valid proxy URL, URI or proxy hash (an empty host or blank proxy_addr is not valid), has a proxy URL scheme other than http or https, or is an https proxy that cannot be used (see proxy).



65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/deepl/client.rb', line 65

def initialize(auth_key, server_url: nil, headers: {}, max_retries: 5, timeout: 10, # rubocop:disable Metrics/ParameterLists
               proxy: nil, send_platform_info: true, app_info: nil, http_client_options: nil,
               logger: nil)
  free = self.class.(auth_key)
  default_server_url = free ? DEEPL_SERVER_URL_FREE : DEEPL_SERVER_URL
  @api = Utils::ClientBuilder.build_api(
    auth_key, key_name: 'auth_key', server_url: server_url,
              default_server_url: default_server_url, headers: headers,
              max_retries: max_retries, timeout: timeout, proxy: proxy,
              send_platform_info: send_platform_info, app_info: app_info,
              http_client_options: http_client_options, logger: logger
  )
end

Class Method Details

.free_account_auth_key?(auth_key) ⇒ Boolean

Returns true if auth_key is a DeepL API Free key (it ends with :fx).

Parameters:

  • auth_key (String, nil) —

    Authentication key.

Returns:

  • (Boolean)


25
26
27
# File 'lib/deepl/client.rb', line 25

def self.(auth_key)
  auth_key.to_s.strip.end_with?(':fx')
end

Instance Method Details

#correct_text(text, target_lang = nil, **options) ⇒ DeepL::Resources::Text+

Corrects the grammar, spelling and punctuation of text. Options set to nil are not sent.

Parameters:

  • text (String, Array<String>) —

    Text or texts to correct.

  • target_lang (String, nil) (defaults to: nil) —

    Target language, nil to keep the language of the text.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last; replaces fields of the same name. Any other option raises ArgumentError.

Returns:

Raises:

  • (ArgumentError) —

    If text is empty or contains an empty string, or target_lang is an empty string; nothing is sent.

  • (DeepL::Exceptions::Error) —

    If the response has fewer improvements than texts.



274
275
276
# File 'lib/deepl/client.rb', line 274

def correct_text(text, target_lang = nil, **options)
  Requests::Correct.new(api, text, target_lang, options).request
end

#create_glossary(name, source_lang, target_lang, entries, **options) ⇒ DeepL::Resources::Glossary

Creates a v2 glossary for one language pair. Glossaries are not regional, so a regional variant is sent as its base language (+EN-GB+ as EN).

Creation is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second glossary.

Parameters:

  • name (String) —

    Name of the glossary.

  • source_lang (String) —

    Source language.

  • target_lang (String) —

    Target language.

  • entries (Hash, Array<Array(String, String)>, String) —

    Source term to target term, as a hash, source/target pairs or a TSV string. Sent as TSV.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last.

Returns:

Raises:

  • (ArgumentError) —

    If name or entries is empty.

  • (DeepL::Exceptions::ValidationError) —

    (an ArgumentError) If a term is empty after stripping surrounding whitespace or contains a control character, a TSV line is not exactly two terms, or a source term appears twice.



349
350
351
352
353
354
355
# File 'lib/deepl/client.rb', line 349

def create_glossary(name, source_lang, target_lang, entries, **options)
  raise ArgumentError, 'Glossary entries must not be empty' if entries.nil? || entries.empty?

  tsv = Utils::GlossaryEntries.to_tsv(entries)
  Requests::Glossary::Create.new(api, name, source_lang, target_lang, tsv, 'tsv',
                                 options).request
end

#create_glossary_from_csv(name, source_lang, target_lang, csv, **options) ⇒ DeepL::Resources::Glossary

Creates a v2 glossary from CSV content, for example a file downloaded from the DeepL website.

Creation is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second glossary.

Parameters:

  • name (String) —

    Name of the glossary.

  • source_lang (String) —

    Source language.

  • target_lang (String) —

    Target language.

  • csv (String, IO) —

    CSV content, or an IO to read it from. Sent as given.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last.

Returns:

Raises:

  • (ArgumentError) —

    If name is empty.



373
374
375
376
377
378
# File 'lib/deepl/client.rb', line 373

def create_glossary_from_csv(name, source_lang, target_lang, csv, **options)
  csv = csv.read if csv.respond_to?(:read)

  Requests::Glossary::Create.new(api, name, source_lang, target_lang, csv, 'csv',
                                 options).request
end

#create_multilingual_glossary(name, dictionaries, **options) ⇒ DeepL::Resources::MultilingualGlossary

Creates a multilingual glossary with one dictionary per language pair.

Creation is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second glossary.

Parameters:

  • name (String) —

    Name of the glossary.

  • dictionaries (Array<DeepL::Resources::MultilingualGlossaryDictionaryEntries, Hash>) —

    One entry per language pair. A hash needs the keys :source_lang, :target_lang and :entries (a hash, source/target pairs or a TSV string; :entries_format 'csv' for a CSV string, which must not be empty or whitespace only and is otherwise sent as given). Entries other than a string are always sent as TSV.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last.

Returns:

Raises:

  • (DeepL::Exceptions::ValidationError) —

    (an ArgumentError) If a term is empty after stripping surrounding whitespace or contains a control character, or a TSV line is not exactly two terms.

  • (ArgumentError) —

    If name or dictionaries is empty, a dictionary has no entries (including empty or whitespace-only CSV entries), or a source_lang or target_lang of a dictionary is nil or empty, before any request.



449
450
451
452
# File 'lib/deepl/client.rb', line 449

def create_multilingual_glossary(name, dictionaries, **options)
  check_csv_entries!(dictionaries)
  Requests::MultilingualGlossary::Create.new(api, name, dictionaries, options).request
end

#create_multilingual_glossary_from_csv(name, source_lang, target_lang, csv, **options) ⇒ DeepL::Resources::MultilingualGlossary

Creates a multilingual glossary with one dictionary from CSV content.

Creation is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second glossary.

Parameters:

  • name (String) —

    Name of the glossary.

  • source_lang (String) —

    Source language of the dictionary.

  • target_lang (String) —

    Target language of the dictionary.

  • csv (String, IO) —

    CSV content, or an IO to read it from. Sent as given.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last.

Returns:

Raises:

  • (ArgumentError) —

    If name is empty, or source_lang or target_lang is nil or empty, before any request.



470
471
472
473
# File 'lib/deepl/client.rb', line 470

def create_multilingual_glossary_from_csv(name, source_lang, target_lang, csv, **options)
  dictionary = csv_dictionary(source_lang, target_lang, csv)
  Requests::MultilingualGlossary::Create.new(api, name, [dictionary], options).request
end

#create_spoken_terms(name, term_lists, **options) ⇒ DeepL::Resources::SpokenTerms

Creates a spoken terms collection, which improves the transcription of the given terms.

Creation is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second collection.

Parameters:

  • name (String) —

    Name of the collection.

  • term_lists (Array<DeepL::Resources::SpokenTermsEntries, Hash>) —

    One entry per language. A hash needs the keys :lang and :entries (an array of terms).

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last.

Returns:

Raises:

  • (DeepL::Exceptions::ValidationError) —

    (an ArgumentError) If a term is empty after stripping surrounding whitespace or contains a control character.

  • (ArgumentError) —

    If the lang of a term list is nil or empty, before any request.



671
672
673
# File 'lib/deepl/client.rb', line 671

def create_spoken_terms(name, term_lists, **options)
  Requests::SpokenTerms::Create.new(api, name, term_lists, options).request
end

#create_style_profile(name, description: nil, industry: nil, glossary_ids: nil, style_rule_ids: nil, translation_memory_ids: nil, glossary_priority_order_enabled: nil, **options) ⇒ DeepL::Resources::StyleProfile

Creates a style profile, which links glossaries, style rule lists and translation memories. Keywords left nil are not sent. If a component cannot be used, the request fails and no style profile is created.

Creation is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second style profile.

Parameters:

  • name (String) —

    Name of the style profile.

  • description (String, nil) (defaults to: nil) —

    Free-text description.

  • industry (String, nil) (defaults to: nil) —

    The industry the style profile is written for.

  • glossary_ids (Array<String, DeepL::Resources::Glossary, DeepL::Resources::MultilingualGlossary>, nil) (defaults to: nil) —

    Glossaries to link (IDs or objects), highest priority first.

  • style_rule_ids (Array<String, DeepL::Resources::StyleRule>, nil) (defaults to: nil) —

    Style rule lists.

  • translation_memory_ids (Array<String, DeepL::Resources::TranslationMemory>, nil) (defaults to: nil) —

    Translation memories.

  • glossary_priority_order_enabled (Boolean, nil) (defaults to: nil) —

    Whether the order of glossary_ids sets priority.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last.

Returns:



950
951
952
953
954
955
956
957
# File 'lib/deepl/client.rb', line 950

def create_style_profile(name, description: nil, industry: nil, glossary_ids: nil, # rubocop:disable Metrics/ParameterLists
                         style_rule_ids: nil, translation_memory_ids: nil,
                         glossary_priority_order_enabled: nil, **options)
  fields = { description: description, industry: industry, glossary_ids: glossary_ids,
             style_rule_ids: style_rule_ids, translation_memory_ids: translation_memory_ids,
             glossary_priority_order_enabled: glossary_priority_order_enabled }
  Requests::StyleProfile::Create.new(api, name, fields, options).request
end

#create_style_rule(name, language, configured_rules: nil, custom_instructions: nil, **options) ⇒ DeepL::Resources::StyleRule

Creates a style rule list. Keywords left nil are not sent.

Creation is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second style rule list.

Parameters:

  • name (String) —

    Name of the style rule list.

  • language (String) —

    Language the rules apply to, for example 'en'.

  • configured_rules (Hash, nil) (defaults to: nil) —

    Category -> rule -> value, sent as given.

  • custom_instructions (Array<Hash>, nil) (defaults to: nil) —

    Instructions in the wire shape (+label+, prompt and optionally source_language), sent as given.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last.

Returns:

Raises:

  • (ArgumentError) —

    If name or language is empty, or a custom instruction's source_language is empty, before any request.



792
793
794
795
796
797
# File 'lib/deepl/client.rb', line 792

def create_style_rule(name, language, configured_rules: nil, custom_instructions: nil,
                      **options)
  options = options.merge(configured_rules: configured_rules,
                          custom_instructions: custom_instructions).compact
  Requests::StyleRule::Create.new(api, name, language, options).request
end

#create_style_rule_custom_instruction(style_rule, label, prompt, source_language: nil, **options) ⇒ DeepL::Resources::CustomInstruction

Adds a custom instruction to a style rule list. source_language is not sent if nil.

Creation is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second custom instruction.

Parameters:

  • style_rule (String, DeepL::Resources::StyleRule) —

    ID or style rule list.

  • label (String) —

    Label of the instruction.

  • prompt (String) —

    The instruction.

  • source_language (String, nil) (defaults to: nil) —

    Source language the instruction applies to.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last.

Returns:

Raises:

  • (ArgumentError) —

    If the style rule ID, label or prompt is empty, source_language is empty (+nil+ leaves it unset), or the list has no ID, before any request.



866
867
868
869
870
# File 'lib/deepl/client.rb', line 866

def create_style_rule_custom_instruction(style_rule, label, prompt, source_language: nil,
                                         **options)
  Requests::StyleRule::CreateCustomInstruction.new(api, style_rule, label, prompt,
                                                   source_language, options).request
end

#create_translation_memory_export(translation_memory) ⇒ DeepL::Resources::TranslationMemoryExport

Creates an export job for a translation memory. Wait for it with #wait_until_translation_memory_job_done, then download the TMX file with #download_translation_memory_export.

Creation is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second export job.

Parameters:

Returns:

Raises:

  • (ArgumentError) —

    If the ID is empty or the object has no ID, before any request.



1154
1155
1156
# File 'lib/deepl/client.rb', line 1154

def create_translation_memory_export(translation_memory)
  translation_memories.create_export(translation_memory)
end

#create_translation_memory_import(file_name, content_length, content_type: nil, display_name: nil, extra_body_parameters: nil) ⇒ DeepL::Resources::TranslationMemoryImport

Creates an import job for a new translation memory. Upload the TMX file to the returned upload URL with #upload_translation_memory_file, then wait for the job with #wait_until_translation_memory_job_done. Keywords left nil are not sent.

Creation is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second import job.

Parameters:

  • file_name (String) —

    Name of the TMX file, for example 'legal.tmx'.

  • content_length (Integer) —

    Size of the file in bytes.

  • content_type (String, nil) (defaults to: nil) —

    MIME type of the file (API default: application/xml).

  • display_name (String, nil) (defaults to: nil) —

    Name of the translation memory (API default: the file name).

  • extra_body_parameters (Hash, nil) (defaults to: nil) —

    A hash added to the request body last.

Returns:

Raises:

  • (ArgumentError) —

    If file_name is empty or content_length is not positive, before any request.



1078
1079
1080
1081
1082
1083
# File 'lib/deepl/client.rb', line 1078

def create_translation_memory_import(file_name, content_length, content_type: nil,
                                     display_name: nil, extra_body_parameters: nil)
  translation_memories.create_import(file_name, content_length,
                                     content_type: content_type, display_name: display_name,
                                     extra_body_parameters: extra_body_parameters)
end

#delete_glossary(glossary) ⇒ nil

Deletes a v2 glossary.

Parameters:

Returns:

  • (nil)

Raises:



414
415
416
# File 'lib/deepl/client.rb', line 414

def delete_glossary(glossary)
  Requests::Glossary::Destroy.new(api, glossary).request
end

#delete_multilingual_glossary(glossary) ⇒ nil

Deletes a multilingual glossary.

Parameters:

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    If the glossary ID is empty or the glossary has no ID, before any request.



651
652
653
# File 'lib/deepl/client.rb', line 651

def delete_multilingual_glossary(glossary)
  Requests::MultilingualGlossary::Destroy.new(api, glossary).request
end

#delete_multilingual_glossary_dictionary(glossary, source_lang, target_lang) ⇒ nil

Deletes the dictionary of one language pair from a multilingual glossary.

Parameters:

  • glossary (String, DeepL::Resources::MultilingualGlossary) —

    ID or glossary.

  • source_lang (String) —

    Source language of the dictionary.

  • target_lang (String) —

    Target language of the dictionary.

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    If the glossary ID, source_lang or target_lang is empty, or the glossary has no ID, before any request.



639
640
641
642
# File 'lib/deepl/client.rb', line 639

def delete_multilingual_glossary_dictionary(glossary, source_lang, target_lang)
  Requests::MultilingualGlossary::DestroyDictionary.new(api, glossary, source_lang,
                                                        target_lang).request
end

#delete_spoken_terms(spoken_terms) ⇒ nil

Deletes a spoken terms collection.

Parameters:

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    If the ID is empty or the collection has no ID, before any request.



718
719
720
# File 'lib/deepl/client.rb', line 718

def delete_spoken_terms(spoken_terms)
  Requests::SpokenTerms::Destroy.new(api, spoken_terms).request
end

#delete_spoken_terms_list(spoken_terms, lang) ⇒ nil

Deletes the term list of one language of a collection.

Parameters:

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    If the ID is empty, the collection has no ID, or lang is nil or empty, before any request.



758
759
760
# File 'lib/deepl/client.rb', line 758

def delete_spoken_terms_list(spoken_terms, lang)
  Requests::SpokenTerms::DestroyTermList.new(api, spoken_terms, lang).request
end

#delete_style_profile(style_profile) ⇒ nil

Deletes a style profile.

Parameters:

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    If the ID is empty.



998
999
1000
1001
# File 'lib/deepl/client.rb', line 998

def delete_style_profile(style_profile)
  Requests::StyleProfile::Destroy.new(api, style_profile).request
  nil
end

#delete_style_rule(style_rule) ⇒ nil

Deletes a style rule list.

Parameters:

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    If the style rule ID is empty or the list has no ID, before any request.



845
846
847
848
# File 'lib/deepl/client.rb', line 845

def delete_style_rule(style_rule)
  Requests::StyleRule::Destroy.new(api, style_rule).request
  nil
end

#delete_style_rule_custom_instruction(style_rule, instruction_id) ⇒ nil

Deletes a custom instruction of a style rule list.

Parameters:

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    If the style rule or instruction ID is empty or the object has no ID, before any request.



913
914
915
916
# File 'lib/deepl/client.rb', line 913

def delete_style_rule_custom_instruction(style_rule, instruction_id)
  Requests::StyleRule::DestroyCustomInstruction.new(api, style_rule, instruction_id).request
  nil
end

#delete_translation_memory(translation_memory) ⇒ nil

Deletes a translation memory.

Parameters:

Returns:

  • (nil)

Raises:

  • (ArgumentError) —

    If the ID is empty or the object has no ID, before any request.



1032
1033
1034
1035
# File 'lib/deepl/client.rb', line 1032

def delete_translation_memory(translation_memory)
  translation_memories.destroy(translation_memory)
  nil
end

#download_translation_memory_export(job, output_path) ⇒ nil

Downloads the TMX file of a completed export job to output_path. The download URL is a pre-signed storage URL: no Authorization header and no configured headers are sent to it.

Parameters:

  • job (DeepL::Resources::TranslationMemoryJob) —

    The completed export job, as returned by #wait_until_translation_memory_job_done.

  • output_path (String) —

    Path to write the file to. Must not exist.

Returns:

  • (nil)

Raises:

  • (DeepL::Exceptions::Error) —

    If the job has no download URL, for example because it is not completed yet, before any request.

  • (SystemCallError) —

    Errno::EEXIST if output_path exists, Errno::ENOENT or Errno::EACCES if its directory is missing or not writable (checked before the request), or the error of writing the file.

  • (DeepL::Exceptions::Error) —

    If the download fails.



1173
1174
1175
1176
# File 'lib/deepl/client.rb', line 1173

def download_translation_memory_export(job, output_path)
  translation_memories.download_export(job, output_path)
  nil
end

#export_translation_memory_to_filepath(translation_memory, output_path, timeout_s: nil) ⇒ DeepL::Resources::TranslationMemoryJob

Exports a translation memory to a TMX file: creates the export job, waits until it is completed and writes the file to output_path.

Starting the export is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second export job.

Parameters:

  • translation_memory (String, DeepL::Resources::TranslationMemory) —

    ID or translation memory.

  • output_path (String) —

    Path to write the file to. Must not exist.

  • timeout_s (Numeric, nil) (defaults to: nil) —

    Maximum time in seconds to wait for the job, nil to wait until it is completed.

Returns:

Raises:

  • (DeepL::Exceptions::TranslationMemoryJobError) —

    For every failure, the original error as cause: output_path exists or its directory does not exist or is not writable (checked before the job is created), an empty ID or an object without one, a failed job creation, a job that fails or expires (with the API's error message), an expired timeout_s, a failed download or a failure writing the file. job_id is set once the job was created, job is the last status fetched (+nil+ before the first status check); http_status_code and should_retry? are those of a DeepL error cause.



1200
1201
1202
1203
# File 'lib/deepl/client.rb', line 1200

def export_translation_memory_to_filepath(translation_memory, output_path, timeout_s: nil)
  translation_memories.export_to_filepath(translation_memory, output_path,
                                          timeout_s: timeout_s)
end

#get_all_style_rules(page: nil, page_size: nil, detailed: nil) ⇒ Array<DeepL::Resources::StyleRule>

Lists style rule lists, one page at a time. Arguments left nil are not sent.

Parameters:

  • page (Integer, nil) (defaults to: nil) —

    Index of the page, starting at 0 (API default: 0).

  • page_size (Integer, nil) (defaults to: nil) —

    Style rule lists per page (API default: 10).

  • detailed (Boolean, nil) (defaults to: nil) —

    Whether to include configured_rules and custom_instructions.

Returns:



770
771
772
773
# File 'lib/deepl/client.rb', line 770

def get_all_style_rules(page: nil, page_size: nil, detailed: nil)
  options = { page: page, page_size: page_size, detailed: detailed }.compact
  Requests::StyleRule::List.new(api, options).request
end

#get_glossary(glossary) ⇒ DeepL::Resources::Glossary

Retrieves a v2 glossary, without its entries.

Parameters:

Returns:

Raises:



394
395
396
# File 'lib/deepl/client.rb', line 394

def get_glossary(glossary)
  Requests::Glossary::Find.new(api, glossary).request
end

#get_glossary_entries(glossary) ⇒ Hash{String => String}

Retrieves the entries of a v2 glossary.

Parameters:

Returns:

  • (Hash{String => String}) —

    Source term to target term.

Raises:



404
405
406
# File 'lib/deepl/client.rb', line 404

def get_glossary_entries(glossary)
  Requests::Glossary::Entries.new(api, glossary).request
end

#get_glossary_languages ⇒ Array<DeepL::Resources::LanguagePair>

Retrieves the language pairs supported by glossaries: every source language combined with every other target language of /v3/languages?resource=glossary.

Returns:



423
424
425
# File 'lib/deepl/client.rb', line 423

def get_glossary_languages # rubocop:disable Naming/AccessorMethodName
  Requests::Glossary::LanguagePairs.new(api).request
end

#get_language_resources ⇒ Array<DeepL::Resources::LanguageResource>

Retrieves the resources supported by the DeepL API with their features, and whether each feature requires support from the source and/or target language.

Returns:



301
302
303
# File 'lib/deepl/client.rb', line 301

def get_language_resources # rubocop:disable Naming/AccessorMethodName
  Requests::LanguageResources.new(api).request
end

#get_languages_for_resource(resource, include: nil) ⇒ Array<DeepL::Resources::LanguageSupport>

Retrieves the languages supported by resource, each with its per-feature support. The language codes are returned as the API sends them.

Parameters:

  • resource (String, Symbol) —

    Resource to query, see DeepL::Constants::LanguageResourceName. Other values are sent unchanged.

  • include (String, Array<String>, nil) (defaults to: nil) —

    Also return beta languages and features or features relying on third-party providers, see DeepL::Constants::LanguageInclude. Sent as one include query parameter per value; nil sends none, which returns stable languages and features only.

Returns:

Raises:

  • (ArgumentError) —

    If resource is empty.



317
318
319
# File 'lib/deepl/client.rb', line 317

def get_languages_for_resource(resource, include: nil)
  Requests::LanguagesForResource.new(api, resource, { include: include }.compact).request
end

#get_multilingual_glossary(glossary) ⇒ DeepL::Resources::MultilingualGlossary

Retrieves a multilingual glossary, without its entries.

Parameters:

Returns:

Raises:

  • (DeepL::Exceptions::NotFound) —

    If the glossary does not exist.

  • (ArgumentError) —

    If the glossary ID is empty or the glossary has no ID, before any request.



491
492
493
# File 'lib/deepl/client.rb', line 491

def get_multilingual_glossary(glossary)
  Requests::MultilingualGlossary::Find.new(api, glossary).request
end

#get_multilingual_glossary_dictionary_entries(glossary, source_lang, target_lang) ⇒ DeepL::Resources::MultilingualGlossaryDictionaryEntries

Retrieves the entries of the dictionary of one language pair.

Parameters:

  • glossary (String, DeepL::Resources::MultilingualGlossary) —

    ID or glossary.

  • source_lang (String) —

    Source language of the dictionary.

  • target_lang (String) —

    Target language of the dictionary.

Returns:

Raises:

  • (DeepL::Exceptions::NotFound) —

    If the glossary does not exist or has no dictionary for the language pair (HTTP 404), or if the API answers 200 with no entries for the pair (then without response and with http_status_code nil).

  • (ArgumentError) —

    If the glossary ID is empty, the glossary has no ID, or source_lang or target_lang is nil or empty, before any request.



626
627
628
# File 'lib/deepl/client.rb', line 626

def get_multilingual_glossary_dictionary_entries(glossary, source_lang, target_lang)
  Requests::MultilingualGlossary::Entries.new(api, glossary, source_lang, target_lang).request
end

#get_source_languages ⇒ Array<DeepL::Resources::Language>

Retrieves the languages that can be translated from, with upper-case codes (+EN+, DE).

Returns:



283
284
285
# File 'lib/deepl/client.rb', line 283

def get_source_languages # rubocop:disable Naming/AccessorMethodName
  Requests::Languages.new(api, :source).request
end

#get_spoken_terms(spoken_terms) ⇒ DeepL::Resources::SpokenTerms

Retrieves a spoken terms collection.

Parameters:

Returns:

Raises:

  • (DeepL::Exceptions::NotFound) —

    If the collection does not exist.

  • (ArgumentError) —

    If the ID is empty or the collection has no ID, before any request.



690
691
692
# File 'lib/deepl/client.rb', line 690

def get_spoken_terms(spoken_terms)
  Requests::SpokenTerms::Find.new(api, spoken_terms).request
end

#get_spoken_terms_entries(spoken_terms, lang) ⇒ DeepL::Resources::SpokenTermsEntries

Retrieves the terms of one language of a collection.

Parameters:

Returns:

Raises:

  • (ArgumentError) —

    If the ID is empty, the collection has no ID, or lang is nil or empty, before any request.



730
731
732
# File 'lib/deepl/client.rb', line 730

def get_spoken_terms_entries(spoken_terms, lang)
  Requests::SpokenTerms::Entries.new(api, spoken_terms, lang).request
end

#get_style_profile(style_profile) ⇒ DeepL::Resources::StyleProfile

Retrieves a style profile.

Parameters:

Returns:

Raises:



966
967
968
# File 'lib/deepl/client.rb', line 966

def get_style_profile(style_profile)
  Requests::StyleProfile::Find.new(api, style_profile).request
end

#get_style_rule(style_rule) ⇒ DeepL::Resources::StyleRule

Retrieves a style rule list, including its configured rules and custom instructions.

Parameters:

Returns:

Raises:

  • (DeepL::Exceptions::NotFound) —

    If the style rule list does not exist.

  • (ArgumentError) —

    If the style rule ID is empty or the list has no ID, before any request.



807
808
809
# File 'lib/deepl/client.rb', line 807

def get_style_rule(style_rule)
  Requests::StyleRule::Find.new(api, style_rule).request
end

#get_style_rule_custom_instruction(style_rule, instruction_id) ⇒ DeepL::Resources::CustomInstruction

Retrieves a custom instruction of a style rule list.

Parameters:

Returns:

Raises:

  • (DeepL::Exceptions::NotFound) —

    If the instruction does not exist.

  • (ArgumentError) —

    If the style rule or instruction ID is empty or the object has no ID, before any request.



881
882
883
# File 'lib/deepl/client.rb', line 881

def get_style_rule_custom_instruction(style_rule, instruction_id)
  Requests::StyleRule::FindCustomInstruction.new(api, style_rule, instruction_id).request
end

#get_target_languages ⇒ Array<DeepL::Resources::Language>

Retrieves the languages that can be translated into, with upper-case codes (+EN-GB+, DE).

Returns:



292
293
294
# File 'lib/deepl/client.rb', line 292

def get_target_languages # rubocop:disable Naming/AccessorMethodName
  Requests::Languages.new(api, :target).request
end

#get_translation_memory(translation_memory) ⇒ DeepL::Resources::TranslationMemory

Retrieves a translation memory.

Parameters:

Returns:

Raises:

  • (DeepL::Exceptions::NotFound) —

    If the translation memory does not exist.

  • (ArgumentError) —

    If the ID is empty or the object has no ID, before any request.



1021
1022
1023
# File 'lib/deepl/client.rb', line 1021

def get_translation_memory(translation_memory)
  translation_memories.find(translation_memory)
end

#get_translation_memory_job(job) ⇒ DeepL::Resources::TranslationMemoryJob

Retrieves the status of a translation memory import or export job once.

Parameters:

Returns:

Raises:

  • (ArgumentError) —

    If the ID is empty or the object has no ID, before any request.



1211
1212
1213
# File 'lib/deepl/client.rb', line 1211

def get_translation_memory_job(job)
  translation_memories.find_job(job)
end

#get_usage ⇒ DeepL::Resources::Usage

Retrieves the usage and limits of the account and, for API Pro, of this API key.

Returns:



325
326
327
# File 'lib/deepl/client.rb', line 325

def get_usage # rubocop:disable Naming/AccessorMethodName
  Requests::Usage.new(api).request
end

#import_translation_memory_from_filepath(input_path, display_name: nil, content_type: nil, timeout_s: nil, extra_body_parameters: nil) ⇒ DeepL::Resources::TranslationMemoryJob

Imports a TMX file as a new translation memory: creates the import job, uploads the file and waits until the job is completed.

Creating the import job is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second import job.

Parameters:

  • input_path (String) —

    Path of the TMX file.

  • display_name (String, nil) (defaults to: nil) —

    Name of the translation memory (API default: the file name).

  • content_type (String, nil) (defaults to: nil) —

    MIME type of the file, declared in the import job and sent with the upload. nil uses application/xml.

  • timeout_s (Numeric, nil) (defaults to: nil) —

    Maximum time in seconds to wait for the job, nil to wait until it is completed. The API reports awaiting_input for a while after the upload.

  • extra_body_parameters (Hash, nil) (defaults to: nil) —

    A hash added to the body of the import job request last.

Returns:

Raises:

  • (ArgumentError) —

    If the file does not exist, before any request is sent.

  • (DeepL::Exceptions::TranslationMemoryJobError) —

    For any other failure, the original error as cause: an empty or unreadable file (before any request), an invalid argument or failure of the job creation, a failed upload, a job that fails or expires (with the API's error message), or an expired timeout_s. job_id is set once the job was created, job is the last status fetched (+nil+ before the first status check); http_status_code and should_retry? are those of a DeepL error cause.



1131
1132
1133
1134
1135
1136
1137
# File 'lib/deepl/client.rb', line 1131

def import_translation_memory_from_filepath(input_path, display_name: nil, content_type: nil,
                                            timeout_s: nil, extra_body_parameters: nil)
  translation_memories.import_from_filepath(
    input_path, display_name: display_name, content_type: content_type, timeout_s: timeout_s,
                extra_body_parameters: extra_body_parameters
  )
end

#inspect ⇒ Object



1230
1231
1232
# File 'lib/deepl/client.rb', line 1230

def inspect
  "#<#{self.class.name} server_url=#{configuration.host}>"
end

#list_glossaries ⇒ Array<DeepL::Resources::Glossary>

Lists all v2 glossaries.

Returns:



384
385
386
# File 'lib/deepl/client.rb', line 384

def list_glossaries
  Requests::Glossary::List.new(api).request
end

#list_multilingual_glossaries ⇒ Array<DeepL::Resources::MultilingualGlossary>

Lists all multilingual glossaries.



479
480
481
# File 'lib/deepl/client.rb', line 479

def list_multilingual_glossaries
  Requests::MultilingualGlossary::List.new(api).request
end

#list_spoken_terms ⇒ Array<DeepL::Resources::SpokenTerms>

Lists all spoken terms collections.

Returns:



679
680
681
# File 'lib/deepl/client.rb', line 679

def list_spoken_terms
  Requests::SpokenTerms::List.new(api).request
end

#list_style_profiles(page: nil, page_size: nil) ⇒ Array<DeepL::Resources::StyleProfile>

Lists style profiles, one page at a time. Arguments left nil are not sent.

Parameters:

  • page (Integer, nil) (defaults to: nil) —

    Index of the page, starting at 0 (API default: 0).

  • page_size (Integer, nil) (defaults to: nil) —

    Style profiles per page (API default: 10, at most 100).

Returns:



924
925
926
# File 'lib/deepl/client.rb', line 924

def list_style_profiles(page: nil, page_size: nil)
  Requests::StyleProfile::List.new(api, { page: page, page_size: page_size }.compact).request
end

#list_translation_memories(page: nil, page_size: nil) ⇒ Array<DeepL::Resources::TranslationMemory>

Lists translation memories, one page at a time. Arguments left nil are not sent.

Parameters:

  • page (Integer, nil) (defaults to: nil) —

    Index of the page, starting at 0 (API default: 0).

  • page_size (Integer, nil) (defaults to: nil) —

    Translation memories per page (API default: 10).

Returns:



1009
1010
1011
# File 'lib/deepl/client.rb', line 1009

def list_translation_memories(page: nil, page_size: nil)
  translation_memories.list({ page: page, page_size: page_size }.compact)
end

#list_translation_memory_segments(translation_memory, page_size: nil, page_cursor: nil, filter_text: nil, filter_case_sensitive: nil) ⇒ DeepL::Resources::TranslationMemorySegments

Retrieves one page of the segments of a translation memory. Pagination is cursor-based: omit page_cursor on the first call, then pass the next_page_cursor of the previous page until it is nil. Arguments left nil are not sent.

Parameters:

  • translation_memory (String, DeepL::Resources::TranslationMemory) —

    ID or translation memory.

  • page_size (Integer, nil) (defaults to: nil) —

    Segments per page, 1-100 (API default: 50).

  • page_cursor (String, nil) (defaults to: nil) —

    next_page_cursor of the previous page.

  • filter_text (String, nil) (defaults to: nil) —

    Substring matched against source and target texts, at least 2 characters.

  • filter_case_sensitive (Boolean, nil) (defaults to: nil) —

    Whether filter_text is case-sensitive (API default: false).

Returns:

Raises:

  • (ArgumentError) —

    If the ID is empty or the object has no ID, before any request.



1052
1053
1054
1055
1056
1057
# File 'lib/deepl/client.rb', line 1052

def list_translation_memory_segments(translation_memory, page_size: nil, page_cursor: nil,
                                     filter_text: nil, filter_case_sensitive: nil)
  options = { page_size: page_size, page_cursor: page_cursor, filter_text: filter_text,
              filter_case_sensitive: filter_case_sensitive }.compact
  translation_memories.segments(translation_memory, options)
end

#rephrase_text(text, target_lang = nil, writing_style: nil, tone: nil, **options) ⇒ DeepL::Resources::Text+

Rephrases text, optionally into another variant or language and with a writing style or tone. Options set to nil are not sent.

Parameters:

  • text (String, Array<String>) —

    Text or texts to rephrase.

  • target_lang (String, nil) (defaults to: nil) —

    Target language, nil to keep the language of the text.

  • writing_style (String, nil) (defaults to: nil) —

    Writing style, see DeepL::Constants::WritingStyle. Cannot be combined with tone.

  • tone (String, nil) (defaults to: nil) —

    Tone, see DeepL::Constants::Tone.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last; replaces fields of the same name. Any other option raises ArgumentError.

Returns:

Raises:

  • (ArgumentError) —

    If text is empty or contains an empty string, target_lang is an empty string, or an option is unknown; nothing is sent.

  • (DeepL::Exceptions::Error) —

    If the response has fewer improvements than texts.



257
258
259
# File 'lib/deepl/client.rb', line 257

def rephrase_text(text, target_lang = nil, writing_style: nil, tone: nil, **options)
  Requests::Rephrase.new(api, text, target_lang, writing_style, tone, options).request
end

#replace_multilingual_glossary_dictionary(glossary, dictionary, **options) ⇒ DeepL::Resources::MultilingualGlossaryDictionary

Replaces the entries of the dictionary of one language pair, or adds the dictionary if the language pair is new.

Parameters:

Returns:

Raises:

  • (DeepL::Exceptions::ValidationError) —

    (an ArgumentError) If a term is empty after stripping or contains a control character.

  • (ArgumentError) —

    If the glossary ID or the entries are empty (CSV entries also if whitespace only), a source_lang or target_lang of a dictionary is nil or empty, or the glossary has no ID, before any request.



587
588
589
590
591
# File 'lib/deepl/client.rb', line 587

def replace_multilingual_glossary_dictionary(glossary, dictionary, **options)
  check_csv_entries!([dictionary])
  Requests::MultilingualGlossary::ReplaceDictionary.new(api, glossary, dictionary,
                                                        options).request
end

#replace_multilingual_glossary_dictionary_from_csv(glossary, source_lang, target_lang, csv, **options) ⇒ DeepL::Resources::MultilingualGlossaryDictionary

Replaces the entries of the dictionary of one language pair with CSV content.

Parameters:

  • glossary (String, DeepL::Resources::MultilingualGlossary) —

    ID or glossary.

  • source_lang (String) —

    Source language of the dictionary.

  • target_lang (String) —

    Target language of the dictionary.

  • csv (String, IO) —

    CSV content, or an IO to read it from. Must not be empty or whitespace only; otherwise sent as given.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last.

Returns:

Raises:

  • (ArgumentError) —

    If the CSV content is empty or whitespace only, source_lang or target_lang is nil or empty, the glossary ID is empty or the glossary has no ID, before any request.



606
607
608
609
610
611
# File 'lib/deepl/client.rb', line 606

def replace_multilingual_glossary_dictionary_from_csv(glossary, source_lang, target_lang, csv,
                                                      **options)
  dictionary = non_empty_csv_dictionary(source_lang, target_lang, csv)
  Requests::MultilingualGlossary::ReplaceDictionary.new(api, glossary, dictionary,
                                                        options).request
end

#replace_spoken_terms_list(spoken_terms, entries, **options) ⇒ DeepL::Resources::SpokenTermsList

Replaces the terms of one language, or adds the list if the language is new.

Parameters:

Returns:

Raises:

  • (DeepL::Exceptions::ValidationError) —

    (an ArgumentError) If a term is empty after stripping or contains a control character.

  • (ArgumentError) —

    If the ID is empty, the collection has no ID, or the lang of the term list is nil or empty, before any request.



746
747
748
# File 'lib/deepl/client.rb', line 746

def replace_spoken_terms_list(spoken_terms, entries, **options)
  Requests::SpokenTerms::ReplaceTermList.new(api, spoken_terms, entries, options).request
end

#translate_document(input_path, output_path, source_lang, target_lang, timeout_s: nil, **options) ⇒ DeepL::Resources::DocumentTranslationStatus

Translates the document at input_path and writes the result to output_path: uploads it, waits until the translation is done and downloads it.

The upload is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second document.

Parameters:

  • input_path (String) —

    Path of the document to translate.

  • output_path (String) —

    Path to write the translated document to. Must not exist.

  • source_lang (String, nil) —

    Source language, nil to detect it.

  • target_lang (String) —

    Target language.

  • timeout_s (Numeric, nil) (defaults to: nil) —

    Maximum time in seconds to wait for the translation after the upload, nil to wait until it is done.

  • options (Hash) —

    The options of #translate_document_upload, including :filename.

Returns:

Raises:

  • (ArgumentError) —

    If input_path does not exist; nothing is uploaded.

  • (DeepL::Exceptions::DocumentTranslationError) —

    For any other failure: an existing output_path (the file is kept) or one whose directory is missing or not writable, both checked before the upload; an argument error of #translate_document_upload, such as an unknown option, raised before anything is sent; a failed translation or an expired timeout_s. Its document_handle is set once the upload succeeded, so the document can still be queried and downloaded. http_status_code and should_retry? are those of the DeepL error that caused it, if any.



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/deepl/client.rb', line 139

def translate_document(input_path, output_path, source_lang, target_lang, timeout_s: nil, # rubocop:disable Metrics/MethodLength
                       **options)
  raise ArgumentError, "Input file does not exist: #{input_path}" unless File.exist?(input_path)

  check_document_output_path(output_path)
  handle = nil
  begin
    handle = translate_document_upload(input_path, source_lang, target_lang, **options)
    status = translate_document_wait_until_done(handle, timeout_s: timeout_s)
    translate_document_download(handle, output_path)
    status
  rescue StandardError => e
    FileUtils.rm_f(output_path)
    raise Exceptions::DocumentTranslationError.new(
      "Error occurred during document translation: #{e.message}", handle, e
    )
  end
end

#translate_document_download(handle, output_path) ⇒ nil

Downloads the translated document to output_path.

Parameters:

  • handle (DeepL::Resources::DocumentHandle) —

    Handle returned by the upload.

  • output_path (String) —

    Path to write the translated document to. Must not exist.

Returns:

  • (nil)

Raises:

  • (SystemCallError) —

    Before the request: Errno::EEXIST if output_path exists, Errno::ENOENT if its directory does not exist, Errno::EACCES if the directory is not writable.

  • (DeepL::Exceptions::DocumentNotReadyError) —

    If the translation is not done yet.



234
235
236
237
238
239
# File 'lib/deepl/client.rb', line 234

def translate_document_download(handle, output_path)
  Utils::OutputPath.check!(output_path)
  Requests::Document::Download.new(api, handle.document_id, handle.document_key,
                                   output_path).request
  nil
end

#translate_document_get_status(handle) ⇒ DeepL::Resources::DocumentTranslationStatus

Queries the status of a document translation once.

Parameters:

Returns:



207
208
209
# File 'lib/deepl/client.rb', line 207

def translate_document_get_status(handle)
  Requests::Document::GetStatus.new(api, handle.document_id, handle.document_key).request
end

#translate_document_upload(input_path, source_lang, target_lang, **options) ⇒ DeepL::Resources::DocumentHandle

Uploads the document at input_path for translation. Options set to nil are not sent.

The upload is retried only after failures that show the request was not processed (HTTP 429 and transient network failures while connecting, such as DNS resolution errors, refused connections, unreachable hosts or networks, connection timeouts and resets during the TLS or proxy handshake), so that a retry cannot create a second document.

Parameters:

  • input_path (String) —

    Path of the document to translate.

  • source_lang (String, nil) —

    Source language, nil to detect it.

  • target_lang (String) —

    Target language.

  • options (Hash) —

    Document translation options. Any other option raises ArgumentError before a request is sent:

    • :filename - File name sent with the upload, including its extension. Defaults to the base name of input_path.
    • :formality, :output_format - Sent unchanged.
    • :enable_watermark - true or false.
    • :glossary - A glossary ID, DeepL::Resources::Glossary or DeepL::Resources::MultilingualGlossary, sent as glossary_id. Requires source_lang.
    • :glossary_ids - Up to 5 glossaries (IDs or objects). Requires source_lang and cannot be combined with :glossary.
    • :style_rule, :style_profile, :translation_memory - An ID or the resource object. nil leaves it unset.
    • :translation_memory_threshold - Integer 0-100. Requires :translation_memory.
    • :extra_body_parameters - A hash added to the form last; replaces fields of the same name. A nil value removes the field, the library's own field of that name included.

Returns:

Raises:

  • (ArgumentError) —

    If input_path does not exist, target_lang or a given source_lang is empty, an option is unknown, :glossary or :glossary_ids is set without source_lang, the glossary options are combined or more than 5 are given, :glossary, :style_rule, :style_profile, :translation_memory or an entry of :glossary_ids is an empty ID or a resource object without its ID, or :translation_memory_threshold is set without :translation_memory or is not from 0 to 100; nothing is uploaded.

  • (SystemCallError) —

    If input_path cannot be read, e.g. Errno::EISDIR for a directory or Errno::EACCES; nothing is uploaded.



193
194
195
196
197
198
199
200
# File 'lib/deepl/client.rb', line 193

def translate_document_upload(input_path, source_lang, target_lang, **options)
  raise ArgumentError, "Input file does not exist: #{input_path}" unless File.exist?(input_path)
  raise Errno::EISDIR, input_path if File.directory?(input_path)

  filename = options.delete(:filename)
  Requests::Document::Upload.new(api, input_path, source_lang, target_lang, filename,
                                 options).request
end

#translate_document_wait_until_done(handle, timeout_s: nil) ⇒ DeepL::Resources::DocumentTranslationStatus

Polls the status of a document translation every 5 seconds until it is done.

Parameters:

  • handle (DeepL::Resources::DocumentHandle) —

    Handle returned by the upload.

  • timeout_s (Numeric, nil) (defaults to: nil) —

    Maximum time to wait in seconds, nil to wait until the translation is done or failed.

Returns:

Raises:



220
221
222
# File 'lib/deepl/client.rb', line 220

def translate_document_wait_until_done(handle, timeout_s: nil)
  Utils::DocumentPoller.wait_until_done(api, handle, timeout_s: timeout_s)
end

#translate_text(text, source_lang, target_lang, **options) ⇒ DeepL::Resources::Text+

Translates text from source_lang into target_lang. Always requests the billed characters; options set to nil are not sent.

Parameters:

  • text (String, Array<String>) —

    Text or texts to translate.

  • source_lang (String, nil) —

    Source language, nil to detect it.

  • target_lang (String) —

    Target language.

  • options (Hash) —

    Translation options. Any other option raises ArgumentError before a request is sent:

    • :glossary - A glossary ID, DeepL::Resources::Glossary or DeepL::Resources::MultilingualGlossary, sent as glossary_id.
    • :glossary_ids - Up to 5 glossaries (IDs or objects). Cannot be combined with :glossary. Without source_lang, the API detects it.
    • :style_rule, :style_profile, :translation_memory - An ID or the resource object. nil leaves it unset.
    • :split_sentences - +true+/+false+ are sent as +'1'+/+'0'+.
    • :custom_instructions - An array of instructions; a string is one instruction.
    • :extra_body_parameters - A hash added to the request body last; replaces fields of the same name.
    • :formality, :context, :tag_handling, :tag_handling_version, :model_type, :preserve_formatting, :outline_detection, :splitting_tags, :non_splitting_tags, :ignore_tags - Sent unchanged.
    • :translation_memory_threshold - Integer 0-100. Requires :translation_memory.

Returns:

Raises:

  • (ArgumentError) —

    If text is empty or contains an empty string, target_lang or a given source_lang is empty, an option is unknown, the glossary options are combined or more than 5 are given, :glossary, :style_rule, :style_profile, :translation_memory or an entry of :glossary_ids is an empty ID or a resource object without its ID, or :translation_memory_threshold is set without :translation_memory or is not from 0 to 100; nothing is sent.



110
111
112
# File 'lib/deepl/client.rb', line 110

def translate_text(text, source_lang, target_lang, **options)
  Requests::Translate.new(api, text, source_lang, target_lang, options).request
end

#update_multilingual_glossary(glossary, name: nil, dictionaries: nil, **options) ⇒ DeepL::Resources::MultilingualGlossary

Renames a glossary and/or merges entries into its dictionaries. Arguments left nil are not sent; without any, an empty object is sent.

Parameters:

Returns:

Raises:

  • (DeepL::Exceptions::ValidationError) —

    (an ArgumentError) If a term is empty after stripping or contains a control character.

  • (ArgumentError) —

    If the glossary ID or the entries of a dictionary are empty (CSV entries also if whitespace only), a source_lang or target_lang of a dictionary is nil or empty, or the glossary has no ID, before any request.



511
512
513
514
515
# File 'lib/deepl/client.rb', line 511

def update_multilingual_glossary(glossary, name: nil, dictionaries: nil, **options)
  check_csv_entries!(dictionaries) unless dictionaries.nil?
  Requests::MultilingualGlossary::Update.new(api, glossary, name, dictionaries,
                                             options).request
end

#update_multilingual_glossary_dictionary(glossary, dictionary, **options) ⇒ DeepL::Resources::MultilingualGlossary

Merges entries into the dictionary of one language pair, or adds the dictionary if the language pair is new.

Parameters:

Returns:

Raises:

  • (DeepL::Exceptions::ValidationError) —

    (an ArgumentError) If a term is empty after stripping or contains a control character.

  • (ArgumentError) —

    If the glossary ID or the entries are empty (CSV entries also if whitespace only), a source_lang or target_lang of a dictionary is nil or empty, or the glossary has no ID, before any request.



546
547
548
549
550
# File 'lib/deepl/client.rb', line 546

def update_multilingual_glossary_dictionary(glossary, dictionary, **options)
  check_csv_entries!([dictionary])
  Requests::MultilingualGlossary::Update.new(api, glossary, nil, [dictionary],
                                             options).request
end

#update_multilingual_glossary_dictionary_from_csv(glossary, source_lang, target_lang, csv, **options) ⇒ DeepL::Resources::MultilingualGlossary

Merges CSV entries into the dictionary of one language pair, or adds the dictionary if the language pair is new.

Parameters:

  • glossary (String, DeepL::Resources::MultilingualGlossary) —

    ID or glossary.

  • source_lang (String) —

    Source language of the dictionary.

  • target_lang (String) —

    Target language of the dictionary.

  • csv (String, IO) —

    CSV content, or an IO to read it from. Must not be empty or whitespace only; otherwise sent as given.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last.

Returns:

Raises:

  • (ArgumentError) —

    If the CSV content is empty or whitespace only, source_lang or target_lang is nil or empty, the glossary ID is empty or the glossary has no ID, before any request.



566
567
568
569
570
571
# File 'lib/deepl/client.rb', line 566

def update_multilingual_glossary_dictionary_from_csv(glossary, source_lang, target_lang, csv,
                                                     **options)
  dictionary = non_empty_csv_dictionary(source_lang, target_lang, csv)
  Requests::MultilingualGlossary::Update.new(api, glossary, nil, [dictionary],
                                             options).request
end

#update_multilingual_glossary_name(glossary, name, **options) ⇒ DeepL::Resources::MultilingualGlossary

Renames a multilingual glossary.

Parameters:

Returns:

Raises:

  • (ArgumentError) —

    If name or the glossary ID is empty, or the glossary has no ID, before any request.



526
527
528
529
530
# File 'lib/deepl/client.rb', line 526

def update_multilingual_glossary_name(glossary, name, **options)
  raise ArgumentError, 'Glossary name must not be empty' if name.to_s.empty?

  Requests::MultilingualGlossary::Update.new(api, glossary, name, nil, options).request
end

#update_spoken_terms(spoken_terms, name: nil, term_lists: nil, **options) ⇒ DeepL::Resources::SpokenTerms

Renames a collection and/or merges terms into its lists. Arguments left nil are not sent; without any, an empty object is sent.

Parameters:

  • spoken_terms (String, DeepL::Resources::SpokenTerms) —

    ID or collection.

  • name (String, nil) (defaults to: nil) —

    New name.

  • term_lists (Array<DeepL::Resources::SpokenTermsEntries, Hash>, nil) (defaults to: nil) —

    Terms to merge into the list of each language; a new language adds a list.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last.

Returns:

Raises:

  • (DeepL::Exceptions::ValidationError) —

    (an ArgumentError) If a term is empty after stripping or contains a control character.

  • (ArgumentError) —

    If the ID is empty, the collection has no ID, or the lang of a term list is nil or empty, before any request.



708
709
710
# File 'lib/deepl/client.rb', line 708

def update_spoken_terms(spoken_terms, name: nil, term_lists: nil, **options)
  Requests::SpokenTerms::Update.new(api, spoken_terms, name, term_lists, options).request
end

#update_style_profile(style_profile, name: nil, description: nil, industry: nil, glossary_ids: nil, style_rule_ids: nil, translation_memory_ids: nil, glossary_priority_order_enabled: nil, **options) ⇒ DeepL::Resources::StyleProfile

Updates a style profile. Keywords left nil are not sent and leave the field unchanged; without any, an empty object is sent. An empty string clears description or industry. A component list replaces the linked list in full; an empty array unlinks all components of that kind.

Parameters:

  • style_profile (String, DeepL::Resources::StyleProfile) —

    ID or style profile.

  • name (String, nil) (defaults to: nil) —

    New name.

  • options (Hash) —

    The keywords of #create_style_profile, including :extra_body_parameters.

Returns:

Raises:

  • (ArgumentError) —

    If the ID is empty.



982
983
984
985
986
987
988
989
990
# File 'lib/deepl/client.rb', line 982

def update_style_profile(style_profile, name: nil, description: nil, industry: nil, # rubocop:disable Metrics/ParameterLists
                         glossary_ids: nil, style_rule_ids: nil, translation_memory_ids: nil,
                         glossary_priority_order_enabled: nil, **options)
  fields = { name: name, description: description, industry: industry,
             glossary_ids: glossary_ids, style_rule_ids: style_rule_ids,
             translation_memory_ids: translation_memory_ids,
             glossary_priority_order_enabled: glossary_priority_order_enabled }
  Requests::StyleProfile::Update.new(api, style_profile, fields, options).request
end

#update_style_rule_configured_rules(style_rule, configured_rules, **options) ⇒ DeepL::Resources::StyleRule

Replaces the configured rules of a style rule list.

Parameters:

  • style_rule (String, DeepL::Resources::StyleRule) —

    ID or style rule list.

  • configured_rules (Hash) —

    Category -> rule -> value, sent as the request body.

  • options (Hash) —

    :extra_body_parameters, added to the body as further keys.

Returns:

Raises:

  • (ArgumentError) —

    If the style rule ID is empty or the list has no ID, before any request.



833
834
835
836
# File 'lib/deepl/client.rb', line 833

def update_style_rule_configured_rules(style_rule, configured_rules, **options)
  Requests::StyleRule::UpdateConfiguredRules.new(api, style_rule, configured_rules,
                                                 options).request
end

#update_style_rule_custom_instruction(style_rule, instruction_id, label, prompt, source_language: nil, **options) ⇒ DeepL::Resources::CustomInstruction

Replaces a custom instruction of a style rule list. source_language is not sent if nil.

Parameters:

  • style_rule (String, DeepL::Resources::StyleRule) —

    ID or style rule list.

  • instruction_id (String, DeepL::Resources::CustomInstruction) —

    ID or instruction.

  • label (String) —

    Label of the instruction.

  • prompt (String) —

    The instruction.

  • source_language (String, nil) (defaults to: nil) —

    Source language the instruction applies to.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last.

Returns:

Raises:

  • (ArgumentError) —

    If an ID, label or prompt is empty, source_language is empty (+nil+ leaves it unset), or an object has no ID, before any request.



898
899
900
901
902
903
# File 'lib/deepl/client.rb', line 898

def update_style_rule_custom_instruction(style_rule, instruction_id, label, prompt,
                                         source_language: nil, **options)
  Requests::StyleRule::UpdateCustomInstruction.new(api, style_rule, instruction_id, label,
                                                   prompt, source_language,
                                                   options).request
end

#update_style_rule_name(style_rule, name, **options) ⇒ DeepL::Resources::StyleRule

Renames a style rule list.

Parameters:

  • style_rule (String, DeepL::Resources::StyleRule) —

    ID or style rule list.

  • name (String) —

    New name.

  • options (Hash) —

    :extra_body_parameters, a hash added to the request body last.

Returns:

Raises:

  • (ArgumentError) —

    If the style rule ID or name is empty, or the list has no ID, before any request.



820
821
822
# File 'lib/deepl/client.rb', line 820

def update_style_rule_name(style_rule, name, **options)
  Requests::StyleRule::Update.new(api, style_rule, name, options).request
end

#upload_translation_memory_file(translation_memory_import, content, content_type: nil) ⇒ nil

Uploads a TMX file to the upload URL of an import job, which starts the processing. The upload URL is a pre-signed storage URL: no Authorization header and no configured headers are sent to it.

Parameters:

  • translation_memory_import (DeepL::Resources::TranslationMemoryImport, String) —

    The import, or its upload URL.

  • content (String) —

    Content of the TMX file.

  • content_type (String, nil) (defaults to: nil) —

    MIME type of the file, must match the one of the import job. nil sends application/xml.

Returns:

  • (nil)

Raises:

  • (DeepL::Exceptions::Error) —

    If the storage URL replies with a non-2xx status; the error carries http_status_code, and should_retry? is true for 429 and 5xx.

  • (ArgumentError) —

    If the upload URL is empty, before any request.



1099
1100
1101
1102
# File 'lib/deepl/client.rb', line 1099

def upload_translation_memory_file(translation_memory_import, content, content_type: nil)
  translation_memories.upload_file(translation_memory_import, content,
                                   content_type: content_type)
end

#wait_until_translation_memory_job_done(job, timeout_s: nil) ⇒ DeepL::Resources::TranslationMemoryJob

Polls a translation memory import or export job every 5 seconds until it is completed.

Parameters:

  • job (String, DeepL::Resources::TranslationMemoryJob) —

    ID or job.

  • timeout_s (Numeric, nil) (defaults to: nil) —

    Maximum time to wait in seconds, nil to wait until the job is completed, failed or expired. The last wait is cut so that the call never waits past timeout_s. A job whose file is never uploaded does not finish.

Returns:

Raises:

  • (DeepL::Exceptions::Error) —

    If the job fails or expires (with the API's error message), or timeout_s expires.

  • (ArgumentError) —

    If the ID is empty or the object has no ID, before any request.



1226
1227
1228
# File 'lib/deepl/client.rb', line 1226

def wait_until_translation_memory_job_done(job, timeout_s: nil)
  translation_memories.wait_until_job_done(job, timeout_s: timeout_s)
end