Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Yandex Translator #27

Merged
merged 10 commits into from Jan 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions config/locales/server.en.yml
Expand Up @@ -4,6 +4,7 @@ en:
translator: "The provider of the translation service."
translator_azure_subscription_key: "Azure Subscription Key"
translator_google_api_key: "Google API Key"
translator_yandex_api_key: "Yandex API Key"
translator:
failed: "The translator is unable to translate this language."
not_supported: "This language is not supported by the translator."
Expand Down
1 change: 1 addition & 0 deletions config/locales/server.es.yml
Expand Up @@ -4,6 +4,7 @@ es:
translator: "El proveedor del servicio de traducción."
translator_azure_subscription_key: "Azure Subscription Key"
translator_google_api_key: "Google Api Key"
translator_yandex_api_key: "Yandex API Key"
translator:
failed: "El traductor no fue capaz de traducir este idioma."
not_supported: "Este idioma no está disponible en el traductor."
Expand Down
3 changes: 3 additions & 0 deletions config/settings.yml
Expand Up @@ -9,7 +9,10 @@ plugins:
choices:
- Microsoft
- Google
- Yandex
translator_azure_subscription_key:
default: ''
translator_google_api_key:
default: ''
translator_yandex_api_key:
default: ''
1 change: 1 addition & 0 deletions plugin.rb
Expand Up @@ -17,6 +17,7 @@ module ::DiscourseTranslator

autoload :Microsoft, "#{Rails.root}/plugins/discourse-translator/services/discourse_translator/microsoft"
autoload :Google, "#{Rails.root}/plugins/discourse-translator/services/discourse_translator/google"
autoload :Yandex, "#{Rails.root}/plugins/discourse-translator/services/discourse_translator/yandex"

class Engine < ::Rails::Engine
engine_name PLUGIN_NAME
Expand Down
197 changes: 197 additions & 0 deletions services/discourse_translator/yandex.rb
@@ -0,0 +1,197 @@
# frozen_string_literal: true

require_relative 'base'

module DiscourseTranslator
class Yandex < Base
TRANSLATE_URI = "https://translate.yandex.net/api/v1.5/tr.json/translate"
DETECT_URI = "https://translate.yandex.net/api/v1.5/tr.json/detect"

SUPPORTED_LANG = {
pt_BR: 'pt',
pl_PL: 'pl',
no_NO: 'no',
fa_IR: 'fa',
zh_CN: 'zh',
zh_TW: 'zh',
tr_TR: 'tr',
en_US: 'en',
en_GB: 'en',
az: 'az',
ml: 'ml',
sq: 'sq',
mt: 'mt',
am: 'am',
mk: 'mk',
en: 'en',
mi: 'mi',
ar: 'ar',
mr: 'mr',
hy: 'hy',
mhr: 'mhr',
af: 'af',
mn: 'mn',
eu: 'eu',
de: 'de',
ba: 'ba',
ne: 'ne',
be: 'be',
no: 'no',
bn: 'bn',
pa: 'pa',
my: 'my',
pap: 'pap',
bg: 'bg',
fa: 'fa',
bs: 'bs',
pl: 'pl',
cy: 'cy',
pt: 'pt',
hu: 'hu',
ro: 'ro',
vi: 'vi',
ru: 'ru',
ht: 'ht',
ceb: 'ceb',
gl: 'gl',
sr: 'sr',
nl: 'nl',
si: 'si',
mrj: 'mrj',
sk: 'sk',
el: 'el',
sl: 'sl',
ka: 'ka',
sw: 'sw',
gu: 'gu',
su: 'su',
da: 'da',
tg: 'tg',
he: 'he',
th: 'th',
yi: 'yi',
tl: 'tl',
id: 'id',
ta: 'ta',
ga: 'ga',
tt: 'tt',
it: 'it',
te: 'te',
is: 'is',
tr: 'tr',
es: 'es',
udm: 'udm',
kk: 'kk',
uz: 'uz',
kn: 'kn',
uk: 'uk',
ca: 'ca',
ur: 'ur',
ky: 'ky',
fi: 'fi',
zh: 'zh',
fr: 'fr',
ko: 'ko',
hi: 'hi',
xh: 'xh',
hr: 'hr',
km: 'km',
cs: 'cs',
lo: 'lo',
sv: 'sv',
la: 'la',
gd: 'gd',
lv: 'lv',
et: 'et',
lt: 'lt',
eo: 'eo',
lb: 'lb',
jv: 'jv',
mg: 'mg',
ja: 'ja',
ms: 'ms',
}

