Write a translation plugin for Albert launcher

need

I usually check less, and it is troublesome to install a translation software. I used Firefox's translation script before, but the page needs to be refreshed after the script is enabled; if it is always enabled, a box will pop up when the text is selected, blue and thin.
During this time, I started to use the albert launcher, which supports qt and python extensions, and comes with the Google translator plug-in. Can be changed to domestic translation services.

test

There are many translation services available in China: Youdao, Kingsoft Powerword, Baidu, Bing, Haici, Sogou, etc.

  1. Use crawler technology. Similar to the browser directly accessing the page, the disadvantage is that the performance is a bit worse, and it is often necessary to crack the anti-crawling measures, which is slightly troublesome to implement.
  2. Use official API: fast speed, generally return json format; no suspicion of embezzlement. But to register, the function will be limited. It is said that Sogou's full-text translation is the best, but API charges are based on usage.
    In the end, I chose Youdao, after all, it was just a word search.

accomplish

Documentation: Youdao Zhiyun , albert doc
can refer to the plugin: https://github.com/albertlauncher/python
official demo: https://github.com/albertlauncher/python/tree/master/ApiTest

# -*- coding: utf-8 -*-

"""Translate text using Youdao Translate API.
Usage: tr <text>
Example: tr hello

Check available languages here:
http://ai.youdao.com/docs/doc-trans-api.s#p05
"""

from albertv0 import *
import json
import urllib.request
import urllib.parse
import hashlib
import locale

__iid__ = "PythonInterface/v0.1"
__prettyname__ = "Youdao Translate"
__version__ = "1.0"
__trigger__ = "tr "  # 触发命令
__author__ = "jack"
__dependencies__ = []

ua = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36"
urltmpl = "http://openapi.youdao.com/api?appKey={}&q={}&from=auto&to={}&salt={}&sign={}"

iconPath = iconLookup('config-language')  # 自定义图标
if not iconPath:
    iconPath = ":python_module"

# 根据 Linux 的 locale 设置自动获取目标语言
langSupported = dict.fromkeys(('zh', 'en', 'es', 'fr', 'ko', 'ja', 'ru', 'pt'))
toLang = locale.getdefaultlocale()
if toLang:
    toLang = toLang[0].split('_')[0]  # cat /etc/locale.gen
if not toLang in langSupported:
    toLang = 'en'

def getUrl(src, dst, txt):
''' 按有道的格式生成请求地址。src为源语言,dst为目标语言 '''
    appKey = '您的应用ID'  # 注册智云后获得
    secretKey = '您的key'
    salt = '123456'
    sign = appKey + txt + salt + secretKey
    m1 = hashlib.md5()
    m1.update(sign.encode(encoding='utf-8'))
    sign = m1.hexdigest()
    q = urllib.parse.quote_plus(txt)
    url = urltmpl.format(appKey, q, dst, salt, sign)
    return url

def handleQuery(query):
    if query.isTriggered:
        def getItem(text, subtext=''):  # 显示的项
            item = Item(
                id=__prettyname__, 
                icon=iconPath, 
                completion=query.rawString,
                text=text, 
                subtext=subtext
            )
            item.addAction(ClipAction("Copy translation to clipboard", text))  # 项支持的操作
            return item
        txt = query.string.strip()
        if txt:
            url = getUrl('auto', toLang, txt)
            req = urllib.request.Request(url, headers={'User-Agent': ua})
            with urllib.request.urlopen(req) as response:
                items = []  # 待返回的列表
                data = json.load(response)
                fromTo = data['l']
                if 'basic' in data:
                    if 'phonetic' in data['basic']:  # 读音
                        items.append(getItem('/' + data['basic']['phonetic'] + '/', fromTo))
                    for exp in data['basic']['explains']:  # 释义
                        items.append(getItem(exp, 'basic'))
                elif 'translation' in data:  # 句子翻译
                    items.append(getItem(data['translation'][0], 'translation'))
                if 'web' in data:  # 网络释义
                    for w in data['web']:
                        value = list(set(w['value']))  # 去重
                        items.append(getItem(w['key']+': '+'; '.join(value[:2]), 'web'))
                return items
        else:
            return getItem("Enter a translation query")

debugging

Copy the plugin to ~/.local/share/albert/org.albert.extension.python/modules, then enable the python plugin in the settings, and then you can load the python extension. This
can be used to print debugging in the code, and the printing information can be seen in the system log.info(query.string)

use

Input: tr hello
albert translator plugin
related

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325076997&siteId=291194637