-
Notifications
You must be signed in to change notification settings - Fork 0
/
final_script.py
86 lines (68 loc) · 3.23 KB
/
final_script.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import os
import sys
import json
import numpy as np
from rsciio.emd import file_reader as emd_reader
from rsciio.pantarhei import file_reader as prz_reader
if __name__ == "__main__":
try:
if len(sys.argv) != 2:
raise Exception("Please provide input directory name as an argument: python final_script.py <directory_name>")
input_dir = sys.argv[1]
if not (os.path.exists(input_dir) and os.path.isdir(input_dir)):
raise Exception(f"Directory with name '{input_dir}' does not exist.")
for filename in os.listdir(input_dir):
print("\n" + filename)
metadata_dict = {}
if filename.endswith(".emd"):
try:
f = emd_reader(os.path.join(input_dir, filename))
if len(f) == 1:
metadata_dict.update(f[0]["metadata"])
metadata_dict.update(f[0]["original_metadata"])
metadata_dict["axes"] = f[0]["axes"]
else:
metadata_dict["sample_elements"] = []
for el in f:
if el["metadata"]["General"]["title"] == "EDS":
metadata_dict.update(f[0]["metadata"])
metadata_dict.update(f[0]["original_metadata"])
metadata_dict["axes"] = f[0]["axes"]
else:
metadata_dict["sample_elements"].append(el["metadata"]["General"]["title"])
except Exception as e:
print(e)
pass
elif filename.endswith(".prz"):
try:
f = prz_reader(os.path.join(input_dir, filename))
metadata_dict.update(f[0]["metadata"])
metadata_dict.update(f[0]["original_metadata"])
metadata_dict["axes"] = f[0]["axes"]
except Exception as e:
print(e)
print("Trying again, using numpy...")
try:
f = np.load(os.path.join(input_dir, filename), allow_pickle=True)
meta_data = f["meta_data"].tolist()
data_model = f["data_model"].tolist()
metadata_dict = {}
for dict in meta_data:
metadata_dict.update(dict)
for dict in data_model:
metadata_dict.update(dict)
print("Success")
except Exception as e:
print(e)
pass
else:
print("Unsupported file format.")
pass
# create output directory if it doesn't exist
output_dir = sys.argv[0].replace(".py", "_") + "metadata/"
os.makedirs(output_dir, exist_ok=True)
# save metadata as a json file
with open(output_dir + filename.replace(" ", "_") + "_metadata.json", "w") as outfile:
json.dump(metadata_dict, outfile, sort_keys=True, indent=4)
except Exception as e:
print(e)