| import json |
| import os |
| import sys |
| from dataclasses import asdict |
| from datetime import datetime |
| from enum import Enum |
| from typing import Any |
|
|
| import pytz |
|
|
|
|
| class MyUtils: |
| @staticmethod |
| def is_path_exists(path: str) -> bool: |
| return os.path.exists(path) |
| |
| @staticmethod |
| def mkdir(path: str) -> None: |
| os.makedirs(path, exist_ok=True) |
|
|
| @staticmethod |
| def save_to_json(obj: Any, path: str) -> None: |
| MyUtils.mkdir(os.path.dirname(path)) |
| with open(path, "w", encoding="utf-8") as f: |
| json.dump(obj, f, indent=4, ensure_ascii=False) |
|
|
| @staticmethod |
| def log_metrics(dataset: str, metrics: dict) -> None: |
| print(f"***** {dataset} metrics *****") |
| k_width = max(len(str(x)) for x in metrics.keys()) |
| v_width = max(len(str(x)) for x in metrics.values()) |
| for key in sorted(metrics.keys()): |
| print(f" {key: <{k_width}} = {metrics[key]: >{v_width}}") |
|
|
| @staticmethod |
| def save_metrics(dataset: str, metrics: dict, path: str): |
| context = {} |
| if MyUtils.is_path_exists(path): |
| context = json.load(open(path, "r")) |
|
|
| if dataset not in context: |
| context[dataset] = metrics |
| else: |
| context[dataset] |= metrics |
|
|
| MyUtils.save_to_json(context, path) |
|
|
| @staticmethod |
| def save_command(path: str): |
| time_zone = pytz.timezone('Asia/Shanghai') |
| time = f"{'Time': <10}: {json.dumps(datetime.now(time_zone).strftime('%Y-%m-%d, %H:%M:%S'), ensure_ascii=False)}" |
| command = f"{'Command': <10}: {json.dumps(' '.join(sys.argv), ensure_ascii=False)}" |
|
|
| MyUtils.mkdir(os.path.dirname(path)) |
| with open(path, "w", encoding="utf-8") as f: |
| f.write(f"{time}\n") |
| f.write(f"{command}\n") |
|
|
| @staticmethod |
| def args_to_dict(args: Any) -> dict: |
| d = asdict(args) |
| for k, v in d.items(): |
| if isinstance(v, Enum): |
| d[k] = v.value |
| if isinstance(v, list) and len(v) > 0 and isinstance(v[0], Enum): |
| d[k] = [x.value for x in v] |
| if k.endswith("_token"): |
| d[k] = f"<{k.upper()}>" |
| return d |
|
|
| @staticmethod |
| def find_common_prefix_suffix(lst_1, lst_2): |
| min_len = min(len(lst_1), len(lst_2)) |
| |
| |
| prefix = [lst_1[i] for i in range(min_len) if lst_1[i] == lst_2[i]] |
| |
| |
| suffix = [lst_1[-i] for i in range(1, min_len + 1) if lst_1[-i] == lst_2[-i]] |
| |
| |
| suffix = suffix[::-1] |
|
|
| return prefix, suffix |