Skip to content

Commit

Permalink
Add sub-command enum for text and document translation
Browse files Browse the repository at this point in the history
  • Loading branch information
kojix2 committed Jan 30, 2024
1 parent 7fdf369 commit 702ca68
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
7 changes: 6 additions & 1 deletion src/deepl/options.cr
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
module Deepl
enum SubCmd : UInt8
Text
Document
end

struct Options
property target_lang : String = "EN"
property source_lang : String = "AUTO"
property input : String = ""
property doc : Bool = false
property sub_command : SubCmd = SubCmd::Text
end
end
2 changes: 1 addition & 1 deletion src/deepl/parser.cr
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ module Deepl
@translator = translator
self.banner = "Usage: deepl [arguments]"
on("doc", "Upload and translate a document") do
opt.doc = true
opt.sub_command = SubCmd::Document
end
on("-i", "--input [TEXT]", "Input text") do |text|
opt.input = text
Expand Down
18 changes: 13 additions & 5 deletions src/deepl/translator.cr
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,10 @@ module Deepl
end

def translate(option)
if option.doc
case option.sub_command
when SubCmd::Document
translate_document(option)
else
when SubCmd::Text
translate_text(option.input, option.target_lang, option.source_lang)
end
end
Expand All @@ -70,17 +71,24 @@ module Deepl
end

def translate_document(option)
pp option
io = IO::Memory.new
builder = HTTP::FormData::Builder.new(io)
builder.field("target_lang", option.target_lang)
builder.field("source_lang", option.source_lang) unless option.source_lang == "AUTO"
file = File.open(option.input)
filename = File.basename(option.input)
builder.file("file", file, HTTP::FormData::FileMetadata.new(filename: filename))
metadata = HTTP::FormData::FileMetadata.new(filename: filename)
headers = HTTP::Headers{"Content-Type" => "text/plain"}
builder.file("file", file, metadata, headers)
builder.finish

pp execute_post_request(API_URL_DOCUMENT, io, http_headers_for_document(builder.content_type))
response = execute_post_request(API_URL_DOCUMENT, io, http_headers_for_document(builder.content_type))
parsed_response = JSON.parse(response.body)
begin
parsed_response.dig("document_id")
rescue
raise RequestError.new("Error: #{parsed_response}")
end
end

private def execute_post_request(url = url, body = body, headers = headers)
Expand Down

0 comments on commit 702ca68

Please sign in to comment.