try2 / server.js
ardasen's picture
Update server.js
f6778f2
const baseUrl = getExternalUrl(process.env.SPACE_ID);
const openaiKey = process.env.OPENAI_KEY;
const proxyKey = process.env.PROXY_KEY; // Your secret proxy key
const express = require('express');
const proxy = require("express-http-proxy");
const fs = require("fs");
const FormData = require("form-data");
const port = 7860;
const app = express();
const bodyParser = require('body-parser');
const axios = require('axios');
const multer = require('multer'); // for handling multipart/form-data
// Middleware to parse JSON and URL-encoded form data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Middleware for handling file uploads
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
function authenticateProxyKey(req, res, next) {
const providedKey = req.headers['auro'];
if (providedKey && providedKey === proxyKey) {
next();
} else {
res.status(401).json({ error: 'Unauthorized' });
}
}
// Define routes
app.post('/upload', authenticateProxyKey, upload.single('file'), async (req, res) => {
try {
// Extract the uploaded file and other form data
const fileData = req.file;
const formData = req.body;
// Get the API key from the environment variable
const apiKey = process.env.OPENAI_KEY;
// Create a new FormData object to send to the Whisper API
const whisperFormData = new FormData();
whisperFormData.append('file', fileData.buffer, { filename: fileData.originalname });
// Append other form data fields if needed
for (const key in formData) {
whisperFormData.append(key, formData[key]);
}
// Make a request to the Whisper API with the obtained API key and multipart/form-data
const whisperResponse = await axios.post('https://api.openai.com/v1/audio/transcriptions', whisperFormData, {
headers: {
'Authorization': `Bearer ${apiKey}`,
...whisperFormData.getHeaders(),
},
});
console.log('Whisper API Response:', whisperResponse.data);
// Forward the response from the Whisper API back to the iOS app
res.status(whisperResponse.status).send(whisperResponse.data);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
function getExternalUrl(spaceId) {
try {
const [username, spacename] = spaceId.split('/');
return `https://${username}-${spacename.replace(/_/g, '-')}.hf.space/api/v1`;
} catch (e) {
return '';
}
}
app.get('/', (req, res) => {
// res.send(`This is your OpenAI Reverse Proxy URL: ${baseUrl}`);
});
app.listen(port, () => {
console.log(`Reverse proxy server running on ${baseUrl}`);
});