Install the plugin "Search on Internet" in the "obsidian" community plugin marketplace.
Apply for the Baidu Translation API, and fill in the appid
and appkey
in the following link, and then fill in the URL
column in the plugin configuration. Setting to_lang
can change the language of translation. For more details, please refer to the Baidu Translation API documentation.
https://xxx/query?query={{query}}&appid={appid}&appkey={appkey}&to_lang=zh
Right-click on the selected text and choose "Search on ***".
Complete code
from flask import Flask, request, jsonify
import hashlib
import requests
import random
app = Flask(__name__)
# Set 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:
# Get query parameters
query = request.args.get('query', '')
appid = request.args.get('appid', '')
appkey = request.args.get('appkey', '')
to_lang = request.args.get('to_lang', '')
# Generate a random salt
salt = random.randint(32768, 65536)
# Calculate md5
sign = make_md5(appid + query + str(salt) + appkey)
# Build request parameters
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
# Send request to translation API
response = requests.post(url, params=payload, headers=headers)
result = response.json()
# Extract translation results
translations = result.get("trans_result", [])
output = []
for item in translations:
dst = item.get("dst", "")
src = item.get("src", "")
# No longer need to manually handle Unicode escape characters
separate = "——————————————————————————————"
output.append(f"{separate} <br> Translation: <br> {dst} <br><br> Original: <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)
Restart the service command:
systemctl restart myflaskapp.service