Spaces:
Lakshay3605
/
Sleeping

File size: 29,544 Bytes
c50284e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
import fetch from 'node-fetch';
import express from 'express';
import cors from 'cors';
import fs from 'fs/promises';
import fsSync from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { randomUUID } from 'crypto';
import { exec } from 'child_process';
import util from 'util';

const execPromise = util.promisify(exec);

const PORT = 3000;
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const HISTORY_FILE = path.join(__dirname, 'posting_history.json');

// Local cache directory for downloaded HF images β€” served as static files
const OUTPUTS_DIR = path.join(__dirname, 'outputs');
fsSync.mkdirSync(OUTPUTS_DIR, { recursive: true });

// Path to Python CLI and CWD
const INSTAGRAM_CWD = path.join(__dirname, '..', 'INSTAGRAM', 'INSTAGRAM');
const PYTHON_EXE = process.platform === 'win32'
  ? path.join(INSTAGRAM_CWD, '.venv', 'Scripts', 'python.exe')
  : path.join(INSTAGRAM_CWD, '.venv', 'bin', 'python');

function loadEnv() {
  try {
    const envPath = path.join(INSTAGRAM_CWD, '.env');
    if (fsSync.existsSync(envPath)) {
      const content = fsSync.readFileSync(envPath, 'utf-8');
      content.split('\n').forEach(line => {
        const parts = line.split('=');
        if (parts.length >= 2) {
          const key = parts[0].trim();
          const val = parts.slice(1).join('=').trim().replace(/^["']|["']$/g, '');
          process.env[key] = val;
        }
      });
    }
  } catch (err) {
    console.error('Failed to load .env file:', err);
  }
}
loadEnv();


async function readHistory() {
  try {
    const raw = await fs.readFile(HISTORY_FILE, 'utf-8');
    const data = JSON.parse(raw);
    return Array.isArray(data) ? data : [];
  } catch (err) {
    if (err.code === 'ENOENT') return [];
    throw err;
  }
}

async function writeHistory(posts) {
  await fs.writeFile(HISTORY_FILE, JSON.stringify(posts, null, 2), 'utf-8');
}

async function appendHistory(entry) {
  const posts = await readHistory();
  posts.unshift(entry);
  await writeHistory(posts);
}

function isHttpUrl(str) {
  try {
    const u = new URL(str.trim());
    return u.protocol === 'http:' || u.protocol === 'https:';
  } catch {
    return false;
  }
}

const PROBE_HEADERS = {
  'User-Agent':
    'Mozilla/5.0 (compatible; FashionAI-Bot/1.0; +https://github.com/sharjilsharma)',
  Accept: 'image/*,*/*;q=0.8',
};

async function fetchImageProbe(url) {
  // Hugging Face /file= paths are short-lived, auth-gated, and often return 404
  // on probe requests even when valid. Trust them without probing.
  if (url.includes('hf.space') || url.includes('huggingface.co')) {
    console.log(`[probe] Skipping probe for HF URL (trusted): ${url}`);
    return { ok: true, status: 200 };
  }

  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 10000);
  try {
    const headers = { ...PROBE_HEADERS };
    // Hugging Face proxy returns 200 OK for HEAD even on 404 paths.
    // Use GET with Range by default to fetch only the start of the image.
    let res = await fetch(url, {
      method: 'GET',
      redirect: 'follow',
      headers: { ...headers, Range: 'bytes=0-1023' },
      signal: controller.signal,
    });
    if (res.status === 405 || res.status === 501) {
      res = await fetch(url, {
        method: 'GET',
        redirect: 'follow',
        headers: headers,
        signal: controller.signal,
      });
    }
    if (!res.ok) {
      return { ok: false, status: res.status, error: `URL returned HTTP ${res.status}` };
    }
    return { ok: true, status: res.status };
  } finally {
    clearTimeout(timer);
  }
}

async function validateImageUrl(url) {
  const trimmed = url.trim();
  if (!trimmed) {
    return { url: trimmed, ok: false, error: 'URL is empty' };
  }
  if (trimmed.startsWith('data:image/') || trimmed.includes(';base64,')) {
    return { url: '[Local File]', ok: true };
  }
  if (!isHttpUrl(trimmed)) {
    return { url: trimmed, ok: false, error: 'Invalid URL β€” must start with http:// or https://' };
  }
  try {
    return { url: trimmed, ...(await fetchImageProbe(trimmed)) };
  } catch (err) {
    if (err.name === 'AbortError') {
      return { url: trimmed, ok: true, warning: 'URL check timed out β€” proceeding anyway' };
    }
    return { url: trimmed, ok: false, error: err.message };
  }
}

async function validateImageUrls(urls) {
  const unique = [...new Set(urls.map((u) => u.trim()).filter(Boolean))];
  const results = await Promise.all(unique.map((url) => validateImageUrl(url)));
  return results;
}

// Shared helper: download an HF image server-side and save it to the local
// outputs cache. Returns a stable localhost URL that never expires.
async function cacheHfImageLocally(remoteUrl, prefix = 'img') {
  if (!remoteUrl) return null;
  try {
    const hfToken = (process.env.HF_TOKEN || '').trim();
    const dlHeaders = { ...PROBE_HEADERS };
    if ((remoteUrl.includes('hf.space') || remoteUrl.includes('huggingface.co')) && hfToken) {
      dlHeaders['Authorization'] = `Bearer ${hfToken}`;
    }
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), 30000);
    let dlRes;
    try {
      dlRes = await fetch(remoteUrl, { method: 'GET', redirect: 'follow', headers: dlHeaders, signal: controller.signal });
    } finally {
      clearTimeout(timer);
    }
    if (!dlRes.ok) {
      console.warn(`[cache] Download failed HTTP ${dlRes.status} for ${remoteUrl}`);
      return null;
    }
    const contentType = dlRes.headers.get('content-type') || 'image/jpeg';
    const extMap = { 'image/jpeg': '.jpg', 'image/png': '.png', 'image/webp': '.webp', 'image/gif': '.gif' };
    const ext = extMap[contentType.split(';')[0].trim()] || '.jpg';
    const filename = `${prefix}_${randomUUID()}${ext}`;
    const localPath = path.join(OUTPUTS_DIR, filename);
    const buf = await dlRes.arrayBuffer();
    await fs.writeFile(localPath, Buffer.from(buf));
    const localUrl = `http://localhost:${PORT}/outputs/${filename}`;
    console.log(`[cache] Saved ${remoteUrl} β†’ ${localUrl}`);
    return { filename, localUrl };
  } catch (err) {
    console.warn(`[cache] Failed to cache ${remoteUrl}: ${err.message}`);
    return null;
  }
}

