forked from ReproNim/reproschema-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathto_reproschema.py
executable file
·361 lines (317 loc) · 12.3 KB
/
to_reproschema.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import argparse
import os
import re
import shutil
import warnings
from pathlib import Path
from typing import Any, Dict, List
import pandas as pd
import yaml
from bs4 import BeautifulSoup, MarkupResemblesLocatorWarning
from .context_url import CONTEXTFILE_URL
from .jsonldutils import get_context_version
from .mappings import (
ADDITIONAL_NOTES_LIST,
CSV_TO_REPROSCHEMA_MAP,
INPUT_TYPE_MAP,
VALUE_TYPE_MAP,
)
from .models import Activity, Item, Protocol, write_obj_jsonld
warnings.filterwarnings("ignore", category=MarkupResemblesLocatorWarning)
def load_config(config_file: str) -> Dict[str, Any]:
with open(config_file, "r") as f:
return yaml.safe_load(f)
class ReproSchemaConverter:
def __init__(self, config: Dict[str, Any]):
self.config = config
self.branch_logic_pattern = re.compile(
r"\[([^\]]+)\]|\b(AND|OR)\b|([^><!=])=|sum\(([^)]+)\)"
)
def load_csv(self, csv_file: str) -> pd.DataFrame:
df = pd.read_csv(csv_file)
df.columns = df.columns.str.strip().str.replace('"', "")
return self.preprocess_fields(df)
def preprocess_fields(self, df: pd.DataFrame) -> pd.DataFrame:
special_fields = [
col
for col in df.columns
if col.endswith(("_Validity", "_Administration", "_Informant"))
]
for field in special_fields:
df[field] = df[field].apply(
lambda x: (
x.replace(">", ">").replace("\n", "").replace("\r", "")
if isinstance(x, str)
else x
)
)
return df
def process_response_options(
self, response_option_str: str, item_name: str
) -> tuple:
if pd.isna(response_option_str):
return [], ["xsd:string"]
choices = []
value_types = set()
if item_name.endswith(("_Validity", "_Administration", "_Informant")):
pattern = r"''([^']+)'(?:=>|=>)'([^']+)''"
matches = re.findall(pattern, response_option_str)
choices = [
{"name": {"en": name}, "value": value}
for value, name in matches
]
else:
for choice in response_option_str.split("{-}"):
choice = choice.strip()
if "=>" in choice:
value, name = map(
lambda x: x.strip("'").strip('"'), choice.split("=>")
)
choices.append(
{
"name": {"en": name},
"value": (
None if value.lower() == "null" else value
),
}
)
elif choice != "NULL=>''":
print(
f"Warning: Unexpected choice format '{choice}' in {item_name} field"
)
if not choices:
print(f"Warning: No valid choices found for {item_name}")
choices.append({"name": {"en": "No valid choices"}, "value": None})
value_types.add("xsd:string")
return choices, list(value_types)
def clean_html(self, raw_html: str) -> str:
if pd.isna(raw_html):
return ""
text = str(raw_html)
if "<" in text and ">" in text:
return BeautifulSoup(text, "html.parser").get_text()
return text
def process_item(self, item: Dict[str, Any]) -> Dict[str, Any]:
item_data = {
"category": "reproschema:Item",
"id": item[CSV_TO_REPROSCHEMA_MAP["item_name"]],
"prefLabel": {"en": item[CSV_TO_REPROSCHEMA_MAP["item_name"]]},
"question": {
"en": self.clean_html(item[CSV_TO_REPROSCHEMA_MAP["question"]])
},
"ui": {
"inputType": INPUT_TYPE_MAP.get(
item[CSV_TO_REPROSCHEMA_MAP["inputType"]], "text"
)
},
"responseOptions": {
"valueType": [
VALUE_TYPE_MAP.get(
str(
item.get(
CSV_TO_REPROSCHEMA_MAP.get("validation", ""),
"",
)
).strip(),
"xsd:string",
)
],
"multipleChoice": item[CSV_TO_REPROSCHEMA_MAP["inputType"]]
== "Multi-select",
},
}
if CSV_TO_REPROSCHEMA_MAP["response_option"] in item:
(
item_data["responseOptions"]["choices"],
item_data["responseOptions"]["valueType"],
) = self.process_response_options(
item[CSV_TO_REPROSCHEMA_MAP["response_option"]],
item[CSV_TO_REPROSCHEMA_MAP["item_name"]],
)
item_data["additionalNotesObj"] = [
{"source": "redcap", "column": column, "value": item[column]}
for column in ADDITIONAL_NOTES_LIST
if column in item and item[column]
]
return item_data
def process_dataframe(self, df: pd.DataFrame) -> Dict[str, Dict[str, Any]]:
activities = {}
for activity_name, group in df.groupby(
CSV_TO_REPROSCHEMA_MAP["activity_name"]
):
items = [
self.process_item(item) for item in group.to_dict("records")
]
activities[activity_name] = {
"items": items,
"order": [f"items/{item['id']}" for item in items],
"compute": [
{"variableName": item["id"], "jsExpression": ""}
for item in items
if "_score" in item["id"].lower()
or item["id"].lower().endswith("_raw")
],
}
return activities
def create_activity_schema(
self,
activity_name: str,
activity_data: Dict[str, Any],
output_path: Path,
redcap_version: str,
):
json_ld = {
"category": "reproschema:Activity",
"id": f"{activity_name}_schema",
"prefLabel": {"en": activity_name},
"schemaVersion": get_context_version(CONTEXTFILE_URL),
"version": redcap_version,
"ui": {
"order": activity_data["order"],
"addProperties": [
{
"variableName": item["id"],
"isAbout": f"items/{item['id']}",
"valueRequired": item.get("valueRequired", False),
"isVis": not (
"_score" in item["id"].lower()
or item["id"].lower().endswith("_raw")
or "@HIDDEN" in item.get("annotation", "").lower()
),
}
for item in activity_data["items"]
],
"shuffle": False,
},
}
if activity_data["compute"]:
json_ld["compute"] = activity_data["compute"]
act = Activity(**json_ld)
path = output_path / "activities" / activity_name
path.mkdir(parents=True, exist_ok=True)
write_obj_jsonld(
act,
path / f"{activity_name}_schema",
contextfile_url=CONTEXTFILE_URL,
)
items_path = path / "items"
items_path.mkdir(parents=True, exist_ok=True)
for item in activity_data["items"]:
item_path = items_path / item["id"]
item_path.parent.mkdir(parents=True, exist_ok=True)
write_obj_jsonld(
Item(**item), item_path, contextfile_url=CONTEXTFILE_URL
)
print(f"{activity_name} Instrument schema created")
def create_protocol_schema(
self,
protocol_name: str,
protocol_data: Dict[str, Any],
activities: List[str],
output_path: Path,
):
protocol_schema = {
"category": "reproschema:Protocol",
"id": f"{protocol_name}_schema",
"prefLabel": {"en": protocol_data["protocol_display_name"]},
"description": {
"en": protocol_data.get("protocol_description", "")
},
"schemaVersion": get_context_version(CONTEXTFILE_URL),
"version": protocol_data["redcap_version"],
"ui": {
"addProperties": [
{
"isAbout": f"../activities/{activity}/{activity}_schema",
"variableName": f"{activity}_schema",
"prefLabel": {
"en": activity.replace("_", " ").title()
},
"isVis": True,
}
for activity in activities
],
"order": [
f"../activities/{activity}/{activity}_schema"
for activity in activities
],
"shuffle": False,
},
}
protocol_dir = output_path / protocol_name
protocol_dir.mkdir(parents=True, exist_ok=True)
write_obj_jsonld(
Protocol(**protocol_schema),
protocol_dir / f"{protocol_name}_schema",
contextfile_url=CONTEXTFILE_URL,
)
print(f"Protocol schema created in {protocol_dir}")
def clean_output_directories(self, output_path: Path):
"""Remove only the folders in the output directory."""
if output_path.exists():
for item in output_path.iterdir():
if item.is_dir():
shutil.rmtree(item)
print(f"Removed directory: {item}")
print(f"Cleaned folders in output directory: {output_path}")
else:
print(
f"Output directory does not exist, will be created: {output_path}"
)
def remove_ds_store(self, directory: Path):
"""Remove all .DS_Store files in the given directory and its subdirectories."""
for root, dirs, files in os.walk(directory):
for file in files:
if file == ".DS_Store":
file_path = Path(root) / file
file_path.unlink()
print(f"Removed .DS_Store file: {file_path}")
def convert(self, csv_file: str, output_path: str):
try:
df = self.load_csv(csv_file)
activities = self.process_dataframe(df)
abs_output_path = Path(output_path) / self.config[
"protocol_name"
].replace(" ", "_")
# Clean only the folders in the output directory before conversion
self.clean_output_directories(abs_output_path)
abs_output_path.mkdir(parents=True, exist_ok=True)
for activity_name, activity_data in activities.items():
self.create_activity_schema(
activity_name,
activity_data,
abs_output_path,
self.config["redcap_version"],
)
self.create_protocol_schema(
self.config["protocol_name"],
self.config,
list(activities.keys()),
abs_output_path,
)
# Remove .DS_Store files after conversion
self.remove_ds_store(abs_output_path)
print("Conversion completed and .DS_Store files removed.")
except Exception as e:
print(f"An error occurred during conversion: {str(e)}")
import traceback
traceback.print_exc()
raise
def main():
parser = argparse.ArgumentParser(
description="Convert a CSV file to ReproSchema format."
)
parser.add_argument("csv_file", help="Path to the input CSV file.")
parser.add_argument(
"config_file", help="Path to the YAML configuration file."
)
parser.add_argument(
"output_path",
help="Path to the directory where the output schemas will be saved.",
)
args = parser.parse_args()
config = load_config(args.config_file)
converter = ReproSchemaConverter(config)
converter.convert(args.csv_file, args.output_path)
if __name__ == "__main__":
main()