使用go构建彩云翻译的Alfred Workflow | 青训营笔记

Author: 颖奇L’Amore

Blog: www.gem-love.com

最近参加了字节跳动的后端专场青训营,是一个免费的Go培训项目,正好最近入职了字节跳动的安全与风控部门,负责公司的业务安全(电商SDLC),公司大部分业务以Go为主,借此青训营机会希望也可以提升一下自己的Go后端开发水平,更好的为公司工作。

按照青训营要求,每个学员为了顺利结业需参加笔记创作活动,这是我的第一篇笔记,首发于掘金社区

以下是正文


这是我参与「第三届青训营 -后端场」笔记创作活动的的第1篇笔记

前言

160640_C8oFg4

在Day1的『Go语言上手-基础语言』中,老师给了三个项目,其中一个是基于彩云翻译使用Go来实现一个建议的词典查询功能,代码支持英译汉。我发现彩云翻译很好用,不需要自己申请api就可以使用,于是我在此基础上加以改造,将其做成了一个Alfred Workflow,并且添加了中译英的功能。

AlfredWorkflow初体验

Alfred是MacOS上提升工作效率的工具。关于Alfred可以看我博客的两篇文章:

可以在我的github下载到这次的彩云翻译Workflow:
https://github.com/y1nglamore/caiyunTranslator

效果如下:

161248_QQ20220508-161156-HD

如果上面的Gif动画加载不出来,可以看静态图:

image-20220508155901644

image-20220508155914512

使用方法

首先去我的github仓库下载彩云翻译.alfredworkflow

双击导入Alfred,然后双击这个Script Filter
161421_SuAg4d

将命令中的go的绝对路径改成你本机的绝对路径,可以用whereis go查看
161504_JmrHgl

然后只需要在Alfred中输入cy xxx即可。这里如果xxx是英文就是英译汉,如果是中文就是汉译英。

构造思路

代码

首先老师给的版本是这样的:

package main

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)

type DictRequest struct {
TransType string `json:"trans_type"`
Source string `json:"source"`
UserID string `json:"user_id"`
}

type DictResponse struct {
Rc int `json:"rc"`
Wiki struct {
KnownInLaguages int `json:"known_in_laguages"`
Description struct {
Source string `json:"source"`
Target interface{} `json:"target"`
} `json:"description"`
ID string `json:"id"`
Item struct {
Source string `json:"source"`
Target string `json:"target"`
} `json:"item"`
ImageURL string `json:"image_url"`
IsSubject string `json:"is_subject"`
Sitelink string `json:"sitelink"`
} `json:"wiki"`
Dictionary struct {
Prons struct {
EnUs string `json:"en-us"`
En string `json:"en"`
} `json:"prons"`
Explanations []string `json:"explanations"`
Synonym []string `json:"synonym"`
Antonym []string `json:"antonym"`
WqxExample [][]string `json:"wqx_example"`
Entry string `json:"entry"`
Type string `json:"type"`
Related []interface{} `json:"related"`
Source string `json:"source"`
} `json:"dictionary"`
}

func query(word string) {
client := &http.Client{}
request := DictRequest{TransType: "en2zh", Source: word}
buf, err := json.Marshal(request)
if err != nil {
log.Fatal(err)
}
var data = bytes.NewReader(buf)
req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Connection", "keep-alive")
req.Header.Set("DNT", "1")
req.Header.Set("os-version", "")
req.Header.Set("sec-ch-ua-mobile", "?0")
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36")
req.Header.Set("app-name", "xy")
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("device-id", "")
req.Header.Set("os-type", "web")
req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi")
req.Header.Set("Origin", "https://fanyi.caiyunapp.com")
req.Header.Set("Sec-Fetch-Site", "cross-site")
req.Header.Set("Sec-Fetch-Mode", "cors")
req.Header.Set("Sec-Fetch-Dest", "empty")
req.Header.Set("Referer", "https://fanyi.caiyunapp.com/")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
req.Header.Set("Cookie", "_ym_uid=16456948721020430059; _ym_d=1645694872")
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
bodyText, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
if resp.StatusCode != 200 {
log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))
}
var dictResponse DictResponse
err = json.Unmarshal(bodyText, &dictResponse)
if err != nil {
log.Fatal(err)
}
fmt.Println(word, "UK:", dictResponse.Dictionary.Prons.En, "US:", dictResponse.Dictionary.Prons.EnUs)
for _, item := range dictResponse.Dictionary.Explanations {
fmt.Println(item)
}
}

