-
Notifications
You must be signed in to change notification settings - Fork 0
/
deepgram.js
221 lines (208 loc) · 8.5 KB
/
deepgram.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
#!/usr/bin/env node
/*!
** deepgram-cli -- Convert Voice to Text with Deepgram API
** Copyright (c) 2023-2024 Dr. Ralf S. Engelschall <rse@engelschall.com>
** Licensed under MIT Open Source license.
*/
/* internal requirements */
const fs = require("node:fs")
/* external requirements */
const dotenv = require("dotenv")
const yargs = require("yargs")
const chalk = require("chalk")
const tmp = require("tmp")
const Deepgram = require("@deepgram/sdk")
const DeepL = require("deepl-node")
const mimeTypes = require("mime-types")
const getStream = require("get-stream")
/* act in an asynchronous context */
;(async () => {
/* load environment variables */
dotenv.config()
/* command-line option parsing */
const argv = yargs
/* eslint indent: off */
.usage("Usage: $0 " +
"[-h|--help] " +
"[-v|--verbose] " +
"[-o|--output <output-file>] " +
"[-f|--format <output-format>] " +
"[-l|--language <input-language>] " +
"[-t|--translate <output-language>] " +
"[-M|--model <deepgram-model>] " +
"[-T|--tier <deepgram-tier>] " +
"[-O|--options <deepgram-options>] " +
"<input-file>"
)
.help("h").alias("h", "help").default("h", false)
.describe("h", "show usage help")
.boolean("v").alias("v", "verbose").default("v", false)
.describe("v", "print verbose messages")
.string("o").nargs("o", 1).alias("o", "output").default("o", "-")
.describe("o", "output file")
.string("f").nargs("f", 1).alias("f", "format").default("f", "txt")
.describe("f", "output format (\"txt\", \"vtt+\", \"vtt\" or \"srt\")")
.string("l").nargs("l", 1).alias("l", "language").default("l", "auto")
.describe("l", "input language (\"auto\", \"en-US\", \"de\", etc.)")
.string("t").nargs("t", 1).alias("t", "translate").default("t", "none")
.describe("t", "translation language (\"none\", \"en\", \"de\", etc.)")
.string("M").nargs("M", 1).alias("M", "model").default("M", "general")
.describe("M", "conversion model (\"global\", etc)")
.string("T").nargs("T", 1).alias("T", "tier").default("T", "nova")
.describe("T", "conversion tier (\"nova\", etc)")
.string("O").nargs("O", 1).alias("O", "options").default("O", "")
.describe("O", "conversion options (\"sentiment=true\", etc)")
.version(false)
.strict()
.showHelpOnFail(true)
.demand(1)
.parse(process.argv.slice(2))
/* verbose message printing */
const verbose = (msg) => {
if (argv.verbose)
process.stderr.write(`${msg}\n`)
}
/* sanity check input */
if (argv._.length !== 1)
throw new Error("require input file")
/* instantiate Deepgram API SDK */
const deepgramApiKey = process.env.DEEPGRAM_API_KEY ?? ""
if (deepgramApiKey === "")
throw new Error("require Deepgram API key (via \$DEEPGRAM_API_KEY environment variable)")
const deepgram = Deepgram.createClient(deepgramApiKey)
/* instantiate DeepL API SDK (optional) */
let translator = null
if (argv.translate !== "none") {
const deeplApiKey = process.env.DEEPL_API_KEY ?? ""
if (deeplApiKey === "")
throw new Error("require DeepL API key (via \$DEEPL_API_KEY environment variable)")
translator = new DeepL.Translator(deeplApiKey)
}
/* determine conversion source */
verbose("++ reading input")
const source = {}
if (argv._[0].match(/^https?:\/\/.+$/)) {
verbose(`-- remote input: URL (${chalk.blue(argv._[0])})`)
source.url = argv._[0]
}
else if (argv._[0] === "-") {
verbose(`-- local input: stdin`)
const buffer = await getStream.buffer(process.stdin)
source.buffer = buffer
}
else {
verbose(`-- local input: file (${chalk.blue(argv._[0])})`)
const buffer = await fs.promises.readFile(argv._[0], { encoding: null })
source.buffer = buffer
}
/* determine conversion options */
const options = {
model: argv.model,
tier: argv.tier,
punctuate: true,
utterances: true
}
if (argv.language === "auto")
options.detect_language = true
else
options.language = argv.language
if (argv.options !== "") {
for (const option of argv.options.split(/,/)) {
let m
if ((m = option.match(/^(\S+)=(\S+)$/)) === null)
throw new Error("invalid option specification")
let [ , key, val ] = m
if (val === "true") val = true
else if (val === "false") val = false
else if (val.match(/^\d+$/)) val = parseInt(val)
else if (val.match(/^(?:\d*\.\d+|\d+\.\d*)$/)) val = parseFloat(val)
options[key] = val
}
}
for (const [ key, val ] of Object.entries(options))
verbose(`-- conversion ${key}: ${chalk.blue(val)}`)
/* call Deepgram API */
verbose(`++ calling ${chalk.bold("Deepgram API")}`)
const { result, error } = await (source.url ?
deepgram.listen.prerecorded.transcribeUrl(source.url, options) :
deepgram.listen.prerecorded.transcribeFile(source.buffer, options))
if (error)
throw new Error(`transcription failed: ${error}`)
/* generate output */
verbose("++ writing output")
verbose(`-- output file: ${chalk.blue(argv.output)}`)
verbose(`-- output format: ${chalk.blue(argv.format)}`)
let output = ""
const makeTime = (time) =>
new Date(time * 1000).toISOString().substr(11, 12)
const translate = async (text) => {
const result = await translator.translateText(text, argv.language.replace(/-.+$/, ""), argv.translate, {
splitSentences: "off"
})
return (result?.text ?? text)
}
if (argv.format === "txt") {
for (let i = 0; i < result.results.utterances.length; i++) {
const utterance = result.results.utterances[i]
let text = utterance.transcript
if (argv.translate !== "none")
text = await translate(text)
output += `${text}\n`
}
}
else if (argv.format === "vtt+") {
if (argv.translate !== "none")
throw new Error("sorry, VTT+ is not supported in combination with translation")
output += "WEBVTT\n\n"
let i = 1
for (const utterance of result.results.utterances) {
let transcript = utterance.transcript.split(/\s+/)
let j = 0
for (const word of utterance.words) {
const start = makeTime(word.start)
const end = makeTime(word.end)
output += `${i++}\n`
output += `${start} --> ${end}\n`
const text = [ ...transcript ]
text[j] = `<b>${text[j]}</b>`
output += `${text.join(" ")}\n\n`
j++
}
}
}
else if (argv.format === "vtt") {
output += "WEBVTT\n\n"
for (let i = 0; i < result.results.utterances.length; i++) {
const utterance = result.results.utterances[i]
const start = makeTime(utterance.start)
const end = makeTime(utterance.end)
let text = utterance.transcript
if (argv.translate !== "none")
text = await translate(text)
output += `${i + 1}\n`
output += `${start} --> ${end}\n`
output += `${text}\n\n`
}
}
else if (argv.format === "srt") {
for (let i = 0; i < result.results.utterances.length; i++) {
const utterance = result.results.utterances[i]
const start = makeTime(utterance.start).replace(".", ",")
const end = makeTime(utterance.end).replace(".", ",")
let text = utterance.transcript
if (argv.translate !== "none")
text = await translate(text)
output += `${i + 1}\n`
output += `${start} --> ${end}\n`
output += `${text}\n\n`
}
}
if (argv.output === "-")
process.stdout.write(output)
else
await fs.promises.writeFile(argv.output, output, { encoding: "utf8" })
})().catch((err) => {
/* report error */
process.stderr.write(chalk.red(`deepgram: ERROR: ${err}\n`))
process.exit(1)
})