-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathspeech-api_js.js
64 lines (59 loc) · 1.8 KB
/
speech-api_js.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
const fetch = require('node-fetch');
const util = require('util');
const fs = require('fs');
const KEY = '<GOOGLE API KEY>';
const GOOGLE_STORAGE_BUCKET = 'gs://<BUCKET-PATH>';
const FILES_IN_BUCKET = [
'<FILES-IN-BUCKET>'
];
const getOperations = async (name) => {
const response = await fetch(`https://speech.googleapis.com/v1/operations/${name}?key=${KEY}`);
if (!response.ok) {
throw new Error(await response.text());
}
return await response.json();
};
const startProcessing = async (filename) => {
const url = `https://speech.googleapis.com/v1/speech:longrunningrecognize?key=${KEY}`;
const uri = `${GOOGLE_STORAGE_BUCKET}/${filename}`;
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify({
config: {
enableWordTimeOffsets: true,
enableAutomaticPunctuation: true,
useEnhanced: true,
audioChannelCount: 1,
model: 'video',
languageCode: 'en-US'
},
"audio": {
uri
}
})
});
if (!response.ok) {
throw new Error(await response.text());
}
return await response.json();
};
const processFile = async (filename) => {
const { name } = await startProcessing(filename);
let done = false;
let operation;
while (!done) {
operation = await getOperations(name);
done = operation.done || false;
const progress = operation.metadata.progressPercent;
console.log(`${filename} - ${progress}% waiting ....`);
await new Promise((resolve) => setTimeout(resolve, 2000));
}
console.log(util.inspect(operation, { depth: null, colors: true }));
return { ...operation, filename };
};
const main = async () => {
const promises = FILES_IN_BUCKET.map(processFile);
const operations = await Promise.all(promises);
fs.writeFileSync('data.json', JSON.stringify(operations))
};
main();