The article directories

  • I. Demand analysis
  • Second, the use of batch document translation tools has been done
  • Iii. Development process
    • (I) Personal developer account registration
    • (2) Create applications and instances
    • (3) Interface call and code implementation
      • 1. API interface introduction
      • 3. Batch document translation and development
  • Four,

I. Demand analysis

Requirements:

Recently, I had a task to translate a batch of documents from Chinese to English

At the beginning of thinking very simple ah, then directly copy to the translation software, in the copy out of bai.

There are many ways to achieve translation:

You can use Google Translate, which is completely free. But the downside is that you need to import document by document. If I have hundreds of files, I’m gonna lose my hand.

You can also use netease Youdao Dictionary:

The translation method of manual copy and paste of a single document is too tedious, considering the repeatability of work and my pursuit of improving efficiency, less hands-on (lazy).

As a member of the computer industry, we should make full use of it, otherwise the technology will not be learned in vain. I took full advantage of it.

I found several translation apis on the Internet, and by comparing the translation results and learning costs, I chose the service of ** Youdao Wisdom Cloud and developed a small software for batch translation by myself. Record the use and development process in detail, the latter friends have relevant needs, you can refer to.

Use Python to call existing interface methods to implement a batch translation tool, once and for all.

I plan to keep updating for a month or so, recording the whole process in detail and making it easy for my fans to use.

Second, the use of batch document translation tools has been done

Here I develop a batch document translation tool using Python as a development tool, the functions are as follows:

1) Select multiple documents through folders;

2) You can save the translation results of multiple documents to the target folder.

Look at the picture ↓↓↓↓↓

Part of the translation results show (involving confidentiality of work content, here the lotus pond moonlight as an example) :

Can try first, I uploaded to baidu network disk:

You can follow my official account: reply: 20200910 to get the resources oh, at the same time will be synchronized to GitHub, link at the end of the article.

Iii. Development process

The steps of calling The YOUdao Wisdom Cloud API interface and the software development process are described in detail below:

(I) Personal developer account registration

First, you need to register a personal developer account.

Click on the official website to register and fill in your personal information. To complete the registration, the official website: ai.youdao.com/gw.s

(2) Create applications and instances

The personal center page after successful registration and login is shown in the following figure. Youdao Cloud provides service interfaces such as natural language translation, text recognition, speech synthesis and voice evaluation. These service interfaces are run as instances and managed by applications. You need to create an instance and an application, and obtain the application ID and application key from the application.

I use the natural language translation service here. First of all, I need to create an application and an instance of natural speech translation respectively. Second, you need to bind the instance to the application. Finally, the application ID and application key can be used to invoke the natural speech translation API interface. Youdao platform will record, analyze and charge for the use of different instances and applications. Newly registered users will get a free experience and 50 yuan of experience money (plus customer service, there will be an additional 50 yuan).

Steps to create an instance:

Select the service (Natural Language Translation/OCR/TTS/ASR/Intelligent Voice Evaluation/Multi-platform Editor) > Create Instance according to your requirements, and then create the instance as required.

Create an application and bind the instance (there are three application interfaces: API, Android and ios) :

Click “Application Management” -> “My Application” -> “Create Application”, fill in the application name and other related information, select the access mode, and bind the created instance to complete the application creation. Here we use API access, Android, ios interface need to fill in the corresponding information as prompted, see the official website novice guide.

After an application is created, you can obtain the application ID (appKey) and application key, which are essential parameters for invoking APIS.

(3) Interface call and code implementation

1. API interface introduction

The following describes how to call the API interface

Text translation API HTTPS address: openapi.youdao.com/api

Invocation rules: Follow these rules when invoking the integrated text translation API.

The rules describe
transport HTTPS
Request way GET/POST
A character encoding Use utF-8 encoding
The request format The form
The response format JSON

Call parameter: Calling the API needs to send the following fields to the interface to access the service.

The field name type meaning mandatory note
q text Text to be translated True Must be UTF-8 encoding
from text The source language True Refer to the belowSupport language(You can set it to auto.)
to text The target language True Refer to the belowSupport language(You can set it to auto.)
appKey text Application ID True Can be inApplication managementTo view
salt text UUID True UUID
sign text The signature True Sha256 (App ID+input+salt+curtime+ app key)
signType text Signature type True v3
curtime text Current UTC timestamp in seconds true TimeStamp
ext text Translated results in audio format, mp3 support false mp3
voice text Translation results pronunciation selection false 0 is female and 1 is male. Female voice by default
strict text Whether to translate exactly as specified from and to: true/false false If false, it is automatically translated from Chinese to English and from English to Chinese. The default is false

The signature generation method is as follows: signType=v3; Sign =sha256(appid +input+salt+curtime+ appkey); Input = the first 10 characters of Q + q length + the last 10 characters of Q (when Q length is greater than 20) or input=q character string (when Q length is less than or equal to 20).

Format of the returned result: The returned result is in JSON format, which is described as follows:

