File size: 1,430 Bytes
abed4cc
587da90
 
 
 
abed4cc
587da90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abed4cc
 
587da90
abed4cc
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
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}`);
});