Skip to content

Instantly share code, notes, and snippets.

@BobDu
Created April 24, 2020 03:48
Show Gist options
  • Save BobDu/e9e8904ae827709cd99ea3343cf66e3e to your computer and use it in GitHub Desktop.
Save BobDu/e9e8904ae827709cd99ea3343cf66e3e to your computer and use it in GitHub Desktop.
google translate api
import time
import hashlib
import html
from urllib import parse
import logging
import urllib3
import requests
import execjs
logger = logging.getLogger(__name__)
GET_TK_JS = """
function TL(a) {
var k = "";
var b = 406644;
var b1 = 3293161072;
var jd = ".";
var $b = "+-a^+6";
var Zb = "+-3^+b+-f";
for (var e = [], f = 0, g = 0; g < a.length; g++) {
var m = a.charCodeAt(g);
128 > m ? e[f++] = m : (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023),
e[f++] = m >> 18 | 240,
e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224,
e[f++] = m >> 6 & 63 | 128),
e[f++] = m & 63 | 128)
}
a = b;
for (f = 0; f < e.length; f++) a += e[f],
a = RL(a, $b);
a = RL(a, Zb);
a ^= b1 || 0;
0 > a && (a = (a & 2147483647) + 2147483648);
a %= 1E6;
return a.toString() + jd + (a ^ b)
};
function RL(a, b) {
var t = "a";
var Yb = "+";
for (var c = 0; c < b.length - 2; c += 3) {
var d = b.charAt(c + 2),
d = d >= t ? d.charCodeAt(0) - 87 : Number(d),
d = b.charAt(c + 1) == Yb ? a >>> d: a << d;
a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d
}
return a
}
"""
def get_tk(text: str):
ctx = execjs.compile(GET_TK_JS)
tk = ctx.call('TL', text)
return tk
def translate_get(text):
translate_url = 'https://translate.google.cn/translate_a/single'
params = {
'client': 'webapp',
'sl': 'en',
'tl': 'zh-CN',
'dt': 't',
'tk': get_tk(text),
'q': text,
}
zh_text_list = []
try:
trynum = 0
while trynum < 5:
try:
resp = requests.get(translate_url, params=params, timeout=5)
zz = resp.json()[0]
break
except Exception as e:
logger.debug('translate error',exc_info=True)
logger.debug(text, exc_info=True)
logger.debug(e,exc_info=True)
trynum += 1
continue
for index, texts in enumerate(zz):
if texts[0]:
zh_text_list.append(texts[0])
return ' '.join(zh_text_list)
except Exception as e:
logger.debug(e,exc_info=True)
return 'too long'
def translate_post(text):
translate_post_url = 'https://translate.google.cn/translate_a/t'
params = {
'client': 'te_lib',
'format': 'html',
'v': '1.0',
'sl': 'en',
'tl': 'zh-CN',
# 'sp': 'nmt',
# 'tc': '1',
# 'sr': '1',
'tk': get_tk(text),
# 'mode': '1',
}
data = {
'q': text,
}
resp = requests.post(translate_post_url, params=params, data=data, timeout=5)
if resp.status_code != 200:
logger.error('Response code is: {}, Request body is: {}'.format(resp.status_code, resp.request.body))
raise Exception
translation = resp.json()
translation = html.unescape(translation)
return translation
def translate(raw_text, post=True):
if not raw_text.strip():
return ''
text = html.unescape(raw_text)
if post:
return translate_post(text)
else:
return translate_get(text)
if __name__ == "__main__":
# res = translate("""In this article, we construct the [sc]A[s ?c ?]V ?[sc]V[s ?c ?]A-type tensor cur-
# rent to study the mass and width of the X(4274) with the QCD sum
# rules in detail. The predicted mass MX = (4.27 ± 0.09) GeV for the
# JPC = 1++ tetraquark state is in excellent agreement with the experi-
# mental data 4273.3 ± 8.3+17.2 MeV from the LHCb Collaboration. The ?3.6
# central value of the width Γ(X(4274) → J/ψφ) = 47.9 MeV is in excellent agreement with the experimental data 56 ± 11+8 MeV from the LHCb
# ?11
# Collaboration. The present work supports assigning the X(4274) to be
# the J P C = 1++ [sc]A [s ?c ?]V ? [sc]V [s ?c ?]A tetraquark state with a relative P-wave between the diquark and antidiquark constituents. Furthermore, we obtain the mass of the [sc]A[s ?c ?]V ?[sc]V[s ?c ?]A-type tetraquark state with JPC = 1?+ as a byproduct.
# """)
logging.basicConfig(level=logging.DEBUG)
# translate('Study of semileptonic decays of neutral kaons allows to perform a test of discrete symmetries, as well as basic principles of the Standard Model. In this paper, a general review on dependency between charge asymmetry constructed for semileptonic decays of short- and long-lived kaons and $\mathcal{CPT}$ symmetry is given.')
res = translate("""I think that the best way to learn Java (or any other skills) is by doing it. This book includes visual charts that you'll guide you and help you learn those specific codes that you want to learn really fast. And in this way, believe me that you'll have an immense sense of achievement and it’ll also help you retain the knowledge and master the language.""")
print(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment