166 lines
7.5 KiB
Python
166 lines
7.5 KiB
Python
from googletrans import Translator
|
|
import requests
|
|
import hashlib
|
|
import time
|
|
import traceback
|
|
|
|
class TranslatorNode:
|
|
NODE_NAME = "Basic Translator 🦉| OwlV"
|
|
@classmethod
|
|
def INPUT_TYPES(cls):
|
|
return {
|
|
"required": {
|
|
"text": ("STRING", {
|
|
"multiline": True,
|
|
"default": ""
|
|
}),
|
|
"target_language": (["English", "Chinese", "Japanese", "Korean", "French", "German", "Spanish", "Italian", "Russian", "Portuguese"], {
|
|
"default": "English"
|
|
}),
|
|
"translator_service": (["Google Translate", "Baidu Translate", "Youdao Translate", "Tencent Translate"], {
|
|
"default": "Google Translate"
|
|
}),
|
|
},
|
|
"optional": {
|
|
"baidu_app_id": ("STRING", {"default": ""}),
|
|
"baidu_secret_key": ("STRING", {"default": ""}),
|
|
"youdao_app_id": ("STRING", {"default": ""}),
|
|
"youdao_secret_key": ("STRING", {"default": ""}),
|
|
"tencent_secret_id": ("STRING", {"default": ""}),
|
|
"tencent_secret_key": ("STRING", {"default": ""}),
|
|
}
|
|
}
|
|
|
|
RETURN_TYPES = ("STRING",)
|
|
RETURN_NAMES = ("translated_text",)
|
|
FUNCTION = "translate"
|
|
CATEGORY = "Text Processing"
|
|
|
|
def translate(self, text, target_language, translator_service,
|
|
baidu_app_id="", baidu_secret_key="",
|
|
youdao_app_id="", youdao_secret_key="",
|
|
tencent_secret_id="", tencent_secret_key=""):
|
|
# 语言映射字典 - 支持多个翻译服务的语言代码
|
|
language_map = {
|
|
"English": {"google": "en", "baidu": "en", "youdao": "en", "tencent": "en"},
|
|
"Chinese": {"google": "zh-cn", "baidu": "zh", "youdao": "zh-CHS", "tencent": "zh"},
|
|
"Japanese": {"google": "ja", "baidu": "jp", "youdao": "ja", "tencent": "ja"},
|
|
"Korean": {"google": "ko", "baidu": "kor", "youdao": "ko", "tencent": "ko"},
|
|
"French": {"google": "fr", "baidu": "fra", "youdao": "fr", "tencent": "fr"},
|
|
"German": {"google": "de", "baidu": "de", "youdao": "de", "tencent": "de"},
|
|
"Spanish": {"google": "es", "baidu": "spa", "youdao": "es", "tencent": "es"},
|
|
"Italian": {"google": "it", "baidu": "it", "youdao": "it", "tencent": "it"},
|
|
"Russian": {"google": "ru", "baidu": "ru", "youdao": "ru", "tencent": "ru"},
|
|
"Portuguese": {"google": "pt", "baidu": "pt", "youdao": "pt", "tencent": "pt"}
|
|
}
|
|
|
|
if not text or not text.strip():
|
|
return ("",)
|
|
|
|
try:
|
|
# 获取目标语言代码
|
|
target_lang = language_map.get(target_language, {
|
|
"google": "en", "baidu": "en", "youdao": "en", "tencent": "en"
|
|
})
|
|
|
|
# 根据选择的翻译服务调用对应的方法
|
|
if translator_service == "Google Translate":
|
|
return self._google_translate(text, target_lang["google"])
|
|
elif translator_service == "Baidu Translate":
|
|
if not baidu_app_id or not baidu_secret_key:
|
|
return ("Baidu Translate requires App ID and secret key. Please configure them in the optional parameters.",)
|
|
return self._baidu_translate(text, target_lang["baidu"], baidu_app_id, baidu_secret_key)
|
|
elif translator_service == "Youdao Translate":
|
|
if not youdao_app_id or not youdao_secret_key:
|
|
return ("Youdao Translate requires App ID and secret key. Please configure them in the optional parameters.",)
|
|
return self._youdao_translate(text, target_lang["youdao"], youdao_app_id, youdao_secret_key)
|
|
elif translator_service == "Tencent Translate":
|
|
if not tencent_secret_id or not tencent_secret_key:
|
|
return ("Tencent Translate requires Secret ID and secret key. Please configure them in the optional parameters.",)
|
|
return self._tencent_translate(text, target_lang["tencent"], tencent_secret_id, tencent_secret_key)
|
|
else:
|
|
return ("Unsupported translation service.",)
|
|
|
|
except Exception as e:
|
|
error_msg = f"Translation failed: {str(e)}"
|
|
print(f"Translator node error: {error_msg}")
|
|
print(f"Error details: {traceback.format_exc()}")
|
|
return (error_msg,)
|
|
|
|
def _google_translate(self, text, target_lang):
|
|
"""Google Translate - suitable for international network environments"""
|
|
translator = Translator()
|
|
result = translator.translate(text, dest=target_lang)
|
|
return (result.text,)
|
|
|
|
def _baidu_translate(self, text, target_lang, app_id, secret_key):
|
|
"""Baidu Translate - suitable for mainland China network environments"""
|
|
# 生成签名
|
|
salt = str(int(time.time() * 1000))
|
|
sign_str = app_id + text + salt + secret_key
|
|
sign = hashlib.md5(sign_str.encode('utf-8')).hexdigest()
|
|
|
|
# 构建请求
|
|
url = "https://fanyi-api.baidu.com/api/trans/vip/translate"
|
|
params = {
|
|
'q': text,
|
|
'from': 'auto',
|
|
'to': target_lang,
|
|
'appid': app_id,
|
|
'salt': salt,
|
|
'sign': sign
|
|
}
|
|
|
|
response = requests.get(url, params=params, timeout=10)
|
|
result = response.json()
|
|
|
|
if 'trans_result' in result:
|
|
return (result['trans_result'][0]['dst'],)
|
|
else:
|
|
error_code = result.get('error_code', '未知')
|
|
error_msg = result.get('error_msg', '未知错误')
|
|
return (f"Baidu Translate error [{error_code}]: {error_msg}",)
|
|
|
|
def _youdao_translate(self, text, target_lang, app_id, secret_key):
|
|
"""Youdao Translate - suitable for mainland China network environments"""
|
|
# 生成签名
|
|
salt = str(int(time.time() * 1000))
|
|
curtime = str(int(time.time()))
|
|
sign_str = app_id + self._truncate(text) + salt + curtime + secret_key
|
|
sign = hashlib.sha256(sign_str.encode('utf-8')).hexdigest()
|
|
|
|
# 构建请求
|
|
url = "https://openapi.youdao.com/api"
|
|
data = {
|
|
'q': text,
|
|
'from': 'auto',
|
|
'to': target_lang,
|
|
'appKey': app_id,
|
|
'salt': salt,
|
|
'sign': sign,
|
|
'signType': 'v3',
|
|
'curtime': curtime
|
|
}
|
|
|
|
response = requests.post(url, data=data, timeout=10)
|
|
result = response.json()
|
|
|
|
if result.get('errorCode') == '0':
|
|
return (result['translation'][0],)
|
|
else:
|
|
error_code = result.get('errorCode', '未知')
|
|
return (f"Youdao Translate error code: {error_code}",)
|
|
|
|
def _tencent_translate(self, text, target_lang, secret_id, secret_key):
|
|
"""Tencent Translate - requires Tencent Cloud SDK; currently a basic framework"""
|
|
# Note: A full implementation requires the Tencent Cloud SDK and its signing algorithms
|
|
# This provides a basic framework; installing tencentcloud-sdk-python is recommended for production use
|
|
return ("Tencent Translate requires the Tencent Cloud SDK. Consider using Baidu or Youdao Translate instead.",)
|
|
|
|
def _truncate(self, q):
|
|
"""有道翻译签名需要的文本截断方法"""
|
|
if q is None:
|
|
return None
|
|
size = len(q)
|
|
return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]
|