315 字
2 分钟
Obsidian实现百度翻译

Obsidian 实现百度翻译#

obsidian 社区插件市场中安装插件 Search on Internet

申请 百度翻译API 后,在以下链接中填入 appid 以及 appkey 后填入插件配置中的 URL 栏,设置 to_lang 可以改变翻译的语言,具体查看百度翻译 API 文档

https://xxx/query?query={{query}}&appid={appid}&appkey={appkey}&to_lang=zh

选中文本后右键 Search on ***

完整代码

from flask import Flask, request, jsonify
import hashlib
import requests
import random

app = Flask(__name__)

# 设置appid/appkey.
# appid = 'appid'
# appkey = 'appkey'

from_lang = 'auto'
# to_lang = 'zh'

endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path


def make_md5(s, encoding='utf-8'):
    return hashlib.md5(s.encode(encoding)).hexdigest()


@app.route('/query', methods=['GET'])
def translate_query():
    try:
        # 获取查询参数
        query = request.args.get('query', '')
        appid = request.args.get('appid', '')
        appkey = request.args.get('appkey', '')
        to_lang = request.args.get('to_lang', '')

        # 随机生成salt
        salt = random.randint(32768, 65536)

        # 计算md5
        sign = make_md5(appid + query + str(salt) + appkey)

        # 构建请求参数
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

        # 发送请求到翻译API
        response = requests.post(url, params=payload, headers=headers)
        result = response.json()

        # 提取翻译结果
        translations = result.get("trans_result", [])
        output = []

        for item in translations:
            dst = item.get("dst", "")
            src = item.get("src", "")

            # 不再需要手动处理Unicode转义字符
            separate = "——————————————————————————————"
            output.append(f"{separate} <br> 译文: <br> {dst} <br><br> 原文: <br> {src} <br><br>")

        return "\n\n".join(output)

    except Exception as e:
        return jsonify({'error': str(e)}), 500


if __name__ == '__main__':
    app.run(debug=True, port=8081)

重启服务命令:systemctl restart myflaskapp.service

Obsidian实现百度翻译
https://blog.xbxin.com/posts/script/how-to-integrate-baidu-translation-in-obsidian/
作者
binxin
发布于
2023-11-22
许可协议
CC BY-NC-SA 4.0