aphantasia_drawing_dataset / data_processing.py
jmc255's picture
Upload data_processing.py
9c423f3 verified
raw
history blame
6.18 kB
# -*- 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)