File size: 6,175 Bytes
9c423f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""data_processing.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1Oz1QL0mD9g3lVBgtmqHa-QiwwIJ2JaX5
"""

import pandas as pd
import numpy as np
import os
from zipfile import ZipFile
import re
import json
import io
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

from google.colab import drive
drive.mount('/content/drive')

path = "/content/drive/MyDrive/Duke/aphantasia_drawing_project/"

data_path = os.path.join(path,"data",'drawing_experiment')



df = pd.read_excel(data_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.replace([np.nan,pd.NA, "nan","na","NA","n/a","N/A","N/a"], None)

df.set_index('sub_id', inplace=True)



actual_image_path = os.path.join(data_path,"Stimuli","Images")



actual_images = {}
for image_file in os.listdir(actual_image_path):
  img_path = os.path.join(actual_image_path, image_file)
  actual_images[image_file.removesuffix(".jpg")] = Image.open(img_path)



key_map = {
    'high_sun_ajwbpqrwvknlvpeh': 'kitchen',
    'low_sun_acqsqjhtcbxeomux': 'bedroom',
    "low_sun_byqgoskwpvsbllvy":"livingroom"
    }

for old_key, new_key in key_map.items():
  actual_images[new_key] = actual_images.pop(old_key)

aphantasia_drawings_path = os.path.join(data_path,"Drawings","Aphantasia")
control_drawings_path = os.path.join(data_path,"Drawings","Control")



directories = {
    "Aphantasia": aphantasia_drawings_path,
    "Control": control_drawings_path
}



aphantasia_subs = {i: "Aphantasia" for i in os.listdir(directories["Aphantasia"]) if "sub" in i}
control_subs = {i: "Control" for i in os.listdir(directories["Control"]) if "sub" in i}
sub_treatment_key = {**aphantasia_subs, **control_subs}



def get_sub_files(sub):
  treatment_group = sub_treatment_key[sub]
  directory = directories[treatment_group]
  pattern = re.compile("^.*" + sub + "-[a-z]{3}\d-(kitchen|livingroom|bedroom).*")
  sub_files = os.listdir(os.path.join(directory, sub))
  files_needed = {'mem1',"mem2",'mem3','pic1','pic2','pic3'}

  sub_key = {}
  for f in sub_files:
    if pattern.match(f):
      main_path = os.path.join(directory, sub, f)
      draw_type = f.split("-")[1]
      label = f.split("-")[2].removesuffix(".jpg")
      alt_path = os.path.join(directory, sub, "-".join([sub, draw_type]) + ".jpg")
      try:
        img = Image.open(main_path)
      except:
        img = Image.open(alt_path)
      sub_key[draw_type] = {
          "label": label,
          "drawing": img
      }

  unknown_drawings = files_needed - sub_key.keys()
  if unknown_drawings:
    for unk in unknown_drawings:
      path = os.path.join(directory, sub, "-".join([sub, unk]) + ".jpg")
      try:
        img = Image.open(path)
      except:
        img = "No Image"
      sub_key[unk] = {
          "label": "unknown",
          "drawing": img
      }
  return sub_key





subject_data = {}
for sub in iter(sub_treatment_key):
  subject_data[sub] = get_sub_files(sub)

def is_image_blank(image):
  if image.mode != 'RGB':
    image = image.convert('RGB')
  pixels = list(image.getdata())
  return all(pixel == (255, 255, 255) for pixel in pixels)

for sub in iter(subject_data):
  dat = subject_data[sub]
  for key in dat.keys():
    if is_image_blank(dat[key]["drawing"]):
      dat[key]["label"] = "blank"



subs_missing_labels = {}
for sub in iter(subject_data):
  dat = subject_data[sub]
  for key in dat.keys():
    if "unknown" in dat[key]["label"]:
      if sub not in subs_missing_labels:
        subs_missing_labels[sub] = []
      subs_missing_labels[sub].append(key)

subs_missing_labels

subject_data["sub8"]["pic3"]["label"] = "livingroom"
subject_data["sub6"]["pic3"]["label"] = "bedroom"
subject_data["sub6"]["pic1"]["label"] = "kitchen"



def clean_sub_dat(sub):
  id = int(sub[3:])
  treatment_group = sub_treatment_key[sub]
  if id in df.index:
    demographics_dict = df.loc[id].to_dict()
  else:
    demographics_dict = {}
  demographics_dict.pop("treatment",None)
  drawings = {
    "bedroom": {},
    "kitchen": {},
    "livingroom": {}
    }
  for draw_type, draw_data in subject_data[sub].items():
    t = "memory" if draw_type[:-1] == "mem" else "perception"
    for d in drawings.keys():
      if draw_data["label"] == d:
        drawings[d][t] = draw_data["drawing"]

  return {
      "subject_id": id,
      "treatment": treatment_group,
      "demographics": demographics_dict,
      "drawings": drawings,
      "image": actual_images
  }



full_data = []
for s in subject_data.keys():
  full_data.append(clean_sub_dat(s))

"""160,161,162 removed, they dont have images"""



full_df = pd.json_normalize(full_data)



def image_to_byt(img, size=(224, 224)):
  if  pd.isna(img):
    return None
  img_resized = img.resize(size)
  img_byte_arr = io.BytesIO()
  img_resized.save(img_byte_arr, format='PNG')
  return img_byte_arr.getvalue()

drawing_columns = [col for col in full_df.columns if "drawings" in col or "image" in col]



for col in drawing_columns:
  full_df[col] = full_df[col].apply(image_to_byt)

def safe_convert_to_int(value):
  try:
    return int(value)
  except (ValueError, TypeError):
    return -99

col_to_process = [
    "demographics.age",
    "demographics.art_ability",
    "demographics.vviq_score",
    "demographics.osiq_score"
]

for col in col_to_process:
    full_df[col] = full_df[col].apply(safe_convert_to_int)

full_data_path = os.path.join(path, "data","aphantasia_data.parquet")

full_df.to_parquet(full_data_path, index=False)