82 lines
2.0 KiB
Python
82 lines
2.0 KiB
Python
import pickle
|
|
import json
|
|
import os
|
|
|
|
import numpy
|
|
|
|
|
|
def parse_value(value):
|
|
if type(value) is dict:
|
|
return convert_to_json(value)
|
|
elif type(value) in (list, set):
|
|
value = value
|
|
converted = []
|
|
for v in value:
|
|
converted.append(parse_value(v))
|
|
return converted
|
|
elif type(value) in (float, bool, int):
|
|
return value
|
|
elif type(value) is numpy.ndarray:
|
|
return parse_value(value.tolist())
|
|
elif type(value) is numpy.float64:
|
|
return float(value)
|
|
elif type(value) is numpy.int64:
|
|
return int(value)
|
|
else:
|
|
print(type(value))
|
|
print(value)
|
|
raise TypeError()
|
|
|
|
|
|
def parse_key(key):
|
|
if type(key) is bytes:
|
|
return key.decode('utf-8')
|
|
elif type(key) is tuple:
|
|
l = []
|
|
for k in key:
|
|
l.append(parse_key(k))
|
|
return json.dumps(l)
|
|
elif type(key) is str:
|
|
return key
|
|
else:
|
|
print(type(key))
|
|
print(key)
|
|
raise TypeError()
|
|
|
|
|
|
def convert_to_json(obj: dict):
|
|
parsed_dict = {}
|
|
for k in obj.keys():
|
|
new_key = parse_key(k)
|
|
value = parse_value(obj[k])
|
|
parsed_dict[new_key] = value
|
|
return parsed_dict
|
|
|
|
|
|
def extract_pickle(file):
|
|
filename = os.path.basename(file)
|
|
dirname = os.path.dirname(file)
|
|
json_file = os.path.join(dirname, filename[:filename.rfind(".")] + ".json")
|
|
if os.path.isfile(json_file):
|
|
return
|
|
print(f"extracting {file}")
|
|
|
|
with open(file, 'rb') as f:
|
|
obj = pickle.load(f, encoding='bytes')
|
|
obj = convert_to_json(obj)
|
|
json_str = json.dumps(obj, indent=4, ensure_ascii=False)
|
|
print(f"writing to {json_file}")
|
|
with open(json_file, 'w', encoding='utf-8') as f_json:
|
|
f_json.write(json_str)
|
|
|
|
|
|
def main():
|
|
path = "D:/datasets/BrnoCompSpeed"
|
|
for root, dirs, files in os.walk(path):
|
|
for file in files:
|
|
if str(file).endswith(".pkl"):
|
|
extract_pickle(os.path.join(root, file))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |