-
Notifications
You must be signed in to change notification settings - Fork 21
/
viame.ts
349 lines (310 loc) · 11.5 KB
/
viame.ts
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
import npath from 'path';
import { spawn } from 'child_process';
import fs from 'fs-extra';
import {
Settings, DesktopJob, RunPipeline, RunTraining,
DesktopJobUpdater,
} from 'platform/desktop/constants';
import { cleanString } from 'platform/desktop/sharedUtils';
import { serialize } from 'platform/desktop/backend/serializers/viame';
import { observeChild } from 'platform/desktop/backend/native/processManager';
import { MultiType, stereoPipelineMarker, multiCamPipelineMarkers } from 'dive-common/constants';
import * as common from './common';
import { jobFileEchoMiddleware, createWorkingDirectory } from './utils';
import {
getMultiCamImageFiles, getMultiCamVideoPath,
writeMultiCamStereoPipelineArgs,
} from './multiCamUtils';
const PipelineRelativeDir = 'configs/pipelines';
const DiveJobManifestName = 'dive_job_manifest.json';
export interface ViameConstants {
setupScriptAbs: string; // abs path setup comman
trainingExe: string; // name of training binary on PATH
kwiverExe: string; // name of kwiver binary on PATH
shell: string | boolean; // shell arg for spawn
}
/**
* a node.js implementation of dive_tasks.tasks.run_pipeline
*/
async function runPipeline(
settings: Settings,
runPipelineArgs: RunPipeline,
updater: DesktopJobUpdater,
validateViamePath: (settings: Settings) => Promise<true | string>,
viameConstants: ViameConstants,
): Promise<DesktopJob> {
const { datasetId, pipeline } = runPipelineArgs;
const isValid = await validateViamePath(settings);
if (isValid !== true) {
throw new Error(isValid);
}
let pipelinePath = npath.join(settings.viamePath, PipelineRelativeDir, pipeline.pipe);
if (runPipelineArgs.pipeline.type === 'trained') {
pipelinePath = pipeline.pipe;
}
const projectInfo = await common.getValidatedProjectDir(settings, datasetId);
const meta = await common.loadJsonMetadata(projectInfo.metaFileAbsPath);
const jobWorkDir = await createWorkingDirectory(settings, [meta], pipeline.name);
const detectorOutput = npath.join(jobWorkDir, 'detector_output.csv');
let trackOutput = npath.join(jobWorkDir, 'track_output.csv');
const joblog = npath.join(jobWorkDir, 'runlog.txt');
//TODO: TEMPORARY FIX FOR DEMO PURPOSES
let requiresInput = false;
if ((/utility_/g).test(pipeline.pipe)) {
requiresInput = true;
}
let groundTruthFileName;
if (requiresInput) {
// MultiCam ids have '/' in it to designate camera, replace to make a valid location
groundTruthFileName = `groundtruth_${meta.id.replace('/', '_')}.csv`;
const groundTruthFileStream = fs.createWriteStream(
npath.join(jobWorkDir, groundTruthFileName),
);
const inputData = await common.loadAnnotationFile(projectInfo.trackFileAbsPath);
await serialize(groundTruthFileStream, inputData, meta);
groundTruthFileStream.end();
}
let metaType = meta.type;
if (metaType === MultiType && meta.multiCam) {
metaType = meta.multiCam.cameras[meta.multiCam.defaultDisplay].type;
}
let command: string[] = [];
const stereoOrMultiCam = (pipeline.type === stereoPipelineMarker
|| multiCamPipelineMarkers.includes(pipeline.type));
if (metaType === 'video') {
let videoAbsPath = npath.join(meta.originalBasePath, meta.originalVideoFile);
if (meta.type === MultiType) {
videoAbsPath = getMultiCamVideoPath(meta);
} else if (meta.transcodedVideoFile) {
videoAbsPath = npath.join(projectInfo.basePath, meta.transcodedVideoFile);
}
command = [
`${viameConstants.setupScriptAbs} &&`,
`"${viameConstants.kwiverExe}" runner`,
'-s "input:video_reader:type=vidl_ffmpeg"',
`-p "${pipelinePath}"`,
`-s downsampler:target_frame_rate=${meta.fps}`,
];
if (!stereoOrMultiCam) {
command.push(`-s input:video_filename="${videoAbsPath}"`);
command.push(`-s detector_writer:file_name="${detectorOutput}"`);
command.push(`-s track_writer:file_name="${trackOutput}"`);
}
} else if (metaType === 'image-sequence') {
// Create frame image manifest
const manifestFile = npath.join(jobWorkDir, 'image-manifest.txt');
// map image file names to absolute paths
let imageList = meta.originalImageFiles;
if (meta.type === MultiType) {
imageList = getMultiCamImageFiles(meta);
}
const fileData = imageList
.map((f) => npath.join(meta.originalBasePath, f))
.join('\n');
await fs.writeFile(manifestFile, fileData);
command = [
`${viameConstants.setupScriptAbs} &&`,
`"${viameConstants.kwiverExe}" runner`,
`-p "${pipelinePath}"`,
];
if (!stereoOrMultiCam) {
command.push(`-s input:video_filename="${manifestFile}"`);
command.push(`-s detector_writer:file_name="${detectorOutput}"`);
command.push(`-s track_writer:file_name="${trackOutput}"`);
}
}
if (requiresInput && !stereoOrMultiCam) {
command.push(`-s detection_reader:file_name="${groundTruthFileName}"`);
command.push(`-s track_reader:file_name="${groundTruthFileName}"`);
}
let multiOutFiles: Record<string, string>;
if (meta.multiCam && stereoOrMultiCam) {
// eslint-disable-next-line max-len
const { argFilePair, outFiles } = await writeMultiCamStereoPipelineArgs(jobWorkDir, meta, settings, requiresInput);
Object.entries(argFilePair).forEach(([arg, file]) => {
command.push(`-s ${arg}="${file}"`);
});
multiOutFiles = {};
Object.entries(outFiles).forEach(([cameraName, fileName]) => {
multiOutFiles[cameraName] = npath.join(jobWorkDir, fileName);
});
trackOutput = npath.join(jobWorkDir, outFiles[meta.multiCam.defaultDisplay]);
if (meta.multiCam.calibration) {
command.push(`-s measurer:calibration_file="${meta.multiCam.calibration}"`);
}
} else if (pipeline.type === stereoPipelineMarker) {
throw new Error('Attempting to run a multicam pipeline on non multicam data');
}
const job = observeChild(spawn(command.join(' '), {
shell: viameConstants.shell,
cwd: jobWorkDir,
}));
const jobBase: DesktopJob = {
key: `pipeline_${job.pid}_${jobWorkDir}`,
command: command.join(' '),
jobType: 'pipeline',
pid: job.pid,
args: runPipelineArgs,
title: runPipelineArgs.pipeline.name,
workingDir: jobWorkDir,
datasetIds: [datasetId],
exitCode: job.exitCode,
startTime: new Date(),
};
fs.writeFile(npath.join(jobWorkDir, DiveJobManifestName), JSON.stringify(jobBase, null, 2));
updater({
...jobBase,
body: [''],
});
job.stdout.on('data', jobFileEchoMiddleware(jobBase, updater, joblog));
job.stderr.on('data', jobFileEchoMiddleware(jobBase, updater, joblog));
job.on('exit', async (code) => {
if (code === 0) {
try {
const { meta: newMeta } = await common.ingestDataFiles(settings, datasetId, [detectorOutput, trackOutput], multiOutFiles);
if (newMeta) {
meta.attributes = newMeta.attributes;
await common.saveMetadata(settings, datasetId, meta);
}
} catch (err) {
console.error(err);
}
}
updater({
...jobBase,
body: [''],
exitCode: code,
endTime: new Date(),
});
});
return jobBase;
}
/**
* a node.js implementation of dive_tasks.tasks.run_training
*/
async function train(
settings: Settings,
runTrainingArgs: RunTraining,
updater: DesktopJobUpdater,
validateViamePath: (settings: Settings) => Promise<true | string>,
viameConstants: ViameConstants,
): Promise<DesktopJob> {
const isValid = await validateViamePath(settings);
if (isValid !== true) {
throw new Error(isValid);
}
/* Zip together project info and meta */
const infoAndMeta = await Promise.all(
runTrainingArgs.datasetIds.map(async (id) => {
const projectInfo = await common.getValidatedProjectDir(settings, id);
const meta = await common.loadJsonMetadata(projectInfo.metaFileAbsPath);
return { projectInfo, meta };
}),
);
const jsonMetaList = infoAndMeta.map(({ meta }) => meta);
// Working dir for training
const jobWorkDir = await createWorkingDirectory(settings, jsonMetaList, runTrainingArgs.pipelineName);
// Argument files for training
const inputFolderFileList = npath.join(jobWorkDir, 'input_folder_list.txt');
const groundTruthFileList = npath.join(jobWorkDir, 'input_truth_list.txt');
const groundtruthFilenames = await Promise.all(
infoAndMeta.map(async ({ meta, projectInfo }) => {
// Organize data for training
const groundTruthFileName = `groundtruth_${meta.id}.csv`;
const groundTruthFileStream = fs.createWriteStream(
npath.join(jobWorkDir, groundTruthFileName),
);
const inputData = await common.loadAnnotationFile(projectInfo.trackFileAbsPath);
await serialize(groundTruthFileStream, inputData, meta);
groundTruthFileStream.end();
return groundTruthFileName;
}),
);
// Write groundtruth filenames to list
const groundtruthFile = fs.createWriteStream(groundTruthFileList);
groundtruthFilenames.forEach((name) => groundtruthFile.write(`${name}\n`));
groundtruthFile.end();
// Write input folder paths to list
const inputFile = fs.createWriteStream(inputFolderFileList);
infoAndMeta.forEach(({ projectInfo, meta }) => {
if (meta.type === 'video') {
let videopath = '';
/* If the video has been transcoded, use that video */
if (meta.transcodedVideoFile) {
videopath = npath.join(projectInfo.basePath, meta.transcodedVideoFile);
} else {
videopath = npath.join(meta.originalBasePath, meta.originalVideoFile);
}
inputFile.write(`${videopath}\n`);
} else if (meta.type === 'image-sequence') {
inputFile.write(`${npath.join(meta.originalBasePath)}\n`);
}
});
inputFile.end();
const joblog = npath.join(jobWorkDir, 'runlog.txt');
const configFilePath = npath.join(settings.viamePath, PipelineRelativeDir, runTrainingArgs.trainingConfig);
const command = [
`${viameConstants.setupScriptAbs} &&`,
`"${viameConstants.trainingExe}"`,
`--input-list "${inputFolderFileList}"`,
`--input-truth "${groundTruthFileList}"`,
`--config "${configFilePath}"`,
'--no-query',
'--no-adv-prints',
'--no-embedded-pipe',
];
if (runTrainingArgs.annotatedFramesOnly) {
command.push('--gt-frames-only');
}
const job = observeChild(spawn(command.join(' '), {
shell: viameConstants.shell,
cwd: jobWorkDir,
}));
const cleanPipelineName = cleanString(runTrainingArgs.pipelineName);
const jobBase: DesktopJob = {
key: `pipeline_${job.pid}_${jobWorkDir}`,
command: command.join(' '),
jobType: 'training',
pid: job.pid,
args: runTrainingArgs,
title: cleanPipelineName,
workingDir: jobWorkDir,
datasetIds: runTrainingArgs.datasetIds,
exitCode: job.exitCode,
startTime: new Date(),
};
fs.writeFile(npath.join(jobWorkDir, DiveJobManifestName), JSON.stringify(jobBase, null, 2));
updater({
...jobBase,
body: [''],
});
job.stdout.on('data', jobFileEchoMiddleware(jobBase, updater, joblog));
job.stderr.on('data', jobFileEchoMiddleware(jobBase, updater, joblog));
job.on('exit', async (code) => {
let exitCode = code;
const bodyText = [''];
if (code === 0) {
try {
await common.processTrainedPipeline(settings, runTrainingArgs, jobWorkDir);
} catch (err) {
console.error(err);
exitCode = 1;
bodyText.unshift((err as Error).toString());
fs.appendFile(joblog, bodyText[0], (error) => {
if (error) throw error;
});
}
}
updater({
...jobBase,
body: bodyText,
exitCode,
endTime: new Date(),
});
});
return jobBase;
}
export {
runPipeline,
train,
};