feat: added google translate support (#131)

* added google translate support.

* format code using black.
This commit is contained in:
lizhimiao 2023-03-10 15:06:05 +08:00 committed by GitHub
parent 26fdfb0f0d
commit e6e4916ac4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 44 additions and 1 deletions

View File

@ -1,3 +1,7 @@
This forked added Google Translate support, only supported translate to `zh-CN`.
Usage: make sure to add `--model google` in the command.
**[中文](./README-CN.md) | English** **[中文](./README-CN.md) | English**
# bilingual_book_maker # bilingual_book_maker

View File

@ -48,7 +48,7 @@ def main():
dest="model", dest="model",
type=str, type=str,
default="chatgptapi", default="chatgptapi",
choices=["chatgptapi", "gpt3"], # support DeepL later choices=["chatgptapi", "gpt3", "google"], # support DeepL later
metavar="MODEL", metavar="MODEL",
help="model to use, available: {%(choices)s}", help="model to use, available: {%(choices)s}",
) )

View File

@ -1,8 +1,10 @@
from book_maker.translator.chatgptapi_translator import ChatGPTAPI from book_maker.translator.chatgptapi_translator import ChatGPTAPI
from book_maker.translator.gpt3_translator import GPT3 from book_maker.translator.gpt3_translator import GPT3
from book_maker.translator.google_translator import Google
MODEL_DICT = { MODEL_DICT = {
"chatgptapi": ChatGPTAPI, "chatgptapi": ChatGPTAPI,
"gpt3": GPT3, "gpt3": GPT3,
"google": Google
# add more here # add more here
} }

View File

@ -0,0 +1,37 @@
from .base_translator import Base
import requests
class Google(Base):
"""
google translate
"""
def __init__(self, key, language, api_base=None):
super().__init__(key, language)
self.api_url = "https://translate.google.com/translate_a/single?client=it&dt=qca&dt=t&dt=rmt&dt=bd&dt=rms&dt=sos&dt=md&dt=gt&dt=ld&dt=ss&dt=ex&otf=2&dj=1&hl=en&ie=UTF-8&oe=UTF-8&sl=auto&tl=zh-CN"
self.headers = {
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "GoogleTranslate/6.29.59279 (iPhone; iOS 15.4; en; iPhone14,2)",
}
# TODO support more models here
self.session = requests.session()
self.language = language
def rotate_key(self):
pass
def translate(self, text):
print(text)
r = self.session.post(
self.api_url,
headers=self.headers,
data="q={text}".format(text=requests.utils.quote(text)),
)
if not r.ok:
return text
t_text = "".join(
[sentence.get("trans", "") for sentence in r.json()["sentences"]]
)
print(t_text)
return t_text