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 and images to a newly-joining client
52 state.comments.forEach((comment) => {
53 socket.emit('comment', comment)
55 state.images.forEach((image) => {
56 socket.emit('image', image)
59 // When any client comments, send that to all clients (including sender)
60 socket.on('comment', (comment) => {
61 io.emit('comment', comment);
62 state.comments.push(comment);
65 // Generate an image when requested
66 socket.on('generate', (request) => {
67 console.log(`Generating image with code=${request['code']} and prompt=${request['prompt']}`);
68 async function generate_image(code, prompt) {
71 promise = execFile(python_path, [generate_image_script, `--seed=${code}`, prompt])
73 promise = execFile(python_path, [generate_image_script, prompt])
75 const child = promise.child;
76 child.stdout.on('data', (data) => {
77 const images = JSON.parse(data);
78 images.forEach((image) => {
79 console.log(`Emitting image to clients: ${image}`);
80 io.emit('image', image);
81 state.images.push(image);
84 child.stderr.on('data', (data) => {
85 console.log("Error occurred during generate-image: " + data);
87 const { stdout, stderr } = await promise;
89 generate_image(request['code'], request['prompt']);
93 server.listen(port, () => {
94 console.log(`listening on *:${port}`);