jmc255 commited on
Commit
9c423f3
1 Parent(s): d93115d

Upload data_processing.py

Browse files
Files changed (1) hide show
  1. data_processing.py +245 -0
data_processing.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """data_processing.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1Oz1QL0mD9g3lVBgtmqHa-QiwwIJ2JaX5
8
+ """
9
+
10
+ import pandas as pd
11
+ import numpy as np
12
+ import os
13
+ from zipfile import ZipFile
14
+ import re
15
+ import json
16
+ import io
17
+ from PIL import Image, ImageFile
18
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
19
+
20
+ from google.colab import drive
21
+ drive.mount('/content/drive')
22
+
23
+ path = "/content/drive/MyDrive/Duke/aphantasia_drawing_project/"
24
+
25
+ data_path = os.path.join(path,"data",'drawing_experiment')
26
+
27
+
28
+
29
+ df = pd.read_excel(data_path+"/questionnaire-data.xlsx", header=2)
30
+
31
+ df["vviq_score"] = np.sum(df.filter(like = "vviq"), axis = 1)
32
+ df["osiq_score"] = np.sum(df.filter(like = "osiq"), axis = 1)
33
+ df["treatment"] = np.where(df.vviq_score > 40, "control", "aphantasia")
34
+
35
+ df = df.rename(columns={
36
+ "Sub ID": "sub_id",
37
+ df.columns[5]: "art_ability",
38
+ df.columns[6]: "art_experience",
39
+ df.columns[9]: "difficult",
40
+ df.columns[10]: "diff_explanation"
41
+ })
42
+
43
+ df.columns = df.columns.str.lower()
44
+
45
+ df = df.drop(df.filter(like="unnamed").columns, axis = 1)
46
+ df = df.drop(df.filter(regex="(vviq|osiq)\d+").columns, axis = 1)
47
+
48
+ df[df.columns[df.dtypes == "object"]] = df[df.columns[df.dtypes == "object"]].astype("string")
49
+
50
+ df = df.replace([np.nan,pd.NA, "nan","na","NA","n/a","N/A","N/a"], None)
51
+
52
+ df.set_index('sub_id', inplace=True)
53
+
54
+
55
+
56
+ actual_image_path = os.path.join(data_path,"Stimuli","Images")
57
+
58
+
59
+
60
+ actual_images = {}
61
+ for image_file in os.listdir(actual_image_path):
62
+ img_path = os.path.join(actual_image_path, image_file)
63
+ actual_images[image_file.removesuffix(".jpg")] = Image.open(img_path)
64
+
65
+
66
+
67
+ key_map = {
68
+ 'high_sun_ajwbpqrwvknlvpeh': 'kitchen',
69
+ 'low_sun_acqsqjhtcbxeomux': 'bedroom',
70
+ "low_sun_byqgoskwpvsbllvy":"livingroom"
71
+ }
72
+
73
+ for old_key, new_key in key_map.items():
74
+ actual_images[new_key] = actual_images.pop(old_key)
75
+
76
+ aphantasia_drawings_path = os.path.join(data_path,"Drawings","Aphantasia")
77
+ control_drawings_path = os.path.join(data_path,"Drawings","Control")
78
+
79
+
80
+
81
+ directories = {
82
+ "Aphantasia": aphantasia_drawings_path,
83
+ "Control": control_drawings_path
84
+ }
85
+
86
+
87
+
88
+ aphantasia_subs = {i: "Aphantasia" for i in os.listdir(directories["Aphantasia"]) if "sub" in i}
89
+ control_subs = {i: "Control" for i in os.listdir(directories["Control"]) if "sub" in i}
90
+ sub_treatment_key = {**aphantasia_subs, **control_subs}
91
+
92
+
93
+
94
+ def get_sub_files(sub):
95
+ treatment_group = sub_treatment_key[sub]
96
+ directory = directories[treatment_group]
97
+ pattern = re.compile("^.*" + sub + "-[a-z]{3}\d-(kitchen|livingroom|bedroom).*")
98
+ sub_files = os.listdir(os.path.join(directory, sub))
99
+ files_needed = {'mem1',"mem2",'mem3','pic1','pic2','pic3'}
100
+
101
+ sub_key = {}
102
+ for f in sub_files:
103
+ if pattern.match(f):
104
+ main_path = os.path.join(directory, sub, f)
105
+ draw_type = f.split("-")[1]
106
+ label = f.split("-")[2].removesuffix(".jpg")
107
+ alt_path = os.path.join(directory, sub, "-".join([sub, draw_type]) + ".jpg")
108
+ try:
109
+ img = Image.open(main_path)
110
+ except:
111
+ img = Image.open(alt_path)
112
+ sub_key[draw_type] = {
113
+ "label": label,
114
+ "drawing": img
115
+ }
116
+
117
+ unknown_drawings = files_needed - sub_key.keys()
118
+ if unknown_drawings:
119
+ for unk in unknown_drawings:
120
+ path = os.path.join(directory, sub, "-".join([sub, unk]) + ".jpg")
121
+ try:
122
+ img = Image.open(path)
123
+ except:
124
+ img = "No Image"
125
+ sub_key[unk] = {
126
+ "label": "unknown",
127
+ "drawing": img
128
+ }
129
+ return sub_key
130
+
131
+
132
+
133
+
134
+
135
+ subject_data = {}
136
+ for sub in iter(sub_treatment_key):
137
+ subject_data[sub] = get_sub_files(sub)
138
+
139
+ def is_image_blank(image):
140
+ if image.mode != 'RGB':
141
+ image = image.convert('RGB')
142
+ pixels = list(image.getdata())
143
+ return all(pixel == (255, 255, 255) for pixel in pixels)
144
+
145
+ for sub in iter(subject_data):
146
+ dat = subject_data[sub]
147
+ for key in dat.keys():
148
+ if is_image_blank(dat[key]["drawing"]):
149
+ dat[key]["label"] = "blank"
150
+
151
+
152
+
153
+ subs_missing_labels = {}
154
+ for sub in iter(subject_data):
155
+ dat = subject_data[sub]
156
+ for key in dat.keys():
157
+ if "unknown" in dat[key]["label"]:
158
+ if sub not in subs_missing_labels:
159
+ subs_missing_labels[sub] = []
160
+ subs_missing_labels[sub].append(key)
161
+
162
+ subs_missing_labels
163
+
164
+ subject_data["sub8"]["pic3"]["label"] = "livingroom"
165
+ subject_data["sub6"]["pic3"]["label"] = "bedroom"
166
+ subject_data["sub6"]["pic1"]["label"] = "kitchen"
167
+
168
+
169
+
170
+ def clean_sub_dat(sub):
171
+ id = int(sub[3:])
172
+ treatment_group = sub_treatment_key[sub]
173
+ if id in df.index:
174
+ demographics_dict = df.loc[id].to_dict()
175
+ else:
176
+ demographics_dict = {}
177
+ demographics_dict.pop("treatment",None)
178
+ drawings = {
179
+ "bedroom": {},
180
+ "kitchen": {},
181
+ "livingroom": {}
182
+ }
183
+ for draw_type, draw_data in subject_data[sub].items():
184
+ t = "memory" if draw_type[:-1] == "mem" else "perception"
185
+ for d in drawings.keys():
186
+ if draw_data["label"] == d:
187
+ drawings[d][t] = draw_data["drawing"]
188
+
189
+ return {
190
+ "subject_id": id,
191
+ "treatment": treatment_group,
192
+ "demographics": demographics_dict,
193
+ "drawings": drawings,
194
+ "image": actual_images
195
+ }
196
+
197
+
198
+
199
+ full_data = []
200
+ for s in subject_data.keys():
201
+ full_data.append(clean_sub_dat(s))
202
+
203
+ """160,161,162 removed, they dont have images"""
204
+
205
+
206
+
207
+ full_df = pd.json_normalize(full_data)
208
+
209
+
210
+
211
+ def image_to_byt(img, size=(224, 224)):
212
+ if pd.isna(img):
213
+ return None
214
+ img_resized = img.resize(size)
215
+ img_byte_arr = io.BytesIO()
216
+ img_resized.save(img_byte_arr, format='PNG')
217
+ return img_byte_arr.getvalue()
218
+
219
+ drawing_columns = [col for col in full_df.columns if "drawings" in col or "image" in col]
220
+
221
+
222
+
223
+ for col in drawing_columns:
224
+ full_df[col] = full_df[col].apply(image_to_byt)
225
+
226
+ def safe_convert_to_int(value):
227
+ try:
228
+ return int(value)
229
+ except (ValueError, TypeError):
230
+ return -99
231
+
232
+ col_to_process = [
233
+ "demographics.age",
234
+ "demographics.art_ability",
235
+ "demographics.vviq_score",
236
+ "demographics.osiq_score"
237
+ ]
238
+
239
+ for col in col_to_process:
240
+ full_df[col] = full_df[col].apply(safe_convert_to_int)
241
+
242
+ full_data_path = os.path.join(path, "data","aphantasia_data.parquet")
243
+
244
+ full_df.to_parquet(full_data_path, index=False)
245
+