shashwatIDR commited on
Commit
e4256ad
·
verified ·
1 Parent(s): 8b3ddc0

Create server.js

Browse files
Files changed (1) hide show
  1. server.js +926 -0
server.js ADDED
@@ -0,0 +1,926 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from 'express';
2
+ import cors from 'cors';
3
+ import multer from 'multer';
4
+ import axios from 'axios';
5
+ import { Client } from '@gradio/client';
6
+ import dotenv from 'dotenv';
7
+ import bcrypt from 'bcrypt';
8
+ import jwt from 'jsonwebtoken';
9
+ import FormData from 'form-data';
10
+ import pg from 'pg';
11
+
12
+ dotenv.config();
13
+
14
+ const { Pool } = pg;
15
+
16
+ const app = express();
17
+ const port = process.env.PORT || 3000;
18
+
19
+ // Middleware
20
+ app.use(cors());
21
+ app.use(express.json());
22
+ app.use(express.static('public'));
23
+
24
+ // Database connection
25
+ const pool = new Pool({
26
+ connectionString: 'postgresql://img_owner:npg_PgXtYG4py8Vb@ep-wandering-salad-a1eva4cg-pooler.ap-southeast-1.aws.neon.tech/img?sslmode=require',
27
+ ssl: {
28
+ rejectUnauthorized: false
29
+ }
30
+ });
31
+
32
+ // Create tables if they don't exist
33
+ const initializeDatabase = async () => {
34
+ try {
35
+ await pool.query(`
36
+ CREATE TABLE IF NOT EXISTS users (
37
+ id SERIAL PRIMARY KEY,
38
+ username VARCHAR(255) NOT NULL UNIQUE,
39
+ email VARCHAR(255) NOT NULL UNIQUE,
40
+ password VARCHAR(255) NOT NULL,
41
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
42
+ );
43
+
44
+ CREATE TABLE IF NOT EXISTS images (
45
+ id SERIAL PRIMARY KEY,
46
+ user_id INTEGER REFERENCES users(id),
47
+ image_url VARCHAR(255) NOT NULL,
48
+ uploaded_url VARCHAR(255),
49
+ prompt TEXT NOT NULL,
50
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
51
+ );
52
+
53
+ CREATE TABLE IF NOT EXISTS user_generations (
54
+ id SERIAL PRIMARY KEY,
55
+ user_id INTEGER REFERENCES users(id),
56
+ original_url VARCHAR(255) NOT NULL,
57
+ uploaded_url VARCHAR(255),
58
+ prompt TEXT NOT NULL,
59
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
60
+ deleted_at TIMESTAMP
61
+ );
62
+ `);
63
+ // Add censored column if it doesn't exist
64
+ await pool.query(`ALTER TABLE images ADD COLUMN IF NOT EXISTS censored BOOLEAN DEFAULT false;`);
65
+ console.log('Database initialized successfully');
66
+ } catch (error) {
67
+ console.error('Error initializing database:', error);
68
+ throw error;
69
+ }
70
+ };
71
+
72
+ initializeDatabase();
73
+
74
+ // Authentication middleware
75
+ const authenticateToken = (req, res, next) => {
76
+ const authHeader = req.headers['authorization'];
77
+ const token = authHeader && authHeader.split(' ')[1];
78
+
79
+ if (!token) return res.sendStatus(401);
80
+
81
+ jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key', (err, user) => {
82
+ if (err) return res.sendStatus(403);
83
+ req.user = user;
84
+ next();
85
+ });
86
+ };
87
+
88
+ // Gemini censorship check function
89
+ const GEMINI_API_KEY = 'AIzaSyCq23lcvpPfig6ifq1rmt-z11vKpMvDD4I'; // <-- Updated Gemini API key
90
+ async function checkPromptCensorship(prompt) {
91
+ const apiKey = GEMINI_API_KEY;
92
+ const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;
93
+ const systemInstruction =
94
+ 'You are a content moderation AI. If the following prompt contains any NSFW, adult, explicit, sexual, violent, or otherwise censored content, respond ONLY with the word "true". If it is safe and contains no censored elements, respond ONLY with the word "false". Do not explain.';
95
+ try {
96
+ const response = await axios.post(url, {
97
+ contents: [
98
+ {
99
+ parts: [
100
+ { text: `${systemInstruction}\nPrompt: ${prompt}` }
101
+ ]
102
+ }
103
+ ]
104
+ });
105
+ const text = response.data?.candidates?.[0]?.content?.parts?.[0]?.text?.trim().toLowerCase();
106
+ if (text === 'true') return true;
107
+ if (text === 'false') return false;
108
+ // fallback: treat as not censored if unclear
109
+ return false;
110
+ } catch (e) {
111
+ console.error('Gemini censorship API error:', e.message);
112
+ // fallback: treat as not censored if error
113
+ return false;
114
+ }
115
+ }
116
+
117
+ // Routes
118
+ app.post('/api/register', async (req, res) => {
119
+ try {
120
+ const { username, email, password } = req.body;
121
+
122
+ if (!username || !email || !password) {
123
+ return res.status(400).json({ error: 'All fields are required' });
124
+ }
125
+
126
+ // Check if email already exists
127
+ const emailCheck = await pool.query('SELECT id FROM users WHERE email = $1', [email]);
128
+ if (emailCheck.rows.length > 0) {
129
+ return res.status(400).json({ error: 'Email already registered' });
130
+ }
131
+
132
+ // Check if username already exists
133
+ const usernameCheck = await pool.query('SELECT id FROM users WHERE username = $1', [username]);
134
+ if (usernameCheck.rows.length > 0) {
135
+ return res.status(400).json({ error: 'Username already taken' });
136
+ }
137
+
138
+ const hashedPassword = await bcrypt.hash(password, 10);
139
+
140
+ const result = await pool.query(
141
+ 'INSERT INTO users (username, email, password) VALUES ($1, $2, $3) RETURNING id, username, email',
142
+ [username, email, hashedPassword]
143
+ );
144
+
145
+ const token = jwt.sign({ id: result.rows[0].id }, process.env.JWT_SECRET || 'your-secret-key');
146
+ res.json({
147
+ token,
148
+ user: result.rows[0]
149
+ });
150
+ } catch (error) {
151
+ console.error('Registration error:', error);
152
+ res.status(500).json({ error: 'Error during registration' });
153
+ }
154
+ });
155
+
156
+ app.post('/api/login', async (req, res) => {
157
+ try {
158
+ const { email, password } = req.body;
159
+
160
+ if (!email || !password) {
161
+ return res.status(400).json({ error: 'Email and password are required' });
162
+ }
163
+
164
+ const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
165
+
166
+ if (result.rows.length === 0) {
167
+ return res.status(401).json({ error: 'Invalid email or password' });
168
+ }
169
+
170
+ const user = result.rows[0];
171
+ const validPassword = await bcrypt.compare(password, user.password);
172
+
173
+ if (!validPassword) {
174
+ return res.status(401).json({ error: 'Invalid email or password' });
175
+ }
176
+
177
+ const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET || 'your-secret-key');
178
+ res.json({
179
+ token,
180
+ user: {
181
+ id: user.id,
182
+ username: user.username,
183
+ email: user.email
184
+ }
185
+ });
186
+ } catch (error) {
187
+ console.error('Login error:', error);
188
+ res.status(500).json({ error: 'Error during login' });
189
+ }
190
+ });
191
+
192
+ app.get('/api/reset-db', async (req, res) => {
193
+ try {
194
+ await pool.query(`
195
+ DROP TABLE IF EXISTS user_generations;
196
+ DROP TABLE IF EXISTS images;
197
+ DROP TABLE IF EXISTS users;
198
+ `);
199
+ await initializeDatabase();
200
+ res.json({ success: true, message: 'Database reset successfully' });
201
+ } catch (error) {
202
+ console.error('Error resetting database:', error);
203
+ res.status(500).json({ error: 'Failed to reset database' });
204
+ }
205
+ });
206
+
207
+ app.post('/api/upload-image', authenticateToken, async (req, res) => {
208
+ try {
209
+ const { imageUrl, prompt } = req.body;
210
+ const userId = req.user.id;
211
+
212
+ // First, download the image from Heartsync
213
+ const imageResponse = await axios.get(imageUrl, { responseType: 'arraybuffer' });
214
+ const imageBuffer = Buffer.from(imageResponse.data);
215
+
216
+ // Create form data for File2Link
217
+ const formData = new FormData();
218
+ formData.append('file', new Blob([imageBuffer]), 'image.jpg');
219
+
220
+ // Upload to File2Link
221
+ const uploadResponse = await axios.post('https://file2link-ol4p.onrender.com/upload', formData, {
222
+ headers: {
223
+ ...formData.getHeaders()
224
+ }
225
+ });
226
+
227
+ const uploadedUrl = uploadResponse.data.access_url;
228
+
229
+ // Check censorship
230
+ const censored = await checkPromptCensorship(prompt);
231
+
232
+ // Save to images table for community gallery
233
+ const imageResult = await pool.query(
234
+ 'INSERT INTO images (user_id, image_url, uploaded_url, prompt, censored) VALUES ($1, $2, $3, $4, $5) RETURNING *',
235
+ [userId, imageUrl, uploadedUrl, prompt, censored]
236
+ );
237
+
238
+ // Save to user_generations table for user history
239
+ const generationResult = await pool.query(
240
+ 'INSERT INTO user_generations (user_id, original_url, uploaded_url, prompt) VALUES ($1, $2, $3, $4) RETURNING *',
241
+ [userId, imageUrl, uploadedUrl, prompt]
242
+ );
243
+
244
+ res.json({
245
+ success: true,
246
+ image: imageResult.rows[0],
247
+ generation: generationResult.rows[0]
248
+ });
249
+ } catch (error) {
250
+ console.error('Error uploading image:', error);
251
+ res.status(500).json({ error: 'Error uploading image' });
252
+ }
253
+ });
254
+
255
+ app.get('/api/community-images', async (req, res) => {
256
+ try {
257
+ const result = await pool.query(`
258
+ SELECT i.id, i.image_url, i.uploaded_url, i.prompt, i.created_at, i.censored, u.username
259
+ FROM images i
260
+ JOIN users u ON i.user_id = u.id
261
+ ORDER BY i.created_at DESC
262
+ `);
263
+ res.json(result.rows);
264
+ } catch (error) {
265
+ console.error('Error fetching community images:', error);
266
+ res.status(500).json({ error: 'Error fetching community images' });
267
+ }
268
+ });
269
+
270
+ app.get('/api/user-generations', authenticateToken, async (req, res) => {
271
+ try {
272
+ const userId = req.user.id;
273
+ const result = await pool.query(
274
+ 'SELECT * FROM user_generations WHERE user_id = $1 AND deleted_at IS NULL ORDER BY created_at DESC',
275
+ [userId]
276
+ );
277
+ res.json(result.rows);
278
+ } catch (error) {
279
+ console.error('Error fetching user generations:', error);
280
+ res.status(500).json({ error: 'Error fetching user generations' });
281
+ }
282
+ });
283
+
284
+ app.delete('/api/user-generations/:id', authenticateToken, async (req, res) => {
285
+ try {
286
+ const { id } = req.params;
287
+ const userId = req.user.id;
288
+
289
+ // First, get the image details to find the corresponding community image
290
+ const generationResult = await pool.query(
291
+ 'SELECT original_url, uploaded_url FROM user_generations WHERE id = $1 AND user_id = $2',
292
+ [id, userId]
293
+ );
294
+
295
+ if (generationResult.rows.length === 0) {
296
+ return res.status(404).json({ error: 'Image not found' });
297
+ }
298
+
299
+ const { original_url, uploaded_url } = generationResult.rows[0];
300
+
301
+ // Soft delete from user_generations
302
+ await pool.query(
303
+ 'UPDATE user_generations SET deleted_at = CURRENT_TIMESTAMP WHERE id = $1 AND user_id = $2',
304
+ [id, userId]
305
+ );
306
+
307
+ // Remove from community images (images table) - fix column name matching
308
+ await pool.query(
309
+ 'DELETE FROM images WHERE user_id = $1 AND (image_url = $2 OR uploaded_url = $3)',
310
+ [userId, original_url, uploaded_url]
311
+ );
312
+
313
+ res.json({ success: true });
314
+ } catch (error) {
315
+ console.error('Error deleting generation:', error);
316
+ res.status(500).json({ error: 'Error deleting generation' });
317
+ }
318
+ });
319
+
320
+ // Image Generation endpoint (backend only handles Heartsync interaction)
321
+ app.post('/api/generate', authenticateToken, async (req, res) => {
322
+ res.setHeader('Content-Type', 'text/event-stream');
323
+ res.setHeader('Cache-Control', 'no-cache');
324
+ res.setHeader('Connection', 'keep-alive');
325
+
326
+ try {
327
+ const { prompt } = req.body;
328
+ const sessionHash = Math.random().toString(36).substring(2, 15);
329
+
330
+ // First, join the queue
331
+ const joinResponse = await axios.post('https://heartsync-nsfw-uncensored.hf.space/gradio_api/queue/join', {
332
+ data: [
333
+ prompt,
334
+ "text, talk bubble, low quality, watermark, signature",
335
+ 0,
336
+ true,
337
+ 1024,
338
+ 1024,
339
+ 7,
340
+ 28
341
+ ],
342
+ event_data: null,
343
+ fn_index: 2,
344
+ trigger_id: 14,
345
+ session_hash: sessionHash
346
+ }, {
347
+ headers: {
348
+ 'Content-Type': 'application/json',
349
+ 'Referer': 'https://heartsync-nsfw-uncensored.hf.space/'
350
+ }
351
+ });
352
+
353
+ // Poll for results
354
+ let attempts = 0;
355
+ const maxAttempts = 60; // Increased attempts for potentially longer queues
356
+
357
+ while (attempts < maxAttempts) {
358
+ const dataResponse = await axios.get(
359
+ `https://heartsync-nsfw-uncensored.hf.space/gradio_api/queue/data?session_hash=${encodeURIComponent(sessionHash)}`,
360
+ {
361
+ headers: {
362
+ 'Accept': 'text/event-stream',
363
+ 'Referer': 'https://heartsync-nsfw-uncensored.hf.space/'
364
+ }
365
+ }
366
+ );
367
+
368
+ const data = dataResponse.data;
369
+
370
+ // Manually parse the event stream data
371
+ const lines = data.split('\n');
372
+ let eventData = '';
373
+ let foundEvent = false;
374
+ for (const line of lines) {
375
+ if (line.startsWith('data: ')) {
376
+ eventData += line.substring(6);
377
+ } else if (line === '') {
378
+ // Process eventData when an empty line is encountered
379
+ if (eventData) {
380
+ try {
381
+ const json = JSON.parse(eventData);
382
+ console.log(`[Image] Parsed event: ${json.msg}`);
383
+
384
+ if (json.msg === 'process_completed' && json.output?.data?.[0]?.url) {
385
+ const imageUrl = json.output.data[0].url;
386
+
387
+ // Send the original image URL back to the client as an SSE
388
+ res.write(`data: ${JSON.stringify({
389
+ type: 'success',
390
+ originalUrl: imageUrl
391
+ })}\n\n`);
392
+ res.end(); // End the connection after sending the final event
393
+ return; // Exit the function
394
+ }
395
+
396
+ if (json.msg === 'estimation') {
397
+ res.write(`data: ${JSON.stringify({ type: 'estimation', queueSize: json.queue_size, eta: json.rank_eta })}\n\n`);
398
+ foundEvent = true;
399
+ } else if (json.msg === 'process_starts') {
400
+ res.write(`data: ${JSON.stringify({ type: 'processing' })}\n\n`);
401
+ foundEvent = true;
402
+ } else if (json.msg === 'process_failed') {
403
+ console.log(`[Image] Process failed:`, json);
404
+ res.write(`data: ${JSON.stringify({ type: 'error', message: 'Generation failed on server' })}\n\n`);
405
+ res.end();
406
+ return;
407
+ }
408
+
409
+ } catch (error) {
410
+ console.error('[Image] Error parsing event data:', error, 'Raw data:', eventData);
411
+ }
412
+ eventData = ''; // Reset for the next event
413
+ }
414
+ } else if (line.startsWith(':')) {
415
+ // Ignore comment lines
416
+ continue;
417
+ } else if (line !== '') {
418
+ // If line is not data or comment, it might be part of a multi-line data chunk, append to eventData
419
+ eventData += line;
420
+ }
421
+ }
422
+
423
+ // If loop finishes without 'process_completed', wait and try again
424
+ await new Promise(resolve => setTimeout(resolve, 2000)); // Wait longer before next poll attempt
425
+ attempts++;
426
+ }
427
+
428
+ // If the loop times out without success
429
+ if (!foundEvent) {
430
+ console.log(`[Image] No events found in response, raw data:`, data.substring(0, 500));
431
+ }
432
+ res.status(500).write(`data: ${JSON.stringify({ type: 'error', message: 'Generation timed out' })}\n\n`);
433
+ res.end();
434
+
435
+ } catch (error) {
436
+ console.error('Generation endpoint error:', error);
437
+ res.status(500).write(`data: ${JSON.stringify({ type: 'error', message: error.message || 'Failed to generate image' })}\n\n`);
438
+ res.end();
439
+ }
440
+ });
441
+
442
+ // Anime-UC Generation endpoint (using Heartsync API like original)
443
+ app.post('/api/generate/anime-uc', authenticateToken, async (req, res) => {
444
+ res.setHeader('Content-Type', 'text/event-stream');
445
+ res.setHeader('Cache-Control', 'no-cache');
446
+ res.setHeader('Connection', 'keep-alive');
447
+
448
+ try {
449
+ const { prompt } = req.body;
450
+ const sessionHash = Math.random().toString(36).substring(2, 15);
451
+
452
+ console.log(`[Anime-UC] Starting generation for prompt: "${prompt}" with session: ${sessionHash}`);
453
+
454
+ // First, join the queue using Heartsync API
455
+ const joinResponse = await axios.post('https://heartsync-nsfw-uncensored.hf.space/gradio_api/queue/join', {
456
+ data: [
457
+ prompt,
458
+ "text, talk bubble, low quality, watermark, signature",
459
+ 0,
460
+ true,
461
+ 1024,
462
+ 1024,
463
+ 7,
464
+ 28
465
+ ],
466
+ event_data: null,
467
+ fn_index: 2,
468
+ trigger_id: 14,
469
+ session_hash: sessionHash
470
+ }, {
471
+ headers: {
472
+ 'Content-Type': 'application/json',
473
+ 'Referer': 'https://heartsync-nsfw-uncensored.hf.space/'
474
+ }
475
+ });
476
+
477
+ console.log(`[Anime-UC] Queue joined, event_id: ${joinResponse.data?.event_id}`);
478
+
479
+ // Poll for results
480
+ let attempts = 0;
481
+ const maxAttempts = 60; // Heartsync typically faster
482
+
483
+ while (attempts < maxAttempts) {
484
+ try {
485
+ const dataResponse = await axios.get(
486
+ `https://heartsync-nsfw-uncensored.hf.space/gradio_api/queue/data?session_hash=${encodeURIComponent(sessionHash)}`,
487
+ {
488
+ headers: {
489
+ 'Accept': 'text/event-stream',
490
+ 'Referer': 'https://heartsync-nsfw-uncensored.hf.space/'
491
+ },
492
+ timeout: 10000 // 10 second timeout
493
+ }
494
+ );
495
+
496
+ const data = dataResponse.data;
497
+ console.log(`[Anime-UC] Poll attempt ${attempts + 1}, data length: ${data.length}`);
498
+
499
+ // Manually parse the event stream data
500
+ const lines = data.split('\n');
501
+ let eventData = '';
502
+ let foundEvent = false;
503
+
504
+ for (const line of lines) {
505
+ if (line.startsWith('data: ')) {
506
+ eventData += line.substring(6);
507
+ } else if (line === '') {
508
+ // Process eventData when an empty line is encountered
509
+ if (eventData) {
510
+ try {
511
+ const json = JSON.parse(eventData);
512
+ console.log(`[Anime-UC] Parsed event: ${json.msg}`);
513
+
514
+ if (json.msg === 'process_completed' && json.output?.data?.[0]?.url) {
515
+ const imageUrl = json.output.data[0].url;
516
+ console.log(`[Anime-UC] Found image:`, imageUrl);
517
+
518
+ // Send the image URL back to the client as an SSE
519
+ res.write(`data: ${JSON.stringify({
520
+ type: 'success',
521
+ originalUrl: imageUrl,
522
+ allImages: [imageUrl]
523
+ })}\n\n`);
524
+ res.end();
525
+ return;
526
+ }
527
+
528
+ if (json.msg === 'estimation') {
529
+ res.write(`data: ${JSON.stringify({ type: 'estimation', queueSize: json.queue_size || 0, eta: json.rank_eta || null })}\n\n`);
530
+ foundEvent = true;
531
+ } else if (json.msg === 'process_starts') {
532
+ res.write(`data: ${JSON.stringify({ type: 'processing' })}\n\n`);
533
+ foundEvent = true;
534
+ }
535
+
536
+ } catch (error) {
537
+ console.error('[Anime-UC] Error parsing event data:', error, 'Raw data:', eventData);
538
+ }
539
+ eventData = '';
540
+ }
541
+ } else if (line.startsWith(':')) {
542
+ continue;
543
+ } else if (line !== '') {
544
+ eventData += line;
545
+ }
546
+ }
547
+
548
+ // If no events were found, log the raw data for debugging
549
+ if (!foundEvent && data.trim()) {
550
+ console.log(`[Anime-UC] No events found in response, raw data:`, data.substring(0, 500));
551
+ }
552
+
553
+ } catch (pollError) {
554
+ console.error(`[Anime-UC] Poll error on attempt ${attempts + 1}:`, pollError.message);
555
+ }
556
+
557
+ await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds between polls
558
+ attempts++;
559
+ }
560
+
561
+ console.log(`[Anime-UC] Generation timed out after ${maxAttempts} attempts`);
562
+ res.status(500).write(`data: ${JSON.stringify({ type: 'error', message: 'Generation timed out' })}\n\n`);
563
+ res.end();
564
+
565
+ } catch (error) {
566
+ console.error('[Anime-UC] Generation endpoint error:', error);
567
+ res.status(500).write(`data: ${JSON.stringify({ type: 'error', message: error.message || 'Failed to generate image' })}\n\n`);
568
+ res.end();
569
+ }
570
+ });
571
+
572
+ // Flux Generation endpoint (now GET, returns only image URL)
573
+ app.get('/api/generate/flux', authenticateToken, async (req, res) => {
574
+ try {
575
+ const { prompt, aspect } = req.query;
576
+ if (!prompt) {
577
+ return res.status(400).json({ success: false, error: 'Prompt is required' });
578
+ }
579
+
580
+ // Aspect ratio logic
581
+ let width = 1280, height = 720;
582
+ if (aspect === '9:16') {
583
+ width = 720; height = 1280;
584
+ } else if (aspect === '1:1') {
585
+ width = 1024; height = 1024;
586
+ }
587
+
588
+ const sessionHash = Math.random().toString(36).substring(2, 15);
589
+
590
+ console.log(`[Flux] Starting generation for prompt: "${prompt}" with session: ${sessionHash}`);
591
+
592
+ // Join the queue using the correct API structure
593
+ const joinResponse = await axios.post('https://yanze-pulid-flux.hf.space/queue/join', {
594
+ data: [
595
+ prompt,
596
+ null, // id_image (null for no ID image)
597
+ 0, // start_step
598
+ 4, // guidance
599
+ "-1", // seed
600
+ 1, // true_cfg
601
+ width,
602
+ height,
603
+ 20, // num_steps
604
+ 1, // id_weight
605
+ "bad quality, worst quality, text, signature, watermark, extra limbs", // neg_prompt
606
+ 1, // timestep_to_start_cfg
607
+ 128 // max_sequence_length
608
+ ],
609
+ event_data: null,
610
+ fn_index: 4,
611
+ trigger_id: 21,
612
+ session_hash: sessionHash
613
+ }, {
614
+ headers: {
615
+ 'Content-Type': 'application/json',
616
+ 'Referer': 'https://yanze-pulid-flux.hf.space/'
617
+ }
618
+ });
619
+
620
+ console.log(`[Flux] Queue joined, event_id: ${joinResponse.data?.event_id}`);
621
+
622
+ // Poll for results
623
+ let attempts = 0;
624
+ const maxAttempts = 60;
625
+
626
+ while (attempts < maxAttempts) {
627
+ try {
628
+ const dataResponse = await axios.get(
629
+ `https://yanze-pulid-flux.hf.space/queue/data?session_hash=${encodeURIComponent(sessionHash)}`,
630
+ {
631
+ headers: {
632
+ 'Accept': 'text/event-stream',
633
+ 'Referer': 'https://yanze-pulid-flux.hf.space/'
634
+ },
635
+ timeout: 10000
636
+ }
637
+ );
638
+
639
+ const data = dataResponse.data;
640
+ console.log(`[Flux] Poll attempt ${attempts + 1}, data length: ${data.length}`);
641
+
642
+ // Parse the event stream data
643
+ const lines = data.split('\n');
644
+ let eventData = '';
645
+
646
+ for (const line of lines) {
647
+ if (line.startsWith('data: ')) {
648
+ eventData += line.substring(6);
649
+ } else if (line === '') {
650
+ if (eventData) {
651
+ try {
652
+ const json = JSON.parse(eventData);
653
+ console.log(`[Flux] Parsed event: ${json.msg}`);
654
+
655
+ if (json.msg === 'process_completed' && json.output?.data?.[0]?.url) {
656
+ const imageUrl = json.output.data[0].url;
657
+ console.log(`[Flux] Found image:`, imageUrl);
658
+
659
+ res.json({ success: true, imageUrl: imageUrl });
660
+ return;
661
+ }
662
+
663
+ } catch (error) {
664
+ console.error('[Flux] Error parsing event data:', error, 'Raw data:', eventData);
665
+ }
666
+ eventData = '';
667
+ }
668
+ } else if (line.startsWith(':')) {
669
+ continue;
670
+ } else if (line !== '') {
671
+ eventData += line;
672
+ }
673
+ }
674
+
675
+ } catch (pollError) {
676
+ console.error(`[Flux] Poll error on attempt ${attempts + 1}:`, pollError.message);
677
+ }
678
+
679
+ await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds between polls
680
+ attempts++;
681
+ }
682
+
683
+ console.log(`[Flux] Generation timed out after ${maxAttempts} attempts`);
684
+ res.status(500).json({ success: false, error: 'Generation timed out' });
685
+
686
+ } catch (error) {
687
+ console.error('[Flux] Generation endpoint error:', error);
688
+ res.status(500).json({ success: false, error: error.message || 'Failed to generate image' });
689
+ }
690
+ });
691
+
692
+ // New endpoint to add community image (handles data from client-side upload)
693
+ app.post('/api/add-community-image', authenticateToken, async (req, res) => {
694
+ try {
695
+ const { originalUrl, uploadedUrl, prompt } = req.body;
696
+ const userId = req.user.id;
697
+
698
+ if (!originalUrl || !uploadedUrl || !prompt) {
699
+ return res.status(400).json({ error: 'Missing required fields' });
700
+ }
701
+
702
+ // Check censorship
703
+ const censored = await checkPromptCensorship(prompt);
704
+
705
+ // Save to images table for community gallery
706
+ const imageResult = await pool.query(
707
+ 'INSERT INTO images (user_id, image_url, uploaded_url, prompt, censored) VALUES ($1, $2, $3, $4, $5) RETURNING *',
708
+ [userId, originalUrl, uploadedUrl, prompt, censored]
709
+ );
710
+
711
+ // Save to user_generations table for user history
712
+ const generationResult = await pool.query(
713
+ 'INSERT INTO user_generations (user_id, original_url, uploaded_url, prompt) VALUES ($1, $2, $3, $4) RETURNING *',
714
+ [userId, originalUrl, uploadedUrl, prompt]
715
+ );
716
+
717
+ res.json({
718
+ success: true,
719
+ image: imageResult.rows[0],
720
+ generation: generationResult.rows[0]
721
+ });
722
+ } catch (error) {
723
+ console.error('Error adding community image:', error);
724
+ res.status(500).json({ error: 'Error adding image to community' });
725
+ }
726
+ });
727
+
728
+ // Auth status endpoint
729
+ app.get('/api/auth/status', authenticateToken, async (req, res) => {
730
+ try {
731
+ const result = await pool.query(
732
+ 'SELECT id, username, email FROM users WHERE id = $1',
733
+ [req.user.id]
734
+ );
735
+
736
+ if (result.rows.length === 0) {
737
+ return res.status(401).json({ error: 'User not found' });
738
+ }
739
+
740
+ res.json({ user: result.rows[0] });
741
+ } catch (error) {
742
+ console.error('Auth status error:', error);
743
+ res.status(500).json({ error: 'Error checking auth status' });
744
+ }
745
+ });
746
+
747
+ // Admin endpoints (no authentication required for admin functions)
748
+
749
+ // Get image statistics
750
+ app.get('/api/admin/stats', async (req, res) => {
751
+ try {
752
+ const totalImages = await pool.query('SELECT COUNT(*) as count FROM images');
753
+ const uniqueUsers = await pool.query('SELECT COUNT(DISTINCT user_id) as count FROM images');
754
+ const last24Hours = await pool.query(`
755
+ SELECT COUNT(*) as count FROM images
756
+ WHERE created_at >= NOW() - INTERVAL '24 hours'
757
+ `);
758
+
759
+ res.json({
760
+ totalImages: parseInt(totalImages.rows[0].count),
761
+ uniqueUsers: parseInt(uniqueUsers.rows[0].count),
762
+ last24Hours: parseInt(last24Hours.rows[0].count)
763
+ });
764
+ } catch (error) {
765
+ console.error('Error getting admin stats:', error);
766
+ res.status(500).json({ error: 'Error getting statistics' });
767
+ }
768
+ });
769
+
770
+ // Delete single image (admin)
771
+ app.delete('/api/admin/images/:id', async (req, res) => {
772
+ try {
773
+ const { id } = req.params;
774
+
775
+ // Delete from images table
776
+ const result = await pool.query('DELETE FROM images WHERE id = $1 RETURNING *', [id]);
777
+
778
+ if (result.rows.length === 0) {
779
+ return res.status(404).json({ error: 'Image not found' });
780
+ }
781
+
782
+ // Also delete from user_generations if it exists
783
+ await pool.query(
784
+ 'DELETE FROM user_generations WHERE original_url = $1 OR uploaded_url = $2',
785
+ [result.rows[0].image_url, result.rows[0].uploaded_url]
786
+ );
787
+
788
+ res.json({ success: true, message: 'Image deleted successfully' });
789
+ } catch (error) {
790
+ console.error('Error deleting image:', error);
791
+ res.status(500).json({ error: 'Error deleting image' });
792
+ }
793
+ });
794
+
795
+ // Delete all images (admin)
796
+ app.delete('/api/admin/images', async (req, res) => {
797
+ try {
798
+ // Delete all images from images table
799
+ await pool.query('DELETE FROM images');
800
+
801
+ // Clear user_generations table (soft delete all)
802
+ await pool.query('UPDATE user_generations SET deleted_at = CURRENT_TIMESTAMP WHERE deleted_at IS NULL');
803
+
804
+ res.json({ success: true, message: 'All images deleted successfully' });
805
+ } catch (error) {
806
+ console.error('Error deleting all images:', error);
807
+ res.status(500).json({ error: 'Error deleting all images' });
808
+ }
809
+ });
810
+
811
+ // Export all images data (admin)
812
+ app.get('/api/admin/export', async (req, res) => {
813
+ try {
814
+ const result = await pool.query(`
815
+ SELECT i.id, i.image_url, i.uploaded_url, i.prompt, i.created_at, i.censored, u.username
816
+ FROM images i
817
+ JOIN users u ON i.user_id = u.id
818
+ ORDER BY i.created_at DESC
819
+ `);
820
+ const exportData = {
821
+ images: result.rows,
822
+ exportDate: new Date().toISOString(),
823
+ totalImages: result.rows.length,
824
+ uniqueUsers: new Set(result.rows.map(img => img.username)).size
825
+ };
826
+ res.setHeader('Content-Type', 'application/json');
827
+ res.setHeader('Content-Disposition', `attachment; filename="community-images-${new Date().toISOString().split('T')[0]}.json"`);
828
+ res.json(exportData);
829
+ } catch (error) {
830
+ console.error('Error exporting data:', error);
831
+ res.status(500).json({ error: 'Error exporting data' });
832
+ }
833
+ });
834
+
835
+ // Bulk update images (admin, no auth)
836
+ app.post('/api/admin/bulk-update-images', async (req, res) => {
837
+ try {
838
+ const images = req.body;
839
+ if (!Array.isArray(images)) {
840
+ return res.status(400).json({ error: 'Request body must be an array of images' });
841
+ }
842
+ let updated = 0, inserted = 0, errors = [];
843
+ for (const img of images) {
844
+ if (!img.id || !img.image_url || !img.uploaded_url) {
845
+ errors.push({ id: img.id, error: 'Missing id, image_url, or uploaded_url' });
846
+ continue;
847
+ }
848
+ try {
849
+ // Try to update
850
+ let updateFields = ['image_url = $1', 'uploaded_url = $2'];
851
+ let updateValues = [img.image_url, img.uploaded_url, img.id];
852
+ let paramIdx = 3;
853
+ if (typeof img.prompt === 'string') {
854
+ updateFields.push(`prompt = $${paramIdx}`);
855
+ updateValues.splice(paramIdx - 1, 0, img.prompt);
856
+ paramIdx++;
857
+ }
858
+ if (typeof img.censored === 'boolean') {
859
+ updateFields.push(`censored = $${paramIdx}`);
860
+ updateValues.splice(paramIdx - 1, 0, img.censored);
861
+ paramIdx++;
862
+ }
863
+ const updateResult = await pool.query(
864
+ `UPDATE images SET ${updateFields.join(', ')} WHERE id = $${paramIdx} RETURNING *`,
865
+ updateValues
866
+ );
867
+ if (updateResult.rowCount > 0) {
868
+ updated++;
869
+ } else {
870
+ // Insert if not found
871
+ const insertFields = ['id', 'image_url', 'uploaded_url'];
872
+ const insertValues = [img.id, img.image_url, img.uploaded_url];
873
+ const insertParams = ['$1', '$2', '$3'];
874
+ let insertIdx = 4;
875
+ if (typeof img.prompt === 'string') {
876
+ insertFields.push('prompt');
877
+ insertValues.push(img.prompt);
878
+ insertParams.push(`$${insertIdx++}`);
879
+ }
880
+ if (typeof img.censored === 'boolean') {
881
+ insertFields.push('censored');
882
+ insertValues.push(img.censored);
883
+ insertParams.push(`$${insertIdx++}`);
884
+ }
885
+ await pool.query(
886
+ `INSERT INTO images (${insertFields.join(', ')}) VALUES (${insertParams.join(', ')})`,
887
+ insertValues
888
+ );
889
+ inserted++;
890
+ }
891
+ } catch (e) {
892
+ errors.push({ id: img.id, error: e.message });
893
+ }
894
+ }
895
+ res.json({ updated, inserted, errors });
896
+ } catch (error) {
897
+ console.error('Bulk update error:', error);
898
+ res.status(500).json({ error: 'Bulk update failed' });
899
+ }
900
+ });
901
+
902
+ // Admin endpoint to process all old images for censorship
903
+ app.post('/api/admin/process-old', async (req, res) => {
904
+ try {
905
+ // Get all images
906
+ const result = await pool.query('SELECT id, prompt FROM images');
907
+ let updated = 0, errors = [];
908
+ for (const img of result.rows) {
909
+ try {
910
+ const censored = await checkPromptCensorship(img.prompt);
911
+ await pool.query('UPDATE images SET censored = $1 WHERE id = $2', [censored, img.id]);
912
+ updated++;
913
+ } catch (e) {
914
+ errors.push({ id: img.id, error: e.message });
915
+ }
916
+ }
917
+ res.json({ updated, errors });
918
+ } catch (error) {
919
+ console.error('Process-old error:', error);
920
+ res.status(500).json({ error: 'Failed to process old images' });
921
+ }
922
+ });
923
+
924
+ app.listen(port, () => {
925
+ console.log(`Server running on port ${port}`);
926
+ });