-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_chat.py
More file actions
76 lines (67 loc) · 2.25 KB
/
Copy pathjson_chat.py
File metadata and controls
76 lines (67 loc) · 2.25 KB
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
from __future__ import print_function
from itertools import *
import os.path
import json
import sys
import re
class DecodeError(Exception):
pass
def load_language(file):
try:
return json.load(file)
except ValueError:
language = dict()
for line in file:
try: name, value = line.split('=', 1)
except ValueError: continue
language[name] = value.strip()
return language
with open(os.path.join(os.path.dirname(__file__), './en_us.json')) as file:
language = load_language(file)
def decode_string(data):
try:
return decode_struct(json.loads(data))
except DecodeError as e:
print(e, file=sys.stderr)
return data
def decode_struct(data):
if isinstance(data, str):
return data
elif isinstance(data, list):
return ''.join(decode_struct(part) for part in data)
elif isinstance(data, dict):
if 'text' in data:
result = decode_struct(data['text'])
elif 'translate' in data:
using = data.get('using') or data.get('with') or []
using = [decode_struct(item) for item in using]
result = translate(data['translate'], using)
else:
raise DecodeError
if 'extra' in data:
result += decode_struct(data['extra'])
return result
else:
raise DecodeError
def translate(id, params):
if id not in language: raise DecodeError
ord_params = params[:]
def repl(match):
if match.group() == '%%':
return '%'
elif match.group('index'):
index = int(match.group('index')) - 1
if index >= len(params): raise DecodeError(
'Index %s in "%s" out of bounds for %s.'
% (match.group(), language[id], params))
param = params[index]
elif match.group('rest') != '%':
if not ord_params: raise DecodeError(
'Too few arguments for "%s" in %s.'
% (language[id], params))
param = ord_params.pop(0)
rest = match.group('rest')
return ('%' + rest) % (int(param) if rest == 'd' else param)
return re.sub(
r'%((?P<index>\d+)\$)?(?P<rest>(\.\d+)?[a-zA-Z%])',
repl, language[id])