const express = require('express'); const bodyParser = require('body-parser'); const dotenv = require('dotenv'); // Динамический импорт node-fetch const fetch = (await import('node-fetch')).default; // Загрузка переменных окружения из .env файла dotenv.config(); const app = express(); const port = 3000; const apiKey = process.env.KEY; app.use(bodyParser.json()); // Обработка только POST запросов app.all('/', (req, res, next) => { if (req.method !== 'POST') { res.status(405).send('Только POST'); } else { const { prompt } = req.body; if (!prompt) { return res.status(400).send('Missing "prompt" in request body'); } try { console.log('Sending request to Hugging Face API...'); const response = await fetch('https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-3-medium', { method: 'POST', headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ inputs: prompt }), // Добавляем тайм-аут в 60 секунд timeout: 60000 }); if (!response.ok) { throw new Error(`Error from Hugging Face API: ${response.statusText}`); } console.log('Received response from Hugging Face API, processing image...'); const imageBuffer = await response.buffer(); const base64Image = imageBuffer.toString('base64'); res.json({ image: base64Image }); } catch (error) { console.error('Error generating image:', error.message); res.status(500).send('Error generating image'); } } }); }); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });