-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
190 lines (164 loc) · 7.91 KB
/
server.js
File metadata and controls
190 lines (164 loc) · 7.91 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
const dbManager = require('./core/dbManager');
const llmService = require('./core/llmService');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors());
app.use(express.json({ limit: '2mb' }));
app.use(express.static(path.join(__dirname, 'public')));
// Initialize the database on startup
dbManager.initDb();
/* ─── GET /api/history ─── */
app.get('/api/history', async (req, res) => {
try {
const history = await dbManager.getChatHistory();
res.json(history);
} catch (error) {
console.error('[/api/history]', error.message);
res.status(500).json({ error: error.message });
}
});
/* ─── GET /api/models ─── */
app.get('/api/models', async (req, res) => {
try {
const models = await llmService.fetchInstalledModels();
res.json(models);
} catch (error) {
console.error('[/api/models]', error.message);
res.status(500).json({ error: error.message });
}
});
/* ─── POST /api/chat ─── */
app.post('/api/chat', async (req, res) => {
try {
const startTime = Date.now();
const { message, userRole, targetAudience, objective, model } = req.body;
if (!message || !message.trim()) {
return res.status(400).json({ error: 'Message cannot be empty.' });
}
// Save user message
await dbManager.saveMessage('user', message);
// Build context from recent history
const history = await dbManager.getChatHistory();
const recentHistory = history.slice(-6).map(m => `${m.role}: ${m.content}`).join('\n');
const context = [
`User Role: ${userRole || 'General Professional'}`,
`Target Audience: ${targetAudience || 'General Audience'}`,
`Core Objective: ${objective || 'General Communication'}`,
recentHistory ? `Recent Context:\n${recentHistory}` : ''
].filter(Boolean).join('\n');
// Call AI
const analysis = await llmService.analyzeCommunication(message, context, model);
const duration = ((Date.now() - startTime) / 1000).toFixed(1);
console.log(`[Server] Inference complete in ${duration}s`);
// Build readable AI summary
const aiSummary = analysis.direct_answer || "Analysis complete.";
const msgId = await dbManager.saveMessage('assistant', aiSummary, JSON.stringify(analysis));
// Compute and persist metrics
const enriched = {
...analysis,
professionalism_score: analysis.persuasion_score || 80,
clarity_score: analysis.actionability_score || 80,
emotional_intelligence_score: analysis.eq_score || 80,
risk_level: (analysis.risk_score || 'Low')
};
await dbManager.saveMetrics(msgId, enriched);
res.json({
userMessage: { role: 'user', content: message },
assistantMessage: { role: 'assistant', content: aiSummary, analysis: enriched }
});
} catch (error) {
console.error('[/api/chat]', error.message);
res.status(500).json({ error: error.message });
}
});
/* ─── POST /api/clear (was missing — caused "Initialize Core" to fail) ─── */
app.post('/api/clear', async (req, res) => {
try {
await dbManager.clearChatHistory();
res.json({ success: true, message: 'Chat history cleared.' });
} catch (error) {
console.error('[/api/clear]', error.message);
res.status(500).json({ error: error.message });
}
});
/* ─── POST /api/spellcheck ─── */
app.post('/api/spellcheck', async (req, res) => {
try {
const { text } = req.body;
if (!text || !text.trim()) {
return res.json({ corrections: 'No text provided.', hasErrors: false });
}
const prompt = `Check for spelling and grammar mistakes in this text: "${text}".
List only actual misspelled words and their corrections as "wrong → correct" pairs, one per line.
If no errors are found, respond with exactly: No spelling errors detected.`;
const analysis = await llmService.analyzeCommunication(prompt, 'Spellcheck Analysis');
const raw = analysis.direct_answer || '';
const hasErrors = !/no spelling errors detected/i.test(raw);
res.json({ corrections: raw, hasErrors });
} catch (error) {
console.error('[/api/spellcheck]', error.message);
res.status(500).json({ error: error.message });
}
});
/* ─── POST /api/presence-analyze ─── */
app.post('/api/presence-analyze', async (req, res) => {
try {
const { metrics } = req.body;
const prompt = `Analyze this presence/body language session data and provide concise, actionable insights.
Eye Contact: ${metrics.eyeScore}%, Posture: ${metrics.postureScore}%, Gestures: ${metrics.gestureScore}%,
Audio Clarity: ${metrics.audioClarity}%, Engagement: ${metrics.engagement}%, Confidence: ${metrics.confidence}%,
Warmth: ${metrics.warmth}%, Pacing: ${metrics.pacing}%.
Provide 2-3 specific recommendations for improvement.`;
const analysis = await llmService.analyzeCommunication(prompt, 'Presence Lab Analysis');
res.json({
summary: analysis.direct_answer || 'Analysis complete.',
insights: `Tone detected: ${analysis.tone || 'Engaged'}. Formality: ${analysis.formality_level || 'Professional'}.`,
recommendations: `Risk level: ${analysis.risk_score || 'Low'}. Action: ${analysis.video_query || 'Practice active listening.'}`
});
} catch (error) {
console.error('[/api/presence-analyze]', error.message);
res.status(500).json({ error: error.message });
}
});
/* ─── POST /api/draft-analyze ─── */
app.post('/api/draft-analyze', async (req, res) => {
try {
const { text } = req.body;
if (!text || !text.trim()) {
return res.json({ tone: 'Neutral', risk_score: 'Low', formality_level: 'Professional', persuasion_score: 50, clarity: 50, impact: 50, momentum: 50, suggestion: 'Start typing your message...' });
}
const analysis = await llmService.analyzeCommunication(text, 'Real-time draft analysis');
const resp = analysis.direct_answer || '';
// Extract inline numeric scores if present
const extractNum = (str, key) => {
const m = str.match(new RegExp(`${key}[^0-9]*(\\d+)`, 'i'));
return m ? Math.min(100, parseInt(m[1])) : null;
};
res.json({
tone: analysis.tone || 'Neutral',
risk_score: analysis.risk_score || 'Low',
formality_level: analysis.formality_level || 'Professional',
persuasion_score: analysis.persuasion_score || 50,
clarity: analysis.actionability_score|| 50,
impact: extractNum(resp, 'impact') || Math.round((analysis.persuasion_score || 50 + analysis.actionability_score || 50) / 2),
momentum: extractNum(resp, 'momentum') || analysis.confidence_score || 50,
suggestion: resp.split(/[.!?\n]/)[0] || 'Consider strengthening your opening statement.'
});
} catch (error) {
console.error('[/api/draft-analyze]', error.message);
res.status(500).json({ error: error.message });
}
});
/* ─── Fallback to SPA ─── */
app.use((req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(PORT, () => {
console.log(`\n🚀 Neural Core running → http://localhost:${PORT}`);
console.log(` Ollama endpoint: ${process.env.OLLAMA_API_URL || 'http://localhost:11434'}`);
console.log(` Default model : ${process.env.OLLAMA_MODEL || 'llama3.2:1b'}\n`);
});