const app = express();
app.use(cors());
app.use(express.json({ limit: '50mb' }));
// Serve locally cached try-on images β€” stable URLs that never expire
app.use('/outputs', express.static(OUTPUTS_DIR));

app.get('/', async (_req, res) => {
  try {
    const htmlPath = path.join(__dirname, 'index.html');
    const html = await fs.readFile(htmlPath, 'utf-8');
    res.type('html').send(html);
  } catch (err) {
    res.status(500).send(`Failed to load UI: ${err.message}`);
  }
});

// Proxy endpoint: downloads an image from a remote URL (e.g. HF Space) server-side
// and streams it back to the client. Avoids CORS issues and browser auth restrictions.
app.get('/api/proxy-image', async (req, res) => {
  const { url } = req.query;
  if (!url || !isHttpUrl(url)) {
    return res.status(400).json({ error: 'Missing or invalid url query parameter' });
  }
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), 30000);
  try {
    const headers = { ...PROBE_HEADERS };
    const hfToken = process.env.HF_TOKEN;
    if ((url.includes('hf.space') || url.includes('huggingface.co')) && hfToken) {
      headers['Authorization'] = `Bearer ${hfToken}`;
    }
    const upstream = await fetch(url, {
      method: 'GET',
      redirect: 'follow',
      headers,
      signal: controller.signal,
    });
    clearTimeout(timer);
    if (!upstream.ok) {
      return res.status(upstream.status).json({ error: `Upstream returned HTTP ${upstream.status}` });
    }
    const contentType = upstream.headers.get('content-type') || 'image/jpeg';
    res.setHeader('Content-Type', contentType);
    res.setHeader('Cache-Control', 'no-store');
    // Stream the body directly to the client
    upstream.body.pipe(res);
  } catch (err) {
    clearTimeout(timer);
    if (err.name === 'AbortError') {
      return res.status(504).json({ error: 'Proxy request timed out' });
    }
    console.error('[proxy-image] Error:', err);
    res.status(500).json({ error: err.message });
  }
});