The field name type meaning note
errorCode text Error return code There must be
query text The source language If the query is correct, it must exist
translation Array Translation results If the query is correct, it must exist
basic text The meaning A basic dictionary for looking up words
web Array The meaning The result does not necessarily exist
l text Source and target languages There must be
dict text Dictionary deeplink This parameter is available if the query language is a supported language
webdict text webdeeplink This parameter is available if the query language is a supported language
tSpeakUrl text Translation result pronunciation address The translation must be successful, and you need to apply the bound speech synthesis instance to play normally. Otherwise, error code 110 is returned
speakUrl text Source language pronunciation address The translation must be successful, and you need to apply the bound speech synthesis instance to play normally. Otherwise, error code 110 is returned
returnPhrase Array The result of word verification The main check letter case, the word before the symbol, simple and traditional Chinese

If the errorCode is 0, the invocation succeeds. If the errorCode is not 0, error codes with different meanings are displayed. For details, please refer to the official development documentation.

3. Batch document translation and development

Batch translation demo using PYTHon3 implementation, in order to facilitate the test, I use Tkinter to do a simple interface, used to read the document to be translated, specify the result storage path, in order to maximize the simplification of the development process, reduce the time cost of testing, currently only read. TXT type file method.

Py, translate. Py and translateTool. py. Mainwindow is the UI part of the code. Translatetool is a translation method modified according to the example code. It can encapsulate corresponding methods when calling other platform APIS, which increases the extensibility of the project.

The elements of mainwindow are as follows:

root=tk.Tk()
root.title("netease youdao translation test")
frm = tk.Frame(root)
frm.grid(padx='50', pady='50')
btn_get_file = tk.Button(frm, text='Select file to be translated', command=get_files)
btn_get_file.grid(row=0, column=0, ipadx='3', ipady='3', padx='10', pady='20')
text1 = tk.Text(frm, width='40', height='10')
text1.grid(row=0, column=1)
btn_get_result_path=tk.Button(frm,text='Select translation result path',command=set_result_path)
btn_get_result_path.grid(row=1,column=0)
text2=tk.Text(frm,width='40', height='2')
text2.grid(row=1,column=1)
btn_sure=tk.Button(frm,text="Translation",command=translate_files)
btn_sure.grid(row=2,column=1)
Copy the code

Where the translate_files() method finally calls the translate_files() method of translate:

def translate_files() :
    if translate.file_paths:
        translate.translate_files()
        tk.messagebox.showinfo("Tip"."Done")
    else :
        tk.messagebox.showinfo("Tip"."No file")
Copy the code

The translate class is defined as follows:

import  os
from translatetool import connect

class Translate() :
    def __init__(self,name,file_paths,result_root_path,trans_type) :
        self.name=name
        self.file_paths=file_paths							Path of the file to be translated
        self.result_root_path=result_root_path				# Translation result storage path
        self.trans_type=trans_type
        
    # Translation process: Read file - drop Youdao API - parse returned information - save
    def translate_files(self) :
        for file_path in self.file_paths:
            file_name=os.path.basename(file_path)
            file_content=open(file_path,encoding='utf-8').read()
            trans_reult=self.translate_use_netease(file_content)
            resul_file=open(self.result_root_path+'/result_'+file_name,'w').write(trans_reult)
    def translate_use_netease(self,file_content) :
        result=', '.join(connect(file_content,'zh-CH'.'EN'))	 The translation API returns the result as an array
        return result
Copy the code

The main method of calling Youdao API is connect(). Data is composed according to the requirements of API signature information and send a request, and the returned JSON is parsed:

Fromlanguage indicates the language tolanguage translates into
# return the translated field
def connect(inputtext,fromlanguage,tolanguage) :
    q=inputtext
    data = {}
    data['from'] = fromlang
    data['to'] = tolang
    data['signType'] = 'v3'
    curtime = str(int(time.time()))
    data['curtime'] = curtime
    salt = str(uuid.uuid1())
    signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET
    sign = encrypt(signStr)
    data['appKey'] = APP_KEY
    data['q'] = q
    data['salt'] = salt
    data['sign'] = sign
    print(data)
    response = do_request(data)
    print(response.content)
    j = json.loads(str(response.content, encoding="utf-8"))"translation"]
    return j
Copy the code

Full demo code address: github.com/LemonQH/Bat…

Thanks to the low cost of learning API, the development process of the interface call part was very smooth, except for one small incident. At the beginning, THE API call always returned error code 206 (i.e. timestamp error), and finally found that my system time was ten minutes behind the standard time – #

Four,

For the document I need to translate this time, the words and account amount given by Youdao Wisdom Cloud are enough, but if YOU want to use it for a long time, you still have to pay. Finally, it is found that Youdao Wisdom Cloud also provides hourly statistics on the number of instance calls and query characters of the day and daily statistics on the number of instance calls and characters of historical days on the personal homepage. For partners who have requirements, they can also record and check the status of their interface translation volume and real-time call volume.

Above is my whole demo development process. On the whole, the process from registration to calling Youdao Wisdom Cloud API is relatively smooth, and there are official detailed documents for reference for each step. So much so that most of the development time was devoted to tkinter typography (pun intended to make Tkinter “usable” :p).

Stay tuned for the next update to this series.