-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
114 lines (99 loc) · 3 KB
/
server.js
File metadata and controls
114 lines (99 loc) · 3 KB
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
const express = require('express');
const bodyParser = require('body-parser');
const { spawn } = require('child_process');
const app = express();
var cors = require('cors')
app.use(cors()) // Use this after the variable declaration
app.use(bodyParser.json());
function predict(x, y, speed) {
console.log('in preidct');
return new Promise((resolve, reject) => {
console.log('x:', x, 'y:', y, 'speed:', speed);
const python = spawn('python', ['predict.py', x, y, speed]);
let result = '';
let errorOutput = '';
python.stdout.on('data', (data) => {
let tempString = data.toString();
console.log('tempString:', tempString);
result += tempString;
});
python.stderr.on('data', (data) => {
errorOutput += data.toString();
});
python.on('close', (code) => {
if (code !== 0) {
console.error(`Python stderr: ${errorOutput}`);
reject(`Python script exited with code ${code}`);
} else {
console.log('result:', result);
resolve(JSON.parse(result));
}
});
});
}
function getUserCondition(cluster) {
switch(parseInt(cluster)) {
case 0: return 'relaxed';
case 1: return 'anxious';
case 2: return 'sleepy';
case 3: return 'anxious';
default: return 'unknown';
}
}
app.get('/', (req, res) => {
res.send('Hello World!');
console.log('user connected');
}
);
app.post('/predict', async (req, res) => {
console.log('predicting...');
const { x, y, speed } = req.body;
try {
console.log('in try');
const { cluster } = await predict(x, y, speed);
console.log('cluster:', cluster);
const condition = getUserCondition(cluster);
res.json({
cluster,
condition,
uiSuggestions: getUISuggestions(condition)
});
} catch (error) {
console.log('error:', error);
res.status(500).json({ error: error.toString() });
}
});
function getUISuggestions(condition) {
switch(condition) {
case 'relaxed':
return {
fontSize: 'larger',
spacing: 'increased',
animation: 'minimal'
};
case 'sleepy':
return {
interactiveElements: 'increased',
contentSuggestions: true,
navigation: 'prominent'
};
case 'relaxed':
return {
distractions: 'minimized',
focusArea: 'highlighted',
notifications: 'suppressed'
};
case 'anxious':
return {
layout: 'simplified',
helpPrompts: true,
guidedExperience: true
};
default:
return {};
}
}
const port = process.env.PORT || 3001; // Fallback to 3000 if process.env.PORT is not defined
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});