deepl_api 0.2.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e882987aea99da75e1dec09b2c375816169d24622a93978f100656bd6b2e11ba
4
+ data.tar.gz: 2f04a5b7a53d52426f8f93a8f5b6707dcc49e644292ebac45b56b209546257ef
5
+ SHA512:
6
+ metadata.gz: 696b17977bb4fd596f77056d65a6db83b87f098addd18d71b73e5a2feff8c6545410fbf42050807604e7eefc1385666a500b3e4620f69956ad2a79a6a6d042fd
7
+ data.tar.gz: a7143248566554a754e05d0e0cd9a487ee81f413ab39672d3f7afeec53add2925d32b1f17ab98053701d8ea1eae7b52c7e4c6293c39fd676329d80845089ece5
@@ -0,0 +1,33 @@
1
+ # This workflow uses actions that are not certified by GitHub.
2
+ # They are provided by a third-party and are governed by
3
+ # separate terms of service, privacy policy, and support
4
+ # documentation.
5
+ # This workflow will download a prebuilt Ruby version, install dependencies and run tests with Rake
6
+ # For more information see: https://github.com/marketplace/actions/setup-ruby-jruby-and-truffleruby
7
+
8
+ name: Ruby
9
+
10
+ on: [push, pull_request]
11
+
12
+ jobs:
13
+ test:
14
+
15
+ runs-on: ubuntu-latest
16
+ strategy:
17
+ matrix:
18
+ ruby-version: ['2.6', '2.7', '3.0']
19
+
20
+ steps:
21
+ - uses: actions/checkout@v2
22
+ - name: Set up Ruby
23
+ # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby,
24
+ # change this to (see https://github.com/ruby/setup-ruby#versioning):
25
+ # uses: ruby/setup-ruby@v1
26
+ uses: ruby/setup-ruby@473e4d8fe5dd94ee328fdfca9f8c9c7afc9dae5e
27
+ with:
28
+ ruby-version: ${{ matrix.ruby-version }}
29
+ bundler-cache: true # runs 'bundle install' and caches installed gems automatically
30
+ - name: Run tests
31
+ env:
32
+ DEEPL_API_KEY: ${{ secrets.DEEPL_API_KEY }}
33
+ run: bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+
13
+ /vendor/
data/.rdoc_options ADDED
@@ -0,0 +1,27 @@
1
+ --- !ruby/object:RDoc::Options
2
+ encoding: UTF-8
3
+ static_path: []
4
+ rdoc_include:
5
+ - "./lib"
6
+ charset: UTF-8
7
+ exclude:
8
+ - "bin/"
9
+ - "vendor/"
10
+ - "Gemfile.*"
11
+ - ".*gemspec"
12
+ - "Rakefile"
13
+ hyperlink_all: false
14
+ line_numbers: false
15
+ locale:
16
+ locale_dir: locale
17
+ locale_name:
18
+ main_page: README.md
19
+ markup: markdown
20
+ output_decoration: true
21
+ page_dir:
22
+ show_hash: false
23
+ tab_width: 8
24
+ template_stylesheets: []
25
+ title: DeeplAPI Documentation
26
+ visibility: :protected
27
+ webcvs:
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,19 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.4
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Metrics/AbcSize:
13
+ Enabled: false
14
+
15
+ Metrics/MethodLength:
16
+ Max: 20
17
+
18
+ Layout/LineLength:
19
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ ## [0.2.0] - 2021-05-23
2
+ - Added support for the DeepL free tier which requires a different API endpoint, which will be automatically selected based on the provided API key.
3
+ - Removed erroneous limitation of this gem to the darwin-20 platform. It supports all platforms that Ruby runs on.
4
+
5
+ ## [0.1.0] - 2021-02-15
6
+
7
+ - Initial release
data/Gemfile ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in deepl_api.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+ gem "rspec-temp_dir", "~> 1.1"
12
+
13
+ gem "rubocop", "~> 1.7"
14
+ gem "rubocop-rake"
15
+ gem "rubocop-rspec"
data/Gemfile.lock ADDED
@@ -0,0 +1,73 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ deepl_api (0.2.0)
5
+ ruby-enum (~> 0.9)
6
+ thor (~> 1.1)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ ast (2.4.2)
12
+ concurrent-ruby (1.1.8)
13
+ diff-lcs (1.4.4)
14
+ i18n (1.8.9)
15
+ concurrent-ruby (~> 1.0)
16
+ parallel (1.20.1)
17
+ parser (3.0.0.0)
18
+ ast (~> 2.4.1)
19
+ rainbow (3.0.0)
20
+ rake (13.0.3)
21
+ regexp_parser (2.0.3)
22
+ rexml (3.2.4)
23
+ rspec (3.10.0)
24
+ rspec-core (~> 3.10.0)
25
+ rspec-expectations (~> 3.10.0)
26
+ rspec-mocks (~> 3.10.0)
27
+ rspec-core (3.10.1)
28
+ rspec-support (~> 3.10.0)
29
+ rspec-expectations (3.10.1)
30
+ diff-lcs (>= 1.2.0, < 2.0)
31
+ rspec-support (~> 3.10.0)
32
+ rspec-mocks (3.10.2)
33
+ diff-lcs (>= 1.2.0, < 2.0)
34
+ rspec-support (~> 3.10.0)
35
+ rspec-support (3.10.2)
36
+ rspec-temp_dir (1.1.0)
37
+ rspec (>= 3.0)
38
+ rubocop (1.9.1)
39
+ parallel (~> 1.10)
40
+ parser (>= 3.0.0.0)
41
+ rainbow (>= 2.2.2, < 4.0)
42
+ regexp_parser (>= 1.8, < 3.0)
43
+ rexml
44
+ rubocop-ast (>= 1.2.0, < 2.0)
45
+ ruby-progressbar (~> 1.7)
46
+ unicode-display_width (>= 1.4.0, < 3.0)
47
+ rubocop-ast (1.4.1)
48
+ parser (>= 2.7.1.5)
49
+ rubocop-rake (0.5.1)
50
+ rubocop
51
+ rubocop-rspec (2.3.0)
52
+ rubocop (~> 1.0)
53
+ rubocop-ast (>= 1.1.0)
54
+ ruby-enum (0.9.0)
55
+ i18n
56
+ ruby-progressbar (1.11.0)
57
+ thor (1.1.0)
58
+ unicode-display_width (2.0.0)
59
+
60
+ PLATFORMS
61
+ ruby
62
+
63
+ DEPENDENCIES
64
+ deepl_api!
65
+ rake (~> 13.0)
66
+ rspec (~> 3.0)
67
+ rspec-temp_dir (~> 1.1)
68
+ rubocop (~> 1.7)
69
+ rubocop-rake
70
+ rubocop-rspec
71
+
72
+ BUNDLED WITH
73
+ 2.2.9
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Martin Gruner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,26 @@
1
+ # deepl-api-rb
2
+
3
+ This repository contains a [Ruby](https://www.ruby-lang.org/) implementation of the [DeepL REST API](https://www.deepl.com/docs-api/).
4
+
5
+ ## Contents
6
+
7
+ - A [Ruby package](https://mgruner.github.io/deepl-api-rb-docs/DeeplAPI/DeepL.html) for easy integration into Ruby applications.
8
+ - The `deepl` [unix-style commandline application](https://mgruner.github.io/deepl-api-rb-docs/lib/deepl_api/deepl_md.html) for integration into existing toolchains without any programming effort.
9
+ - Unit and integration tests.
10
+
11
+ Please refer to the linked documentation for instructions on how to get started with the API and/or the CLI tool.
12
+
13
+ ## Features
14
+
15
+ - Query your account usage & limits information.
16
+ - Fetch the list of available source and target languages provided by DeepL.
17
+ - Translate text.
18
+
19
+ ## Not Implemented
20
+
21
+ - Support for the [(beta) document translation endpoint](https://www.deepl.com/docs-api/translating-documents/).
22
+ - Support for the [XML handling flags](https://www.deepl.com/docs-api/translating-text/) in the translation endpoint.
23
+
24
+ ## See Also
25
+
26
+ There are comparable implementations for [Rust](https://github.com/mgruner/deepl-api-rs) and [Python](https://github.com/mgruner/deepl-api-py).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "deepl_api"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/deepl_api.gemspec ADDED
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/deepl_api/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "deepl_api"
7
+ spec.version = DeeplAPI::VERSION
8
+ spec.authors = ["Martin Gruner"]
9
+ spec.email = ["mg.pub@gmx.net"]
10
+
11
+ spec.summary = "Bindings and a commandline tool for the DeepL REST API"
12
+ spec.description = "Bindings and a commandline tool for the DeepL REST API (https://www.deepl.com/docs-api/)"
13
+ spec.homepage = "https://github.com/mgruner/deepl-api-rb"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
16
+
17
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = "https://github.com/mgruner/deepl-api-rb"
21
+ spec.metadata["changelog_uri"] = "https://github.com/mgruner/deepl-api-rb/blob/next/CHANGELOG.md"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
27
+ end
28
+ spec.bindir = "exe"
29
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+
32
+ spec.add_dependency "ruby-enum", "~> 0.9"
33
+ spec.add_dependency "thor", "~> 1.1"
34
+
35
+ # For more information and examples about making a new gem, checkout our
36
+ # guide at: https://bundler.io/guides/creating_gem.html
37
+ end
data/exe/deepl ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "deepl_api/cli"
5
+
6
+ begin
7
+ DeeplAPI::CLI.start
8
+ rescue StandardError => e
9
+ warn "Error: #{e}"
10
+ exit(1)
11
+ end
data/lib/deepl_api.rb ADDED
@@ -0,0 +1,212 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "json"
5
+ require "ruby-enum"
6
+ require_relative "deepl_api/version"
7
+ require_relative "deepl_api/errors"
8
+
9
+ # Provides a lightweight wrapper for the DeepL Pro REST API.
10
+ #
11
+ # This gem contains both the [backend API](DeeplAPI/DeepL.html) and the
12
+ # [deepl command line utility](lib/deepl_api/deepl_md.html).
13
+
14
+ ## Requirements
15
+ #
16
+ # You need to have a valid [DeepL Pro Developer](https://www.deepl.com/pro#developer) account
17
+ # with an associated API key. This key must be made available to the application, e. g. via
18
+ # environment variable:
19
+ #
20
+ # ```bash
21
+ # export DEEPL_API_KEY=YOUR_KEY
22
+ # ```
23
+ #
24
+ # ## Example
25
+ #
26
+ # ```text
27
+ # require "deepl_api"
28
+ #
29
+ # deepl = DeeplAPI::DeepL.new( api_key: ENV["DEEPL_API_KEY"] )
30
+ # usage = deepl.usage_information()
31
+ # => #<DeeplAPI::UsageInformation:0x00007fcbc588cc08 @character_limit=250000, @character_count=1450>
32
+ #
33
+ # translation = deepl.translate( source_language: "DE", target_language: "EN-US", texts: ["ja"] )
34
+ # => [{"detected_source_language"=>"DE", "text"=>"yes"}]
35
+ # ```
36
+ #
37
+ # ## See Also
38
+ #
39
+ # The main API functions are documented in the DeepL class.
40
+
41
+ module DeeplAPI
42
+ # The main API entry point representing a DeepL developer account with an associated API key.
43
+ #
44
+ # Use this to create a new DeepL API client instance where multiple function calls can be performed.
45
+ # A valid `api_key` is required.
46
+ #
47
+ # Should you ever need to use more than one DeepL account in our program, then you can create one
48
+ # instance for each account / API key.
49
+ #
50
+ # ##Error Handling
51
+ #
52
+ # These methods may throw exceptions from DeeplAPI::Errors and `Net::HTTP`.
53
+ class DeepL
54
+ # Create an instance by providing a valid API key.
55
+ def initialize(api_key:)
56
+ @api_key = api_key.to_s
57
+ @api_base_url = @api_key[-3, 3].eql?(":fx") ? "https://api-free.deepl.com/v2" : "https://api.deepl.com/v2"
58
+ return unless @api_key.empty?
59
+
60
+ raise DeeplAPI::Errors::DeeplAuthorizationError, "No API key provided."
61
+ end
62
+
63
+ # Retrieve information about API usage & limits.
64
+ # This can also be used to verify an API key without consuming translation contingent.
65
+ #
66
+ # Returns a DeeplAPI::UsageInformation object.
67
+ #
68
+ # See also the [vendor documentation](https://www.deepl.com/docs-api/other-functions/monitoring-usage/).
69
+ def usage_information
70
+ data = api_call(url: "/usage")
71
+ UsageInformation.new(
72
+ character_count: data["character_count"],
73
+ character_limit: data["character_limit"]
74
+ )
75
+ end
76
+
77
+ # Retrieve all currently available source languages.
78
+ #
79
+ # See also the [vendor documentation](https://www.deepl.com/docs-api/other-functions/listing-supported-languages/).
80
+ #
81
+ # Returns a dictionary like: `{"DE" => "German", ...}`
82
+ def source_languages
83
+ languages(type: "source")
84
+ end
85
+
86
+ # Retrieve all currently available target languages.
87
+ #
88
+ # See also the [vendor documentation](https://www.deepl.com/docs-api/other-functions/listing-supported-languages/).
89
+ #
90
+ # Returns a dictionary like: `{"DE" => "German", ...}`
91
+ def target_languages
92
+ languages(type: "target")
93
+ end
94
+
95
+ # rubocop:disable Metrics/ParameterLists, Style/KeywordParametersOrder
96
+
97
+ # Translate one or more text chunks at once. You can pass in optional
98
+ # translation options if you need non-default behaviour.
99
+ #
100
+ # Please see the parameter documentation and the
101
+ # [vendor documentation](https://www.deepl.com/docs-api/translating-text/) for details.
102
+ #
103
+ # Returns a list of dictionaries for the translated content:
104
+ #
105
+ # ```ruby
106
+ # [
107
+ # {
108
+ # "detected_source_language" => "DE",
109
+ # "text" => "Yes. No.",
110
+ # },
111
+ # ...
112
+ # ]
113
+ # ```
114
+ def translate(
115
+ source_language: nil,
116
+ target_language:,
117
+ split_sentences: nil,
118
+ preserve_formatting: true,
119
+ formality: Formality::DEFAULT,
120
+ texts:
121
+ )
122
+ # rubocop:enable Metrics/ParameterLists, Style/KeywordParametersOrder
123
+
124
+ payload = {
125
+ target_lang: target_language,
126
+ text: texts
127
+ }
128
+
129
+ payload[:source_lang] = source_language unless source_language.nil?
130
+ payload[:split_sentences] = split_sentences unless split_sentences.nil?
131
+ payload[:preserve_formatting] = preserve_formatting unless preserve_formatting.nil?
132
+ payload[:formality] = formality unless formality.nil?
133
+
134
+ data = api_call(url: "/translate", payload: payload)
135
+
136
+ raise DeeplAPI::Errors::DeeplDeserializationError unless data.include?("translations")
137
+
138
+ data["translations"]
139
+ end
140
+
141
+ private
142
+
143
+ # Private method to perform the actual HTTP calls.
144
+ def api_call(url:, payload: {})
145
+ res = Net::HTTP.post_form(URI(@api_base_url + url), { **payload, auth_key: @api_key })
146
+ return JSON.parse(res.body) if res.instance_of? Net::HTTPOK
147
+ if res.instance_of?(Net::HTTPUnauthorized) || res.instance_of?(Net::HTTPForbidden)
148
+ raise DeeplAPI::Errors::DeeplAuthorizationError, "Authorization failed, is your API key correct?"
149
+ end
150
+
151
+ begin
152
+ data = JSON.parse(res.body)
153
+ if data["message"]
154
+ raise DeeplAPI::Errors::DeeplServerError,
155
+ "An error occurred while communicating with the DeepL server: '#{data["message"]}'."
156
+ end
157
+ rescue JSON::ParserError
158
+ raise DeeplAPI::Errors::DeeplServerError, res.code
159
+ end
160
+ raise DeeplAPI::Errors::DeeplServerError, res.code
161
+ end
162
+
163
+ # Private method to make API calls for the language lists
164
+ def languages(type:)
165
+ data = api_call(url: "/languages", payload: { type: type })
166
+ raise(DeeplAPI::Errors::DeeplDesearializationError) if !data.length || !data[0].include?("language")
167
+
168
+ result = {}
169
+ data.each { |i| result[i["language"]] = i["name"] }
170
+ result
171
+ end
172
+ end
173
+
174
+ # Information about API usage & limits for this account.
175
+ class UsageInformation
176
+ # How many characters can be translated per billing period, based on the account settings.
177
+ attr_reader :character_limit
178
+ # How many characters were already translated in the current billing period.
179
+ attr_reader :character_count
180
+
181
+ def initialize(character_limit:, character_count:)
182
+ @character_limit = character_limit
183
+ @character_count = character_count
184
+ end
185
+ end
186
+
187
+ # Translation option that controls the splitting of sentences before the translation.
188
+ #
189
+ # - `SplitSentences::NONE` - Don't split sentences.
190
+ # - `SplitSentences::PUNCTUATION` - Split on punctiation only.
191
+ # - `SplitSentences::PUNCTUATION_AND_NEWLINES` - Split on punctiation and newlines.
192
+ class SplitSentences
193
+ include Ruby::Enum
194
+
195
+ define :NONE, 0
196
+ define :PUNCTUATION, 1
197
+ define :PUNCTUATION_AND_NEWLINES, 2
198
+ end
199
+
200
+ # Translation option that controls the desired translation formality
201
+ #
202
+ # - `Formality::LESS` - Translate less formally.
203
+ # - `Formality::DEFAULT` - Default formality.
204
+ # - `Formality::MORE` - Translate more formally.
205
+ class Formality
206
+ include Ruby::Enum
207
+
208
+ define :LESS, "less"
209
+ define :DEFAULT, "default"
210
+ define :MORE, "more"
211
+ end
212
+ end
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "thor"
4
+ require_relative "../deepl_api"
5
+
6
+ module DeeplAPI
7
+ # This class implements the `deepl` command line utility.
8
+ class CLI < Thor
9
+ def self.exit_on_failure?
10
+ # Exit in case of missing arguments etc.
11
+ true
12
+ end
13
+
14
+ desc "usage-information", "Fetch account usage information"
15
+ def usage_information
16
+ usage = instance.usage_information
17
+ puts("Available characters per billing period: #{usage.character_limit}")
18
+ puts("Characters already translated in the current billing period: #{usage.character_count}")
19
+ end
20
+
21
+ desc "languages", "Fetch information about available source and target languages"
22
+ def languages
23
+ deepl = instance
24
+ source_langs = deepl.source_languages
25
+ target_langs = deepl.target_languages
26
+
27
+ puts("DeepL can translate from the following source languages:")
28
+ source_langs.each { |language, name| puts(" #{language.ljust(5)} (#{name})") }
29
+ puts
30
+ puts("DeepL can translate to the following target languages:")
31
+ target_langs.each { |language, name| puts(" #{language.ljust(5)} (#{name})") }
32
+ end
33
+
34
+ # rubocop:disable Metrics/MethodLength
35
+ option "source-language", desc: "The source language to use", banner: "DE"
36
+ option "target-language", desc: "The target language to use", banner: "EN", required: true
37
+ option "input-file", desc: "Read from this file rather than STDIN", banner: "path/to/file"
38
+ option "output-file", desc: "Write to this file rather than STDOUT", banner: "path/to/file"
39
+ option "preserve-formatting", desc: "Preserve source text formatting", type: :boolean
40
+ option "formality-more", desc: "Translate more formally", type: :boolean
41
+ option "formality-less", desc: "Translate less formally", type: :boolean
42
+ desc "translate", "Translate text"
43
+ def translate
44
+ formality = DeeplAPI::Formality::DEFAULT
45
+ formality = DeeplAPI::Formality::LESS if options["formality-less"]
46
+ formality = DeeplAPI::Formality::MORE if options["formality-more"]
47
+
48
+ text = if options["input-file"]
49
+ File.read(options["input-file"])
50
+ else
51
+ $stdin.read
52
+ end
53
+
54
+ result = instance.translate(
55
+ source_language: options["source-language"],
56
+ target_language: options["target-language"],
57
+ preserve_formatting: options["preserve-formatting"],
58
+ formality: formality,
59
+ texts: [text]
60
+ )
61
+
62
+ text = result.map { |entry| entry["text"] }.join
63
+
64
+ if options["output-file"]
65
+ File.write(options["output-file"], text)
66
+ else
67
+ puts text
68
+ end
69
+ end
70
+ # rubocop:enable Metrics/MethodLength
71
+
72
+ private
73
+
74
+ def instance
75
+ api_key = ENV["DEEPL_API_KEY"].to_s
76
+ if api_key.empty?
77
+ raise StandardError, "No DEEPL_API_KEY found. Please provide your API key in this environment variable."
78
+ end
79
+
80
+ DeeplAPI::DeepL.new(api_key: ENV["DEEPL_API_KEY"])
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,78 @@
1
+ # `deepl` command line utility
2
+
3
+ Unix-style commandline application for integrating the
4
+ [DeepL API](https://www.deepl.com/docs-api/) into toolchains without any programming effort.
5
+
6
+ *If you are looking for the `deepl-api` API library, please refer
7
+ to [its documentation](../../DeeplAPI/DeepL.html) instead.*
8
+
9
+ ## Requirements
10
+
11
+ You need to have a valid [DeepL Pro Developer](https://www.deepl.com/pro#developer) account
12
+ with an associated API key. This key must be made available to the application, e. g. via
13
+ environment variable:
14
+
15
+ ```bash
16
+ export DEEPL_API_KEY=YOUR_KEY
17
+ ```
18
+
19
+ ## Examples
20
+
21
+ ### Overview
22
+
23
+ To get an overview of the available commands, just invoke the program.
24
+
25
+ ```text
26
+ shell> deepl
27
+ Usage: deepl [OPTIONS] COMMAND [ARGS]...
28
+
29
+ Options:
30
+ --help Show this message and exit.
31
+
32
+ Commands:
33
+ languages
34
+ translate
35
+ usage-information
36
+ ```
37
+
38
+ You can call `deepl help translate` to get a detailed reference for the various options of the
39
+ `translate` command, for example.
40
+
41
+ ### Translating Text
42
+
43
+ By default, `deepl` reads from `STDIN` and writes to `STDOUT`, which means that you can integrate
44
+ it nicely into toolchains.
45
+
46
+ ```text
47
+ shell> echo "Please go home." | deepl translate --source-language EN --target-language DE | cat -
48
+ Bitte gehen Sie nach Hause.
49
+ ```
50
+
51
+ By providing the options `--input-file` and / or `--output-file`, you can tell `deepl` to
52
+ read from / write to files, rather than `STDIN` / `STDOUT`.
53
+
54
+ ### Retrieving Account Usage & Limits
55
+
56
+ ```text
57
+ shell> deepl usage-information
58
+ Available characters per billing period: 250000
59
+ Characters already translated in the current billing period: 3317
60
+ ```
61
+
62
+ ### Retrieving Available Languages
63
+
64
+ ```text
65
+ shell> deepl languages
66
+ DeepL can translate from the following source languages:
67
+ DE (German)
68
+ EN (English)
69
+ ES (Spanish)
70
+ ...
71
+
72
+ DeepL can translate to the following target languages:
73
+ DE (German)
74
+ EN-GB (English (British))
75
+ EN-US (English (American))
76
+ ES (Spanish)
77
+ ...
78
+ ```
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DeeplAPI
4
+ # DeepL API exception classes.
5
+ module Errors
6
+ # Base class for exceptions in this module.
7
+ class DeeplBaseError < StandardError
8
+ end
9
+
10
+ # Authorization failed.
11
+ class DeeplAuthorizationError < DeeplBaseError
12
+ end
13
+
14
+ # Received an error message from the server.
15
+ class DeeplServerError < DeeplBaseError
16
+ end
17
+
18
+ # Exception raised when deserialization the server response.
19
+ class DeeplDeserializationError < DeeplBaseError
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DeeplAPI
4
+ VERSION = "0.2.0"
5
+ end
metadata ADDED
@@ -0,0 +1,96 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: deepl_api
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - Martin Gruner
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-05-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: ruby-enum
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.9'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.9'
27
+ - !ruby/object:Gem::Dependency
28
+ name: thor
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.1'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.1'
41
+ description: Bindings and a commandline tool for the DeepL REST API (https://www.deepl.com/docs-api/)
42
+ email:
43
+ - mg.pub@gmx.net
44
+ executables:
45
+ - deepl
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - ".github/workflows/ruby.yml"
50
+ - ".gitignore"
51
+ - ".rdoc_options"
52
+ - ".rspec"
53
+ - ".rubocop.yml"
54
+ - CHANGELOG.md
55
+ - Gemfile
56
+ - Gemfile.lock
57
+ - LICENSE.txt
58
+ - README.md
59
+ - Rakefile
60
+ - bin/console
61
+ - bin/setup
62
+ - deepl_api.gemspec
63
+ - exe/deepl
64
+ - lib/deepl_api.rb
65
+ - lib/deepl_api/cli.rb
66
+ - lib/deepl_api/deepl.md
67
+ - lib/deepl_api/errors.rb
68
+ - lib/deepl_api/version.rb
69
+ homepage: https://github.com/mgruner/deepl-api-rb
70
+ licenses:
71
+ - MIT
72
+ metadata:
73
+ allowed_push_host: https://rubygems.org
74
+ homepage_uri: https://github.com/mgruner/deepl-api-rb
75
+ source_code_uri: https://github.com/mgruner/deepl-api-rb
76
+ changelog_uri: https://github.com/mgruner/deepl-api-rb/blob/next/CHANGELOG.md
77
+ post_install_message:
78
+ rdoc_options: []
79
+ require_paths:
80
+ - lib
81
+ required_ruby_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: 2.4.0
86
+ required_rubygems_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ requirements: []
92
+ rubygems_version: 3.0.9
93
+ signing_key:
94
+ specification_version: 4
95
+ summary: Bindings and a commandline tool for the DeepL REST API
96
+ test_files: []