Java calls Baidu Translation API and Youdao Translation API for translation

Table of contents

Interface writing

Call Baidu API

Call Youdao API

source code


Interface writing

We first need to design the GUI interface of this translation program. We write a class inherited from the JFrame class to display the main window of the program, set the name and size of the window, and set the program to terminate when the window is closed. In order to make the interface beautiful, We set the layout to flow layout, center aligned.

Next, prepare to use four panels as containers to divide the entire interface into four rows.

First, the first line displays the label and input box of the original Chinese text, as well as a translation button.

The second line displays the Baidu translation label and a line of text display boxes used to display the Baidu translated translation.

Similarly, the third line displays the Youdao translation label and text display box.

The last line shows the same part of the label and text display box.

Finally, in the main function, the display of the window is executed on the Swing event scheduling thread. For convenience, a lambda anonymous function is used here.

Run the program to see the display effect. It can be seen that the aesthetics are still there, because we actually determined the size of the window and the length of the components after many tests, making the entire page look neater.

Call Baidu API

Next we need to call the translation API to implement the function.

First use a Baidu account to log in to the Baidu Translation Development Platform,Baidu Translation Open Platform (baidu.com), and register as a developer.

Then open the universal translation API service onBaidu Translation Open Platform (baidu.com).

Just choose to activate the standard version.

Write a little bit about the application form.

Then you can see the APP ID and key required to call the API in the management console.

According to the tutorial of the official documentUniversal Translation API Access Document, we need to splice out the request parameter encryption. Here we can use the one written by Baidu DEMO, download the Java version of the demo.

After unzipping, put the package com in our project source code directory.

Then import this package into the project.

Then call the API to translate Chinese into English by passing in the APP ID and key.

We add a listening event to the click button. When the button is clicked, this lambda anonymous function is executed. In the function, the text translated by Baidu is displayed on the text box.

Run the program to test Baidu Translation. The result returned does not seem to be the ideal result we want.

By consulting the official documentation, we know that the returned result is a JSON object.

There is no built-in JSON parsing in Java. If you want to process JSON, you must use a third-party library. Here we can simply use regular expressions to extract the translation results.

Run the program again, this can output the translation results we want.

Call Youdao API

In the same way, if you need to call Youdao Translation API, we need to perform similar process operations.

Register as a developer atYoudao Zhiyun (youdao.com).

Then create the app.

After creating the application, you can view the application ID and application key.

Also download the Java version demo written by Youdao.

We put Youdao's software package into the project and put it together with Baidu's software package.

Then put pom.xml in the project directory, click to load the maven project, pull out TranslateDemo.java from the software package and put it in the project source code directory, rename it to YouDaoAPI.java, we will modify this program.

First add the constructor of YouDaoAPI and assign values ​​to the application ID and application key.

Then modify the function that creates the request parameters to set the request parameters by passing in the parameters.

Finally, the main function is modified as an external translation interface, and the request parameter function is called through the incoming original text and original language and the target translation language, and the request response is returned.

Then call the API to translate Chinese into English by passing in the APP ID and key.

Similarly, we extract translation results through regular expressions.

Run the program and you can see that the translation is successful.

source code

TranslationDemo.java

import javax.swing.*;
import java.awt.*;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.baidu.translate.demo.TransApi;

public class TranslationDemo extends JFrame {
    private JLabel inputLabel, baiduLabel, youdaoLabel, commonLabel;
    private JTextField inputText, baiduTranslation, youdaoTranslation, commonTextArea;
    private JButton translateButton;

