|
| 1 | +#!/usr/bin/python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +import json |
| 5 | +import os |
| 6 | +import re |
| 7 | + |
| 8 | +import click |
| 9 | +import coloredlogs |
| 10 | +from libs.decorator import withlog |
| 11 | +from libs.predicate import * |
| 12 | + |
| 13 | + |
| 14 | +@click.group() |
| 15 | +@click.option('-l', '--level', type=click.Choice(['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']), help='log level', |
| 16 | + default='INFO') |
| 17 | +def cli(level: str): |
| 18 | + coloredlogs.install(milliseconds=True, |
| 19 | + level=level, |
| 20 | + fmt='%(asctime)s:%(msecs)03d %(levelname)s %(programname)s::%(name)s [%(process)d] %(message)s', |
| 21 | + field_styles={'asctime': {'color': 'green'}, |
| 22 | + 'msecs': {'color': 'green'}, |
| 23 | + 'hostname': {'color': 'red'}, |
| 24 | + 'levelname': {'bold': True, 'color': 'magenta'}, |
| 25 | + 'name': {'faint': True, 'color': 'blue'}, |
| 26 | + 'programname': {'bold': True, 'color': 'cyan'}, |
| 27 | + 'process': {'faint': True, 'color': 'green'}, |
| 28 | + 'username': {'color': 'yellow'}}, |
| 29 | + level_styles={'critical': {'bold': True, 'color': 'red'}, |
| 30 | + 'debug': {'color': 'cyan'}, |
| 31 | + 'error': {'color': 'red'}, |
| 32 | + 'info': {'bright': True, 'color': 'white'}, |
| 33 | + 'notice': {'color': 'magenta'}, |
| 34 | + 'spam': {'color': 'green', 'faint': True}, |
| 35 | + 'success': {'bold': True, 'color': 'green'}, |
| 36 | + 'verbose': {'color': 'blue'}, |
| 37 | + 'warning': {'bright': True, 'color': 'yellow'}}) |
| 38 | + |
| 39 | + |
| 40 | +RE_OEIS_ID = re.compile(r'A\d+') |
| 41 | + |
| 42 | + |
| 43 | +@cli.command('clean') |
| 44 | +@click.argument('folder', type=click.Path(exists=True), default='data/detail') |
| 45 | +def _filter_results(folder): |
| 46 | + """Filter results |
| 47 | +
|
| 48 | + Remove all sequences with no valid formula""" |
| 49 | + |
| 50 | + def check(_single_result: dict) -> bool: |
| 51 | + return 'formula' in _single_result.keys() and 'data' in _single_result.keys() |
| 52 | + |
| 53 | + @withlog |
| 54 | + def filter_results(_result_folder: str, **kwargs): |
| 55 | + logger = kwargs.get('logger') |
| 56 | + |
| 57 | + __remove_cnt, __clean_cnt, __total_cnt = 0, 0, sum( |
| 58 | + len(filenames) for _, __, filenames in os.walk(_result_folder)) |
| 59 | + __flag: bool = True |
| 60 | + |
| 61 | + while __flag: |
| 62 | + __flag = False |
| 63 | + __id_set: set = set() |
| 64 | + for dir_path, _, filenames in os.walk(_result_folder): |
| 65 | + __id_set = __id_set.union( |
| 66 | + x.removesuffix('.json') for x in filter(lambda x: x.endswith('.json'), filenames)) |
| 67 | + |
| 68 | + for dir_path, _, filenames in os.walk(_result_folder): |
| 69 | + for name in filter(lambda x: x.endswith('.json'), filenames): |
| 70 | + filename = os.path.join(dir_path, name) |
| 71 | + logger.debug(f'reading {filename}') |
| 72 | + now_json: dict = json.load(open(filename, 'r')) |
| 73 | + if not check(now_json): |
| 74 | + logger.debug( |
| 75 | + f'remove {filename} because of failing check') |
| 76 | + os.remove(filename) |
| 77 | + __remove_cnt += 1 |
| 78 | + __flag = True |
| 79 | + else: |
| 80 | + new_formulas: list[str] = list( |
| 81 | + filter(lambda x: all(i in __id_set for i in re.findall(RE_OEIS_ID, x)), |
| 82 | + now_json['formula'])) |
| 83 | + if new_formulas: |
| 84 | + if now_json['formula'] != new_formulas: |
| 85 | + __clean_cnt += 1 |
| 86 | + now_json['formula'] = new_formulas |
| 87 | + json.dump(now_json, open(filename, 'w')) |
| 88 | + else: |
| 89 | + logger.debug( |
| 90 | + f'remove {filename} because of no valid formula') |
| 91 | + os.remove(filename) |
| 92 | + __remove_cnt += 1 |
| 93 | + __flag = True |
| 94 | + |
| 95 | + logger.info(f'{__remove_cnt} / {__total_cnt} result(s) removed') |
| 96 | + logger.info(f'{__clean_cnt} / {__total_cnt} result(s) cleaned') |
| 97 | + |
| 98 | + filter_results(click.format_filename(folder)) |
| 99 | + |
| 100 | + |
| 101 | +@cli.command('rmbad') |
| 102 | +@click.argument('folder', type=click.Path(exists=True), default='data/detail') |
| 103 | +def _remove_bad_results(folder): |
| 104 | + """Remove bad results""" |
| 105 | + |
| 106 | + @withlog |
| 107 | + def remove_bad_results(_result_folder: str, **kwargs): |
| 108 | + logger = kwargs.get('logger') |
| 109 | + |
| 110 | + __remove_cnt, __total_cnt = 0, 0 |
| 111 | + for dir_path, _, filenames in os.walk(_result_folder): |
| 112 | + for name in filter(lambda x: x.endswith('.json'), filenames): |
| 113 | + filename = os.path.join(dir_path, name) |
| 114 | + __total_cnt += 1 |
| 115 | + try: |
| 116 | + if not os.path.getsize(filename): |
| 117 | + raise Exception(f'Empty file: {filename}') |
| 118 | + if json.load(open(filename, 'r'))['number'] != int(name.removeprefix('A').removesuffix('.json')): |
| 119 | + raise Exception('Invalid result') |
| 120 | + except Exception as e: |
| 121 | + os.remove(filename) |
| 122 | + __remove_cnt += 1 |
| 123 | + logger.info(f'{__remove_cnt} / {__total_cnt} bad result(s) removed') |
| 124 | + |
| 125 | + remove_bad_results(click.format_filename(folder)) |
| 126 | + |
| 127 | + |
| 128 | +@cli.command('reduce') |
| 129 | +@click.option('-k', '--key', required=True, multiple=True, help='Key which will be removed') |
| 130 | +@click.argument('folder', type=click.Path(exists=True), default='data/detail') |
| 131 | +def _reduce_results(key: tuple[str, ...], folder): |
| 132 | + """Remove some keys in results""" |
| 133 | + |
| 134 | + @withlog |
| 135 | + def reduce_results(_key_removed: set[str], _result_folder: str, **kwargs): |
| 136 | + logger = kwargs.get('logger') |
| 137 | + |
| 138 | + for dir_path, _, filenames in os.walk(_result_folder): |
| 139 | + for name in filter(lambda x: x.endswith('.json'), filenames): |
| 140 | + filename = os.path.join(dir_path, name) |
| 141 | + json.dump(dict([(k, v) for k, v in json.load(open(filename, 'r')).items() if k not in _key_removed]), |
| 142 | + open(filename, 'w')) |
| 143 | + |
| 144 | + reduce_results(set(key), click.format_filename(folder)) |
| 145 | + |
| 146 | + |
| 147 | +if __name__ == '__main__': |
| 148 | + cli() |
0 commit comments