deepl-rb 3.9.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +27 -1
  3. data/CHANGELOG.md +741 -18
  4. data/Gemfile +4 -0
  5. data/README.md +1001 -327
  6. data/Rakefile +29 -7
  7. data/VERSION +1 -1
  8. data/deepl-rb.gemspec +75 -88
  9. data/lib/deepl/admin_client.rb +208 -0
  10. data/lib/deepl/api.rb +18 -8
  11. data/lib/deepl/app_info.rb +19 -0
  12. data/lib/deepl/client.rb +1284 -0
  13. data/lib/deepl/configuration.rb +27 -32
  14. data/lib/deepl/constants/admin_usage_group_by.rb +13 -0
  15. data/lib/deepl/constants/custom_tag_usage_aggregate_by.rb +13 -0
  16. data/lib/deepl/constants/document_status_code.rb +17 -0
  17. data/lib/deepl/constants/language_include.rb +17 -0
  18. data/lib/deepl/constants/language_resource_name.rb +21 -0
  19. data/lib/deepl/constants/tag_handling_version.rb +14 -0
  20. data/lib/deepl/exceptions/authorization_failed.rb +1 -1
  21. data/lib/deepl/exceptions/bad_request.rb +1 -3
  22. data/lib/deepl/exceptions/connection_error.rb +40 -0
  23. data/lib/deepl/exceptions/document_not_ready_error.rb +17 -0
  24. data/lib/deepl/exceptions/document_translation_error.rb +17 -1
  25. data/lib/deepl/exceptions/error.rb +13 -1
  26. data/lib/deepl/exceptions/limit_exceeded.rb +1 -1
  27. data/lib/deepl/exceptions/not_found.rb +8 -3
  28. data/lib/deepl/exceptions/quota_exceeded.rb +1 -1
  29. data/lib/deepl/exceptions/request_entity_too_large.rb +1 -2
  30. data/lib/deepl/exceptions/request_error.rb +26 -2
  31. data/lib/deepl/exceptions/server_error.rb +9 -2
  32. data/lib/deepl/exceptions/translation_memory_job_error.rb +32 -0
  33. data/lib/deepl/exceptions/validation_error.rb +15 -0
  34. data/lib/deepl/requests/admin/base.rb +94 -0
  35. data/lib/deepl/requests/admin/create_developer_key.rb +38 -0
  36. data/lib/deepl/requests/admin/custom_tag_usage_analytics.rb +38 -0
  37. data/lib/deepl/requests/admin/list_developer_keys.rb +28 -0
  38. data/lib/deepl/requests/admin/update_developer_key.rb +35 -0
  39. data/lib/deepl/requests/admin/usage_analytics.rb +36 -0
  40. data/lib/deepl/requests/base.rb +313 -65
  41. data/lib/deepl/requests/correct.rb +51 -0
  42. data/lib/deepl/requests/document/download.rb +11 -3
  43. data/lib/deepl/requests/document/get_status.rb +2 -2
  44. data/lib/deepl/requests/document/upload.rb +56 -20
  45. data/lib/deepl/requests/glossary/base.rb +30 -0
  46. data/lib/deepl/requests/glossary/create.rb +18 -18
  47. data/lib/deepl/requests/glossary/destroy.rb +4 -16
  48. data/lib/deepl/requests/glossary/entries.rb +6 -14
  49. data/lib/deepl/requests/glossary/find.rb +3 -13
  50. data/lib/deepl/requests/glossary/language_pairs.rb +22 -6
  51. data/lib/deepl/requests/glossary/list.rb +2 -2
  52. data/lib/deepl/requests/language_resources.rb +41 -0
  53. data/lib/deepl/requests/languages.rb +25 -6
  54. data/lib/deepl/requests/languages_for_resource.rb +56 -0
  55. data/lib/deepl/requests/multilingual_glossary/create.rb +45 -0
  56. data/lib/deepl/requests/multilingual_glossary/destroy.rb +36 -0
  57. data/lib/deepl/requests/multilingual_glossary/destroy_dictionary.rb +55 -0
  58. data/lib/deepl/requests/multilingual_glossary/entries.rb +68 -0
  59. data/lib/deepl/requests/multilingual_glossary/find.rb +35 -0
  60. data/lib/deepl/requests/multilingual_glossary/helpers.rb +71 -0
  61. data/lib/deepl/requests/multilingual_glossary/list.rb +39 -0
  62. data/lib/deepl/requests/multilingual_glossary/replace_dictionary.rb +41 -0
  63. data/lib/deepl/requests/multilingual_glossary/update.rb +40 -0
  64. data/lib/deepl/requests/rephrase.rb +8 -10
  65. data/lib/deepl/requests/spoken_terms/create.rb +42 -0
  66. data/lib/deepl/requests/spoken_terms/destroy.rb +36 -0
  67. data/lib/deepl/requests/spoken_terms/destroy_term_list.rb +42 -0
  68. data/lib/deepl/requests/spoken_terms/entries.rb +47 -0
  69. data/lib/deepl/requests/spoken_terms/find.rb +35 -0
  70. data/lib/deepl/requests/spoken_terms/helpers.rb +74 -0
  71. data/lib/deepl/requests/spoken_terms/list.rb +35 -0
  72. data/lib/deepl/requests/spoken_terms/replace_term_list.rb +41 -0
  73. data/lib/deepl/requests/spoken_terms/update.rb +40 -0
  74. data/lib/deepl/requests/style_profile/base.rb +83 -0
  75. data/lib/deepl/requests/style_profile/create.rb +40 -0
  76. data/lib/deepl/requests/style_profile/destroy.rb +34 -0
  77. data/lib/deepl/requests/style_profile/find.rb +33 -0
  78. data/lib/deepl/requests/style_profile/list.rb +43 -0
  79. data/lib/deepl/requests/style_profile/update.rb +35 -0
  80. data/lib/deepl/requests/style_rule/create.rb +24 -0
  81. data/lib/deepl/requests/style_rule/create_custom_instruction.rb +11 -2
  82. data/lib/deepl/requests/style_rule/destroy.rb +4 -2
  83. data/lib/deepl/requests/style_rule/destroy_custom_instruction.rb +5 -3
  84. data/lib/deepl/requests/style_rule/find.rb +4 -2
  85. data/lib/deepl/requests/style_rule/find_custom_instruction.rb +5 -3
  86. data/lib/deepl/requests/style_rule/helpers.rb +44 -0
  87. data/lib/deepl/requests/style_rule/list.rb +3 -1
  88. data/lib/deepl/requests/style_rule/update.rb +5 -2
  89. data/lib/deepl/requests/style_rule/update_configured_rules.rb +4 -2
  90. data/lib/deepl/requests/style_rule/update_custom_instruction.rb +7 -3
  91. data/lib/deepl/requests/translate.rb +43 -27
  92. data/lib/deepl/requests/translation_memory/base.rb +1 -4
  93. data/lib/deepl/requests/translation_memory/create_export.rb +7 -2
  94. data/lib/deepl/requests/translation_memory/create_import.rb +11 -1
  95. data/lib/deepl/requests/translation_memory/destroy.rb +1 -1
  96. data/lib/deepl/requests/translation_memory/find.rb +1 -1
  97. data/lib/deepl/requests/translation_memory/find_job.rb +1 -1
  98. data/lib/deepl/requests/translation_memory/list.rb +4 -3
  99. data/lib/deepl/requests/translation_memory/segments.rb +5 -4
  100. data/lib/deepl/requests/translation_memory/storage_base.rb +37 -9
  101. data/lib/deepl/requests/translation_memory/upload_file.rb +1 -1
  102. data/lib/deepl/requests/usage.rb +28 -1
  103. data/lib/deepl/requests/write_improvements.rb +42 -0
  104. data/lib/deepl/resources/admin_usage_report.rb +73 -0
  105. data/lib/deepl/resources/custom_tag_usage_report.rb +59 -0
  106. data/lib/deepl/resources/developer_key.rb +57 -0
  107. data/lib/deepl/resources/document_handle.rb +8 -34
  108. data/lib/deepl/resources/document_translation_status.rb +14 -7
  109. data/lib/deepl/resources/language.rb +5 -3
  110. data/lib/deepl/resources/language_resource.rb +57 -0
  111. data/lib/deepl/resources/language_support.rb +56 -0
  112. data/lib/deepl/resources/multilingual_glossary.rb +112 -0
  113. data/lib/deepl/resources/spoken_terms.rb +61 -0
  114. data/lib/deepl/resources/style_profile.rb +44 -0
  115. data/lib/deepl/resources/style_rule.rb +4 -23
  116. data/lib/deepl/resources/text.rb +18 -2
  117. data/lib/deepl/resources/translation_memory.rb +8 -2
  118. data/lib/deepl/resources/translation_memory_import.rb +1 -1
  119. data/lib/deepl/resources/translation_memory_job.rb +26 -7
  120. data/lib/deepl/resources/translation_memory_segments.rb +8 -6
  121. data/lib/deepl/resources/usage.rb +61 -5
  122. data/lib/deepl/utils/client_builder.rb +89 -0
  123. data/lib/deepl/utils/document_poller.rb +70 -0
  124. data/lib/deepl/utils/exception_builder.rb +3 -2
  125. data/lib/deepl/utils/glossary_entries.rb +30 -0
  126. data/lib/deepl/utils/http_client_builder.rb +116 -0
  127. data/lib/deepl/utils/number_parser.rb +34 -0
  128. data/lib/deepl/utils/output_path.rb +25 -0
  129. data/lib/deepl/utils/term_validator.rb +33 -0
  130. data/lib/deepl/utils/time_parser.rb +14 -0
  131. data/lib/deepl/utils/translation_memory_operations.rb +230 -0
  132. data/lib/deepl.rb +68 -108
  133. data/lib/http_client_options.rb +21 -1
  134. data/lib/version.rb +1 -1
  135. data/upgrading_to_v4.md +374 -0
  136. metadata +84 -85
  137. data/.circleci/config.yml +0 -27
  138. data/.github/workflows/add_issues_to_kanban.yml +0 -16
  139. data/.gitlab-ci.yml +0 -179
  140. data/lib/deepl/document_api.rb +0 -131
  141. data/lib/deepl/exceptions/not_supported.rb +0 -14
  142. data/lib/deepl/glossary_api.rb +0 -38
  143. data/lib/deepl/style_rule_api.rb +0 -61
  144. data/lib/deepl/translation_memory_api.rb +0 -309
  145. data/license_checker.sh +0 -8
  146. data/spec/api/api_spec.rb +0 -20
  147. data/spec/api/configuration_spec.rb +0 -122
  148. data/spec/api/deepl_spec.rb +0 -262
  149. data/spec/constants/constants_spec.rb +0 -158
  150. data/spec/integration_tests/document_api_spec.rb +0 -211
  151. data/spec/integration_tests/document_error_paths_spec.rb +0 -33
  152. data/spec/integration_tests/glossary_api_spec.rb +0 -114
  153. data/spec/integration_tests/glossary_error_paths_spec.rb +0 -107
  154. data/spec/integration_tests/integration_test_utils.rb +0 -178
  155. data/spec/integration_tests/languages_api_spec.rb +0 -54
  156. data/spec/integration_tests/languages_error_paths_spec.rb +0 -25
  157. data/spec/integration_tests/rephrase_api_spec.rb +0 -90
  158. data/spec/integration_tests/rephrase_error_paths_spec.rb +0 -53
  159. data/spec/integration_tests/smoke_test_spec.rb +0 -24
  160. data/spec/integration_tests/style_rule_api_spec.rb +0 -117
  161. data/spec/integration_tests/style_rule_error_paths_spec.rb +0 -45
  162. data/spec/integration_tests/translate_api_spec.rb +0 -117
  163. data/spec/integration_tests/translate_error_paths_spec.rb +0 -48
  164. data/spec/integration_tests/translation_memory_api_spec.rb +0 -244
  165. data/spec/integration_tests/translation_memory_error_paths_spec.rb +0 -87
  166. data/spec/integration_tests/usage_api_spec.rb +0 -29
  167. data/spec/integration_tests/usage_error_paths_spec.rb +0 -18
  168. data/spec/requests/document/upload_spec.rb +0 -130
  169. data/spec/requests/extra_body_parameters_types_spec.rb +0 -82
  170. data/spec/requests/glossary/create_spec.rb +0 -44
  171. data/spec/requests/glossary/destroy_spec.rb +0 -27
  172. data/spec/requests/glossary/entries_spec.rb +0 -27
  173. data/spec/requests/glossary/find_spec.rb +0 -28
  174. data/spec/requests/glossary/language_pairs_spec.rb +0 -27
  175. data/spec/requests/glossary/list_spec.rb +0 -27
  176. data/spec/requests/languages_spec.rb +0 -27
  177. data/spec/requests/rephrase_spec.rb +0 -46
  178. data/spec/requests/style_rule/create_custom_instruction_spec.rb +0 -30
  179. data/spec/requests/style_rule/create_spec.rb +0 -29
  180. data/spec/requests/style_rule/destroy_custom_instruction_spec.rb +0 -28
  181. data/spec/requests/style_rule/destroy_spec.rb +0 -27
  182. data/spec/requests/style_rule/find_custom_instruction_spec.rb +0 -29
  183. data/spec/requests/style_rule/find_spec.rb +0 -28
  184. data/spec/requests/style_rule/list_spec.rb +0 -27
  185. data/spec/requests/style_rule/update_configured_rules_spec.rb +0 -31
  186. data/spec/requests/style_rule/update_custom_instruction_spec.rb +0 -32
  187. data/spec/requests/style_rule/update_spec.rb +0 -29
  188. data/spec/requests/translate_spec.rb +0 -338
  189. data/spec/requests/translation_memory/create_export_spec.rb +0 -37
  190. data/spec/requests/translation_memory/create_import_spec.rb +0 -61
  191. data/spec/requests/translation_memory/destroy_spec.rb +0 -36
  192. data/spec/requests/translation_memory/download_export_spec.rb +0 -54
  193. data/spec/requests/translation_memory/find_job_spec.rb +0 -37
  194. data/spec/requests/translation_memory/find_spec.rb +0 -36
  195. data/spec/requests/translation_memory/list_spec.rb +0 -27
  196. data/spec/requests/translation_memory/segments_spec.rb +0 -58
  197. data/spec/requests/translation_memory/upload_file_spec.rb +0 -55
  198. data/spec/requests/usage_spec.rb +0 -27
  199. data/spec/resources/custom_instruction_spec.rb +0 -32
  200. data/spec/resources/glossary_spec.rb +0 -38
  201. data/spec/resources/language_pair_spec.rb +0 -23
  202. data/spec/resources/language_spec.rb +0 -45
  203. data/spec/resources/style_rule_spec.rb +0 -68
  204. data/spec/resources/text_spec.rb +0 -23
  205. data/spec/resources/translation_memory_export_spec.rb +0 -38
  206. data/spec/resources/translation_memory_import_spec.rb +0 -30
  207. data/spec/resources/translation_memory_job_spec.rb +0 -109
  208. data/spec/resources/translation_memory_segments_spec.rb +0 -78
  209. data/spec/resources/translation_memory_spec.rb +0 -52
  210. data/spec/resources/usage_spec.rb +0 -35
  211. data/spec/spec_helper.rb +0 -62
  212. data/spec/support/live_mock_server.rb +0 -12
  213. data/spec/support/managed_glossary.rb +0 -65
  214. data/spec/support/managed_style_rule.rb +0 -17
  215. data/spec/support/managed_translation_memory.rb +0 -55
