shashwatIDR commited on
Commit
b24cb40
·
verified ·
1 Parent(s): 059c23a

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +51 -45
server.js CHANGED
@@ -570,7 +570,7 @@ app.post('/api/generate/anime-uc', authenticateToken, async (req, res) => {
570
  }
571
  });
572
 
573
- // Flux Generation endpoint (UNO-FLUX direct API with detailed logging)
574
  app.get('/api/generate/flux', authenticateToken, async (req, res) => {
575
  try {
576
  const { prompt, aspect } = req.query;
@@ -612,71 +612,77 @@ app.get('/api/generate/flux', authenticateToken, async (req, res) => {
612
  console.log('[Flux] Sending queue/join payload:', JSON.stringify(joinPayload));
613
  let joinResponse;
614
  try {
615
- joinResponse = await axios.post(
616
  'https://bytedance-research-uno-flux.hf.space/gradio_api/queue/join?__theme=system',
617
- joinPayload,
618
  {
 
619
  headers: {
620
  'Content-Type': 'application/json',
621
- 'Referer': 'https://bytedance-research-uno-flux.hf.space/'
622
- }
 
 
623
  }
624
  );
625
- console.log('[Flux] queue/join response:', joinResponse.data);
 
626
  } catch (err) {
627
- console.error('[Flux] Error joining UNO-FLUX queue:', err.response?.data || err.message);
628
  return res.status(500).json({ success: false, error: 'Failed to join UNO-FLUX queue' });
629
  }
630
 
631
- // Poll for results
632
- let attempts = 0;
633
- const maxAttempts = 60;
634
  const pollUrl = `https://bytedance-research-uno-flux.hf.space/gradio_api/queue/data?session_hash=${encodeURIComponent(sessionHash)}`;
635
  console.log(`[Flux] Polling for results at: ${pollUrl}`);
636
  let found = false;
637
- while (attempts < maxAttempts) {
 
 
 
638
  attempts++;
639
  try {
640
- const dataResponse = await axios.get(
641
- pollUrl,
642
- {
643
- headers: {
644
- 'Accept': 'text/event-stream',
645
- 'Referer': 'https://bytedance-research-uno-flux.hf.space/'
646
- },
647
- timeout: 10000
648
- }
649
- );
650
- const data = dataResponse.data;
651
- console.log(`[Flux] Poll attempt ${attempts}, data length: ${data.length}`);
652
- // Parse the event stream data
653
- const lines = data.split('\n');
654
- let eventData = '';
655
- for (const line of lines) {
656
- if (line.startsWith('data: ')) {
657
- eventData += line.substring(6);
658
- } else if (line === '') {
659
- if (eventData) {
660
- try {
661
- const json = JSON.parse(eventData);
662
- console.log(`[Flux] Event:`, json);
663
- if (json.msg === 'process_completed' && json.output?.data?.[0]?.url) {
664
- const imageUrl = json.output.data[0].url;
665
- console.log(`[Flux] Success! Image URL: ${imageUrl}`);
666
- found = true;
667
- return res.json({ success: true, imageUrl });
668
- } else if (json.msg === 'process_completed') {
669
- console.warn('[Flux] process_completed but no image URL:', json);
 
 
 
670
  }
671
- } catch (error) {
672
- console.error('[Flux] Error parsing event data:', error, 'Raw data:', eventData);
673
  }
674
- eventData = '';
675
  }
 
676
  }
 
677
  }
678
  } catch (pollError) {
679
- console.error(`[Flux] Poll error on attempt ${attempts}:`, pollError.message);
680
  }
681
  await new Promise(resolve => setTimeout(resolve, 2000));
682
  }
 
570
  }
571
  });
572
 
573
+ // Flux Generation endpoint (UNO-FLUX direct API with node-fetch SSE polling)
574
  app.get('/api/generate/flux', authenticateToken, async (req, res) => {
575
  try {
576
  const { prompt, aspect } = req.query;
 
612
  console.log('[Flux] Sending queue/join payload:', JSON.stringify(joinPayload));
613
  let joinResponse;
614
  try {
615
+ joinResponse = await fetch(
616
  'https://bytedance-research-uno-flux.hf.space/gradio_api/queue/join?__theme=system',
 
617
  {
618
+ method: 'POST',
619
  headers: {
620
  'Content-Type': 'application/json',
621
+ 'Referer': 'https://bytedance-research-uno-flux.hf.space/',
622
+ 'Origin': 'https://bytedance-research-uno-flux.hf.space'
623
+ },
624
+ body: JSON.stringify(joinPayload)
625
  }
626
  );
627
+ const joinData = await joinResponse.json();
628
+ console.log('[Flux] queue/join response:', joinData);
629
  } catch (err) {
630
+ console.error('[Flux] Error joining UNO-FLUX queue:', err);
631
  return res.status(500).json({ success: false, error: 'Failed to join UNO-FLUX queue' });
632
  }
633
 
634
+ // Poll for results using node-fetch and streaming
 
 
635
  const pollUrl = `https://bytedance-research-uno-flux.hf.space/gradio_api/queue/data?session_hash=${encodeURIComponent(sessionHash)}`;
636
  console.log(`[Flux] Polling for results at: ${pollUrl}`);
637
  let found = false;
638
+ let attempts = 0;
639
+ const maxAttempts = 60;
640
+ let buffer = '';
641
+ while (attempts < maxAttempts && !found) {
642
  attempts++;
643
  try {
644
+ const response = await fetch(pollUrl, {
645
+ headers: {
646
+ 'Accept': 'text/event-stream',
647
+ 'Referer': 'https://bytedance-research-uno-flux.hf.space/',
648
+ 'Origin': 'https://bytedance-research-uno-flux.hf.space'
649
+ },
650
+ timeout: 10000
651
+ });
652
+ if (!response.ok) {
653
+ console.error(`[Flux] Poll error on attempt ${attempts}:`, response.status, await response.text());
654
+ await new Promise(resolve => setTimeout(resolve, 2000));
655
+ continue;
656
+ }
657
+ const reader = response.body.getReader();
658
+ let done = false;
659
+ while (!done) {
660
+ const { value, done: streamDone } = await reader.read();
661
+ if (value) {
662
+ buffer += Buffer.from(value).toString('utf8');
663
+ const lines = buffer.split('\n');
664
+ for (const line of lines) {
665
+ if (line.startsWith('data: ')) {
666
+ try {
667
+ const json = JSON.parse(line.slice(6));
668
+ console.log('[Flux] Event:', json);
669
+ if (json.msg === 'process_completed' && json.output?.data?.[0]?.url) {
670
+ const imageUrl = json.output.data[0].url;
671
+ console.log(`[Flux] Success! Image URL: ${imageUrl}`);
672
+ found = true;
673
+ return res.json({ success: true, imageUrl });
674
+ }
675
+ } catch (e) {
676
+ console.error('[Flux] Parse error:', e, line);
677
  }
 
 
678
  }
 
679
  }
680
+ buffer = lines[lines.length - 1]; // keep incomplete line
681
  }
682
+ done = streamDone;
683
  }
684
  } catch (pollError) {
685
+ console.error(`[Flux] Poll error on attempt ${attempts}:`, pollError);
686
  }
687
  await new Promise(resolve => setTimeout(resolve, 2000));
688
  }