Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
Remi-Gau committed May 28, 2024
1 parent a9f7a5a commit 4bb563f
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 85 deletions.
2 changes: 1 addition & 1 deletion cobidas_schema
Submodule cobidas_schema updated 35 files
+33 −0 schemas/cobidas/README_eCOBIDAS-en.html
+1 −1 schemas/cobidas/protocols/cobidas_schema.jsonld
+22 −0 schemas/eyetracking/README_eyetracker-en.html
+0 −74 schemas/eyetracking/README_eyetracker-en.md
+1 −1 schemas/eyetracking/protocols/eyetracking_schema.jsonld
+7 −3 schemas/neurovault/README_eCOBIDAS-en.html
+23 −0 schemas/pet/README_PET-en.html
+0 −66 schemas/pet/README_PET-en.md
+1 −1 schemas/pet/protocols/pet_schema.jsonld
+9 −0 schemas/reexecution/README_reexecute-en.html
+0 −1 schemas/reexecution/README_reexecute-en.md
+1 −1 schemas/reexecution/protocols/reexecution_schema.jsonld
+0 −1 templates/methods_boilerplates/README.md
+0 −14 templates/methods_boilerplates/anat_info.tmp
+0 −5 templates/methods_boilerplates/anat_report.tmp
+0 −1 templates/methods_boilerplates/device_channel_count.tmp
+0 −2 templates/methods_boilerplates/device_channels.tmp
+0 −1 templates/methods_boilerplates/device_freq_config.tmp
+0 −1 templates/methods_boilerplates/device_info.tmp
+0 −1 templates/methods_boilerplates/dewar_positioning.tmp
+0 −1 templates/methods_boilerplates/eeg_channel_placement.tmp
+0 −13 templates/methods_boilerplates/eeg_report.tmp
+0 −5 templates/methods_boilerplates/func_report.tmp
+0 −1 templates/methods_boilerplates/head_coil_frequency.tmp
+0 −1 templates/methods_boilerplates/head_localisation.tmp
+0 −1 templates/methods_boilerplates/institution.tmp
+0 −21 templates/methods_boilerplates/meg_report.tmp
+0 −6 templates/methods_boilerplates/mri_inplane_spatial_encoding.tmp
+0 −1 templates/methods_boilerplates/mri_rf_contrasts.tmp
+0 −16 templates/methods_boilerplates/mri_scanner_hardware.tmp
+0 −8 templates/methods_boilerplates/mri_sequence.tmp
+0 −1 templates/methods_boilerplates/mri_slice_acceleration.tmp
+0 −7 templates/methods_boilerplates/mri_timing_parameters.tmp
+0 −1 templates/methods_boilerplates/recording_properties.tmp
+0 −1 templates/methods_boilerplates/task_name.tmp
144 changes: 60 additions & 84 deletions ui/ecobidas_ui/protocols/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,38 +28,6 @@
blueprint = Blueprint("protocol", __name__, url_prefix="/protocol")


def update_visibility(items: dict[str, Any], form_data):
"""Evaluate visibility condition of each item and make item visible if necessary."""
# assign response to a variable with same name as the item it comees from
for key, value in form_data.items():
if key not in items:
continue
if not value:
value = None
string_to_eval = f"{key} = {value}"
try:
exec(string_to_eval)
except Exception as exc:
current_app.logger.error(
f"Could not execute '{string_to_eval}' as a valid python statement.\n{exc}"
)

# evaluate visibility
for item, values in items.items():
isVis = values["isVis"]
if isinstance(isVis, str):
try:
items[item]["visibility"] = eval(isVis)
except Exception as exc:
# actually log this
current_app.logger.error(
f"Could not evaluate '{eval(isVis)}' as a valid python expression.\n{exc}"
)
items[item]["visibility"] = False

return items


@blueprint.route("/<protocol_name>", methods=["GET", "POST"])
def protocol(protocol_name: str) -> str:

Expand All @@ -81,10 +49,7 @@ def protocol(protocol_name: str) -> str:


def show_export_button(protocol_name):
if protocol_name in ["neurovault", "cobidas"]:
return True
else:
return False
return protocol_name in ["neurovault", "cobidas"]


@blueprint.get("/<protocol_name>/<activity_name>")
Expand Down Expand Up @@ -196,11 +161,11 @@ def activity_post(protocol_name, activity_name) -> str:
flash(message, category="warning")
return redirect(request.url)

