import { Router, Request, Response } from 'express';
import multer from 'multer';
import path from 'path';
import { z } from 'zod';
import config from '../config';
import { transcriptionService } from '../services/transcriptionService';
import { languageService } from '../services/languageService';
const router = Router();
// Configure multer for file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'tmp/uploads/');
},
filename: (req, file, cb) => {
const uniqueSuffix = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
cb(null, `${uniqueSuffix}${path.extname(file.originalname)}`);
},
});
const fileFilter = (req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
const allowedFormats = config.upload.allowedAudioFormats;
const fileExtension = path.extname(file.originalname).toLowerCase().substring(1);
if (allowedFormats.includes(fileExtension)) {
cb(null, true);
} else {
cb(new Error(`Invalid file format. Allowed formats: ${allowedFormats.join(', ')}`));
}
};
const upload = multer({
storage,
fileFilter,
limits: {
fileSize: config.upload.maxFileSizeMB * 1024 * 1024, // Convert MB to bytes
},
});
// Schema for query parameters
const uploadSchema = z.object({
language: z.string().min(2).max(10).optional(),
});
router.post('/upload-voice', upload.single('audio'), async (req: Request, res: Response) => {
try {
if (!req.file) {
return res.status(400).json({
success: false,
error: 'No audio file provided',
});
}
// Detect language from audio
const detectedLanguage = await languageService.detectFromAudio(
req.file.path,
req.sessionId || 'default'
);
// Transcribe the audio file using detected language
const result = await transcriptionService.transcribeAudio(
req.file.path,
detectedLanguage.code
);
res.json({
success: true,
...result,
detectedLanguage,
});
} catch (error) {
if (error instanceof multer.MulterError) {
return res.status(400).json({
success: false,
error: 'File upload error',
details: error.message,
});
}
console.error('Error processing voice upload:', error);
res.status(500).json({
success: false,
error: 'Failed to process voice upload',
});
}
});
export default router;