File size: 3,577 Bytes
1f784ac
 
 
 
 
f9f0fec
eb5e811
f9f0fec
2767dda
a227ed8
325f41a
59f8f57
 
 
 
 
f9f0fec
 
 
 
 
 
eb5e811
9a70daf
59f8f57
 
f9f0fec
eb5e811
a227ed8
 
eb5e811
 
325f41a
f9f0fec
 
 
a227ed8
eb5e811
 
 
 
 
 
 
59f8f57
 
 
 
 
 
 
 
 
 
 
 
 
 
eb5e811
 
 
 
325f41a
a227ed8
59f8f57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb5e811
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
// At the top of your index.mjs or wherever you're planning to use fetch
import fetch from 'node-fetch';
if (!globalThis.fetch) {
    globalThis.fetch = fetch;
}
import express from "express";
import 'dotenv/config.js';
import { createServer } from "http";
import { Server } from "socket.io";
import { client } from "@gradio/client";
import { createRequire } from 'node:module';
import { writeFile, readFileSync, appendFileSync } from 'node:fs';
import { join } from 'node:path';
import { randomBytes } from 'node:crypto';
import base64url from 'base64-url';

const require = createRequire(import.meta.url);
global.EventSource = require('eventsource');

const app = express();
const httpServer = createServer(app);
app.use(express.static('public'));
const io = new Server(httpServer, { /* options */ });

const textHistoryPath = join(__dirname, 'public', 'history.txt');

io.on("connection", (socket) => {
    console.log("new socket connection ๐ŸŽ‰");
    
    socket.on("ask_api", (client_data) => {
        console.log("Received data from client ๐Ÿ“ธ", client_data);
        console.log("Attempting to reach API... ๐Ÿš€");   
        asyncAPICall(client_data, socket);
    });
});

async function asyncAPICall(data, socket) {
  const grapi = await client("fffiloni/mndrm-call");
  try {
      const api_result = await grapi.predict("/infer", [
          data[0], // blob in 'image' Image component
          data[1], // string in 'Question' Textbox component
      ]);
      console.log("API response received โœ…", api_result);
      
      // Save image and text
      const imageName = saveImage(api_result.data.image); // Assuming api_result.data.image is the image blob or base64 string
      const textName = saveText(api_result.data.text, imageName); // Assuming api_result.data.text is the text to be saved
      
      // Emit the response with download links
      socket.emit("api_response", {
        ...api_result.data,
        imageDownloadLink: `/download/${imageName}`,
        textDownloadLink: `/download/${textName}`
      });
      
      updateHistory(api_result.data.text, imageName);
      
  } catch (e) {
      console.error("API call failed โŒ", e);
      socket.emit("api_error", ("ERROR ON API SIDE, SORRY..."));
  }    
}

function saveImage(imageData) {
    const imageName = `image_${randomBytes(8).toString('hex')}.png`;
    writeFile(join(__dirname, 'public', imageName), imageData, 'base64', (err) => {
        if (err) throw err;
        console.log(`Image saved as ${imageName}`);
    });
    return imageName;
}

function saveText(text, imageName) {
    const textName = `text_${randomBytes(8).toString('hex')}.txt`;
    writeFile(join(__dirname, 'public', textName), `${text}\nImage File: ${imageName}\n`, (err) => {
        if (err) throw err;
        console.log(`Text saved as ${textName}`);
    });
    return textName;
}

function updateHistory(text, imageName) {
    appendFileSync(textHistoryPath, `${text}\nImage File: ${imageName}\n`);
}

// Serve files for download
app.get('/download/:name', (req, res) => {
    const fileName = req.params.name;
    const filePath = join(__dirname, 'public', fileName);
    res.download(filePath);
});

// Serve history.txt encoded in Base64
app.get('/history', (req, res) => {
    const history = readFileSync(textHistoryPath, 'utf8');
    const encodedHistory = base64url.encode(history);
    res.send(`<a href="data:text/plain;base64,${encodedHistory}" download="history.txt">Download History</a>`);
});

httpServer.listen(7860, () => console.log("App running on localhost:7860 ๐ŸŒ"));