improve decoding of type1 ciphertexts

This commit is contained in:
rusinthread 2017-01-07 23:57:44 +03:00
parent b08c2582ec
commit 5bf61081d3
4 changed files with 42 additions and 23 deletions

View File

@ -38,7 +38,7 @@
В ответ получаешь:
```
ФОТОРОБОТ80%ТОЧЗНОСТЬ
ФОТОРОБОТ80%ТОЧНОСТЬ
```
## Другое

View File

@ -1,21 +1,41 @@
import os
import json
import re
import datetime
import time
CWD = os.path.dirname(os.path.realpath(__file__))
def load_data():
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):
with open(os.path.join(CWD, "data.json")) as f:
data = json.loads(f.read())
# 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))
data = sorted(data, key=sort_f, reverse=sort_reverse)
return data
def clean_string(s, remove_junk=False):
s = s.replace(')', ') ')
s = re.sub(r'(\!|\.)([^\)])', r'\1 \2', s)
s = re.sub(r'(\!|\.|\]|\,)([^\)])', r'\1 \2', s)
#s = s.replace('/', ' ')
s = s.upper()
@ -35,16 +55,20 @@ def clean_string(s, remove_junk=False):
'С ВЫШЕСТОЯЩИМИ',
#'ПРИСУТСТВИЕ',
#'ЛИНЕЙНО',
'ЗАКОННО!',
'ИНСТРУКЦИИ',
'ЗАКОННО',
'ПОХЛЕБКА',
'СВЯЗЕЙ',
'ЖУЮЩЕГО ХРЯЩИ',
'ИНДЕКСИРОВАН БЕЗУКОРИЗНЕНННО',
'ИНДЕКСИРОВАН БЕЗУКОРИЗНЕННО',
'ОТКЛАДЫВАЕТСЯ ЛИНЕЙНО',
'УСТАЛИ СМОТРЯЩИХ',
'- ЕГО ВЕЛИЧЕСТВО',
'ГУБЕРНИЯ',
'С ВЫШЕСТОЯЩИМИ КОНТРОЛЬ',
'С ЛОКАЦИИ',
'С ЛОКАЦИИ',
'КАЗНЬ ВЫШЕСТОЯЩ',
#'КАЗНЬ',
'ГУБЕРНИЯ',
'ПРОВЕРКИ',
@ -97,17 +121,20 @@ def clean_string(s, remove_junk=False):
# только с пробелами
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 = 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
@ -116,7 +143,7 @@ def decode(s, is_url=False):
buf = ''
for word in s.split(' '):
word = word.strip()
if word == '':
if word == '' or word == '!':
continue
if re.match(r'^\d+', word):

View File

@ -1,6 +1,4 @@
#!/usr/bin/python3.4
import datetime
import time
import sys
import os
import shutil
@ -26,9 +24,6 @@ MD_START = """
"""
def sort_data_by_date(item):
return int(time.mktime(datetime.datetime.strptime(item['date'], '%d/%m/%y').timetuple()))
def resize(in_path, out_path):
subprocess.call(['convert', in_path, '-resize', '250', out_path])
@ -46,8 +41,7 @@ def gen_previews():
resize(img_path, img_preview_path)
def main():
data = load_data()
data = sorted(data, key=sort_data_by_date)
data = load_data(sort='date')
print("Generating previews (don't forget to git add them)...")
gen_previews()

12
main.py
View File

@ -3,6 +3,7 @@
import argparse
import sys
import os
from pprint import pprint
try:
from termcolor import cprint
@ -10,7 +11,7 @@ try:
except ImportError:
colors_supported = False
from data_lib import load_data, decode_auto
from data_lib import load_data, decode_auto, clean_string
def print_colored(s, color, fallback_prefix=''):
@ -32,8 +33,8 @@ def main():
parser.add_argument('--reverse-decoded', action='store_true')
args = parser.parse_args()
data = load_data()
data = load_data('date', sort_reverse=True)
if args.decode:
# filter by type
if args.type == 2:
@ -41,9 +42,6 @@ def main():
else:
data = list(filter(lambda i: 'type' not in i, data))
# sort by text length
data = sorted(data, key=lambda i: len(i['text']))
for obj in data:
text = obj['text']
text_decoded = decode_auto(text,
@ -53,7 +51,7 @@ def main():
# print all information
print(obj['text'])
print_colored(text, 'green', fallback_prefix='[CLEANED] ')
print_colored(clean_string(text, remove_junk=(not args.with_junk)), 'green', fallback_prefix='[CLEANED] ')
print_colored(text_decoded, 'cyan', fallback_prefix='[DECODED] ')
if 'pic' in obj: