Download src/tools/utils.py from rainym00d/PluginTransformer: direct link, hf CLI and curl.
- Browser
- Download file 2.68 kB
-
https://huggingface.co/datasets/rainym00d/PluginTransformer/resolve/main/src/tools/utils.py
- Command line
-
hf download hf://datasets/rainym00d/PluginTransformer/src/tools/utils.py
-
curl -L -o utils.py https://huggingface.co/datasets/rainym00d/PluginTransformer/resolve/main/src/tools/utils.py
2.68 kB
| 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: | |
| def is_path_exists(path: str) -> bool: | |
| return os.path.exists(path) | |
| def mkdir(path: str) -> None: | |
| os.makedirs(path, exist_ok=True) | |
| 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) | |
| 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}}") | |
| 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) | |
| 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") | |
| 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 | |
| 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 |