-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
126 lines (104 loc) · 3.39 KB
/
server.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
require('dotenv').config();
const express = require("express");
const multer = require("multer");
const fsPromises = require("fs").promises; // For async file operations
const fs = require("fs");
const { exec } = require("child_process");
const { Configuration, OpenAIApi } = require("openai");
const bodyParser = require('body-parser');
const basicAuth = require('express-basic-auth');
const uuidv4 = require('uuid').v4; // Import UUID library to generate unique IDs
// Read data from .env file
let apiKey = process.env.OPENAI_KEY;
const deploy_env = process.env.DEPLOY_ENV || 'local';
const username = process.env.BASIC_AUTH_USERNAME;
const password = process.env.BASIC_AUTH_PASSWORD;
let openai;
function updateOpenAIConfiguration(key) {
const configuration = new Configuration({
apiKey: key,
});
openai = new OpenAIApi(configuration);
}
// Initialize OpenAI API
updateOpenAIConfiguration(apiKey);
const app = express();
// Basic Authentication
if (deploy_env !== 'local') {
app.use(basicAuth({
users: { [username]: password },
challenge: true,
realm: 'Transcriber',
}));
}
// Parse JSON request body
app.use(bodyParser.json());
// Serve static files from the "public" directory
app.use(express.static("public"));
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
async function transcribeAudio(filename) {
try {
const transcript = await openai.createTranscription(
fs.createReadStream(filename),
"whisper-1"
);
return transcript.data.text;
} catch (error) {
console.error(`Error while transcribing audio file: ${error.message}`);
throw error;
}
}
async function translateAudio(filename) {
try {
const transcript = await openai.createTranslation(
fs.createReadStream(filename),
"whisper-1"
);
return transcript.data.text;
} catch (error) {
console.error(`Error while transcribing audio file: ${error.message}`);
throw error;
}
}
app.post("/transcribe", upload.single("audio"), async (req, res) => {
const audioFilename = `files/${uuidv4()}.wav`;
fsPromises
.writeFile(audioFilename, req.file.buffer)
.then(async () => {
let responseText;
const translate = req.body.translate;
if (translate === "true") {
try {
responseText = await translateAudio(audioFilename);
} catch (error) {
console.error("Error translating text:", error);
// In case of translation error, you can choose to use the original transcription or return an error message
responseText = "Translation failed";
}
} else {
responseText = await transcribeAudio(audioFilename);
}
res.send(responseText); // Send the response text back to the client
// Delete the audio file after processing
fsPromises.unlink(audioFilename).catch((err) => {
console.error("Error deleting file:", err);
});
})
.catch((err) => {
console.error("Error writing file:", err);
res.status(500).send("Server error");
});
});
app.get("/checkEnv", async (req, res) => {
try {
await fsPromises.access('.env');
res.sendStatus(200); // File exist, send status code 200
} catch (error) {
res.sendStatus(404); // File not found, send status code 404
}
});
app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
exec('start "" /b http://localhost:3000');
});