基于百度云API的简易机器翻译

发布时间 2023-11-30 08:54:44作者: (该昵称暂可见)

import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.regex.Pattern;

public class Translation extends JFrame {
private static final String API_KEY = "hxYwOsG4T3N2GSpycshM12CX";
private static final String SECRET_KEY = "eSUc55mPGkPl0sWpyd1mQdWbomE9eHho";

private final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

private JTextArea inputTextArea;
private JButton translateButton;
private JTextArea outputTextArea;

public Translation() {
setTitle("文本翻译");
setSize(600, 400);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));

JLabel titleLabel = new JLabel("输入要翻译的文本:");
titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
titleLabel.setMinimumSize(new Dimension(1, 50)); // 增加标签高度
centerPanel.add(titleLabel);

inputTextArea = new JTextArea(10, 40);
inputTextArea.setLineWrap(true);
inputTextArea.setAlignmentX(Component.CENTER_ALIGNMENT);
centerPanel.add(inputTextArea);

translateButton = new JButton("翻译");
translateButton.setAlignmentX(Component.CENTER_ALIGNMENT);
translateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
translateText();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
});
centerPanel.add(translateButton);

outputTextArea = new JTextArea(10, 40);
outputTextArea.setLineWrap(true);
outputTextArea.setAlignmentX(Component.CENTER_ALIGNMENT);
centerPanel.add(outputTextArea);

add(centerPanel, BorderLayout.CENTER);
}

private void translateText() throws IOException {
String inputText = inputTextArea.getText();

String fromLang, toLang;
if (containsChinese(inputText)) {
fromLang = "zh";
toLang = "en";
} else {
fromLang = "en";
toLang = "zh";
}

MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"from\":\"" + fromLang + "\",\"to\":\"" + toLang + "\",\"q\":\"" + inputText + "\"}");
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();

try {
Response response = HTTP_CLIENT.newCall(request).execute();
String translationResult = response.body().string();

// 解析JSON并提取dst字段
JSONObject json = new JSONObject(translationResult);
JSONArray transResultArray = json.getJSONObject("result").getJSONArray("trans_result");
StringBuilder dstText = new StringBuilder();
for (int i = 0; i < transResultArray.length(); i++) {
String dst = transResultArray.getJSONObject(i).getString("dst");
dstText.append(dst).append("\n");
}

outputTextArea.setText(dstText.toString());
} catch (IOException e) {
e.printStackTrace();
}
}

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();

try {
Response response = HTTP_CLIENT.newCall(request).execute();
return new JSONObject(response.body().string()).getString("access_token");
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

private boolean containsChinese(String str) {
Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]");
return pattern.matcher(str).find();
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
Translation translationGUI = new Translation();
translationGUI.setVisible(true);
}
});
}
}