func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, `usage: simpleDict WORD
example: simpleDict hello
`)
os.Exit(1)
}
word := os.Args[1]
query(word)
}

161757_MyY9Dp

先给出我的改良后适配Alfred的完整代码,也没什么大改:

package main

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
"unicode"
)

type DictRequest struct {
TransType string `json:"trans_type"`
Source string `json:"source"`
UserID string `json:"user_id"`
}

type DictResponse struct {
Rc int `json:"rc"`
Wiki struct {
KnownInLaguages int `json:"known_in_laguages"`
Description struct {
Source string `json:"source"`
Target interface{} `json:"target"`
} `json:"description"`
ID string `json:"id"`
Item struct {
Source string `json:"source"`
Target string `json:"target"`
} `json:"item"`
ImageURL string `json:"image_url"`
IsSubject string `json:"is_subject"`
Sitelink string `json:"sitelink"`
} `json:"wiki"`
Dictionary struct {
Prons struct {
EnUs string `json:"en-us"`
En string `json:"en"`
} `json:"prons"`
Explanations []string `json:"explanations"`
Synonym []string `json:"synonym"`
Antonym []string `json:"antonym"`
WqxExample [][]string `json:"wqx_example"`
Entry string `json:"entry"`
Type string `json:"type"`
Related []interface{} `json:"related"`
Source string `json:"source"`
} `json:"dictionary"`
}

// 用于翻译结果的图标显示
type icon struct {
Type string `json:"type"`
Path string `json:"path"`
}

// 用于单条结果
type item struct {
Subtitle string `json:"subtitle"` // 固定的小字的标题
Title string `json:"title"`
Arg string `json:"arg"`
Icon icon `json:"icon"`
}

// 结果集
type items struct {
Items []item `json:"items"`
}

func queryEnglish(word string, icon icon) {
client := &http.Client{}
request := DictRequest{TransType: "en2zh", Source: word}
buf, err := json.Marshal(request)
if err != nil {
log.Fatal(err)
}
var data = bytes.NewReader(buf)
req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Connection", "keep-alive")
req.Header.Set("DNT", "1")
req.Header.Set("os-version", "")
req.Header.Set("sec-ch-ua-mobile", "?0")
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36")
req.Header.Set("app-name", "xy")
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("device-id", "")
req.Header.Set("os-type", "web")
req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi")
req.Header.Set("Origin", "https://fanyi.caiyunapp.com")
req.Header.Set("Sec-Fetch-Site", "cross-site")
req.Header.Set("Sec-Fetch-Mode", "cors")
req.Header.Set("Sec-Fetch-Dest", "empty")
req.Header.Set("Referer", "https://fanyi.caiyunapp.com/")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
req.Header.Set("Cookie", "_ym_uid=16456948721020430059; _ym_d=1645694872")
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
bodyText, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}

// 发生错误时的结果
if resp.StatusCode != 200 {
//log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))
var errItem []item
errItem = []item{
{
Subtitle: "error",
Title: "bad StatusCode: " + strconv.FormatInt(int64(resp.StatusCode), 10),
Arg: "bad StatusCode: " + strconv.FormatInt(int64(resp.StatusCode), 10),
Icon: icon,
},
}

errItems := items{Items: errItem}
itemsJson, _ := json.Marshal(errItems)
fmt.Println(string(itemsJson))
return
}

