mirror of
https://github.com/yihong0618/bilingual_book_maker.git
synced 2025-06-06 11:35:49 +00:00
feat: added google translate support (#131)
* added google translate support. * format code using black.
This commit is contained in:
parent
26fdfb0f0d
commit
e6e4916ac4
@ -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**
|
||||
|
||||
# bilingual_book_maker
|
||||
|
@ -48,7 +48,7 @@ def main():
|
||||
dest="model",
|
||||
type=str,
|
||||
default="chatgptapi",
|
||||
choices=["chatgptapi", "gpt3"], # support DeepL later
|
||||
choices=["chatgptapi", "gpt3", "google"], # support DeepL later
|
||||
metavar="MODEL",
|
||||
help="model to use, available: {%(choices)s}",
|
||||
)
|
||||
|
@ -1,8 +1,10 @@
|
||||
from book_maker.translator.chatgptapi_translator import ChatGPTAPI
|
||||
from book_maker.translator.gpt3_translator import GPT3
|
||||
from book_maker.translator.google_translator import Google
|
||||
|
||||
MODEL_DICT = {
|
||||
"chatgptapi": ChatGPTAPI,
|
||||
"gpt3": GPT3,
|
||||
"google": Google
|
||||
# add more here
|
||||
}
|
||||
|
37
book_maker/translator/google_translator.py
Normal file
37
book_maker/translator/google_translator.py
Normal 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
|
Loading…
x
Reference in New Issue
Block a user