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
@@ -0,0 +1,1284 @@
1
+ # Copyright 2026 DeepL SE (https://www.deepl.com)
2
+ # Use of this source code is governed by an MIT
3
+ # license that can be found in the LICENSE.md file.
4
+ # frozen_string_literal: true
5
+
6
+ module DeepL
7
+ ##
8
+ # Client for the DeepL API. Every client owns its configuration and HTTP connection: two
9
+ # clients never share options, and nothing is read from environment variables.
10
+ #
11
+ # client = DeepL::Client.new(ENV.fetch('DEEPL_AUTH_KEY'), app_info: { app_name: 'my-app',
12
+ # app_version: '1.2.3' })
13
+ #
14
+ # All methods may raise a +DeepL::Exceptions::Error+ or a subclass.
15
+ class Client # rubocop:disable Metrics/ClassLength
16
+ DEEPL_SERVER_URL = 'https://api.deepl.com'
17
+ DEEPL_SERVER_URL_FREE = 'https://api-free.deepl.com'
18
+ private_constant :DEEPL_SERVER_URL, :DEEPL_SERVER_URL_FREE
19
+
20
+ ##
21
+ # Returns true if +auth_key+ is a DeepL API Free key (it ends with +:fx+).
22
+ #
23
+ # @param [String, nil] auth_key Authentication key.
24
+ # @return [Boolean]
25
+ def self.free_account_auth_key?(auth_key)
26
+ auth_key.to_s.strip.end_with?(':fx')
27
+ end
28
+
29
+ ##
30
+ # A keyword argument given as +nil+ takes its default, like an omitted one.
31
+ # @param [String] auth_key Authentication key, surrounding whitespace is removed.
32
+ # @param [String, nil] server_url Base URL of the DeepL API, an absolute +http+ or +https+
33
+ # URL with a host; a port and a path prefix are kept, trailing slashes are removed.
34
+ # Defaults to +https://api-free.deepl.com+ for Free keys (ending in +:fx+), else
35
+ # +https://api.deepl.com+.
36
+ # @param [Hash] headers HTTP headers sent with every DeepL API request (pre-signed storage
37
+ # URLs get only a +User-Agent+). A header of the same name in any casing replaces the
38
+ # library's, +Authorization+ and +User-Agent+ included, except the technical headers
39
+ # +Content-Type+, +Content-Length+, +Transfer-Encoding+ and +Host+.
40
+ # @param [Integer, nil] max_retries Number of retries after the first attempt, for HTTP 429, any
41
+ # 5xx and transient network failures (not TLS failures or malformed responses). Requests that
42
+ # create a resource (glossaries, spoken terms, style rule lists and custom instructions, style
43
+ # profiles, document uploads, translation memory import and export jobs) are retried only
44
+ # after HTTP 429 and transient network failures while connecting, such as DNS resolution
45
+ # errors, refused connections, unreachable hosts or networks, connection timeouts and resets
46
+ # during the TLS or proxy handshake, when the request was not processed.
47
+ # @param [Numeric, nil] timeout Timeout of each attempt in seconds, applied to opening the
48
+ # connection, reading and writing. A longer backoff interval takes precedence.
49
+ # @param [String, URI, Hash, nil] proxy Proxy URL (+http+ or +https+ scheme) as a String or
50
+ # +URI+, e.g. +http://user:password@proxy.example:8080+, or a hash with +proxy_addr+ and
51
+ # +proxy_port+ (string or symbol keys, both required), which is a plain HTTP proxy. An
52
+ # +https+ proxy is connected to over TLS and needs net-http 0.5.0 or later (bundled from
53
+ # Ruby 3.4) and an +https+ server URL.
54
+ # @param [Boolean, nil] send_platform_info Whether to add the OS and Ruby versions to the
55
+ # +User-Agent+.
56
+ # @param [DeepL::AppInfo, Hash, nil] app_info Your application's +app_name+ and
57
+ # +app_version+, added to the +User-Agent+.
58
+ # @param [DeepL::HTTPClientOptions, nil] http_client_options Proxy, certificate, SSL
59
+ # verification and per-phase timeouts. Its timeouts take precedence over +timeout+.
60
+ # @param [Logger, nil] logger Logger for requests and retries.
61
+ # @raise [ArgumentError] If +auth_key+ is empty, +server_url+ is not an absolute +http+ or
62
+ # +https+ URL with a host, or +proxy+ is not a valid proxy URL, +URI+ or proxy hash (an empty
63
+ # host or blank +proxy_addr+ is not valid), has a proxy URL scheme other than +http+ or
64
+ # +https+, or is an +https+ proxy that cannot be used (see +proxy+).
65
+ def initialize(auth_key, server_url: nil, headers: {}, max_retries: 5, timeout: 10, # rubocop:disable Metrics/ParameterLists
66
+ proxy: nil, send_platform_info: true, app_info: nil, http_client_options: nil,
67
+ logger: nil)
68
+ free = self.class.free_account_auth_key?(auth_key)
69
+ default_server_url = free ? DEEPL_SERVER_URL_FREE : DEEPL_SERVER_URL
70
+ @api = Utils::ClientBuilder.build_api(
71
+ auth_key, key_name: 'auth_key', server_url: server_url,
72
+ default_server_url: default_server_url, headers: headers,
73
+ max_retries: max_retries, timeout: timeout, proxy: proxy,
74
+ send_platform_info: send_platform_info, app_info: app_info,
75
+ http_client_options: http_client_options, logger: logger
76
+ )
77
+ end
78
+
79
+ ##
80
+ # Translates +text+ from +source_lang+ into +target_lang+. Always requests the billed
81
+ # characters; options set to +nil+ are not sent.
82
+ #
83
+ # @param [String, Array<String>] text Text or texts to translate.
84
+ # @param [String, nil] source_lang Source language, +nil+ to detect it.
85
+ # @param [String] target_lang Target language.
86
+ # @param [Hash] options Translation options. Any other option raises ArgumentError before a
87
+ # request is sent:
88
+ # * +:glossary+ - A glossary ID, `DeepL::Resources::Glossary` or
89
+ # `DeepL::Resources::MultilingualGlossary`, sent as +glossary_id+.
90
+ # * +:glossary_ids+ - Up to 5 glossaries (IDs or objects). Cannot be combined with
91
+ # +:glossary+. Without +source_lang+, the API detects it.
92
+ # * +:style_rule+, +:style_profile+, +:translation_memory+ - An ID or the resource object.
93
+ # +nil+ leaves it unset.
94
+ # * +:split_sentences+ - +true+/+false+ are sent as +'1'+/+'0'+.
95
+ # * +:custom_instructions+ - An array of instructions; a string is one instruction.
96
+ # * +:extra_body_parameters+ - A hash added to the request body last; replaces fields of
97
+ # the same name.
98
+ # * +:formality+, +:context+, +:tag_handling+, +:tag_handling_version+, +:model_type+,
99
+ # +:preserve_formatting+, +:outline_detection+, +:splitting_tags+, +:non_splitting_tags+,
100
+ # +:ignore_tags+ - Sent unchanged.
101
+ # * +:translation_memory_threshold+ - Integer 0-100. Requires +:translation_memory+.
102
+ # @return [DeepL::Resources::Text, Array<DeepL::Resources::Text>] One result for a string,
103
+ # an array for an array (also for a one-element array).
104
+ # @raise [ArgumentError] If +text+ is empty or contains an empty string, +target_lang+ or a
105
+ # given +source_lang+ is empty, an option is unknown, the glossary options are combined or
106
+ # more than 5 are given, +:glossary+, +:style_rule+, +:style_profile+, +:translation_memory+
107
+ # or an entry of +:glossary_ids+ is an empty ID or a resource object without its ID, or
108
+ # +:translation_memory_threshold+ is set without +:translation_memory+ or is not from 0 to
109
+ # 100; nothing is sent.
110
+ def translate_text(text, source_lang, target_lang, **options)
111
+ Requests::Translate.new(api, text, source_lang, target_lang, options).request
112
+ end
113
+
114
+ ##
115
+ # Translates the document at +input_path+ and writes the result to +output_path+: uploads
116
+ # it, waits until the translation is done and downloads it.
117
+ #
118
+ # The upload is retried only after failures that show the request was not processed (HTTP 429
119
+ # and transient network failures while connecting, such as DNS resolution errors, refused
120
+ # connections, unreachable hosts or networks, connection timeouts and resets during the TLS or
121
+ # proxy handshake), so that a retry cannot create a second document.
122
+ #
123
+ # @param [String] input_path Path of the document to translate.
124
+ # @param [String] output_path Path to write the translated document to. Must not exist.
125
+ # @param [String, nil] source_lang Source language, +nil+ to detect it.
126
+ # @param [String] target_lang Target language.
127
+ # @param [Numeric, nil] timeout_s Maximum time in seconds to wait for the translation after
128
+ # the upload, +nil+ to wait until it is done.
129
+ # @param [Hash] options The options of #translate_document_upload, including +:filename+.
130
+ # @return [DeepL::Resources::DocumentTranslationStatus] The final status, +done+.
131
+ # @raise [ArgumentError] If +input_path+ does not exist; nothing is uploaded.
132
+ # @raise [DeepL::Exceptions::DocumentTranslationError] For any other failure: an existing
133
+ # +output_path+ (the file is kept) or one whose directory is missing or not writable, both
134
+ # checked before the upload; an argument error of #translate_document_upload, such as an
135
+ # unknown option, raised before anything is sent; a failed translation or an expired
136
+ # +timeout_s+. Its +document_handle+ is set once the upload succeeded, so the
137
+ # document can still be queried and downloaded. +http_status_code+ and +should_retry?+ are
138
+ # those of the DeepL error that caused it, if any.
139
+ def translate_document(input_path, output_path, source_lang, target_lang, timeout_s: nil, # rubocop:disable Metrics/MethodLength
140
+ **options)
141
+ raise ArgumentError, "Input file does not exist: #{input_path}" unless File.exist?(input_path)
142
+
143
+ check_document_output_path(output_path)
144
+ handle = nil
145
+ begin
146
+ handle = translate_document_upload(input_path, source_lang, target_lang, **options)
147
+ status = translate_document_wait_until_done(handle, timeout_s: timeout_s)
148
+ translate_document_download(handle, output_path)
149
+ status
150
+ rescue StandardError => e
151
+ FileUtils.rm_f(output_path)
152
+ raise Exceptions::DocumentTranslationError.new(
153
+ "Error occurred during document translation: #{e.message}", handle, e
154
+ )
155
+ end
156
+ end
157
+
158
+ ##
159
+ # Uploads the document at +input_path+ for translation. Options set to +nil+ are not sent.
160
+ #
161
+ # The upload is retried only after failures that show the request was not processed (HTTP 429
162
+ # and transient network failures while connecting, such as DNS resolution errors, refused
163
+ # connections, unreachable hosts or networks, connection timeouts and resets during the TLS or
164
+ # proxy handshake), so that a retry cannot create a second document.
165
+ #
166
+ # @param [String] input_path Path of the document to translate.
167
+ # @param [String, nil] source_lang Source language, +nil+ to detect it.
168
+ # @param [String] target_lang Target language.
169
+ # @param [Hash] options Document translation options. Any other option raises ArgumentError
170
+ # before a request is sent:
171
+ # * +:filename+ - File name sent with the upload, including its extension. Defaults to the
172
+ # base name of +input_path+.
173
+ # * +:formality+, +:output_format+ - Sent unchanged.
174
+ # * +:enable_watermark+ - +true+ or +false+.
175
+ # * +:glossary+ - A glossary ID, `DeepL::Resources::Glossary` or
176
+ # `DeepL::Resources::MultilingualGlossary`, sent as +glossary_id+. Requires +source_lang+.
177
+ # * +:glossary_ids+ - Up to 5 glossaries (IDs or objects). Requires +source_lang+ and
178
+ # cannot be combined with +:glossary+.
179
+ # * +:style_rule+, +:style_profile+, +:translation_memory+ - An ID or the resource object.
180
+ # +nil+ leaves it unset.
181
+ # * +:translation_memory_threshold+ - Integer 0-100. Requires +:translation_memory+.
182
+ # * +:extra_body_parameters+ - A hash added to the form last; replaces fields of the same
183
+ # name. A +nil+ value removes the field, the library's own field of that name included.
184
+ # @return [DeepL::Resources::DocumentHandle] Handle of the uploaded document.
185
+ # @raise [ArgumentError] If +input_path+ does not exist, +target_lang+ or a given +source_lang+
186
+ # is empty, an option is unknown, +:glossary+ or +:glossary_ids+ is set without +source_lang+,
187
+ # the glossary options are combined or more than 5 are given, +:glossary+, +:style_rule+,
188
+ # +:style_profile+, +:translation_memory+ or an entry of +:glossary_ids+ is an empty ID or a
189
+ # resource object without its ID, or +:translation_memory_threshold+ is set without
190
+ # +:translation_memory+ or is not from 0 to 100; nothing is uploaded.
191
+ # @raise [SystemCallError] If +input_path+ cannot be read, e.g. +Errno::EISDIR+ for a directory
192
+ # or +Errno::EACCES+; nothing is uploaded.
193
+ def translate_document_upload(input_path, source_lang, target_lang, **options)
194
+ raise ArgumentError, "Input file does not exist: #{input_path}" unless File.exist?(input_path)
195
+ raise Errno::EISDIR, input_path if File.directory?(input_path)
196
+
197
+ filename = options.delete(:filename)
198
+ Requests::Document::Upload.new(api, input_path, source_lang, target_lang, filename,
199
+ options).request
200
+ end
201
+
202
+ ##
203
+ # Queries the status of a document translation once.
204
+ #
205
+ # @param [DeepL::Resources::DocumentHandle] handle Handle returned by the upload.
206
+ # @return [DeepL::Resources::DocumentTranslationStatus]
207
+ def translate_document_get_status(handle)
208
+ Requests::Document::GetStatus.new(api, handle.document_id, handle.document_key).request
209
+ end
210
+
211
+ ##
212
+ # Polls the status of a document translation every 5 seconds until it is done.
213
+ #
214
+ # @param [DeepL::Resources::DocumentHandle] handle Handle returned by the upload.
215
+ # @param [Numeric, nil] timeout_s Maximum time to wait in seconds, +nil+ to wait until the
216
+ # translation is done or failed.
217
+ # @return [DeepL::Resources::DocumentTranslationStatus] The final status, +done+.
218
+ # @raise [DeepL::Exceptions::Error] If the translation fails (with the API's error message)
219
+ # or +timeout_s+ expires.
220
+ def translate_document_wait_until_done(handle, timeout_s: nil)
221
+ Utils::DocumentPoller.wait_until_done(api, handle, timeout_s: timeout_s)
222
+ end
223
+
224
+ ##
225
+ # Downloads the translated document to +output_path+.
226
+ #
227
+ # @param [DeepL::Resources::DocumentHandle] handle Handle returned by the upload.
228
+ # @param [String] output_path Path to write the translated document to. Must not exist.
229
+ # @return [nil]
230
+ # @raise [SystemCallError] Before the request: +Errno::EEXIST+ if +output_path+ exists,
231
+ # +Errno::ENOENT+ if its directory does not exist, +Errno::EACCES+ if the directory is not
232
+ # writable.
233
+ # @raise [DeepL::Exceptions::DocumentNotReadyError] If the translation is not done yet.
234
+ def translate_document_download(handle, output_path)
235
+ Utils::OutputPath.check!(output_path)
236
+ Requests::Document::Download.new(api, handle.document_id, handle.document_key,
237
+ output_path).request
238
+ nil
239
+ end
240
+
241
+ ##
242
+ # Rephrases +text+, optionally into another variant or language and with a writing style
243
+ # or tone. Options set to +nil+ are not sent.
244
+ #
245
+ # @param [String, Array<String>] text Text or texts to rephrase.
246
+ # @param [String, nil] target_lang Target language, +nil+ to keep the language of the text.
247
+ # @param [String, nil] writing_style Writing style, see +DeepL::Constants::WritingStyle+.
248
+ # Cannot be combined with +tone+.
249
+ # @param [String, nil] tone Tone, see +DeepL::Constants::Tone+.
250
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last;
251
+ # replaces fields of the same name. Any other option raises ArgumentError.
252
+ # @return [DeepL::Resources::Text, Array<DeepL::Resources::Text>] One result for a string,
253
+ # an array for an array (also for a one-element array).
254
+ # @raise [ArgumentError] If +text+ is empty or contains an empty string, +target_lang+ is an
255
+ # empty string, or an option is unknown; nothing is sent.
256
+ # @raise [DeepL::Exceptions::Error] If the response has fewer improvements than texts.
257
+ def rephrase_text(text, target_lang = nil, writing_style: nil, tone: nil, **options)
258
+ Requests::Rephrase.new(api, text, target_lang, writing_style, tone, options).request
259
+ end
260
+
261
+ ##
262
+ # Corrects the grammar, spelling and punctuation of +text+. Options set to +nil+ are not
263
+ # sent.
264
+ #
265
+ # @param [String, Array<String>] text Text or texts to correct.
266
+ # @param [String, nil] target_lang Target language, +nil+ to keep the language of the text.
267
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last;
268
+ # replaces fields of the same name. Any other option raises ArgumentError.
269
+ # @return [DeepL::Resources::Text, Array<DeepL::Resources::Text>] One result for a string,
270
+ # an array for an array (also for a one-element array).
271
+ # @raise [ArgumentError] If +text+ is empty or contains an empty string, or +target_lang+ is
272
+ # an empty string; nothing is sent.
273
+ # @raise [DeepL::Exceptions::Error] If the response has fewer improvements than texts.
274
+ def correct_text(text, target_lang = nil, **options)
275
+ Requests::Correct.new(api, text, target_lang, options).request
276
+ end
277
+
278
+ ##
279
+ # Retrieves the languages that can be translated from, with upper-case codes (+EN+, +DE+).
280
+ #
281
+ # @return [Array<DeepL::Resources::Language>] The source languages;
282
+ # +supports_formality?+ is +nil+ for each.
283
+ def get_source_languages # rubocop:disable Naming/AccessorMethodName
284
+ Requests::Languages.new(api, :source).request
285
+ end
286
+
287
+ ##
288
+ # Retrieves the languages that can be translated into, with upper-case codes (+EN-GB+, +DE+).
289
+ #
290
+ # @return [Array<DeepL::Resources::Language>] The target languages, each with
291
+ # +supports_formality?+ set to +true+ or +false+.
292
+ def get_target_languages # rubocop:disable Naming/AccessorMethodName
293
+ Requests::Languages.new(api, :target).request
294
+ end
295
+
296
+ ##
297
+ # Retrieves the resources supported by the DeepL API with their features, and whether each
298
+ # feature requires support from the source and/or target language.
299
+ #
300
+ # @return [Array<DeepL::Resources::LanguageResource>] One entry per resource.
301
+ def get_language_resources # rubocop:disable Naming/AccessorMethodName
302
+ Requests::LanguageResources.new(api).request
303
+ end
304
+
305
+ ##
306
+ # Retrieves the languages supported by +resource+, each with its per-feature support. The
307
+ # language codes are returned as the API sends them.
308
+ #
309
+ # @param [String, Symbol] resource Resource to query, see
310
+ # +DeepL::Constants::LanguageResourceName+. Other values are sent unchanged.
311
+ # @param [String, Array<String>, nil] include Also return beta languages and features or
312
+ # features relying on third-party providers, see +DeepL::Constants::LanguageInclude+. Sent
313
+ # as one +include+ query parameter per value; +nil+ sends none, which returns stable
314
+ # languages and features only.
315
+ # @return [Array<DeepL::Resources::LanguageSupport>] The supported languages.
316
+ # @raise [ArgumentError] If +resource+ is empty.
317
+ def get_languages_for_resource(resource, include: nil)
318
+ Requests::LanguagesForResource.new(api, resource, { include: include }.compact).request
319
+ end
320
+
321
+ ##
322
+ # Retrieves the usage and limits of the account and, for API Pro, of this API key.
323
+ #
324
+ # @return [DeepL::Resources::Usage] Usage per type; a type absent from the response is +nil+.
325
+ def get_usage # rubocop:disable Naming/AccessorMethodName
326
+ Requests::Usage.new(api).request
327
+ end
328
+
329
+ ##
330
+ # Creates a v2 glossary for one language pair. Glossaries are not regional, so a regional
331
+ # variant is sent as its base language (+EN-GB+ as +EN+).
332
+ #
333
+ # Creation is retried only after failures that show the request was not processed (HTTP 429 and
334
+ # transient network failures while connecting, such as DNS resolution errors, refused
335
+ # connections, unreachable hosts or networks, connection timeouts and resets during the TLS or
336
+ # proxy handshake), so that a retry cannot create a second glossary.
337
+ #
338
+ # @param [String] name Name of the glossary.
339
+ # @param [String] source_lang Source language.
340
+ # @param [String] target_lang Target language.
341
+ # @param [Hash, Array<Array(String, String)>, String] entries Source term to target term, as a
342
+ # hash, source/target pairs or a TSV string. Sent as TSV.
343
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
344
+ # @return [DeepL::Resources::Glossary] The created glossary.
345
+ # @raise [ArgumentError] If +name+ or +entries+ is empty.
346
+ # @raise [DeepL::Exceptions::ValidationError] (an ArgumentError) If a term is empty after
347
+ # stripping surrounding whitespace or contains a control character, a TSV line is not exactly
348
+ # two terms, or a source term appears twice.
349
+ def create_glossary(name, source_lang, target_lang, entries, **options)
350
+ raise ArgumentError, 'Glossary entries must not be empty' if entries.nil? || entries.empty?
351
+
352
+ tsv = Utils::GlossaryEntries.to_tsv(entries)
353
+ Requests::Glossary::Create.new(api, name, source_lang, target_lang, tsv, 'tsv',
354
+ options).request
355
+ end
356
+
357
+ ##
358
+ # Creates a v2 glossary from CSV content, for example a file downloaded from the DeepL
359
+ # website.
360
+ #
361
+ # Creation is retried only after failures that show the request was not processed (HTTP 429 and
362
+ # transient network failures while connecting, such as DNS resolution errors, refused
363
+ # connections, unreachable hosts or networks, connection timeouts and resets during the TLS or
364
+ # proxy handshake), so that a retry cannot create a second glossary.
365
+ #
366
+ # @param [String] name Name of the glossary.
367
+ # @param [String] source_lang Source language.
368
+ # @param [String] target_lang Target language.
369
+ # @param [String, IO] csv CSV content, or an IO to read it from. Sent as given.
370
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
371
+ # @return [DeepL::Resources::Glossary] The created glossary.
372
+ # @raise [ArgumentError] If +name+ is empty.
373
+ def create_glossary_from_csv(name, source_lang, target_lang, csv, **options)
374
+ csv = csv.read if csv.respond_to?(:read)
375
+
376
+ Requests::Glossary::Create.new(api, name, source_lang, target_lang, csv, 'csv',
377
+ options).request
378
+ end
379
+
380
+ ##
381
+ # Lists all v2 glossaries.
382
+ #
383
+ # @return [Array<DeepL::Resources::Glossary>]
384
+ def list_glossaries
385
+ Requests::Glossary::List.new(api).request
386
+ end
387
+
388
+ ##
389
+ # Retrieves a v2 glossary, without its entries.
390
+ #
391
+ # @param [String, DeepL::Resources::Glossary] glossary ID or glossary.
392
+ # @return [DeepL::Resources::Glossary]
393
+ # @raise [DeepL::Exceptions::NotFound] If the glossary does not exist.
394
+ def get_glossary(glossary)
395
+ Requests::Glossary::Find.new(api, glossary).request
396
+ end
397
+
398
+ ##
399
+ # Retrieves the entries of a v2 glossary.
400
+ #
401
+ # @param [String, DeepL::Resources::Glossary] glossary ID or glossary.
402
+ # @return [Hash{String => String}] Source term to target term.
403
+ # @raise [DeepL::Exceptions::NotFound] If the glossary does not exist.
404
+ def get_glossary_entries(glossary)
405
+ Requests::Glossary::Entries.new(api, glossary).request
406
+ end
407
+
408
+ ##
409
+ # Deletes a v2 glossary.
410
+ #
411
+ # @param [String, DeepL::Resources::Glossary] glossary ID or glossary.
412
+ # @return [nil]
413
+ # @raise [DeepL::Exceptions::NotFound] If the glossary does not exist.
414
+ def delete_glossary(glossary)
415
+ Requests::Glossary::Destroy.new(api, glossary).request
416
+ end
417
+
418
+ ##
419
+ # Retrieves the language pairs supported by glossaries: every source language combined with
420
+ # every other target language of +/v3/languages?resource=glossary+.
421
+ #
422
+ # @return [Array<DeepL::Resources::LanguagePair>]
423
+ def get_glossary_languages # rubocop:disable Naming/AccessorMethodName
424
+ Requests::Glossary::LanguagePairs.new(api).request
425
+ end
426
+
427
+ ##
428
+ # Creates a multilingual glossary with one dictionary per language pair.
429
+ #
430
+ # Creation is retried only after failures that show the request was not processed (HTTP 429 and
431
+ # transient network failures while connecting, such as DNS resolution errors, refused
432
+ # connections, unreachable hosts or networks, connection timeouts and resets during the TLS or
433
+ # proxy handshake), so that a retry cannot create a second glossary.
434
+ #
435
+ # @param [String] name Name of the glossary.
436
+ # @param [Array<DeepL::Resources::MultilingualGlossaryDictionaryEntries, Hash>] dictionaries
437
+ # One entry per language pair. A hash needs the keys +:source_lang+, +:target_lang+ and
438
+ # +:entries+ (a hash, source/target pairs or a TSV string; +:entries_format+ +'csv'+ for a
439
+ # CSV string, which must not be empty or whitespace only and is otherwise sent as given).
440
+ # Entries other than a string are always sent as TSV.
441
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
442
+ # @return [DeepL::Resources::MultilingualGlossary] The created glossary.
443
+ # @raise [DeepL::Exceptions::ValidationError] (an ArgumentError) If a term is empty after
444
+ # stripping surrounding whitespace or contains a control character, or a TSV line is not
445
+ # exactly two terms.
446
+ # @raise [ArgumentError] If +name+ or +dictionaries+ is empty, a dictionary has no entries
447
+ # (including empty or whitespace-only CSV entries), or a +source_lang+ or +target_lang+ of a
448
+ # dictionary is nil or empty, before any request.
449
+ def create_multilingual_glossary(name, dictionaries, **options)
450
+ check_csv_entries!(dictionaries)
451
+ Requests::MultilingualGlossary::Create.new(api, name, dictionaries, options).request
452
+ end
453
+
454
+ ##
455
+ # Creates a multilingual glossary with one dictionary from CSV content.
456
+ #
457
+ # Creation is retried only after failures that show the request was not processed (HTTP 429 and
458
+ # transient network failures while connecting, such as DNS resolution errors, refused
459
+ # connections, unreachable hosts or networks, connection timeouts and resets during the TLS or
460
+ # proxy handshake), so that a retry cannot create a second glossary.
461
+ #
462
+ # @param [String] name Name of the glossary.
463
+ # @param [String] source_lang Source language of the dictionary.
464
+ # @param [String] target_lang Target language of the dictionary.
465
+ # @param [String, IO] csv CSV content, or an IO to read it from. Sent as given.
466
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
467
+ # @return [DeepL::Resources::MultilingualGlossary] The created glossary.
468
+ # @raise [ArgumentError] If +name+ is empty, or +source_lang+ or +target_lang+ is nil or empty,
469
+ # before any request.
470
+ def create_multilingual_glossary_from_csv(name, source_lang, target_lang, csv, **options)
471
+ dictionary = csv_dictionary(source_lang, target_lang, csv)
472
+ Requests::MultilingualGlossary::Create.new(api, name, [dictionary], options).request
473
+ end
474
+
475
+ ##
476
+ # Lists all multilingual glossaries.
477
+ #
478
+ # @return [Array<DeepL::Resources::MultilingualGlossary>]
479
+ def list_multilingual_glossaries
480
+ Requests::MultilingualGlossary::List.new(api).request
481
+ end
482
+
483
+ ##
484
+ # Retrieves a multilingual glossary, without its entries.
485
+ #
486
+ # @param [String, DeepL::Resources::MultilingualGlossary] glossary ID or glossary.
487
+ # @return [DeepL::Resources::MultilingualGlossary]
488
+ # @raise [DeepL::Exceptions::NotFound] If the glossary does not exist.
489
+ # @raise [ArgumentError] If the glossary ID is empty or the glossary has no ID, before any
490
+ # request.
491
+ def get_multilingual_glossary(glossary)
492
+ Requests::MultilingualGlossary::Find.new(api, glossary).request
493
+ end
494
+
495
+ ##
496
+ # Renames a glossary and/or merges entries into its dictionaries. Arguments left +nil+ are
497
+ # not sent; without any, an empty object is sent.
498
+ #
499
+ # @param [String, DeepL::Resources::MultilingualGlossary] glossary ID or glossary.
500
+ # @param [String, nil] name New name.
501
+ # @param [Array<DeepL::Resources::MultilingualGlossaryDictionaryEntries, Hash>, nil]
502
+ # dictionaries Entries to merge into the dictionary of each language pair; a new language
503
+ # pair adds a dictionary.
504
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
505
+ # @return [DeepL::Resources::MultilingualGlossary] The updated glossary.
506
+ # @raise [DeepL::Exceptions::ValidationError] (an ArgumentError) If a term is empty after
507
+ # stripping or contains a control character.
508
+ # @raise [ArgumentError] If the glossary ID or the entries of a dictionary are empty (CSV
509
+ # entries also if whitespace only), a +source_lang+ or +target_lang+ of a dictionary is nil or
510
+ # empty, or the glossary has no ID, before any request.
511
+ def update_multilingual_glossary(glossary, name: nil, dictionaries: nil, **options)
512
+ check_csv_entries!(dictionaries) unless dictionaries.nil?
513
+ Requests::MultilingualGlossary::Update.new(api, glossary, name, dictionaries,
514
+ options).request
515
+ end
516
+
517
+ ##
518
+ # Renames a multilingual glossary.
519
+ #
520
+ # @param [String, DeepL::Resources::MultilingualGlossary] glossary ID or glossary.
521
+ # @param [String] name New name.
522
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
523
+ # @return [DeepL::Resources::MultilingualGlossary] The updated glossary.
524
+ # @raise [ArgumentError] If +name+ or the glossary ID is empty, or the glossary has no ID,
525
+ # before any request.
526
+ def update_multilingual_glossary_name(glossary, name, **options)
527
+ raise ArgumentError, 'Glossary name must not be empty' if name.to_s.empty?
528
+
529
+ Requests::MultilingualGlossary::Update.new(api, glossary, name, nil, options).request
530
+ end
531
+
532
+ ##
533
+ # Merges entries into the dictionary of one language pair, or adds the dictionary if the
534
+ # language pair is new.
535
+ #
536
+ # @param [String, DeepL::Resources::MultilingualGlossary] glossary ID or glossary.
537
+ # @param [DeepL::Resources::MultilingualGlossaryDictionaryEntries, Hash] dictionary The
538
+ # language pair and its entries, see #create_multilingual_glossary.
539
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
540
+ # @return [DeepL::Resources::MultilingualGlossary] The updated glossary.
541
+ # @raise [DeepL::Exceptions::ValidationError] (an ArgumentError) If a term is empty after
542
+ # stripping or contains a control character.
543
+ # @raise [ArgumentError] If the glossary ID or the entries are empty (CSV entries also if
544
+ # whitespace only), a +source_lang+ or +target_lang+ of a dictionary is nil or empty, or the
545
+ # glossary has no ID, before any request.
546
+ def update_multilingual_glossary_dictionary(glossary, dictionary, **options)
547
+ check_csv_entries!([dictionary])
548
+ Requests::MultilingualGlossary::Update.new(api, glossary, nil, [dictionary],
549
+ options).request
550
+ end
551
+
552
+ ##
553
+ # Merges CSV entries into the dictionary of one language pair, or adds the dictionary if
554
+ # the language pair is new.
555
+ #
556
+ # @param [String, DeepL::Resources::MultilingualGlossary] glossary ID or glossary.
557
+ # @param [String] source_lang Source language of the dictionary.
558
+ # @param [String] target_lang Target language of the dictionary.
559
+ # @param [String, IO] csv CSV content, or an IO to read it from. Must not be empty or
560
+ # whitespace only; otherwise sent as given.
561
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
562
+ # @return [DeepL::Resources::MultilingualGlossary] The updated glossary.
563
+ # @raise [ArgumentError] If the CSV content is empty or whitespace only, +source_lang+ or
564
+ # +target_lang+ is nil or empty, the glossary ID is empty or the glossary has no ID, before
565
+ # any request.
566
+ def update_multilingual_glossary_dictionary_from_csv(glossary, source_lang, target_lang, csv,
567
+ **options)
568
+ dictionary = non_empty_csv_dictionary(source_lang, target_lang, csv)
569
+ Requests::MultilingualGlossary::Update.new(api, glossary, nil, [dictionary],
570
+ options).request
571
+ end
572
+
573
+ ##
574
+ # Replaces the entries of the dictionary of one language pair, or adds the dictionary if
575
+ # the language pair is new.
576
+ #
577
+ # @param [String, DeepL::Resources::MultilingualGlossary] glossary ID or glossary.
578
+ # @param [DeepL::Resources::MultilingualGlossaryDictionaryEntries, Hash] dictionary The
579
+ # language pair and its entries, see #create_multilingual_glossary.
580
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
581
+ # @return [DeepL::Resources::MultilingualGlossaryDictionary] The replaced dictionary.
582
+ # @raise [DeepL::Exceptions::ValidationError] (an ArgumentError) If a term is empty after
583
+ # stripping or contains a control character.
584
+ # @raise [ArgumentError] If the glossary ID or the entries are empty (CSV entries also if
585
+ # whitespace only), a +source_lang+ or +target_lang+ of a dictionary is nil or empty, or the
586
+ # glossary has no ID, before any request.
587
+ def replace_multilingual_glossary_dictionary(glossary, dictionary, **options)
588
+ check_csv_entries!([dictionary])
589
+ Requests::MultilingualGlossary::ReplaceDictionary.new(api, glossary, dictionary,
590
+ options).request
591
+ end
592
+
593
+ ##
594
+ # Replaces the entries of the dictionary of one language pair with CSV content.
595
+ #
596
+ # @param [String, DeepL::Resources::MultilingualGlossary] glossary ID or glossary.
597
+ # @param [String] source_lang Source language of the dictionary.
598
+ # @param [String] target_lang Target language of the dictionary.
599
+ # @param [String, IO] csv CSV content, or an IO to read it from. Must not be empty or
600
+ # whitespace only; otherwise sent as given.
601
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
602
+ # @return [DeepL::Resources::MultilingualGlossaryDictionary] The replaced dictionary.
603
+ # @raise [ArgumentError] If the CSV content is empty or whitespace only, +source_lang+ or
604
+ # +target_lang+ is nil or empty, the glossary ID is empty or the glossary has no ID, before
605
+ # any request.
606
+ def replace_multilingual_glossary_dictionary_from_csv(glossary, source_lang, target_lang, csv,
607
+ **options)
608
+ dictionary = non_empty_csv_dictionary(source_lang, target_lang, csv)
609
+ Requests::MultilingualGlossary::ReplaceDictionary.new(api, glossary, dictionary,
610
+ options).request
611
+ end
612
+
613
+ ##
614
+ # Retrieves the entries of the dictionary of one language pair.
615
+ #
616
+ # @param [String, DeepL::Resources::MultilingualGlossary] glossary ID or glossary.
617
+ # @param [String] source_lang Source language of the dictionary.
618
+ # @param [String] target_lang Target language of the dictionary.
619
+ # @return [DeepL::Resources::MultilingualGlossaryDictionaryEntries] The entries as a hash
620
+ # of source term to target term.
621
+ # @raise [DeepL::Exceptions::NotFound] If the glossary does not exist or has no dictionary
622
+ # for the language pair (HTTP 404), or if the API answers 200 with no entries for the pair
623
+ # (then without +response+ and with +http_status_code+ +nil+).
624
+ # @raise [ArgumentError] If the glossary ID is empty, the glossary has no ID, or +source_lang+
625
+ # or +target_lang+ is nil or empty, before any request.
626
+ def get_multilingual_glossary_dictionary_entries(glossary, source_lang, target_lang)
627
+ Requests::MultilingualGlossary::Entries.new(api, glossary, source_lang, target_lang).request
628
+ end
629
+
630
+ ##
631
+ # Deletes the dictionary of one language pair from a multilingual glossary.
632
+ #
633
+ # @param [String, DeepL::Resources::MultilingualGlossary] glossary ID or glossary.
634
+ # @param [String] source_lang Source language of the dictionary.
635
+ # @param [String] target_lang Target language of the dictionary.
636
+ # @return [nil]
637
+ # @raise [ArgumentError] If the glossary ID, +source_lang+ or +target_lang+ is empty, or the
638
+ # glossary has no ID, before any request.
639
+ def delete_multilingual_glossary_dictionary(glossary, source_lang, target_lang)
640
+ Requests::MultilingualGlossary::DestroyDictionary.new(api, glossary, source_lang,
641
+ target_lang).request
642
+ end
643
+
644
+ ##
645
+ # Deletes a multilingual glossary.
646
+ #
647
+ # @param [String, DeepL::Resources::MultilingualGlossary] glossary ID or glossary.
648
+ # @return [nil]
649
+ # @raise [ArgumentError] If the glossary ID is empty or the glossary has no ID, before any
650
+ # request.
651
+ def delete_multilingual_glossary(glossary)
652
+ Requests::MultilingualGlossary::Destroy.new(api, glossary).request
653
+ end
654
+
655
+ ##
656
+ # Creates a spoken terms collection, which improves the transcription of the given terms.
657
+ #
658
+ # Creation is retried only after failures that show the request was not processed (HTTP 429 and
659
+ # transient network failures while connecting, such as DNS resolution errors, refused
660
+ # connections, unreachable hosts or networks, connection timeouts and resets during the TLS or
661
+ # proxy handshake), so that a retry cannot create a second collection.
662
+ #
663
+ # @param [String] name Name of the collection.
664
+ # @param [Array<DeepL::Resources::SpokenTermsEntries, Hash>] term_lists One entry per
665
+ # language. A hash needs the keys +:lang+ and +:entries+ (an array of terms).
666
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
667
+ # @return [DeepL::Resources::SpokenTerms] The created collection.
668
+ # @raise [DeepL::Exceptions::ValidationError] (an ArgumentError) If a term is empty after
669
+ # stripping surrounding whitespace or contains a control character.
670
+ # @raise [ArgumentError] If the +lang+ of a term list is nil or empty, before any request.
671
+ def create_spoken_terms(name, term_lists, **options)
672
+ Requests::SpokenTerms::Create.new(api, name, term_lists, options).request
673
+ end
674
+
675
+ ##
676
+ # Lists all spoken terms collections.
677
+ #
678
+ # @return [Array<DeepL::Resources::SpokenTerms>]
679
+ def list_spoken_terms
680
+ Requests::SpokenTerms::List.new(api).request
681
+ end
682
+
683
+ ##
684
+ # Retrieves a spoken terms collection.
685
+ #
686
+ # @param [String, DeepL::Resources::SpokenTerms] spoken_terms ID or collection.
687
+ # @return [DeepL::Resources::SpokenTerms]
688
+ # @raise [DeepL::Exceptions::NotFound] If the collection does not exist.
689
+ # @raise [ArgumentError] If the ID is empty or the collection has no ID, before any request.
690
+ def get_spoken_terms(spoken_terms)
691
+ Requests::SpokenTerms::Find.new(api, spoken_terms).request
692
+ end
693
+
694
+ ##
695
+ # Renames a collection and/or merges terms into its lists. Arguments left +nil+ are not
696
+ # sent; without any, an empty object is sent.
697
+ #
698
+ # @param [String, DeepL::Resources::SpokenTerms] spoken_terms ID or collection.
699
+ # @param [String, nil] name New name.
700
+ # @param [Array<DeepL::Resources::SpokenTermsEntries, Hash>, nil] term_lists Terms to merge
701
+ # into the list of each language; a new language adds a list.
702
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
703
+ # @return [DeepL::Resources::SpokenTerms] The updated collection.
704
+ # @raise [DeepL::Exceptions::ValidationError] (an ArgumentError) If a term is empty after
705
+ # stripping or contains a control character.
706
+ # @raise [ArgumentError] If the ID is empty, the collection has no ID, or the +lang+ of a term
707
+ # list is nil or empty, before any request.
708
+ def update_spoken_terms(spoken_terms, name: nil, term_lists: nil, **options)
709
+ Requests::SpokenTerms::Update.new(api, spoken_terms, name, term_lists, options).request
710
+ end
711
+
712
+ ##
713
+ # Deletes a spoken terms collection.
714
+ #
715
+ # @param [String, DeepL::Resources::SpokenTerms] spoken_terms ID or collection.
716
+ # @return [nil]
717
+ # @raise [ArgumentError] If the ID is empty or the collection has no ID, before any request.
718
+ def delete_spoken_terms(spoken_terms)
719
+ Requests::SpokenTerms::Destroy.new(api, spoken_terms).request
720
+ end
721
+
722
+ ##
723
+ # Retrieves the terms of one language of a collection.
724
+ #
725
+ # @param [String, DeepL::Resources::SpokenTerms] spoken_terms ID or collection.
726
+ # @param [String] lang Language code, for example +'en'+.
727
+ # @return [DeepL::Resources::SpokenTermsEntries]
728
+ # @raise [ArgumentError] If the ID is empty, the collection has no ID, or +lang+ is nil or
729
+ # empty, before any request.
730
+ def get_spoken_terms_entries(spoken_terms, lang)
731
+ Requests::SpokenTerms::Entries.new(api, spoken_terms, lang).request
732
+ end
733
+
734
+ ##
735
+ # Replaces the terms of one language, or adds the list if the language is new.
736
+ #
737
+ # @param [String, DeepL::Resources::SpokenTerms] spoken_terms ID or collection.
738
+ # @param [DeepL::Resources::SpokenTermsEntries, Hash] entries The language and its terms; a
739
+ # hash needs the keys +:lang+ and +:entries+.
740
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
741
+ # @return [DeepL::Resources::SpokenTermsList]
742
+ # @raise [DeepL::Exceptions::ValidationError] (an ArgumentError) If a term is empty after
743
+ # stripping or contains a control character.
744
+ # @raise [ArgumentError] If the ID is empty, the collection has no ID, or the +lang+ of the
745
+ # term list is nil or empty, before any request.
746
+ def replace_spoken_terms_list(spoken_terms, entries, **options)
747
+ Requests::SpokenTerms::ReplaceTermList.new(api, spoken_terms, entries, options).request
748
+ end
749
+
750
+ ##
751
+ # Deletes the term list of one language of a collection.
752
+ #
753
+ # @param [String, DeepL::Resources::SpokenTerms] spoken_terms ID or collection.
754
+ # @param [String] lang Language code, for example +'en'+.
755
+ # @return [nil]
756
+ # @raise [ArgumentError] If the ID is empty, the collection has no ID, or +lang+ is nil or
757
+ # empty, before any request.
758
+ def delete_spoken_terms_list(spoken_terms, lang)
759
+ Requests::SpokenTerms::DestroyTermList.new(api, spoken_terms, lang).request
760
+ end
761
+
762
+ ##
763
+ # Lists style rule lists, one page at a time. Arguments left +nil+ are not sent.
764
+ #
765
+ # @param [Integer, nil] page Index of the page, starting at 0 (API default: 0).
766
+ # @param [Integer, nil] page_size Style rule lists per page (API default: 10).
767
+ # @param [Boolean, nil] detailed Whether to include +configured_rules+ and
768
+ # +custom_instructions+.
769
+ # @return [Array<DeepL::Resources::StyleRule>]
770
+ def get_all_style_rules(page: nil, page_size: nil, detailed: nil)
771
+ options = { page: page, page_size: page_size, detailed: detailed }.compact
772
+ Requests::StyleRule::List.new(api, options).request
773
+ end
774
+
775
+ ##
776
+ # Creates a style rule list. Keywords left +nil+ are not sent.
777
+ #
778
+ # Creation is retried only after failures that show the request was not processed (HTTP 429 and
779
+ # transient network failures while connecting, such as DNS resolution errors, refused
780
+ # connections, unreachable hosts or networks, connection timeouts and resets during the TLS or
781
+ # proxy handshake), so that a retry cannot create a second style rule list.
782
+ #
783
+ # @param [String] name Name of the style rule list.
784
+ # @param [String] language Language the rules apply to, for example +'en'+.
785
+ # @param [Hash, nil] configured_rules Category -> rule -> value, sent as given.
786
+ # @param [Array<Hash>, nil] custom_instructions Instructions in the wire shape
787
+ # (+label+, +prompt+ and optionally +source_language+), sent as given.
788
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
789
+ # @return [DeepL::Resources::StyleRule] The created style rule list.
790
+ # @raise [ArgumentError] If +name+ or +language+ is empty, or a custom instruction's
791
+ # +source_language+ is empty, before any request.
792
+ def create_style_rule(name, language, configured_rules: nil, custom_instructions: nil,
793
+ **options)
794
+ options = options.merge(configured_rules: configured_rules,
795
+ custom_instructions: custom_instructions).compact
796
+ Requests::StyleRule::Create.new(api, name, language, options).request
797
+ end
798
+
799
+ ##
800
+ # Retrieves a style rule list, including its configured rules and custom instructions.
801
+ #
802
+ # @param [String, DeepL::Resources::StyleRule] style_rule ID or style rule list.
803
+ # @return [DeepL::Resources::StyleRule]
804
+ # @raise [DeepL::Exceptions::NotFound] If the style rule list does not exist.
805
+ # @raise [ArgumentError] If the style rule ID is empty or the list has no ID, before any
806
+ # request.
807
+ def get_style_rule(style_rule)
808
+ Requests::StyleRule::Find.new(api, style_rule).request
809
+ end
810
+
811
+ ##
812
+ # Renames a style rule list.
813
+ #
814
+ # @param [String, DeepL::Resources::StyleRule] style_rule ID or style rule list.
815
+ # @param [String] name New name.
816
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
817
+ # @return [DeepL::Resources::StyleRule] The updated style rule list.
818
+ # @raise [ArgumentError] If the style rule ID or +name+ is empty, or the list has no ID, before
819
+ # any request.
820
+ def update_style_rule_name(style_rule, name, **options)
821
+ Requests::StyleRule::Update.new(api, style_rule, name, options).request
822
+ end
823
+
824
+ ##
825
+ # Replaces the configured rules of a style rule list.
826
+ #
827
+ # @param [String, DeepL::Resources::StyleRule] style_rule ID or style rule list.
828
+ # @param [Hash] configured_rules Category -> rule -> value, sent as the request body.
829
+ # @param [Hash] options +:extra_body_parameters+, added to the body as further keys.
830
+ # @return [DeepL::Resources::StyleRule] The updated style rule list.
831
+ # @raise [ArgumentError] If the style rule ID is empty or the list has no ID, before any
832
+ # request.
833
+ def update_style_rule_configured_rules(style_rule, configured_rules, **options)
834
+ Requests::StyleRule::UpdateConfiguredRules.new(api, style_rule, configured_rules,
835
+ options).request
836
+ end
837
+
838
+ ##
839
+ # Deletes a style rule list.
840
+ #
841
+ # @param [String, DeepL::Resources::StyleRule] style_rule ID or style rule list.
842
+ # @return [nil]
843
+ # @raise [ArgumentError] If the style rule ID is empty or the list has no ID, before any
844
+ # request.
845
+ def delete_style_rule(style_rule)
846
+ Requests::StyleRule::Destroy.new(api, style_rule).request
847
+ nil
848
+ end
849
+
850
+ ##
851
+ # Adds a custom instruction to a style rule list. +source_language+ is not sent if +nil+.
852
+ #
853
+ # Creation is retried only after failures that show the request was not processed (HTTP 429 and
854
+ # transient network failures while connecting, such as DNS resolution errors, refused
855
+ # connections, unreachable hosts or networks, connection timeouts and resets during the TLS or
856
+ # proxy handshake), so that a retry cannot create a second custom instruction.
857
+ #
858
+ # @param [String, DeepL::Resources::StyleRule] style_rule ID or style rule list.
859
+ # @param [String] label Label of the instruction.
860
+ # @param [String] prompt The instruction.
861
+ # @param [String, nil] source_language Source language the instruction applies to.
862
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
863
+ # @return [DeepL::Resources::CustomInstruction] The created instruction.
864
+ # @raise [ArgumentError] If the style rule ID, +label+ or +prompt+ is empty, +source_language+
865
+ # is empty (+nil+ leaves it unset), or the list has no ID, before any request.
866
+ def create_style_rule_custom_instruction(style_rule, label, prompt, source_language: nil,
867
+ **options)
868
+ Requests::StyleRule::CreateCustomInstruction.new(api, style_rule, label, prompt,
869
+ source_language, options).request
870
+ end
871
+
872
+ ##
873
+ # Retrieves a custom instruction of a style rule list.
874
+ #
875
+ # @param [String, DeepL::Resources::StyleRule] style_rule ID or style rule list.
876
+ # @param [String, DeepL::Resources::CustomInstruction] instruction_id ID or instruction.
877
+ # @return [DeepL::Resources::CustomInstruction]
878
+ # @raise [DeepL::Exceptions::NotFound] If the instruction does not exist.
879
+ # @raise [ArgumentError] If the style rule or instruction ID is empty or the object has no ID,
880
+ # before any request.
881
+ def get_style_rule_custom_instruction(style_rule, instruction_id)
882
+ Requests::StyleRule::FindCustomInstruction.new(api, style_rule, instruction_id).request
883
+ end
884
+
885
+ ##
886
+ # Replaces a custom instruction of a style rule list. +source_language+ is not sent if
887
+ # +nil+.
888
+ #
889
+ # @param [String, DeepL::Resources::StyleRule] style_rule ID or style rule list.
890
+ # @param [String, DeepL::Resources::CustomInstruction] instruction_id ID or instruction.
891
+ # @param [String] label Label of the instruction.
892
+ # @param [String] prompt The instruction.
893
+ # @param [String, nil] source_language Source language the instruction applies to.
894
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
895
+ # @return [DeepL::Resources::CustomInstruction] The updated instruction.
896
+ # @raise [ArgumentError] If an ID, +label+ or +prompt+ is empty, +source_language+ is empty
897
+ # (+nil+ leaves it unset), or an object has no ID, before any request.
898
+ def update_style_rule_custom_instruction(style_rule, instruction_id, label, prompt,
899
+ source_language: nil, **options)
900
+ Requests::StyleRule::UpdateCustomInstruction.new(api, style_rule, instruction_id, label,
901
+ prompt, source_language,
902
+ options).request
903
+ end
904
+
905
+ ##
906
+ # Deletes a custom instruction of a style rule list.
907
+ #
908
+ # @param [String, DeepL::Resources::StyleRule] style_rule ID or style rule list.
909
+ # @param [String, DeepL::Resources::CustomInstruction] instruction_id ID or instruction.
910
+ # @return [nil]
911
+ # @raise [ArgumentError] If the style rule or instruction ID is empty or the object has no ID,
912
+ # before any request.
913
+ def delete_style_rule_custom_instruction(style_rule, instruction_id)
914
+ Requests::StyleRule::DestroyCustomInstruction.new(api, style_rule, instruction_id).request
915
+ nil
916
+ end
917
+
918
+ ##
919
+ # Lists style profiles, one page at a time. Arguments left +nil+ are not sent.
920
+ #
921
+ # @param [Integer, nil] page Index of the page, starting at 0 (API default: 0).
922
+ # @param [Integer, nil] page_size Style profiles per page (API default: 10, at most 100).
923
+ # @return [Array<DeepL::Resources::StyleProfile>]
924
+ def list_style_profiles(page: nil, page_size: nil)
925
+ Requests::StyleProfile::List.new(api, { page: page, page_size: page_size }.compact).request
926
+ end
927
+
928
+ ##
929
+ # Creates a style profile, which links glossaries, style rule lists and translation
930
+ # memories. Keywords left +nil+ are not sent. If a component cannot be used, the request
931
+ # fails and no style profile is created.
932
+ #
933
+ # Creation is retried only after failures that show the request was not processed (HTTP 429 and
934
+ # transient network failures while connecting, such as DNS resolution errors, refused
935
+ # connections, unreachable hosts or networks, connection timeouts and resets during the TLS or
936
+ # proxy handshake), so that a retry cannot create a second style profile.
937
+ #
938
+ # @param [String] name Name of the style profile.
939
+ # @param [String, nil] description Free-text description.
940
+ # @param [String, nil] industry The industry the style profile is written for.
941
+ # @param [Array<String, DeepL::Resources::Glossary, DeepL::Resources::MultilingualGlossary>,
942
+ # nil] glossary_ids Glossaries to link (IDs or objects), highest priority first.
943
+ # @param [Array<String, DeepL::Resources::StyleRule>, nil] style_rule_ids Style rule lists.
944
+ # @param [Array<String, DeepL::Resources::TranslationMemory>, nil] translation_memory_ids
945
+ # Translation memories.
946
+ # @param [Boolean, nil] glossary_priority_order_enabled Whether the order of +glossary_ids+
947
+ # sets priority.
948
+ # @param [Hash] options +:extra_body_parameters+, a hash added to the request body last.
949
+ # @return [DeepL::Resources::StyleProfile] The created style profile.
950
+ def create_style_profile(name, description: nil, industry: nil, glossary_ids: nil, # rubocop:disable Metrics/ParameterLists
951
+ style_rule_ids: nil, translation_memory_ids: nil,
952
+ glossary_priority_order_enabled: nil, **options)
953
+ fields = { description: description, industry: industry, glossary_ids: glossary_ids,
954
+ style_rule_ids: style_rule_ids, translation_memory_ids: translation_memory_ids,
955
+ glossary_priority_order_enabled: glossary_priority_order_enabled }
956
+ Requests::StyleProfile::Create.new(api, name, fields, options).request
957
+ end
958
+
959
+ ##
960
+ # Retrieves a style profile.
961
+ #
962
+ # @param [String, DeepL::Resources::StyleProfile] style_profile ID or style profile.
963
+ # @return [DeepL::Resources::StyleProfile]
964
+ # @raise [ArgumentError] If the ID is empty.
965
+ # @raise [DeepL::Exceptions::NotFound] If the style profile does not exist.
966
+ def get_style_profile(style_profile)
967
+ Requests::StyleProfile::Find.new(api, style_profile).request
968
+ end
969
+
970
+ ##
971
+ # Updates a style profile. Keywords left +nil+ are not sent and leave the field unchanged;
972
+ # without any, an empty object is sent. An empty string clears +description+ or +industry+.
973
+ # A component list replaces the linked list in full; an empty array unlinks all components
974
+ # of that kind.
975
+ #
976
+ # @param [String, DeepL::Resources::StyleProfile] style_profile ID or style profile.
977
+ # @param [String, nil] name New name.
978
+ # @param [Hash] options The keywords of #create_style_profile, including
979
+ # +:extra_body_parameters+.
980
+ # @return [DeepL::Resources::StyleProfile] The updated style profile.
981
+ # @raise [ArgumentError] If the ID is empty.
982
+ def update_style_profile(style_profile, name: nil, description: nil, industry: nil, # rubocop:disable Metrics/ParameterLists
983
+ glossary_ids: nil, style_rule_ids: nil, translation_memory_ids: nil,
984
+ glossary_priority_order_enabled: nil, **options)
985
+ fields = { name: name, description: description, industry: industry,
986
+ glossary_ids: glossary_ids, style_rule_ids: style_rule_ids,
987
+ translation_memory_ids: translation_memory_ids,
988
+ glossary_priority_order_enabled: glossary_priority_order_enabled }
989
+ Requests::StyleProfile::Update.new(api, style_profile, fields, options).request
990
+ end
991
+
992
+ ##
993
+ # Deletes a style profile.
994
+ #
995
+ # @param [String, DeepL::Resources::StyleProfile] style_profile ID or style profile.
996
+ # @return [nil]
997
+ # @raise [ArgumentError] If the ID is empty.
998
+ def delete_style_profile(style_profile)
999
+ Requests::StyleProfile::Destroy.new(api, style_profile).request
1000
+ nil
1001
+ end
1002
+
1003
+ ##
1004
+ # Lists translation memories, one page at a time. Arguments left +nil+ are not sent.
1005
+ #
1006
+ # @param [Integer, nil] page Index of the page, starting at 0 (API default: 0).
1007
+ # @param [Integer, nil] page_size Translation memories per page (API default: 10).
1008
+ # @return [Array<DeepL::Resources::TranslationMemory>]
1009
+ def list_translation_memories(page: nil, page_size: nil)
1010
+ translation_memories.list({ page: page, page_size: page_size }.compact)
1011
+ end
1012
+
1013
+ ##
1014
+ # Retrieves a translation memory.
1015
+ #
1016
+ # @param [String, DeepL::Resources::TranslationMemory] translation_memory ID or translation
1017
+ # memory.
1018
+ # @return [DeepL::Resources::TranslationMemory]
1019
+ # @raise [DeepL::Exceptions::NotFound] If the translation memory does not exist.
1020
+ # @raise [ArgumentError] If the ID is empty or the object has no ID, before any request.
1021
+ def get_translation_memory(translation_memory)
1022
+ translation_memories.find(translation_memory)
1023
+ end
1024
+
1025
+ ##
1026
+ # Deletes a translation memory.
1027
+ #
1028
+ # @param [String, DeepL::Resources::TranslationMemory] translation_memory ID or translation
1029
+ # memory.
1030
+ # @return [nil]
1031
+ # @raise [ArgumentError] If the ID is empty or the object has no ID, before any request.
1032
+ def delete_translation_memory(translation_memory)
1033
+ translation_memories.destroy(translation_memory)
1034
+ nil
1035
+ end
1036
+
1037
+ ##
1038
+ # Retrieves one page of the segments of a translation memory. Pagination is cursor-based:
1039
+ # omit +page_cursor+ on the first call, then pass the +next_page_cursor+ of the previous page
1040
+ # until it is +nil+. Arguments left +nil+ are not sent.
1041
+ #
1042
+ # @param [String, DeepL::Resources::TranslationMemory] translation_memory ID or translation
1043
+ # memory.
1044
+ # @param [Integer, nil] page_size Segments per page, 1-100 (API default: 50).
1045
+ # @param [String, nil] page_cursor +next_page_cursor+ of the previous page.
1046
+ # @param [String, nil] filter_text Substring matched against source and target texts, at
1047
+ # least 2 characters.
1048
+ # @param [Boolean, nil] filter_case_sensitive Whether +filter_text+ is case-sensitive (API
1049
+ # default: false).
1050
+ # @return [DeepL::Resources::TranslationMemorySegments]
1051
+ # @raise [ArgumentError] If the ID is empty or the object has no ID, before any request.
1052
+ def list_translation_memory_segments(translation_memory, page_size: nil, page_cursor: nil,
1053
+ filter_text: nil, filter_case_sensitive: nil)
1054
+ options = { page_size: page_size, page_cursor: page_cursor, filter_text: filter_text,
1055
+ filter_case_sensitive: filter_case_sensitive }.compact
1056
+ translation_memories.segments(translation_memory, options)
1057
+ end
1058
+
1059
+ ##
1060
+ # Creates an import job for a new translation memory. Upload the TMX file to the returned
1061
+ # upload URL with #upload_translation_memory_file, then wait for the job with
1062
+ # #wait_until_translation_memory_job_done. Keywords left +nil+ are not sent.
1063
+ #
1064
+ # Creation is retried only after failures that show the request was not processed (HTTP 429 and
1065
+ # transient network failures while connecting, such as DNS resolution errors, refused
1066
+ # connections, unreachable hosts or networks, connection timeouts and resets during the TLS or
1067
+ # proxy handshake), so that a retry cannot create a second import job.
1068
+ #
1069
+ # @param [String] file_name Name of the TMX file, for example +'legal.tmx'+.
1070
+ # @param [Integer] content_length Size of the file in bytes.
1071
+ # @param [String, nil] content_type MIME type of the file (API default: +application/xml+).
1072
+ # @param [String, nil] display_name Name of the translation memory (API default: the file
1073
+ # name).
1074
+ # @param [Hash, nil] extra_body_parameters A hash added to the request body last.
1075
+ # @return [DeepL::Resources::TranslationMemoryImport] The job ID and the upload URL.
1076
+ # @raise [ArgumentError] If +file_name+ is empty or +content_length+ is not positive, before
1077
+ # any request.
1078
+ def create_translation_memory_import(file_name, content_length, content_type: nil,
1079
+ display_name: nil, extra_body_parameters: nil)
1080
+ translation_memories.create_import(file_name, content_length,
1081
+ content_type: content_type, display_name: display_name,
1082
+ extra_body_parameters: extra_body_parameters)
1083
+ end
1084
+
1085
+ ##
1086
+ # Uploads a TMX file to the upload URL of an import job, which starts the processing. The
1087
+ # upload URL is a pre-signed storage URL: no +Authorization+ header and no configured
1088
+ # +headers+ are sent to it.
1089
+ #
1090
+ # @param [DeepL::Resources::TranslationMemoryImport, String] translation_memory_import The
1091
+ # import, or its upload URL.
1092
+ # @param [String] content Content of the TMX file.
1093
+ # @param [String, nil] content_type MIME type of the file, must match the one of the import
1094
+ # job. +nil+ sends +application/xml+.
1095
+ # @return [nil]
1096
+ # @raise [DeepL::Exceptions::Error] If the storage URL replies with a non-2xx status; the error
1097
+ # carries +http_status_code+, and +should_retry?+ is true for 429 and 5xx.
1098
+ # @raise [ArgumentError] If the upload URL is empty, before any request.
1099
+ def upload_translation_memory_file(translation_memory_import, content, content_type: nil)
1100
+ translation_memories.upload_file(translation_memory_import, content,
1101
+ content_type: content_type)
1102
+ end
1103
+
1104
+ ##
1105
+ # Imports a TMX file as a new translation memory: creates the import job, uploads the file
1106
+ # and waits until the job is completed.
1107
+ #
1108
+ # Creating the import job is retried only after failures that show the request was not processed
1109
+ # (HTTP 429 and transient network failures while connecting, such as DNS resolution errors,
1110
+ # refused connections, unreachable hosts or networks, connection timeouts and resets during the
1111
+ # TLS or proxy handshake), so that a retry cannot create a second import job.
1112
+ #
1113
+ # @param [String] input_path Path of the TMX file.
1114
+ # @param [String, nil] display_name Name of the translation memory (API default: the file
1115
+ # name).
1116
+ # @param [String, nil] content_type MIME type of the file, declared in the import job and
1117
+ # sent with the upload. +nil+ uses +application/xml+.
1118
+ # @param [Numeric, nil] timeout_s Maximum time in seconds to wait for the job, +nil+ to wait
1119
+ # until it is completed. The API reports +awaiting_input+ for a while after the upload.
1120
+ # @param [Hash, nil] extra_body_parameters A hash added to the body of the import job request
1121
+ # last.
1122
+ # @return [DeepL::Resources::TranslationMemoryJob] The completed job; its result carries the
1123
+ # ID of the new translation memory.
1124
+ # @raise [ArgumentError] If the file does not exist, before any request is sent.
1125
+ # @raise [DeepL::Exceptions::TranslationMemoryJobError] For any other failure, the original
1126
+ # error as +cause+: an empty or unreadable file (before any request), an invalid argument or
1127
+ # failure of the job creation, a failed upload, a job that fails or expires (with the API's
1128
+ # error message), or an expired +timeout_s+. +job_id+ is set once the job was created, +job+
1129
+ # is the last status fetched (+nil+ before the first status check); +http_status_code+ and
1130
+ # +should_retry?+ are those of a DeepL error cause.
1131
+ def import_translation_memory_from_filepath(input_path, display_name: nil, content_type: nil,
1132
+ timeout_s: nil, extra_body_parameters: nil)
1133
+ translation_memories.import_from_filepath(
1134
+ input_path, display_name: display_name, content_type: content_type, timeout_s: timeout_s,
1135
+ extra_body_parameters: extra_body_parameters
1136
+ )
1137
+ end
1138
+
1139
+ ##
1140
+ # Creates an export job for a translation memory. Wait for it with
1141
+ # #wait_until_translation_memory_job_done, then download the TMX file with
1142
+ # #download_translation_memory_export.
1143
+ #
1144
+ # Creation is retried only after failures that show the request was not processed (HTTP 429 and
1145
+ # transient network failures while connecting, such as DNS resolution errors, refused
1146
+ # connections, unreachable hosts or networks, connection timeouts and resets during the TLS or
1147
+ # proxy handshake), so that a retry cannot create a second export job.
1148
+ #
1149
+ # @param [String, DeepL::Resources::TranslationMemory] translation_memory ID or translation
1150
+ # memory.
1151
+ # @return [DeepL::Resources::TranslationMemoryExport] The job ID, and whether the API reused
1152
+ # a previously completed export.
1153
+ # @raise [ArgumentError] If the ID is empty or the object has no ID, before any request.
1154
+ def create_translation_memory_export(translation_memory)
1155
+ translation_memories.create_export(translation_memory)
1156
+ end
1157
+
1158
+ ##
1159
+ # Downloads the TMX file of a completed export job to +output_path+. The download URL is a
1160
+ # pre-signed storage URL: no +Authorization+ header and no configured +headers+ are sent to
1161
+ # it.
1162
+ #
1163
+ # @param [DeepL::Resources::TranslationMemoryJob] job The completed export job, as returned
1164
+ # by #wait_until_translation_memory_job_done.
1165
+ # @param [String] output_path Path to write the file to. Must not exist.
1166
+ # @return [nil]
1167
+ # @raise [DeepL::Exceptions::Error] If the job has no download URL, for example because it is
1168
+ # not completed yet, before any request.
1169
+ # @raise [SystemCallError] +Errno::EEXIST+ if +output_path+ exists, +Errno::ENOENT+ or
1170
+ # +Errno::EACCES+ if its directory is missing or not writable (checked before the request),
1171
+ # or the error of writing the file.
1172
+ # @raise [DeepL::Exceptions::Error] If the download fails.
1173
+ def download_translation_memory_export(job, output_path)
1174
+ translation_memories.download_export(job, output_path)
1175
+ nil
1176
+ end
1177
+
1178
+ ##
1179
+ # Exports a translation memory to a TMX file: creates the export job, waits until it is
1180
+ # completed and writes the file to +output_path+.
1181
+ #
1182
+ # Starting the export is retried only after failures that show the request was not processed
1183
+ # (HTTP 429 and transient network failures while connecting, such as DNS resolution errors,
1184
+ # refused connections, unreachable hosts or networks, connection timeouts and resets during the
1185
+ # TLS or proxy handshake), so that a retry cannot create a second export job.
1186
+ #
1187
+ # @param [String, DeepL::Resources::TranslationMemory] translation_memory ID or translation
1188
+ # memory.
1189
+ # @param [String] output_path Path to write the file to. Must not exist.
1190
+ # @param [Numeric, nil] timeout_s Maximum time in seconds to wait for the job, +nil+ to wait
1191
+ # until it is completed.
1192
+ # @return [DeepL::Resources::TranslationMemoryJob] The completed job.
1193
+ # @raise [DeepL::Exceptions::TranslationMemoryJobError] For every failure, the original error
1194
+ # as +cause+: +output_path+ exists or its directory does not exist or is not writable
1195
+ # (checked before the job is created), an empty ID or an object without one, a failed job
1196
+ # creation, a job that fails or expires (with the API's error message), an expired
1197
+ # +timeout_s+, a failed download or a failure writing the file. +job_id+ is set once the job
1198
+ # was created, +job+ is the last status fetched (+nil+ before the first status check);
1199
+ # +http_status_code+ and +should_retry?+ are those of a DeepL error cause.
1200
+ def export_translation_memory_to_filepath(translation_memory, output_path, timeout_s: nil)
1201
+ translation_memories.export_to_filepath(translation_memory, output_path,
1202
+ timeout_s: timeout_s)
1203
+ end
1204
+
1205
+ ##
1206
+ # Retrieves the status of a translation memory import or export job once.
1207
+ #
1208
+ # @param [String, DeepL::Resources::TranslationMemoryJob] job ID or job.
1209
+ # @return [DeepL::Resources::TranslationMemoryJob]
1210
+ # @raise [ArgumentError] If the ID is empty or the object has no ID, before any request.
1211
+ def get_translation_memory_job(job)
1212
+ translation_memories.find_job(job)
1213
+ end
1214
+
1215
+ ##
1216
+ # Polls a translation memory import or export job every 5 seconds until it is completed.
1217
+ #
1218
+ # @param [String, DeepL::Resources::TranslationMemoryJob] job ID or job.
1219
+ # @param [Numeric, nil] timeout_s Maximum time to wait in seconds, +nil+ to wait until the
1220
+ # job is completed, failed or expired. The last wait is cut so that the call never waits
1221
+ # past +timeout_s+. A job whose file is never uploaded does not finish.
1222
+ # @return [DeepL::Resources::TranslationMemoryJob] The completed job.
1223
+ # @raise [DeepL::Exceptions::Error] If the job fails or expires (with the API's error
1224
+ # message), or +timeout_s+ expires.
1225
+ # @raise [ArgumentError] If the ID is empty or the object has no ID, before any request.
1226
+ def wait_until_translation_memory_job_done(job, timeout_s: nil)
1227
+ translation_memories.wait_until_job_done(job, timeout_s: timeout_s)
1228
+ end
1229
+
1230
+ def inspect
1231
+ "#<#{self.class.name} server_url=#{configuration.host}>"
1232
+ end
1233
+
1234
+ private
1235
+
1236
+ attr_reader :api
1237
+
1238
+ def translation_memories
1239
+ @translation_memories ||= Utils::TranslationMemoryOperations.new(api)
1240
+ end
1241
+
1242
+ def configuration
1243
+ api.configuration
1244
+ end
1245
+
1246
+ def check_document_output_path(output_path)
1247
+ Utils::OutputPath.check!(output_path)
1248
+ rescue Errno::EEXIST
1249
+ raise Exceptions::DocumentTranslationError.new('File already exists at output path', nil)
1250
+ rescue SystemCallError => e
1251
+ raise Exceptions::DocumentTranslationError.new("Cannot write to output path: #{e.message}",
1252
+ nil, e)
1253
+ end
1254
+
1255
+ def csv_dictionary(source_lang, target_lang, csv)
1256
+ csv = csv.read if csv.respond_to?(:read)
1257
+ { source_lang: source_lang, target_lang: target_lang, entries: csv, entries_format: 'csv' }
1258
+ end
1259
+
1260
+ # Like #csv_dictionary, but raises ArgumentError for empty or whitespace-only CSV content.
1261
+ def non_empty_csv_dictionary(source_lang, target_lang, csv)
1262
+ dictionary = csv_dictionary(source_lang, target_lang, csv)
1263
+ check_csv_entries!([dictionary])
1264
+ dictionary
1265
+ end
1266
+
1267
+ # Raises ArgumentError if a dictionary hash gives its entries as a CSV string that is empty or
1268
+ # whitespace only. Other dictionaries are checked when the request body is built.
1269
+ def check_csv_entries!(dictionaries)
1270
+ return unless (dictionaries || []).any? { |dictionary| empty_csv_entries?(dictionary) }
1271
+
1272
+ raise ArgumentError, 'CSV content must not be empty'
1273
+ end
1274
+
1275
+ # Reads +:entries+ and +:entries_format+ like the request body does (symbol or string key).
1276
+ def empty_csv_entries?(dictionary)
1277
+ return false unless dictionary.is_a?(Hash)
1278
+
1279
+ value = ->(key) { dictionary[key] || dictionary[key.to_s] }
1280
+ entries = value.call(:entries)
1281
+ value.call(:entries_format) == 'csv' && entries.is_a?(String) && entries.strip.empty?
1282
+ end
1283
+ end
1284
+ end