Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
397 lines (348 loc) · 12.3 KB
/
Copy pathserver.js
File metadata and controls
397 lines (348 loc) · 12.3 KB
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/**
* Node Transcription Starter - Backend Server
*
* This is a simple Express server that provides a transcription API endpoint
* powered by Deepgram's Speech-to-Text service. It's designed to be easily
* modified and extended for your own projects.
*
* Key Features:
* - Single API endpoint: POST /api/transcription
* - Accepts both file uploads and URLs
* - CORS enabled for frontend communication
* - JWT session auth with rate limiting (production only)
* - Pure API server (frontend served separately)
*/
require("dotenv").config();
const { DeepgramClient } = require("@deepgram/sdk");
const cors = require("cors");
const crypto = require("crypto");
const express = require("express");
const fs = require("fs");
const jwt = require("jsonwebtoken");
const multer = require("multer");
const path = require("path");
// ============================================================================
// CONFIGURATION - Customize these values for your needs
// ============================================================================
/**
* Default transcription model to use when none is specified
* Options: "nova-3", "nova-2", "nova", "enhanced", "base"
* See: https://developers.deepgram.com/docs/models-languages-overview
*/
const DEFAULT_MODEL = "nova-3";
/**
* Server configuration - These can be overridden via environment variables
*/
const CONFIG = {
port: process.env.PORT || 8081,
host: process.env.HOST || "0.0.0.0",
};
// ============================================================================
// SESSION AUTH - JWT tokens for production security
// ============================================================================
/**
* Session secret for signing JWTs.
*/
const SESSION_SECRET =
process.env.SESSION_SECRET || crypto.randomBytes(32).toString("hex");
/** JWT expiry time (1 hour) */
const JWT_EXPIRY = "1h";
/**
* Express middleware that validates JWT from Authorization header.
* Returns 401 with JSON error if token is missing or invalid.
*/
function requireSession(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return res.status(401).json({
error: {
type: "AuthenticationError",
code: "MISSING_TOKEN",
message: "Authorization header with Bearer token is required",
},
});
}
try {
const token = authHeader.slice(7);
jwt.verify(token, SESSION_SECRET);
next();
} catch (err) {
return res.status(401).json({
error: {
type: "AuthenticationError",
code: "INVALID_TOKEN",
message:
err.name === "TokenExpiredError"
? "Session expired, please refresh the page"
: "Invalid session token",
},
});
}
}
// ============================================================================
// API KEY LOADING - Load Deepgram API key from .env or config.json
// ============================================================================
/**
* Loads the Deepgram API key from environment variables or config.json
* Priority: DEEPGRAM_API_KEY env var > config.json > error
*/
function loadApiKey() {
// Try environment variable first (recommended)
let apiKey = process.env.DEEPGRAM_API_KEY;
// Fall back to config.json if it exists
if (!apiKey) {
try {
const config = require("./config.json");
apiKey = config.dgKey;
} catch (err) {
// config.json doesn't exist or is invalid - that's ok
}
}
// Exit with helpful error if no API key found
if (!apiKey) {
console.error("\n❌ ERROR: Deepgram API key not found!\n");
console.error("Please set your API key using one of these methods:\n");
console.error("1. Create a .env file (recommended):");
console.error(" DEEPGRAM_API_KEY=your_api_key_here\n");
console.error("2. Environment variable:");
console.error(" export DEEPGRAM_API_KEY=your_api_key_here\n");
console.error("3. Create a config.json file:");
console.error(" cp config.json.example config.json");
console.error(" # Then edit config.json with your API key\n");
console.error("Get your API key at: https://console.deepgram.com\n");
process.exit(1);
}
return apiKey;
}
const apiKey = loadApiKey();
// ============================================================================
// SETUP - Initialize Express, Deepgram, and middleware
// ============================================================================
// Initialize Deepgram client. The override is for self-hosted deployments and
// local compatibility tests; production continues to use the SDK default.
const deepgramOptions = { apiKey };
const deepgramBaseUrl = process.env.DEEPGRAM_BASE_URL;
if (deepgramBaseUrl) {
let parsedBaseUrl;
try {
parsedBaseUrl = new URL(deepgramBaseUrl);
} catch {
console.error("DEEPGRAM_BASE_URL must be a valid HTTP(S) URL");
process.exit(1);
}
if (!["http:", "https:"].includes(parsedBaseUrl.protocol)) {
console.error("DEEPGRAM_BASE_URL must use HTTP or HTTPS");
process.exit(1);
}
deepgramOptions.baseUrl = deepgramBaseUrl;
}
const deepgram = new DeepgramClient(deepgramOptions);
// Configure Multer for file uploads (stores files in memory)
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
// Initialize Express app
const app = express();
// Enable CORS (wildcard is safe -- same-origin via Vite proxy / Caddy in production)
app.use(cors());
// ============================================================================
// HELPER FUNCTIONS - Modular logic for easier understanding and testing
// ============================================================================
/**
* Validates that either a file or URL was provided in the request
* @param {Object} file - Multer file object
* @param {string} url - URL string from request body
* @returns {Object|null} - Request object for Deepgram, or null if invalid
*/
function validateTranscriptionInput(file, url) {
// URL-based transcription
if (url) {
return { url };
}
// File-based transcription
if (file) {
return { buffer: file.buffer, mimetype: file.mimetype };
}
// Neither provided
return null;
}
/**
* Sends a transcription request to Deepgram
* @param {Object} dgRequest - Request object with url OR buffer+mimetype
* @param {string} model - Model name to use (e.g., "nova-3")
* @returns {Promise<Object>} - Deepgram API response
*/
async function transcribeAudio(dgRequest, model = DEFAULT_MODEL) {
// URL transcription
if (dgRequest.url) {
return await deepgram.listen.v1.media.transcribeUrl({
url: dgRequest.url,
model,
});
}
// File transcription. The uploaded file's MIME type must travel on the
// uploadable (Content-Type header) — the request-options object has no
// `mimetype` field in v5, so passing it there would be silently dropped.
return await deepgram.listen.v1.media.transcribeFile(
{ data: dgRequest.buffer, contentType: dgRequest.mimetype },
{ model }
);
}
/**
* Formats Deepgram's response into a simplified, consistent structure
* This is where you'd customize the response format for your application
*
* @param {Object} transcriptionResponse - Raw Deepgram API response
* @param {string} modelName - Name of model used for transcription
* @returns {Object} - Formatted response object
*/
function formatTranscriptionResponse(transcriptionResponse, modelName) {
// v5 returns the transcription data directly (v4 wrapped it in `.result`).
const transcription = transcriptionResponse;
const result = transcription?.results?.channels?.[0]?.alternatives?.[0];
if (!result) {
throw new Error("No transcription results returned from Deepgram");
}
// Build response object
const response = {
transcript: result.transcript || "",
words: result.words || [],
metadata: {
model_uuid: transcription.metadata?.model_uuid,
request_id: transcription.metadata?.request_id,
model_name: modelName,
},
};
// Add optional fields if available
if (transcription.metadata?.duration) {
response.duration = transcription.metadata.duration;
}
return response;
}
/**
* Formats error responses in a consistent structure
* @param {Error} error - The error that occurred
* @param {number} statusCode - HTTP status code to return
* @returns {Object} - Formatted error response
*/
function formatErrorResponse(error, statusCode = 500) {
return {
statusCode,
body: {
error: {
type: statusCode === 400 ? "ValidationError" : "TranscriptionError",
code: statusCode === 400 ? "MISSING_INPUT" : "TRANSCRIPTION_FAILED",
message: error.message || "An error occurred during transcription",
details: {
originalError: error.toString(),
},
},
},
};
}
// ============================================================================
// SESSION ROUTES - Auth endpoints (unprotected)
// ============================================================================
/**
* GET /api/session — Issues a signed JWT for session authentication.
*/
app.get("/api/session", (req, res) => {
const token = jwt.sign(
{ iat: Math.floor(Date.now() / 1000) },
SESSION_SECRET,
{ expiresIn: JWT_EXPIRY }
);
res.json({ token });
});
// ============================================================================
// API ROUTES - Define your API endpoints here
// ============================================================================
/**
* POST /api/transcription
*
* Main transcription endpoint. Accepts either:
* - A file upload (multipart/form-data with 'file' field)
* - A URL to audio file (form data with 'url' field)
*
* Optional parameters:
* - model: Deepgram model to use (default: "nova-3")
*
* Protected by JWT session auth (requireSession middleware).
*/
app.post("/api/transcription", requireSession, upload.single("file"), async (req, res) => {
try {
const { body, file } = req;
const { url, model } = body;
// Validate input - must have either file or URL
const dgRequest = validateTranscriptionInput(file, url);
if (!dgRequest) {
const errorResponse = formatErrorResponse(
new Error("Either file or url must be provided"),
400
);
return res.status(errorResponse.statusCode).json(errorResponse.body);
}
// Send transcription request to Deepgram
const transcriptionResponse = await transcribeAudio(
dgRequest,
model || DEFAULT_MODEL
);
// Format and return response
const response = formatTranscriptionResponse(
transcriptionResponse,
model || DEFAULT_MODEL
);
res.json(response);
} catch (err) {
console.error("Transcription error:", err);
// Return formatted error response
const errorResponse = formatErrorResponse(err);
res.status(errorResponse.statusCode).json(errorResponse.body);
}
});
/**
* GET /api/metadata
*
* Returns metadata about this starter application from deepgram.toml
* Required for standardization compliance
*/
app.get("/api/metadata", (req, res) => {
try {
const toml = require("toml");
const tomlPath = path.join(__dirname, "deepgram.toml");
const tomlContent = fs.readFileSync(tomlPath, "utf-8");
const config = toml.parse(tomlContent);
if (!config.meta) {
return res.status(500).json({
error: "INTERNAL_SERVER_ERROR",
message: "Missing [meta] section in deepgram.toml",
});
}
res.json(config.meta);
} catch (error) {
console.error("Error reading metadata:", error);
res.status(500).json({
error: "INTERNAL_SERVER_ERROR",
message: "Failed to read metadata from deepgram.toml",
});
}
});
/**
* ADD YOUR CUSTOM ROUTES HERE
*
* Examples:
* - POST /stt/transcribe-with-diarization
* - POST /stt/summarize
* - GET /health (health check endpoint)
* - POST /webhooks/deepgram (callback endpoint)
*/
// ============================================================================
// SERVER START
// ============================================================================
app.listen(CONFIG.port, CONFIG.host, () => {
console.log("\n" + "=".repeat(70));
console.log(`🚀 Backend API running at http://localhost:${CONFIG.port}`);
console.log(`📡 GET /api/session`);
console.log(`📡 POST /api/transcription (auth required)`);
console.log(`📡 GET /api/metadata`);
console.log("=".repeat(70) + "\n");
});