-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyaml_to_dir.py
84 lines (66 loc) · 2.86 KB
/
yaml_to_dir.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
import os
import yaml
import json
import argparse
def create_folder_structure(base_dir, classification_dict, level=0, max_levels=10):
if level > max_levels:
return
# Process the current level of the dictionary
for key, value in classification_dict.items():
# print(key, value)
if value is None:
print(key, "Value is None")
continue # Skip if value is None
# Check if the value is a dictionary, which means we have a class with subclasses
if isinstance(value, dict):
# Retrieve the 'name' key if present, otherwise use an empty string
dir_name = f"{key} {value.get('name', '')}".strip()
current_dir = os.path.join(base_dir, dir_name)
os.makedirs(current_dir, exist_ok=True)
print(f"Created directory DICT: {current_dir}")
# If there are subclasses, recursively process them
subclasses = value.get('subclasses', [])
# print(subclasses)
if isinstance(subclasses, list):
# print("LIST")
for subclass in subclasses:
# Each subclass is a dictionary; get its key and value
if subclass:
# print(subclass)
subclass_key, subclass_value = list(subclass.items())[0]
# Call the function recursively with the subclass dictionary
create_folder_structure(current_dir, {subclass_key: subclass_value}, level + 1, max_levels)
# If the value is a string, we have a subclass entry
elif isinstance(value, str):
dir_name = f"{key} {value}".strip()
current_dir = os.path.join(base_dir, dir_name)
os.makedirs(current_dir, exist_ok=True)
print(f"Created directory STRING: {current_dir}")
def main():
# Set up argument parsing
parser = argparse.ArgumentParser(
description="Create folder structure from a YAML file."
)
parser.add_argument("file", type=str, help="Path to the YAML file")
parser.add_argument(
"output_dir",
type=str,
help="Base output directory where folders will be created",
)
# Parse arguments
args = parser.parse_args()
if args.file.endswith("yaml"):
with open(args.file, "r", encoding="utf8") as file:
data = yaml.safe_load(file)
# print(json.dumps(data, indent=4))
create_folder_structure(args.output_dir, data)
elif args.file.endswith("json"):
with open(args.file, "r", encoding="utf-8") as file:
data = json.load(file)
# print(data)
create_folder_structure(args.output_dir, data)
else:
print("No valid file was provided")
# Create the folder structure
if __name__ == "__main__":
main()