Created
August 28, 2018 10:44
-
-
Save HHRy/3cc192e50e188ea7da4b0815a02ad1d9 to your computer and use it in GitHub Desktop.
Simple wrapper with caching for Amazon Translate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Simple wrapper around the amazon translate SDK that also tries to | |
# implement basic caching to avoid sending (and being charged for) | |
# duplicate translations. | |
# | |
# Supports JA, EN at the moment only. | |
# | |
require 'digest/sha2' | |
module AmazonTranslate | |
class <<self | |
def to_ja(string) | |
cached_ja_tanslation(string) || translate('en', 'ja', string) | |
end | |
def to_en(string) | |
cached_en_tanslation(string) || translate('ja', 'en', string) | |
end | |
private | |
def initialize_caches! | |
@en = {} if @en.nil? | |
@ja = {} if @ja.nil? | |
end | |
def cached_en_tanslation(string) | |
initialize_caches! | |
@en[Digest::SHA2.hexdigest(string)] | |
end | |
def cached_ja_tanslation(string) | |
initialize_caches! | |
@ja[Digest::SHA2.hexdigest(string)] | |
end | |
def translate(from, to, string) | |
req = { | |
text: string, | |
source_language_code: from, | |
target_language_code: to | |
} | |
client = Aws::Translate::Client.new(region: 'us-east-1') | |
translated = client.translate_text(req).translated_text | |
if to == 'ja' | |
@ja[Digest::SHA2.hexdigest(string)] = translated | |
else | |
@en[Digest::SHA2.hexdigest(string)] = translated | |
end | |
translated | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment