shashwatIDR commited on
Commit
dfc3a58
·
verified ·
1 Parent(s): aa08e9f

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +28 -897
server.js CHANGED
@@ -1,20 +1,12 @@
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
- import fetch from 'node-fetch';
12
- import NodeCache from 'node-cache';
13
 
14
  dotenv.config();
15
 
16
  // --- Hugging Face Space Auto-Restarter ---
17
- const HF_TOKEN = process.env.HF_TOKEN
18
  const SPACE_ID = process.env.HF_SPACE_ID || 'shashwatIDR/vision';
19
  const HF_API_BASE = 'https://huggingface.co/api';
20
 
@@ -82,333 +74,20 @@ async function testHFAPI() {
82
  console.log('[⏰ Scheduled] Space will restart every 5 minutes');
83
  })();
84
 
85
- const { Pool } = pg;
86
-
87
  const app = express();
88
  const port = process.env.PORT || 3000;
89
-
90
- // Middleware
91
- app.use(cors({ origin: '*', credentials: true }));
92
  app.use(express.json());
93
- app.use(express.static('public'));
94
-
95
- // Database connection
96
- const pool = new Pool({
97
- connectionString: 'postgresql://img_owner:npg_PgXtYG4py8Vb@ep-wandering-salad-a1eva4cg-pooler.ap-southeast-1.aws.neon.tech/img?sslmode=require',
98
- ssl: {
99
- rejectUnauthorized: false
100
- }
101
- });
102
-
103
- // Initialize cache (default TTL: 60 seconds)
104
- const cache = new NodeCache({ stdTTL: 60, checkperiod: 120 });
105
-
106
- // Create tables if they don't exist
107
- const initializeDatabase = async () => {
108
- try {
109
- await pool.query(`
110
- CREATE TABLE IF NOT EXISTS users (
111
- id SERIAL PRIMARY KEY,
112
- username VARCHAR(255) NOT NULL UNIQUE,
113
- email VARCHAR(255) NOT NULL UNIQUE,
114
- password VARCHAR(255) NOT NULL,
115
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
116
- );
117
-
118
- CREATE TABLE IF NOT EXISTS images (
119
- id SERIAL PRIMARY KEY,
120
- user_id INTEGER REFERENCES users(id),
121
- image_url VARCHAR(255) NOT NULL,
122
- uploaded_url VARCHAR(255),
123
- prompt TEXT NOT NULL,
124
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
125
- );
126
-
127
- CREATE TABLE IF NOT EXISTS user_generations (
128
- id SERIAL PRIMARY KEY,
129
- user_id INTEGER REFERENCES users(id),
130
- original_url VARCHAR(255) NOT NULL,
131
- uploaded_url VARCHAR(255),
132
- prompt TEXT NOT NULL,
133
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
134
- deleted_at TIMESTAMP
135
- );
136
- `);
137
- // Add censored column if it doesn't exist
138
- await pool.query(`ALTER TABLE images ADD COLUMN IF NOT EXISTS censored BOOLEAN DEFAULT false;`);
139
- // Add indexes for performance
140
- await pool.query(`CREATE INDEX IF NOT EXISTS idx_images_user_id ON images(user_id);`);
141
- await pool.query(`CREATE INDEX IF NOT EXISTS idx_images_created_at ON images(created_at);`);
142
- await pool.query(`CREATE INDEX IF NOT EXISTS idx_user_generations_user_id ON user_generations(user_id);`);
143
- await pool.query(`CREATE INDEX IF NOT EXISTS idx_user_generations_created_at ON user_generations(created_at);`);
144
- console.log('Database initialized successfully');
145
- } catch (error) {
146
- console.error('Error initializing database:', error);
147
- throw error;
148
- }
149
- };
150
-
151
- initializeDatabase();
152
-
153
- // Authentication middleware
154
- const authenticateToken = (req, res, next) => {
155
- const authHeader = req.headers['authorization'];
156
- const token = authHeader && authHeader.split(' ')[1];
157
-
158
- if (!token) return res.sendStatus(401);
159
-
160
- jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key', (err, user) => {
161
- if (err) return res.sendStatus(403);
162
- req.user = user;
163
- next();
164
- });
165
- };
166
-
167
- // Gemini censorship check function
168
- const GEMINI_API_KEY = 'AIzaSyCq23lcvpPfig6ifq1rmt-z11vKpMvDD4I'; // <-- Updated Gemini API key
169
- async function checkPromptCensorship(prompt) {
170
- const apiKey = GEMINI_API_KEY;
171
- const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;
172
- const systemInstruction =
173
- '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.';
174
- try {
175
- const response = await axios.post(url, {
176
- contents: [
177
- {
178
- parts: [
179
- { text: `${systemInstruction}\nPrompt: ${prompt}` }
180
- ]
181
- }
182
- ]
183
- });
184
- const text = response.data?.candidates?.[0]?.content?.parts?.[0]?.text?.trim().toLowerCase();
185
- if (text === 'true') return true;
186
- if (text === 'false') return false;
187
- // fallback: treat as not censored if unclear
188
- return false;
189
- } catch (e) {
190
- console.error('Gemini censorship API error:', e.message);
191
- // fallback: treat as not censored if error
192
- return false;
193
- }
194
- }
195
-
196
- // Routes
197
- app.post('/api/register', async (req, res) => {
198
- try {
199
- const { username, email, password } = req.body;
200
-
201
- if (!username || !email || !password) {
202
- return res.status(400).json({ error: 'All fields are required' });
203
- }
204
-
205
- // Check if email already exists
206
- const emailCheck = await pool.query('SELECT id FROM users WHERE email = $1', [email]);
207
- if (emailCheck.rows.length > 0) {
208
- return res.status(400).json({ error: 'Email already registered' });
209
- }
210
-
211
- // Check if username already exists
212
- const usernameCheck = await pool.query('SELECT id FROM users WHERE username = $1', [username]);
213
- if (usernameCheck.rows.length > 0) {
214
- return res.status(400).json({ error: 'Username already taken' });
215
- }
216
-
217
- const hashedPassword = await bcrypt.hash(password, 10);
218
-
219
- const result = await pool.query(
220
- 'INSERT INTO users (username, email, password) VALUES ($1, $2, $3) RETURNING id, username, email',
221
- [username, email, hashedPassword]
222
- );
223
-
224
- const token = jwt.sign({ id: result.rows[0].id }, process.env.JWT_SECRET || 'your-secret-key');
225
- res.json({
226
- token,
227
- user: result.rows[0]
228
- });
229
- } catch (error) {
230
- console.error('Registration error:', error);
231
- res.status(500).json({ error: 'Error during registration' });
232
- }
233
- });
234
-
235
- app.post('/api/login', async (req, res) => {
236
- try {
237
- const { email, password } = req.body;
238
-
239
- if (!email || !password) {
240
- return res.status(400).json({ error: 'Email and password are required' });
241
- }
242
-
243
- const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
244
-
245
- if (result.rows.length === 0) {
246
- return res.status(401).json({ error: 'Invalid email or password' });
247
- }
248
-
249
- const user = result.rows[0];
250
- const validPassword = await bcrypt.compare(password, user.password);
251
-
252
- if (!validPassword) {
253
- return res.status(401).json({ error: 'Invalid email or password' });
254
- }
255
-
256
- const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET || 'your-secret-key');
257
- res.json({
258
- token,
259
- user: {
260
- id: user.id,
261
- username: user.username,
262
- email: user.email
263
- }
264
- });
265
- } catch (error) {
266
- console.error('Login error:', error);
267
- res.status(500).json({ error: 'Error during login' });
268
- }
269
- });
270
-
271
- app.get('/api/reset-db', async (req, res) => {
272
- try {
273
- await pool.query(`
274
- DROP TABLE IF EXISTS user_generations;
275
- DROP TABLE IF EXISTS images;
276
- DROP TABLE IF EXISTS users;
277
- `);
278
- await initializeDatabase();
279
- res.json({ success: true, message: 'Database reset successfully' });
280
- } catch (error) {
281
- console.error('Error resetting database:', error);
282
- res.status(500).json({ error: 'Failed to reset database' });
283
- }
284
- });
285
-
286
- app.post('/api/upload-image', authenticateToken, async (req, res) => {
287
- try {
288
- const { imageUrl, prompt } = req.body;
289
- const userId = req.user.id;
290
-
291
- // First, download the image from Heartsync
292
- const imageResponse = await axios.get(imageUrl, { responseType: 'arraybuffer' });
293
- const imageBuffer = Buffer.from(imageResponse.data);
294
-
295
- // Create form data for File2Link
296
- const formData = new FormData();
297
- formData.append('file', new Blob([imageBuffer]), 'image.jpg');
298
-
299
- // Upload to File2Link
300
- const uploadResponse = await axios.post('https://file2link-ol4p.onrender.com/upload', formData, {
301
- headers: {
302
- ...formData.getHeaders()
303
- }
304
- });
305
-
306
- const uploadedUrl = uploadResponse.data.access_url;
307
-
308
- // Check censorship
309
- const censored = await checkPromptCensorship(prompt);
310
-
311
- // Save to images table for community gallery
312
- const imageResult = await pool.query(
313
- 'INSERT INTO images (user_id, image_url, uploaded_url, prompt, censored) VALUES ($1, $2, $3, $4, $5) RETURNING *',
314
- [userId, imageUrl, uploadedUrl, prompt, censored]
315
- );
316
-
317
- // Save to user_generations table for user history
318
- const generationResult = await pool.query(
319
- 'INSERT INTO user_generations (user_id, original_url, uploaded_url, prompt) VALUES ($1, $2, $3, $4) RETURNING *',
320
- [userId, imageUrl, uploadedUrl, prompt]
321
- );
322
-
323
- res.json({
324
- success: true,
325
- image: imageResult.rows[0],
326
- generation: generationResult.rows[0]
327
- });
328
- } catch (error) {
329
- console.error('Error uploading image:', error);
330
- res.status(500).json({ error: 'Error uploading image' });
331
- }
332
- });
333
-
334
- // Community images with cache and pagination
335
- app.get('/api/community-images', async (req, res) => {
336
- try {
337
- const page = parseInt(req.query.page) || 1;
338
- const limit = parseInt(req.query.limit) || 50;
339
- const offset = (page - 1) * limit;
340
- const cacheKey = `community-images:${page}:${limit}`;
341
- const cached = cache.get(cacheKey);
342
- if (cached) {
343
- return res.json(cached);
344
- }
345
- const result = await pool.query(`
346
- SELECT i.id, i.image_url, i.uploaded_url, i.prompt, i.created_at, i.censored, u.username
347
- FROM images i
348
- JOIN users u ON i.user_id = u.id
349
- ORDER BY i.created_at DESC
350
- LIMIT $1 OFFSET $2
351
- `, [limit, offset]);
352
- cache.set(cacheKey, result.rows);
353
- res.json(result.rows);
354
- } catch (error) {
355
- console.error('Error fetching community images:', error);
356
- res.status(500).json({ error: 'Error fetching community images' });
357
- }
358
- });
359
-
360
- app.get('/api/user-generations', authenticateToken, async (req, res) => {
361
- try {
362
- const userId = req.user.id;
363
- const result = await pool.query(
364
- 'SELECT * FROM user_generations WHERE user_id = $1 AND deleted_at IS NULL ORDER BY created_at DESC',
365
- [userId]
366
- );
367
- res.json(result.rows);
368
- } catch (error) {
369
- console.error('Error fetching user generations:', error);
370
- res.status(500).json({ error: 'Error fetching user generations' });
371
- }
372
- });
373
 
