-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
231 lines (199 loc) · 6.44 KB
/
app.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
223
224
225
226
227
228
229
230
231
const express = require('express');
const multer = require('multer');
const mongoose = require('mongoose');
const fs = require('fs');
const axios = require('axios');
const path = require('path');
const FormData = require('form-data');
const { execSync: exec } = require('child_process');
const ffmpegStatic = require('ffmpeg-static');
const ffmpegPath = require('ffmpeg-static');
const e = require('express');
const audioFile = path.join(__dirname, '${filePath}.mp3');
const model = 'whisper-1';
require('dotenv').config();
const app = express();
// Configure multer to store files in a folder named 'uploads'
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, file.originalname);
},
});
const upload = multer({ storage: storage });
//connect to mongodb
mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const videoSchema = new mongoose.Schema({
name: String,
path: String,
});
const Video = mongoose.model('Video', videoSchema);
/* Test the database connection
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.info('Database connected');
});
// Serve the index.html file
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});*/
/* test dummy data insertion to mongodb
const video = new Video({
name: 'test',
path: 'test',
});
video.save((err, video) => {
if (err) {
console.error(err);
} else {
console.log(video);
}
}
);*/
// Sync the model with the database
//Video.sync();
// Route to handle file uploading
app.post('/upload', upload.single('video'), (req, res) => {
const file = req.file;
// Create a new video record in the database with the file name and path
const video = new Video({
name: file.originalname,
path: file.path,
});
const audioFile = file.path.replace(/\.[^/.]+$/, '.mp3');
// Check if the MP3 file already exists
if (fs.existsSync(audioFile)) {
// MP3 file already exists, generate a unique filename
const timestamp = Date.now();
const uniqueAudioFile = `${audioFile.replace('.mp3', '')}_${timestamp}.mp3`;
// Convert the video file to an audio file with the unique filename and specify the output codec as MP3
exec(`${ffmpegPath} -i ${file.path} -vn -acodec mp3 ${uniqueAudioFile}`, (error, stdout, stderr) => {
if (error) {
console.error(error);
res.status(500).json({ success: false, error: error.message });
} else {
video.audioFile = uniqueAudioFile;
video.save((err, video) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, error: err.message });
} else {
res.redirect(`/videos/${video._id}`);
}
});
}
});
} else {
// MP3 file does not exist, convert the video to audio with the original filename and specify the output codec as MP3
exec(`${ffmpegPath} -i ${file.path} -vn -acodec mp3 ${audioFile}`, (error, stdout, stderr) => {
if (error) {
console.error(error);
res.status(500).json({ success: false, error: error.message });
} else {
video.audioFile = audioFile;
video.save((err, video) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, error: err.message });
} else {
res.redirect(`/videos/${video._id}`);
}
});
}
});
}
});
// Route for video transcription
app.get('/transcript/:id', (req, res) => {
const id = req.params.id;
// Find the video record in the database by id
Video.findById(id, (err, video) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, error: err.message });
return;
}
if (video) {
const filePath = video.path;
const audioFile = path.join(__dirname, `${filePath}.mp3`);
const model = 'whisper-1';
if (fs.existsSync(audioFile)) {
const formData = new FormData();
formData.append('model', model);
formData.append('file', fs.createReadStream(audioFile));
axios
.post('https://api.openai.com/v1/audio/transcriptions', formData, {
headers: {
Authorization: `Bearer ${process.env.OPENAL_KEY}`,
'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
},
})
.then((transcript) => {
const transcription = transcript.data;
res.send(transcription);
})
.catch((err) => {
console.error(err);
res.status(500).json({ success: false, error: err.message });
});
} else {
res.status(404).json({ success: false, error: 'Audio file does not exist' });
}
} else {
res.status(404).json({ success: false, error: 'Record does not exist' });
}
});
});
// Route for serving the video files
app.get('/videos/:id', (req, res) => {
const id = req.params.id;
// Find the video record in the database by id
Video.findById(id, (err, video) => {
if (err) {
console.error(err);
res.status(500).json({ success: false, error: err.message });
return;
}
if (!video) {
res.status(404).json({ success: false, error: 'Record does not exist' });
return;
}
const filePath = video.path;
const videoFile = path.join(__dirname, filePath);
const stat = fs.statSync(videoFile);
const fileSize = stat.size;
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, '').split('-');
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunkSize = (end - start) + 1;
const file = fs.createReadStream(videoFile, { start, end });
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunkSize,
'Content-Type': 'video/mp4',
};
res.writeHead(206, head);
file.pipe(res);
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4',
};
res.writeHead(200, head);
fs.createReadStream(videoFile).pipe(res);
}
});
});
// Start the server
app.listen(process.env.PORT, () => {
console.log('Server running');
});