-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
574 lines (530 loc) · 24.7 KB
/
Copy pathindex.html
File metadata and controls
574 lines (530 loc) · 24.7 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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
<!--- This project is done by Aswanth R --->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Smart Attendance System</title>
<script src="https://cdn.jsdelivr.net/npm/face-api.js@0.22.2/dist/face-api.min.js"></script>
<script src="https://cdn.sheetjs.com/xlsx-0.20.1/package/dist/xlsx.full.min.js"></script>
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family:'Segoe UI',Roboto,sans-serif; background:#f5f7fb; color:#1e293b; min-height:100vh; display:flex; align-items:center; justify-content:center; padding:16px; }
.app { max-width:700px; width:100%; background:white; border-radius:28px; box-shadow:0 20px 60px rgba(0,0,0,0.08); padding:24px 20px 32px; }
h1 { font-size:24px; font-weight:700; text-align:center; margin-bottom:20px; color:#0f172a; }
.page { display:none; animation:fade .25s ease; }
.page.active { display:block; }
@keyframes fade { 0%{opacity:0;transform:translateY(6px)} 100%{opacity:1;transform:translateY(0)} }
.menu-grid { display:flex; flex-direction:column; gap:14px; margin-top:12px; }
.menu-btn { background:#f8fafc; border:1px solid #e2e8f0; border-radius:16px; padding:18px 20px; font-size:18px; font-weight:600; color:#0f172a; cursor:pointer; transition:all .15s; text-align:left; display:flex; align-items:center; gap:12px; }
.menu-btn:active { background:#eef2f6; transform:scale(0.98); }
.menu-btn .icon { font-size:28px; }
.menu-btn .badge { background:#e2e8f0; border-radius:30px; padding:2px 12px; font-size:14px; font-weight:500; color:#475569; }
.page-header { display:flex; align-items:center; gap:12px; margin-bottom:20px; }
.back-btn { background:none; border:none; font-size:28px; cursor:pointer; padding:4px 8px; border-radius:12px; }
.back-btn:active { background:#e2e8f0; }
.page-title { font-size:20px; font-weight:700; flex:1; }
.action-btn { background:#eef2f6; border:none; border-radius:30px; padding:6px 16px; font-size:14px; font-weight:600; color:#1e293b; cursor:pointer; display:flex; align-items:center; gap:6px; }
.action-btn:active { background:#cbd5e1; }
.action-btn.primary { background:#0f172a; color:white; }
.action-btn.primary:active { background:#1e293b; }
.video-wrapper { background:#f1f5f9; border-radius:20px; overflow:hidden; margin:12px 0 16px; position:relative; }
#video { width:100%; display:block; aspect-ratio:4/3; object-fit:cover; background:#0f172a; }
.cam-controls { display:flex; gap:12px; flex-wrap:wrap; justify-content:center; margin:12px 0 8px; }
.cam-btn { background:#0f172a; border:none; border-radius:40px; padding:12px 28px; color:white; font-weight:600; font-size:16px; cursor:pointer; flex:1 1 auto; min-width:120px; }
.cam-btn:active { background:#1e293b; }
.cam-btn.secondary { background:#e2e8f0; color:#0f172a; }
.cam-btn.secondary:active { background:#cbd5e1; }
.cam-btn.success { background:#16a34a; }
.cam-btn.success:active { background:#15803d; }
.cam-btn:disabled { opacity:0.5; cursor:not-allowed; }
.status-msg { text-align:center; padding:12px; font-weight:500; border-radius:12px; margin:8px 0; }
.status-msg.success { background:#dcfce7; color:#166534; }
.status-msg.error { background:#fee2e2; color:#991b1b; }
.status-msg.info { background:#e0f2fe; color:#0369a1; }
.status-msg.warning { background:#fef3c7; color:#92400e; }
.table-wrap { overflow-x:auto; margin:12px 0 16px; border-radius:16px; border:1px solid #e2e8f0; }
table { width:100%; border-collapse:collapse; font-size:15px; }
th { background:#f8fafc; text-align:left; padding:12px 16px; font-weight:600; border-bottom:1px solid #e2e8f0; }
td { padding:10px 16px; border-bottom:1px solid #f1f5f9; }
tr:last-child td { border-bottom:none; }
.status-present { color:#16a34a; font-weight:600; }
.status-absent { color:#dc2626; font-weight:600; }
.empty-msg { text-align:center; padding:32px 16px; color:#64748b; }
.date-picker { display:flex; gap:10px; align-items:center; margin:8px 0 16px; flex-wrap:wrap; }
.date-picker input[type="date"] { padding:10px 14px; border:1px solid #d1d5db; border-radius:30px; font-size:16px; background:white; flex:1 1 180px; }
.date-picker button { background:#0f172a; border:none; border-radius:30px; padding:10px 22px; color:white; font-weight:600; font-size:15px; cursor:pointer; }
.date-picker button:active { background:#1e293b; }
.mt-8 { margin-top:8px; }
.result-box { padding:16px; border-radius:16px; margin:12px 0; text-align:center; }
.result-box .name { font-size:28px; font-weight:700; }
.result-box .sub { font-size:16px; color:#475569; margin-top:4px; }
.result-box.success { background:#dcfce7; border:1px solid #86efac; }
.result-box.error { background:#fee2e2; border:1px solid #fca5a5; }
.result-box .emoji { font-size:40px; display:block; margin-bottom:8px; }
.hidden { display:none; }
.badge-count { background:#e2e8f0; border-radius:30px; padding:2px 12px; font-size:14px; font-weight:500; color:#475569; }
.flex { display:flex; gap:12px; }
.flex button { flex:1; }
</style>
</head>
<body>
<div class="app" id="app">
<h1>Smart Attendance System</h1>
<div id="page-main" class="page active">
<div class="menu-grid">
<button class="menu-btn" id="goFace">
<span class="label">Face Recognition Attendance</span>
<span class="badge">Live</span>
</button>
<button class="menu-btn" id="goAttendance">
<span class="label">Today’s Attendance</span>
<span class="badge">View</span>
</button>
<button class="menu-btn" id="goAbsentees">
<span class="label">Today’s Absentees</span>
<span class="badge">View</span>
</button>
</div>
<div style="margin-top:24px; text-align:center; font-size:14px; color:#94a3b8;">
<span>Connected via GitHub proxy</span>
</div>
</div>
<div id="page-face" class="page">
<div class="page-header">
<button class="back-btn" data-back="main">‹</button>
<span class="page-title">Face Recognition</span>
</div>
<div class="video-wrapper">
<video id="video" autoplay playsinline></video>
</div>
<div class="cam-controls">
<button class="cam-btn" id="startCam">Start Camera</button>
<button class="cam-btn secondary" id="stopCam">Stop</button>
<button class="cam-btn success" id="markAttendanceBtn" disabled>Mark Attendance</button>
</div>
<div id="faceStatus" class="status-msg info">Camera off. Start camera, then click “Mark Attendance”.</div>
<div id="resultBox" class="result-box hidden">
<span class="emoji" id="resultEmoji"></span>
<div class="name" id="resultName">—</div>
<div class="sub" id="resultSub"></div>
</div>
</div>
<div id="page-attendance" class="page">
<div class="page-header">
<button class="back-btn" data-back="main">‹</button>
<span class="page-title">Attendance</span>
<button class="action-btn primary" id="downloadAttendance">Download Excel</button>
</div>
<div class="date-picker">
<input type="date" id="attDate" />
<button id="loadAttendance">Load</button>
</div>
<div id="attendanceTableWrap" class="table-wrap">
<div class="empty-msg">Select a date and click Load.</div>
</div>
</div>
<div id="page-absentees" class="page">
<div class="page-header">
<button class="back-btn" data-back="main">‹</button>
<span class="page-title">Absentees</span>
<button class="action-btn primary" id="downloadAbsentees">Download Excel</button>
</div>
<div class="date-picker">
<input type="date" id="absDate" />
<button id="loadAbsentees">Load</button>
</div>
<div id="absenteesList" class="table-wrap">
<div class="empty-msg">Select a date and click Load.</div>
</div>
</div>
</div>
<script>
async function githubRequest(method, path, data = null) {
const url = '/api/github';
console.log(`Sending ${method} to ${url} with path: ${path}`);
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path, method, data }),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `HTTP ${response.status}`);
}
return await response.json();
}
async function getFileContent(path) {
try {
const data = await githubRequest('GET', path);
if (data.content) {
const content = atob(data.content.replace(/\n/g, ''));
return { content, sha: data.sha };
}
return null;
} catch (e) {
if (e.message.includes('404')) return null;
throw e;
}
}
async function updateFile(path, content, message = 'Update file') {
const existing = await getFileContent(path);
const payload = {
message,
content: btoa(content),
sha: existing ? existing.sha : undefined,
};
return await githubRequest('PUT', path, payload);
}
let students = [];
let studentNames = [];
async function loadStudents() {
try {
const file = await getFileContent('students.json');
if (!file) {
console.warn('students.json not found');
students = [];
studentNames = [];
return;
}
const data = JSON.parse(file.content);
students = data.map(s => {
let descriptors;
if (s.descriptors && Array.isArray(s.descriptors)) {
descriptors = s.descriptors.map(d => new Float32Array(d));
} else if (s.descriptor) {
descriptors = [new Float32Array(s.descriptor)];
} else {
throw new Error('Missing descriptors or descriptor');
}
return { name: s.name, descriptors };
});
studentNames = students.map(s => s.name);
console.log(`Loaded ${students.length} students.`);
} catch (e) {
console.error('Failed to load students:', e);
students = [];
studentNames = [];
}
}
function getTodayStr() {
return new Date().toISOString().split('T')[0];
}
function getCsvPath(dateStr) {
return `register/${dateStr}.csv`;
}
async function loadAttendanceCsv(dateStr) {
try {
const file = await getFileContent(getCsvPath(dateStr));
if (!file) return null;
const lines = file.content.trim().split('\n');
return lines.map(line => {
const [name, status] = line.split(',');
return { name: name.trim(), status: status.trim() };
});
} catch (e) {
return null;
}
}
async function getFullAttendance(dateStr) {
let records = await loadAttendanceCsv(dateStr);
const allNames = await getAllStudentNames();
if (!records) {
records = allNames.map(name => ({ name, status: 'Absent' }));
} else {
const existing = new Set(records.map(r => r.name));
for (const name of allNames) {
if (!existing.has(name)) {
records.push({ name, status: 'Absent' });
}
}
}
records.sort((a, b) => a.name.localeCompare(b.name));
return records;
}
async function getAllStudentNames() {
await loadStudents();
return studentNames;
}
function showPage(pageId) {
document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
document.getElementById(pageId).classList.add('active');
}
document.querySelectorAll('[data-back]').forEach(btn => {
btn.addEventListener('click', () => showPage('page-main'));
});
document.getElementById('goFace').addEventListener('click', () => {
showPage('page-face');
initFaceRecognition();
});
document.getElementById('goAttendance').addEventListener('click', () => {
showPage('page-attendance');
const today = getTodayStr();
document.getElementById('attDate').value = today;
loadAttendance(today);
});
document.getElementById('goAbsentees').addEventListener('click', () => {
showPage('page-absentees');
const today = getTodayStr();
document.getElementById('absDate').value = today;
loadAbsentees(today);
});
let faceModelsLoaded = false;
let cameraStream = null;
const video = document.getElementById('video');
const faceStatus = document.getElementById('faceStatus');
const resultBox = document.getElementById('resultBox');
const resultEmoji = document.getElementById('resultEmoji');
const resultName = document.getElementById('resultName');
const resultSub = document.getElementById('resultSub');
const markBtn = document.getElementById('markAttendanceBtn');
function setFaceStatus(msg, type = 'info') {
faceStatus.textContent = msg;
faceStatus.className = 'status-msg ' + type;
}
function showResult(emoji, name, sub, type) {
resultBox.classList.remove('hidden', 'success', 'error');
resultBox.classList.add(type);
resultEmoji.textContent = emoji;
resultName.textContent = name;
resultSub.textContent = sub;
}
function hideResult() {
resultBox.classList.add('hidden');
}
async function loadFaceModels() {
if (faceModelsLoaded) return true;
markBtn.disabled = true;
setFaceStatus('Loading face models...Please wait', 'info');
try {
const MODEL_URL = 'https://cdn.jsdelivr.net/npm/@vladmandic/face-api@1.7.11/model/';
await faceapi.nets.ssdMobilenetv1.loadFromUri(MODEL_URL);
await faceapi.nets.faceLandmark68Net.loadFromUri(MODEL_URL);
await faceapi.nets.faceRecognitionNet.loadFromUri(MODEL_URL);
faceModelsLoaded = true;
setFaceStatus('Models loaded. Start camera.', 'success');
markBtn.disabled = false;
return true;
} catch (e) {
console.warn('Primary model load failed, trying fallback...', e);
try {
const FALLBACK_URL = 'https://justadudewhohacks.github.io/face-api.js/models/';
await faceapi.nets.ssdMobilenetv1.loadFromUri(FALLBACK_URL);
await faceapi.nets.faceLandmark68Net.loadFromUri(FALLBACK_URL);
await faceapi.nets.faceRecognitionNet.loadFromUri(FALLBACK_URL);
faceModelsLoaded = true;
setFaceStatus('Models loaded (fallback). Start camera.', 'success');
markBtn.disabled = false;
return true;
} catch (e2) {
setFaceStatus('Failed to load models. Check internet.', 'error');
markBtn.disabled = true;
return false;
}
}
}
async function initFaceRecognition() {
await loadFaceModels();
await loadStudents();
if (students.length === 0) {
setFaceStatus('No students loaded. Please create students.json.', 'error');
markBtn.disabled = true;
} else {
setFaceStatus(`Loaded ${students.length} students. Start camera.`, 'info');
markBtn.disabled = false;
}
hideResult();
}
async function startCamera() {
if (cameraStream) stopCamera();
try {
cameraStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' }, audio: false });
video.srcObject = cameraStream;
await video.play();
setFaceStatus('Camera ready. Click "Mark Attendance".', 'info');
hideResult();
markBtn.disabled = false;
} catch (e) {
setFaceStatus('Camera access denied.', 'error');
markBtn.disabled = true;
}
}
function stopCamera() {
if (cameraStream) {
cameraStream.getTracks().forEach(t => t.stop());
cameraStream = null;
video.srcObject = null;
setFaceStatus('Camera stopped.', 'info');
hideResult();
}
}
function findBestMatch(descriptor) {
let bestDist = Infinity;
let bestStudent = null;
for (const student of students) {
for (const desc of student.descriptors) {
const dist = faceapi.euclideanDistance(descriptor, desc);
if (dist < bestDist) {
bestDist = dist;
bestStudent = student;
}
}
}
const THRESHOLD = 0.5; // stricter
if (bestDist < THRESHOLD) {
const confidence = Math.max(0, (1 - bestDist / THRESHOLD) * 100);
console.log(`Match found: ${bestStudent.name} with confidence ${confidence.toFixed(1)}%`);
return { student: bestStudent, distance: bestDist, confidence };
}
console.warn(`No match – best distance ${bestDist.toFixed(3)} > threshold`);
return null;
}
async function markAttendance() {
// Ensure models are loaded
if (!faceModelsLoaded) {
setFaceStatus('Models still loading, please wait...', 'warning');
await loadFaceModels();
if (!faceModelsLoaded) {
setFaceStatus(' Models failed to load. Cannot mark attendance.', 'error');
return;
}
}
if (!cameraStream || video.readyState < 2) {
setFaceStatus('Start camera first.', 'error');
return;
}
setFaceStatus('Wait recognising...', 'info');
hideResult();
try {
const detection = await faceapi.detectSingleFace(video, new faceapi.SsdMobilenetv1Options())
.withFaceLandmarks()
.withFaceDescriptor();
if (!detection) {
showResult(' No face detected', 'Please look at the camera and try again.', 'error');
setFaceStatus(' No face in frame.', 'error');
return;
}
const descriptor = detection.descriptor;
const match = findBestMatch(descriptor);
if (!match) {
showResult('Not recognised', 'You are not in our system. Please contact admin.', 'error');
setFaceStatus('Unknown person.', 'error');
return;
}
const name = match.student.name;
const confidence = (1 - match.distance) * 100;
// Mark attendance
const today = getTodayStr();
const records = await getFullAttendance(today);
const found = records.find(r => r.name === name);
if (found && found.status === 'Present') {
showResult(name, `Already marked present today (confidence ${confidence.toFixed(1)}%).`, 'success');
setFaceStatus(`${name} already present.`, 'info');
return;
}
const updated = records.map(r => {
if (r.name === name) r.status = 'Present';
return r;
});
const csvContent = updated.map(r => `${r.name},${r.status}`).join('\n');
await updateFile(getCsvPath(today), csvContent, `Mark ${name} present`);
showResult(name, `Attendance marked! (confidence ${confidence.toFixed(1)}%)`, 'success');
setFaceStatus(`${name} marked present!`, 'success');
} catch (err) {
showResult('Error', err.message, 'error');
setFaceStatus('Error: ' + err.message, 'error');
}
}
document.getElementById('startCam').addEventListener('click', startCamera);
document.getElementById('stopCam').addEventListener('click', stopCamera);
document.getElementById('markAttendanceBtn').addEventListener('click', markAttendance);
async function loadAttendance(dateStr) {
const wrap = document.getElementById('attendanceTableWrap');
wrap.innerHTML = '<div class="empty-msg">Loading...</div>';
try {
const records = await getFullAttendance(dateStr);
if (!records || records.length === 0) {
wrap.innerHTML = '<div class="empty-msg">No records.</div>';
return;
}
let html = `<table><thead><tr><th>Name</th><th>Status</th></tr></thead><tbody>`;
let present = 0;
for (const r of records) {
const isPresent = r.status === 'Present';
if (isPresent) present++;
html += `<tr><td>${r.name}</td><td class="${isPresent ? 'status-present' : 'status-absent'}">${r.status}</td></tr>`;
}
html += `</tbody></table>`;
wrap.innerHTML = html;
const summary = document.createElement('div');
summary.style.marginTop = '12px';
summary.style.fontWeight = '600';
summary.textContent = `Present: ${present} | Absent: ${records.length - present}`;
wrap.parentNode.insertBefore(summary, wrap.nextSibling);
} catch (e) {
wrap.innerHTML = `<div class="empty-msg">Error: ${e.message}</div>`;
}
}
async function loadAbsentees(dateStr) {
const wrap = document.getElementById('absenteesList');
wrap.innerHTML = '<div class="empty-msg">Loading...</div>';
try {
const records = await getFullAttendance(dateStr);
const absent = records.filter(r => r.status === 'Absent');
if (absent.length === 0) {
wrap.innerHTML = '<div class="empty-msg">Everyone is present!</div>';
return;
}
let html = `<table><thead><tr><th>Name</th></tr></thead><tbody>`;
for (const r of absent) html += `<tr><td>${r.name}</td></tr>`;
html += `</tbody></table>`;
wrap.innerHTML = html;
} catch (e) {
wrap.innerHTML = `<div class="empty-msg">Error: ${e.message}</div>`;
}
}
document.getElementById('loadAttendance').addEventListener('click', () => {
const date = document.getElementById('attDate').value;
if (date) loadAttendance(date);
});
document.getElementById('loadAbsentees').addEventListener('click', () => {
const date = document.getElementById('absDate').value;
if (date) loadAbsentees(date);
});
async function downloadAttendanceForDate(dateStr, type = 'attendance') {
try {
const records = await getFullAttendance(dateStr);
let data;
if (type === 'absentees') {
data = records.filter(r => r.status === 'Absent').map(r => ({ Name: r.name }));
} else {
data = records.map(r => ({ Name: r.name, Status: r.status }));
}
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.json_to_sheet(data);
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
XLSX.writeFile(wb, `${type}_${dateStr}.xlsx`);
} catch (e) {
alert('Download failed: ' + e.message);
}
}
document.getElementById('downloadAttendance').addEventListener('click', () => {
const date = document.getElementById('attDate').value;
if (date) downloadAttendanceForDate(date, 'attendance');
});
document.getElementById('downloadAbsentees').addEventListener('click', () => {
const date = document.getElementById('absDate').value;
if (date) downloadAttendanceForDate(date, 'absentees');
});
(async function init() {
showPage('page-main');
await loadStudents();
const today = getTodayStr();
document.getElementById('attDate').value = today;
document.getElementById('absDate').value = today;
console.log('App ready.');
})();
</script>
</body>
</html>
<!---Please don't try to change or edit without knowning what you are doing--->