374
- app.delete('/api/user-generations/:id', authenticateToken, async (req, res) => {
375
- try {
376
- const { id } = req.params;
377
- const userId = req.user.id;
378
-
379
- // First, get the image details to find the corresponding community image
380
- const generationResult = await pool.query(
381
- 'SELECT original_url, uploaded_url FROM user_generations WHERE id = $1 AND user_id = $2',
382
- [id, userId]
383
- );
384
-
385
- if (generationResult.rows.length === 0) {
386
- return res.status(404).json({ error: 'Image not found' });
387
- }
388
-
389
- const { original_url, uploaded_url } = generationResult.rows[0];
390
-
391
- // Soft delete from user_generations
392
- await pool.query(
393
- 'UPDATE user_generations SET deleted_at = CURRENT_TIMESTAMP WHERE id = $1 AND user_id = $2',
394
- [id, userId]
395
- );
396
-
397
- // Remove from community images (images table) - fix column name matching
398
- await pool.query(
399
- 'DELETE FROM images WHERE user_id = $1 AND (image_url = $2 OR uploaded_url = $3)',
400
- [userId, original_url, uploaded_url]
401
- );
402
 
403
- res.json({ success: true });
404
- } catch (error) {
405
- console.error('Error deleting generation:', error);
406
- res.status(500).json({ error: 'Error deleting generation' });
407
- }
408
  });
