-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·223 lines (205 loc) · 7.18 KB
/
index.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
import express from 'express';
import bodyParser from 'body-parser'
import _ from 'lodash';
import fs from 'fs';
import {Server} from 'http'
import textToSpeech from '@google-cloud/text-to-speech'
import speech from '@google-cloud/speech'
import webpack from 'webpack'
import webpackConfig from '../webpack.config'
import WebpackMiddleware from 'webpack-dev-middleware'
import WebpackHotMiddleware from 'webpack-hot-middleware'
import opus from 'node-opus'
import ogg from 'ogg'
import wav from 'wav'
import ffmpeg from 'fluent-ffmpeg'
import * as MSTTS from './ms-tts'
import * as GoogleTranslate from './google-translate'
import * as Forms from './forms'
import * as Unsplash from './unsplash'
//import Signaling from './signaling'
const options = {
key: fs.readFileSync('./server/ssl/server.key'),
cert: fs.readFileSync('./server/ssl/server.crt')
};
const app = express();
//const server = require('https').Server(options, app);
const server = Server(app);
/*
const signaling = new Signaling(io);
signaling.init(); */
app.use(express.static('public'));
const compiler = webpack(webpackConfig);
app.use(
WebpackMiddleware(compiler, {
publicPath: webpackConfig.output.publicPath
})
);
app.use(WebpackHotMiddleware(compiler));
app.use(bodyParser.json());
app.get('/api/google-speak',(req, res) => {
const client = new textToSpeech.TextToSpeechClient();
if (!req.query.text) {
res.send(500,"Invalid request");
return;
}
const request = {
input: {text: req.query.text},
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
audioConfig: {audioEncoding: 'MP3'},
};
// Performs the Text-to-Speech request
client.synthesizeSpeech(request, (err, response) => {
if (err) {
console.log(err);
res.send(500,err.toString());
return;
}
res.set('Content-Type', 'audio/mpeg');
res.send(response.audioContent);
});
});
app.get('/api/ms-speak', async (req, res) => {
try {
if (!req.query.text) {
res.send(500,"Invalid request");
return;
}
const googleTarget = req.query.target ? req.query.target.split("-")[0] : null;
let text = googleTarget ? await GoogleTranslate.translate(req.query.text, googleTarget) : req.query.text;
console.log("Text ", text);
let {bodyStream, headers} = await MSTTS.getSpeech(text, req.query.target);
console.log("Response headers", headers);
res.type("audio/mpeg");
bodyStream.pipe(res);
}
catch (e) {
console.log("Error", e);
res.send("Error " + e);
}
});
app.get('/api/stream', async (req, res) => {
try {
res.type("audio/mpeg");
fs.createReadStream("public/test/web-audio-speech.mpga").pipe(res);
}
catch (e) {
console.log("Error", e);
res.send("Error " + e);
}
});
app.post('/transcribe', async function(req, res) {
try {
if (!req.query.model) {
res.send(500,"Invalid request");
return;
}
//const file = fs.createReadStream(await Forms.getFile(req,'audio'));
//
const opusDecodeStream = new opus.Decoder(48000, 2, 4800);
const oggDecode = new ogg.Decoder();
oggDecode.on('stream', function (stream) {
let bufs = [];
console.log("Got OGG stream");
stream._readableState.highWaterMark = 1;
opusDecodeStream.on('format', function (format) {
console.log("Raw format:",format);
const outputWavStream = new wav.Writer({
sampleRate: format.sampleRate,
channels: format.channels
});
//outputWavStream.setEncoding('base64');
opusDecodeStream.pipe(outputWavStream);
outputWavStream.on('data', (chunk) => {
bufs.push(chunk);
})
});
opusDecodeStream.on('end', function (e) {
console.log("Finished writing!");
const waveBuffer = Buffer.concat(bufs);
const base64Wave = waveBuffer.toString('base64');
const client = new speech.SpeechClient();
const audio = {
content: base64Wave,
};
const config = {
enoding: 'LINEAR16',
languageCode: req.query.model,
audioChannelCount: 2
};
const request = {
audio: audio,
config: config,
};
client
.recognize(request)
.then(async data => {
const response = data[0];
console.log(data);
const transcription = response.results
.map(result => result.alternatives[0].transcript)
.join('\n');
console.log(`Transcription: ${transcription}`);
let returnData = {
"status": "success",
"transcription": transcription
};
if (req.query.translate && req.query.translate.length > 0) {
let translation = await GoogleTranslate.translate(transcription, req.query.translate);
console.log(`Translation: ${translation}`);
returnData.translation = translation;
}
res.send(returnData);
})
.catch(err => {
console.error('ERROR:', err);
res.status(500).send({status: "error", error: err.toString()});
});
});
opusDecodeStream.on('error', function (err) {
console.log("Error decoding opus", err);
res.status(500).send({status: "error", error: "Error decoding opus: " + err.toString()});
});
stream.pipe(opusDecodeStream);
});
oggDecode.on('error', function (err) {
console.log("Error decoding ogg", err);
res.status(500).send({status: "error", error: "Error decoding ogg: " + err.toString()});
});
const fileName = await Forms.getFile(req,'audio');
ffmpeg(fileName)
.format('ogg')
.audioCodec('copy')
.output(oggDecode)
.on('error', function(err, stdout, stderr) {
console.log('Error decoding recording:' + err.message);
res.status(500).send({status: "error", error: "Error decoding recording: " + err.message});
})
.on('start', function(commandLine) {
console.log('Spawned Ffmpeg with command: ' + commandLine);
})
.run();
}
catch (err) {
console.log(err);
res.status(500).send({status: "error", error: err.toString()})
}
})
app.get('/api/random-image', async (req, res) => {
try {
if (!req.query.seed || !req.query.id) {
res.send(500,"Invalid request");
return;
}
let {bodyStream, headers} = await Unsplash.getRandomImage(req.query.seed, req.query.id);
res.type(headers.get('content-type'));
bodyStream.pipe(res);
}
catch (e) {
console.log("Error", e);
res.send("Error " + e);
}
});
server.listen(3080, () => {
console.log('listening on port 3080!');
});