Autopsy  4.21.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
BingTranslator.java
Go to the documentation of this file.
1 /*
2  * Autopsy Forensic Browser
3  *
4  * Copyright 2019 Basis Technology Corp.
5  * Contact: carrier <at> sleuthkit <dot> org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 package org.sleuthkit.autopsy.texttranslation.translators;
20 
21 import com.google.gson.JsonArray;
22 import com.google.gson.JsonObject;
23 import com.google.gson.JsonParser;
24 import com.squareup.okhttp.MediaType;
25 import com.squareup.okhttp.OkHttpClient;
26 import com.squareup.okhttp.Request;
27 import com.squareup.okhttp.RequestBody;
28 import com.squareup.okhttp.Response;
29 import java.io.IOException;
30 import javax.swing.JPanel;
31 import org.openide.util.NbBundle.Messages;
32 import org.openide.util.lookup.ServiceProvider;
37 
42 @ServiceProvider(service = TextTranslator.class)
43 public class BingTranslator implements TextTranslator {
44 
45  //The target language follows the to= in the string below. You can include multiple target
46  //languages separated by commas. A full list of supported languages is here:
47  //https://docs.microsoft.com/en-us/azure/cognitive-services/translator/language-support
48  private static final String BASE_URL = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=";
49  private static final int MAX_STRING_LENGTH = 5000;
51  private final BingTranslatorSettings settings = new BingTranslatorSettings();
52  // This sends messages to Microsoft.
53  private final OkHttpClient CLIENT = new OkHttpClient();
54 
58  public BingTranslator() {
59 
60  }
61 
71  static String getTranlatorUrl(String languageCode) {
72  return BASE_URL + languageCode;
73  }
74 
86  public String postTranslationRequest(String string) throws IOException {
87  MediaType mediaType = MediaType.parse("application/json");
88 
89  JsonArray jsonArray = new JsonArray();
90  JsonObject jsonObject = new JsonObject();
91  jsonObject.addProperty("Text", string);
92  jsonArray.add(jsonObject);
93  String bodyString = jsonArray.toString();
94 
95  RequestBody body = RequestBody.create(mediaType,
96  bodyString);
97  Request request = new Request.Builder()
98  .url(getTranlatorUrl(settings.getTargetLanguageCode())).post(body)
99  .addHeader("Ocp-Apim-Subscription-Key", settings.getAuthenticationKey())
100  .addHeader("Content-type", "application/json").build();
101  Response response = CLIENT.newCall(request).execute();
102  return response.body().string();
103  }
104 
105  @Override
106  public String translate(String string) throws TranslationException {
107  if (settings.getAuthenticationKey() == null || settings.getAuthenticationKey().isEmpty()) {
108  throw new TranslationException("Bing Translator has not been configured, authentication key needs to be specified");
109  }
110  String toTranslate = string.trim();
111  //Translates some text into English, without specifying the source langauge.
112 
113  //Google Translate required us to replace (\r\n|\n) with <br />
114  //but Bing Translator doesn not have that requirement.
115  //The free account has a maximum file size. If you have a paid account,
116  //you probably still want to limit file size to prevent accidentally
117  //translating very large documents.
118  if (toTranslate.length() > MAX_STRING_LENGTH) {
119  toTranslate = toTranslate.substring(0, MAX_STRING_LENGTH);
120  }
121 
122  try {
123  String response = postTranslationRequest(toTranslate);
124  return parseJSONResponse(response);
125  } catch (IOException | TranslationException ex) {
126  throw new TranslationException("Exception while attempting to translate using BingTranslator", ex);
127  }
128  }
129 
130  @Messages({"BingTranslator.name.text=Bing Translator"})
131  @Override
132  public String getName() {
133  return Bundle.BingTranslator_name_text();
134  }
135 
136  @Override
138  public JPanel getSettingsPanel() {
139  if(settingsPanel == null) {
140  settingsPanel = new BingTranslatorSettingsPanel(settings.getAuthenticationKey(), settings.getTargetLanguageCode());
141  }
142  return settingsPanel;
143  }
144 
145  @Override
147  settings.setAuthenticationKey(settingsPanel.getAuthenticationKey());
148  settings.setTargetLanguageCode(settingsPanel.getTargetLanguageCode());
149  settings.saveSettings();
150  }
151 
162  private String parseJSONResponse(String json_text) throws TranslationException {
163  /*
164  * Here is an example of the text we get from Bing when input is "gato",
165  * the Spanish word for cat: [ { "detectedLanguage": { "language": "es",
166  * "score": 1.0 }, "translations": [ { "text": "cat", "to": "en" } ] } ]
167  */
168  try {
169  JsonArray responses = JsonParser.parseString(json_text).getAsJsonArray();
170  //As far as I know, there's always exactly one item in the array.
171  JsonObject response0 = responses.get(0).getAsJsonObject();
172  JsonArray translations = response0.getAsJsonArray("translations");
173  JsonObject translation0 = translations.get(0).getAsJsonObject();
174  return translation0.get("text").getAsString();
175  } catch (IllegalStateException | ClassCastException | NullPointerException | IndexOutOfBoundsException e) {
176  throw new TranslationException("JSON text does not match Bing Translator scheme: " + e);
177  }
178  }
179 
180  @Override
181  public int getMaxTextChars() {
182  return MAX_STRING_LENGTH;
183  }
184 }

Copyright © 2012-2022 Basis Technology. Generated on: Tue Feb 6 2024
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.