-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
194 lines (156 loc) · 4.97 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
require("dotenv").config()
const express = require("express")
const bodyParser = require("body-parser")
const Vonage = require("@vonage/server-sdk")
const AWS = require("aws-sdk")
const shortid = require("shortid")
const fs = require("fs")
const options = {
appendToUserAgent: "amazon-transcribe-call/1.0.0",
}
const vonage = new Vonage({
apiKey: "not_used", // Voice applications don't use API key or secret
apiSecret: "not_used",
applicationId: process.env.VONAGE_APPLICATION_ID,
privateKey: __dirname + "/" + process.env.VONAGE_PRIVATE_KEY_FILE
})
AWS.config.update({
region: process.env.AWS_REGION,
accessKeyId: process.env.AWS_KEY,
secretAccessKey: process.env.AWS_SECRET
})
const app = express()
app.use(bodyParser.json())
const transcribeService = new AWS.TranscribeService()
const S3 = new AWS.S3()
app.get('/webhooks/answer', (req, res) => {
return res.json([
{
action: 'talk',
text: 'Thanks for calling, we will connect you now'
},
{
action: 'connect',
endpoint: [{
type: 'phone',
number: process.env.OTHER_PHONE_NUMBER
}]
},
{
action: 'record',
eventUrl: [`${req.protocol}://${req.get('host')}/webhooks/recording`],
split: 'conversation',
channels: 2,
format: 'mp3'
}
])
})
app.post('/webhooks/events', (req, res) => {
console.log(req.body)
return res.status(204).send("")
})
app.post('/webhooks/recording', (req, res) => {
let audioFileName = `vonage-${shortid.generate()}.mp3`
//let audioFileLocalPath = `./recordings/${audioFileName}`
let audioFileLocalPath = `./recordings/${audioFileName}`
console.log("recording...")
console.log(req.body)
vonage.files.save(req.body.recording_url, audioFileLocalPath, (err, res) => {
if (err) {
console.log("Could not save audio file")
console.error(err)
}
else {
uploadFile(audioFileLocalPath, audioFileName)
}
})
return res.status(204).send("")
})
// When transcribe job complete, lambda makes a POST request to this endpoint
app.post('/webhooks/transcription', (req, res) => {
const jobname = req.body.detail.TranscriptionJobName
const jobstatus = req.body.detail.TranscriptionJobStatus
if (jobstatus === "FAILED") {
console.log(`Error processing job ${jobname}`)
} else {
console.log(`${jobname} job successful`)
const params = {
TranscriptionJobName: jobname
}
console.log(`Getting transcription job: ${params.TranscriptionJobName}`)
transcribeService.getTranscriptionJob(params, (err, data) => {
if (err) {
console.log(err, err.stack)
}
else {
console.log("Retrieved transcript")
downloadFile(data.TranscriptionJob.TranscriptionJobName + '.json')
}
})
}
return res.status(200).send("")
})
function displayResults(transcriptJson) {
const channels = transcriptJson.results.channel_labels.channels
channels.forEach((channel) => {
console.log(`*** Channel: ${channel.channel_label}`)
let words = ''
channel.items.forEach((item) => {
words += item.alternatives[0].content + ' '
})
console.log(words)
})
}
function uploadFile(localPath, fileName) {
fs.readFile(localPath, (err, data) => {
if (err) { throw err }
const uploadParams = {
Bucket: process.env.S3_AUDIO_BUCKET_NAME,
Key: fileName,
Body: data
}
const putObjectPromise = S3.putObject(uploadParams).promise()
putObjectPromise.then((data) => {
console.log(`${fileName} uploaded to ${process.env.S3_AUDIO_BUCKET_NAME} bucket`)
transcribeRecording({
audioFileUri: process.env.S3_PATH + '/' + process.env.S3_AUDIO_BUCKET_NAME + '/' + fileName,
transcriptFileName: `transcript-${fileName}`
})
})
})
}
function transcribeRecording(params) {
const jobParams = {
LanguageCode: 'en-GB',
Media: {
MediaFileUri: params.audioFileUri
},
MediaFormat: 'mp3',
OutputBucketName: process.env.S3_TRANSCRIPTS_BUCKET_NAME,
Settings: {
ChannelIdentification: true
},
TranscriptionJobName: params.transcriptFileName
}
console.log(`Submitting file ${jobParams.Media.MediaFileUri} for transcription...`)
const startTranscriptionJobPromise = transcribeService.startTranscriptionJob(jobParams).promise()
startTranscriptionJobPromise.then((data) => {
console.log(`Started transcription job ${data.TranscriptionJob.TranscriptionJobName}...`)
})
}
function downloadFile(key) {
console.log(`downloading ${key}`)
const filePath = `./transcripts/${key}`
const params = {
Bucket: process.env.S3_TRANSCRIPTS_BUCKET_NAME,
Key: key
}
const getObjectPromise = S3.getObject(params).promise()
getObjectPromise.then((data) => {
fs.writeFileSync(filePath, data.Body.toString())
console.log(`Transcript: ${filePath} has been created.`)
let transcriptJson = JSON.parse(fs.readFileSync(filePath, 'utf-8'))
displayResults(transcriptJson)
})
}
app.listen(3000, () => console.log("Waiting for an inbound call..."))