124 lines
5.2 KiB
JavaScript
124 lines
5.2 KiB
JavaScript
const router = require('express').Router();
|
|
const { moderationText } = require('./initiatives-ai-agents/moderation.ts');
|
|
const { generatePicture } = require('./initiatives-ai-agents/picture.ts');
|
|
const { getSupabaseClient } = require('./supabaseClient');
|
|
|
|
// Обработчик для модерации текста
|
|
router.post('/moderate', async (req, res) => {
|
|
try {
|
|
const { title, body } = req.body;
|
|
if (!title || !body) {
|
|
res.status(400).json({ error: 'Заголовок и текст обязательны' });
|
|
return;
|
|
}
|
|
|
|
console.log('Запрос на модерацию:', { title: title.substring(0, 50), body: body.substring(0, 100) });
|
|
|
|
const [comment, fixedText, isApproved] = await moderationText(title, body);
|
|
|
|
console.log('Результат модерации получен:', { comment, fixedText: fixedText?.substring(0, 100), isApproved });
|
|
|
|
// Дополнительная проверка на стороне сервера
|
|
if (!isApproved && (!comment || comment.trim() === '')) {
|
|
console.warn('Обнаружен некорректный результат модерации - пустой комментарий при отклонении');
|
|
}
|
|
|
|
res.json({
|
|
comment,
|
|
fixedText,
|
|
isApproved
|
|
});
|
|
} catch (error) {
|
|
console.error('Error in moderation:', error);
|
|
res.status(500).json({ error: 'Внутренняя ошибка сервера', details: error.message });
|
|
}
|
|
});
|
|
|
|
// Обработчик для генерации изображений
|
|
router.post('/generate-image', async (req, res) => {
|
|
try {
|
|
const { prompt, userId } = req.body;
|
|
if (!prompt) {
|
|
res.status(400).json({ error: 'Необходимо указать запрос для генерации' });
|
|
return;
|
|
}
|
|
|
|
// Генерируем изображение
|
|
const imageBuffer = await generatePicture(prompt);
|
|
|
|
//console.log('Изображение получено, размер буфера:', imageBuffer?.length || 0, 'байт');
|
|
if (!imageBuffer || imageBuffer.length === 0) {
|
|
res.status(500).json({ error: 'Получен пустой буфер изображения' });
|
|
return;
|
|
}
|
|
|
|
//console.log('Начинаем загрузку в Supabase Storage...');
|
|
|
|
// Получаем Supabase клиент и создаем имя файла
|
|
const supabase = getSupabaseClient();
|
|
const timestamp = Date.now();
|
|
const filename = `image_${userId || 'user'}_${timestamp}.jpg`;
|
|
|
|
let uploadResult;
|
|
let retries = 0;
|
|
const maxRetries = 5;
|
|
|
|
while (retries < maxRetries) {
|
|
try {
|
|
uploadResult = await supabase.storage
|
|
.from('images')
|
|
.upload(filename, imageBuffer, {
|
|
contentType: 'image/jpeg',
|
|
upsert: true
|
|
});
|
|
|
|
if (!uploadResult.error) {
|
|
break; // Успешная загрузка
|
|
}
|
|
|
|
//console.warn(`Попытка загрузки ${retries + 1} неудачна:`, uploadResult.error);
|
|
retries++;
|
|
|
|
if (retries < maxRetries) {
|
|
// Ждем перед повторной попыткой
|
|
await new Promise(resolve => setTimeout(resolve, 1000 * retries));
|
|
}
|
|
} catch (error) {
|
|
//console.warn(`Попытка загрузки ${retries + 1} неудачна (исключение):`, error.message);
|
|
retries++;
|
|
|
|
if (retries < maxRetries) {
|
|
// Ждем перед повторной попыткой
|
|
await new Promise(resolve => setTimeout(resolve, 1000 * retries));
|
|
} else {
|
|
throw error; // Перебрасываем ошибку после всех попыток
|
|
}
|
|
}
|
|
}
|
|
|
|
if (uploadResult?.error) {
|
|
//console.error('Supabase storage error after all retries:', uploadResult.error);
|
|
res.status(500).json({ error: 'Ошибка при сохранении изображения после нескольких попыток' });
|
|
return;
|
|
}
|
|
|
|
//console.log('Изображение успешно загружено в Supabase Storage:', filename);
|
|
|
|
// Получаем публичный URL
|
|
const { data: urlData } = supabase.storage
|
|
.from('images')
|
|
.getPublicUrl(filename);
|
|
|
|
res.json({
|
|
success: true,
|
|
imageUrl: urlData.publicUrl,
|
|
imagePath: filename
|
|
});
|
|
|
|
} catch (error) {
|
|
//console.error('Error in image generation:', error);
|
|
res.status(500).json({ error: 'Внутренняя ошибка сервера', details: error.message });
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|