1 const fs = require('fs');
3 const util = require('util');
4 const execFile = util.promisify(require('child_process').execFile);
6 const express = require('express');
8 const http = require('http');
9 const server = http.createServer(app);
10 const { Server } = require("socket.io");
11 const io = new Server(server);
14 const python_path = '/usr/bin/python3'
15 const generate_image_script = '/home/cworth/src/zombocom-ai/generate-image.py'
16 const state_file = 'zombocom-state.json'
20 // Load comments at server startup
21 fs.readFile(state_file, (err, data) => {
23 state = { images: [], comments: [] };
25 state = JSON.parse(data);
28 // Save comments when server is shutting down
30 fs.writeFileSync('zombocom-state.json', JSON.stringify(state), (error) => {
36 // And connect to that on either clean exit...
37 process.on('exit', cleanup);
39 // ... or on a SIGINT (control-C)
40 process.on('SIGINT', () => {
45 app.get('/index.html', (req, res) => {
46 res.sendFile(__dirname + '/index.html');
49 io.on('connection', (socket) => {
51 // Replay old comments to a newly-joining client
52 state.comments.forEach((comment) => {
53 socket.emit('comment', comment)
56 // When any client comments, send that to all clients (including sender)
57 socket.on('comment', (comment) => {
58 io.emit('comment', comment);
59 state.comments.push(comment);
62 // Generate an image when requested
63 socket.on('generate', (request) => {
64 console.log(`Generating image with code=${request['code']} and prompt=${request['prompt']}`);
65 async function generate_image(code, prompt) {
68 promise = execFile(python_path, [generate_image_script, `--seed=${code}`, prompt])
70 promise = execFile(python_path, [generate_image_script, prompt])
72 const child = promise.child;
73 child.stdout.on('data', (data) => {
74 const images = JSON.parse(data);
75 images.forEach((image) => {
76 console.log(`Emitting image to clients: ${image}`);
77 io.emit('image', image);
78 state.images.push(image);
81 child.stderr.on('data', (data) => {
82 console.log("Error occurred during generate-image: " + data);
84 const { stdout, stderr } = await promise;
86 generate_image(request['code'], request['prompt']);
90 server.listen(port, () => {
91 console.log(`listening on *:${port}`);