Repository navigation
Expand file tree
/
Copy pathfile_processing.py
More file actions
300 lines (251 loc) · 13.4 KB
/
Copy pathfile_processing.py
File metadata and controls
300 lines (251 loc) · 13.4 KB
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
"""
csv_processor.py
Author: Biranugan Pirabaharan, Shreshth Saxena
Purpose: File management related to the Pupil Devices exported format.
"""
import os, glob
import zipfile
import json
import re
from tqdm import tqdm
from datetime import datetime
import shutil
try:
from offlineInterface.csv_processor import CSVProcessor
from offlineInterface.config import config
except:
#resolve relative paths when executing the interface independently from src/offlineInterface/
import sys
sys.path.append("../")
from offlineInterface.csv_processor import CSVProcessor
from offlineInterface.config import config
class FileProcessor:
"""
A class that provides methods for processing files.
Methods:
- unzip_file(zip_path, extract_to): Unzips a file to the specified directory.
- parse_directories(input_path): Retrieves the paths of glasses-related files from a directory and its subdirectories.
- get_central_data(input_path): Retrieves the paths of central video and timestamp files from a directory.
- generate_transformed_gaze_csv_templates(output_path, glasses_names): Generates transformed gaze CSV templates for each pair of glasses.
"""
@staticmethod
def unzip_file(zip_path, extract_to):
"""
Unzips a file to the specified directory.
Args:
- zip_path (str): The path of the zip file.
- extract_to (str): The directory to extract the files to.
"""
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
# Filter out __MACOSX directory entries
valid_files = [file for file in zip_ref.namelist(
) if not file.startswith('__MACOSX/')]
# Extract only the valid files
for file in valid_files:
zip_ref.extract(file, extract_to)
@staticmethod
def device_name_from_path(path, name_as_ip = True):
"""
Extracts a device name from a file system path based on Pupil Labs naming conventions.
The device name can be searched as an identifier (e.g., "G001") or an IP address (e.g., "192.168.1.101")
within a file path, starting from the last directory segment and moving backwards.
Args:
path (str): The file path from which to extract the device name or IP address.
name_as_ip (bool, optional):
If True, returns the name as corresponding IP address.
If False, returns the name in the "G###" format. Defaults to True.
Returns:
str or None: The extracted device name or IP address, or None if no valid match is found.
"""
g_pattern = re.compile(r'^G\d{3}$')
ip_pattern = re.compile(r'^(?:\d{1,3}\.){3}\d{1,3}$')
for node in path.split(os.sep)[::-1]: #Match last node first
if g_pattern.fullmatch(node):
if name_as_ip:
return config["defaults"]["network_id"] + "." + str(config["defaults"]["offset"] + int(node[-3:]))
else:
return node
elif ip_pattern.fullmatch(node):
# Validate IP numbers are 0–255
if name_as_ip and all(0 <= int(part) <= 255 for part in node.split('.')):
return node
elif not name_as_ip:
return "G" + str(int(node.split()[-1]) - config["defaults"]["offset"]).zfill(3)
return None
@staticmethod
def parse_glasses_dir(input_path, offset_corrected = True, search_key="", device_name_from_info = False):
"""
Parses a directory to find recordings and relevant data files.
This function recursively scans the given directory path for Pupil Labs recording folders,
identified by UUID-named directories. It collects file paths to key data streams such as
gaze, world, fixations, blinks, events, IMU, and saccades, as well as worldview videos.
Optionally, it determines the name of the glasses device either from metadata files or
from the directory structure.
Args:
input_path (str): The root directory to search through recursively.
offset_corrected (bool, optional):
If True, expects files prefixed with 'ts_corr_' (offset-corrected versions).
Defaults to False.
search_key (str, optional):
If provided, only files containing this string in their path will be processed.
Useful for filtering specific subsets of files. Defaults to "".
device_name_from_info (bool, optional):
If True, attempts to read device name from the 'info.json' file within each recording.
If False, device name is derived from the directory path. Defaults to False.
Returns:
tuple:
- glasses_names (list of str): List of device names or IPs (based on config settings).
- worldview_vids (list of str): List of file paths to worldview video files.
- stream_csvs (dict of str: list of str): Dictionary mapping stream names
('gaze', 'world', 'fixations', 'blinks', 'events', 'imu', 'saccades', '3d_eye_states')
to lists of corresponding file paths.
"""
glasses_names, worldview_vids, rec_paths = [], [], []
stream_csvs = {"gaze": [], "world": [], "fixations": [], "blinks": [], "events": [], "imu": [], "saccades": [], "3d_eye_states": []}
pre = "ts_corr_" if offset_corrected else ""
worldview_pattern = re.compile(config["paths"]["worldview_video_filename_re"])
#Pupil Labs recording directories are named as UIDs so the following lines recursively searches for all dirs that match the UID regex
uid_pattern = re.compile(r'[a-fA-F0-9]{8}-?[a-fA-F0-9]{4}-?[a-fA-F0-9]{4}-?[a-fA-F0-9]{4}-?[a-fA-F0-9]{12}')
for p in tqdm(glob.glob(os.path.join(input_path, "**"), recursive=True), desc = "Scanning files..."):
try:
if os.path.isdir(p) and uid_pattern.fullmatch(os.path.basename(p)) and not os.path.basename(p).startswith("b5b4"): #rejecting workspace dirs which are also named as UIDs
name = None
rec_paths.append(p)
device_worldviews = []
for file_ in glob.glob(os.path.join(p, "**"), recursive=True):
#check extension and search phrase
if (not os.path.isfile(file_)) or (search_key not in file_):
continue
elif worldview_pattern.fullmatch(os.path.basename(file_)): #There could be more than one worldview videos in a recording
device_worldviews.append(file_)
elif os.path.basename(file_) == pre + config["paths"]["worldview_csv_filename"]:
stream_csvs["world"].append(file_)
elif os.path.basename(file_) == pre + config["paths"]["gaze_csv_filename"]:
stream_csvs["gaze"].append(file_)
elif os.path.basename(file_) == pre + config["paths"]["blinks_csv_filename"]:
stream_csvs["blinks"].append(file_)
elif os.path.basename(file_) == pre + config["paths"]["fixations_csv_filename"]:
stream_csvs["fixations"].append(file_)
elif os.path.basename(file_) == pre + config["paths"]["events_csv_filename"]:
stream_csvs["events"].append(file_)
elif os.path.basename(file_) == pre + config["paths"]["imu_csv_filename"]:
stream_csvs["imu"].append(file_)
elif os.path.basename(file_) == pre + config["paths"]["saccades_csv_filename"]:
stream_csvs["saccades"].append(file_)
elif os.path.basename(file_) == pre + config["paths"]["eye_states_csv_filename"]:
stream_csvs["3d_eye_states"].append(file_)
elif device_name_from_info and os.path.basename(file_) == config["paths"]["info_filename"]:
with open(file_, 'r') as f:
data = json.load(f)
name = data.get('android_device_name')
worldview_vids.append(device_worldviews) #one item per device.
name = name if name is not None else FileProcessor.device_name_from_path(p, name_as_ip=config["defaults"]["device_name_as_ip"])
glasses_names.append(name)
except Exception as e:
print(e)
continue
return glasses_names, worldview_vids, stream_csvs, rec_paths
@staticmethod
def parse_central_camera_dir(input_path,
video_fname = "output_video.mp4",
csv_fname = "central_timestamp.csv"):
"""
Retrieves the paths of central video and corresponding timestamp file from a directory.
Args:
- input_path (str): The path of the directory.
- video_fname (str): Filename for video file inside directory. Default value = "output_video.mp4"
- csv_fname (str): Filename for timestamp csv file inside directory. Defaule value = "central_timestamp.csv"
Returns:
- central_video_path (str): The path of the central video file.
- central_timestamp_path (str): The path of the central timestamp CSV file.
"""
central_video_path = None
central_timestamp_path = None
# offset_path = None
for file in os.listdir(input_path):
if file == video_fname:
central_video_path = os.path.join(input_path, file)
elif file == csv_fname:
# if file == 'offsets.csv':
# offset_path = os.path.join(input_path, file)
# else:
central_timestamp_path = (os.path.join(input_path, file))
return central_video_path, central_timestamp_path
@staticmethod
def generate_csv_templates(output_path, goal, glasses_names, cols):
"""
Generates CSV templates for each pair of glasses.
Args:
- output_path (str): The path of the output directory for the transformed gaze CSV files.
- glasses_names (list[str]): A list of glasses names.
Returns:
- csv_file_paths (list): A list of CSV file paths.
"""
if not os.path.exists(output_path):
os.makedirs(output_path)
csv_file_paths = []
for name in glasses_names:
csv_filename = f'{goal}_{name}.csv'
csv_file_path = os.path.join(output_path, csv_filename)
csv_file = CSVProcessor(csv_file_path, cols=cols)
csv_file.write_csv()
csv_file_paths.append(csv_file_path)
return csv_file_paths
@staticmethod
def check_date(path, year, month, date, tz = 'Canada/Eastern'):
"""
Checks whether the start time in a Neon recording's info.json file matches the given date in a specified timezone.
Args:
path (str): Path to the JSON file for a Neon Companion recording. The file must have a "start_time" field.
year (int): Year to compare against.
month (int): Month to compare against.
date (int): Day to compare against.
tz (str, optional): Timezone to convert the start time to. Defaults to 'Canada/Eastern'.
Returns:
bool: True if the start time matches the specified date in the given timezone, False otherwise.
"""
with open(path) as f:
d = json.load(f)
utc_time = datetime.fromtimestamp(d["start_time"]/1000000000, tz=timezone.utc)
toronto_time = utc_time.astimezone(pytz.timezone(tz))
return toronto_time.date() == datetime(year, month, date).date()
@staticmethod
def confirm_and_delete(path, confirm_over_mbs = 10):
"""
Prints the size of the file or directory at the given path and prompts the user for confirmation before deletion.
Args:
path (str): The path to the file or directory to be deleted.
Returns:
bool: True if the file/directory was deleted, False otherwise.
"""
if not os.path.exists(path):
print(f"Path does not exist: {path}")
return False
if os.path.isfile(path):
size_bytes = os.path.getsize(path)
elif os.path.isdir(path):
size_bytes = sum(
os.path.getsize(os.path.join(dirpath, filename))
for dirpath, _, filenames in os.walk(path)
for filename in filenames
)
else:
print(f"Unsupported file type: {path}")
return False
size_mb = size_bytes / (1024 ** 2) #readable size
# Prompt for confirmation
if size_mb <= confirm_over_mbs:
confirm = 'y'
else:
print(f"Size of '{path}': {size_mb:.2f} MB")
confirm = input("Press y to confirm deletion? [y/N]: ").strip().lower()
if confirm in ['y', 'yes']:
if os.path.isfile(path):
os.remove(path)
else:
shutil.rmtree(path)
# print(f"Deleted: {path}")
return True
else:
print("Deletion cancelled.")
return False