data/README.md CHANGED
@@ -12,6 +12,8 @@ To use the DeepL Ruby Library, you'll need an API authentication key. To get a k
12
12
 
13
13
  ## Installation
14
14
 
15
+ Requires Ruby 3.0 and later.
16
+
15
17
  Install this gem with
16
18
 
17
19
  ```sh
@@ -25,90 +27,182 @@ Or add it to your Gemfile:
25
27
  gem 'deepl-rb', require: 'deepl'
26
28
  ```
27
29
 
28
- ## Usage
30
+ ### Upgrading
29
31
 
30
- Setup an environment variable named `DEEPL_AUTH_KEY` with your authentication key:
32
+ Upgrading from version 3? Read [Upgrading to 4.0.0](upgrading_to_v4.md) for the removed
33
+ module-level API, the stricter argument checks and the other breaking changes.
31
34
 
32
- ```sh
33
- export DEEPL_AUTH_KEY="your-api-token"
34
- ```
35
+ ## Usage
35
36
 
36
- Alternatively, you can configure the API client within a ruby block:
37
+ ### Creating a client
37
38
 
38
- ```rb
39
- DeepL.configure do |config|
40
- config.auth_key = 'your-api-token'
41
- end
42
- ```
43
-
44
- You can also configure the API host and the API version:
39
+ Create a `DeepL::Client` with your authentication key. Each client owns its configuration and
40
+ HTTP connection, so several clients with different keys or options can be used side by side.
41
+ The client reads no environment variables:
45
42
 
46
43
  ```rb
47
- DeepL.configure do |config|
48
- config.auth_key = 'your-api-token'
49
- config.host = 'https://api-free.deepl.com' # Default value is 'https://api.deepl.com'
50
- config.version = 'v1' # Default value is 'v2'
51
- end
44
+ client = DeepL::Client.new(ENV.fetch('DEEPL_AUTH_KEY'))
52
45
  ```
53
46
 