form, items, fields = process_acquisition_form(
form,
form, items, fields = process_upload_form(
form.data,
activity_name,
items,
filename=Path(current_app.config["UPLOAD_FOLDER"]) / uploaded_files[0],
JsonMeta(Path(current_app.config["UPLOAD_FOLDER"]) / uploaded_files[0]),
)

if not fields:
Expand Down Expand Up @@ -233,26 +198,6 @@ def activity_post(protocol_name, activity_name) -> str:
)


def validate_participants_form(data):
nb_files_uploaded = len(data)
if nb_files_uploaded != 2:
message = f"2 files must be uploaded. Received: {nb_files_uploaded}"
return message

participants_json_uploaded = any(file.filename == "participants.json" for file in data)
if not participants_json_uploaded:
message = "No 'participants.json' was uploaded."
return message

participants_tsv_uploaded = any(file.filename == "participants.tsv" for file in data)
if not participants_tsv_uploaded:
message = "No 'participants.tsv' was uploaded."
return message

else:
return ""


def generate_extra_forms(protocol_name, activity_name) -> tuple[FlaskForm | None]:

upload_participants_form = None
Expand All @@ -265,6 +210,7 @@ def generate_extra_forms(protocol_name, activity_name) -> tuple[FlaskForm | None
protocol_name == "cobidas" and activity_name == "sample"
):
upload_participants_form = UploadParticipantsForm(prefix="upload-")

if (protocol_name == "neurovault" and activity_name == "mri_acquisition") or (
protocol_name == "cobidas" and activity_name == "common_parameters"
):
Expand All @@ -273,45 +219,43 @@ def generate_extra_forms(protocol_name, activity_name) -> tuple[FlaskForm | None
return upload_participants_form, upload_acquisition_form


def process_acquisition_form(form: FlaskForm, activity_name: str, items, filename):
"""Use uploaded bold.json to prefill the form."""
with open(filename) as f:
bold_json = json.load(f)

found = JsonMeta(bold_json)
def validate_participants_form(data):
nb_files_uploaded = len(data)
if nb_files_uploaded != 2:
message = f"2 files must be uploaded. Received: {nb_files_uploaded}"
return message

fields = []
for key in found.__dir__():
if not getattr(found, key) or key not in form:
continue
fields.append(key)
participants_json_uploaded = any(file.filename == "participants.json" for file in data)
if not participants_json_uploaded:
message = "No 'participants.json' was uploaded."
return message

form, items = update_items_and_forms(form.data, items, activity_name, obj=found)
participants_tsv_uploaded = any(file.filename == "participants.tsv" for file in data)
if not participants_tsv_uploaded:
message = "No 'participants.tsv' was uploaded."
return message

return form, items, fields
else:
return ""


class JsonMeta:

def __init__(self, json_content) -> None:

def __init__(self, json_file) -> None:
with open(json_file) as f:
json_content = json.load(f)
for key in json_content:
self.__setattr__(key, json_content[key])


def process_participants_form(form: FlaskForm, activity_name: str, items, tsv_file, json_file):
json_content = json.load(open(json_file))

found = extract_values_participants(tsv_file, json_content=json_content)
found = extract_values_participants(tsv_file, json_content=json.load(open(json_file)))
return process_upload_form(form.data, activity_name, items, found)

fields = []
for key in found.__dir__():
if not getattr(found, key) or key not in form:
continue
fields.append(key)

form, items = update_items_and_forms(form.data, items, activity_name, obj=found)

def process_upload_form(form_data, activity_name, items, found):
form, items = update_items_and_forms(form_data, items, activity_name, obj=found)
fields = [key for key in found.__dir__() if getattr(found, key) and key in form]
return form, items, fields


Expand All @@ -325,3 +269,35 @@ def update_items_and_forms(form_data: dict, items, activity_name: str, obj=None)
items = update_format(items, form_data)
form = generate_form(items, prefix=activity_name, obj=obj)
return form, items


def update_visibility(items: dict[str, Any], form_data):
"""Evaluate visibility condition of each item and make item visible if necessary."""
# assign response to a variable with same name as the item it comees from
for key, value in form_data.items():
if key not in items:
continue
if not value:
value = None
string_to_eval = f"{key} = {value}"
try:
exec(string_to_eval)
except Exception as exc:
current_app.logger.error(
f"Could not execute '{string_to_eval}' as a valid python statement.\n{exc}"
)

# evaluate visibility
for item, values in items.items():
isVis = values["isVis"]
if isinstance(isVis, str):
try:
items[item]["visibility"] = eval(isVis)
except Exception as exc:
# actually log this
current_app.logger.error(
f"Could not evaluate '{eval(isVis)}' as a valid python expression.\n{exc}"
)
items[item]["visibility"] = False

return items

0 comments on commit 4bb563f

Please sign in to comment.