-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
93 lines (80 loc) · 2.75 KB
/
server.js
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
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const OpenAI = require('openai');
const app = express();
const port = 3000;
// Initialize OpenAI with error handling
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
app.use(cors());
app.use(bodyParser.json());
app.use(express.static('public'));
// Get AI workout recommendations
app.post('/api/recommendations', async (req, res) => {
const { goals, fitnessLevel, preferences, bodyMetrics } = req.body;
try {
// Validate OpenAI API key
if (!process.env.OPENAI_API_KEY || process.env.OPENAI_API_KEY === 'your_openai_api_key_here') {
throw new Error('Invalid OpenAI API key');
}
const completion = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{
role: "system",
content: "You are a professional fitness trainer providing workout recommendations."
}, {
role: "user",
content: `Create a workout plan for someone with the following details:
Goals: ${goals}
Fitness Level: ${fitnessLevel}
Preferences: ${preferences}
Height: ${bodyMetrics.height}cm
Weight: ${bodyMetrics.weight}kg
BMI: ${bodyMetrics.bmi}
Please provide a structured weekly plan with specific exercises, considering their body metrics and BMI.`
}]
});
res.json({ recommendation: completion.choices[0].message.content });
} catch (error) {
console.error('OpenAI API Error:', error.message);
res.status(500).json({
error: 'Error generating recommendation',
details: error.message
});
}
});
// Track workout
app.post('/api/track-workout', async (req, res) => {
const { workout } = req.body;
try {
// Validate OpenAI API key
if (!process.env.OPENAI_API_KEY || process.env.OPENAI_API_KEY === 'your_openai_api_key_here') {
throw new Error('Invalid OpenAI API key');
}
const completion = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{
role: "system",
content: "You are a fitness analysis AI providing feedback on workouts."
}, {
role: "user",
content: `Analyze this workout and provide feedback:
${workout}
Please provide specific tips for improvement and form suggestions.`
}]
});
res.json({ feedback: completion.choices[0].message.content });
} catch (error) {
console.error('OpenAI API Error:', error.message);
res.status(500).json({
error: 'Error analyzing workout',
details: error.message
});
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});