2017-03-10 11:19:46 +01:00
|
|
|
"""A conversion module for googletrans"""
|
|
|
|
import json
|
2020-06-14 08:42:32 +02:00
|
|
|
import re
|
2017-03-10 11:19:46 +01:00
|
|
|
|
2017-03-10 14:44:39 +01:00
|
|
|
|
2020-02-08 09:17:31 +01:00
|
|
|
def build_params(query, src, dest, token, override):
|
2017-03-10 14:44:39 +01:00
|
|
|
params = {
|
2019-02-05 09:30:09 +01:00
|
|
|
'client': 'webapp',
|
2017-03-10 14:44:39 +01:00
|
|
|
'sl': src,
|
|
|
|
'tl': dest,
|
|
|
|
'hl': dest,
|
|
|
|
'dt': ['at', 'bd', 'ex', 'ld', 'md', 'qca', 'rw', 'rm', 'ss', 't'],
|
|
|
|
'ie': 'UTF-8',
|
|
|
|
'oe': 'UTF-8',
|
|
|
|
'otf': 1,
|
|
|
|
'ssel': 0,
|
|
|
|
'tsel': 0,
|
|
|
|
'tk': token,
|
|
|
|
'q': query,
|
|
|
|
}
|
2020-02-08 09:17:31 +01:00
|
|
|
|
|
|
|
if override is not None:
|
|
|
|
for key, value in get_items(override):
|
|
|
|
params[key] = value
|
|
|
|
|
2017-03-10 14:44:39 +01:00
|
|
|
return params
|
|
|
|
|
|
|
|
|
2017-10-02 16:26:34 +02:00
|
|
|
def legacy_format_json(original):
|
2017-03-10 11:19:46 +01:00
|
|
|
# save state
|
|
|
|
states = []
|
|
|
|
text = original
|
2020-06-08 12:09:24 +02:00
|
|
|
|
2017-10-02 16:26:34 +02:00
|
|
|
# save position for double-quoted texts
|
2017-03-10 11:19:46 +01:00
|
|
|
for i, pos in enumerate(re.finditer('"', text)):
|
2017-10-02 16:26:34 +02:00
|
|
|
# pos.start() is a double-quote
|
2017-03-10 11:19:46 +01:00
|
|
|
p = pos.start() + 1
|
|
|
|
if i % 2 == 0:
|
|
|
|
nxt = text.find('"', p)
|
|
|
|
states.append((p, text[p:nxt]))
|
|
|
|
|
|
|
|
# replace all weired characters in text
|
|
|
|
while text.find(',,') > -1:
|
|
|
|
text = text.replace(',,', ',null,')
|
|
|
|
while text.find('[,') > -1:
|
|
|
|
text = text.replace('[,', '[null,')
|
|
|
|
|
|
|
|
# recover state
|
|
|
|
for i, pos in enumerate(re.finditer('"', text)):
|
|
|
|
p = pos.start() + 1
|
|
|
|
if i % 2 == 0:
|
|
|
|
j = int(i / 2)
|
|
|
|
nxt = text.find('"', p)
|
|
|
|
# replacing a portion of a string
|
|
|
|
# use slicing to extract those parts of the original string to be kept
|
|
|
|
text = text[:p] + states[j][1] + text[nxt:]
|
|
|
|
|
|
|
|
converted = json.loads(text)
|
|
|
|
return converted
|
|
|
|
|
|
|
|
|
2020-02-08 09:17:31 +01:00
|
|
|
def get_items(dict_object):
|
|
|
|
for key in dict_object:
|
|
|
|
yield key, dict_object[key]
|
|
|
|
|
|
|
|
|
2017-10-02 16:26:34 +02:00
|
|
|
def format_json(original):
|
|
|
|
try:
|
|
|
|
converted = json.loads(original)
|
|
|
|
except ValueError:
|
|
|
|
converted = legacy_format_json(original)
|
2018-05-06 14:14:06 +02:00
|
|
|
|
2017-10-02 16:26:34 +02:00
|
|
|
return converted
|
|
|
|
|
|
|
|
|
2017-03-10 11:19:46 +01:00
|
|
|
def rshift(val, n):
|
|
|
|
"""python port for '>>>'(right shift with padding)
|
|
|
|
"""
|
2017-03-10 14:44:39 +01:00
|
|
|
return (val % 0x100000000) >> n
|