var dictResponse DictResponse
err = json.Unmarshal(bodyText, &dictResponse)
if err != nil {
log.Fatal(err)
}
//fmt.Println(word, "UK:", dictResponse.Dictionary.Prons.En, "US:", dictResponse.Dictionary.Prons.EnUs)
//for _, item := range dictResponse.Dictionary.Explanations {
// fmt.Println(item)
//}

var resultItem []item
resultItem = []item{
{
Subtitle: "音标",
Title: "EN:" + dictResponse.Dictionary.Prons.En + " US:" + dictResponse.Dictionary.Prons.EnUs,
Arg: "EN:" + dictResponse.Dictionary.Prons.En + " US:" + dictResponse.Dictionary.Prons.EnUs,
Icon: icon,
},
}
for i, paraphrase := range dictResponse.Dictionary.Explanations {
paraphraseItem := item{Subtitle: "解释" + strconv.FormatInt(int64(i+1), 10), Title: paraphrase, Arg: "解释" + strconv.FormatInt(int64(i+1), 10), Icon: icon}
resultItem = append(resultItem, paraphraseItem)
}
resultItems := items{Items: resultItem}
resultJson, _ := json.Marshal(resultItems)
fmt.Println(string(resultJson))
}

func queryChinese(word string, icon icon) {
client := &http.Client{}
request := DictRequest{TransType: "zh2en", Source: word}
buf, err := json.Marshal(request)
if err != nil {
log.Fatal(err)
}
var data = bytes.NewReader(buf)
req, err := http.NewRequest("POST", "https://api.interpreter.caiyunai.com/v1/dict", data)
if err != nil {
log.Fatal(err)
}
req.Header.Set("Connection", "keep-alive")
req.Header.Set("DNT", "1")
req.Header.Set("os-version", "")
req.Header.Set("sec-ch-ua-mobile", "?0")
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36")
req.Header.Set("app-name", "xy")
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("device-id", "")
req.Header.Set("os-type", "web")
req.Header.Set("X-Authorization", "token:qgemv4jr1y38jyq6vhvi")
req.Header.Set("Origin", "https://fanyi.caiyunapp.com")
req.Header.Set("Sec-Fetch-Site", "cross-site")
req.Header.Set("Sec-Fetch-Mode", "cors")
req.Header.Set("Sec-Fetch-Dest", "empty")
req.Header.Set("Referer", "https://fanyi.caiyunapp.com/")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
req.Header.Set("Cookie", "_ym_uid=16456948721020430059; _ym_d=1645694872")
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
bodyText, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}

// 发生错误时的结果
if resp.StatusCode != 200 {
//log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))
var errItem []item
errItem = []item{
{
Subtitle: "error",
Title: "bad StatusCode: " + strconv.FormatInt(int64(resp.StatusCode), 10),
Arg: "bad StatusCode: " + strconv.FormatInt(int64(resp.StatusCode), 10),
Icon: icon,
},
}

errItems := items{Items: errItem}
itemsJson, _ := json.Marshal(errItems)
fmt.Println(string(itemsJson))
return
}

var dictResponse DictResponse
err = json.Unmarshal(bodyText, &dictResponse)
if err != nil {
log.Fatal(err)
}
//fmt.Println(word, "UK:", dictResponse.Dictionary.Prons.En, "US:", dictResponse.Dictionary.Prons.EnUs)
//for _, item := range dictResponse.Dictionary.Explanations {
// fmt.Println(item)
//}

var resultItem []item
resultItem = []item{}
//fmt.Printf("[+] %+v\n", dictResponse.Dictionary)
i := 1
for _, paraphrase := range dictResponse.Dictionary.Explanations {
paraphraseArr := strings.Split(paraphrase, "; ")
for _, singleParapharase := range paraphraseArr {
paraphraseItem := item{Subtitle: "解释" + strconv.FormatInt(int64(i), 10), Title: singleParapharase, Arg: "解释" + strconv.FormatInt(int64(i), 10), Icon: icon}
resultItem = append(resultItem, paraphraseItem)
i += 1
}
}
resultItems := items{Items: resultItem}
resultJson, _ := json.Marshal(resultItems)
fmt.Println(string(resultJson))
}

