百度翻译优化之后

package com.example;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

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

public class fanyi extends JFrame {

private static final String API_KEY = "dzjU0EZolFp0hpYlKD8ckSpk";
private static final String SECRET_KEY = "XbMab4iuLO4dkkKACNDQw5nONYRjTyv4";

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

private JTextArea inputTextArea;
private JTextArea outputTextArea;
private JComboBox<String> fromLanguageComboBox;
private JComboBox<String> toLanguageComboBox;


public fanyi() {
// Set up the main frame
setTitle("Translation GUI");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Set up the language options
String[] languages = {"en", "zh"};
fromLanguageComboBox = new JComboBox<>(languages);
toLanguageComboBox = new JComboBox<>(languages);

// Create components
inputTextArea = new JTextArea(10, 40);
inputTextArea.setFont(new Font("SimSun", Font.PLAIN, 16)); // Set font size to 16
outputTextArea = new JTextArea("Translation results will be displayed here.");
outputTextArea.setFont(new Font("SimSun", Font.PLAIN, 16)); // Set font size to 16
outputTextArea.setForeground(new Color(34, 139, 34)); // Set text color to green
outputTextArea.setEditable(false);

JButton translateButton = new JButton("Translate");
translateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
translateText();
}
});

// Set up the layout
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

JPanel inputPanel = new JPanel(new BorderLayout());
inputPanel.add(new JLabel("Input Text:"), BorderLayout.NORTH);
inputPanel.add(new JScrollPane(inputTextArea), BorderLayout.CENTER);

JPanel translationOptionsPanel = new JPanel();
translationOptionsPanel.add(fromLanguageComboBox);
translationOptionsPanel.add(new JLabel("->"));
translationOptionsPanel.add(toLanguageComboBox);

JPanel buttonPanel = new JPanel();
buttonPanel.add(translateButton);

mainPanel.add(inputPanel, BorderLayout.NORTH);
mainPanel.add(outputTextArea, BorderLayout.CENTER);
mainPanel.add(translationOptionsPanel, BorderLayout.WEST);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);

// Add components to the frame
add(mainPanel);

// Make the frame visible
setVisible(true);
}

private void translateText() {
try {
String inputText = inputTextArea.getText();
String accessToken = getAccessToken();
String translationResult = performTranslation(inputText, accessToken);
System.out.println(inputText);
String translatedText = extractTranslation(translationResult);
outputTextArea.setText(translatedText);
} catch (IOException e) {
e.printStackTrace();
outputTextArea.setText("Error during translation. Check the console for details.");
}
}
private String performTranslation(String text, String accessToken) throws IOException {
String fromLanguage = (String) fromLanguageComboBox.getSelectedItem();
String toLanguage = (String) toLanguageComboBox.getSelectedItem();
MediaType mediaType = MediaType.parse("application/json");
String jsonBody = String.format( "{\"from\":\"%s\",\"to\":\"%s\",\"q\":\"" + text + "\"}", fromLanguage, toLanguage);
RequestBody body = RequestBody.create(mediaType, jsonBody);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + accessToken)
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
return response.body().string();

}

private String extractTranslation(String translationResult) {
JsonObject json = JsonParser.parseString(translationResult).getAsJsonObject();
JsonObject resultObject = json.getAsJsonObject("result");
System.out.println(json);
JsonArray translations = resultObject.getAsJsonArray("trans_result");
System.out.println(translations);
JsonObject translation = translations.get(0).getAsJsonObject();
if (json.has("error_code")) {
// 检查是否包含错误码,如果是,处理错误信息
int errorCode = json.get("error_code").getAsInt();
String errorMsg = json.get("error_msg").getAsString();
System.out.println("Translation error: " + errorCode + ", " + errorMsg);
return "Translation not available";
}
if (json.has("trans_result")) {

if (!translations.isJsonNull() && translations.size() > 0) {

if (translation.has("dst")) {
return translation.get("dst").getAsString();
}
}
}
return translation.get("dst").getAsString();
}


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();
try {
return new JSONObject(response.body().string()).getString("access_token");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new fanyi();
}
});
}
}

 

posted @ 2023-12-09 23:01  布吉岛???  阅读(14)  评论(0编辑  收藏  举报