app.get('/api/status', async (_req, res) => {
  const sessionPath = path.join(INSTAGRAM_CWD, 'session.json');
  let token_valid = false;
  try {
    await fs.access(sessionPath);
    token_valid = true;
  } catch {}
  res.json({
    status: 'ok',
    token_valid,
  });
});

app.get('/api/fetch-latest', async (req, res) => {
  try {
    const hfSpaceUrl = process.env.HF_SPACE_URL || 'https://lakshay3605-automatic-uploader.hf.space';
    const hfToken = (process.env.HF_TOKEN || '').trim();
    const headers = {};
    if (hfToken) headers['Authorization'] = `Bearer ${hfToken}`;

    const apiEndpoint = `${hfSpaceUrl.replace(/\/$/, '')}/api/latest-image`;
    console.log(`[fetch-latest] Requesting latest image from: ${apiEndpoint}`);
    const response = await fetch(apiEndpoint, { method: 'GET', headers });
    if (!response.ok) {
      const errText = await response.text();
      return res.status(response.status).json({
        success: false,
        error: `Hugging Face space returned HTTP ${response.status}: ${errText}`
      });
    }
    const data = await response.json();

    let finalUrl, filename;

    if (data.image_data) {
      // New protocol: HF Space returns base64 image data directly β€” write to local cache
      const base64Data = data.image_data.includes(',') ? data.image_data.split(',')[1] : data.image_data;
      filename = `latest_${randomUUID()}.jpg`;
      const localPath = path.join(OUTPUTS_DIR, filename);
      await fs.writeFile(localPath, Buffer.from(base64Data, 'base64'));
      finalUrl = `http://localhost:${PORT}/outputs/${filename}`;
      console.log(`[fetch-latest] Saved base64 image to: ${localPath}`);
    } else if (data.image_url) {
      // Legacy protocol: try to cache the URL (may fail if Space restarted)
      const cached = await cacheHfImageLocally(data.image_url, 'latest');
      finalUrl = cached?.localUrl || data.image_url;
      filename = cached?.filename || data.output_filename;
    } else {
      return res.status(500).json({ success: false, error: 'No image data returned from Space' });
    }

    console.log(`[fetch-latest] Serving cached image at: ${finalUrl}`);
    res.json({
      success: true,
      image_url: finalUrl,
      output_filename: filename || data.output_filename
    });
  } catch (err) {
    console.error('[fetch-latest] Failed to retrieve latest image:', err);
    res.status(500).json({ success: false, error: err.message });
  }
});

