-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTranslator.py
109 lines (104 loc) · 5.48 KB
/
Translator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import asyncio
import aiohttp
import time
import hashlib
import random
from urllib.parse import quote
class Translate:
tkk='428913.2184257098'#'428194.2961085901'
base_server='https://translate.google.cn/'
base_url='translate_a/single?client=webapp&sl=en&tl=zh-CN&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&source=btn&ssel=0&tsel=0&kc=0&tk='
headers={
'refer':base_server,
'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360EE'
}
youdao_headers={
'Host':'fanyi.youdao.com',
'Origin':'http://fanyi.youdao.com',
'Referer':'http://fanyi.youdao.com/'
}
youdao_url='http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
base_youdao_data={'from':'AUTO','to':'AUTO','smartresult':'dict','client':'fanyideskweb','doctype':'json','version':'2.1','keyfrom':'fanyi.web','action':'FY_BY_CLICKBUTTION','typoResult':'false'}
async def google_translate(self,text):
url=f'{self.base_server}{self.base_url}{self.tk(text)}&q={quote(text)}'
async with aiohttp.ClientSession() as session:
await session.get('https://translate.google.cn')#初始化一个cookie
return ''.join(list(map(lambda x:x[0] or '',(await self.base_get(session,url))[0])))
async def google_translate_list(self,text_list):
temp=[f'{self.base_server}{self.base_url}{self.tk(text)}&q={quote(text)}' for text in text_list]
async with aiohttp.ClientSession() as session:
await session.get('https://translate.google.cn')#初始化一个cookie
result,fail=await asyncio.wait([self.base_get(session,temp[i],index=i+1) for i in range(len(temp))])
js_result=map(lambda x:x[1],sorted([i.result() for i in result]))
return [''.join(list(map(lambda x:x[0] or '',k[0]))) for k in js_result]
async def base_get(self,session,url,index=None,headers=headers):
async with session.get(url,headers=headers) as resp:
if index:return [index,await resp.json()]
return await resp.json()
async def base_post(self,session,url,data,index=None,headers=youdao_headers):
async with session.post(url,headers=headers,data=data) as resp:
if index:return [index,await resp.json()]
return await resp.json()
def tk(self,text):
b = self.tkk if self.tkk != '0' else ''
d = b.split('.')
b = int(d[0]) if len(d) > 1 else 0
e = []
g = 0
size = len(text)
for i, char in enumerate(text):
l = ord(char)
if l < 128:e.append(l)
else:
if l < 2048:e.append(l >> 6 | 192)
else:
if (l & 64512) == 55296 and g + 1 < size and ord(text[g + 1]) & 64512 == 56320:
g += 1
l = 65536 + ((l & 1023) << 10) + ord(text[g]) & 1023
e.append(l >> 18 | 240)
e.append(l >> 12 & 63 | 128)
else:e.append(l >> 12 | 224)
e.append(l >> 6 & 63 | 128)
e.append(l & 63 | 128)
a = b
for i, value in enumerate(e):a = self._xr(a+value, '+-a^+6')
a = self._xr(a, '+-3^+b+-f')
a ^= int(d[1]) if len(d) > 1 else 0
if a < 0:a = (a & 2147483647) + 2147483648
a %= 1000000
return '{}.{}'.format(a, a ^ b)
def _xr(self, a, b):
size_b = len(b)
c = 0
while c < size_b - 2:
d = b[c + 2]
d = ord(d[0]) - 87 if 'a' <= d else int(d)
d = ((a % 0x100000000) >> d) if '+' == b[c + 1] else a << d
a = a + d & 4294967295 if '+' == b[c] else a ^ d
c += 3
return a
async def youdao_translate(self,text):
async with aiohttp.ClientSession(cookies={'___rl__test__cookies':int(time.time()*1000)}) as session:
await session.get('http://fanyi.youdao.com')#初始化一个cookie
temp=await self.base_post(self.youdao_url,self.youdao_data(text))
return self.youdao_combine(temp['translateResult'])
async def youdao_translate_list(self,text):
temp=[self.youdao_data(i) for i in text]
async with aiohttp.ClientSession(cookies={'___rl__test__cookies':int(time.time()*1000)}) as session:
await session.get('http://fanyi.youdao.com')#初始化一个cookie
result,fail=await asyncio.wait([self.base_post(session,self.youdao_url,temp[i],index=i+1) for i in range(len(temp))])
js_result=map(lambda x:x[1]['translateResult'],sorted([i.result() for i in result]))
return ['\n'.join([self.youdao_combine(i) for i in k]) for k in js_result]
def youdao_combine(self,todo):
if type(todo).__name__=='dict':return todo.get('tgt','')
return ''.join([self.youdao_combine(i) for i in todo])
def youdao_data(self,text):
text=text.lstrip('\ufeff')
temp_data={}
temp_data['i']=text
temp_data['salt']=str(int(time.time()*1000)+ random.randint(1,10))
temp_data['sign']=hashlib.md5(("fanyideskweb"+text+temp_data['salt']+"p09@Bn{h02_BIEe]$P^nG").encode('utf-8')).hexdigest()
temp_data={**self.base_youdao_data,**temp_data}
return temp_data
#result=asyncio.get_event_loop().run_until_complete(Translate().google_translate('nice'))
#result=asyncio.get_event_loop().run_until_complete(Translate().youdao_translate_list(['Hello','good','job']))