-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfacetrack.html
More file actions
328 lines (293 loc) · 12.1 KB
/
facetrack.html
File metadata and controls
328 lines (293 loc) · 12.1 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exercise Tracker App</title>
<script src="https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/vision_bundle.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body { font-family: Arial, sans-serif; text-align: center; }
#video { display: none; } /* Change to block for debugging */
#canvas { border: 1px solid black; display: none; }
#output { margin-top: 20px; }
#chartContainer { margin-top: 20px; width: 80%; margin: auto; }
</style>
</head>
<body>
<h1>Exercise Tracker</h1>
<p>Use the front-facing camera to track head movement for repetitive exercises.</p>
<button id="startBtn">Start Exercise</button>
<button id="stopBtn" style="display:none;">Stop Exercise</button>
<video id="video" playsinline></video>
<canvas id="canvas"></canvas>
<div id="output">
<p>Reps: <span id="reps">0</span></p>
<p>Points: <span id="points">0</span></p>
<p>Timer: <span id="timer">00:00</span></p>
<p>Status: <span id="status">Ready</span></p>
<p>Milestones: <span id="milestones"></span></p>
</div>
<div id="chartContainer">
<canvas id="dailyChart"></canvas>
</div>
<script>
const { PoseLandmarker, FilesetResolver, DrawingUtils } = window.vision;
let poseLandmarker;
let video;
let canvas;
let ctx;
let drawingUtils;
let lastVideoTime = -1;
let running = false;
let webcamRunning = false;
let reps = 0;
let points = 0;
let timerSeconds = 0;
let timerInterval;
let breakSeconds = 0;
let breakInterval;
let isPaused = false;
let lastRepTime = Date.now();
let cadence = 0; // seconds per rep
let targetCadence = 2; // initial target, adjust
let initialRange = 0;
let calibrating = true;
let calibrationReps = [];
let currentMinY = Infinity;
let currentMaxY = -Infinity;
let noseYHistory = [];
const HISTORY_LENGTH = 10;
let direction = 'up'; // assume starting up
let milestones = [];
let speech = new SpeechSynthesisUtterance();
const milestonesThresholds = [10, 50, 100, 200];
const awards = ['Bronze', 'Silver', 'Gold', 'Platinum'];
async function createPoseLandmarker() {
try {
const filesetResolver = await FilesetResolver.forVisionTasks(
"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm"
);
poseLandmarker = await PoseLandmarker.createFromOptions(filesetResolver, {
baseOptions: {
modelAssetPath: `https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_lite/float16/1/pose_landmarker_lite.task`,
delegate: "CPU" // Using CPU to avoid potential GPU issues
},
runningMode: "VIDEO",
numPoses: 1
});
console.log('PoseLandmarker created successfully');
} catch (err) {
console.error('Error creating PoseLandmarker:', err);
document.getElementById('status').innerText = 'Error initializing model: ' + err.message;
}
}
async function startCamera() {
video = document.getElementById('video');
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
drawingUtils = new DrawingUtils(ctx);
const constraints = {
video: { facingMode: 'user' }
};
try {
const stream = await navigator.mediaDevices.getUserMedia(constraints);
video.srcObject = stream;
video.addEventListener('loadeddata', () => {
console.log('Video loaded');
predictWebcam();
});
} catch (err) {
console.error('Error accessing camera:', err);
document.getElementById('status').innerText = 'Camera access denied or error: ' + err.message;
}
}
function predictWebcam() {
if (running) {
webcamRunning = true;
let nowInMs = performance.now();
if (video.currentTime !== lastVideoTime) {
lastVideoTime = video.currentTime;
poseLandmarker.detectForVideo(video, nowInMs, (result) => {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
ctx.save();
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (result.landmarks && result.landmarks.length > 0) {
const landmarks = result.landmarks[0];
drawingUtils.drawLandmarks(landmarks, { color: '#FF0000', radius: 1 });
drawingUtils.drawConnectors(landmarks, PoseLandmarker.POSE_CONNECTIONS, { color: '#00FF00' });
processLandmarks(landmarks);
}
ctx.restore();
});
}
window.requestAnimationFrame(predictWebcam);
}
}
function processLandmarks(landmarks) {
const nose = landmarks[0]; // nose landmark
if (!nose) return;
const noseY = nose.y; // normalized 0-1
noseYHistory.push(noseY);
if (noseYHistory.length > HISTORY_LENGTH) noseYHistory.shift();
// Simple rep detection: detect direction change
currentMinY = Math.min(currentMinY, noseY);
currentMaxY = Math.max(currentMaxY, noseY);
const avgY = noseYHistory.reduce((a, b) => a + b, 0) / noseYHistory.length;
const mid = (currentMinY + currentMaxY) / 2;
if (calibrating) {
calibrate(noseY);
return;
}
// Detect rep: crossing mid point
if (direction === 'down' && noseY < mid - 0.01) {
// Reached up
direction = 'up';
completeRep();
} else if (direction === 'up' && noseY > mid + 0.01) {
// Reached down
direction = 'down';
}
checkPause();
}
function calibrate(noseY) {
// Collect 5 reps for calibration
if (calibrationReps.length < 5) {
document.getElementById('status').innerText = `Calibrating: Do 5 slow reps (${calibrationReps.length}/5)`;
// Detect rep similarly
const mid = (currentMinY + currentMaxY) / 2;
if (direction === 'down' && noseY < mid - 0.01) {
direction = 'up';
const range = currentMaxY - currentMinY;
calibrationReps.push(range);
currentMinY = Infinity;
currentMaxY = -Infinity;
speak('Up');
} else if (direction === 'up' && noseY > mid + 0.01) {
direction = 'down';
speak('Down');
}
} else {
initialRange = calibrationReps.reduce((a, b) => a + b, 0) / 5;
calibrating = false;
document.getElementById('status').innerText = 'Calibration complete. Start exercising!';
targetCadence = 3; // assume initial 3s per rep
}
}
function completeRep() {
const now = Date.now();
const repTime = (now - lastRepTime) / 1000;
lastRepTime = now;
reps++;
points += 1;
const currentRange = currentMaxY - currentMinY;
if (currentRange > initialRange) {
points += (currentRange - initialRange) * 10; // bonus
}
currentMinY = Infinity;
currentMaxY = -Infinity;
cadence = repTime;
if (cadence > targetCadence + 0.5) {
speak('Faster');
} else if (cadence < targetCadence - 0.5) {
speak('Slow down');
}
// Slowly increase cadence (decrease time)
if (reps % 10 === 0) {
targetCadence *= 0.99; // 1% faster
}
checkMilestones();
updateDisplay();
saveData();
}
function checkPause() {
const now = Date.now();
if ((now - lastRepTime) / 1000 > 10 && !isPaused) { // no rep for 10s
pauseTimer();
startBreak();
}
if ((now - lastRepTime) / 1000 > 120) { // 2 min
stopExercise();
}
}
function startTimer() {
timerInterval = setInterval(() => {
timerSeconds++;
document.getElementById('timer').innerText = formatTime(timerSeconds);
}, 1000);
}
function pauseTimer() {
clearInterval(timerInterval);
isPaused = true;
document.getElementById('status').innerText = 'Paused';
}
function resumeTimer() {
startTimer();
isPaused = false;
document.getElementById('status').innerText = 'Exercising';
clearInterval(breakInterval);
breakSeconds = 0;
}
function startBreak() {
breakInterval = setInterval(() => {
breakSeconds++;
if (breakSeconds === 60) {
speak('Start exercising again');
}
}, 1000);
}
function checkMilestones() {
for (let i = 0; i < milestonesThresholds.length; i++) {
if (reps === milestonesThresholds[i] && !milestones.includes(awards[i])) {
milestones.push(awards[i]);
speak(`Congratulations! ${awards[i]} medal for ${reps} reps`);
}
}
document.getElementById('milestones').innerText = milestones.join(', ');
}
function updateDisplay() {
document.getElementById('reps').innerText = reps;
document.getElementById('points').innerText = points;
}
function formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
function speak(text) {
speech.text = text;
window.speechSynthesis.speak(speech);
}
function saveData() {
const today = new Date().toISOString().split('T')[0];
let data = JSON.parse(localStorage.getItem('exerciseData')) || {};
data[today] = { reps, milestones };
localStorage.setItem('exerciseData', JSON.stringify(data));
updateChart();
}
function updateChart() {
const data = JSON.parse(localStorage.getItem('exerciseData')) || {};
const labels = Object.keys(data).slice(-7); // last 7 days
const repsData = labels.map(date => data[date]?.reps || 0);
const chartCanvas = document.getElementById('dailyChart');
if (Chart.getChart(chartCanvas)) {
Chart.getChart(chartCanvas).destroy();
}
new Chart(chartCanvas, {
type: 'line',
data: {
labels,
datasets: [{
label: 'Daily Reps',
data: repsData,
borderColor: 'blue',
fill: false
}]
},
options: {
scales: {
y: { beginAtZero: true }
}
}
});