File size: 5,973 Bytes
a7ad084 |
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 |
# -*- coding: utf-8 -*-
"""dataprocessing.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/10At7vh21OGTlE-Myv1NhAHi7l7NwBocQ
"""
import pandas as pd
import numpy as np
import os
from zipfile import ZipFile
import re
import json
import base64
from google.colab import drive
drive.mount('/content/drive')
path = "/content/drive/MyDrive/Duke/huggingface_project/data"
df = pd.read_excel(path+"/questionnaire-data.xlsx", header=2)
df["vviq_score"] = np.sum(df.filter(like = "vviq"), axis = 1)
df["osiq_score"] = np.sum(df.filter(like = "osiq"), axis = 1)
df["treatment"] = np.where(df.vviq_score > 40, "control", "aphantasia")
df = df.rename(columns={
"Sub ID": "sub_id",
df.columns[5]: "art_ability",
df.columns[6]: "art_experience",
df.columns[9]: "difficult",
df.columns[10]: "diff_explanation"
})
df.columns = df.columns.str.lower()
df = df.drop(df.filter(like="unnamed").columns, axis = 1)
df = df.drop(df.filter(regex="(vviq|osiq)\d+").columns, axis = 1)
df[df.columns[df.dtypes == "object"]] = df[df.columns[df.dtypes == "object"]].astype("string")
df[df.columns] = df[df.columns].replace([np.nan,pd.NA, "nan","na","NA","n/a","N/A","N/a"], None)
data = {}
for ind, row in df.iterrows():
data[row["sub_id"]] = {
"subject_id": int(row["sub_id"]),
"treatment": row["treatment"],
"demographics": dict(df.iloc[ind][1:-1])
}
data[row["sub_id"]]["demographics"]["art_ability"] = int(data[row["sub_id"]]["demographics"]["art_ability"])
data[row["sub_id"]]["demographics"]["vviq_score"] = int(data[row["sub_id"]]["demographics"]["vviq_score"])
data[row["sub_id"]]["demographics"]["osiq_score"] = int(data[row["sub_id"]]["demographics"]["osiq_score"])
stored_images = {}
with ZipFile(path + "/Images.zip", "r") as zip:
for image_file in zip.namelist():
with zip.open(image_file, 'r') as fil:
im = fil.read()
im_encoded = base64.b64encode(im).decode("utf-8")
stored_images[image_file.removesuffix(".jpg")] = im_encoded
def get_sub_files(subject, file_list):
pattern = re.compile("^.*" + subject + "-[a-z]{3}\d-(kitchen|livingroom|bedroom).*")
sub_files = [f for f in file_list if pattern.match(f)]
sub = {
"kitchen": {
"perception": "",
"memory": ""
},
"livingroom": {
"perception": "",
"memory": ""
},
"bedroom": {
"perception": "",
"memory": ""
},
}
for fil in sub_files:
if "kitchen" in fil:
if "pic" in fil:
sub["kitchen"]["perception"] = fil
else:
sub["kitchen"]["memory"] = fil
elif "livingroom" in fil:
if "pic" in fil:
sub["livingroom"]["perception"] = fil
else:
sub["livingroom"]["memory"] = fil
else:
if "pic" in fil:
sub["bedroom"]["perception"] = fil
else:
sub["bedroom"]["memory"] = fil
return sub
with ZipFile(path + "/Aphantasia-Drawings.zip", "r") as zip:
files = zip.namelist()
aphan_subs = list({f.split("/")[0] for f in files})
aphantasia_drawing_dataset = {}
for s in aphan_subs:
if int(s[3:]) in data.keys():
data[int(s[3:])]["drawings"] = get_sub_files(s, files)
else:
data[int(s[3:])] = {"drawings": get_sub_files(s,files)}
with ZipFile(path + "/Control-Drawings.zip", "r") as zip:
files = zip.namelist()
cntrl_subs = list({f.split("/")[0] for f in files})
full_control = {}
for s in cntrl_subs:
if int(s[3:]) in data.keys():
data[int(s[3:])]["drawings"] = get_sub_files(s, files)
else:
data[int(s[3:])] = {"drawings": get_sub_files(s,files)}
stored_images["kitchen"] = stored_images.pop('high_sun_ajwbpqrwvknlvpeh')
stored_images["bedroom"] = stored_images.pop('low_sun_acqsqjhtcbxeomux')
stored_images["livingroom"] = stored_images.pop('low_sun_byqgoskwpvsbllvy')
def extract_images(subject, treatment):
images_bytes = {
"kitchen": {
"perception": "",
"memory": ""
},
"livingroom": {
"perception": "",
"memory": ""
},
"bedroom": {
"perception": "",
"memory": ""
}
}
for room in ["kitchen", "livingroom", "bedroom"]:
paths = data[subject]["drawings"].get(room).values()
paths = [p for p in paths if p != ""]
if treatment == "aphantasia":
with ZipFile(path + "/Aphantasia-Drawings.zip", "r") as zip:
for filename in paths:
with zip.open(filename, 'r') as fil:
im = fil.read()
im_encoded = base64.b64encode(im).decode("utf-8")
if "mem" in filename:
images_bytes[room]["memory"] = im_encoded
else:
images_bytes[room]["perception"] = im_encoded
else:
with ZipFile(path + "/Control-Drawings.zip", "r") as zip:
for filename in paths:
with zip.open(filename, 'r') as fil:
im = fil.read()
im_encoded = base64.b64encode(im).decode("utf-8")
if "mem" in filename:
images_bytes[room]["memory"] = im_encoded
else:
images_bytes[room]["perception"] = im_encoded
return images_bytes
missing = []
for i in data.keys():
if "drawings" in data[i] and "treatment" in data[i]:
data[i]["drawings"] = extract_images(i,data[i]["treatment"])
else:
missing.append(i)
for num in missing:
data.pop(num, None)
for sub in data.keys():
data[sub]["image"] = stored_images
subject_data_path = path + "/clean_data.json"
#with open(subject_data_path, "w", encoding="utf-8") as sub_data:
#json.dump(data, sub_data, indent=2)
type(data)
da = pd.DataFrame(data)
flattened_data = []
for key, value in data.items():
flattened_subject = pd.json_normalize(value, sep='_')
flattened_data.append(flattened_subject)
da = pd.concat(flattened_data, ignore_index=True)
# Save the DataFrame to a Parquet file
da.to_parquet(path + 'data.parquet') |