def self.access_token_key
"yandex-translator"
end

def self.access_token
SiteSetting.translator_yandex_api_key || (raise TranslatorError.new("NotFound: Yandex API Key not set."))
end
CvX marked this conversation as resolved.
Show resolved Hide resolved

def self.detect(post)
post.custom_fields[DiscourseTranslator::DETECTED_LANG_CUSTOM_FIELD] ||= begin
query = default_query.merge(
"text" => post.raw
)

uri = URI(DETECT_URI)
uri.query = URI.encode_www_form(query)

response_body = result(uri.to_s, "", default_headers)

response_body["lang"]
end
end

def self.translate(post)
detected_lang = detect(post)

if !SUPPORTED_LANG.keys.include?(detected_lang.to_sym) &&
!SUPPORTED_LANG.values.include?(detected_lang.to_s)

raise TranslatorError.new(I18n.t('translator.failed'))
end

translated_text = from_custom_fields(post) do
query = default_query.merge(
"lang" => "#{detected_lang}-#{locale}",
"text" => post.cooked,
"format" => "html"
)

uri = URI(TRANSLATE_URI)
uri.query = URI.encode_www_form(query)

response_body = result(uri.to_s, "", default_headers)
response_body["text"][0]
end

[detected_lang, translated_text]
end

private

def self.locale
SUPPORTED_LANG[I18n.locale] || (raise I18n.t("translator.not_supported"))
end

def self.post(uri, body, headers = {})
Excon.post(uri, body: body, headers: headers)
CvX marked this conversation as resolved.
Show resolved Hide resolved
end

def self.result(uri, body, headers)
response = post(uri, body, headers)
response_body = JSON.parse(response.body)

if response.status != 200
raise TranslatorError.new(response_body)
else
response_body
end
end

def self.default_headers
{
'Content-Type' => 'application/x-www-form-urlencoded'
}
end

def self.default_query
{
key: access_token
}
end
end
end
51 changes: 51 additions & 0 deletions spec/services/yandex_spec.rb
@@ -0,0 +1,51 @@
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe DiscourseTranslator::Yandex do
let(:mock_response) { Struct.new(:status, :body) }

describe '.access_token' do
describe 'when set' do
api_key = '12345'
before { SiteSetting.translator_yandex_api_key = api_key }

it 'should return back translator_yandex_api_key' do
expect(described_class.access_token).to eq(api_key)
end
end
end

describe '.detect' do
let(:post) { Fabricate(:post) }

it 'should store the detected language in a custom field' do
detected_lang = 'en'
described_class.expects(:access_token).returns('12345')
Excon.expects(:post).returns(mock_response.new(200, %{ { "code": 200, "lang": "#{detected_lang}" } })).once
expect(described_class.detect(post)).to eq(detected_lang)

2.times do
expect(
post.custom_fields[::DiscourseTranslator::DETECTED_LANG_CUSTOM_FIELD]
).to eq(detected_lang)
end
end
end

describe '.translate' do
let(:post) { Fabricate(:post) }

it 'raises an error on failure' do
described_class.expects(:access_token).returns('12345')
described_class.expects(:detect).returns('en')

Excon.expects(:post).returns(mock_response.new(
400,
{ error: 'something went wrong', error_description: 'you passed in a wrong param' }.to_json
))

expect { described_class.translate(post) }.to raise_error DiscourseTranslator::TranslatorError
end
end
end