app.post('/api/generate-tryon', async (req, res) => {
  try {
    const { human_image, garment_image, garment_description } = req.body ?? {};
    if (!human_image || !garment_image || !garment_description) {
      return res.status(400).json({ success: false, error: 'human_image, garment_image, and garment_description are required' });
    }

    const hfSpaceUrl = (process.env.HF_SPACE_URL || 'https://lakshay3605-automatic-uploader.hf.space').replace(/\/$/, '');
    const hfToken = process.env.HF_TOKEN;

    const authHeaders = {};
    if (hfToken) {
      authHeaders['Authorization'] = `Bearer ${hfToken}`;
    }

    // --- Helper: convert data URI to a Blob for upload ---
    function dataUriToBlob(dataUri) {
      const parts = dataUri.split(',');
      const meta = parts[0]; // e.g. "data:image/jpeg;base64"
      const raw = parts[1];
      const mime = meta.match(/:(.*?);/)?.[1] || 'image/jpeg';
      const ext = mime.split('/')[1] || 'jpg';
      const buffer = Buffer.from(raw, 'base64');
      return { buffer, mime, ext };
    }

    // --- Helper: upload a single image to Gradio's /upload endpoint ---
    async function uploadToGradio(dataUri, filename) {
      const { buffer, mime, ext } = dataUriToBlob(dataUri);
      const fname = filename || `upload.${ext}`;
      
      const blob = new Blob([buffer], { type: mime });
      const formData = new FormData();
      formData.append('files', blob, fname);

      console.log(`[generate-tryon] Uploading ${fname} (${buffer.length} bytes, ${mime}) to ${hfSpaceUrl}/upload`);
      
      const uploadRes = await fetch(`${hfSpaceUrl}/upload`, {
        method: 'POST',
        headers: { ...authHeaders },
        body: formData
      });

      if (!uploadRes.ok) {
        const errText = await uploadRes.text();
        throw new Error(`Upload failed HTTP ${uploadRes.status}: ${errText}`);
      }

      const uploadResult = await uploadRes.json();
      console.log(`[generate-tryon] Upload result:`, JSON.stringify(uploadResult));
      // Returns array of file paths, e.g. ["/tmp/gradio/abc/image.jpg"]
      if (Array.isArray(uploadResult) && uploadResult.length > 0) {
        return uploadResult[0];
      }
      throw new Error(`Unexpected upload response: ${JSON.stringify(uploadResult)}`);
    }

    // Step 1: Upload both images to the Gradio server
    console.log(`[generate-tryon] Step 1: Uploading images to Gradio...`);
    const [humanPath, garmentPath] = await Promise.all([
      uploadToGradio(human_image, 'human.jpg'),
      uploadToGradio(garment_image, 'garment.jpg')
    ]);
    console.log(`[generate-tryon] Human path: ${humanPath}, Garment path: ${garmentPath}`);

    // Step 2: POST to /call/tryon with file paths
    const callEndpoint = `${hfSpaceUrl}/call/tryon`;
    console.log(`[generate-tryon] Step 2: Calling ${callEndpoint} with uploaded file paths...`);

    // Gradio 4.x /call/ format: image inputs as {path: "...", meta: {_type: "gradio.FileData"}}
    const humanFileData = { path: humanPath, meta: { _type: "gradio.FileData" } };
    const garmentFileData = { path: garmentPath, meta: { _type: "gradio.FileData" } };

    // start_tryon_wrapper inputs: [imgs, garm_img, prompt, is_checked, is_checked_crop, denoise_steps, seed, auto_post_instagram, instagram_caption]
    const gradioPayload = {
      data: [
        // imgs (ImageEditor): dict with background, layers, composite
        { background: humanFileData, layers: [], composite: null },
        // garm_img (Image)
        garmentFileData,
        // garment_des (Textbox)
        garment_description,
        // is_checked (Checkbox)
        true,
        // is_checked_crop (Checkbox)
        false,
        // denoise_steps (Number)
        30,
        // seed (Number)
        42,
        // auto_post_instagram (Checkbox)
        false,
        // instagram_caption (Textbox)
        ""
      ]
    };

    const callResponse = await fetch(callEndpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', ...authHeaders },
      body: JSON.stringify(gradioPayload)
    });

    if (!callResponse.ok) {
      const errText = await callResponse.text();
      return res.status(callResponse.status).json({
        success: false,
        error: `Gradio /call/ initiation failed HTTP ${callResponse.status}: ${errText}`
      });
    }

    const callResult = await callResponse.json();
    const eventId = callResult.event_id;
    if (!eventId) {
      return res.status(500).json({
        success: false,
        error: `Gradio /call/ did not return event_id: ${JSON.stringify(callResult)}`
      });
    }
    console.log(`[generate-tryon] Step 3: Got event_id=${eventId}, polling SSE stream...`);

    // Step 3: GET /call/tryon/<event_id> as SSE stream
    const sseEndpoint = `${callEndpoint}/${eventId}`;

    const sseController = new AbortController();
    const sseTimer = setTimeout(() => sseController.abort(), 300000); // 5 min timeout

    let sseResponse;
    try {
      sseResponse = await fetch(sseEndpoint, {
        method: 'GET',
        headers: { ...authHeaders },
        signal: sseController.signal
      });
    } catch (fetchErr) {
      clearTimeout(sseTimer);
      if (fetchErr.name === 'AbortError') {
        return res.status(504).json({ success: false, error: 'Try-on generation timed out (5 min). The Space may be overloaded.' });
      }
      throw fetchErr;
    }

    if (!sseResponse.ok) {
      clearTimeout(sseTimer);
      const errText = await sseResponse.text();
      return res.status(sseResponse.status).json({
        success: false,
        error: `Gradio SSE stream failed HTTP ${sseResponse.status}: ${errText}`
      });
    }

    // Parse SSE stream to get the final result
    const sseText = await sseResponse.text();
    clearTimeout(sseTimer);

    // Log raw SSE for debugging
    console.log(`[generate-tryon] Raw SSE response (first 2000 chars):\n${sseText.substring(0, 2000)}`);

    // Parse SSE events into a map of { eventType -> dataStr }
    const sseEvents = [];
    const lines = sseText.split('\n');
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i].trim();
      if (line.startsWith('event:')) {
        const eventType = line.substring(6).trim();
        const dataLine = lines[i + 1]?.trim() ?? '';
        const dataStr = dataLine.startsWith('data:') ? dataLine.substring(5).trim() : '';
        console.log(`[generate-tryon] SSE event: ${eventType}, data preview: ${dataStr.substring(0, 300)}`);
        sseEvents.push({ eventType, dataStr });
      }
    }

    const errorEvent = sseEvents.find(e => e.eventType === 'error');
    const completeEvent = sseEvents.find(e => e.eventType === 'complete');

    if (errorEvent) {
      // Try to extract a meaningful message from the error data
      let errMsg = 'Gradio job failed';
      if (errorEvent.dataStr && errorEvent.dataStr !== 'null') {
        try {
          const parsed = JSON.parse(errorEvent.dataStr);
          errMsg = parsed?.message || parsed?.error || JSON.stringify(parsed);
        } catch {
          errMsg = errorEvent.dataStr;
        }
      } else {
        // data: null means Gradio killed the job (ZeroGPU timeout, OOM, Space restart, etc.)
        // Check if there's a useful message in any other event
        const anyMsg = sseEvents.find(e => e.dataStr && e.dataStr !== 'null' && e.eventType !== 'heartbeat');
        errMsg = anyMsg
          ? `Gradio job failed (data: null). Last event data: ${anyMsg.dataStr.substring(0, 300)}`
          : 'Gradio job failed: the Space returned a null error β€” this usually means a ZeroGPU timeout, out-of-memory, or the Space restarted. Try again.';
      }
      return res.status(500).json({ success: false, error: errMsg });
    }

    let gradioData = null;
    if (completeEvent) {
      try {
        gradioData = JSON.parse(completeEvent.dataStr);
      } catch (parseErr) {
        console.error('[generate-tryon] Failed to parse SSE complete data:', parseErr);
      }
    }

    if (!gradioData || !Array.isArray(gradioData)) {
      return res.status(500).json({
        success: false,
        error: `Gradio returned no complete event. Raw SSE: ${sseText.substring(0, 500)}`
      });
    }

    // gradioData is a list of outputs: [image_out, masked_img, instagram_status, last_output_path_state]
    const imageOut = gradioData[0];
    const maskedImg = gradioData[1];

    // Extract image URL from Gradio output
    let imageUrl = null;
    if (imageOut) {
      if (typeof imageOut === 'string') {
        imageUrl = imageOut;
      } else if (imageOut.url) {
        imageUrl = imageOut.url;
      } else if (imageOut.path) {
        imageUrl = `${hfSpaceUrl}/file=${imageOut.path}`;
      }
    }

    if (!imageUrl) {
      return res.status(500).json({
        success: false,
        error: `Could not extract image URL from Gradio response: ${JSON.stringify(gradioData).substring(0, 500)}`
      });
    }

    // If the URL is relative, make it absolute
    if (imageUrl.startsWith('/')) {
      imageUrl = `${hfSpaceUrl}${imageUrl}`;
    }

    let maskUrl = null;
    if (maskedImg) {
      if (typeof maskedImg === 'string') {
        maskUrl = maskedImg;
      } else if (maskedImg.url) {
        maskUrl = maskedImg.url;
      } else if (maskedImg.path) {
        maskUrl = `${hfSpaceUrl}/file=${maskedImg.path}`;
      }
    }
    if (maskUrl && maskUrl.startsWith('/')) {
      maskUrl = `${hfSpaceUrl}${maskUrl}`;
    }

    console.log(`[generate-tryon] Success! Remote image URL: ${imageUrl}`);

    // Cache both images immediately using the shared helper
    const [cachedMain, cachedMask] = await Promise.all([
      cacheHfImageLocally(imageUrl, 'tryon'),
      cacheHfImageLocally(maskUrl, 'mask'),
    ]);

    const finalImageUrl = cachedMain?.localUrl || imageUrl;
    const finalMaskUrl  = cachedMask?.localUrl  || maskUrl;
    const outputFilename = cachedMain?.filename ||
      (imageOut?.path ? imageOut.path.split('/').pop() : 'tryon_output.jpg');

    console.log(`[generate-tryon] Serving cached image at: ${finalImageUrl}`);
    res.json({
      success: true,
      image_url: finalImageUrl,
      mask_url: finalMaskUrl,
      output_filename: outputFilename
    });

  } catch (err) {
    console.error('[generate-tryon] Failed to generate try-on:', err);
    res.status(500).json({ success: false, error: err.message });
  }
});

