Spaces:
Sleeping
Sleeping
const express = require('express'); | |
const rateLimit = require('express-rate-limit'); | |
const axios = require('axios'); | |
require('dotenv').config(); | |
const app = express(); | |
const openai_key = process.env.OPENAI_KEY; | |
// Rate limiter configuration | |
const limiter = rateLimit({ | |
windowMs: 30 * 1000, // 30 seconds | |
max: 1, // limit each IP to 1 request per windowMs | |
onLimitReached: (req, res) => { | |
console.error(`Rate limit exceeded for ${req.ip}`); | |
} | |
}); | |
// Apply rate limiting to all requests | |
app.use(limiter); | |
// Enable JSON body parsing | |
app.use(express.json()); | |
// DALL-E 3 image generation endpoint | |
app.post('/', async (req, res) => { | |
try { | |
const { prompt } = req.body; | |
// Check if the prompt is provided | |
if (!prompt) { | |
return res.status(400).send({ message: 'No prompt provided' }); | |
} | |
// Send the request to OpenAI's DALL-E 3 API | |
const response = await axios.post('https://api.openai.com/v1/images/generations', { | |
prompt: prompt | |
}, { | |
headers: { | |
'Authorization': `Bearer ${openai_key}`, | |
'Content-Type': 'application/json' | |
} | |
}); | |
// Send back the generated image | |
res.send(response.data); | |
} catch (error) { | |
console.error('Error generating image:', error); | |
res.status(500).send({ message: 'Error generating image' }); | |
} | |
}); | |
const port = 7860; | |
app.listen(port, () => { | |
console.log(`API server listening on port ${port}`); | |
}); |