aboutsummaryrefslogtreecommitdiff
path: root/data_lib.py
blob: 5015fdcdb9acb1de7fb025add49e593a2f62b08e (plain)
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import os
import json
import re
import datetime
import time
from util import split_sen, rot_ru

CWD = os.path.dirname(os.path.realpath(__file__))

def _data_sort_len(i):
    return len(i['text'])

def _data_sort_date(i):
    return int(time.mktime(datetime.datetime.strptime(i['date'], '%d/%m/%y').timetuple()))

# sort: 'len', 'date'
def load_data(sort='len', sort_reverse=False, date=None, type=None):
    with open(os.path.join(CWD, "data.json")) as f:
        data = json.loads(f.read())

    # stringify all types
    for k, v in enumerate(data):
        if 'type' in data[k]:
            data[k]['type'] = str(data[k]['type'])
        else:
            data[k]['type'] = '1'

    # ignore placeholders
    data = list(filter(lambda i: i['text'] != '', data))

    # sort
    if sort == 'len':
        sort_f = _data_sort_len
    elif sort == 'date':
        sort_f = _data_sort_date
    else:
        raise Error("Unknown sort type " + str(sort))

    # filter by date
    data = sorted(data, key=sort_f, reverse=sort_reverse)

    if date:
        data = list(filter(lambda i: 'date' in i and i['date'] == date, data))

    if type:
        data = list(filter(lambda i: 'type' in i and i['type'] == str(type), data))

    return data

def clean_string(s, remove_junk=False):
    s = s.replace(')', ') ')
    s = re.sub(r'(\!|\.|\]|\,)([^\)])', r'\1 \2', s)
    #s = s.replace('/', ' ')
    s = s.upper()
    
    s = s.replace('/', ' ')
    s = re.sub(r'\s+', ' ', s).strip()

    junks = [
        'ВОЕННОЕ',
        'ВЫШЕСТОЯЩИХ',
        'ПРАВО',
        'ПРАВИЛАМ ВОЙНЫ',
        'ВЫПИСКА',
        'КОНТРОЛЬ',
        'ИХ',
        'ПО',
        'НАВЫКИ',
        'С ВЫШЕСТОЯЩИМИ',
        #'ПРИСУТСТВИЕ',
        #'ЛИНЕЙНО',
        'ИНСТРУКЦИИ',
        'ЗАКОННО',
        'ПОХЛЕБКА',
        'СВЯЗЕЙ',
        'ЖУЮЩЕГО ХРЯЩИ',
        'ИНДЕКСИРОВАН БЕЗУКОРИЗНЕНННО',
        'ИНДЕКСИРОВАН БЕЗУКОРИЗНЕННО',
        'ОТКЛАДЫВАЕТСЯ ЛИНЕЙНО',
        'УСТАЛИ СМОТРЯЩИХ',
        '- ЕГО ВЕЛИЧЕСТВО',
        'ГУБЕРНИЯ',
        'С ВЫШЕСТОЯЩИМИ КОНТРОЛЬ',
         'С ЛОКАЦИИ',
        'КАЗНЬ ВЫШЕСТОЯЩ',
        #'КАЗНЬ',
        'ГУБЕРНИЯ',
        'ПРОВЕРКИ',
        'УСТАНОВЛЕНО',
        'ПОБЕДИТЕЛЕМ',
        #'СТАЛЬНЫЕ',
        'НЕРВЫ',
        'ДАРОВАНО',
        #'ТРАНСПОРТИРОВКА',
        'ОДОБРЕНО',
        'ПРОЯВЛЕНИЯ',
        'УЗАКОНЕНО',
        'ИМЕЕТСЯ',
        'ЗНАЛ',
        'НЕ ПРИМЕЧЕНО',
        'НА СЕВЕР',
        'ПРИГОВОРИТЬ',
        'ШЕСТВУЕМ',
        'ДАГОН',
        'ДА МЕРЗНУЩИЙ',
        'КОФЕ',
        #'РЕАГИРОВАНИЕ',
        'УКАЗАНО',
        '- ВЫСОКИЙ ТИТУЛ',
        'ЗАКАЗ',
        'ЧЕРТЫ ЛИЦА',
        
        # english
        'SCHOOL ON THE RIGHT',
        'WILL NOT ALLOW',
        'FLYWHEEL',
        'TRIUMPHANTLY',
        'BEING USED',
        'NICE',
        'UMBRELLA',
        #'BIOROBOT',
        'CONSERVATISM',
        'WAS ESTABLISHED',
        'WITH A PASSWORD',
        'ANT',
        'YEAR',
        'RECOGNIZED',
        'SEARCHED'
        #'LEGAL',
        #'FIGHTING'
    ]

    # только без пробелов
    junks_words = list(filter(lambda w: ' ' not in w, junks))

    # только с пробелами
    junks_nwords = list(filter(lambda w: w not in junks_words, junks))
    #print(junks_nwords)

    if remove_junk:
        s = s.split(' ')
        s = list(filter(lambda l: re.sub(r'\.|\!|,$', '', l) not in junks_words, s))
        s = ' '.join(s)

        for j in junks_nwords:
            s = s.replace(j, '')

        s = s.replace('Х О Р Т И Ц А', 'Х_О_Р_Т_И_Ц_А')
        s = s.replace('ЯРОСЛАВСКАЯ ГУБЕРНИЯ', 'ЯРОСЛАВСКАЯ_ГУБЕРНИЯ')
        s = s.replace('ЩУКА В МЕШКЕ', 'ЩУКА_В_МЕШКЕ')
        s = s.replace('Ъ - ВЕЛИЧЕСТВЕННО', 'Ъ_-_ВЕЛИЧЕСТВЕННО')
    
    s = re.sub(r'\s+', ' ', s).strip()
    return s

