-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
2832 lines (2212 loc) · 83.9 KB
/
Copy pathmain.js
File metadata and controls
2832 lines (2212 loc) · 83.9 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Modules to control application life and create native browser window
const { app, BrowserWindow, Menu, MenuItem, ipcMain, dialog } = require('electron');
const { updateElectronApp, UpdateSourceType } = require('update-electron-app');
const { MediaInfo , mediaInfoFactory} = require('mediainfo.js');
// run this as early in the main process as possible
// https://www.electronforge.io/config/makers/squirrel.windows
if (require('electron-squirrel-startup')) app.quit();
const isMac = process.platform === 'darwin'
const menuTemplate = [
// { role: 'appMenu' }
...(isMac
? [{
label: app.name,
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideOthers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' }
]
}]
: []),
// { role: 'fileMenu' }
{
label: 'File',
submenu: [
isMac ? { role: 'close' } : { role: 'quit' }
]
},
// { role: 'editMenu' }
{
label: 'Edit',
submenu: [
{ role: 'undo' },
// { role: 'redo' },
// { type: 'separator' },
// { role: 'cut' },
// { role: 'copy' },
// { role: 'paste' },
// ...(isMac
// ? [
// // { role: 'pasteAndMatchStyle' },
// { role: 'delete' },
// // { role: 'selectAll' },
// // { type: 'separator' },
// ]
// : [
// { role: 'delete' },
// // { type: 'separator' },
// // { role: 'selectAll' }
// ])
]
},
// { role: 'viewMenu' }
{
label: 'View',
submenu: [
// { role: 'reload' },
// { role: 'forceReload' },
{ role: 'toggleDevTools' },
{ type: 'separator' },
// { role: 'resetZoom' },
// { role: 'zoomIn' },
// { role: 'zoomOut' },
// { type: 'separator' },
{ role: 'togglefullscreen' }
]
},
// { role: 'windowMenu' }
{
label: 'Window',
submenu: [
{ role: 'minimize' },
{ role: 'zoom' },
...(isMac
? [
{ type: 'separator' },
{ role: 'front' },
{ type: 'separator' },
{ role: 'window' }
]
: [
{ role: 'close' }
])
]
},
// {
// role: 'help',
// submenu: [
// {
// label: 'Learn More',
// click: async () => {
// const { shell } = require('electron')
// await shell.openExternal('https://electronjs.org')
// }
// }
// ]
// }
]
// Use win32 property for consistency across Windows and MacOS
// https://nodejs.org/api/path.html#windows-vs-posix
const path = process.platform === 'win32' ? require('node:path/win32') : require('node:path/posix');
const fs = require('node:fs')
const readline = require('node:readline');
// Update the app automatically
updateElectronApp({
updateSource: {
type: UpdateSourceType.ElectronPublicUpdateService,
repo: 'ecker-lab/SiLVi'
},
updateInterval: '5 minutes'
});
const videoFormatNames = ['mp4', 'mov', 'm4v', 'mkv', 'webm'];
const videoExtensions = videoFormatNames.map(name => '.' + name)
const configFileName = 'config.json';
// Define column headers for behavior records
const behaviorColHeaderRow = [
'Subject', 'Action', 'Target',
'StartFrame', 'EndFrame', 'DurationInFrames',
'StartSecond', 'EndSecond', 'DurationInSeconds'
];
// Define the tracking data columns
const trackingColNames = [
'trackNumber', 'trackId', 'x', 'y', 'width', 'height', 'confidenceTrack',
'classId', 'nameOrder', 'confidenceId'
];
// Define the value for variables which do not have defined values
const naStr = 'NA';
// Define CSV delimiter
const csvDelimiter = ',';
// Numbers after decimal point for time-related values in exported files
const precisionForSeconds = 4;
// User data directory path for the app
const userDataDir = app.getPath('userData');
const appDataDir = path.join(userDataDir, 'appData');
// Create the app data folder if it does not exist already
if (!fs.existsSync(appDataDir)) {
try {
fs.mkdirSync(appDataDir);
} catch (err) {
console.error(err);
}
}
/**
*
* @param {*} folderPath
* @returns
*/
async function getFilesInFolder(folderPath) {
try {
if (fs.existsSync(folderPath)) {
const isFile = fileName => {
return fs.lstatSync(fileName).isFile();
};
const files = fs.readdirSync(folderPath)
.map(fileName => {
return path.join(folderPath, fileName);
})
.filter(isFile);
return files
}
} catch (err) {
console.error(err);
}
}
function handleClearAppData() {
try {
fs.rmSync(appDataDir, { recursive: true, force: true });
console.log(`${appDataDir} is deleted!`);
return 'success';
} catch (err) {
console.error(`${appDataDir} could not be deleted!`, err);
}
}
function handleResetSettings() {
const configFilePath = path.join(appDataDir, configFileName);
try {
fs.unlinkSync(configFilePath);
console.log('Config file deleted successfully!', configFileName)
return configFilePath;
} catch (err) {
console.log('Error deleting config file!', err);
return;
}
}
/**
* Copies a file to the user data directory with a given name
* @param {import('node:fs').PathLike} filePath File path of the original file
* @param {String} fileName File name of the copy in the user data directory
* @returns
*/
function handleCopyToUserDataDir(filePath, fileName) {
const pathInUserDataDir = path.join(appDataDir, fileName);
try {
fs.copyFileSync(filePath, pathInUserDataDir);
console.log(`${filePath} was copied to ${pathInUserDataDir}`);
return {success: true};
} catch {
console.error('The file could not be copied to the user data directory!');
}
}
async function handleOpenDirectory () {
const { canceled, filePaths } = await dialog.showOpenDialog(BrowserWindow.getFocusedWindow(), {
title: 'Choose a directory',
// filters: [{ name: 'Movies', extensions: ['mkv', 'avi', 'mp4'] }],
properties: ['openDirectory'],
message: "Choose a directory"
})
if (canceled) {
return { canceled: true }
}
if (!canceled) {
const dirPath = filePaths[0];
// Check read/write access
try {
fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
console.log(`${dirPath} is readable/writable`);
return { dirPath: dirPath };
} catch (err) {
console.error(`${dirPath} is NOT accessible!`);
}
}
}
// Get video file path list if user placed them in the specific folder
async function handleGetVideosFromDir(experimentDir) {
const isFile = filePath => {
return fs.lstatSync(filePath).isFile()
}
const isVideo = filePath => {
return videoExtensions.includes(path.extname(filePath).toLowerCase())
}
// const videoDirPath = path.join(__dirname, 'Experiment', 'Videos')
const videoDirPath = path.join(experimentDir, 'Videos')
if (fs.existsSync(videoDirPath)) {
const videoFilePaths = fs.readdirSync(videoDirPath)
.map(fileName => {return path.join(videoDirPath, fileName)})
.filter(isFile)
.filter(isVideo);
return videoFilePaths
} else {
console.log('No video folder could be found!')
return
}
}
/**
*
* Function to determine delimiter
* @param {*} line - A line in a file
* @returns {String} - file delimiter
*/
function determineDelimiter(line) {
// Array of potential delimiters to test
const potentialDelimiters = [',', ';', '\t', '|', ' ', ':'];
// Iterate through each potential delimiter and count occurrences
let maxCount = 0;
let delimiter = '';
potentialDelimiters.forEach(potentialDelimiter => {
let count = line.split(potentialDelimiter).length - 1;
if (count > maxCount) {
maxCount = count;
delimiter = potentialDelimiter;
}
});
return delimiter;
}
async function handleReadInteractionFile(filePath) {
const data = fs.readFileSync(filePath, 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
});
const delimiter = determineDelimiter(filePath);
// Split the file content into rows
const rows = data.split('\n').map(row => row.split(delimiter));
// Array to save observations
let observationArr = [];
// Initialize last observation properties
let lastSubjectId;
let lastObjectId;
let lastLabel;
let lastFrameNumber;
let lastObservation;
// Iterate over rows to collapse each observation (with consecutive properties) into a single entry
rows.forEach(row => {
const [frameNumber, subjectId, objectId, label] = row;
// Check if you encountered a new observation
if (subjectId !== lastSubjectId || objectId !== lastObjectId || lastLabel !== label) {
// Complete the last observation and add it to the array
if (lastObservation) {
lastObservation.timeEnd = lastFrameNumber;
observationArr.push(lastObservation);
}
// Start a new observation
let newObservation = {
subjectId: subjectId,
objectId: objectId,
label: label,
timeStart: parseInt(frameNumber),
timeEnd: 'TBD'
}
lastSubjectId = subjectId;
lastObjectId = objectId;
lastLabel = label;
lastObservation = newObservation;
}
// Always keep track of frame number
lastFrameNumber = parseInt(frameNumber);
})
if (observationArr.length > 0) {
return observationArr;
}
}
/**
* Reads a tracking file with or without identification labels (i.e. individual IDs/names)
* @param {import('node:fs').PathLike} filePath Absolute file path of the tracking file
* @returns {Object[] | undefined} Array of Objects for all tracks or undefined if the operation was unsuccessful
*/
function handleReadTrackingFile(filePath) {
// Reads all tracks into a master Array which consists of track Objects.
// The master Array will be referenced by two lookup tables/Maps in the front end.
// 1. idMap: { classId: { trackId: masterArray[idx] }
// 2. frameMap: { trackNumber: masterArray[idx] }
if (!trackingColNames) return;
return new Promise((resolve, reject) => {
// Check if a file path is given
if (!filePath) {
const reason = 'No file path was given for the tracking file!';
console.log(reason);
reject(reason);
return;
}
// Check if the given path exists
if (!fs.existsSync(filePath)) {
const reason = `Given path for the tracking file does not exist! ${filePath}`;
console.log(reason);
reject(reason);
return;
}
// Check if the given path is accessible
try {
fs.accessSync(filePath, fs.constants.R_OK)
} catch (err) {
console.log(err);
const reason = `Given path for the tracking file cannot be read! ${filePath}`;
reject(reason);
return;
}
// Define the variables that should be Strings or have float and integer values
const floatVarNames = ['width', 'height', 'w', 'h', 'x', 'y', 'confidence'];
const intVarNames = ['nameOrder', 'order'];
const idVarNames = ['classId', 'trackId'];
const masterVarNames = ['trackNumber', 'frameNumber']; // These are the main values to determine the validity of the row
const readStream = fs.createReadStream(filePath);
const rl = readline.createInterface({
input: readStream,
// output: stdout,
crlfDelay: Infinity // For reading files with \r\n line delimiter
});
// Initialize an array for holding track objects
const tracks = [];
// Read and process each line
rl.on('line', (line) => {
// Skip header lines (metadata) starting with "#" character
if (!line.startsWith('#')) {
// Split the line into columns
const delimiter = line.includes(';') ? ';' : ',';
// console.log('Delimiter:', delimiter);
const lineArr = line.split(new RegExp('\\s*' + delimiter + '\\s*'));
// console.log('Splitted line regex', new RegExp('\\s*' + delimiter + '\\s*'));
// Skip the empty line
if (lineArr.length === 0) return;
// Object for each track to contain key-value pairs
const trackObj = {};
// Iterate over the tracking data column names
for (let idx = 0; idx < trackingColNames.length; idx++) {
// Get the column name
const colName = trackingColNames[idx];
// Link each column of the row to its corresponding variable name
// First convert everything to string and remove all white spaces
trackObj[colName] = lineArr[idx] ? lineArr[idx].toString().replace(/\s+/g, '') : naStr;
// Convert column name to lower case for robust comparison
const lowColName = colName.toLowerCase();
// Skip an iteration which corresponds to an invalid row
const isMasterVar = masterVarNames.some(varName => lowColName.includes(varName));
if (isMasterVar && Number.isNaN(parseInt(trackObj[colName]))) {
return;
};
// Format float columns
const isFloat = floatVarNames.some(varName => lowColName.includes(varName));
if (isFloat) {
const parsedVal = parseFloat(trackObj[colName]);
trackObj[colName] = Number.isNaN(parsedVal) ? naStr : parsedVal;
}
// Format integer columns
const isInt = intVarNames.some(varName => lowColName.includes(varName));
if (isInt) {
const parsedVal = parseInt(trackObj[colName]);
trackObj[colName] = Number.isNaN(parsedVal) ? naStr : parsedVal;
}
// If all track object values are empty, ignore the line
const isInvalidObj = Object.values(trackObj).every(value => value === naStr || value === null || typeof value === 'undefined');
if (isInvalidObj) return;
}
// Add the extracted track data to final array
tracks.push(trackObj);
}
});
// Return the result if process was successful
rl.on('close', () => {
console.log('File reading finished');
// readStream.destroy();
resolve(tracks);
});
// Check for line reading errors
rl.on('error', (err) => {
console.error('Cleaning up:', err);
readStream.destroy();
reject(err);
});
// Handle read stream errors
readStream.on('error', (err) => {
console.log('Failed to open the stream:', err);
readStream.destroy();
reject(err);
});
});
}
/**
* Reads a tracking file with or without identification labels (i.e. individual IDs/names)
* @param {import('node:fs').PathLike} filePath Absolute file path of the tracking file
* @returns {Object[] | undefined} Array of Objects for all tracks or undefined if the operation was unsuccessful
*/
function handleReadTrackingFileOld(filePath) {
// Reads all tracks into a master Array which consists of track Objects.
// The master Array will be referenced by two lookup tables/Maps in the front end.
// 1. idMap: { classId: { trackId: masterArray[idx] }
// 2. frameMap: { trackNumber: masterArray[idx] }
if (!filePath) return;
if (!trackingColNames) return;
const data = fs.readFileSync(filePath, 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
});
// Skip header lines (metadata) starting with "#" character
const filteredRows = data.split('\n').filter(row => !row.startsWith('#'))
// Create an array of rows separated by file delimiter
const delimiter = determineDelimiter(filteredRows[0]);
const rows = filteredRows.map(row => row.split(delimiter));
// const trackingMap = new Map(); // Tracking map track/frame numbers as keys
// let uniqueSpecies = new Set(); // Find unique class values
// const uniqueTrackIds = new Map(); // Find unique track ID values
// Tracking map with class and track IDs as keys.
// Each class has an inner Map as its value.
// Each inner Map has track IDs as keys and arrays of Objects for track info as values.
// idMap structure: Map(classId: Map(trackId: Array of Obj(trackInfo)))
// const idMap = new Map();
// Define the variables that should be Strings or have float and integer values
const floatVarNames = ['width', 'height', 'w', 'h', 'x', 'y', 'confidence'];
const intVarNames = ['nameOrder', 'order'];
const idVarNames = ['classId', 'trackId'];
const masterVarNames = ['trackNumber', 'frameNumber']; // These are the main values to determine the validity of the row
// Initialize an array for holding track objects
const tracks = [];
rows.forEach(row => {
// const [trackNumber, trackId, x, y, width, height, confidenceTrack, classId, nameOrder, confidenceId] = row;
// Flag for skipping empty/invalid rows
let shouldSkip = true;
// Object for each track to contain key-value pairs
const trackObj = {};
// Iterate over the tracking data column names
for (let idx = 0; idx < trackingColNames.length; idx++) {
// Get the column name
const colName = trackingColNames[idx];
// Link each column of the row to its corresponding variable name
// First convert everything to string and remove all white spaces
trackObj[colName] = row[idx] ? row[idx].toString().replace(/\s+/g, '') : naStr;
// Convert column name to lower case for robust comparison
const lowColName = colName.toLowerCase();
// Skip an iteration which corresponds to an invalid row
const isMasterVar = masterVarNames.some(varName => lowColName.includes(varName));
if (isMasterVar && Number.isNaN(parseInt(trackObj[colName]))) {
shouldSkip = true;
break;
};
// Format float columns
const isFloat = floatVarNames.some(varName => lowColName.includes(varName));
if (isFloat) {
const parsedVal = parseFloat(trackObj[colName]);
trackObj[colName] = Number.isNaN(parsedVal) ? naStr : parsedVal;
}
// Format integer columns
const isInt = intVarNames.some(varName => lowColName.includes(varName));
if (isInt) {
const parsedVal = parseInt(trackObj[colName]);
trackObj[colName] = Number.isNaN(parsedVal) ? naStr : parsedVal;
}
// Add values
// trackObj[colName] = variables[colName];
}
// Skip the invalid row
if (shouldSkip) return;
// Add the data
tracks.push(trackObj);
// // Convert Strings to Numbers and back to Strings for consistency to remove white spaces
// const parsedId = parseInt(trackId).toString();
// const parsedSpecies = parseInt(class).toString();
// const parsedFrame = parseInt(trackNumber).toString();
// // Create the track info object
// let trackInfo = {
// trackNumber: trackNumber ? parseInt(trackNumber) : naStr,
// trackId: trackId ? parseInt(trackId) : naStr,
// x: x ? parseFloat(x) : naStr,
// y: y ? parseFloat(y) : naStr,
// width: width ? parseFloat(width) : naStr,
// height: height ? parseFloat(height) : naStr,
// confidenceTrack: confidenceTrack ? parseFloat(confidenceTrack): naStr,
// classId: classId ? classId.toString() : naStr
// }
// // Check if it is a identification file
// if (nameOrder && confidenceId) {
// trackInfo.nameOrder = parseInt(nameOrder);
// trackInfo.confidenceId = parseFloat(confidenceId);
// }
// Add it to the master array
// tracks.push(trackInfo);
// // Populate the tracking map
// if (!trackingMap.has(parsedFrame)) {
// trackingMap.set(parsedFrame, [trackInfo]);
// } else {
// trackingMap.get(parsedFrame).push(trackInfo);
// }
// // Create a Map with classes and track IDs as the keys
// if (!idMap.has(parsedSpecies)) {
// idMap.set(parsedSpecies, new Map([[parsedId, [trackInfo]]]));
// } else {
// const innerMap = idMap.get(parsedSpecies);
// if (!innerMap.has(parsedId)) {
// innerMap.set(parsedId, [trackInfo]);
// } else {
// const trackInfoArr = innerMap.get(parsedId);
// if (trackInfoArr && Array.isArray(trackInfoArr)) trackInfoArr.push(trackInfo);
// }
// }
// uniqueSpecies.add(parseInt(trackInfo['classId']));
// if (!isNaN(trackInfo.trackId)) {
// if (!uniqueTrackIds.has(trackInfo.classId)) {
// uniqueTrackIds.set(trackInfo.classId, new Set())
// }
// uniqueTrackIds.get(trackInfo.classId).add(trackInfo.trackId);
// }
// })
// let firstAvailTrackIds = new Map();
// for (let [class, trackIds] of uniqueTrackIds) {
// const firstAvailId = Math.max(...uniqueTrackIds.get(class)) + 1;
// firstAvailTrackIds.set(class, firstAvailId)
// }
// return {
// trackingMap: trackingMap,
// idMap: idMap,
// uniqueSpecies: uniqueSpecies,
// uniqueTrackIds: uniqueTrackIds,
// firstAvailTrackIds: firstAvailTrackIds
// }
});
return tracks
}
/**
*
* @param {*} filePath
* @returns - dictionary with rows in the tracking file
*/
// async function handleReadIdentificationFile(filePath) {
// // Same structure in tracking file until the end of last tracking coordinate
// // File structure after tracking boxes coordinates:
// // confidence of tracking: ?
// // class id: (e.g. 0)
// // order of identified individual in the individuals.txt file: (e.g. 7)
// // confidence in detection: (e.g. 0.6600000262260437)
// // Read the file
// const data = fs.readFileSync(filePath, 'utf8', (err, data) => {
// if (err) {
// console.error(err);
// return;
// }
// });
// // Determine file delimiter
// const delimiter = determineDelimiter(filePath);
// console.log(delimiter)
// if (!delimiter) {
// console.log('File delimiter could not be detected!');
// return;
// }
// let idMap = new Map();
// // Split file content into rows and then list of entries for each row
// const rows = data.split('\n').map(row => row.split(delimiter));
// rows.forEach(row => {
// const [trackNumber, trackId, x, y, width, height, confidenceTrack, classId, nameOrder, confidenceId] = row;
// const trackInfo = {
// 'trackNumber': parseInt(trackNumber),
// 'trackId': parseInt(trackId),
// 'x': parseFloat(x),
// 'y': parseFloat(y),
// 'width': parseFloat(width),
// 'height': parseFloat(height),
// 'confidenceTrack': parseFloat(confidenceTrack),
// 'classId': parseInt(classId),
// 'nameOrder': parseInt(nameOrder),
// 'confidenceId': parseFloat(confidenceId)
// }
// // Populate the map
// if (!idMap.has(parseInt(trackNumber))) {
// idMap.set(parseInt(trackNumber), [trackInfo]);
// } else {
// idMap.get(parseInt(trackNumber)).push(trackInfo);
// }
// })
// return {idMap: idMap, fileDelimiter: delimiter}
// }
function handleReadNameFile(filePath) {
const data = fs.readFileSync(filePath, 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
});
// Split the data into rows
const rows = data.split('\n');
// Get the first line to determine file delimiter
// const delimiter = determineDelimiter(rows[0]);
// if (!delimiter) {
// console.log('File delimiter could not be detected!');
// return;
// }
const names = rows
.map(row => row.split(csvDelimiter))
.filter(row => row.length > 0)
.flat(Infinity)
.map(name => name.trim());
// Attempt to verify the validity of the name file
const nameCount = names.length;
const upperThreshold = 1000; // Too many entries
const lowerThreshold = 1; // Too few entries
const maxStrLength = 50; // Too long strings - Maximum string length
// Result object
const result = {
names: null, // Read names array
reason: null // Reason for failure
}
if (nameCount > upperThreshold) {
result.reason = `Likely not a valid name file! More than ${upperThreshold} names detected.`;;
} else if (nameCount < lowerThreshold) {
result.reason = `Likely not a valid name file! Fewer than ${lowerThreshold} names detected.`;
} else if (names.some(name => name.length > maxStrLength)) {
result.reason = `Likely not a valid name file! Some entries have more then ${maxStrLength} characters.`;
} else {
result.names = names;
}
return result;
}
/**
* Search for the ethogram file for a video in a given directory
* @param {import('node:fs').PathLike} videoFilePath | Path of the opened video
* @param {import('node:fs').PathLike} dirPathToSearch | Optional path of the directory to search for. If no path is given, the default user data directory will be searched.
* @returns {import('node:fs').PathLike} | File path or undefined if no path was found
*/
function handleFindBehaviorFile(videoFilePath, dirPathToSearch) {
// Search user data directory by default
const dirPath = dirPathToSearch ? dirPathToSearch : appDataDir;
// console.log('Dir path', dirPath);
// console.log('Video file path', videoFilePath);
try {
// Check access
try {
fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
} catch (err) {
console.log(err);
}
// Get the filename without extension
const videoFileName = path.parse(videoFilePath).name;
// Read the directory contents including any subdirectories within it
const dirContentPaths = fs.readdirSync(dirPath, {recursive: true});
// Find directory that have an identical name to the video
// Return the absolute path of the ethogram file
const filePaths = dirContentPaths
.filter(entry => {
const parsedEntry = path.parse(entry);
return parsedEntry.name.includes(videoFileName) &&
(parsedEntry.name.includes('behavior') || parsedEntry.name.includes('ethogram')) &&
parsedEntry.ext.includes('csv');
})
.map(filteredEntry => path.join(dirPath, filteredEntry))
return filePaths[0]
} catch (err) {
console.log(err);
}
}
/**
* Search for the notes file for a video in a given directory
* @param {import('node:fs').PathLike} videoFilePath | Path of the opened video
* @param {import('node:fs').PathLike} dirPathToSearch | Optional path of the directory to search for. If no path is given, the default user data directory will be searched.
* @returns {import('node:fs').PathLike} | File path or undefined if no path was found
*/
function handleFindNotesFile(videoFilePath, dirPathToSearch) {
// Search user data directory by default
const dirPath = dirPathToSearch ? dirPathToSearch : appDataDir;
try {
// Check access
try {
fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
} catch (err) {
console.log(err);
}
// Get the filename without extension
const videoFileName = path.parse(videoFilePath).name;
// Read the directory contents including any subdirectories within it
const dirContentPaths = fs.readdirSync(dirPath, {recursive: true});
// Find directory that have an identical name to the video
// Return the absolute path of the notes file
const filePaths = dirContentPaths
.filter(entry => {
const parsedEntry = path.parse(entry);
return parsedEntry.name.includes(videoFileName) &&
parsedEntry.name.includes('notes') &&
parsedEntry.ext.includes('txt');
})
.map(filteredEntry => path.join(dirPath, filteredEntry))
return filePaths[0]
} catch (err) {
console.log(err);
}
}
/**
* Search for the metadata file for a video in a given directory
* @param {import('node:fs').PathLike} videoFilePath | Path of the opened video
* @param {import('node:fs').PathLike} dirPathToSearch | Optional path of the directory to search for. If no path is given, the default user data directory will be searched.
* @returns {import('node:fs').PathLike} | File path or undefined if no path was found
*/
function handleFindMetadataFile(videoFilePath, dirPathToSearch) {
// Search user data directory by default
const dirPath = dirPathToSearch ? dirPathToSearch : appDataDir;
try {
// Check access
try {
fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
} catch (err) {
console.log(err);
}
// Get the filename without extension
const videoFileName = path.parse(videoFilePath).name;
// Read the directory contents including any subdirectories within it
const dirContentPaths = fs.readdirSync(dirPath, {recursive: true});
// Find directory that have an identical name to the video
// Return the absolute path of the notes file
const filePaths = dirContentPaths
.filter(entry => {
const parsedEntry = path.parse(entry);
return parsedEntry.name.includes(videoFileName) &&
parsedEntry.name.includes('metadata') &&
parsedEntry.ext.includes('json');
})
.map(filteredEntry => path.join(dirPath, filteredEntry))
return filePaths[0]
} catch (err) {
console.log(err);
}
}
/**
* Search for tracking files for a video in a given directory
* @param {import('node:fs').PathLike} videoFilePath Path of the opened video
* @param {import('node:fs').PathLike} dirPathToSearch Optional path of the directory to search for. If no path is given, the default user data directory will be searched.
* @returns {Object | undefined} Object with tracking file path and identification file path
* @returns {import('node:fs').PathLike | undefined} Tracking file path
* @returns {import('node:fs').PathLike | undefined} Identification file path
*/
function handleFindTrackingFile(videoFilePath, dirPathToSearch) {
// Search user data directory by default
const dirPath = dirPathToSearch ? dirPathToSearch : appDataDir;
try {
// Check access
try {
fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
} catch (err) {
console.log(err);
}
// Get the filename without extension
const videoFileName = path.parse(videoFilePath).name;
// Read the directory contents including any subdirectories within it