409
 
410
- // Image Generation endpoint (backend only handles Heartsync interaction)
411
- app.post('/api/generate', authenticateToken, async (req, res) => {
412
  res.setHeader('Content-Type', 'text/event-stream');
413
  res.setHeader('Cache-Control', 'no-cache');
414
  res.setHeader('Connection', 'keep-alive');
@@ -529,585 +208,37 @@ app.post('/api/generate', authenticateToken, async (req, res) => {
529
  }
530
  });
531
 
532
- // Anime-UC Generation endpoint (using Heartsync API like original)
533
- app.post('/api/generate/anime-uc', authenticateToken, async (req, res) => {
534
- res.setHeader('Content-Type', 'text/event-stream');
535
- res.setHeader('Cache-Control', 'no-cache');
536
- res.setHeader('Connection', 'keep-alive');
537
-
538
- try {
539
- const { prompt } = req.body;
540
- const sessionHash = Math.random().toString(36).substring(2, 15);
541
-
542
- console.log(`[Anime-UC] Starting generation for prompt: "${prompt}" with session: ${sessionHash}`);
543
-
544
- // First, join the queue using Heartsync API
545
- const joinResponse = await axios.post('https://heartsync-nsfw-uncensored.hf.space/gradio_api/queue/join', {
546
- data: [
547
- prompt,
548
- "text, talk bubble, low quality, watermark, signature",
549
- 0,
550
- true,
551
- 1024,
552
- 1024,
553
- 7,
554
- 28
555
- ],
556
- event_data: null,
557
- fn_index: 2,
558
- trigger_id: 14,
559
- session_hash: sessionHash
560
- }, {
561
- headers: {
562
- 'Content-Type': 'application/json',
563
- 'Referer': 'https://heartsync-nsfw-uncensored.hf.space/'
564
- }
565
- });
566
-
567
- console.log(`[Anime-UC] Queue joined, event_id: ${joinResponse.data?.event_id}`);
568
-
569
- // Poll for results
570
- let attempts = 0;
571
- const maxAttempts = 60; // Heartsync typically faster
572
-
573
- while (attempts < maxAttempts) {
574
- try {
575
- const dataResponse = await axios.get(
576
- `https://heartsync-nsfw-uncensored.hf.space/gradio_api/queue/data?session_hash=${encodeURIComponent(sessionHash)}`,
577
- {
578
- headers: {
579
- 'Accept': 'text/event-stream',
580
- 'Referer': 'https://heartsync-nsfw-uncensored.hf.space/'
581
- },
582
- timeout: 10000 // 10 second timeout
583
- }
584
- );
585
-
586
- const data = dataResponse.data;
587
- console.log(`[Anime-UC] Poll attempt ${attempts + 1}, data length: ${data.length}`);
588
-
589
- // Manually parse the event stream data
590
- const lines = data.split('\n');
591
- let eventData = '';
592
- let foundEvent = false;
593
-
594
- for (const line of lines) {
595
- if (line.startsWith('data: ')) {
596
- eventData += line.substring(6);
597
- } else if (line === '') {
598
- // Process eventData when an empty line is encountered
599
- if (eventData) {
600
- try {
601
- const json = JSON.parse(eventData);
602
- console.log(`[Anime-UC] Parsed event: ${json.msg}`);
603
-
604
- if (json.msg === 'process_completed' && json.output?.data?.[0]?.url) {
605
- const imageUrl = json.output.data[0].url;
606
- console.log(`[Anime-UC] Found image:`, imageUrl);
607
-
608
- // Send the image URL back to the client as an SSE
609
- res.write(`data: ${JSON.stringify({
610
- type: 'success',
611
- originalUrl: imageUrl,
612
- allImages: [imageUrl]
613
- })}\n\n`);
614
- res.end();
615
- return;
616
- }
617
-
618
- if (json.msg === 'estimation') {
619
- res.write(`data: ${JSON.stringify({ type: 'estimation', queueSize: json.queue_size || 0, eta: json.rank_eta || null })}\n\n`);
620
- foundEvent = true;
621
- } else if (json.msg === 'process_starts') {
622
- res.write(`data: ${JSON.stringify({ type: 'processing' })}\n\n`);
623
- foundEvent = true;
624
- }
625
-
626
- } catch (error) {
627
- console.error('[Anime-UC] Error parsing event data:', error, 'Raw data:', eventData);
628
- }
629
- eventData = '';
630
- }
631
- } else if (line.startsWith(':')) {
632
- continue;
633
- } else if (line !== '') {
634
- eventData += line;
635
- }
636
- }
637
-
638
- // If no events were found, log the raw data for debugging
639
- if (!foundEvent && data.trim()) {
640
- console.log(`[Anime-UC] No events found in response, raw data:`, data.substring(0, 500));
641
- }
642
-
643
- } catch (pollError) {
644
- console.error(`[Anime-UC] Poll error on attempt ${attempts + 1}:`, pollError.message);
645
- }
646
-
647
- await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds between polls
648
- attempts++;
649
- }
650
-
651
- console.log(`[Anime-UC] Generation timed out after ${maxAttempts} attempts`);
652
- res.status(500).write(`data: ${JSON.stringify({ type: 'error', message: 'Generation timed out' })}\n\n`);
653
- res.end();
654
-
655
- } catch (error) {
656
- console.error('[Anime-UC] Generation endpoint error:', error);
657
- res.status(500).write(`data: ${JSON.stringify({ type: 'error', message: error.message || 'Failed to generate image' })}\n\n`);
658
- res.end();
659
- }
660
- });
661
-
662
- // Flux Generation endpoint (UNO-FLUX direct API with native fetch SSE polling)
663
- app.get('/api/generate/flux', authenticateToken, async (req, res) => {
664
- try {
665
- const { prompt, aspect } = req.query;
666
- if (!prompt) {
667
- console.error('[Flux] No prompt provided');
668
- return res.status(400).json({ success: false, error: 'Prompt is required' });
669
- }
670
-
671
- // Aspect ratio logic
672
- let width = 1280, height = 720;
673
- if (aspect === '9:16') {
674
- width = 720; height = 1280;
675
- } else if (aspect === '1:1') {
676
- width = 1024; height = 1024;
677
- }
678
-
679
- const sessionHash = Math.random().toString(36).substring(2, 15);
680
- console.log(`[Flux] Starting UNO-FLUX generation for prompt: "${prompt}" | aspect: ${aspect} | width: ${width} | height: ${height} | session: ${sessionHash}`);
681
-
682
- // Join the queue using UNO-FLUX API
683
- const joinPayload = {
684
- data: [
685
- prompt,
686
- width,
687
- height,
688
- 4, // guidance
689
- 25, // num_steps
690
- -1, // seed
691
- null, // image_prompt1
692
- null, // image_prompt2
693
- null, // image_prompt3
694
- null // image_prompt4
695
- ],
696
- event_data: null,
697
- fn_index: 0,
698
- trigger_id: 25,
699
- session_hash: sessionHash
700
- };
701
- console.log('[Flux] Sending queue/join payload:', JSON.stringify(joinPayload));
702
- let joinResponse;
703
- try {
704
- joinResponse = await fetch(
705
- 'https://bytedance-research-uno-flux.hf.space/gradio_api/queue/join?__theme=system',
706
- {
707
- method: 'POST',
708
- headers: {
709
- 'Content-Type': 'application/json',
710
- 'Referer': 'https://bytedance-research-uno-flux.hf.space/',
711
- 'Origin': 'https://bytedance-research-uno-flux.hf.space'
712
- },
713
- body: JSON.stringify(joinPayload)
714
- }
715
- );
716
- const joinData = await joinResponse.json();
717
- console.log('[Flux] queue/join response:', joinData);
718
- } catch (err) {
719
- console.error('[Flux] Error joining UNO-FLUX queue:', err);
720
- return res.status(500).json({ success: false, error: 'Failed to join UNO-FLUX queue' });
721
- }
722
-
723
- // Poll for results using native fetch and streaming
724
- const pollUrl = `https://bytedance-research-uno-flux.hf.space/gradio_api/queue/data?session_hash=${encodeURIComponent(sessionHash)}`;
725
- console.log(`[Flux] Polling for results at: ${pollUrl}`);
726
- let found = false;
727
- let attempts = 0;
728
- const maxAttempts = 60;
729
- let buffer = '';
730
- while (attempts < maxAttempts && !found) {
731
- attempts++;
732
- try {
733
- const response = await fetch(pollUrl, {
734
- headers: {
735
- 'Accept': 'text/event-stream',
736
- 'Referer': 'https://bytedance-research-uno-flux.hf.space/',
737
- 'Origin': 'https://bytedance-research-uno-flux.hf.space'
738
- }
739
- });
740
- if (!response.ok) {
741
- console.error(`[Flux] Poll error on attempt ${attempts}:`, response.status, await response.text());
742
- await new Promise(resolve => setTimeout(resolve, 2000));
743
- continue;
744
- }
745
- // Use Node.js stream reading
746
- for await (const chunk of response.body) {
747
- buffer += chunk.toString('utf8');
748
- const lines = buffer.split('\n');
749
- for (let i = 0; i < lines.length - 1; i++) {
750
- const line = lines[i];
751
- if (line.startsWith('data: ')) {
752
- try {
753
- const json = JSON.parse(line.slice(6));
754
- console.log('[Flux] Event:', json);
755
- if (json.msg === 'process_completed' && json.output?.data?.[0]?.url) {
756
- const imageUrl = json.output.data[0].url;
757
- console.log(`[Flux] Success! Image URL: ${imageUrl}`);
758
- found = true;
759
- return res.json({ success: true, imageUrl });
760
- }
761
- } catch (e) {
762
- console.error('[Flux] Parse error:', e, line);
763
- }
764
- }
765
- }
766
- buffer = lines[lines.length - 1]; // keep incomplete line
767
- }
768
- } catch (pollError) {
769
- console.error(`[Flux] Poll error on attempt ${attempts}:`, pollError);
770
- }
771
- await new Promise(resolve => setTimeout(resolve, 2000));
772
- }
773
- if (!found) {
774
- console.error(`[Flux] Generation timed out after ${maxAttempts} attempts`);
775
- res.status(500).json({ success: false, error: 'Generation timed out' });
776
- }
777
- } catch (error) {
778
- console.error('[Flux] Fatal error in endpoint:', error);
779
- res.status(500).json({ success: false, error: error.message || 'Failed to generate image' });
780
- }
781
- });
782
-
783
- // New endpoint to add community image (handles data from client-side upload)
784
- app.post('/api/add-community-image', authenticateToken, async (req, res) => {
785
- try {
786
- const { originalUrl, uploadedUrl, prompt } = req.body;
787
- const userId = req.user.id;
788
-
789
- if (!originalUrl || !uploadedUrl || !prompt) {
790
- return res.status(400).json({ error: 'Missing required fields' });
791
- }
792
-
793
- // Check censorship
794
- const censored = await checkPromptCensorship(prompt);
795
-
796
- // Save to images table for community gallery
797
- const imageResult = await pool.query(
798
- 'INSERT INTO images (user_id, image_url, uploaded_url, prompt, censored) VALUES ($1, $2, $3, $4, $5) RETURNING *',
799
- [userId, originalUrl, uploadedUrl, prompt, censored]
800
- );
801
-
802
- // Save to user_generations table for user history
803
- const generationResult = await pool.query(
804
- 'INSERT INTO user_generations (user_id, original_url, uploaded_url, prompt) VALUES ($1, $2, $3, $4) RETURNING *',
805
- [userId, originalUrl, uploadedUrl, prompt]
806
- );
807
-
808
- res.json({
809
- success: true,
810
- image: imageResult.rows[0],
811
- generation: generationResult.rows[0]
812
- });
813
- } catch (error) {
814
- console.error('Error adding community image:', error);
815
- res.status(500).json({ error: 'Error adding image to community' });
816
- }
817
- });
818
-
819
- // Auth status endpoint with cache
820
- app.get('/api/auth/status', authenticateToken, async (req, res) => {
821
- try {
822
- const cacheKey = `auth-status:${req.user.id}`;
823
- const cached = cache.get(cacheKey);
824
- if (cached) {
825
- return res.json({ user: cached });
826
- }
827
- const result = await pool.query(
828
- 'SELECT id, username, email FROM users WHERE id = $1',
829
- [req.user.id]
830
- );
831
- if (result.rows.length === 0) {
832
- return res.status(401).json({ error: 'User not found' });
833
- }
834
- cache.set(cacheKey, result.rows[0]);
835
- res.json({ user: result.rows[0] });
836
- } catch (error) {
837
- console.error('Auth status error:', error);
838
- res.status(500).json({ error: 'Error checking auth status' });
839
- }
840
- });
841
-
842
- // Admin endpoints (no authentication required for admin functions)
843
-
844
- // Get image statistics with cache
845
- app.get('/api/admin/stats', async (req, res) => {
846
- try {
847
- const cacheKey = 'admin-stats';
848
- const cached = cache.get(cacheKey);
849
- if (cached) {
850
- return res.json(cached);
851
- }
852
- const totalImages = await pool.query('SELECT COUNT(*) as count FROM images');
853
- const uniqueUsers = await pool.query('SELECT COUNT(DISTINCT user_id) as count FROM images');
854
- const last24Hours = await pool.query(`
855
- SELECT COUNT(*) as count FROM images
856
- WHERE created_at >= NOW() - INTERVAL '24 hours'
857
- `);
858
- const stats = {
859
- totalImages: parseInt(totalImages.rows[0].count),
860
- uniqueUsers: parseInt(uniqueUsers.rows[0].count),
861
- last24Hours: parseInt(last24Hours.rows[0].count)
862
- };
863
- cache.set(cacheKey, stats);
864
- res.json(stats);
865
- } catch (error) {
866
- console.error('Error getting admin stats:', error);
867
- res.status(500).json({ error: 'Error getting statistics' });
868
- }
869
- });
870
-
871
- // Delete single image (admin)
872
- app.delete('/api/admin/images/:id', async (req, res) => {
873
- try {
874
- const { id } = req.params;
875
-
876
- // Delete from images table
877
- const result = await pool.query('DELETE FROM images WHERE id = $1 RETURNING *', [id]);
878
-
879
- if (result.rows.length === 0) {
880
- return res.status(404).json({ error: 'Image not found' });
881
- }
882
-
883
- // Also delete from user_generations if it exists
884
- await pool.query(
885
- 'DELETE FROM user_generations WHERE original_url = $1 OR uploaded_url = $2',
886
- [result.rows[0].image_url, result.rows[0].uploaded_url]
887
- );
888
-
889
- res.json({ success: true, message: 'Image deleted successfully' });
890
- } catch (error) {
891
- console.error('Error deleting image:', error);
892
- res.status(500).json({ error: 'Error deleting image' });
893
- }
894
- });
895
-
896
- // Delete all images (admin)
897
- app.delete('/api/admin/images', async (req, res) => {
898
- try {
899
- // Delete all images from images table
900
- await pool.query('DELETE FROM images');
901
-
902
- // Clear user_generations table (soft delete all)
903
- await pool.query('UPDATE user_generations SET deleted_at = CURRENT_TIMESTAMP WHERE deleted_at IS NULL');
904
-
905
- res.json({ success: true, message: 'All images deleted successfully' });
906
- } catch (error) {
907
- console.error('Error deleting all images:', error);
908
- res.status(500).json({ error: 'Error deleting all images' });
909
- }
910
- });
911
-
912
- // Export all images data (admin)
913
- app.get('/api/admin/export', async (req, res) => {
914
- try {
915
- const result = await pool.query(`
916
- SELECT i.id, i.image_url, i.uploaded_url, i.prompt, i.created_at, i.censored, u.username
917
- FROM images i
918
- JOIN users u ON i.user_id = u.id
919
- ORDER BY i.created_at DESC
920
- `);
921
- const exportData = {
922
- images: result.rows,
923
- exportDate: new Date().toISOString(),
924
- totalImages: result.rows.length,
925
- uniqueUsers: new Set(result.rows.map(img => img.username)).size
926
- };
927
- res.setHeader('Content-Type', 'application/json');
928
- res.setHeader('Content-Disposition', `attachment; filename="community-images-${new Date().toISOString().split('T')[0]}.json"`);
929
- res.json(exportData);
930
- } catch (error) {
931
- console.error('Error exporting data:', error);
932
- res.status(500).json({ error: 'Error exporting data' });
933
- }
934
- });
935
-
936
- // Bulk update images (admin, no auth)
937
- app.post('/api/admin/bulk-update-images', async (req, res) => {
938
- try {
939
- const images = req.body;
940
- if (!Array.isArray(images)) {
941
- return res.status(400).json({ error: 'Request body must be an array of images' });
942
- }
943
- let updated = 0, inserted = 0, errors = [];
944
- for (const img of images) {
945
- if (!img.id || !img.image_url || !img.uploaded_url) {
946
- errors.push({ id: img.id, error: 'Missing id, image_url, or uploaded_url' });
947
- continue;
948
- }
949
- try {
950
- // Try to update
951
- let updateFields = ['image_url = $1', 'uploaded_url = $2'];
952
- let updateValues = [img.image_url, img.uploaded_url, img.id];
953
- let paramIdx = 3;
954
- if (typeof img.prompt === 'string') {
955
- updateFields.push(`prompt = $${paramIdx}`);
956
- updateValues.splice(paramIdx - 1, 0, img.prompt);
957
- paramIdx++;
958
- }
959
- if (typeof img.censored === 'boolean') {
960
- updateFields.push(`censored = $${paramIdx}`);
961
- updateValues.splice(paramIdx - 1, 0, img.censored);
962
- paramIdx++;
963
- }
964
- const updateResult = await pool.query(
965
- `UPDATE images SET ${updateFields.join(', ')} WHERE id = $${paramIdx} RETURNING *`,
966
- updateValues
967
- );
968
- if (updateResult.rowCount > 0) {
969
- updated++;
970
- } else {
971
- // Insert if not found
972
- const insertFields = ['id', 'image_url', 'uploaded_url'];
973
- const insertValues = [img.id, img.image_url, img.uploaded_url];
974
- const insertParams = ['$1', '$2', '$3'];
975
- let insertIdx = 4;
976
- if (typeof img.prompt === 'string') {
977
- insertFields.push('prompt');
978
- insertValues.push(img.prompt);
979
- insertParams.push(`$${insertIdx++}`);
980
- }
981
- if (typeof img.censored === 'boolean') {
982
- insertFields.push('censored');
983
- insertValues.push(img.censored);
984
- insertParams.push(`$${insertIdx++}`);
985
- }
986
- await pool.query(
987
- `INSERT INTO images (${insertFields.join(', ')}) VALUES (${insertParams.join(', ')})`,
988
- insertValues
989
- );
990
- inserted++;
991
- }
992
- } catch (e) {
993
- errors.push({ id: img.id, error: e.message });
994
- }
995
- }
996
- res.json({ updated, inserted, errors });
997
- } catch (error) {
998
- console.error('Bulk update error:', error);
999
- res.status(500).json({ error: 'Bulk update failed' });
1000
- }
1001
- });
1002
-
1003
- // Admin endpoint to process all old images for censorship
1004
- app.post('/api/admin/process-old', async (req, res) => {
1005
- try {
1006
- // Get all images
1007
- const result = await pool.query('SELECT id, prompt FROM images');
1008
- let updated = 0, errors = [];
1009
- for (const img of result.rows) {
1010
- try {
1011
- const censored = await checkPromptCensorship(img.prompt);
1012
- await pool.query('UPDATE images SET censored = $1 WHERE id = $2', [censored, img.id]);
1013
- updated++;
1014
- } catch (e) {
1015
- errors.push({ id: img.id, error: e.message });
1016
- }
1017
- }
1018
- res.json({ updated, errors });
1019
- } catch (error) {
1020
- console.error('Process-old error:', error);
1021
- res.status(500).json({ error: 'Failed to process old images' });
1022
- }
1023
- });
1024
-
1025
- // Proxy route for HuggingFace/Gradio images (update to allow UNO-FLUX output URLs)
1026
- app.get('/proxy-image', async (req, res) => {
1027
- const { url, proxied } = req.query;
1028
- if (!url) {
1029
- return res.status(400).send('Missing url parameter');
1030
- }
1031
- // Allow proxying from yanze-pulid-flux.hf.space and UNO-FLUX output URLs
1032
- if (!url.startsWith('https://yanze-pulid-flux.hf.space/') && !url.startsWith('https://hf.space/')) {
1033
- return res.status(403).send('Forbidden: Only allowed to proxy from yanze-pulid-flux.hf.space or hf.space');
1034
- }
1035
- try {
1036
- const response = await fetch(url, {
1037
- method: 'GET',
1038
- headers: {
1039
- 'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
1040
- 'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8,hi;q=0.7',
1041
- 'Cache-Control': 'no-cache',
1042
- 'Pragma': 'no-cache',
1043
- 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36',
1044
- }
1045
- });
1046
- if (!response.ok) {
1047
- return res.status(response.status).send('Failed to fetch image');
1048
- }
1049
- res.set('Access-Control-Allow-Origin', '*');
1050
- res.set('Access-Control-Allow-Credentials', 'true');
1051
- res.set('Content-Type', response.headers.get('content-type') || 'image/png');
1052
- res.set('Content-Disposition', response.headers.get('content-disposition') || 'inline');
1053
- // If proxied param is set, respond with the proxied URL
1054
- if (proxied === '1') {
1055
- const proxiedUrl = `https://shashwatidr-vision.hf.space/proxy-image?url=${encodeURIComponent(url)}`;
1056
- return res.json({ proxiedUrl });
1057
- }
1058
- response.body.pipe(res);
1059
- } catch (err) {
1060
- res.status(500).send('Proxy error: ' + err.message);
1061
- }
1062
- });
1063
-
1064
- // UNO-FLUX model generation endpoint
1065
- app.post('/api/generate/uno-flux', async (req, res) => {
1066
  try {
1067
  const {
1068
- prompt = "handsome woman in the city",
1069
- width = 512,
1070
- height = 512,
1071
- guidance = 4,
1072
- num_steps = 25,
1073
- seed = -1,
1074
- image_prompt1,
1075
- image_prompt2,
1076
- image_prompt3,
1077
- image_prompt4
1078
  } = req.body;
1079
 
1080
- // Helper to fetch image as blob
1081
- async function fetchImageBlob(url) {
1082
- const response = await fetch(url);
1083
- if (!response.ok) throw new Error('Failed to fetch image: ' + url);
1084
- return await response.blob();
1085
  }
1086
 
1087
- // Fetch all image prompts as blobs
1088
- const [img1, img2, img3, img4] = await Promise.all([
1089
- fetchImageBlob(image_prompt1),
1090
- fetchImageBlob(image_prompt2),
1091
- fetchImageBlob(image_prompt3),
1092
- fetchImageBlob(image_prompt4)
1093
- ]);
1094
-
1095
- // Connect to UNO-FLUX Gradio client
1096
- const client = await Client.connect("bytedance-research/UNO-FLUX");
1097
- const result = await client.predict("/gradio_generate", {
1098
  prompt,
 
 
1099
  width,
1100
  height,
1101
- guidance,
1102
- num_steps,
1103
- seed,
1104
- image_prompt1: img1,
1105
- image_prompt2: img2,
1106
- image_prompt3: img3,
1107
- image_prompt4: img4
1108
  });
1109
 
1110
- res.json({ success: true, data: result.data });
 
1111
  } catch (err) {
1112
  res.status(500).json({ success: false, error: err.message });
1113
  }
 
1
  import express from 'express';
 
 
2
  import axios from 'axios';
3
  import { Client } from '@gradio/client';
4
  import dotenv from 'dotenv';
 
 
 
 
 
 
5
 
6
  dotenv.config();
7
 
8
  // --- Hugging Face Space Auto-Restarter ---
9
+ const HF_TOKEN = process.env.HF_TOKEN;
10
  const SPACE_ID = process.env.HF_SPACE_ID || 'shashwatIDR/vision';
11
  const HF_API_BASE = 'https://huggingface.co/api';
12
 
 
74
  console.log('[⏰ Scheduled] Space will restart every 5 minutes');
75
  })();
76
 
 
 
77
  const app = express();
78
  const port = process.env.PORT || 3000;
 
 
 
79
  app.use(express.json());
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ // Serve static files from public
82
+ app.use(express.static('public'));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
+ // Serve index.html at root
85
+ app.get('/', (req, res) => {
86
+ res.sendFile(__dirname + '/public/index.html');
 
 
87
  });
88
 
89
+ // Image Generation endpoint (Heartsync)
90
+ app.post('/api/generate', async (req, res) => {
91
  res.setHeader('Content-Type', 'text/event-stream');
92
  res.setHeader('Cache-Control', 'no-cache');
93
  res.setHeader('Connection', 'keep-alive');
 
208
  }
209
  });
