Class: MicrosoftCognitiveServices

Inherits:
NuixTranslator show all
Defined in:
Ruby/translation.nuixscript/Translators/microsoft_cognitive_services.rb

Overview

Class for translating items using Microsoft Cognitive Services.

Constant Summary collapse

NAME =
'Microsoft Cognitive Services'.freeze
LANGUAGES =
{ 'af' =>	'Afrikaans',
'ar' =>	'Arabic',
'bn' =>	'Bangla',
'bs' =>	'Bosnian (Latin)',
'bg' =>	'Bulgarian',
'yue' =>	'Cantonese (Traditional)',
'ca' =>	'Catalan',
'zh-Hans' =>	'Chinese Simplified',
'zh-Hant' =>	'Chinese Traditional',
'hr' =>	'Croatian',
'cs' =>	'Czech',
'da' =>	'Danish',
'nl' =>	'Dutch',
'en' =>	'English',
'et' =>	'Estonian',
'fj' =>	'Fijian',
'fil' =>	'Filipino',
'fi' =>	'Finnish',
'fr' =>	'French',
'de' =>	'German',
'el' =>	'Greek',
'ht' =>	'Haitian Creole',
'he' =>	'Hebrew',
'hi' =>	'Hindi',
'mww' =>	'Hmong Daw',
'hu' =>	'Hungarian',
'is' =>	'Icelandic',
'id' =>	'Indonesian',
'it' =>	'Italian',
'ja' =>	'Japanese',
'sw' =>	'Kiswahili',
'tlh' =>	'Klingon',
'tlh-Qaak' =>	'Klingon (plqaD)',
'ko' =>	'Korean',
'lv' =>	'Latvian',
'lt' =>	'Lithuanian',
'mg' =>	'Malagasy',
'ms' =>	'Malay',
'mt' =>	'Maltese',
'nb' =>	'Norwegian',
'fa' =>	'Persian',
'pl' =>	'Polish',
'pt' =>	'Portuguese',
'otq' =>	'Queretaro Otomi',
'ro' =>	'Romanian',
'ru' =>	'Russian',
'sm' =>	'Samoan',
'sr-Cyrl' =>	'Serbian (Cyrillic)',
'sr-Latn' =>	'Serbian (Latin)',
'sk' =>	'Slovak',
'sl' =>	'Slovenian',
'es' =>	'Spanish',
'sv' =>	'Swedish',
'ty' =>	'Tahitian',
'ta' =>	'Tamil',
'te' =>	'Telugu',
'th' =>	'Thai',
'to' =>	'Tongan',
'tr' =>	'Turkish',
'uk' =>	'Ukrainian',
'ur' =>	'Urdu',
'vi' =>	'Vietnamese',
'cy' =>	'Welsh',
'yua' =>	'Yucatec Maya' }.freeze

Constants inherited from NuixTranslator

NuixTranslator::SCRIPT_DIR

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from NuixTranslator

#add_translation, #advance, #get_new_text, #get_original_text, #translation_message, translators

Constructor Details

#initializeMicrosoftCognitiveServices

Creates a new NuixTranslator using Microsoft Cognitive Services API.



78
79
80
81
82
83
84
# File 'Ruby/translation.nuixscript/Translators/microsoft_cognitive_services.rb', line 78

def initialize
  super(NAME, LANGUAGES)
  @main_tab.appendTextField('api_key', 'API Key', '')
  # load langs from CSV?
  add_translation
  @input.validateBeforeClosing { |v| validate_input(v) }
end

Class Method Details

.nameObject



8
9
10
# File 'Ruby/translation.nuixscript/Translators/microsoft_cognitive_services.rb', line 8

def self.name
  NAME
end

Instance Method Details

#ms_translate(text) ⇒ String? (private)

Translates text using Microsoft Cognitive Services.

Parameters:

  • text (String)

    original text

Returns:

  • (String, nil)

    translated text, or nil if there was an error



105
106
107
108
109
110
111
112
113
114
115
116
# File 'Ruby/translation.nuixscript/Translators/microsoft_cognitive_services.rb', line 105

def ms_translate(text)
  https = Net::HTTP.new(@uri.host, @uri.port)
  https.use_ssl = true
  begin
    req = Net::HTTP::Post.new(@uri.request_uri, @headers)
    req.body = [{ 'Text' => text }].to_json
    response = https.request(req)
    return response_body(response)
  rescue StandardError => ex
    puts "ERROR: #{ex.message}"
  end
end

#progress_dialogObject (private)

Progress dialog loop for processing items.



119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'Ruby/translation.nuixscript/Translators/microsoft_cognitive_services.rb', line 119

def progress_dialog
  ProgressDialog.forBlock do |pd|
    super(pd, 'Translating')
    $current_case.with_write_access do
      @items.each_with_index do |item, index|
        break if advance(index, "Item GUID: #{item.getGuid}").nil?

        translate(item)
      end
    end
    pd.setCompleted
  end
end

#response_body(response) ⇒ String? (private)

Handles response from Net::HTTPSuccess

Parameters:

  • response (Net::HTTPResponse)

    from Microsoft Cognitive Services

Returns:

  • (String, nil)

    translated text, or nil if an error occured



137
138
139
140
141
142
143
144
145
146
147
148
# File 'Ruby/translation.nuixscript/Translators/microsoft_cognitive_services.rb', line 137

def response_body(response)
  case response
  when Net::HTTPSuccess
    return JSON.parse(response.body)[0]['translations'][0]['text']
  when Net::HTTPUnauthorized
    msg = 'invalid API key?'
  when Net::HTTPServerError
    msg = 'try again later?'
  end
  @progress.logMessage("ERROR: #{response.message}")
  @progress.logMessage(msg) unless msg.nil?
end

#run(items) ⇒ Object

Runs Translator on the items.

Parameters:

  • items (Set<Item>)


89
90
91
92
93
94
95
96
97
# File 'Ruby/translation.nuixscript/Translators/microsoft_cognitive_services.rb', line 89

def run(items)
  return nil if super(items).nil?

  url = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to='
  @uri = URI.parse(url + @langs.key(@settings['translation_language']))
  @headers = { 'Ocp-Apim-Subscription-Key' => @settings['api_key'] }
  ['Content-Type', 'Accept'].each { |k| @headers[k] = 'application/json' }
  progress_dialog
end

#translate(item) ⇒ Object (private)

Translates item using Microsoft Cognitive Services.

Parameters:

  • item (Item)

    a Nuix item



153
154
155
156
157
158
159
160
# File 'Ruby/translation.nuixscript/Translators/microsoft_cognitive_services.rb', line 153

def translate(item)
  @progress.setMainStatusAndLogIt('Translating')
  text = get_original_text(item)
  return nil if text.empty?

  translated = ms_translate(text)
  super(item, translated) unless translated.nil? || translated.empty?
end

#validate_input(values) ⇒ true, false (private)

Validation function for input.

Checks for API key.

Parameters:

  • values (Hash)

    input values

Returns:

  • (true, false)

    if in validate state



167
168
169
170
171
172
# File 'Ruby/translation.nuixscript/Translators/microsoft_cognitive_services.rb', line 167

def validate_input(values)
  return true unless values['api_key'].strip.empty?

  CommonDialogs.showWarning("Please provide a #{NAME} API Key.")
  false
end