def decode(s, is_url=False):
    buf = ''
    for word in s.split(' '):
        word = word.strip()
        if word == '' or word == '!':
            continue

        if re.match(r'^\d+', word):
            buf += word
        elif is_url and word.endswith('://'):
            buf += word[0]
            buf += '://'
        else:
            letter = word[0]
            buf += letter
    
    return buf

def decode2(s):
    buf = ''
    for s in re.split(r'[\?\.\!]+', s):
        s = s.strip()
        if s == '':
            continue

        words = s.split(' ')

        letter = words[1][0]
        buf += letter

    return buf

def decode3(s):
    buf = ''
    for s in re.split(r'[\?\.\!]+', s):
        s = s.strip()
        s = s.replace(' ', '')
        s = s.replace('-', '')
        if not s:
            continue

        print(s)
        continue

        s = s.upper()

        if s[0] in ('Ш', 'Щ', 'И'):
            buf += s[0]
        elif s[4] == 'Й':
            buf += s[4]
        elif s[0] == 'И':
            buf += 'И'
        elif s[7] == 'М':
            buf += 'М'
        elif s[4] == 'А':
            buf += 'А'
        elif s[2] == 'Р':
            buf += 'Р'
        elif s[1] == 'У':
            buf += 'У'
        elif s[9] == 'Ю':
            buf += 'Ю'
        else:
            buf += '?'

    return buf


def decode_2char_rot_minus3(s):
    lines = split_sen(s)
    buf = ''
    for line in lines:
        line = line.replace(' ', '')
        if re.sub(r'[\.\!\?\\/]', '', line).isdigit():
            buf += line
            continue
        buf += line[1]

    rots = rot_ru(buf, return_list=True)
    return rots[len(rots)-2]

    


# s: source
# t: type
def decode_auto(s, t, reverse_decoded=False, remove_junk=True):
    if t == '1':
        s = clean_string(s, remove_junk=remove_junk)
        result = decode(s)
    
    elif t == '2':
        result = decode2(s)

    elif t == '3':
        result = decode3(s)

    elif t == '2char_rot-3':
        result = decode_2char_rot_minus3(s)

    if reverse_decoded:
        # reverse string
        result = result[::-1]

    return result