-
Notifications
You must be signed in to change notification settings - Fork 0
/
dfaas_utils.py
66 lines (50 loc) · 1.76 KB
/
dfaas_utils.py
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
import json
import sys
from pathlib import Path
import numpy as np
# Thanks to: https://stackoverflow.com/a/47626762
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
elif isinstance(obj, np.number):
return obj.item()
# Use the default JSON encoder for other types.
return json.JSONEncoder.default(self, obj)
def dict_to_json(data, file_path):
file_path = to_pathlib(file_path)
try:
with open(file_path, "w") as file:
json.dump(data, file, cls=NumpyEncoder, sort_keys=True)
except IOError as e:
print(
f"Failed to write dict to json file to {file_path.as_posix()!r}: {e}",
file=sys.stderr,
)
sys.exit(1)
def json_to_dict(file_path):
file_path = to_pathlib(file_path)
try:
with open(file_path, "r") as file:
return json.load(file)
except IOError as e:
print(
f"Failed to read json file from {file_path.as_posix()!r}: {e}",
file=sys.stderr,
)
sys.exit(1)
def to_pathlib(file_path):
# Make sure to have a Path object, because we want the absolute path.
if isinstance(file_path, str):
file_path = Path(file_path)
return file_path.absolute()
def parse_result_file(result_path):
result_path = to_pathlib(result_path)
# Fill the iters list with the "result.json" file.
iters = []
with result_path.open() as result:
# The "result.json" file is not a valid JSON file. Each row is an
# isolated JSON object, the result of one training iteration.
while (raw_iter := result.readline()) != "":
iters.append(json.loads(raw_iter))
return iters