-
Notifications
You must be signed in to change notification settings - Fork 7
/
getClips.js
246 lines (215 loc) · 6.93 KB
/
getClips.js
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
const fs = require('fs');
const path = require('path');
const csv = require('fast-csv');
const config = require('./config');
const { hashId, mkDirByPathSync } = require('./helpers');
const { updateClipStats, formatFinalClipsStats } = require('./processStats');
const errors = { tooSmall: {}, notFound: {} };
const TSV_OPTIONS = {
headers: true,
delimiter: '\t',
quote: false,
};
/**
* Main function for processing and downloading clips
*
* @param {Object} db db connection
* @param {Object} clipBucket datasets bucket object with name and bucket keys
* @param {string} releaseName name of current release
* @param {array} minorityLangs array of languages with fewer than 5 speakers
*
* @return {Object} locale-indexed stats object
*/
const processAndDownloadClips = (
db,
clipBucket,
releaseName,
minorityLangs
) => {
const queryFile = path.join(__dirname, 'queries', config.get('queryFile'));
// Counters for performance optimization and logging
let activeBucketConnections = 0;
let activeWriteStreams = 0;
let rowIndex = 0;
let clipSavedIndex = 0;
// current states
let readAllRows = false;
let stats = {};
// read and write streams for TSV data
const tsvStream = csv.format(TSV_OPTIONS);
tsvStream.pipe(fs.createWriteStream(path.join(releaseName, 'clips.tsv')));
return new Promise((resolve) => {
// cleanUp function to be run at the end of every row to see if everything
// has been completed
const cleanUp = () => {
if (
readAllRows &&
activeBucketConnections === 0 &&
activeWriteStreams === 0
) {
console.log('');
tsvStream.end();
// write errors to disk
fs.writeFileSync(
path.join(__dirname, releaseName, 'errors.json'),
JSON.stringify(errors),
'utf8',
(err) => {
if (err) throw err;
}
);
// format stats and return to main run function
resolve(formatFinalClipsStats(releaseName, stats));
}
};
// Helper function to pause and restart stream depending on
// how many active connections there are, to prevent running out of memory
const updateDbStatus = () => {
if (activeBucketConnections > 50 || activeWriteStreams > 50) {
db.pause();
}
if (activeBucketConnections < 25 && activeWriteStreams < 25) {
db.resume();
}
cleanUp();
};
// Helper function to write current row to master TSV file
const appendToTsv = (row, filePath) => {
activeWriteStreams++;
updateDbStatus();
tsvStream.write(
{
...row,
sentence: row.sentence.replace(/\s/gi, ' '),
client_id: config.get('skipHashing')
? row.client_id
: hashId(row.client_id),
path: filePath,
},
() => {
activeWriteStreams--;
updateDbStatus();
}
);
};
// Helper function to render current progress
const renderProgress = () => {
process.stdout.write(
`${rowIndex} rows processed, ${clipSavedIndex} downloaded\r`
);
};
// Helper function to download a file
const downloadClipFile = (clipPath) => {
activeBucketConnections++;
updateDbStatus();
return clipBucket.bucket.getObject({
Bucket: clipBucket.name,
Key: clipPath,
});
};
// Helper function to get filesize metadata for function
const getMetadata = async (row) => {
activeBucketConnections++;
updateDbStatus();
return clipBucket.bucket
.headObject({ Key: row.path, Bucket: clipBucket.name })
.promise()
.then((res) => res.ContentLength)
.catch((err) => {
throw err;
})
.finally(() => {
activeBucketConnections--;
updateDbStatus();
});
};
let queryParameters = [];
//pass two dates for delta releases
if (config.get('startCutoffTime')) {
queryParameters = [
config.get('startCutoffTime'),
config.get('cutoffTime'),
];
} else {
queryParameters = [config.get('cutoffTime')];
}
// Main query for bundling
db.query(fs.readFileSync(queryFile, 'utf-8'), queryParameters)
.on('result', (dbRow) => {
const row = dbRow;
rowIndex++;
renderProgress(rowIndex, clipSavedIndex);
// Scrub demographic info if it's a minority language
if (minorityLangs.includes(row.locale)) {
row.gender = '';
row.age = '';
}
const clipsDir = path.join(releaseName, row.locale, 'clips');
const newPath = `common_voice_${row.locale}_${row.id}.mp3`;
const soundFilePath = path.join(clipsDir, newPath);
// If audio file has previously been downloaded, update stats/TSV immediately
if (
fs.existsSync(soundFilePath) &&
fs.statSync(soundFilePath).size > 0
) {
stats = updateClipStats(stats, row);
appendToTsv(row, newPath);
return;
}
// Get filesize of clip and skip if it's smaller than 256 (blank clips)
getMetadata(row)
.then((metadata) => {
if (metadata <= 256) {
if (errors.tooSmall[row.locale] === undefined) {
errors.tooSmall[row.locale] = [];
}
// If file is too small, append to error object
errors.tooSmall[row.locale].push({
path: row.path,
size: metadata.ContentLength,
});
} else {
// If valid clip, update clipStats and add to TSV
stats = updateClipStats(stats, row);
appendToTsv(row, newPath);
if (config.get('skipDownload')) {
return;
}
// Prepare clips path
mkDirByPathSync(clipsDir);
// Download clip
downloadClipFile(row.path)
.createReadStream()
.pipe(fs.createWriteStream(soundFilePath))
.on('finish', () => {
clipSavedIndex++;
renderProgress(rowIndex, clipSavedIndex);
activeBucketConnections--;
updateDbStatus();
});
}
})
.catch(() => {
// If file does not exist, append to error object
if (errors.notFound[row.locale] === undefined) {
errors.notFound[row.locale] = [];
}
errors.notFound[row.locale].push({
path: row.path,
});
})
.finally(() => {
// Once all promises resolve, perform cleanup and check status
cleanUp();
});
})
.on('end', () => {
// Once db query completes, set status to read and perform cleanup
readAllRows = true;
cleanUp();
});
});
};
module.exports = {
processAndDownloadClips,
};