47
+ `DeepL::Client.new` accepts these keyword arguments:
48
+
49
+ | Option | Default | Description |
50
+ | ------ | ------- | ----------- |
51
+ | `server_url:` | `https://api-free.deepl.com` for Free keys (ending in `:fx`), else `https://api.deepl.com` | 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. Any other value raises `ArgumentError`. |
52
+ | `headers:` | `{}` | HTTP headers sent with every DeepL API request. A header of the same name, in any casing, replaces the library's, `Authorization` and `User-Agent` included, except `Content-Type`, `Content-Length`, `Transfer-Encoding` and `Host`. Pre-signed storage URLs get only the `User-Agent`. |
53
+ | `max_retries:` | `5` | Retries after the first attempt, for HTTP 429, any 5xx and transient network failures. 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 API cannot have processed them, so that a retry cannot create a second resource. |
54
+ | `timeout:` | `10` | Timeout of each attempt in seconds. A longer backoff interval takes precedence. |
55
+ | `proxy:` | none | Proxy URL (`http://` or `https://`) as a String or `URI`, e.g. `http://user:password@proxy.example:8080`, or a hash with `proxy_addr` and `proxy_port`. Any other value raises `ArgumentError`. |
56
+ | `send_platform_info:` | `true` | Adds the OS and Ruby versions to the `User-Agent`. |
57
+ | `app_info:` | none | A `DeepL::AppInfo` or a hash with `app_name` and `app_version`, added to the `User-Agent`. |
58
+ | `http_client_options:` | none | A `DeepL::HTTPClientOptions` with proxy, certificate, SSL verification and per-phase timeouts. Its timeouts take precedence over `timeout:`. |
59
+ | `logger:` | none | Logger for requests and retries, see [Logging](#logging). |
60
+
61
+ A keyword argument given as `nil` takes its default, like an omitted one.
62
+ The authentication key is trimmed; an empty key raises `ArgumentError`.
63
+ `DeepL::Client.free_account_auth_key?(key)` returns whether a key is a DeepL API Free key.
64
+
65
+ `DeepL::Client` offers text translation (`translate_text`, see [Translate](#translate)),
66
+ document translation (`translate_document` and its steps, see
67
+ [Translate documents](#translate-documents)), rephrasing and correction (`rephrase_text` and
68
+ `correct_text`, see [Rephrase Text](#rephrase-text) and [Correct Text](#correct-text)),
69
+ glossaries (see [Glossaries](#glossaries) and [Multilingual glossaries](#multilingual-glossaries)),
70
+ spoken terms (see
71
+ [Spoken terms](#spoken-terms)), style rules (see [Style Rules](#style-rules)), style profiles
72
+ (see [Style profiles](#style-profiles)), translation memories (see
73
+ [Translation Memories](#translation-memories)) and usage (`get_usage`, see
74
+ [Monitor usage](#monitor-usage)).
75
+
76
+ The module-level API of version 3 (`DeepL.configure`, `DeepL.translate`, `DeepL.glossaries`,
77
+ ...) has been removed, see [Migrating from the module-level API](#migrating-from-the-module-level-api).
78
+
79
+ ### Migrating from the module-level API
80
+
81
+ Version 4 removes the module-level API of version 3, deprecated in 3.10.0. Create a
82
+ `DeepL::Client` and call its methods instead:
83
+
84
+ | Module-level API (removed) | `DeepL::Client` |
85
+ | -------------------------- | --------------- |
86
+ | `DeepL.configure`, `DeepL.configuration` | `DeepL::Client.new(auth_key, server_url:, headers:, max_retries:, timeout:, ...)` |
87
+ | `DeepL.translate` | `translate_text` |
88
+ | `DeepL.rephrase` | `rephrase_text` (`writing_style:` and `tone:` are keywords) |
89
+ | `DeepL.usage` | `get_usage` |
90
+ | `DeepL.languages(type:)` | `get_source_languages` / `get_target_languages` |
91
+ | `DeepL.document.*` | `translate_document`, `translate_document_upload`, `translate_document_get_status`, `translate_document_wait_until_done`, `translate_document_download` |
92
+ | `DeepL.glossaries` | `create_glossary`, `create_glossary_from_csv`, `list_glossaries`, `get_glossary`, `get_glossary_entries`, `delete_glossary`, `get_glossary_languages` |
93
+ | `DeepL.style_rules` | the style rule methods (`get_all_style_rules`, `create_style_rule`, ...) |
94
+ | `DeepL.translation_memories` | the translation memory methods (`list_translation_memories`, ...) |
95
+ | `DeepL.with_session`, `DeepL.http_client`, `DeepL.api` | the `proxy:` and `http_client_options:` options |
96
+ | per-call `additional_headers` | the `headers:` option |
97
+ | `config.user_agent` | `app_info:`, `send_platform_info:` or a `User-Agent` in `headers:` |
98
+
99
+ `DeepL::Client` reads no environment variables: pass the key (and the server URL, if needed)
100
+ yourself. Its behaviour differs from the removed API: network failures raise
101
+ `DeepL::Exceptions::ConnectionError` with the original error as `cause`; the timeout of each
102
+ attempt defaults to 10 seconds instead of 60; an array of texts always returns an array;
103
+ `translate_document` returns the final status; the delete methods return `nil`; and
104
+ `supports_formality?` returns `nil` for a source language instead of raising.
105
+
54
106
  ### Available languages
55
107
 
56
- Available languages can be retrieved via API:
108
+ `get_source_languages` and `get_target_languages` of `DeepL::Client` return the languages that
109
+ can be translated from and into, as `DeepL::Resources::Language` objects with upper-case codes:
57
110
 
58
111
  ```rb
59
- languages = DeepL.languages
112
+ languages = client.get_source_languages
60
113
 
61
- puts languages.class
62
- # => Array
63
114
  puts languages.first.class
64
115
  # => DeepL::Resources::Language
65
116
  puts "#{languages.first.code} -> #{languages.first.name}"
66
117
  # => "ES -> Spanish"
118
+
119
+ german = client.get_target_languages.find { |language| language.code == 'DE' }
120
+ puts german.supports_formality?
121
+ # => true
67
122
  ```
68
123
 
69
- Note that source and target languages may be different, which can be retrieved by using the `type`
70
- option:
124
+ `supports_formality?` is `true` or `false` for target languages and `nil` for source languages.
125
+
126
+ All languages are also defined on the
127
+ [official API documentation](https://developers.deepl.com/docs/api-reference/translate).
128
+
129
+ #### Languages per resource
130
+
131
+ `get_languages_for_resource` returns the languages supported by a given API resource, with
132
+ source/target usability and per-feature support. The language codes are returned as the API sends
133
+ them (`de`, `en-GB`). The resources are defined in `DeepL::Constants::LanguageResourceName`
134
+ (`TRANSLATE_TEXT`, `TRANSLATE_DOCUMENT`, `GLOSSARY`, `VOICE`, `WRITE`, `STYLE_RULES`,
135
+ `TRANSLATION_MEMORY`). Pass `include:` with one value or an array of values from
136
+ `DeepL::Constants::LanguageInclude` (`BETA`, `EXTERNAL`) to also list beta languages and features
137
+ or features that rely on third-party providers. Other strings are sent unchanged, for both the
138
+ resource and `include:`.
71
139
 
72
140
  ```rb
73
- puts DeepL.languages(type: :source).count
74
- # => 24
75
- puts DeepL.languages(type: :target).count
76
- # => 26
141
+ languages = client.get_languages_for_resource(
142
+ DeepL::Constants::LanguageResourceName::TRANSLATE_TEXT,
143
+ include: [DeepL::Constants::LanguageInclude::BETA]
144
+ )
145
+
146
+ german = languages.find { |language| language.code == 'de' }
147
+ puts german.usable_as_target?
148
+ # => true
149
+ puts german.supports?(:formality)
150
+ # => true
151
+ puts german.features['formality'].status
152
+ # => "stable"
77
153
  ```
78
154
 
79
- All languages are also defined on the
80
- [official API documentation](https://developers.deepl.com/docs/api-reference/translate).
155
+ `get_language_resources` lists every resource with its `name` and features, and whether a
156
+ feature must be supported by the source language, the target language, or both:
81
157
 
82
- Note that target languages may include the `supports_formality` flag, which may be checked
83
- using the `DeepL::Resources::Language#supports_formality?`.
158
+ ```rb
159
+ translate_text = client.get_language_resources.find { |resource| resource.name == 'translate_text' }
160
+ formality = translate_text.features['formality']
161
+ puts formality.needs_source_support?
162
+ # => false
163
+ puts formality.needs_target_support?
164
+ # => true
165
+ ```
84
166
 
85
167
  ### Translate
86
168
 
87
- To translate a simple text, use the `translate` method:
169
+ To translate a simple text, use the `translate_text` method of `DeepL::Client`:
88
170
 
89
171
  ```rb
90
- translation = DeepL.translate 'This is my text', 'EN', 'ES'
172
+ translation = client.translate_text 'This is my text', 'EN', 'ES'
91
173
 
92
174
  puts translation.class
93
175
  # => DeepL::Resources::Text
94
176
  puts translation.text
95
177
  # => 'Este es mi texto'
178
+ puts translation.billed_characters
179
+ # => 15
96
180
  ```
97
181
 
182
+ Each result has `text`, `detected_source_language`, `billed_characters` (the characters
183
+ billed for the text; the library always asks the API for it), `model_type_used` and
184
+ `tag_handling_version` (the tag handling version the API used, when tag handling was
185
+ requested). A field the response does not contain is `nil`.
186
+
187
+ An empty text (an empty string, an empty array or an array with an empty string), an empty
188
+ `target_lang` and an empty `source_lang` (pass `nil` to detect the source language) raise
189
+ `ArgumentError` before anything is sent.
190
+
98
191
  Enable auto-detect source language by skipping the source language with `nil`:
99
192
 
100
193
  ```rb
101
- translation = DeepL.translate 'This is my text', nil, 'ES'
194
+ translation = client.translate_text 'This is my text', nil, 'ES'
102
195
 
103
196
  puts translation.detected_source_language
104
197
  # => 'EN'
105
198
  ```
106
199
 
107
- Translate a list of texts by passing an array as an argument:
200
+ Translate a list of texts by passing an array as an argument. An array, also one with a
201
+ single text, returns an array of results:
108
202
 
109
203
  ```rb
110
204
  texts = ['Sample text', 'Another text']
111
- translations = DeepL.translate texts, 'EN', 'ES'
205
+ translations = client.translate_text texts, 'EN', 'ES'
112
206
 
113
207
  puts translations.class
114
208
  # => Array
@@ -116,12 +210,13 @@ puts translations.first.class
116
210
  # => DeepL::Resources::Text
117
211
  ```
118
212
 
119
- You can also use custom query parameters, like `tag_handling`, `split_sentences`, `non_splitting_tags` or `ignore_tags`:
213
+ Options are passed as keyword arguments; an option set to `nil` is not sent. You can use
214
+ options like `tag_handling`, `split_sentences`, `non_splitting_tags` or `ignore_tags`:
120
215
 
121
216
  ```rb
122
- translation = DeepL.translate '<p>A sample</p>', 'EN', 'ES',
123
- tag_handling: 'xml', split_sentences: false,
124
- non_splitting_tags: 'h1', ignore_tags: %w[code pre]
217
+ translation = client.translate_text '<p>A sample</p>', 'EN', 'ES',
218
+ tag_handling: 'xml', split_sentences: false,
219
+ non_splitting_tags: 'h1', ignore_tags: %w[code pre]
125
220
 
126
221
  puts translation.text
127
222
  # => "<p>Una muestra</p>"
@@ -130,20 +225,24 @@ puts translation.text
130
225
  To specify which version of the tag handling algorithm to use, you can use the `tag_handling_version` parameter:
131
226
 
132
227
  ```rb
133
- translation = DeepL.translate '<p>A sample</p>', 'EN', 'ES',
134
- tag_handling: 'xml', tag_handling_version: 'v2'
228
+ translation = client.translate_text '<p>A sample</p>', 'EN', 'ES',
229
+ tag_handling: 'xml',
230
+ tag_handling_version: DeepL::Constants::TagHandlingVersion::V2
135
231
 
136
232
  puts translation.text
137
233
  # => "<p>Una muestra</p>"
234
+ puts translation.tag_handling_version
235
+ # => "v2"
138
236
  ```
139
237
 
140
- The available values are `'v1'` and `'v2'`.
238
+ The available values are `'v1'` and `'v2'` (`DeepL::Constants::TagHandlingVersion::V1` and
239
+ `V2`); other strings are sent as given.
141
240
 
142
241
  To translate with context, simply supply the `context` parameter:
143
242
 
144
243
  ```rb
145
- translation = DeepL.translate 'That is hot!', 'EN', 'ES',
146
- context: 'He did not like the jalapenos in his meal.'
244
+ translation = client.translate_text 'That is hot!', 'EN', 'ES',
245
+ context: 'He did not like the jalapenos in his meal.'
147
246
 
148
247
  puts translation.text
149
248
  # => "¡Eso es picante!"
@@ -152,8 +251,8 @@ puts translation.text
152
251
  To specify a type of translation model to use, you can use the `model_type` option:
153
252
 
154
253
  ```rb
155
- translation = DeepL.translate 'That is hot!', 'EN', 'DE',
156
- model_type: 'quality_optimized'
254
+ translation = client.translate_text 'That is hot!', 'EN', 'DE',
255
+ model_type: 'quality_optimized'
157
256
  ```
158
257
 
159
258
  This would use next-gen translation models for the translation. The available values are
@@ -165,11 +264,12 @@ This would use next-gen translation models for the translation. The available va
165
264
  - `'latency_optimized'`: use a translation model that minimizes response time, at the cost
166
265
  of translation quality.
167
266
 
168
- To translate with custom instructions, supply the `custom_instructions` parameter:
267
+ To translate with custom instructions, supply the `custom_instructions` parameter, an array
268
+ of instructions. A single string is sent as one instruction, commas included:
169
269
 
170
270
  ```rb
171
- translation = DeepL.translate 'Hello, world!', 'EN', 'DE',
172
- custom_instructions: ['Use informal language', 'Be concise']
271
+ translation = client.translate_text 'Hello, world!', 'EN', 'DE',
272
+ custom_instructions: ['Use informal language', 'Be concise']
173
273
 
174
274
  puts translation.text
175
275
  ```
@@ -190,56 +290,98 @@ The following parameters will be automatically converted:
190
290
  | `non_splitting_tags` | Converts arrays to strings joining by commas
191
291
  | `ignore_tags` | Converts arrays to strings joining by commas
192
292
  | `formality` | No conversion applied
193
- | `glossary_id` | No conversion applied
194
- | `style_rule` | No conversion applied (can be a string ID or a StyleRule object)
195
- | `translation_memory` | No conversion applied (can be a string ID or a TranslationMemory object)
196
- | `translation_memory_threshold` | No conversion applied (integer 0-100, recommended minimum 75)
293
+ | `glossary` | A glossary ID string, a `Glossary` or a `MultilingualGlossary` object, sent as `glossary_id` (see [Glossaries](#glossaries)); an empty ID or an object without its ID raises `ArgumentError`
294
+ | `style_rule` | No conversion applied (can be a string ID or a StyleRule object); an empty ID or an object without its ID raises `ArgumentError`
295
+ | `style_profile` | No conversion applied (can be a string ID or a StyleProfile object, see [Style profiles](#style-profiles)); an empty ID or an object without its ID raises `ArgumentError`
296
+ | `translation_memory` | No conversion applied (can be a string ID or a TranslationMemory object); an empty ID or an object without its ID raises `ArgumentError`
297
+ | `translation_memory_threshold` | No conversion applied (integer 0-100, recommended minimum 75); requires `translation_memory`, otherwise `ArgumentError`
197
298
  | `context` | No conversion applied
198
- | `custom_instructions` | No conversion applied
199
- | `tag_handling_version` | No conversion applied
299
+ | `custom_instructions` | An array of strings; a string is sent as a one-element array
300
+ | `tag_handling` | No conversion applied (`DeepL::Constants::TagHandling`)
301
+ | `tag_handling_version` | No conversion applied (`DeepL::Constants::TagHandlingVersion`)
302
+ | `model_type` | No conversion applied (`DeepL::Constants::ModelType`)
200
303
  | `extra_body_parameters` | Hash of extra parameters to pass in the body of the HTTP request. Can be used to access beta features, or to override built-in parameters for testing purposes. Extra parameters can override keys explicitly set by the client.
201
304
 
305
+ `show_billed_characters: true` is always sent.
306
+
307
+ Every method accepts only the options it documents. Any other option, also a misspelled one,
308
+ raises `ArgumentError` naming it before a request is sent. To send a field the library does not
309
+ model, add it to `extra_body_parameters`; every method that takes options accepts it.
310
+
202
311
  ### Rephrase Text
203
312
 
204
- To rephrase or improve text, including changing the writing style or tone of the text, use the `rephrase` method:
313
+ To rephrase or improve text, including changing the writing style or tone of the text, use
314
+ the `rephrase_text` method of `DeepL::Client`:
205
315
 
206
316
  ```rb
207
- rephrased_text = DeepL.rephrase 'you will acquire new rephrased text', 'EN'
317
+ rephrased_text = client.rephrase_text 'you will acquire new rephrased text', 'EN'
208
318
 
209
319
  puts rephrased_text.class
210
320
  # => DeepL::Resources::Text
211
321
  puts rephrased_text.text
212
322
  # => 'You get new rephrased text.'
323
+ puts rephrased_text.detected_source_language
324
+ # => 'en'
325
+ puts rephrased_text.target_language
326
+ # => 'en-US'
213
327
  ```
214
328
 
215
- As with translate, the text input can be a single string or an array of strings.
329
+ As with `translate_text`, the text can be a string or an array of strings: a string returns a
330
+ `DeepL::Resources::Text`, an array returns an array of them (also for an array with one
331
+ element). The target language is optional. Empty text raises `ArgumentError`.
216
332
 
217
- You can use the additional arguments to specify the writing style or tone you want for the rephrased text:
333
+ Use the `writing_style:` or `tone:` keyword to choose the writing style or tone of the
334
+ rephrased text (`DeepL::Constants::WritingStyle` and `DeepL::Constants::Tone` list the values;
335
+ any string is sent as given). `extra_body_parameters:` is a hash added to the request body
336
+ last; it replaces fields of the same name.
218
337
 
219
338
  ```rb
220
- rephrased_text = DeepL.rephrase 'you will acquire new rephrased text', 'EN', 'casual'
339
+ rephrased_text = client.rephrase_text 'you will acquire new rephrased text', 'EN',
340
+ writing_style: 'casual'
221
341
 
222
342
  puts rephrased_text.text
223
343
  # => 'You'll get new, rephrased text.'
224
344
  ```
225
345
 
226
346
  ```rb
227
- rephrased_text = DeepL.rephrase 'you will acquire new rephrased text', 'EN', nil, 'friendly'
347
+ rephrased_text = client.rephrase_text 'you will acquire new rephrased text', 'EN',
348
+ tone: DeepL::Constants::Tone::FRIENDLY
228
349
 
229
350
  puts rephrased_text.text
230
351
  # => 'You'll get to enjoy new, rephrased text!'
231
352
  ```
232
353
 
354
+ ### Correct Text
355
+
356
+ To fix grammar, spelling and punctuation, use the `correct_text` method of `DeepL::Client`.
357
+ It accepts a string or an array of strings, plus an optional target language and
358
+ `extra_body_parameters:`:
359
+
360
+ ```ruby
361
+ corrected = client.correct_text 'I has a apple.', 'en-US'
362
+ puts corrected.text
363
+ # => 'It has an apple.'
364
+ puts corrected.target_language
365
+ # => 'en-US'
366
+ ```
367
+
368
+ A string returns a `DeepL::Resources::Text`; an array returns an array of them (also for an
369
+ array with one element). Empty text raises `ArgumentError`. It raises
370
+ `DeepL::Exceptions::Error` if the response contains fewer improvements than texts were sent.
371
+
233
372
  ### Glossaries
234
373
 
235
- To create a glossary, use the `glossaries.create` method. The glossary `entries` argument should be an array of text pairs. Each pair includes the source and the target translations.
374
+ A v2 glossary holds the entries of one language pair. To create one, call `create_glossary`
375
+ with a name, the source and target languages and the entries, a hash of source term to target
376
+ term (source/target pairs or a TSV string work too). Glossaries are not regional: `EN-GB` is
377
+ sent as `EN`. The entries are sent as TSV; each term is stripped of surrounding whitespace, and
378
+ an empty term, one with a control character or a source term that appears twice raises
379
+ `DeepL::Exceptions::ValidationError`, an `ArgumentError`, before anything is sent. An empty name,
380
+ no entries, or a `nil` or empty `source_lang` or `target_lang` raise `ArgumentError`:
236
381
 
237
382
  ```rb
238
- entries = [
239
- ['Hello World', 'Hola Tierra'],
240
- ['car', 'auto']
241
- ]
242
- glossary = DeepL.glossaries.create 'Mi Glosario', 'EN', 'ES', entries
383
+ glossary = client.create_glossary('My Glossary', 'EN', 'ES',
384
+ { 'Hello World' => 'Hola Tierra', 'car' => 'auto' })
243
385
 
244
386
  puts glossary.class
245
387
  # => DeepL::Resources::Glossary
@@ -249,17 +391,42 @@ puts glossary.entry_count
249
391
  # => 2
250
392
  ```
251
393
 
252
- Created glossaries can be used in the `translate` method by specifying the `glossary_id` option:
394
+ `create_glossary_from_csv` creates a glossary from CSV content (a string or an IO), for example
395
+ a file downloaded from the DeepL website; the content is sent as given:
253
396
 
254
397
  ```rb
255
- translation = DeepL.translate 'Hello World', 'EN', 'ES', glossary_id: 'aa48c7f0-0d02-413e-8a06-d5bbf0ca7a6e'
398
+ glossary = client.create_glossary_from_csv('My Glossary', 'EN', 'ES', File.open('entries.csv'))
399
+ ```
400
+
401
+ Every method that takes a glossary accepts its ID or a `DeepL::Resources::Glossary`:
402
+
403
+ ```rb
404
+ client.list_glossaries # => Array of DeepL::Resources::Glossary
405
+ client.get_glossary(glossary) # => DeepL::Resources::Glossary, without the entries
406
+ client.get_glossary_entries(glossary)
407
+ # => {"Hello World"=>"Hola Tierra", "car"=>"auto"}
408
+ client.delete_glossary(glossary) # => nil
409
+ ```
410
+
411
+ `get_glossary_languages` returns the language pairs supported by glossaries, as
412
+ `DeepL::Resources::LanguagePair` objects with `source_lang` and `target_lang`. A missing
413
+ glossary raises `DeepL::Exceptions::NotFound`. Glossaries with several language pairs are
414
+ managed with the methods in [Multilingual glossaries](#multilingual-glossaries), which also
415
+ handle v2 glossaries.
416
+
417
+ Glossaries can be used in text and document translation by specifying the
418
+ `glossary` option, a glossary ID or a `Glossary` / `MultilingualGlossary` object. It is sent
419
+ as `glossary_id`:
420
+
421
+ ```rb
422
+ translation = client.translate_text 'Hello World', 'EN', 'ES', glossary: 'aa48c7f0-0d02-413e-8a06-d5bbf0ca7a6e'
256
423
 
257
424
  puts translation.class
258
425
  # => DeepL::Resources::Text
259
426
  puts translation.text
260
427
  # => 'Hola Tierra'
261
428
 
262
- translation = DeepL.translate "I wish we had a car.", 'EN', 'ES', glossary_id: 'aa48c7f0-0d02-413e-8a06-d5bbf0ca7a6e'
429
+ translation = client.translate_text "I wish we had a car.", 'EN', 'ES', glossary: glossary
263
430
 
264
431
  puts translation.class
265
432
  # => DeepL::Resources::Text
@@ -268,223 +435,481 @@ puts translation.text
268
435
  ```
269
436
 
270
437
  To use more than one glossary at once, specify the `glossary_ids` option with an
271
- array of up to 5 glossary IDs (as strings or `DeepL::Resources::Glossary`
272
- objects) instead of `glossary_id`. This works for both text and document
273
- translation. `glossary_ids` requires `source_lang` to be set, cannot be combined
274
- with `glossary_id`, and raises `ArgumentError` if these rules are violated or
275
- more than 5 IDs are provided:
438
+ array of up to 5 glossary IDs (as strings, `DeepL::Resources::Glossary` or
439
+ `DeepL::Resources::MultilingualGlossary` objects) instead of `glossary`. This works for both text and document
440
+ translation. `glossary_ids` cannot be combined with `glossary`,
441
+ and raises `ArgumentError` if this rule is violated, more than 5 IDs are
442
+ provided, or an entry is an empty ID or a glossary without its ID. For text
443
+ translation, a glossary (`glossary` or `glossary_ids`) can be used without
444
+ `source_lang`: the API detects the source language and uses the
445
+ glossary's dictionary for the detected language pair. Document translation with
446
+ `glossary` or `glossary_ids` requires `source_lang` and raises `ArgumentError` without it:
276
447
 
277
448
  ```rb
278
449
  # Text translation with multiple glossaries
279
- translation = DeepL.translate 'Hello World', 'EN', 'ES',
280
- glossary_ids: ['aa48c7f0-0d02-413e-8a06-d5bbf0ca7a6e',
281
- 'bb59d8g1-1e13-524f-9b17-e6ccg1db8b7f']
450
+ translation = client.translate_text 'Hello World', 'EN', 'ES',
451
+ glossary_ids: ['aa48c7f0-0d02-413e-8a06-d5bbf0ca7a6e',
452
+ 'bb59d8g1-1e13-524f-9b17-e6ccg1db8b7f']
282
453
 
283
454
  # Document translation with multiple glossaries
284
- handle = DeepL.document.upload 'my_document.docx', 'EN', 'ES', 'my_document.docx',
285
- glossary_ids: ['aa48c7f0-0d02-413e-8a06-d5bbf0ca7a6e',
286
- 'bb59d8g1-1e13-524f-9b17-e6ccg1db8b7f']
455
+ handle = client.translate_document_upload 'my_document.docx', 'EN', 'ES',
456
+ glossary_ids: ['aa48c7f0-0d02-413e-8a06-d5bbf0ca7a6e',
457
+ 'bb59d8g1-1e13-524f-9b17-e6ccg1db8b7f']
287
458
  ```
288
459
 
289
- To list all the glossaries available, use the `glossaries.list` method:
460
+ ### Multilingual glossaries
461
+
462
+ Multilingual glossaries (v3) group several language-pair dictionaries under one
463
+ glossary and are managed through `DeepL::Client`. Every method that takes a
464
+ glossary accepts its ID or a `DeepL::Resources::MultilingualGlossary` object; the
465
+ ID is URL-encoded in the request path. A dictionary's `entries` is a hash of
466
+ source term to target term. An empty glossary ID (or a glossary object without
467
+ one), an empty name, an empty language of a dictionary to delete, no dictionaries
468
+ on create, or a dictionary without entries raises
469
+ `ArgumentError` before anything is sent.
470
+
471
+ To create a multilingual glossary, pass a name and one
472
+ `DeepL::Resources::MultilingualGlossaryDictionaryEntries` (or a hash with
473
+ `:source_lang`, `:target_lang` and `:entries`) per language pair. Entries are given
474
+ as a hash (`{ 'Hello' => 'Hallo' }`), as source/target pairs or as a TSV string (one
475
+ source/target pair per line, separated by a tab); a hash dictionary may also give
476
+ them as a CSV string with `entries_format: 'csv'`. Entries given as a hash or as pairs are
477
+ always sent as TSV, whatever `entries_format` says. Terms not given as CSV are checked like v2
478
+ glossary terms: each term is stripped of surrounding whitespace, and an empty term,
479
+ one with a control character, a pair or TSV line that is not exactly two terms, or a
480
+ source term that appears twice raises
481
+ `DeepL::Exceptions::ValidationError` (an `ArgumentError`) before anything is sent. Empty or
482
+ whitespace-only CSV content raises `ArgumentError` before anything is sent; other CSV content is
483
+ sent as given. Further options, such as
484
+ `extra_body_parameters`, are given as additional keywords:
290
485
 
291
486
  ```rb
292
- glossaries = DeepL.glossaries.list
487
+ glossary = client.create_multilingual_glossary(
488
+ 'My Glossary',
489
+ [
490
+ DeepL::Resources::MultilingualGlossaryDictionaryEntries.new(
491
+ 'EN', 'DE', { 'Hello' => 'Hallo', 'World' => 'Welt' }
492
+ ),
493
+ { source_lang: 'EN', target_lang: 'FR', entries: [['Hello', 'Bonjour']] }
494
+ ]
495
+ )
293
496
 
294
- puts glossaries.class
295
- # => Array
296
- puts glossaries.first.class
297
- # => DeepL::Resources::Glossary
497
+ puts glossary.class
498
+ # => DeepL::Resources::MultilingualGlossary
499
+ puts glossary.id
500
+ # => 'aa48c7f0-0d02-413e-8a06-d5bbf0ca7a6e'
501
+ puts glossary.creation_time.class
502
+ # => Time
503
+ puts glossary.dictionaries.first.entry_count
504
+ # => 2
298
505
  ```
299
506
 
300
- To find an existing glossary, use the `glossaries.find` method:
507
+ To create a multilingual glossary with one dictionary from CSV content (a string
508
+ or an IO), use `create_multilingual_glossary_from_csv`:
301
509
 
302
510
  ```rb
303
- glossary = DeepL.glossaries.find 'aa48c7f0-0d02-413e-8a06-d5bbf0ca7a6e'
511
+ glossary = client.create_multilingual_glossary_from_csv(
512
+ 'My Glossary', 'EN', 'DE', File.read('entries.csv')
513
+ )
514
+ ```
304
515
 
305
- puts glossary.class
306
- # => DeepL::Resources::Glossary
516
+ List or fetch multilingual glossaries with `list_multilingual_glossaries` and
517
+ `get_multilingual_glossary`. The glossary does not include the entries; fetch the
518
+ entries of one language pair with `get_multilingual_glossary_dictionary_entries`,
519
+ which raises `DeepL::Exceptions::NotFound` if the glossary has no dictionary for
520
+ that pair (the API answers 404; if it answers 200 with no entries instead, the
521
+ error's `http_status_code` is `nil`). The returned
522
+ object can be passed to the create, update and replace methods:
523
+
524
+ ```rb
525
+ glossaries = client.list_multilingual_glossaries
526
+ glossary = client.get_multilingual_glossary 'aa48c7f0-0d02-413e-8a06-d5bbf0ca7a6e'
527
+
528
+ dictionary = client.get_multilingual_glossary_dictionary_entries(glossary, 'EN', 'DE')
529
+ puts dictionary.entries.inspect
530
+ # => {"Hello"=>"Hallo", "World"=>"Welt"}
307
531
  ```
308
532
 
309
- The glossary resource does not include the glossary entries. To list the glossary entries, use the `glossaries.entries` method:
533
+ `update_multilingual_glossary` renames the glossary and/or merges entries into
534
+ its dictionaries (a new language pair adds a dictionary). Keywords left `nil` are
535
+ not sent. `update_multilingual_glossary_name`,
536
+ `update_multilingual_glossary_dictionary` and
537
+ `update_multilingual_glossary_dictionary_from_csv` do one of these at a time. To
538
+ replace the entries of a dictionary instead, use
539
+ `replace_multilingual_glossary_dictionary` (or
540
+ `replace_multilingual_glossary_dictionary_from_csv`):
310
541
 
311
542
  ```rb
312
- entries = DeepL.glossaries.entries 'aa48c7f0-0d02-413e-8a06-d5bbf0ca7a6e'
543
+ client.update_multilingual_glossary(
544
+ glossary, name: 'Renamed Glossary',
545
+ dictionaries: [{ source_lang: 'EN', target_lang: 'FR', entries: [['World', 'Monde']] }]
546
+ )
547
+ client.update_multilingual_glossary_name(glossary, 'Renamed Glossary')
548
+ client.update_multilingual_glossary_dictionary(
549
+ glossary, { source_lang: 'EN', target_lang: 'FR', entries: [['World', 'Monde']] }
550
+ )
551
+ client.replace_multilingual_glossary_dictionary(
552
+ glossary, { source_lang: 'EN', target_lang: 'DE', entries: [['Hello', 'Hallo'], ['car', 'Auto']] }
553
+ )
554
+ ```
313
555
 
314
- puts entries.class
315
- # => Array
316
- puts entries.size
556
+ To delete one dictionary or the entire glossary (both return `nil`):
557
+
558
+ ```rb
559
+ client.delete_multilingual_glossary_dictionary(glossary, 'EN', 'FR')
560
+ client.delete_multilingual_glossary(glossary)
561
+ ```
562
+
563
+ ### Spoken terms
564
+
565
+ Spoken terms collections improve the transcription of terms such as product
566
+ names. A collection holds one list of terms per language and is managed through
567
+ `DeepL::Client`. Every method that takes a collection accepts its ID or a
568
+ `DeepL::Resources::SpokenTerms` object; an empty ID, or an object without one,
569
+ raises `ArgumentError` before anything is sent. A `nil` or empty language does too.
570
+ Terms are passed and returned as arrays of strings.
571
+
572
+ To create a collection, pass a name and one `DeepL::Resources::SpokenTermsEntries`
573
+ (or a hash with `:lang` and `:entries`) per language. Terms are checked like
574
+ glossary terms: each term is stripped of surrounding whitespace and sent stripped,
575
+ and `create_spoken_terms`, `update_spoken_terms` and `replace_spoken_terms_list`
576
+ raise `DeepL::Exceptions::ValidationError` (an `ArgumentError`) before sending anything if a term is then empty or contains
577
+ a C0 or C1 control character (such as a tab or newline), U+2028 or U+2029.
578
+ Further options, such as `extra_body_parameters`, are given as additional
579
+ keywords:
580
+
581
+ ```rb
582
+ spoken_terms = client.create_spoken_terms(
583
+ 'Product names',
584
+ [DeepL::Resources::SpokenTermsEntries.new('en', ['DeepL', 'webhook'])]
585
+ )
586
+
587
+ puts spoken_terms.class
588
+ # => DeepL::Resources::SpokenTerms
589
+ puts spoken_terms.spoken_terms_id
590
+ # => 'a74d88fb-ed2a-4943-a664-a4512398b994'
591
+ puts spoken_terms.creation_time.class
592
+ # => Time
593
+ puts spoken_terms.term_lists.first.entry_count
317
594
  # => 2
318
- pp entries.first
319
- # => ["Hello World", "Hola Tierra"]
320
595
  ```
321
596
 
322
- To delete an existing glossary, use the `glossaries.destroy` method:
597
+ `creation_time` is `nil` if the API returns a malformed timestamp. List all
598
+ collections or fetch one with `list_spoken_terms` and `get_spoken_terms`:
323
599
 
324
600
  ```rb
325
- glossary_id = DeepL.glossaries.destroy 'aa48c7f0-0d02-413e-8a06-d5bbf0ca7a6e'
601
+ collections = client.list_spoken_terms
602
+ spoken_terms = client.get_spoken_terms 'a74d88fb-ed2a-4943-a664-a4512398b994'
603
+ ```
604
+
605
+ `update_spoken_terms` renames a collection and/or merges terms into the list of
606
+ each given language. Arguments that are not given are not sent:
326
607
 
327
- puts glossary_id
328
- # => aa48c7f0-0d02-413e-8a06-d5bbf0ca7a6e
608
+ ```rb
609
+ client.update_spoken_terms(spoken_terms, name: 'Renamed')
610
+ client.update_spoken_terms(spoken_terms, name: 'Renamed',
611
+ extra_body_parameters: { example_param: 'value' })
612
+ updated = client.update_spoken_terms(
613
+ spoken_terms, term_lists: [{ lang: 'en', entries: ['authentication'] }]
614
+ )
615
+ puts updated.term_lists.first.entry_count
616
+ # => 3
329
617
  ```
330
618
 
331
- You can list all the language pairs supported by glossaries using the `glossaries.language_pairs` method:
619
+ To read the terms of one language, use `get_spoken_terms_entries`:
332
620
 
333
621
  ```rb
334
- language_pairs = DeepL.glossaries.language_pairs
622
+ entries = client.get_spoken_terms_entries(spoken_terms, 'en')
623
+ puts entries.entries.inspect
624
+ # => ["DeepL", "authentication", "webhook"]
625
+ ```
335
626
 
336
- puts language_pairs.class
337
- # => Array
338
- puts language_pairs.first.class
339
- # => DeepL::Resources::LanguagePair
340
- puts language_pairs.first.source_lang
341
- # => en
342
- puts language_pairs.first.target_lang
343
- # => de
627
+ `replace_spoken_terms_list` replaces the terms of one language, or adds the list
628
+ if the language is new. It takes one `DeepL::Resources::SpokenTermsEntries` or a
629
+ hash with `:lang` and `:entries`:
630
+
631
+ ```rb
632
+ term_list = client.replace_spoken_terms_list(
633
+ spoken_terms, DeepL::Resources::SpokenTermsEntries.new('en', ['API'])
634
+ )
635
+ puts term_list.class
636
+ # => DeepL::Resources::SpokenTermsList
637
+ puts term_list.entry_count
638
+ # => 1
639
+ ```
640
+
641
+ To delete the list of one language or the entire collection (both return `nil`):
642
+
643
+ ```rb
644
+ client.delete_spoken_terms_list(spoken_terms, 'en')
645
+ client.delete_spoken_terms(spoken_terms)
344
646
  ```
345
647
 
346
648
  ### Style Rules
347
649
 
348
650
  Style rules allow you to customize your translations using a managed, shared list
349
- of rules for style, formatting, and more. Multiple style rules can be stored with
350
- your account, each with a user-specified name and a uniquely-assigned ID.
651
+ of rules for style, formatting, and more. Multiple style rule lists can be stored
652
+ with your account, each with a user-specified name and a uniquely-assigned ID
653
+ (`style_id`). `DeepL::Client` manages them with `get_all_style_rules`,
654
+ `create_style_rule`, `get_style_rule`, `update_style_rule_name`,
655
+ `update_style_rule_configured_rules` and `delete_style_rule`. Every method that
656
+ takes a style rule list accepts its ID string or a `DeepL::Resources::StyleRule`
657
+ object, and every method that takes a custom instruction its ID or a
658
+ `DeepL::Resources::CustomInstruction`. An empty ID (or an object without one), and
659
+ an empty name, language, label or prompt, raise `ArgumentError` before anything is
660
+ sent; so does an empty `source_language` of a custom instruction (`nil` leaves it unset).
351
661
 
352
662
  #### Creating a style rule
353
663
 
354
- Use `create` to create a new style rule with a name and language code. You can
355
- optionally provide `configured_rules` and `custom_instructions`.
664
+ Use `create_style_rule` with a name and language code. The optional keywords
665
+ `configured_rules` (category -> rule -> value) and `custom_instructions` (hashes
666
+ with `label`, `prompt` and optionally `source_language`) are sent as given;
667
+ keywords left `nil` are not sent. `extra_body_parameters` adds fields to the
668
+ request body.
356
669
 
357
670
  ```rb
671
+ client = DeepL::Client.new(ENV.fetch('DEEPL_AUTH_KEY'))
672
+
358
673
  # Simple creation with just a name and language
359
- style_rule = DeepL.style_rules.create('My Style Rule', 'en')
674
+ style_rule = client.create_style_rule('My Style Rule', 'en')
360
675
  puts "Created: #{style_rule.name} (#{style_rule.style_id})"
361
676
 
362
677
  # Creation with configured rules and custom instructions
363
- style_rule = DeepL.style_rules.create(
678
+ style_rule = client.create_style_rule(
364
679
  'Formal English',
365
680
  'en',
366
- configured_rules: { style_and_tone: { formality: 'formal' } },
681
+ configured_rules: { dates_and_times: { calendar_era: 'use_bc_and_ad' } },
367
682
  custom_instructions: [{ label: 'Tone', prompt: 'Always use formal language' }]
368
683
  )
369
684
  ```
370
685
 
371
686
  #### Retrieving and listing style rules
372
687
 
373
- Use `find` to retrieve a single style rule by ID, or `list` to list all style
374
- rules.
375
-
376
- `list` returns a list of `StyleRule` objects corresponding to all of your stored
377
- style rules. The method accepts optional parameters: `page` (page number for
378
- pagination, 0-indexed), `page_size` (number of items per page), and `detailed`.
379
- When `true`, the response includes `configured_rules` and `custom_instructions`
380
- for each style rule. When `false` (default), these fields are omitted for faster
381
- responses.
688
+ Use `get_style_rule` to retrieve a single style rule list, or `get_all_style_rules`
689
+ to list them one page at a time. `get_all_style_rules` returns a list of
690
+ `StyleRule` objects and accepts the optional keywords `page` (page number,
691
+ 0-indexed), `page_size` (number of items per page) and `detailed`. When `true`,
692
+ the response includes `configured_rules` and `custom_instructions` for each style
693
+ rule list; when `false` (default), these fields are omitted for faster responses.
694
+ Keywords left `nil` are not sent.
382
695
 
383
696
  ```rb
384
- # Get a single style rule by ID
385
- style_rule = DeepL.style_rules.find('YOUR_STYLE_ID')
697
+ # Get a single style rule list by ID
698
+ style_rule = client.get_style_rule('YOUR_STYLE_ID')
386
699
  puts "#{style_rule.name} (#{style_rule.language})"
387
700
 
388
- # List all style rules
389
- style_rules = DeepL.style_rules.list
390
- style_rules.each do |rule|
701
+ # List the first page of style rule lists
702
+ client.get_all_style_rules.each do |rule|
391
703
  puts "#{rule.name} (#{rule.style_id})"
392
704
  end
393
705
 
394
706
  # List with pagination
395
- style_rules = DeepL.style_rules.list(page: 0, page_size: 10)
707
+ style_rules = client.get_all_style_rules(page: 0, page_size: 10)
396
708
 
397
709
  # List with detailed configuration
398
- style_rules = DeepL.style_rules.list(detailed: true)
399
- style_rules.each do |rule|
710
+ client.get_all_style_rules(detailed: true).each do |rule|
400
711
  if rule.configured_rules
401
- puts " Number formatting: #{rule.configured_rules.numbers.keys.join(', ')}"
712
+ puts " Number formatting: #{rule.configured_rules.fetch('numbers', {}).keys.join(', ')}"
402
713
  end
403
714
  end
404
715
  ```
405
716
 
406
717
  #### Updating a style rule
407
718
 
408
- Use `update_name` to rename a style rule, and `update_configured_rules` to
409
- update its configured rules.
719
+ Use `update_style_rule_name` to rename a style rule list, and
720
+ `update_style_rule_configured_rules` to replace its configured rules. Both accept
721
+ `extra_body_parameters`.
410
722
 
411
723
  ```rb
412
724
  # Update the name
413
- updated = DeepL.style_rules.update_name('YOUR_STYLE_ID', 'New Name')
725
+ updated = client.update_style_rule_name(style_rule, 'New Name')
414
726
 
415
727
  # Update configured rules
416
- updated = DeepL.style_rules.update_configured_rules(
417
- 'YOUR_STYLE_ID',
418
- { style_and_tone: { formality: 'formal' } }
728
+ updated = client.update_style_rule_configured_rules(
729
+ style_rule,
730
+ { dates_and_times: { calendar_era: 'use_bc_and_ad' } }
419
731
  )
420
732
  ```
421
733
 
422
- The `configured_rules` hash supports the following categories: `dates_and_times`,
423
- `formatting`, `numbers`, `punctuation`, `spelling_and_grammar`, `style_and_tone`,
424
- and `vocabulary`.
734
+ `StyleRule#configured_rules` returns the configured rules as the API sends them: a
735
+ hash of category -> rule -> value with string keys, or `nil` when the response omits
736
+ them. Category and rule names are not validated; the API reference lists the
737
+ supported ones.
425
738
 
426
739
  #### Managing custom instructions
427
740
 
428
- Custom instructions allow you to add free-text prompts to a style rule. Each
741
+ Custom instructions allow you to add free-text prompts to a style rule list. Each
429
742
  instruction has an `id`, `label`, `prompt`, and `source_language`. Use
430
- `create_custom_instruction`, `find_custom_instruction`,
431
- `update_custom_instruction`, and `destroy_custom_instruction` to manage them.
743
+ `create_style_rule_custom_instruction`, `get_style_rule_custom_instruction`,
744
+ `update_style_rule_custom_instruction`, and `delete_style_rule_custom_instruction`
745
+ to manage them. An instruction is given as its ID or a
746
+ `DeepL::Resources::CustomInstruction` object; `source_language` is optional and
747
+ not sent if `nil`.
432
748
 
433
749
  ```rb
434
750
  # Create a custom instruction
435
- instruction = DeepL.style_rules.create_custom_instruction(
436
- 'YOUR_STYLE_ID', 'Formal tone', 'Always use formal language'
751
+ instruction = client.create_style_rule_custom_instruction(
752
+ style_rule, 'Formal tone', 'Always use formal language'
437
753
  )
438
754
  puts "Created instruction: #{instruction.id}"
439
755
 
440
756
  # Create with an optional source language
441
- instruction = DeepL.style_rules.create_custom_instruction(
442
- 'YOUR_STYLE_ID', 'Formal tone', 'Always use formal language', 'en'
757
+ instruction = client.create_style_rule_custom_instruction(
758
+ style_rule, 'Formal tone', 'Always use formal language', source_language: 'en'
443
759
  )
444
760
 
445
761
  # Get a custom instruction
446
- instruction = DeepL.style_rules.find_custom_instruction('YOUR_STYLE_ID', instruction.id)
762
+ instruction = client.get_style_rule_custom_instruction(style_rule, instruction)
447
763
 
448
764
  # Update a custom instruction
449
- updated = DeepL.style_rules.update_custom_instruction(
450
- 'YOUR_STYLE_ID', instruction.id, 'Updated label', 'Use very formal language'
765
+ updated = client.update_style_rule_custom_instruction(
766
+ style_rule, instruction, 'Updated label', 'Use very formal language'
451
767
  )
452
768
 
453
- # Delete a custom instruction
454
- DeepL.style_rules.destroy_custom_instruction('YOUR_STYLE_ID', instruction.id)
769
+ # Delete a custom instruction (returns nil)
770
+ client.delete_style_rule_custom_instruction(style_rule, instruction)
455
771
  ```
456
772
 
457
773
  #### Deleting a style rule
458
774
 
459
- Use `destroy` to delete a style rule by ID.
775
+ Use `delete_style_rule` to delete a style rule list. It returns `nil`.
460
776
 
461
777
  ```rb
462
- DeepL.style_rules.destroy('YOUR_STYLE_ID')
778
+ client.delete_style_rule('YOUR_STYLE_ID')
463
779
  ```
464
780
 
465
781
  #### Using style rules in translations
466
782
 
467
- Style rules can be used in the `translate` method by specifying the `style_rule` option
783
+ Style rules can be used in `translate_text` by specifying the `style_rule` option
468
784
  with either a style rule ID string or a `StyleRule` object:
469
785
 
470
786
  ```rb
471
787
  # Using a style rule ID
472
- translation = DeepL.translate 'Hello World', 'EN', 'ES', style_rule: 'dca2e053-8ae5-45e6-a0d2-881156e7f4e4'
788
+ translation = client.translate_text('Hello World', 'EN', 'ES',
789
+ style_rule: 'dca2e053-8ae5-45e6-a0d2-881156e7f4e4')
473
790
 
474
791
  # Or using a StyleRule object
475
- style_rules = DeepL.style_rules.list
476
- translation = DeepL.translate 'Hello World', 'EN', 'ES', style_rule: style_rules.first
792
+ style_rule = client.get_all_style_rules.first
793
+ translation = client.translate_text('Hello World', 'EN', 'ES', style_rule: style_rule)
794
+ ```
795
+
796
+ The same `style_rule` option can be passed to document translation
797
+ (`translate_document` or `translate_document_upload`), accepting either a style
798
+ rule ID string or a `StyleRule` object:
799
+
800
+ ```rb
801
+ client.translate_document('my_document.docx', 'my_document_es.docx', 'EN', 'ES',
802
+ style_rule: 'dca2e053-8ae5-45e6-a0d2-881156e7f4e4')
477
803
  ```
478
804
 
479
- The same `style_rule` option can be passed to document translation via
480
- `DeepL.document.upload` (or `DeepL.document.translate_document`), accepting either
481
- a style rule ID string or a `StyleRule` object:
805
+ ### Style profiles
806
+
807
+ A style profile bundles glossaries, style rule lists and translation memories under one
808
+ name. `DeepL::Client` manages them with `create_style_profile`, `get_style_profile`,
809
+ `list_style_profiles`, `update_style_profile` and `delete_style_profile`. The last three
810
+ take a style profile ID string or a `DeepL::Resources::StyleProfile` object; the ID of a
811
+ profile is `style_profile_id`.
812
+
813
+ #### Creating a style profile
814
+
815
+ Only the name is required. The optional keywords are `description`, `industry`,
816
+ `glossary_ids`, `style_rule_ids`, `translation_memory_ids` and
817
+ `glossary_priority_order_enabled` (when `true`, the order of `glossary_ids` sets priority).
818
+ The component lists take IDs or the resource objects (`Glossary`, `MultilingualGlossary`,
819
+ `StyleRule`, `TranslationMemory`), which are sent as their IDs. If any component cannot be
820
+ used, the request fails and no style profile is created. `extra_body_parameters` adds
821
+ fields to the request body.
482
822
 
483
823
  ```rb
484
- handle = DeepL.document.upload 'my_document.docx', 'EN', 'ES', 'my_document.docx',
485
- style_rule: 'dca2e053-8ae5-45e6-a0d2-881156e7f4e4'
824
+ client = DeepL::Client.new(ENV.fetch('DEEPL_AUTH_KEY'))
825
+
826
+ # Only a name
827
+ profile = client.create_style_profile('Legal, German')
828
+
829
+ # With components
830
+ profile = client.create_style_profile(
831
+ 'Legal, German',
832
+ description: 'Contract wording for the German market.',
833
+ industry: 'Legal',
834
+ glossary_ids: ['YOUR_GLOSSARY_ID'],
835
+ style_rule_ids: [style_rule], # a DeepL::Resources::StyleRule
836
+ translation_memory_ids: ['YOUR_TM_ID'],
837
+ glossary_priority_order_enabled: true
838
+ )
839
+ profile.class
840
+ # => DeepL::Resources::StyleProfile
841
+ profile.style_profile_id
842
+ # => "3f1c9d0e-7a24-4b58-9c31-8f0e5d2a1b47"
843
+ profile.style_rule_ids
844
+ # => ["YOUR_STYLE_ID"]
845
+ profile.creation_time.class
846
+ # => Time
486
847
  ```
487
848
 
849
+ `description` and `industry` are `nil` when the style profile has none.
850
+
851
+ #### Retrieving and listing style profiles
852
+
853
+ `list_style_profiles` returns an array of style profiles, one page at a time. It accepts
854
+ `page:` (0-indexed, default 0) and `page_size:` (default 10; values above 100 are reduced to
855
+ 100).
856
+
857
+ ```rb
858
+ profile = client.get_style_profile('YOUR_STYLE_PROFILE_ID')
859
+
860
+ profiles = client.list_style_profiles
861
+ profiles = client.list_style_profiles(page: 1, page_size: 100)
862
+ ```
863
+
864
+ #### Updating a style profile
865
+
866
+ `update_style_profile` takes the same keywords as `create_style_profile`, plus `name`.
867
+ Keywords you leave out (or set to `nil`) are not sent and leave the field unchanged. An
868
+ empty string clears `description` or `industry`. A component list you send replaces the
869
+ linked list in full; an empty array unlinks all components of that kind.
870
+
871
+ ```rb
872
+ updated = client.update_style_profile(
873
+ 'YOUR_STYLE_PROFILE_ID',
874
+ name: 'Legal, German (2026)',
875
+ industry: 'Legal',
876
+ description: '', # clears the description
877
+ style_rule_ids: [] # unlinks all style rule lists
878
+ )
879
+ updated.description
880
+ # => nil
881
+ ```
882
+
883
+ #### Deleting a style profile
884
+
885
+ `delete_style_profile` returns `nil`.
886
+
887
+ ```rb
888
+ client.delete_style_profile('YOUR_STYLE_PROFILE_ID')
889
+ ```
890
+
891
+ #### Using style profiles in translations
892
+
893
+ Pass the `style_profile` option, a style profile ID string or a `StyleProfile` object, to
894
+ `translate_text`, `translate_document` or `translate_document_upload` to apply the
895
+ profile's glossaries, style rule lists and translation memories. A component that does not
896
+ fit the language pair is left out. The option cannot be combined with `glossary`,
897
+ `glossary_ids`, `style_rule`, `translation_memory`,
898
+ `translation_memory_threshold` or `custom_instructions`; the API rejects such requests.
899
+
900
+ ```rb
901
+ translation = client.translate_text('The artist is here.', nil, 'DE', style_profile: profile)
902
+ puts translation.text
903
+ # => Der Maler ist hier.
904
+
905
+ client.translate_document('/path/to/document.docx', '/path/to/translated.docx', 'EN', 'DE',
906
+ style_profile: 'YOUR_STYLE_PROFILE_ID')
907
+ ```
908
+
909
+ With documents, an unknown style profile is not rejected at upload: the translation fails
910
+ with a `DeepL::Exceptions::DocumentTranslationError` whose message contains
911
+ `Style profile not found.`
912
+
488
913
  ### Translation Memories
489
914
 
490
915
  Translation memories allow you to store and reuse previously created translations.
@@ -495,37 +920,47 @@ account, each with a source language and one or more target languages.
495
920
  Translation memories can also be managed in the DeepL UI via
496
921
  https://www.deepl.com/translation-memory.
497
922
 
498
- Every method that takes a translation memory accepts either a string containing
499
- the translation memory ID or a `TranslationMemory` object.
923
+ `DeepL::Client` manages them with `list_translation_memories`,
924
+ `get_translation_memory`, `list_translation_memory_segments`,
925
+ `import_translation_memory_from_filepath`, `export_translation_memory_to_filepath`
926
+ and `delete_translation_memory`, plus the single steps of an import or export
927
+ described below. Every method that takes a translation memory accepts either a
928
+ string containing the translation memory ID or a `TranslationMemory` object, and
929
+ every method that takes a job accepts its ID or a `TranslationMemoryJob`. An empty
930
+ ID or upload URL, or an object without one, raises `ArgumentError` before any
931
+ request is sent; an export job without a download URL raises
932
+ `DeepL::Exceptions::Error`.
500
933
 
501
934
  #### Listing translation memories
502
935
 
503
- `translation_memories.list` returns a list of `TranslationMemory` objects
504
- for your stored translation memories. The method accepts optional parameters:
505
- `page` (page number for pagination, 0-indexed) and `page_size` (number of items
506
- per page, max 25).
936
+ `list_translation_memories` returns a list of `TranslationMemory` objects for
937
+ your stored translation memories, one page at a time. It accepts the optional
938
+ keywords `page` (page number for pagination, 0-indexed) and `page_size` (number
939
+ of items per page, max 25). Keywords left `nil` are not sent.
507
940
 
508
941
  ```rb
942
+ client = DeepL::Client.new(ENV.fetch('DEEPL_AUTH_KEY'))
943
+
509
944
  # List translation memories
510
- translation_memories = DeepL.translation_memories.list
511
- translation_memories.each do |tm|
945
+ client.list_translation_memories.each do |tm|
512
946
  puts "#{tm.name} (#{tm.translation_memory_id})"
513
947
  puts " Source: #{tm.source_language}, Targets: #{tm.target_languages.join(', ')}"
514
948
  puts " Segments: #{tm.segment_count}"
515
949
  end
516
950
 
517
951
  # List with pagination
518
- translation_memories = DeepL.translation_memories.list(page: 0, page_size: 10)
952
+ translation_memories = client.list_translation_memories(page: 0, page_size: 10)
519
953
  ```
520
954
 
521
955
  #### Retrieving a single translation memory
522
956
 
523
- `translation_memories.find` retrieves one translation memory by ID. In addition
524
- to the fields returned by `list`, the resource carries the `creation_time` and
525
- `updated_time` timestamps.
957
+ `get_translation_memory` retrieves one translation memory. In addition to the
958
+ fields returned by `list_translation_memories`, the resource carries the
959
+ `creation_time` and `updated_time` timestamps (`nil` if the API sends none or a
960
+ malformed one).
526
961
 
527
962
  ```rb
528
- tm = DeepL.translation_memories.find 'YOUR_TM_ID'
963
+ tm = client.get_translation_memory('YOUR_TM_ID')
529
964
 
530
965
  puts tm.class
531
966
  # => DeepL::Resources::TranslationMemory
@@ -539,7 +974,7 @@ puts tm.creation_time.class
539
974
 
540
975
  #### Listing the segments of a translation memory
541
976
 
542
- `translation_memories.segments` returns one page of the segments of a
977
+ `list_translation_memory_segments` returns one page of the segments of a
543
978
  translation memory as a `TranslationMemorySegments` object. Each segment holds
544
979
  the source text and one target per target language of the translation memory.
545
980
 
@@ -547,13 +982,14 @@ Pagination is cursor-based: omit `page_cursor` on the first call, then pass the
547
982
  `next_page_cursor` of the previous response until `next_page?` is `false`. The
548
983
  method also accepts `page_size` (1-100, defaults to 50), `filter_text` (a
549
984
  substring matched against the source and target texts, at least 2 characters)
550
- and `filter_case_sensitive` (defaults to `false`).
985
+ and `filter_case_sensitive` (defaults to `false`). Keywords left `nil` are not
986
+ sent.
551
987
 
552
988
  Note that `segment_count` is the number of segments stored in the translation
553
989
  memory; a text filter does not reduce it.
554
990
 
555
991
  ```rb
556
- page = DeepL.translation_memories.segments 'YOUR_TM_ID', page_size: 50
992
+ page = client.list_translation_memory_segments('YOUR_TM_ID', page_size: 50)
557
993
 
558
994
  puts page.class
559
995
  # => DeepL::Resources::TranslationMemorySegments
@@ -566,28 +1002,39 @@ puts page.segments.first.targets.first.target_text
566
1002
 
567
1003
  # Walk through every page of segments
568
1004
  while page.next_page?
569
- page = DeepL.translation_memories.segments 'YOUR_TM_ID',
570
- page_size: 50,
571
- page_cursor: page.next_page_cursor
1005
+ page = client.list_translation_memory_segments('YOUR_TM_ID',
1006
+ page_size: 50,
1007
+ page_cursor: page.next_page_cursor)
572
1008
  end
573
1009
 
574
1010
  # Only the segments matching a text
575
- page = DeepL.translation_memories.segments 'YOUR_TM_ID',
576
- filter_text: 'Nummer 1',
577
- filter_case_sensitive: true
1011
+ page = client.list_translation_memory_segments('YOUR_TM_ID',
1012
+ filter_text: 'Nummer 1',
1013
+ filter_case_sensitive: true)
578
1014
  ```
579
1015
 
580
1016
  #### Importing a translation memory
581
1017
 
582
- `translation_memories.import_from_filepath` creates a new translation memory
583
- from a TMX file. It creates the import job, uploads the file and waits for the
584
- processing to finish, and returns the finished `TranslationMemoryJob`. Its
585
- result carries the ID of the newly created translation memory.
1018
+ `import_translation_memory_from_filepath` creates a new translation memory from
1019
+ a TMX file. It creates the import job, uploads the file and waits until the job
1020
+ is completed, and returns the `TranslationMemoryJob`. Its result carries the ID
1021
+ of the newly created translation memory. The optional keywords are
1022
+ `display_name` (the name of the translation memory, defaults to the file name),
1023
+ `content_type` (the MIME type of the file, declared in the job and sent with the
1024
+ upload, defaults to `application/xml`), `timeout_s` and `extra_body_parameters`
1025
+ (fields added to the body of the import job request). It raises an
1026
+ `ArgumentError` before any request if the file does not exist. Every other
1027
+ failure raises a `DeepL::Exceptions::TranslationMemoryJobError` with the original
1028
+ error as `cause`: an empty or unreadable file (before any request), a failed job
1029
+ creation or upload, a job that fails or expires (with the API's error message),
1030
+ and an expired `timeout_s`. Its `job_id` is set as soon as the job was created,
1031
+ so you can still query it, and its `job` is the last job status fetched (`nil`
1032
+ before the first status check).
586
1033
 
587
1034
  ```rb
588
- job = DeepL.translation_memories.import_from_filepath 'legal.tmx',
589
- display_name: 'Legal',
590
- timeout_s: 300
1035
+ job = client.import_translation_memory_from_filepath('legal.tmx',
1036
+ display_name: 'Legal',
1037
+ timeout_s: 300)
591
1038
 
592
1039
  puts job.class
593
1040
  # => DeepL::Resources::TranslationMemoryJob
@@ -599,179 +1046,371 @@ puts job.result.skipped_segment_count
599
1046
  # => 0
600
1047
  ```
601
1048
 
602
- The three steps can also be performed separately, for example to upload a file
603
- that is not available on the local file system. The upload URL is a pre-signed
604
- storage URL outside of the DeepL API, so no authorization header is sent with
605
- the upload.
1049
+ The three steps can also be performed separately with
1050
+ `create_translation_memory_import`, `upload_translation_memory_file` and
1051
+ `wait_until_translation_memory_job_done`, for example to upload a file that is
1052
+ not available on the local file system. `create_translation_memory_import`
1053
+ accepts `content_type`, `display_name` and `extra_body_parameters`; keywords left
1054
+ `nil` are not sent. An empty file name or a `content_length` that is not
1055
+ positive raises `ArgumentError` before any request. The upload URL is a pre-signed storage URL outside of the
1056
+ DeepL API, so no authorization header and, of the configured `headers`, only a
1057
+ `User-Agent` is sent with the upload; the proxy, SSL and timeout settings of the client apply. A non-2xx
1058
+ reply of a storage URL (for example 403 for an expired URL) raises a plain
1059
+ `DeepL::Exceptions::Error` carrying `http_status_code`; its `should_retry?` is
1060
+ `true` for 429 and 5xx.
606
1061
 
607
1062
  ```rb
608
- content = File.binread 'legal.tmx'
609
- created = DeepL.translation_memories.create_import 'legal.tmx', content.bytesize,
610
- content_type: 'application/xml',
611
- display_name: 'Legal'
1063
+ content = File.binread('legal.tmx')
1064
+ created = client.create_translation_memory_import('legal.tmx', content.bytesize,
1065
+ content_type: 'application/xml',
1066
+ display_name: 'Legal')
612
1067
 
613
1068
  puts created.upload_url
614
1069
  # => 'https://...'
615
1070
 
616
- DeepL.translation_memories.upload_file created, content
617
- job = DeepL.translation_memories.wait_until_job_done created.job_id
1071
+ client.upload_translation_memory_file(created, content, content_type: 'application/xml')
1072
+ job = client.wait_until_translation_memory_job_done(created.job_id)
618
1073
  ```
619
1074
 
620
1075
  Until the file is uploaded the job stays in the `awaiting_input` status and
621
1076
  `result.required_action` describes what is missing. The API detects the upload
622
1077
  asynchronously, so the job keeps reporting `awaiting_input` for a while
623
1078
  afterwards, typically around half a minute, before it completes.
624
- `wait_until_job_done` therefore polls through that status like any other
625
- non-terminal one. A job whose file is never uploaded does not finish on its own,
626
- so pass `timeout_s` when that is a possibility.
1079
+ `wait_until_translation_memory_job_done` therefore polls through that status
1080
+ like any other non-terminal one. A job whose file is never uploaded does not
1081
+ finish on its own, and a status the library does not know keeps it polling too, so pass
1082
+ `timeout_s` to bound the wait.
627
1083
 
628
1084
  #### Exporting a translation memory
629
1085
 
630
- `translation_memories.export_to_filepath` writes a translation memory to a TMX
631
- file. It creates the export job, waits for it to finish and downloads the
632
- result, overwriting the output file if it already exists.
1086
+ `export_translation_memory_to_filepath` writes a translation memory to a TMX
1087
+ file. It creates the export job, waits until it is completed and downloads the
1088
+ result. It accepts `timeout_s` and wraps every failure in a
1089
+ `DeepL::Exceptions::TranslationMemoryJobError` with the original error as
1090
+ `cause`: an output file that already exists or a directory that does not exist or
1091
+ is not writable (checked before the job is created, `job_id` and `job` are `nil`),
1092
+ a job that fails or expires, an expired `timeout_s`, and a failed download or
1093
+ write. Its `job_id` is set once the job was created, and `job` is the last job
1094
+ status fetched.
633
1095
 
634
1096
  ```rb
635
- job = DeepL.translation_memories.export_to_filepath 'YOUR_TM_ID', 'export.tmx'
1097
+ job = client.export_translation_memory_to_filepath('YOUR_TM_ID', 'export.tmx')
636
1098
 
637
1099
  puts job.status
638
1100
  # => 'completed'
639
1101
  ```
640
1102
 
641
- The steps can be performed separately as well. Repeating the export of an
642
- unchanged translation memory reuses the previously completed job instead of
643
- starting a new one, which `reused_existing?` reports. Just like the upload URL,
644
- the download URL is a pre-signed storage URL and is requested without an
645
- authorization header.
1103
+ The steps can be performed separately as well, with
1104
+ `create_translation_memory_export`, `wait_until_translation_memory_job_done` and
1105
+ `download_translation_memory_export`. Repeating the export of an unchanged
1106
+ translation memory reuses the previously completed job instead of starting a new
1107
+ one, which `reused_existing?` reports. Just like the upload URL, the download URL
1108
+ is a pre-signed storage URL and is requested without an authorization header.
1109
+ `download_translation_memory_export` raises a `SystemCallError` before the
1110
+ download if the output file exists (`Errno::EEXIST`) or its directory is missing
1111
+ or not writable (`Errno::ENOENT`, `Errno::EACCES`), and the `Errno` error of
1112
+ writing the file.
646
1113
 
647
1114
  ```rb
648
- created = DeepL.translation_memories.create_export 'YOUR_TM_ID'
1115
+ created = client.create_translation_memory_export('YOUR_TM_ID')
649
1116
 
650
1117
  puts created.reused_existing?
651
1118
  # => false
652
1119
 
653
- job = DeepL.translation_memories.wait_until_job_done created.job_id
1120
+ job = client.wait_until_translation_memory_job_done(created.job_id)
654
1121
 
655
1122
  puts job.result.download_url
656
1123
  # => 'https://...'
657
1124
 
658
- DeepL.translation_memories.download_export job, 'export.tmx'
1125
+ client.download_translation_memory_export(job, 'export.tmx')
659
1126
  ```
660
1127
 
661
1128
  #### Tracking import and export jobs
662
1129
 
663
- `translation_memories.find_job` returns the current status of an import or
664
- export job, and `translation_memories.wait_until_job_done` polls it every five
665
- seconds until it finished, raising if the job failed or expired. Pass
666
- `timeout_s` to give up after a number of seconds instead of waiting forever.
1130
+ `get_translation_memory_job` returns the current status of an import or export
1131
+ job, and `wait_until_translation_memory_job_done` polls it every five seconds
1132
+ until it is completed, raising a `DeepL::Exceptions::Error` with the API's error
1133
+ message if the job failed or expired. A status the library does not know keeps it
1134
+ polling. Pass `timeout_s` to give up after a number of seconds instead of
1135
+ waiting forever; the last wait is cut so that the call never waits longer than
1136
+ `timeout_s`.
1137
+
1138
+ `done?` is `true` once the job is completed, `ok?` is `false` once it failed or
1139
+ expired (and `true` while it runs), and `finished?` is `true` once it is
1140
+ completed, failed or expired.
667
1141
 
668
1142
  ```rb
669
- job = DeepL.translation_memories.find_job 'YOUR_JOB_ID'
1143
+ job = client.get_translation_memory_job('YOUR_JOB_ID')
670
1144
 
671
1145
  puts job.operation
672
1146
  # => 'import'
673
1147
  puts job.status
674
1148
  # => 'processing'
675
- puts job.finished?
676
- # => false
1149
+ puts [job.done?, job.ok?, job.finished?].inspect
1150
+ # => [false, true, false]
677
1151
  ```
678
1152
 
679
- The status is one of `awaiting_input`, `processing`, `completed`, `downloaded`,
680
- `failed` or `expired`.
1153
+ The status is one of `awaiting_input`, `processing`, `completed`, `failed` or
1154
+ `expired`.
681
1155
 
682
1156
  #### Deleting a translation memory
683
1157
 
684
- `translation_memories.destroy` deletes a translation memory and returns its ID.
1158
+ `delete_translation_memory` deletes a translation memory. It returns `nil`.
685
1159
 
686
1160
  ```rb
687
- DeepL.translation_memories.destroy 'YOUR_TM_ID'
688
- # => 'YOUR_TM_ID'
1161
+ client.delete_translation_memory('YOUR_TM_ID')
689
1162
  ```
690
1163
 
691
1164
  #### Using a translation memory in translations
692
1165
 
693
- Pass the `translation_memory` parameter to `translate` to use a translation
1166
+ Pass the `translation_memory` option to `translate_text` to use a translation
694
1167
  memory. You can pass either a string containing the translation memory ID, or a
695
1168
  `TranslationMemory` object. Use `translation_memory_threshold` to control the
696
1169
  minimum matching percentage for fuzzy matches (0-100, recommended minimum of
697
- 75%).
1170
+ 75%). It requires `translation_memory`; without it, or with a value outside 0 to
1171
+ 100, it raises `ArgumentError` before anything is sent.
698
1172
 
699
1173
  ```rb
700
1174
  # Using a translation memory ID
701
- translation = DeepL.translate 'Hello, world!', 'EN', 'DE',
702
- translation_memory: 'YOUR_TM_ID',
703
- translation_memory_threshold: 80
1175
+ translation = client.translate_text('Hello, world!', 'EN', 'DE',
1176
+ translation_memory: 'YOUR_TM_ID',
1177
+ translation_memory_threshold: 80)
704
1178
 
705
1179
  # Or using a TranslationMemory object
706
- translation_memories = DeepL.translation_memories.list
707
- translation = DeepL.translate 'Hello, world!', 'EN', 'DE',
708
- translation_memory: translation_memories.first
1180
+ translation_memories = client.list_translation_memories
1181
+ translation = client.translate_text('Hello, world!', 'EN', 'DE',
1182
+ translation_memory: translation_memories.first)
709
1183
  ```
710
1184
 
711
1185
  The same `translation_memory` and `translation_memory_threshold` options can be
712
- passed to document translation via `DeepL.document.upload` (or
713
- `DeepL.document.translate_document`). The `translation_memory` option accepts
714
- either a translation memory ID string or a `TranslationMemory` object:
1186
+ passed to document translation via `translate_document_upload` (or
1187
+ `translate_document`). The `translation_memory` option accepts either a
1188
+ translation memory ID string or a `TranslationMemory` object:
715
1189
 
716
1190
  ```rb
717
- handle = DeepL.document.upload 'my_document.docx', 'EN', 'DE', 'my_document.docx',
718
- translation_memory: 'YOUR_TM_ID',
719
- translation_memory_threshold: 80
1191
+ handle = client.translate_document_upload('my_document.docx', 'EN', 'DE',
1192
+ translation_memory: 'YOUR_TM_ID',
1193
+ translation_memory_threshold: 80)
720
1194
  ```
721
1195
 
722
1196
  ### Monitor usage
723
1197
 
724
- To check current API usage, use:
1198
+ To check current API usage, call `get_usage`. It returns a `DeepL::Resources::Usage`. Each
1199
+ usage type is a `DeepL::Resources::Usage::Detail` with `count`, `limit` and `limit_reached?`.
1200
+ `any_character_limit_reached?` is `true` if the account's character limit (`character`) or this
1201
+ API key's character limit (`api_key_character`, API Pro) is reached; the speech minutes have
1202
+ their own details:
725
1203
 
726
1204
  ```rb
727
- usage = DeepL.usage
1205
+ usage = client.get_usage
728
1206
 
729
- puts usage.character_count
1207
+ puts usage.character.count
730
1208
  # => 180118
731
- puts usage.character_limit
1209
+ puts usage.character.limit
732
1210
  # => 1250000
1211
+ puts 'Character limit reached.' if usage.any_character_limit_reached?
1212
+ ```
1213
+
1214
+ For API Pro users, the response also contains this API key's usage, speech usage, the billing
1215
+ period and a per-product breakdown. These fields are `nil` when the response does not contain
1216
+ them (e.g. for API Free users). `any_character_limit_reached?` considers `api_key_character`
1217
+ but not the speech usage; call `limit_reached?` on it directly, e.g.
1218
+ `usage.speech_to_text_minutes.limit_reached?`:
1219
+
1220
+ ```rb
1221
+ usage = client.get_usage
1222
+
1223
+ # Characters used by the whole account vs. by this API key
1224
+ puts "account: #{usage.character}"
1225
+ # => account: 5947223 of 1000000000000
1226
+ puts "this key: #{usage.api_key_character}"
1227
+ # => this key: 636 of 1000000000000
1228
+
1229
+ puts usage.speech_to_text_minutes # => 30 of 600
1230
+ puts usage.speech_to_speech_minutes # => 12 of 600
1231
+ puts usage.start_time # => 2025-05-13 09:18:42 UTC (Time)
1232
+ puts usage.end_time # => 2025-06-13 09:18:42 UTC (Time)
1233
+
1234
+ usage.products&.each do |product|
1235
+ # product_type and billing_unit are plain strings, e.g. 'translate' and 'characters'
1236
+ puts "#{product.product_type}: key #{product.api_key_unit_count}, " \
1237
+ "account #{product.account_unit_count} #{product.billing_unit}"
1238
+ end
1239
+ # => translate: key 636, account 5941580 characters
733
1240
  ```
734
1241
 
735
1242
  ### Translate documents
736
1243
 
737
- To translate a document, use the `document.translate_document` method. Example:
1244
+ To translate a document, use the `translate_document` method of `DeepL::Client`. It uploads
1245
+ the document, waits until the translation is done and writes the translated document to the
1246
+ output path, which must not exist yet. It returns the final
1247
+ `DeepL::Resources::DocumentTranslationStatus`:
1248
+
1249
+ ```rb
1250
+ status = client.translate_document('/path/to/spanish_document.pdf',
1251
+ '/path/to/translated_document.pdf', 'ES', 'EN')
1252
+ puts status.billed_characters
1253
+ # => 2045
1254
+ ```
1255
+
1256
+ A missing input file raises `ArgumentError` before anything is sent. Every other failure raises
1257
+ `DeepL::Exceptions::DocumentTranslationError`: an existing output file (which is kept) or one
1258
+ whose directory is missing or not writable, and an invalid argument of the upload such as an
1259
+ unknown option, all detected before anything is sent (`document_handle` is `nil`), as well as a
1260
+ failed upload or translation. Once the upload succeeded, its `document_handle`
1261
+ is set, so you can still query the status and download the document. If a DeepL error caused
1262
+ it, its `http_status_code` and `should_retry?` are copied from that error. `timeout_s:` limits the wait after the upload in seconds; by default
1263
+ `translate_document` waits until the translation is done or failed:
738
1264
 
739
1265
  ```rb
740
- DeepL.document.translate_document('/path/to/spanish_document.pdf', '/path/to/translated_document.pdf', 'ES', 'EN')
1266
+ begin
1267
+ client.translate_document('/path/to/document.docx', '/path/to/translated.docx', 'EN', 'DE',
1268
+ timeout_s: 600, formality: 'more')
1269
+ rescue DeepL::Exceptions::DocumentTranslationError => e
1270
+ puts "Translation failed: #{e.message}, document: #{e.document_handle&.document_id}"
1271
+ end
741
1272
  ```
742
1273
 
743
- The lower level `upload`, `get_status` and `download` methods are also exposed, as well as the convenience method `wait_until_document_translation_finished` on the `DocumentHandle` object, which would replace `get_status`:
1274
+ The steps are also exposed. `translate_document_upload` returns a
1275
+ `DeepL::Resources::DocumentHandle` (`document_id`, `document_key`). To resume from a stored ID
1276
+ and key, create the handle with `DeepL::Resources::DocumentHandle.new(document_id, document_key)`.
1277
+ `translate_document_wait_until_done(handle, timeout_s: nil)` queries the status every 5 seconds
1278
+ until the translation is done and returns that status; it raises `DeepL::Exceptions::Error`
1279
+ with the API's error message if the translation fails, and when `timeout_s` expires. A status
1280
+ the library does not know keeps it polling, so pass `timeout_s` to bound the wait.
1281
+ `translate_document_get_status` queries the status once, and `translate_document_download`
1282
+ writes the translated document to a path that must not exist yet. Before the request it raises
1283
+ a `SystemCallError` if the output file exists (`Errno::EEXIST`) or its directory is missing or
1284
+ not writable (`Errno::ENOENT`, `Errno::EACCES`); it raises
1285
+ `DeepL::Exceptions::DocumentNotReadyError` if the translation is not done yet.
1286
+
744
1287
  ```rb
745
- doc_handle = DeepL.document.upload('/path/to/spanish_document.pdf', 'ES', 'EN')
746
- doc_status = doc_handle.wait_until_document_translation_finished # alternatively poll `DeepL.document.get_status`
747
- # until the `doc_status.successful?`
748
- DeepL.document.download(doc_handle, '/path/to/translated_document.pdf') unless doc_status.error?
1288
+ handle = client.translate_document_upload('/path/to/spanish_document.pdf', 'ES', 'EN',
1289
+ filename: 'report.pdf')
1290
+ status = client.translate_document_get_status(handle)
1291
+ puts "#{status.status}, ok: #{status.ok?}, done: #{status.done?}"
1292
+ # => translating, ok: true, done: false
1293
+ client.translate_document_wait_until_done(handle)
1294
+ client.translate_document_download(handle, '/path/to/translated_document.pdf')
749
1295
  ```
750
1296
 
1297
+ A `DeepL::Resources::DocumentTranslationStatus` has `document_id`, `status` (a string;
1298
+ `DeepL::Constants::DocumentStatusCode` has the values `QUEUED`, `TRANSLATING`, `DONE` and
1299
+ `ERROR`), `seconds_remaining`, `billed_characters` and `error_message`, and the predicates
1300
+ `done?` (done), `error?` (failed), `ok?` (not failed, also while queued or translating)
1301
+ and `finished?` (done or failed).
1302
+
751
1303
  You can also pass additional options to document translation methods, including `extra_body_parameters`:
752
1304
 
753
1305
  ```rb
754
- options = {
755
- formality: 'more',
756
- extra_body_parameters: { example_param: 'true' }
757
- }
758
- doc_handle = DeepL.document.upload('/path/to/spanish_document.pdf', 'ES', 'EN', nil, options)
1306
+ doc_handle = client.translate_document_upload('/path/to/spanish_document.pdf', 'ES', 'DE',
1307
+ formality: 'more',
1308
+ extra_body_parameters: { example_param: 'true' })
1309
+ ```
1310
+
1311
+ Document translation options include:
1312
+
1313
+ - `filename`: the file name sent with the upload, including its
1314
+ extension. Defaults to the base name of the input path.
1315
+ - `formality`: same as for text translation.
1316
+ - `glossary` / `glossary_ids`: see the glossary sections above.
1317
+ - `output_format`: file extension of the desired output format, e.g. `'pdf'` to translate
1318
+ a `docx` into a PDF.
1319
+ - `enable_watermark`: `true` adds a "Translated by DeepL" watermark to the translated
1320
+ document. The API supports it only for `docx` and `pdf` output and ignores it for other
1321
+ formats. When not set, the parameter is not sent.
1322
+ - `style_rule`, `style_profile`, `translation_memory`, `translation_memory_threshold`:
1323
+ same as in text translation; see the style rules, style profiles and translation memory
1324
+ sections above.
1325
+
1326
+ ```rb
1327
+ client.translate_document('/path/to/document.docx', '/path/to/translated.pdf', 'EN', 'DE',
1328
+ output_format: 'pdf', enable_watermark: true)
1329
+ ```
1330
+
1331
+ The `extra_body_parameters` option allows you to pass arbitrary parameters in the request body. This can be used to access beta features by adding new parameters, or to override built-in parameters (such as `target_lang`, `source_lang`, etc.) for testing purposes. In a document upload, a `nil` value removes the field from the form, the library's own field of that name included.
1332
+
1333
+ ### Admin API
1334
+
1335
+ The Admin API lets you manage the developer keys of your organization and retrieve usage analytics. It requires an admin API key, which you can create in the "Admin API Keys" tab of your DeepL account. Admin keys cannot be used for translation, and developer keys cannot access the Admin API: the API rejects a wrong key with `DeepL::Exceptions::AuthorizationFailed`.
1336
+
1337
+ Create a `DeepL::AdminClient` with your admin key. It reads no environment variables and uses the `https://api.deepl.com` server by default. The admin key is trimmed. It also accepts the `server_url:`, `headers:`, `max_retries:`, `timeout:`, `proxy:`, `send_platform_info:`, `app_info:`, `http_client_options:` and `logger:` keyword arguments of [`DeepL::Client`](#creating-a-client); without `server_url:` it uses `https://api.deepl.com`, also for keys ending in `:fx`.
1338
+
1339
+ ```rb
1340
+ admin_client = DeepL::AdminClient.new('YOUR_ADMIN_KEY')
759
1341
  ```
760
1342
 
761
- The `extra_body_parameters` option allows you to pass arbitrary parameters in the request body. This can be used to access beta features by adding new parameters, or to override built-in parameters (such as `target_lang`, `source_lang`, etc.) for testing purposes.
1343
+ #### Managing developer keys
1344
+
1345
+ ```rb
1346
+ key = admin_client.create_developer_key(label: 'Staging Team Key')
1347
+ puts "Created #{key.label} (#{key.key_id})"
1348
+
1349
+ admin_client.list_developer_keys.each do |developer_key|
1350
+ puts "#{developer_key.label}: deactivated=#{developer_key.deactivated?}"
1351
+ end
1352
+
1353
+ key = admin_client.rename_developer_key(key, 'Production Team Key')
1354
+
1355
+ # Changes only the given limits; the others keep their current value.
1356
+ # nil removes a limit (unlimited) and 0 blocks that usage.
1357
+ key = admin_client.set_developer_key_usage_limits(key, characters: 500_000,
1358
+ speech_to_text_milliseconds: 60_000)
1359
+ key = admin_client.set_developer_key_usage_limits(key, speech_to_speech_milliseconds: nil)
1360
+
1361
+ # Deactivation is permanent.
1362
+ admin_client.deactivate_developer_key(key)
1363
+ ```
1364
+
1365
+ `rename_developer_key`, `set_developer_key_usage_limits` and `deactivate_developer_key` accept either a key ID or a `DeepL::Resources::DeveloperKey` object and return the updated `DeepL::Resources::DeveloperKey`. `set_developer_key_usage_limits` accepts `characters:`, `speech_to_text_milliseconds:` and `speech_to_speech_milliseconds:`; any other keyword raises `ArgumentError` before a request is sent (send fields the library does not model with `extra_body_parameters:`). `create_developer_key` takes the label as the `label:` keyword argument; without it the API labels the key "DeepL API Key". Label and limit values are sent as given and validated by the API. `create_developer_key`, `deactivate_developer_key`, `rename_developer_key` and `set_developer_key_usage_limits` also accept `extra_body_parameters:`, a hash added to the request body last that replaces fields of the same name. A response without a `key_id` raises `DeepL::Exceptions::Error`. `label` and `usage_limits` are `nil` when the response does not contain them.
1366
+
1367
+ A failed `create_developer_key` request is retried only after HTTP 429 or a transient network failure while connecting, such as a DNS resolution error, a refused connection, an unreachable host or network, a connection timeout or a reset during the TLS or proxy handshake, when the API cannot have created the key, like the other requests of the library that create a resource. Other requests are retried like all other requests of the library.
1368
+
1369
+ #### Retrieving usage analytics
1370
+
1371
+ `get_usage_analytics` returns a `DeepL::Resources::AdminUsageReport` for a date range. Dates are UTC calendar days, and both the start day and the end day are included. They can be `Date`, `Time` or `DateTime` objects or `YYYY-MM-DD` strings. For `Time` and `DateTime` values the SDK sends the UTC date of that moment, so `Time.new(2026, 10, 20, 0, 0, 0, '+02:00')` is sent as `2026-10-19`. An invalid date raises `ArgumentError` without sending a request. The API requires the end date to be after the start date, so a report covers at least two days, and at most 366 days after it; otherwise both analytics methods raise `DeepL::Exceptions::BadRequest`. Use `group_by:` to break the usage down by key (`DeepL::Constants::AdminUsageGroupBy::KEY`, see `key_usages`) or by key and day (`DeepL::Constants::AdminUsageGroupBy::KEY_AND_DAY`, see `key_and_day_usages`). The `group_by` of the report is the raw string the API returns. The usage breakdowns include `speech_to_text_minutes` and `speech_to_speech_minutes`. `speech_to_speech_minutes` of a usage breakdown, and `total_usage`, `start_date` and `end_date` of a report, are `nil` when the response does not contain them.
1372
+
1373
+ ```rb
1374
+ report = admin_client.get_usage_analytics('2026-06-01', '2026-07-01',
1375
+ group_by: DeepL::Constants::AdminUsageGroupBy::KEY)
1376
+ puts "Total characters: #{report.total_usage&.total_characters}"
1377
+ report.key_usages.each do |key_usage|
1378
+ puts "#{key_usage.api_key_label}: #{key_usage.usage.total_characters}"
1379
+ end
1380
+ ```
1381
+
1382
+ `get_custom_tag_usage_analytics` returns a `DeepL::Resources::CustomTagUsageReport` with the usage per custom tag, for a date range with the same limits. Use `aggregate_by:` to choose between the whole period (`DeepL::Constants::CustomTagUsageAggregateBy::PERIOD`, the default) and per-day usage (`DeepL::Constants::CustomTagUsageAggregateBy::DAY`). The results are paginated: pass the `next_page` value of a report as `page:` to get the next page. The `aggregate_by` of a custom tag report is the raw string the API returns. `speech_to_speech_minutes` of a custom tag breakdown is `nil` when the response does not contain it.
1383
+
1384
+ ```rb
1385
+ page = nil
1386
+ loop do
1387
+ report = admin_client.get_custom_tag_usage_analytics('2026-06-01', '2026-07-01', page: page)
1388
+ report.usage.each do |tag_usage|
1389
+ puts "#{tag_usage.custom_tag}: #{tag_usage.breakdown.total_characters}"
1390
+ end
1391
+ break if report.next_page.nil?
1392
+
1393
+ page = report.next_page
1394
+ end
1395
+ ```
762
1396
 
763
1397
  ### Sending additional HTTP headers
764
1398
 
765
- You can pass additional HTTP headers to `translate`, `rephrase`, and the
766
- `document` methods. For example, to send the `X-DeepL-Reporting-Tag` header
1399
+ `DeepL::Client.new(key, headers: { 'X-DeepL-Reporting-Tag' => 'my-tag' })` sends the headers
1400
+ with every DeepL API request of that client, for example the `X-DeepL-Reporting-Tag` header
767
1401
  for usage reporting (see the [cookbook entry](https://developers.deepl.com/docs/learning-how-tos/cookbook/sending-custom-reporting-tags-from-client-libraries)):
768
1402
 
769
1403
  ```rb
770
- additional_headers = { 'X-DeepL-Reporting-Tag' => 'my-tag' }
771
- translation = DeepL.translate 'Hello, world!', 'EN', 'DE', {}, additional_headers
772
- rephrased = DeepL.rephrase 'Hello, world!', 'EN', nil, nil, {}, additional_headers
1404
+ client = DeepL::Client.new(auth_key, headers: { 'X-DeepL-Reporting-Tag' => 'my-tag' })
1405
+ translation = client.translate_text 'Hello, world!', 'EN', 'DE'
773
1406
  ```
774
1407
 
1408
+ A header in `headers:` replaces a library
1409
+ header of the same name, in any casing, `Authorization` and `User-Agent` included, except
1410
+ `Content-Type`, `Content-Length`, `Transfer-Encoding` and `Host`, which the library always sets.
1411
+ Pre-signed translation memory storage URLs get only the `User-Agent`, the caller's if one is
1412
+ set.
1413
+
775
1414
  ### Handle exceptions
776
1415
 
777
1416
  You can capture and process exceptions that may be raised during API calls. These are all the possible exceptions:
@@ -780,19 +1419,31 @@ You can capture and process exceptions that may be raised during API calls. Thes
780
1419
  | --------------- | ----------- |
781
1420
  | `DeepL::Exceptions::AuthorizationFailed` | The authorization process has failed. Check your `auth_key` value. |
782
1421
  | `DeepL::Exceptions::BadRequest` | Something is wrong in your request. Check `exception.message` for more information. |
783
- | `DeepL::Exceptions::DocumentTranslationError` | An error occured during document translation. Check `exception.message` for more information. |
1422
+ | `DeepL::Exceptions::ConnectionError` | No complete HTTP response from the API: a DNS, connection or timeout failure, or a response body cut off before its `Content-Length`, after all retries (`should_retry?` is true), or a TLS failure, a proxy failure (the proxy refuses `CONNECT`) or a malformed response, raised without retrying (`should_retry?` is false). Requests that create a resource retry fewer failures, see [Retries and timeouts](#retries-and-timeouts). The original exception is `exception.cause`. |
1423
+ | `DeepL::Exceptions::DocumentNotReadyError` | A subclass of `ServerError`: HTTP 503 on a document download, the translated document is not ready yet. |
1424
+ | `DeepL::Exceptions::DocumentTranslationError` | An error occured during document translation. Check `exception.message` for more information; `exception.document_handle` is the handle of the uploaded document, `nil` if the upload failed; `http_status_code` and `should_retry?` are those of the DeepL error that caused it, if any. |
1425
+ | `DeepL::Exceptions::TranslationMemoryJobError` | Any failure of `import_translation_memory_from_filepath` or `export_translation_memory_to_filepath` except a missing input file. `exception.job_id` is the ID of the job once it was created, `nil` before; `exception.job` is the last `TranslationMemoryJob` status fetched, `nil` before the first status check; `exception.cause` is the original error, and `http_status_code` and `should_retry?` are those of a DeepL error cause. |
784
1426
  | `DeepL::Exceptions::LimitExceeded` | You've reached the API's call limit. |
785
1427
  | `DeepL::Exceptions::QuotaExceeded` | You've reached the API's character limit. |
786
- | `DeepL::Exceptions::RequestError` | An unkown request error. Check `exception.response` and `exception.request` for more information. |
787
- | `DeepL::Exceptions::NotSupported` | The requested method or API endpoint is not supported. |
1428
+ | `DeepL::Exceptions::RequestError` | Any other HTTP error status. Its message contains the status and the API's message; check `exception.response` and `exception.request` for more information. |
788
1429
  | `DeepL::Exceptions::RequestEntityTooLarge` | Your request is too large, reduce the amount of data you are sending. The API has a request size limit of 128 KiB. |
789
- | `DeepL::Exceptions::ServerError` | An error occured in the DeepL API, wait a short amount of time and retry. |
1430
+ | `DeepL::Exceptions::ServerError` | An error occured in the DeepL API (HTTP 5xx), raised after all retries. |
1431
+
1432
+ All of them are subclasses of `DeepL::Exceptions::Error`, which is also raised for a response
1433
+ that cannot be parsed. An invalid argument raises `ArgumentError` before any request is sent;
1434
+ for an invalid glossary or spoken terms term it is the subclass
1435
+ `DeepL::Exceptions::ValidationError`. A method that writes a file raises a `SystemCallError`
1436
+ (`Errno::*`) for an output path it cannot use, where its documentation says so. Errors of an
1437
+ HTTP response carry the status as an `Integer` in
1438
+ `exception.http_status_code` (`nil` otherwise), and their message ends with the API's error
1439
+ message when the response has one, for example `Quota exceeded. The character limit has been
1440
+ reached: <API message>`.
790
1441
 
791
1442
  An exampling of handling a generic exception:
792
1443
 
793
1444
  ```rb
794
- def my_method
795
- item = DeepL.translate 'This is my text', nil, 'ES'
1445
+ def my_method(client)
1446
+ item = client.translate_text 'This is my text', nil, 'ES'
796
1447
  rescue DeepL::Exceptions::RequestError => e
797
1448
  puts 'Oops!'
798
1449
  puts "Code: #{e.response.code}"
@@ -803,7 +1454,7 @@ end
803
1454
 
804
1455
  ### Logging
805
1456
 
806
- To enable logging, pass a suitable logging object (e.g. the default `Logger` from the Ruby standard library) when configuring the library. The library logs HTTP requests to `INFO` and debug information to `DEBUG`. Example:
1457
+ To enable logging, pass a suitable logging object (e.g. the default `Logger` from the Ruby standard library) as the `logger:` of the client. The library logs HTTP requests to `INFO` and debug information to `DEBUG`. Example:
807
1458
 
808
1459
  ```rb
809
1460
  require 'logger'
@@ -811,64 +1462,74 @@ require 'logger'
811
1462
  logger = Logger.new(STDOUT)
812
1463
  logger.level = Logger::INFO
813
1464
 
814
- deepl.configure do |config|
815
- config.auth_key = configuration.auth_key
816
- config.logger = logger
817
- end
1465
+ client = DeepL::Client.new(ENV.fetch('DEEPL_AUTH_KEY'), logger: logger)
818
1466
  ```
819
1467
 
1468
+ ### Retries and timeouts
1469
+
1470
+ Requests that fail with HTTP 429, any 5xx status or a transient network failure (DNS, refused
1471
+ or reset connection, broken pipe, unreachable host, timeout, response body cut off before its
1472
+ `Content-Length`) are retried up to `max_retries:`
1473
+ times (default 5) with exponential backoff; a request is sent at most `max_retries:` + 1 times.
1474
+ Each attempt has a timeout of `timeout:` seconds (default 10). After the last retry, network
1475
+ failures raise `DeepL::Exceptions::ConnectionError`. TLS failures (including certificate
1476
+ verification), proxy failures (the proxy refuses `CONNECT`, e.g. with 407) and malformed
1477
+ responses are not retried and are raised the same way at once.
1478
+ Requests that create a resource are only retried when the request was not sent (HTTP 429, or a
1479
+ transient network failure while connecting, before any request byte is written: DNS failure, refused
1480
+ connection, unreachable host or network, connection timeout, a reset during the TLS or proxy
1481
+ handshake), so that a retry cannot create a second resource: `create_glossary`,
1482
+ `create_glossary_from_csv`, `create_multilingual_glossary`, `create_multilingual_glossary_from_csv`,
1483
+ `create_spoken_terms`, `create_style_rule`, `create_style_rule_custom_instruction`,
1484
+ `create_style_profile`, the document upload of `translate_document` and `translate_document_upload`,
1485
+ the translation memory import and export job creation, and `AdminClient#create_developer_key`. Their
1486
+ other failures are raised at once: a 5xx reply as `DeepL::Exceptions::ServerError` and a network
1487
+ failure as `DeepL::Exceptions::ConnectionError`, both with `should_retry?` false for a failure before
1488
+ the response. A response cut off mid-body, after its headers arrived, is not retried either, but its
1489
+ `DeepL::Exceptions::ConnectionError` has `should_retry?` true, whatever the network failure.
1490
+
820
1491
  ### Proxy configuration
821
1492
 
822
- To use HTTP proxies, a session needs to be used. The proxy can then be configured as part of the HTTP client options:
1493
+ Pass a proxy to the client as a URL string, a `URI`, or a hash with `proxy_addr` and
1494
+ `proxy_port` (string or symbol keys, both required):
823
1495
 
824
1496
  ```rb
825
- client_options = HTTPClientOptions.new({ 'proxy_addr' => 'http://localhost', 'proxy_port' => 80 })
826
- deepl.with_session(client_options) do |session|
827
- # ...
828
- end
1497
+ client = DeepL::Client.new(auth_key, proxy: 'http://user:password@localhost:3128')
1498
+ client = DeepL::Client.new(auth_key, proxy: URI('http://localhost:3128'))
1499
+ client = DeepL::Client.new(auth_key, proxy: { proxy_addr: 'localhost', proxy_port: 3128 })
829
1500
  ```
830
1501
 
831
- ### Anonymous platform information
832
-
833
- By default, we send some basic information about the platform the client library is running on with each request, see [here for an explanation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent). This data is completely anonymous and only used to improve our product, not track any individual users. If you do not wish to send this data, you can opt-out by setting the `send_platform_info` flag in the configuration to `false` like so:
834
-
835
- ```rb
836
- deepl.configure({}, nil, nil, false) do |config|
837
- # ...
838
- end
839
- ```
1502
+ The URL scheme must be `http` or `https`; any other scheme raises `ArgumentError`. With an
1503
+ `https` proxy URL the connection to the proxy uses TLS. This needs net-http 0.5.0 or later
1504
+ (bundled from Ruby 3.4; on older Rubies add `gem 'net-http', '>= 0.5'`) and an `https` server
1505
+ URL; otherwise `ArgumentError` is raised. Net::HTTP does not verify the proxy's certificate. The
1506
+ hash form is always a plain HTTP proxy.
840
1507
 
841
- You can also complete customize the `User-Agent` header like so:
1508
+ Any other value, such as a hash with only one of the two keys or a blank `proxy_addr`, a URL with an
1509
+ empty host (`http://`, `http://:8080`) or a URL with another scheme, raises `ArgumentError`. `DeepL::HTTPClientOptions` takes the proxy in the same forms, together with
1510
+ certificate, SSL verification and timeout options, given as `http_client_options:`:
842
1511
 
843
1512
  ```rb
844
- deepl.configure do |config|
845
- config.user_agent = 'myCustomUserAgent'
846
- end
1513
+ options = DeepL::HTTPClientOptions.new({ 'proxy_addr' => 'localhost', 'proxy_port' => 3128 })
1514
+ client = DeepL::Client.new(auth_key, http_client_options: options)
847
1515
  ```
848
1516
 
849
- ### Sending multiple requests
1517
+ ### Anonymous platform information
850
1518
 
851
- When writing an application that send multiple requests, using a HTTP session will give better performance through [HTTP Keep-Alive](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive). You can use it by simply wrapping your requests in a `with_session` block:
1519
+ By default, we send some basic information about the platform the client library is running on with each request, see [here for an explanation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent). This data is completely anonymous and only used to improve our product, not track any individual users. If you do not wish to send this data, create the client with `send_platform_info: false`.
852
1520
 
853
- ```rb
854
- deepl.with_session do |session|
855
- deepl.translate(sentence1, 'DE', 'EN-GB')
856
- deepl.translate(sentence2, 'DE', 'EN-GB')
857
- deepl.translate(sentence3, 'DE', 'EN-GB')
858
- end
859
- ```
1521
+ You can also completely replace the `User-Agent` header with `headers: { 'User-Agent' => 'myCustomUserAgent' }`.
860
1522
 
861
1523
  ### Writing a plugin
862
1524
 
863
1525
  If you use this library in an application, please identify the application by setting the name and version of the plugin:
864
1526
 
865
1527
  ```rb
866
- deepl.configure({}, 'MyTranslationPlugin', '1.0.1') do |config|
867
- # ...
868
- end
1528
+ client = DeepL::Client.new(auth_key, app_info: { app_name: 'MyTranslationPlugin',
1529
+ app_version: '1.0.1' })
869
1530
  ```
870
1531
 
871
- This information is passed along when the library makes calls to the DeepL API. Both name and version are required. Please note that setting the `User-Agent` header via `deepl.configure` will override this setting, if you need to use this, please manually identify your Application in the `User-Agent` header.
1532
+ This information is passed along when the library makes calls to the DeepL API. Both name and version are required. Please note that a `User-Agent` in `headers:` overrides this setting; if you set one, identify your application in it yourself.
872
1533
 
873
1534
  ## Options Constants
874
1535
 
@@ -884,33 +1545,28 @@ The available values for various possible options are provided under the `DeepL:
884
1545
  To view all the possible options for a given constant, call `options`:
885
1546
 
886
1547
  ```rb
887
- all_available_tones = DeepL::Constants::Tones.options
1548
+ all_available_tones = DeepL::Constants::Tone.options
888
1549
  ```
889
1550
 
890
1551
  To check if a given string is a possible option for a given constant, call `valid?`:
891
1552
 
892
1553
  ```rb
893
- DeepL::Constants::Tones.valid?('friendly') # true
894
- DeepL::Constants::Tones.valid?('rude') # false
1554
+ DeepL::Constants::Tone.valid?('friendly') # true
1555
+ DeepL::Constants::Tone.valid?('rude') # false
895
1556
  ```
896
1557
 
897
1558
  ## Integrations
898
1559
 
899
1560
  ### Ruby on Rails
900
1561
 
901
- You may use this gem as a standalone service by creating an initializer on your
902
- `config/initializers` folder with your DeepL configuration. For example:
1562
+ You may create one client in an initializer on your `config/initializers` folder and use it
1563
+ anywhere in your code (controllers, models, views, jobs, plain ruby objects…). For example:
903
1564
 
904
1565
  ```rb
905
1566
  # config/initializers/deepl.rb
906
- DeepL.configure do |config|
907
- # Your configuration goes here
908
- end
1567
+ DEEPL_CLIENT = DeepL::Client.new(Rails.application.credentials.deepl_auth_key)
909
1568
  ```
910
1569
 
911
- Since the DeepL service is defined globally, you can use service anywhere in your code
912
- (controllers, models, views, jobs, plain ruby objects… you name it).
913
-
914
1570
  ### i18n-tasks
915
1571
 
916
1572
  You may also take a look at [`i18n-tasks`](https://github.com/glebm/i18n-tasks), which is a gem
@@ -927,7 +1583,25 @@ cd deepl-rb
927
1583
  bundle install
928
1584
  ```
929
1585
 
930
- To run tests (rspec and rubocop), use
1586
+ There are two suites of specs, which must run in separate processes:
1587
+
1588
+ - `spec/offline` tests options, validation, errors, retries and polling against intercepted
1589
+ requests (WebMock). It needs no key and no network:
1590
+
1591
+ ```
1592
+ bundle exec rspec spec/offline
1593
+ ```
1594
+
1595
+ - `spec/real_api` sends every endpoint once to the real API. Set `DEEPL_AUTH_KEY` to a test key,
1596
+ `DEEPL_ADMIN_KEY` to an admin key for the Admin API specs, and `DEEPL_SERVER_URL` if the keys
1597
+ are not for the default server. The specs create resources named `sdktest-ruby-...` and delete
1598
+ them again; developer keys cannot be deleted and are deactivated instead. The Admin API spec creates a key, renames it, sets its limits and deactivates it:
1599
+
1600
+ ```
1601
+ DEEPL_AUTH_KEY=... DEEPL_ADMIN_KEY=... bundle exec rspec spec/real_api
1602
+ ```
1603
+
1604
+ To run the offline specs and rubocop, use
931
1605
 
932
1606
  ```
933
1607
  bundle exec rake test