Update route.js
This commit is contained in:
@@ -1,9 +1,9 @@
|
|||||||
import fs, {unlinkSync, existsSync } from 'fs';
|
import fs, { unlinkSync, existsSync } from "fs";
|
||||||
import path from 'path';
|
import path from "path";
|
||||||
import { config } from 'dotenv';
|
import { config } from "dotenv";
|
||||||
import formidable from 'formidable';
|
import formidable from "formidable";
|
||||||
import { AxiosError } from 'axios';
|
import { AxiosError } from "axios";
|
||||||
import OpenAI from 'openai';
|
import OpenAI from "openai";
|
||||||
|
|
||||||
// Load environment variables
|
// Load environment variables
|
||||||
config();
|
config();
|
||||||
@@ -11,7 +11,7 @@ config();
|
|||||||
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
|
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
|
||||||
|
|
||||||
if (!OPENAI_API_KEY) {
|
if (!OPENAI_API_KEY) {
|
||||||
throw new Error('OpenAI API key is missing. Set OPENAI_API_KEY in your .env.local file.');
|
throw new Error("OpenAI API key is missing. Set OPENAI_API_KEY in your .env.local file.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize OpenAI client
|
// Initialize OpenAI client
|
||||||
@@ -22,25 +22,18 @@ const openaiClient = new OpenAI({
|
|||||||
// Helper to parse multipart form data
|
// Helper to parse multipart form data
|
||||||
async function parseMultipartForm(req) {
|
async function parseMultipartForm(req) {
|
||||||
const form = formidable({
|
const form = formidable({
|
||||||
multiples: false, // Single file upload
|
multiples: false,
|
||||||
uploadDir: '/tmp', // Temporary directory
|
uploadDir: "/tmp",
|
||||||
keepExtensions: true,
|
keepExtensions: true,
|
||||||
maxFileSize: 50 * 1024 * 1024, // 50 MB
|
maxFileSize: 50 * 1024 * 1024,
|
||||||
});
|
});
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
form.parse(req, (err, fields, files) => {
|
form.parse(req, (err, fields, files) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err);
|
return reject(err);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
const file = files.file[0];
|
||||||
const file = files.file;
|
|
||||||
if (!file) {
|
|
||||||
reject(new Error('No file found in the upload.'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
resolve({
|
resolve({
|
||||||
filePath: file.filepath,
|
filePath: file.filepath,
|
||||||
originalFilename: file.originalFilename || 'unknown',
|
originalFilename: file.originalFilename || 'unknown',
|
||||||
@@ -50,9 +43,9 @@ async function parseMultipartForm(req) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Main handler
|
// Main handler
|
||||||
export async function POST(req, res) {
|
export default async function handler(req, res) {
|
||||||
if (req.method !== 'POST') {
|
if (req.method !== "POST") {
|
||||||
return res.status(405).json({ error: 'Method not allowed. Use POST.' });
|
return res.status(405).json({ error: "Method not allowed. Use POST." });
|
||||||
}
|
}
|
||||||
|
|
||||||
let filePath = null;
|
let filePath = null;
|
||||||
@@ -63,29 +56,29 @@ export async function POST(req, res) {
|
|||||||
filePath = tempFilePath;
|
filePath = tempFilePath;
|
||||||
|
|
||||||
// Log file details
|
// Log file details
|
||||||
console.log('Uploaded file path:', filePath);
|
console.log("Uploaded file path:", filePath);
|
||||||
console.log('Original filename:', originalFilename);
|
console.log("Original filename:", originalFilename);
|
||||||
|
|
||||||
// Validate file extension
|
// Validate file extension
|
||||||
const allowedExtensions = ['mp3', 'wav', 'm4a'];
|
const allowedExtensions = ["mp3", "wav", "m4a"];
|
||||||
const fileExtension = path.extname(originalFilename).toLowerCase().replace('.', '');
|
const fileExtension = path.extname(originalFilename).toLowerCase().replace(".", "");
|
||||||
if (!allowedExtensions.includes(fileExtension)) {
|
if (!allowedExtensions.includes(fileExtension)) {
|
||||||
unlinkSync(filePath);
|
unlinkSync(filePath);
|
||||||
return res.status(400).json({
|
return res.status(400).json({
|
||||||
error: `Invalid file format. Only ${allowedExtensions.join(', ')} are supported.`,
|
error: `Invalid file format. Only ${allowedExtensions.join(", ")} are supported.`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create file stream
|
// Get transcription from OpenAI Whisper model
|
||||||
const audio_file = fs.createReadStream(filePath);
|
console.log("Requesting transcription...");
|
||||||
|
const transcription = await openaiClient.audio.transcriptions.create({
|
||||||
// Step 2: Get transcription from OpenAI Whisper model
|
file: fs.createReadStream(filePath), // Pass the file stream here
|
||||||
console.log('Requesting transcription...');
|
|
||||||
const transcription = await openaiClient.audio.translations.create({
|
|
||||||
file: fs.createReadStream(audio_file),
|
|
||||||
model: "whisper-1",
|
model: "whisper-1",
|
||||||
|
response_format: "text", // Ensure this is set
|
||||||
});
|
});
|
||||||
|
|
||||||
|
console.log("Transcription:", transcription); // Log the transcription response
|
||||||
|
|
||||||
// Clean up temporary file
|
// Clean up temporary file
|
||||||
if (filePath && existsSync(filePath)) {
|
if (filePath && existsSync(filePath)) {
|
||||||
unlinkSync(filePath);
|
unlinkSync(filePath);
|
||||||
@@ -94,17 +87,17 @@ export async function POST(req, res) {
|
|||||||
// Send response back to client
|
// Send response back to client
|
||||||
return res.status(200).json({ transcription: transcription.text });
|
return res.status(200).json({ transcription: transcription.text });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error during transcription:', error);
|
console.error("Error during transcription:", error);
|
||||||
|
|
||||||
if (error instanceof AxiosError) {
|
if (error instanceof AxiosError) {
|
||||||
console.error('OpenAI API error:', error.response?.data || error.message);
|
console.error("OpenAI API error:", error.response?.data || error.message);
|
||||||
return res.status(error.response?.status || 500).json({
|
return res.status(error.response?.status || 500).json({
|
||||||
error: error.response?.data?.error?.message || 'OpenAI API Error.',
|
error: error.response?.data?.error?.message || "OpenAI API Error.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.status(500).json({
|
return res.status(500).json({
|
||||||
error: 'An unexpected error occurred.',
|
error: "An unexpected error occurred.",
|
||||||
});
|
});
|
||||||
} finally {
|
} finally {
|
||||||
if (filePath) {
|
if (filePath) {
|
||||||
@@ -113,7 +106,7 @@ export async function POST(req, res) {
|
|||||||
unlinkSync(filePath);
|
unlinkSync(filePath);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to clean up temporary file:', err);
|
console.error("Failed to clean up temporary file:", err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user