|
| 1 | +from typing import Tuple, Dict, Any, Optional, List |
| 2 | +import sys |
| 3 | +import json |
| 4 | +import argparse |
| 5 | + |
| 6 | +DELIM = "__" |
| 7 | + |
| 8 | + |
| 9 | +class Serializable: |
| 10 | + def __init__(self): |
| 11 | + pass |
| 12 | + |
| 13 | + # Export Methods |
| 14 | + def export_dict(self) -> Dict[str, Any]: |
| 15 | + """export dictionary recursively |
| 16 | + |
| 17 | + Returns: |
| 18 | + Dictionary that consists child arguments recursively. |
| 19 | + """ |
| 20 | + # Get current item in dictionary |
| 21 | + parent_dict = self.__dict__.copy() |
| 22 | + |
| 23 | + # Build child dictionary recursively |
| 24 | + for key, obj in parent_dict.items(): |
| 25 | + if isinstance(obj, Serializable): |
| 26 | + parent_dict[key] = obj.export_dict() |
| 27 | + |
| 28 | + return parent_dict |
| 29 | + |
| 30 | + def export_json(self, path: str, ignore_error=True) -> bool: |
| 31 | + """ |
| 32 | +
|
| 33 | + Args: |
| 34 | + path: path of json file to be saved. |
| 35 | +
|
| 36 | + Returns: |
| 37 | + succeed saving json file or not. |
| 38 | + """ |
| 39 | + succeed = True |
| 40 | + try: |
| 41 | + # extract dictionary |
| 42 | + extracted_dict = self.export_dict() |
| 43 | + |
| 44 | + # save as json |
| 45 | + with open(path, 'w') as file: |
| 46 | + file.write(json.dumps(extracted_dict, ensure_ascii=False)) |
| 47 | + except Exception as e: |
| 48 | + succeed= False |
| 49 | + print(e) |
| 50 | + if not ignore_error: |
| 51 | + sys.exit() |
| 52 | + return succeed |
| 53 | + |
| 54 | + # Import Methods |
| 55 | + def import_dict(self, data: Dict[str, Any]): |
| 56 | + """Import arguments from dictionary |
| 57 | + |
| 58 | + Args: |
| 59 | + data: dictionary that consists child argument recursively. |
| 60 | + """ |
| 61 | + for key, value in data.items(): |
| 62 | + if hasattr(self, key): |
| 63 | + if isinstance(getattr(self, key), Serializable): |
| 64 | + setattr(self, key, getattr(self, key).import_dict(value)) |
| 65 | + else: |
| 66 | + setattr(self, key, value) |
| 67 | + return self |
| 68 | + |
| 69 | + @classmethod |
| 70 | + def import_json(cls, path: str, ignore_error: bool = True)\ |
| 71 | + -> Tuple[bool, Optional['Serializable']]: |
| 72 | + try: |
| 73 | + with open(path, 'r') as file: |
| 74 | + data = json.load(file) |
| 75 | + return True, cls().import_dict(data) |
| 76 | + except Exception as e: |
| 77 | + print(e) |
| 78 | + if not ignore_error: |
| 79 | + sys.exit() |
| 80 | + return False, None |
| 81 | + |
| 82 | + # Parsing related method |
| 83 | + def parse(self): |
| 84 | + """Implement argument parsing functionality based on object elements |
| 85 | + """ |
| 86 | + parser = argparse.ArgumentParser() |
| 87 | + for key, value in self.strip_dict().items(): |
| 88 | + parser.add_argument('--{}'.format(key), type=type(value)) |
| 89 | + args = parser.parse_args() |
| 90 | + print(vars(args)) |
| 91 | + self.unstrip_dict(vars(args)) |
| 92 | + |
| 93 | + # Utility |
| 94 | + def strip_dict(self, prefix: str = "") -> Dict[str, Any]: |
| 95 | + """Strips dictionary recursively. |
| 96 | +
|
| 97 | + Args: |
| 98 | + prefix: prefix string. |
| 99 | +
|
| 100 | + Returns: |
| 101 | + dictionary with stripped keys. |
| 102 | + """ |
| 103 | + stripped_dict = {} |
| 104 | + for key, value in self.__dict__.items(): |
| 105 | + if isinstance(value, Serializable): |
| 106 | + for k, v in value.strip_dict(prefix=prefix+key+DELIM).items(): |
| 107 | + stripped_dict[k] = v |
| 108 | + else: |
| 109 | + stripped_dict[prefix+key] = value |
| 110 | + return stripped_dict |
| 111 | + |
| 112 | + def unstrip_dict(self, data: Dict[str, Any]): |
| 113 | + """Unstrip parsed dictionary and save. |
| 114 | +
|
| 115 | + Args: |
| 116 | + data: stripped dictionary |
| 117 | + """ |
| 118 | + for key, value in data.items(): |
| 119 | + key_path = key.split(DELIM) |
| 120 | + ref, k = self.get_attribute(key_path) |
| 121 | + setattr(ref, k, value) |
| 122 | + |
| 123 | + def get_attribute(self, key_path: List[str]): |
| 124 | + """Return key path corresponding instance |
| 125 | +
|
| 126 | + Args: |
| 127 | + key_path: heirechical key path. |
| 128 | +
|
| 129 | + Returns: |
| 130 | + key path corresponding instance |
| 131 | + """ |
| 132 | + if len(key_path) > 1: |
| 133 | + child_attr_name = key_path.pop(0) |
| 134 | + return getattr(self, child_attr_name).get_attribute(key_path) |
| 135 | + else: |
| 136 | + return self, key_path[0] |
0 commit comments