func IsChinese(str string) bool {
var count int
for _, v := range str {
if unicode.Is(unicode.Han, v) {
count++
break
}
}
return count > 0
}

func main() {
if len(os.Args) != 2 {
// fmt.Fprintf(os.Stderr, `usage: simpleDict WORD
//example: simpleDict hello
// `)
os.Exit(1)
}
word := os.Args[1]
icon := icon{Type: "file", Path: "logo2.png"}
if !IsChinese(word) {
queryEnglish(word, icon)
} else {
queryChinese(word, icon)
}
}

适配Alfred

为了适配Alfred,我们需要定义输出所需要的结构体:


// 用于翻译结果的图标显示
type icon struct {
Type string `json:"type"`
Path string `json:"path"`
}

// 用于单条结果
type item struct {
Subtitle string `json:"subtitle"` // 固定的小字的标题
Title string `json:"title"`
Arg string `json:"arg"`
Icon icon `json:"icon"`
}

// 结果集
type items struct {
Items []item `json:"items"`
}

然后将输出都以特定的json形式(具体什么形式可以看我博客的Alfred 4: MacOS效率提升大杀器(下篇)的介绍)输出,首先是报错时候的输出:

// 发生错误时的结果
if resp.StatusCode != 200 {
//log.Fatal("bad StatusCode:", resp.StatusCode, "body", string(bodyText))
var errItem []item
errItem = []item{
{
Subtitle: "error",
Title: "bad StatusCode: " + strconv.FormatInt(int64(resp.StatusCode), 10),
Arg: "bad StatusCode: " + strconv.FormatInt(int64(resp.StatusCode), 10),
Icon: icon,
},
}

errItems := items{Items: errItem}
itemsJson, _ := json.Marshal(errItems)
fmt.Println(string(itemsJson))
return
}

然后是结果通过json.Marshal序列化后输出,以英译汉为例:

var resultItem []item
resultItem = []item{
{
Subtitle: "音标",
Title: "EN:" + dictResponse.Dictionary.Prons.En + " US:" + dictResponse.Dictionary.Prons.EnUs,
Arg: "EN:" + dictResponse.Dictionary.Prons.En + " US:" + dictResponse.Dictionary.Prons.EnUs,
Icon: icon,
},
}
for i, paraphrase := range dictResponse.Dictionary.Explanations {
paraphraseItem := item{Subtitle: "解释" + strconv.FormatInt(int64(i+1), 10), Title: paraphrase, Arg: "解释" + strconv.FormatInt(int64(i+1), 10), Icon: icon}
resultItem = append(resultItem, paraphraseItem)
}
resultItems := items{Items: resultItem}
resultJson, _ := json.Marshal(resultItems)
fmt.Println(string(resultJson))

最后写两个函数,通过网上抄的IsChinese()判断是否字符串含有中文,如果含有中文就是汉译英,否则英译汉:

func IsChinese(str string) bool {
var count int
for _, v := range str {
if unicode.Is(unicode.Han, v) {
count++
break
}
}
return count > 0
}

func main() {
if len(os.Args) != 2 {
// fmt.Fprintf(os.Stderr, `usage: simpleDict WORD
//example: simpleDict hello
// `)
os.Exit(1)
}
word := os.Args[1]
icon := icon{Type: "file", Path: "logo2.png"}
if !IsChinese(word) {
queryEnglish(word, icon)
} else {
queryChinese(word, icon)
}
}

后记

第一天的知识比较简单,也没啥可记的,所以就分享一个我自己做的小工具吧。Alfred是真的神器,推荐用mac的同学都来试试,真的会爱不释手。

最后推荐一个我常用的翻译Workflow:有道翻译 超级好用,强烈推荐!

Author: Y1ng
Link: https://www.gem-love.com/2022/05/08/使用go构建彩云翻译的Alfred-Workflow/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
【腾讯云】热门云产品首单特惠秒杀,2核2G云服务器45元/年    【腾讯云】境外1核2G服务器低至2折,半价续费券限量免费领取!