软件构造 作业1
实验一:百度机器翻译SDK实验(2023.11.29日完成)
任务一:下载配置百度翻译Java相关库及环境(占10%)。
任务二:了解百度翻译相关功能并进行总结,包括文本翻译-通用版和文本翻译-词典版(占20%)。
任务三:完成百度翻译相关功能代码并测试调用,要求可以实现中文翻译成英文,英文翻译成中文(占30%)。
任务四:完成百度翻译GUI相关功能代码并测试调用,要求可以实现中文翻译成英文,英文翻译成中文(占30%)。
实验总结:(占10%)
实验效果样例图:
参考资料:https://ai.baidu.com/ai-doc/index/MT
https://cloud.baidu.com/doc/MT/index.html
https://console.bce.baidu.com/tools/?_=1669807341890#/api?product=AI&project=%E6%9C%BA%E5%99%A8%E7%BF%BB%E8%AF%91&parent=%E9%89%B4%E6%9D%83%E8%AE%A4%E8%AF%81%E6%9C%BA%E5%88%B6&api=oauth%2F2.0%2Ftoken&method=post
package org.example.test1;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import okhttp3.*;
import java.io.IOException;
public class TranslationApp extends Application {
public static final String API_KEY = "P7S23q4f4FCRVV6BSCFaOemO";
public static final String SECRET_KEY = "ExMjapgueKChqEsshHj2TpwzjPiKz8o5";
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("实时翻译");
TextField inputTextField = new TextField();
Label outputLabel = new Label();
ComboBox<String> translationDirectionComboBox = new ComboBox<>();
translationDirectionComboBox.getItems().addAll("中译英", "英译中","中译日","中译意大利语","英译日");
translationDirectionComboBox.setValue("中译英");
Button translateButton = new Button("翻译");
translateButton.setOnAction(e -> {
try {
String userInput = inputTextField.getText();
String translationResult = translate(userInput, translationDirectionComboBox.getValue());
outputLabel.setText("翻译结果: " + translationResult);
} catch (IOException ioException) {
ioException.printStackTrace();
}
});
// 使用GridPane重新布局
GridPane gridPane = new GridPane();
gridPane.setHgap(10);
gridPane.setVgap(10);
gridPane.setPadding(new Insets(10, 10, 10, 10));
gridPane.add(new Label("输入文本:"), 0, 0);
gridPane.add(inputTextField, 1, 0);
gridPane.add(new Label("翻译方向:"), 0, 1);
gridPane.add(translationDirectionComboBox, 1, 1);
gridPane.add(new Label(""), 0, 2); // 空行
gridPane.add(new Label(""), 1, 2); // 空行
gridPane.add(translateButton, 5, 0);
VBox vbox = new VBox(gridPane, outputLabel);
vbox.setSpacing(10);
Scene scene = new Scene(vbox, 400, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* 翻译方法
*/
private String translate(String userInput, String translationDirection) throws IOException {
String targetLanguage;
targetLanguage = null;
String translationLanguage = null;
if ( translationDirection.equals("中译英") ){
targetLanguage = "zh";
translationLanguage = "en";
}
else if(translationDirection.equals("英译中")){
targetLanguage = "en";
translationLanguage = "zh";
}
else if (translationDirection.equals("中译日")) {
targetLanguage = "zh";
translationLanguage = "jp";
}
else if (translationDirection.equals("中译意大利语")) {
targetLanguage = "zh";
translationLanguage = "spa";
}
else if(translationDirection.equals("英译日")){
targetLanguage = "en";
translationLanguage = "jp";
}
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"from\":\""+targetLanguage+"\",\"to\":\""+translationLanguage+"\",\"q\":\"" + userInput + "\"}");
// RequestBody body = RequestBody.create(mediaType, "{\"from\":\"zh\",\"to\":\"en\",\"q\":\"" + userInput + "\"}");
Request request = new Request.Builder()
.url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + getAccessToken())
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
String responseString = response.body().string();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseString);
return jsonNode.get("result").get("trans_result").get(0).get("dst").asText();
}
/**
* 获取 Access Token 的方法
*/
private String getAccessToken() throws IOException {
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
+ "&client_secret=" + SECRET_KEY);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/oauth/2.0/token")
.method("POST", body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
return new ObjectMapper().readTree(response.body().string()).get("access_token").asText();
}
}