File size: 2,677 Bytes
c96df66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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))
        
        # * Find common prefix
        prefix = [lst_1[i] for i in range(min_len) if lst_1[i] == lst_2[i]]
        
        # * Find common suffix
        suffix = [lst_1[-i] for i in range(1, min_len + 1) if lst_1[-i] == lst_2[-i]]
        
        # * Correct the order of the common suffix
        suffix = suffix[::-1]

        return prefix, suffix