I wrote a translation tool (TUI command) that wraps GAS in Go language.
It may be worth reading for those who:
I'm not good at English, so I can't let go of dictionary sites and translation sites when reading and writing documents. I usually work in the terminal, but it's stressful because I'm going back and forth between the web browser and the terminal software.
One day, I had never touched GAS (Google Apps Script), so I decided to give it a try for later study, and created a simple translation command that wraps LanguageApp.
At first, I intended to start making it fashionably, but I found it surprisingly convenient to use, so I would like to introduce it in an article.
The command is published in the following repository.
A similar tool is translate-shell. I'm sure many of you are using it, but later in this article I'll touch on the differences between go-tran and translate-shell.
We have confirmed the operation on Linux and Windows. (I think it works on Mac)
Running the tran command with no arguments launches an interactive shell.
By default, it will be translated into the language of the current locale of the execution environment, so all you have to do is enter the foreign language you want to translate.
Below are examples of translating English, French, Italian, Spanish, Korean and Chinese into Japanese.
In the image above, the prompt is `: ja>`
.
It is in the format `(Source): (Target)>`
, the source language is Auto, and the Target language is Japanese (ja). is what it means. For example, when translating from Japanese to English, `ja: en>`
is displayed.
To switch the destination language, enter the two-digit language code (ISO639-1). Below is an example of translating Japanese into English (en), French (fr), Italian (it), Spanish (es), Korean (ko), and Chinese (zh) while switching the target language. is.
If you don't know the language code, you can look it up with the l command (l: Language codes).
The l command displays a list of strings that you enter that are the same as the ISO639-1 code or that partially match the ISO language name (English name). If you don't find either, it will be converted to English internally and then searched again, so you can find the target language code relatively easily even with the name entered in Japanese, for example.
The following is the "l command" that contains "nor", "nese", "German", "Kurdish", "Zulu", and the list can be displayed, but "Cumbric" Was not found. "
If you specify a file name in the command line argument or connect to the standard input of the command by pipe or redirect, it will be executed as a batch command.
If you run go-tran with the pathname of the file as an argument, it will translate the file for you. Again, the destination language (default value) is determined by the current locale of the execution environment.
If the standard input is not a terminal, go-tran runs in batch mode.
For example, in my Ubuntu environment, man is displayed in Japanese, but there are some commands for which a Japanese manual is not available. It's not as Japanese as the commands you don't use often. In the past, when I came across an English word I didn't know, I had to open a web browser to look it up.
But from now on, all you have to do is redirect man to go-tran.
** If you have a Go environment **
install go-tran
$ go get -u github.com/y-bash/go-tran
$ cd $GOPATH/src/github.com/y-bash/go-tran
$ go install ./...
** If you do not have a Go environment and only get the source code **
get source code
$ git clone https://github.com/y-bash/go-tran.git
If you don't have a Go environment but want to use binaries, please feel free to contact us as we will consider a method.
The executable file is named tran.
$ tran
Welcome to the GO-TRAN!
...
The entered characters are generally judged as follows.
String | Description |
---|---|
One character | Judged as a command. |
2 letters | Target language switching. |
3 characters or more | Translate the entered text according to the current mode. |
The types of commands are as follows.
command | Description | Example |
---|---|---|
h | Display help. | |
l [str] | Displays a list of language codes and names. (Language code is ISO639-1)
|
|
s [str] | Source language(Source)Toggle.
|
|
[t] code t [str] |
Destination language(Target)Toggle.
|
|
q | End |
The main key bindings are: (Compatible with bash)
Key | Description | 代替Key |
---|---|---|
Ctrl-a | Move to the beginning of the line | Home |
Ctrl-e | Move to the end of line | End |
Ctrl-b | 1 character retreat | ← |
Ctrl-f | 1 character forward | → |
Key | Description | 代替Key |
---|---|---|
Ctrl-h | Delete the character before the cursor position | Back space |
Ctrl-d | Delete the character at the cursor position | Delete |
Ctrl-k | Delete from the cursor position to the end of the line | |
Ctrl-u | Delete from the beginning of the line to just before the cursor position |
The commands and text you enter are saved in the history, and you can follow them with keystrokes.
Key | Description | 代替Key |
---|---|---|
Ctrl-p | Go back in the input history | ↑ |
Ctrl-n | Go through the input history | ↓ |
Ctrl-r | Incremental search of input history |
The command format is as follows:
format
tran [options] [path...]
[October 12, 2020] Added -a option and -e option
The options are:
option | Description | Example |
---|---|---|
-a | Register with the user's GAS project Display the script. registered Script URL in config file Create your own API server by listing You can call it. This option is for batch mode only. |
$ tran -a |
-e | The source text and the translated text are output alternately line by line. This option is for batch mode only. |
```$tran -e english.txt |
-h | Display help. This option is for batch mode only. |
$ tran -h |
-l | List of language codes and names(184 cases)It is displayed. (Language code is ISO639-1) This option is for batch mode only. |
$ tran -l |
-s code | Source language(Source)To Language code (ISO639)-Specify in 1). If omitted, it will be automatically determined. |
$ tran -s en |
-t code | Destination language(Target)To Language code (ISO639)-Specify in 1). If omitted, it is converted to the current locale. |
$ tran -t en |
###path
The method for specifying the path is as follows.
path | Description | Example |
---|---|---|
Designation | Designationしたファイルを翻訳して標準出力へ出力します。 | $ tran a.txt b.txt |
abridgement |
|
* In the cell"|"Is a double-byte character. Please be careful when copying and pasting. |
###Example of use
Quickly check difficult English words
python
$ echo "penpineappleapplepen" | tran
Pen Pineapple Apple Pen
Convert Japanese files to English
python
$ tran -t en Japanese.txt
this is a pen.
Save Japanese files in Latin
python
$ tran -t la Japanese.txt > Latin.txt
Return the result of automatic translation to Japanese and check if it fits well
python
$ echo "I love apples" | tran -t en | tran
I love apples
strings.Builder (Golang)Make all comment lines in the source code of
python
$ grep '^\s*//' ./builder.go | sed -e 's/^\s*..\s*//' | tran
Copyright 2017 The Go Authors. all rights reserved.
Use of this source code is governed by the BSD style
The license in the LICENSE file.
Builders are used to efficiently build strings using the Write method.
...
Make the error line of all log files under the current directory Japanese
python
$ find . -name '*.log' | xargs grep 'error:' | tran
./tool/vim/src/auto/config.log:conftest.c:154:12: Error:'GETACLCNT' is not declared (first use in this function)
./tool/vim/src/auto/config.log:conftest.c:154:26: Error:'NULL' is not declared (first use in this function)
...
##Configuration file [Added on October 12, 2020]
Version 1.0.This section explains how to use the configuration file supported in 1.
###Configuration file path
The path of the configuration file is as follows. (Depends on the OS)
OS | path |
---|---|
POSIX | $HOME/.config/y-bash/config.toml |
Windows | %AppData%\y-bash\tran\config.toml |
###Items that can be set
table | Key | Description | initial value |
---|---|---|---|
[default] | source | Language code of conversion source(ISO639-1)Default value for. | "" |
[default] | target | Language code of the conversion destination(ISO639-1)Default value for. | Current locale at first boot. |
[api] | endpoint | GAS (Google Apps Script)The URI of the project. You can specify your own API server by setting the URI of the GAS project created by the user. The script to be set in GAS is-Can be displayed with the a option. [Example] tran-a |
As before. |
[api] | limit_n_chars | Maximum number of characters sent in a single API call. If the number of characters in the source text exceeds this value, the API will be called multiple times. | 4000 |
[colors] | info | Information message text color | "#80a0d0" |
[colors] | info | Text color of status change message | "#60c060" |
[colors] | error | Error message text color | "#d04040" |
[colors] | result | Text color of converted text | "#ffc864" |
Actually I translate-I learned about shell, go-After I started making tran.
The functions are almost similar, and the command names are the same.trans
I was surprised because it was.
(At first go-It was called trans)
Moreover, translate-The shell is highly functional, displaying additional information such as part of speech, and displaying multiple meanings of a word.
But after using it a little, go-go to tran-I've gradually come to realize that tran is good.
translate-The shell will display not only the translation result but also the following additional information.
*Source language *Destination language *Part of speech (in the case of words) *Multiple meanings (for words)
translate-Execution example of shell
Since it can be used like a dictionary, it may be convenient for English composition. However, if you have to write a solid English document, you will need a more solid dictionary.
translate-go to shell-The advantages of tran are:
*simple
It is easy to see because it does not output extra information.
Additional information, such as part of speech, can sometimes get in the way.
*Color display
The color display allows you to instantly identify the part you want to see.
*Language code search function
go-With tran, you can easily find the language code.
translate-The shell will have to remember the language code or look at the documentation.
*bash-like key bindings
go-tran is easy to edit characters.
translate-It seems that the shell is just reading the standard input, which makes it difficult to edit characters.
*History function
go-tran can redisplay previously entered commands and texts, edit them, and execute them.
This is also translate-This is a feature that shell does not have.
*Windows native support
go-You can run tran at the Windows command prompt.
translate-It seems that shell requires a UNIX compatible environment such as Cygwin.
go-Image of using tran
GAS (Google Apps Script)The Web API created with and the client created with Go are very easy.
##Create a Web API with GAS
tanabeeI referred to Mr.'s popular article.
The following processing is added to the code that was used as a reference.
*Return with json
The code is below.
Translate.gs
// Common processing
// param e event
function process(e) {
let body // response body
try {
const p = e.parameter // request parameter
const s = LanguageApp.translate (p.text, p.source, p.target) // Translate
body = {code: 200, text: s} // Create a response body
} catch (e) {// param e exception
// Translation failed
try {
const msg = LanguageApp.translate (e.toString (), "", "en") // Error message to English
body = {code: 400, message: msg} // Create a response body
} catch (e) {// param e exception
// Failure to do this is an internal error
body = {code: 500, message: e.toString ()} // Create a response body
}
}
let resp = ContentService.createTextOutput () // Response
resp.setMimeType (ContentService.MimeType.JSON) // Make the MIME type into JSON format
resp.setContent (JSON.stringify (body)) // Convert response body to JSON format string
return resp; // return the response
}
// GET
// param e event
function doGet(e) {
return process (e) // Call common process
}
// POST
// param e event
function doPost(e) {
return process (e) // Call common process
}
Process with the above code(e)And two catches(e)If you are worried about using a variable with the same name in, change the variable name.
After modifying the scriptProject versionToNewI didn't know that it wouldn't be reflected in the product if I didn't do it, so I was worried about this for about 20 minutes.
##Make a client with Go
The client-side functions (Go language) that wrap the Web API created by GAS are as follows.
tran.go
package tran
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
const gURL = "https://script.google.com/macros/s/@@script@@/exec" // @@ script @@ Correction required
// A structure that maps the JSON of the response
type TransData struct {
Code int `json:" code "` // Response status
Text string `json:" text "` // Translation result
Message string `json:" message "` // Error message
}
// translation
func Translate(text, source, target string) (string, error) {
// Create parameters
v := url.Values{}
v.Add ("text", text) // Source string
v.Add ("source", source) // Source language (ISO639-1)
v.Add ("target", target) // Destination language (ISO639-1)
// Request to translation API by POST
resp, err := http.PostForm(gURL, v)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return "", err
}
// Read the response body into the buffer
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
// Map response body (JSON format) to structure
var td TransData
if err := json.Unmarshal(buf, &td); err != nil {
return "", err
}
// Check response status
if td.Code != 200 {
// Error handling (remove the prefix "Exception:")
msg := td.Message
prefix := "exception:"
if strings.HasPrefix(strings.ToLower(msg), prefix) {
msg = string(msg[len(prefix):])
msg = strings.TrimSpace(msg)
}
return "", errors.New(msg)
}
// Normal processing
return td.Text, nil // Extract the converted character string from the structure and return it
}
I didn't do anything difficult, and the simplest way to make an HTTP request(POST)I'm just throwing, but please note the following points.
*Of the above code@@script@@@
Needs to be modified for each GAS project.
*Message prefix when an error occurs"Exception: "I am doing the process of removing, but I think this is unnecessary depending on the situation.
For other code,HerePlease refer to the.
At the moment, there are the following issues, but I think it is not so difficult to improve.
*Response time
Currently, the server side is using the free plan of GAS, so it is possible that the response will be poor due to access restrictions when traffic is concentrated.
For this, I'm thinking of allowing the command's config settings to specify a user-specific URL. This will increase the burden on users to register GAS scripts in their Google Account, but in exchange it should allow them to use commands without worrying about others.
[Added on October 12, 2020]
This issue is version 1.0.It was solved in 1. You can set the URI of your own GAS project in the configuration file. Detail isHerePlease refer to the.
*Batch output format
When translating log files and documents, you still want to compare them with the original text.
For this, we plan to provide an option to output the source text and the translated text alternately line by line. Probably not difficult to deal with.
[Added on October 12, 2020]
This issue is version 1.0.It was solved in 1.-The original text and the translated text can be output alternately by executing with the e option. Detail isHerePlease refer to the.
*Character limit
I found that I got an error when I put a lot of text into the GAS LanguageApp. Regarding this, we will be able to set the maximum value of the number of characters that can be input to the API at one time, and will modify the program so that if a large amount of text is input, it will be translated separately.
[Added on October 12, 2020]
This issue is version 1.0.It was solved in 1. Configuration file limit_n_chars (The initial value can be set with 4000). Detail isHerePlease refer to the.
In this article, a translation tool in Go language(TUI command)I introduced the story of making and how to use the command. I also briefly introduced how to make it. I also wrote that I found out that a similar tool already existed, and at first I was disappointed, but gradually I started to think that my own commands were not bad.
GAS's translation API is easy to use and well known to everyone. At first, I thought that a product using such an API wouldn't be particularly interesting, but when I actually made it, I was able to make something that was surprisingly convenient (it's natural because it's an oleore specification). …).
Also, by making my own, I can see both the advantages and disadvantages of popular tools.
There are as many well-known solutions as there are stars. But this experience is one of those things
*It looks like it's commoditized, but there are uses that no one has noticed yet. *It has become the de facto standard, but there are improvements that no one has noticed yet.
It was an opportunity to recognize such things again.
Well then!
Recommended Posts