Skip to content

Commit 1ba3b2e

Browse files
committed
New JSON encoder
Signed-off-by: Jiri Podivin <[email protected]>
1 parent a4bdc10 commit 1ba3b2e

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

src/evaluate/saving.py

+21-3
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,26 @@
44
import sys
55
from datetime import datetime
66
from pathlib import Path
7+
import numpy as np
78

89
from datasets.utils.filelock import FileLock
910

1011
from . import __version__
1112

1213

14+
class NpEncoder(json.JSONEncoder):
15+
"""Numpy aware JSON encoder."""
16+
17+
def default(self, o):
18+
if isinstance(o, np.floating):
19+
return float(o)
20+
if isinstance(o, np.integer):
21+
return int(o)
22+
if isinstance(o, np.ndarray):
23+
return o.tolist()
24+
return super().default(o)
25+
26+
1327
def save(path_or_file, **data):
1428
"""
1529
Saves results to a JSON file. Also saves system information such as current time, current commit
@@ -40,7 +54,7 @@ def save(path_or_file, **data):
4054

4155
with FileLock(str(file_path) + ".lock"):
4256
with open(file_path, "w") as f:
43-
json.dump(data, f)
57+
json.dump(data, f, cls=NpEncoder)
4458

4559
# cleanup lock file
4660
try:
@@ -65,9 +79,13 @@ def _setup_path(path_or_file, current_time):
6579

6680

6781
def _git_commit_hash():
68-
res = subprocess.run("git rev-parse --is-inside-work-tree".split(), cwd="./", stdout=subprocess.PIPE)
82+
res = subprocess.run(
83+
"git rev-parse --is-inside-work-tree".split(), cwd="./", stdout=subprocess.PIPE
84+
)
6985
if res.stdout.decode().strip() == "true":
70-
res = subprocess.run("git rev-parse HEAD".split(), cwd=os.getcwd(), stdout=subprocess.PIPE)
86+
res = subprocess.run(
87+
"git rev-parse HEAD".split(), cwd=os.getcwd(), stdout=subprocess.PIPE
88+
)
7189
return res.stdout.decode().strip()
7290
else:
7391
return None

0 commit comments

Comments
 (0)