210
 
211
+ // Flux model generation endpoint using black-forest-labs/FLUX.1-dev Gradio client
212
+ app.post('/api/generate/flux', async (req, res) => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  try {
214
  const {
215
+ prompt = '',
216
+ width = 1024,
217
+ height = 1024,
218
+ guidance_scale = 3.5,
219
+ num_inference_steps = 28,
220
+ seed = 0,
221
+ randomize_seed = true
 
 
 
222
  } = req.body;
223
 
224
+ if (!prompt) {
225
+ return res.status(400).json({ success: false, error: 'Prompt is required' });
 
 
 
226
  }
227
 
228
+ // Connect to FLUX.1-dev Gradio client
229
+ const client = await Client.connect("black-forest-labs/FLUX.1-dev");
230
+ const result = await client.predict("/infer", {
 
 
 
 
 
 
 
 
231
  prompt,
232
+ seed,
233
+ randomize_seed,
234
  width,
235
  height,
236
+ guidance_scale,
237
+ num_inference_steps
 
 
 
 
 
238
  });
239
 
240
+ // result.data: [imageUrl, seed]
241
+ res.json({ success: true, image: result.data[0], seed: result.data[1] });
242
  } catch (err) {
243
  res.status(500).json({ success: false, error: err.message });
244
  }