app.get('/api/history', async (_req, res) => {
  try {
    const posts = await readHistory();
    res.json({ total: posts.length, posts });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

app.post('/api/validate-images', async (req, res) => {
  try {
    const { urls } = req.body ?? {};
    const startedAt = Date.now();
    if (!Array.isArray(urls)) {
      return res.status(400).json({ success: false, error: 'urls must be an array' });
    }
    const results = await validateImageUrls(urls);
    const all_ok = results.every((r) => r.ok);
    console.log(
      `[validate-images] urls=${urls.length} all_ok=${all_ok} elapsed_ms=${Date.now() - startedAt}`
    );
    res.json({ success: true, all_ok, results });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

app.post('/api/post', async (req, res) => {
  const startedAt = Date.now();
  const { images, caption, thumbnail_url } = req.body ?? {};

  if (!Array.isArray(images) || images.length === 0) {
    return res.status(400).json({
      success: false,
      error: 'images must be a non-empty array',
    });
  }

  if (typeof caption !== 'string' || !caption.trim()) {
    return res.status(400).json({
      success: false,
      error: 'caption is required',
    });
  }

  const validImages = images.filter((u) => typeof u === 'string' && u.trim());
  if (validImages.length === 0) {
    return res.status(400).json({
      success: false,
      error: 'images must contain at least one valid URL or Base64 file',
    });
  }

  // Prepare images list including optional thumbnail
  let finalImages = [...validImages];
  if (thumbnail_url?.trim() && !finalImages.includes(thumbnail_url.trim())) {
    finalImages.unshift(thumbnail_url.trim());
  }

  if (finalImages.length > 10) {
    return res.status(400).json({
      success: false,
      error: 'maximum 10 images allowed',
    });
  }

  // Pre-validate images
  const validation = await validateImageUrls(finalImages);
  const failed = validation.filter((r) => !r.ok);
  if (failed.length) {
    const details = failed.map((r) => `${r.url}: ${r.error}`).join('; ');
    return res.status(400).json({
      success: false,
      error: `One or more image URLs are not reachable: ${details}`,
      failed_urls: failed,
    });
  }

  // Write payload to a temporary JSON file to avoid command-line arg limit and encoding issues
  const tempFilename = `upload_request_${randomUUID()}.json`;
  const tempDownloadsDir = path.join(INSTAGRAM_CWD, 'tmp_downloads');
  const tempFilePath = path.join(tempDownloadsDir, tempFilename);

  const filePaths = [];
  const localTempFiles = [];

  try {
    // Ensure tmp_downloads exists
    await fs.mkdir(tempDownloadsDir, { recursive: true });

    // Helper: download a remote URL server-side and save to a local temp file.
    // Used for HF Space URLs which are short-lived and auth-gated.
    async function downloadRemoteImage(url) {
      const hfToken = (process.env.HF_TOKEN || '').trim();
      const dlHeaders = { ...PROBE_HEADERS };
      if ((url.includes('hf.space') || url.includes('huggingface.co')) && hfToken) {
        dlHeaders['Authorization'] = `Bearer ${hfToken}`;
      }
      const controller = new AbortController();
      const timer = setTimeout(() => controller.abort(), 30000);
      try {
        const dlRes = await fetch(url, { method: 'GET', redirect: 'follow', headers: dlHeaders, signal: controller.signal });
        if (!dlRes.ok) throw new Error(`Remote image download failed HTTP ${dlRes.status} for ${url}`);
        const contentType = dlRes.headers.get('content-type') || 'image/jpeg';
        const extMap = { 'image/jpeg': '.jpg', 'image/png': '.png', 'image/webp': '.webp', 'image/gif': '.gif' };
        const ext = extMap[contentType.split(';')[0].trim()] || '.jpg';
        const tempPath = path.join(tempDownloadsDir, `hf_download_${randomUUID()}${ext}`);
        const arrayBuffer = await dlRes.arrayBuffer();
        await fs.writeFile(tempPath, Buffer.from(arrayBuffer));
        console.log(`[post] Pre-downloaded HF image to: ${tempPath}`);
        return tempPath;
      } finally {
        clearTimeout(timer);
      }
    }

    // Process images: write Base64 data or HF URLs to local files; leave other URLs as-is
    for (let i = 0; i < finalImages.length; i++) {
      const img = finalImages[i];
      if (img.startsWith('data:image/') || img.includes(';base64,')) {
        // Base64 encoded image β†’ decode and write to disk
        const matches = img.match(/^data:image\/([A-Za-z+]+);base64,(.+)$/);
        let base64Data = img;
        let ext = '.jpg';
        if (matches && matches.length === 3) {
          ext = '.' + matches[1];
          base64Data = matches[2];
        } else {
          const parts = img.split(';base64,');
          if (parts.length === 2) {
            base64Data = parts[1];
          }
        }
        const buffer = Buffer.from(base64Data, 'base64');
        const tempPath = path.join(tempDownloadsDir, `local_upload_${randomUUID()}${ext}`);
        await fs.writeFile(tempPath, buffer);
        filePaths.push(tempPath);
        localTempFiles.push(tempPath);
      } else if (img.includes('hf.space') || img.includes('huggingface.co')) {
        // HF Space URL β†’ pre-download server-side so Python gets a stable local path
        const tempPath = await downloadRemoteImage(img);
        filePaths.push(tempPath);
        localTempFiles.push(tempPath);
      } else {
        filePaths.push(img);
      }
    }

    // Write JSON payload
    await fs.writeFile(tempFilePath, JSON.stringify({ urls: filePaths, caption }, null, 2), 'utf-8');

    // Run Python CLI uploader
    let pythonCmd = 'python';
    if (fsSync.existsSync(PYTHON_EXE)) {
      pythonCmd = PYTHON_EXE;
    }

    console.log(`[post] Spawning python process inside: ${INSTAGRAM_CWD}`);
    console.log(`[post] Command: ${pythonCmd} cli.py --json ${tempFilePath}`);

    const { stdout, stderr } = await execPromise(`"${pythonCmd}" cli.py --json "${tempFilePath}"`, {
      cwd: INSTAGRAM_CWD,
      env: { ...process.env }
    });

    const stdoutStr = stdout.toString();
    const stderrStr = stderr.toString();

    console.log(`[post] stdout:\n${stdoutStr}`);
    if (stderrStr.trim()) {
      console.error(`[post] stderr:\n${stderrStr}`);
    }

    // Find the JSON block printed by cli.py
    const jsonMarker = '--- JSON Output ---';
    const jsonIndex = stdoutStr.indexOf(jsonMarker);

    if (jsonIndex === -1) {
      throw new Error(`Uploader CLI did not return structured output. Details:\n${stdoutStr}\n${stderrStr}`);
    }

    const jsonPart = stdoutStr.substring(jsonIndex + jsonMarker.length).trim();
    const result = JSON.parse(jsonPart);

    const type = finalImages.length === 1 ? 'single' : 'carousel';

    const entry = {
      id: randomUUID(),
      posted_at: new Date().toISOString(),
      instagram_post_id: result.media_id,
      type: type,
      images: finalImages.map(img => (img.startsWith('data:image/') || img.includes(';base64,')) ? '[Local File]' : img),
      caption,
    };
    await appendHistory(entry);

    console.log(
      `[post] type=${type} ig_post_id=${result.media_id} elapsed_ms=${Date.now() - startedAt}`
    );

    res.json({
      success: true,
      post_id: result.media_id,
      type: type,
      post_url: result.post_url
    });

  } catch (err) {
    console.error('[post] Upload failed with error:', err);
    res.status(500).json({ success: false, error: err.message || 'Internal uploader error' });
  } finally {
    // Clean up temporary JSON file
    try {
      if (fsSync.existsSync(tempFilePath)) {
        await fs.unlink(tempFilePath);
      }
    } catch (cleanupErr) {
      console.error(`[post] Failed to clean up temp request file: ${cleanupErr.message}`);
    }
    // Clean up temporary decoded base64 image files
    for (const tempPath of localTempFiles) {
      try {
        if (fsSync.existsSync(tempPath)) {
          await fs.unlink(tempPath);
          console.log(`[post] Cleaned up temporary local image: ${tempPath}`);
        }
      } catch (cleanupErr) {
        console.error(`[post] Failed to clean up temporary local image: ${cleanupErr.message}`);
      }
    }
  }
});

app.listen(PORT, () => {
  console.log(`FashionAI server running at http://localhost:${PORT}`);
});