    public TranslationDemo() {
        setTitle("中译英 Demo");
        setSize(500, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(1));
        inputLabel = new JLabel("中文原文:");
        inputText = new JTextField(33);
        translateButton = new JButton("翻译");
        JPanel panel1 = new JPanel();
        panel1.add(inputLabel);
        panel1.add(inputText);
        panel1.add(translateButton);
        add(panel1);
        baiduLabel = new JLabel("百度翻译:");
        baiduTranslation = new JTextField(40);
        baiduTranslation.setEditable(false);
        JPanel panel2 = new JPanel();
        panel2.add(baiduLabel);
        panel2.add(baiduTranslation);
        add(panel2);
        youdaoLabel = new JLabel("有道翻译:");
        youdaoTranslation = new JTextField(40);
        youdaoTranslation.setEditable(false);
        JPanel panel3 = new JPanel();
        panel3.add(youdaoLabel);
        panel3.add(youdaoTranslation);
        add(panel3);
        commonLabel = new JLabel("相同部分:");
        commonTextArea = new JTextField(40);
        commonTextArea.setEditable(false);
        JPanel panel4 = new JPanel();
        panel4.add(commonLabel);
        panel4.add(commonTextArea);
        add(panel4);
        translateButton.addActionListener(e -> {
            String inputText = this.inputText.getText();
            String outputBaidu, outputYouDao, same;
            try {
                outputBaidu = translateUsingBaidu(inputText);
                outputYouDao = translateUsingYoudao(inputText);
            } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
                throw new RuntimeException(ex);
            }
            Pattern pattern = Pattern.compile("\"dst\":\"(.*?)\"");
            Matcher matcher = pattern.matcher(outputBaidu);
            if (matcher.find())
                outputBaidu = matcher.group(1);
            baiduTranslation.setText(outputBaidu);
            pattern = Pattern.compile( "\"translation\":\\[\"(.*?)\"\\]");
            matcher = pattern.matcher(outputYouDao);
            if (matcher.find())
                outputYouDao = matcher.group(1);
            youdaoTranslation.setText(outputYouDao);
            commonTextArea.setText(findCommonPart(outputBaidu, outputYouDao));
        });
    }

    private String translateUsingBaidu(String text) throws UnsupportedEncodingException {    // 调用百度翻译API进行翻译
        TransApi api = new TransApi("", "");
        return api.getTransResult(text, "zh", "en");
    }


    private String translateUsingYoudao(String text) throws NoSuchAlgorithmException {    // 调用有道翻译API进行翻译
        YouDaoAPI api = new YouDaoAPI("", "");
        return api.getTransResult(text, "zh", "en");
    }

    private String findCommonPart(String text1, String text2) {    // 比较两个翻译结果,找出相同部分
        String[] baidu = text1.split("[ ,.]");
        String[] youdao = text2.split("[ ,.]");
        StringBuilder common = new StringBuilder();
        for (String a : baidu) {
            for (String b : youdao) {
                if (Objects.equals(a, b)) {
                    common.append(a).append(" ");
                }
            }
        }
        return common.toString();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            TranslationDemo demo = new TranslationDemo();
            demo.setVisible(true);
        });
    }
}

YouDaoAPI.java

import com.youdao.aicloud.translate.utils.AuthV3Util;
import com.youdao.aicloud.translate.utils.HttpUtil;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 网易有道智云翻译服务api调用demo
 * api接口: https://openapi.youdao.com/api
 */
public class YouDaoAPI {

    private static String APP_KEY = "";     // 您的应用ID
    private static String APP_SECRET = "";  // 您的应用密钥

    public YouDaoAPI(String appid, String securityKey) {
        APP_KEY = appid;
        APP_SECRET = securityKey;
    }

    public String getTransResult(String query, String from, String to) throws NoSuchAlgorithmException {
        // 添加请求参数
        Map<String, String[]> params = createRequestParams(query, from, to);
        // 添加鉴权相关参数
        AuthV3Util.addAuthParams(APP_KEY, APP_SECRET, params);
        // 请求api服务
        byte[] result = HttpUtil.doPost("https://openapi.youdao.com/api", null, params, "application/json");
        return new String(result, StandardCharsets.UTF_8);
    }

    private static Map<String, String[]> createRequestParams(String query, String from, String to) {
        return new HashMap<String, String[]>() {
   
   {
            put("q", new String[]{query});
            put("from", new String[]{from});
            put("to", new String[]{to});
        }};
    }
}

Guess you like

Origin blog.csdn.net/weixin_62264287/article/details/134928417