bChaukar commited on
Commit
f4d74f2
·
verified ·
1 Parent(s): 3bf00b5

Upload 13 files

Browse files
Files changed (4) hide show
  1. dashboard.html +59 -658
  2. practice.html +1 -1
  3. rise-frontend.js +826 -377
  4. speaking.html +1 -1
dashboard.html CHANGED
@@ -1,4 +1,3 @@
1
-
2
  <!DOCTYPE html>
3
  <html lang="en">
4
  <head>
@@ -6,211 +5,7 @@
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
  <title>Dashboard - RISE</title>
8
  <link rel="stylesheet" href="style.css">
9
-
10
- <style>
11
- .rise-dashboard {
12
- max-width: 1180px;
13
- margin: 0 auto;
14
- padding: 30px 22px 55px;
15
- color: #172033;
16
- }
17
-
18
- .rise-dashboard * { box-sizing: border-box; }
19
-
20
- .rd-welcome {
21
- padding: 30px;
22
- border-radius: 22px;
23
- background: linear-gradient(120deg, #e9f7f4, #f2f5ff);
24
- margin-bottom: 25px;
25
- }
26
-
27
- .rd-eyebrow {
28
- font-size: 12px;
29
- font-weight: 800;
30
- letter-spacing: 1.6px;
31
- color: #0d8178;
32
- }
33
-
34
- .rd-welcome h1 {
35
- font-size: clamp(27px, 4vw, 38px);
36
- margin: 12px 0;
37
- }
38
-
39
- .rd-welcome p { line-height: 1.65; }
40
-
41
- .rd-button {
42
- display: inline-block;
43
- padding: 12px 20px;
44
- border-radius: 10px;
45
- background: #087f75;
46
- color: white;
47
- text-decoration: none;
48
- font-weight: 700;
49
- margin-top: 10px;
50
- }
51
-
52
- .rd-section { margin-top: 32px; }
53
-
54
- .rd-section h2 {
55
- font-size: 23px;
56
- margin-bottom: 7px;
57
- }
58
-
59
- .rd-muted { color: #64748b; font-size: 14px; }
60
-
61
- .rd-grid {
62
- display: grid;
63
- grid-template-columns: repeat(4, minmax(0, 1fr));
64
- gap: 15px;
65
- margin-top: 18px;
66
- }
67
-
68
- .rd-card {
69
- background: white;
70
- border: 1px solid #e2e8f0;
71
- border-radius: 17px;
72
- padding: 20px;
73
- min-width: 0;
74
- box-shadow: 0 5px 18px rgba(15, 23, 42, 0.035);
75
- }
76
-
77
- .rd-stat-label {
78
- font-size: 13px;
79
- color: #64748b;
80
- font-weight: 650;
81
- }
82
-
83
- .rd-stat {
84
- font-size: 30px;
85
- font-weight: 800;
86
- margin: 12px 0 5px;
87
- overflow-wrap: anywhere;
88
- }
89
-
90
- .rd-stat-note {
91
- font-size: 12px;
92
- color: #64748b;
93
- line-height: 1.5;
94
- }
95
-
96
- .rd-chart-grid {
97
- display: grid;
98
- grid-template-columns: repeat(2, minmax(0, 1fr));
99
- gap: 18px;
100
- margin-top: 18px;
101
- }
102
-
103
- .rd-chart-card {
104
- background: white;
105
- border: 1px solid #e2e8f0;
106
- border-radius: 17px;
107
- padding: 20px;
108
- min-width: 0;
109
- }
110
-
111
- .rd-chart-card h3 { margin: 0 0 6px; }
112
-
113
- .rd-chart-wrap {
114
- position: relative;
115
- width: 100%;
116
- height: 245px;
117
- margin-top: 15px;
118
- }
119
-
120
- .rd-chart-wrap canvas {
121
- display: block;
122
- width: 100%;
123
- height: 100%;
124
- }
125
-
126
- .rd-progress-track {
127
- height: 9px;
128
- background: #e2e8f0;
129
- border-radius: 20px;
130
- overflow: hidden;
131
- margin: 14px 0 8px;
132
- }
133
-
134
- .rd-progress-fill {
135
- height: 100%;
136
- width: 0%;
137
- background: #0d9488;
138
- border-radius: inherit;
139
- transition: width .35s ease;
140
- }
141
-
142
- .rd-levels {
143
- display: grid;
144
- grid-template-columns: repeat(5, minmax(0, 1fr));
145
- gap: 10px;
146
- margin-top: 18px;
147
- }
148
-
149
- .rd-level {
150
- padding: 15px 8px;
151
- text-align: center;
152
- border: 1px solid #e2e8f0;
153
- border-radius: 13px;
154
- background: #f8fafc;
155
- }
156
-
157
- .rd-level strong { display: block; margin-bottom: 7px; }
158
- .rd-level span { font-size: 12px; color: #64748b; }
159
- .rd-level.current { background: #e0f2fe; border-color: #38bdf8; }
160
- .rd-level.passed { background: #dcfce7; border-color: #86efac; }
161
-
162
- .rd-table-wrap { overflow-x: auto; margin-top: 15px; }
163
-
164
- .rd-table {
165
- width: 100%;
166
- border-collapse: collapse;
167
- font-size: 14px;
168
- }
169
-
170
- .rd-table th, .rd-table td {
171
- padding: 13px 10px;
172
- border-bottom: 1px solid #e2e8f0;
173
- text-align: left;
174
- white-space: nowrap;
175
- }
176
-
177
- .rd-table th { color: #64748b; font-weight: 700; }
178
-
179
- .rd-empty {
180
- padding: 25px 10px;
181
- text-align: center;
182
- color: #64748b;
183
- line-height: 1.7;
184
- }
185
-
186
- .rd-streak-message {
187
- background: #f8fafc;
188
- padding: 13px;
189
- border-radius: 11px;
190
- margin-top: 15px;
191
- font-size: 14px;
192
- line-height: 1.6;
193
- }
194
-
195
- @media (max-width: 850px) {
196
- .rd-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
197
- .rd-chart-grid { grid-template-columns: 1fr; }
198
- }
199
-
200
- @media (max-width: 500px) {
201
- .rise-dashboard { padding: 20px 14px 40px; }
202
- .rd-welcome { padding: 22px; }
203
- .rd-grid { gap: 10px; }
204
- .rd-card { padding: 15px; }
205
- .rd-stat { font-size: 25px; }
206
- .rd-levels { gap: 5px; }
207
- .rd-level { padding: 12px 3px; }
208
- .rd-level strong { font-size: 12px; }
209
- .rd-level span { font-size: 10px; }
210
- }
211
- </style>
212
  </head>
213
-
214
  <body>
215
  <nav class="navbar">
216
  <div class="logo">RISE</div>
@@ -222,465 +17,71 @@
222
  <a href="index.html" class="signin-btn">Log Out</a>
223
  </nav>
224
 
225
- <main class="rise-dashboard">
226
-
227
- <section class="rd-welcome">
228
- <div class="rd-eyebrow">YOUR PERSONAL LEARNING SPACE</div>
229
- <h1>Welcome back to RISE</h1>
230
- <p>
231
- Every practice session is a step forward.
232
- Keep reading, track your improvement, and build your confidence.
233
- </p>
234
- <p id="rd-date" class="rd-muted"></p>
235
- <a href="practice.html" class="rd-button">Continue Practising</a>
236
- </section>
237
-
238
- <section class="rd-section" id="progress">
239
- <h2>Your learning at a glance</h2>
240
- <p class="rd-muted">Your statistics update as you complete reading sessions.</p>
241
-
242
- <div class="rd-grid">
243
- <article class="rd-card">
244
- <div class="rd-stat-label">Current streak</div>
245
- <div class="rd-stat" id="rd-streak">0 days</div>
246
- <div class="rd-stat-note" id="rd-streak-note">Complete a session to begin.</div>
247
- </article>
248
-
249
- <article class="rd-card">
250
- <div class="rd-stat-label">Practice sessions</div>
251
- <div class="rd-stat" id="rd-sessions">0</div>
252
- <div class="rd-stat-note">Recorded reading results</div>
253
- </article>
254
-
255
- <article class="rd-card">
256
- <div class="rd-stat-label">Average score</div>
257
- <div class="rd-stat" id="rd-average">--</div>
258
- <div class="rd-stat-note">Average overall score</div>
259
- </article>
260
-
261
- <article class="rd-card">
262
- <div class="rd-stat-label">Best score</div>
263
- <div class="rd-stat" id="rd-best">--</div>
264
- <div class="rd-stat-note">Your highest recorded score</div>
265
- </article>
266
- </div>
267
- </section>
268
-
269
- <section class="rd-section">
270
- <h2>Your activity and improvement</h2>
271
- <p class="rd-muted">Review your practice frequency and recent scores.</p>
272
-
273
- <div class="rd-chart-grid">
274
- <article class="rd-chart-card">
275
- <h3>Weekly activity</h3>
276
- <p class="rd-muted">Days on which you completed a session</p>
277
- <div class="rd-chart-wrap">
278
- <canvas id="rd-week-chart" role="img"
279
- aria-label="Bar chart of practice sessions by day"></canvas>
280
- </div>
281
- <p class="rd-muted" id="rd-week-total"></p>
282
- </article>
283
-
284
- <article class="rd-chart-card">
285
- <h3>Score trend</h3>
286
- <p class="rd-muted">Your most recent recorded results</p>
287
- <div class="rd-chart-wrap">
288
- <canvas id="rd-score-chart" role="img"
289
- aria-label="Line chart of recent overall scores"></canvas>
290
- </div>
291
- <p class="rd-muted">The dashed line represents the 80% target.</p>
292
- </article>
293
- </div>
294
- </section>
295
-
296
- <section class="rd-section">
297
- <h2>Level progression</h2>
298
- <p class="rd-muted">
299
- Your starting level comes from your saved assessment setting.
300
- This display does not independently unlock levels.
301
- </p>
302
-
303
- <div class="rd-card">
304
- <div class="rd-stat-label">Starting level</div>
305
- <div class="rd-stat" id="rd-current-level">Level 1</div>
306
- <div id="rd-level-description" class="rd-muted"></div>
307
- <div class="rd-progress-track">
308
- <div class="rd-progress-fill" id="rd-level-progress"></div>
309
- </div>
310
- <div class="rd-stat-note" id="rd-level-note"></div>
311
- </div>
312
-
313
- <div class="rd-levels" id="rd-levels"></div>
314
- </section>
315
-
316
- <section class="rd-section">
317
- <h2>Recent practice sessions</h2>
318
- <p class="rd-muted">Your saved results from the RISE practice page.</p>
319
-
320
- <div class="rd-card">
321
- <div class="rd-table-wrap">
322
- <table class="rd-table">
323
- <thead>
324
- <tr>
325
- <th>Level</th>
326
- <th>Activity</th>
327
- <th>Overall score</th>
328
- <th>Word accuracy</th>
329
- <th>Word error rate</th>
330
- </tr>
331
- </thead>
332
- <tbody id="rd-history-body"></tbody>
333
- </table>
334
- </div>
335
- <div id="rd-history-empty" class="rd-empty" hidden>
336
- No practice results saved yet.<br>
337
- Start a reading session and select “Finish passage &amp; show score”
338
- to record your results.
339
- </div>
340
- </div>
341
- </section>
342
 
343
- <section class="rd-section">
344
- <h2>Your next step</h2>
345
- <div class="rd-card">
346
- <h3 id="rd-next-title">Start your first session</h3>
347
- <p class="rd-muted" id="rd-next-description">
348
- Read a sentence, review your feedback, and continue practising.
349
- </p>
350
- <a href="practice.html" class="rd-button">Go to Practice</a>
 
 
 
 
351
  </div>
352
- </section>
353
-
354
- </main>
355
-
356
- <footer>
357
- <div class="logo">RISE</div>
358
- <p>AI-powered reading and communication assistance.</p>
359
- <p class="copyright">© 2026 RISE. All rights reserved.</p>
360
- </footer>
 
 
361
 
 
362
  <script>
363
  (() => {
364
- "use strict";
365
-
366
- const $ = id => document.getElementById(id);
367
- const levelNames = [
368
- "Beginner",
369
- "Elementary",
370
- "Intermediate",
371
- "Upper Intermediate",
372
- "Advanced"
373
- ];
374
-
375
- function readArray(key) {
376
- try {
377
- const value = JSON.parse(localStorage.getItem(key) || "[]");
378
- return Array.isArray(value) ? value : [];
379
- } catch {
380
- return [];
381
- }
382
- }
383
-
384
- function number(value) {
385
- const n = Number(value);
386
- return Number.isFinite(n) ? n : 0;
387
- }
388
-
389
- function dayKey(date) {
390
- const y = date.getFullYear();
391
- const m = String(date.getMonth() + 1).padStart(2, "0");
392
- const d = String(date.getDate()).padStart(2, "0");
393
- return `${y}-${m}-${d}`;
394
- }
395
-
396
- function readPracticeDays() {
397
- return [...new Set(
398
- readArray("risePracticeDays")
399
- .filter(d => typeof d === "string" &&
400
- /^\d{4}-\d{2}-\d{2}$/.test(d))
401
- )].sort();
402
- }
403
-
404
- function calculateStreak(days) {
405
- const set = new Set(days);
406
- const today = new Date();
407
- const todayKey = dayKey(today);
408
- const yesterday = new Date(today);
409
- yesterday.setDate(yesterday.getDate() - 1);
410
- const yesterdayKey = dayKey(yesterday);
411
-
412
- // A streak remains active until the current day is missed.
413
- let cursor;
414
- if (set.has(todayKey)) cursor = today;
415
- else if (set.has(yesterdayKey)) cursor = yesterday;
416
- else return 0;
417
-
418
- let count = 0;
419
- while (set.has(dayKey(cursor))) {
420
- count++;
421
- cursor.setDate(cursor.getDate() - 1);
422
- }
423
- return count;
424
- }
425
-
426
- function levelNumber(value) {
427
- if (typeof value === "number") {
428
- return Math.min(5, Math.max(1, value));
429
- }
430
-
431
- const names = [
432
- "beginner", "elementary", "intermediate",
433
- "upper_intermediate", "advanced"
434
- ];
435
- const index = names.indexOf(String(value || "").toLowerCase());
436
- if (index >= 0) return index + 1;
437
-
438
- const match = String(value || "").match(/level\s*([1-5])/i);
439
- return match ? Number(match[1]) : 1;
440
- }
441
-
442
- function drawBarChart(canvas, labels, values) {
443
- const ctx = canvas.getContext("2d");
444
- const rect = canvas.getBoundingClientRect();
445
- const width = Math.max(280, rect.width);
446
- const height = Math.max(200, rect.height);
447
- const ratio = window.devicePixelRatio || 1;
448
-
449
- canvas.width = width * ratio;
450
- canvas.height = height * ratio;
451
- ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
452
- ctx.clearRect(0, 0, width, height);
453
-
454
- const left = 32, right = 10, top = 18, bottom = 35;
455
- const plotW = width - left - right;
456
- const plotH = height - top - bottom;
457
- const maxValue = Math.max(3, ...values);
458
-
459
- ctx.font = "11px sans-serif";
460
- ctx.textAlign = "right";
461
- ctx.fillStyle = "#64748b";
462
-
463
- for (let i = 0; i <= 3; i++) {
464
- const y = top + plotH * i / 3;
465
- const value = Math.round(maxValue * (3 - i) / 3);
466
- ctx.fillText(String(value), left - 7, y + 4);
467
- ctx.beginPath();
468
- ctx.strokeStyle = "#e2e8f0";
469
- ctx.moveTo(left, y);
470
- ctx.lineTo(width - right, y);
471
- ctx.stroke();
472
- }
473
-
474
- const slot = plotW / labels.length;
475
- const barW = Math.min(28, slot * 0.55);
476
-
477
- labels.forEach((label, i) => {
478
- const h = plotH * values[i] / maxValue;
479
- const x = left + i * slot + (slot - barW) / 2;
480
- const y = top + plotH - h;
481
-
482
- ctx.fillStyle = "#0d9488";
483
- ctx.fillRect(x, y, barW, h);
484
-
485
- ctx.textAlign = "center";
486
- ctx.fillStyle = "#64748b";
487
- ctx.fillText(label, x + barW / 2, height - 12);
488
- });
489
- }
490
-
491
- function drawScoreChart(canvas, scores) {
492
- const ctx = canvas.getContext("2d");
493
- const rect = canvas.getBoundingClientRect();
494
- const width = Math.max(280, rect.width);
495
- const height = Math.max(200, rect.height);
496
- const ratio = window.devicePixelRatio || 1;
497
-
498
- canvas.width = width * ratio;
499
- canvas.height = height * ratio;
500
- ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
501
- ctx.clearRect(0, 0, width, height);
502
-
503
- const left = 34, right = 14, top = 20, bottom = 30;
504
- const plotW = width - left - right;
505
- const plotH = height - top - bottom;
506
-
507
- ctx.font = "11px sans-serif";
508
- ctx.textAlign = "right";
509
- ctx.fillStyle = "#64748b";
510
-
511
- [0, 25, 50, 75, 100].forEach(v => {
512
- const y = top + plotH * (100 - v) / 100;
513
- ctx.fillText(v + "%", left - 6, y + 4);
514
- ctx.beginPath();
515
- ctx.strokeStyle = v === 80 ? "#f59e0b" : "#e2e8f0";
516
- ctx.setLineDash(v === 80 ? [5, 4] : []);
517
- ctx.moveTo(left, y);
518
- ctx.lineTo(width - right, y);
519
- ctx.stroke();
520
- });
521
- ctx.setLineDash([]);
522
-
523
- if (!scores.length) {
524
- ctx.textAlign = "center";
525
- ctx.fillStyle = "#64748b";
526
- ctx.fillText("Complete a session to see your scores", width / 2, height / 2);
527
- return;
528
- }
529
-
530
- const points = scores.map((score, i) => ({
531
- x: scores.length === 1
532
- ? left + plotW / 2
533
- : left + plotW * i / (scores.length - 1),
534
- y: top + plotH * (100 - score) / 100
535
- }));
536
-
537
- ctx.beginPath();
538
- points.forEach((p, i) => {
539
- if (i === 0) ctx.moveTo(p.x, p.y);
540
- else ctx.lineTo(p.x, p.y);
541
- });
542
- ctx.strokeStyle = "#2563eb";
543
- ctx.lineWidth = 2.5;
544
- ctx.stroke();
545
-
546
- points.forEach((p, i) => {
547
- ctx.beginPath();
548
- ctx.arc(p.x, p.y, 4, 0, Math.PI * 2);
549
- ctx.fillStyle = scores[i] >= 80 ? "#0d9488" : "#2563eb";
550
- ctx.fill();
551
- });
552
-
553
- ctx.textAlign = "center";
554
- ctx.fillStyle = "#64748b";
555
- points.forEach((p, i) => {
556
- ctx.fillText(String(i + 1), p.x, height - 10);
557
- });
558
- }
559
-
560
- function render() {
561
- $("rd-date").textContent = new Date().toLocaleDateString(
562
- undefined,
563
- { weekday: "long", year: "numeric", month: "long", day: "numeric" }
564
- );
565
-
566
- const history = readArray("riseHistory");
567
- const days = readPracticeDays();
568
- const streak = calculateStreak(days);
569
-
570
- // History is stored by the existing RISE practice frontend.
571
- const scores = history.map(r => number(r.overall))
572
- .filter(n => n >= 0 && n <= 100);
573
- const accuracies = history.map(r => number(r.word_accuracy))
574
- .filter(n => n >= 0 && n <= 100);
575
-
576
- const average = scores.length
577
- ? scores.reduce((a, b) => a + b, 0) / scores.length
578
- : null;
579
- const best = scores.length ? Math.max(...scores) : null;
580
-
581
- $("rd-streak").textContent = `${streak} ${streak === 1 ? "day" : "days"}`;
582
- $("rd-streak-note").textContent = streak
583
- ? "Keep practising regularly to maintain your streak."
584
- : "Practise today to start a new streak.";
585
-
586
- $("rd-sessions").textContent = history.length;
587
- $("rd-average").textContent = average === null
588
- ? "--" : average.toFixed(1) + "%";
589
- $("rd-best").textContent = best === null
590
- ? "--" : best.toFixed(1) + "%";
591
-
592
- const startingLevel = Math.min(5, Math.max(
593
- 1, Number(localStorage.getItem("startingLevel")) || 1
594
- ));
595
-
596
- $("rd-current-level").textContent = `Level ${startingLevel}`;
597
- $("rd-level-description").textContent = levelNames[startingLevel - 1];
598
-
599
- // This is a display of the starting level, not an unlock calculation.
600
- $("rd-level-progress").style.width =
601
- ((startingLevel - 1) / 4 * 100) + "%";
602
- $("rd-level-note").textContent =
603
- `Starting point: Level ${startingLevel} of 5.`;
604
-
605
- $("rd-levels").innerHTML = levelNames.map((name, i) => {
606
- const n = i + 1;
607
- const state = n === startingLevel ? "current" : "";
608
- const caption = n === startingLevel ? "Starting level" : "Level";
609
- return `<div class="rd-level ${state}">
610
- <strong>Level ${n}</strong>
611
- <span>${name}</span><br>
612
- <span>${caption}</span>
613
- </div>`;
614
- }).join("");
615
-
616
- const body = $("rd-history-body");
617
- body.replaceChildren();
618
-
619
- const recent = history.slice(-8).reverse();
620
- $("rd-history-empty").hidden = recent.length > 0;
621
-
622
- recent.forEach(r => {
623
- const tr = document.createElement("tr");
624
- const values = [
625
- `Level ${levelNumber(r.level)}`,
626
- String(r.part || "Reading"),
627
- number(r.overall).toFixed(1) + "%",
628
- number(r.word_accuracy).toFixed(1) + "%",
629
- number(r.wer).toFixed(1) + "%"
630
- ];
631
-
632
- values.forEach(value => {
633
- const td = document.createElement("td");
634
- td.textContent = value;
635
- tr.appendChild(td);
636
- });
637
-
638
- body.appendChild(tr);
639
- });
640
-
641
- const today = new Date();
642
- const weekLabels = [];
643
- const weekKeys = [];
644
-
645
- for (let i = 6; i >= 0; i--) {
646
- const date = new Date(today);
647
- date.setDate(today.getDate() - i);
648
- weekKeys.push(dayKey(date));
649
- weekLabels.push(date.toLocaleDateString(undefined, {weekday: "short"}));
650
- }
651
-
652
- const daySet = new Set(days);
653
- const weekCounts = weekKeys.map(key => daySet.has(key) ? 1 : 0);
654
-
655
- drawBarChart($("rd-week-chart"), weekLabels, weekCounts);
656
- $("rd-week-total").textContent =
657
- `${weekCounts.reduce((a, b) => a + b, 0)} of the last 7 days had recorded practice.`;
658
-
659
- drawScoreChart($("rd-score-chart"), scores.slice(-8));
660
-
661
- if (!history.length) {
662
- $("rd-next-title").textContent = "Start your first session";
663
- $("rd-next-description").textContent =
664
- "Your charts and statistics will populate after you complete and score a reading session.";
665
- } else if (average < 80) {
666
- $("rd-next-title").textContent = "Keep practising your current activity";
667
- $("rd-next-description").textContent =
668
- "Your recorded average is below 80%. Review your feedback and practise again to improve.";
669
- } else {
670
- $("rd-next-title").textContent = "Keep building consistency";
671
- $("rd-next-description").textContent =
672
- "Your recorded average is at least 80%. Follow the progression rules shown in the practice page.";
673
- }
674
  }
675
-
676
- render();
677
-
678
- // Keep charts sized correctly when the dashboard layout changes.
679
- let resizeTimer;
680
- window.addEventListener("resize", () => {
681
- clearTimeout(resizeTimer);
682
- resizeTimer = setTimeout(render, 150);
683
- });
 
 
 
 
 
 
 
 
 
 
 
 
684
  })();
685
  </script>
686
  </body>
 
 
1
  <!DOCTYPE html>
2
  <html lang="en">
3
  <head>
 
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
  <title>Dashboard - RISE</title>
7
  <link rel="stylesheet" href="style.css">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  </head>
 
9
  <body>
10
  <nav class="navbar">
11
  <div class="logo">RISE</div>
 
17
  <a href="index.html" class="signin-btn">Log Out</a>
18
  </nav>
19
 
20
+ <section class="dashboard-welcome">
21
+ <div>
22
+ <p class="small-title">WELCOME TO RISE</p>
23
+ <h1>Hello! 👋<br><span>Ready to grow your reading skills?</span></h1>
24
+ <p>Your personalized reading journey starts here. Choose a level and improve step by step.</p>
25
+ <p id="level-message"></p>
26
+ </div>
27
+ </section>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ <section class="dashboard-section" id="practice">
30
+ <div class="section-heading">
31
+ <p>YOUR PRACTICE</p>
32
+ <h2>Ready to practise?</h2>
33
+ <p>Choose your level, read aloud, and build your fluency one step at a time.</p>
34
+ </div>
35
+ <div class="dashboard-cards" style="grid-template-columns:minmax(260px,520px);justify-content:center">
36
+ <div class="dashboard-card" style="text-align:center">
37
+ <div class="dashboard-icon">📖</div>
38
+ <h3>Reading Practice</h3>
39
+ <p>Start with a sentence, progress to a paragraph, and finish with a story. Score above 80% to advance.</p>
40
+ <a href="practice.html" class="primary-btn" style="display:inline-flex;justify-content:center;align-items:center;text-decoration:none;width:100%;box-sizing:border-box">Start Practice</a>
41
  </div>
42
+ </div>
43
+ </section>
44
+
45
+ <section class="dashboard-section progress-section" id="progress">
46
+ <div class="section-heading"><p>YOUR PROGRESS</p><h2>Keep growing every day</h2></div>
47
+ <div class="progress-container">
48
+ <div class="progress-card"><h3>Communication Confidence</h3><div class="progress-bar"><div class="progress-fill"></div></div><p>Getting started</p></div>
49
+ <div class="progress-card"><h3>Practice Sessions</h3><div class="progress-number">0</div><p>Sessions completed</p></div>
50
+ <div class="progress-card"><h3>Starting Level</h3><div class="progress-number" id="current-level">Level 1</div><p id="level-description">Getting Started</p></div>
51
+ </div>
52
+ </section>
53
 
54
+ <footer><div class="logo">RISE</div><p>AI-powered reading and communication assistance.</p><p class="copyright">© 2026 RISE. All rights reserved.</p></footer>
55
  <script>
56
  (() => {
57
+ const email = (localStorage.getItem("riseActiveUserEmail") || "").trim().toLowerCase();
58
+ const key = email ? "riseUser:" + email : null;
59
+ let profile = key ? JSON.parse(localStorage.getItem(key) || "null") : null;
60
+ if (!profile) {
61
+ const level = 1;
62
+ profile = { startingLevel: level, unlockedLevel: level, attempts: [], sessionsCompleted: 0, averageScore: 0 };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  }
64
+ profile.startingLevel = Math.min(5, Math.max(1, Number(profile.startingLevel) || 1));
65
+ profile.unlockedLevel = Math.min(5, Math.max(profile.startingLevel, Number(profile.unlockedLevel) || profile.startingLevel));
66
+ profile.attempts = Array.isArray(profile.attempts) ? profile.attempts : [];
67
+ const names = {1:"Beginner",2:"Elementary",3:"Intermediate",4:"Upper Intermediate",5:"Advanced"};
68
+ const descriptions = {1:"Let's build basic reading skills.",2:"Let's strengthen familiar reading skills.",3:"Let's practise connected ideas and varied vocabulary.",4:"Let's develop more complex reading skills.",5:"Let's practise advanced vocabulary and sentence structures."};
69
+ document.getElementById("current-level").textContent = "Level " + profile.unlockedLevel;
70
+ document.getElementById("level-description").textContent = names[profile.unlockedLevel];
71
+ document.getElementById("level-message").textContent =
72
+ "Your current level is Level " + profile.unlockedLevel + " — " + names[profile.unlockedLevel] + ". " + descriptions[profile.unlockedLevel] +
73
+ " Levels 1–" + profile.unlockedLevel + " are available; higher levels unlock after you score at least 80% on the story at your current level.";
74
+ const count = document.querySelector(".progress-card:nth-child(2) .progress-number");
75
+ if (count) count.textContent = String(Number(profile.sessionsCompleted) || 0);
76
+ const scores = profile.attempts.map(a => Number(a.overall)).filter(n => Number.isFinite(n));
77
+ const avg = scores.length ? scores.reduce((a,b) => a+b,0) / scores.length : 0;
78
+ profile.averageScore = Math.round(avg * 100) / 100;
79
+ const confidence = document.querySelector(".progress-card:first-child .progress-fill");
80
+ if (confidence) confidence.style.width = Math.max(0, Math.min(100, profile.averageScore)) + "%";
81
+ const confidenceText = document.querySelector(".progress-card:first-child p");
82
+ if (confidenceText) confidenceText.textContent = scores.length ? "Average practice score: " + profile.averageScore + "%" : "No practice attempts recorded yet";
83
+ if (key) localStorage.setItem(key, JSON.stringify(profile));
84
+ document.querySelectorAll(".signin-btn").forEach(link => link.addEventListener("click", () => localStorage.removeItem("riseActiveUserEmail")));
85
  })();
86
  </script>
87
  </body>
practice.html CHANGED
@@ -52,7 +52,7 @@
52
 
53
  <footer><div class="logo">RISE</div><p>AI-powered reading and communication assistance.</p><p class="copyright">© 2026 RISE. All rights reserved.</p></footer>
54
  <script>
55
- window.RISE_API_BASE = "https://easter-fraction-rna-tommy.trycloudflare.com/";
56
  const picker = document.getElementById("level-picker");
57
  const readingArea = document.getElementById("reading-area");
58
  const activeEmail = (localStorage.getItem("riseActiveUserEmail") || "").trim().toLowerCase();
 
52
 
53
  <footer><div class="logo">RISE</div><p>AI-powered reading and communication assistance.</p><p class="copyright">© 2026 RISE. All rights reserved.</p></footer>
54
  <script>
55
+ window.RISE_API_BASE = "https://gmbh-highly-travelers-inputs.trycloudflare.com/";
56
  const picker = document.getElementById("level-picker");
57
  const readingArea = document.getElementById("reading-area");
58
  const activeEmail = (localStorage.getItem("riseActiveUserEmail") || "").trim().toLowerCase();
rise-frontend.js CHANGED
@@ -1,446 +1,895 @@
1
- from pathlib import Path
2
 
3
- code = r'''/* RISE frontend adapter */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  (() => {
5
- const $ = (s, root = document) => root.querySelector(s);
6
- const root = document.getElementById('rise-reader') ||
7
- document.getElementById('rise-reading-app');
 
8
 
9
  if (!root) {
10
- console.error('RISE: Could not find #rise-reader or #rise-reading-app.');
11
  return;
12
  }
13
 
14
- root.id = 'rise-reader';
15
-
16
- const levels = ['beginner', 'elementary', 'intermediate', 'upper_intermediate', 'advanced'];
17
- const levelLabels = ['Beginner', 'Elementary', 'Intermediate', 'Upper Intermediate', 'Advanced'];
18
- let apiBase = (window.RISE_API_BASE || localStorage.getItem('riseApiBase') || '').replace(/\/$/, '');
19
- let session = null, mediaStream = null, recorder = null, chunks = [], busy = false;
 
 
20
 
21
- const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({
22
- '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;'
23
- }[c]));
24
- const labelLevel = s => levelLabels[levels.indexOf(s)] || s;
25
- const labelPart = s => s ? s[0].toUpperCase() + s.slice(1) : '';
26
 
27
  root.innerHTML = `
28
- <style>
29
- #rise-reader{font-family:inherit;color:var(--body-text-color,#172033);margin:20px auto;max-width:1000px}
30
- #rise-reader *{box-sizing:border-box}
31
- .rise-shell{border:1px solid #dce3eb;border-radius:18px;padding:24px;background:var(--background-fill-primary,#fff)}
32
- .rise-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:18px 0}
33
- .rise-field label{display:block;font-weight:650;margin-bottom:6px}
34
- .rise-field input,.rise-field select{width:100%;padding:11px;border:1px solid #cbd5e1;border-radius:9px;font:inherit}
35
- .rise-actions{display:flex;flex-wrap:wrap;gap:9px;margin:15px 0}
36
- .rise-btn{padding:10px 14px;border:1px solid #cbd5e1;border-radius:9px;cursor:pointer;font:inherit;font-weight:600}
37
- .rise-primary{background:#5b4be0;color:white;border:0}
38
- .rise-btn:disabled{opacity:.5;cursor:not-allowed}
39
- .rise-passage{white-space:pre-wrap;font-size:1.15rem;line-height:1.9;padding:18px;background:#f7f8fc;border-radius:12px;margin:16px 0;color:#172033}
40
- .rise-status{min-height:24px;margin:12px 0}
41
- .rise-error{color:#b91c1c}.rise-success{color:#047857}
42
- .rise-pill{display:inline-block;padding:5px 9px;margin:3px;border-radius:20px;background:#eef2ff}
43
- .rise-results{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}
44
- .rise-metric{border:1px solid #dce3eb;border-radius:10px;padding:12px}
45
- .rise-metric strong{display:block;font-size:1.2rem}
46
- .rise-events{display:flex;flex-wrap:wrap;gap:6px;margin:12px 0}
47
- .rise-word{padding:5px 8px;border-radius:6px;background:#dcfce7;color:#166534}
48
- .rise-hidden{display:none!important}
49
- .rise-history{width:100%;border-collapse:collapse}
50
- .rise-history th,.rise-history td{text-align:left;padding:8px;border-bottom:1px solid #ddd}
51
- @media(max-width:600px){.rise-grid{grid-template-columns:1fr}.rise-results{grid-template-columns:repeat(2,minmax(0,1fr))}}
52
- </style>
53
-
54
- <div class="rise-shell">
55
- <h2>RISE Reading Practice</h2>
56
- <p>Read the passage aloud. RISE evaluates your speech and tracks your progress.</p>
57
- <div><span class="rise-pill" id="rise-connection">Backend not checked</span></div>
58
-
59
- <div class="rise-grid">
60
- <div class="rise-field">
61
- <label for="rise-api-url">Colab API URL</label>
62
- <input id="rise-api-url" type="url" placeholder="https://your-tunnel.trycloudflare.com">
63
- </div>
64
- <div class="rise-field">
65
- <label for="rise-level">Reading level</label>
66
- <select id="rise-level">
67
- ${levels.map((v,i)=>`<option value="${v}">${levelLabels[i]}</option>`).join('')}
68
- </select>
69
- </div>
70
- </div>
71
-
72
- <div class="rise-actions">
73
- <button class="rise-btn" id="rise-check">Check connection</button>
74
- <button class="rise-btn rise-primary" id="rise-start">Start session</button>
75
- </div>
76
- <div id="rise-status" class="rise-status" role="status">Check your backend connection before starting.</div>
77
-
78
- <div id="rise-workspace" class="rise-hidden">
79
- <div>
80
- <span class="rise-pill" id="rise-level-pill"></span>
81
- <span class="rise-pill" id="rise-part-pill"></span>
82
- <span class="rise-pill">Pass mark: 80%</span>
83
- </div>
84
- <div id="rise-passage" class="rise-passage"></div>
85
- <div id="rise-progress-text">0 words evaluated</div>
86
-
87
- <div class="rise-actions">
88
- <button class="rise-btn rise-primary" id="rise-record">Start recording</button>
89
- <button class="rise-btn" id="rise-stop" disabled>Stop & evaluate</button>
90
- <button class="rise-btn" id="rise-finish">Finish passage</button>
91
- <button class="rise-btn" id="rise-gesture">Check gesture</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  </div>
93
 
94
- <p id="rise-heard"></p>
95
- <div id="rise-events" class="rise-events"></div>
96
- <div class="rise-field">
97
- <label for="rise-pronounce-word">Pronounce a word</label>
98
- <input id="rise-pronounce-word" placeholder="Enter a word">
99
- <button class="rise-btn" id="rise-pronounce">Play pronunciation</button>
 
 
 
 
100
  </div>
101
- <div id="rise-results"></div>
102
- <div id="rise-decision" class="rise-hidden">
103
- <p id="rise-decision-text"></p>
104
- <button class="rise-btn rise-primary" id="rise-retry">Try again</button>
105
- <button class="rise-btn" id="rise-give-up">Stop for now</button>
106
  </div>
107
- <div id="rise-history"></div>
108
- </div>
109
- </div>`;
110
 
111
- $('#rise-api-url').value = apiBase;
112
- if (levels.includes(window.RISE_SELECTED_LEVEL)) {
113
- $('#rise-level').value = window.RISE_SELECTED_LEVEL;
114
- }
115
 
116
- const setStatus = (msg, type='') => {
117
- const el = $('#rise-status');
118
- el.textContent = msg;
119
- el.className = 'rise-status ' + (type ? 'rise-' + type : '');
120
- };
121
 
122
- const saveApi = () => {
123
- apiBase = $('#rise-api-url').value.trim().replace(/\/$/, '');
124
- if (apiBase) localStorage.setItem('riseApiBase', apiBase);
125
- };
126
 
127
- const request = async (path, options={}) => {
128
- if (!apiBase) throw new Error('Enter your current Colab Cloudflare URL.');
129
- let response;
130
- try {
131
- response = await fetch(apiBase + path, options);
132
- } catch (e) {
133
- throw new Error('Backend connection failed. Check Colab and your current tunnel URL.');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  }
135
- const data = await response.json().catch(() => ({}));
136
- if (!response.ok) throw new Error(data.detail || `HTTP ${response.status}`);
137
- return data;
138
- };
 
 
139
 
140
- const postJSON = body => ({
141
- method:'POST',
142
- headers:{'Content-Type':'application/json'},
143
- body:JSON.stringify(body)
144
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
- const renderSession = data => {
147
- session = {...(session || {}), ...data};
148
- $('#rise-workspace').classList.remove('rise-hidden');
149
- $('#rise-level-pill').textContent = 'Level: ' + labelLevel(session.level);
150
- $('#rise-part-pill').textContent = 'Part: ' + labelPart(session.part);
151
- $('#rise-passage').textContent = session.passage || 'No passage returned.';
152
- $('#rise-progress-text').textContent =
153
- `${session.cursor || 0} / ${session.total_words || 0} words evaluated (${session.progress_percent || 0}%)`;
154
- $('#rise-record').disabled = busy || !session.passage || !!session.session_ended ||
155
- (session.total_words != null && session.cursor >= session.total_words);
156
- $('#rise-finish').disabled = busy || !session.passage || !!session.session_ended;
157
  };
158
 
159
- const saveCumulativeHistory = history => {
160
- try {
161
- const old = JSON.parse(localStorage.getItem('riseHistory') || '[]');
162
- const combined = [...(Array.isArray(old) ? old : []), ...(Array.isArray(history) ? history : [])];
163
- const seen = new Set();
164
- const unique = combined.filter(r => {
165
- const key = r.timestamp != null
166
- ? 'timestamp:' + r.timestamp
167
- : `${r.level}|${r.part}|${r.overall}|${r.word_accuracy}|${r.wer}`;
168
- if (seen.has(key)) return false;
169
- seen.add(key);
170
- return true;
171
- });
172
- localStorage.setItem('riseHistory', JSON.stringify(unique));
173
- return unique;
174
- } catch (e) {
175
- console.warn('History storage failed', e);
176
- return Array.isArray(history) ? history : [];
177
  }
178
  };
179
 
180
- const renderHistory = history => {
181
- const records = saveCumulativeHistory(history);
182
- $('#rise-history').innerHTML = records.length ? `
183
- <h3>Session history</h3><table class="rise-history">
184
- <thead><tr><th>Level / part</th><th>Score</th><th>Accuracy</th><th>WER</th></tr></thead>
185
- <tbody>${records.slice().reverse().slice(0,20).map(r=>`
186
- <tr><td>${esc(labelLevel(r.level))} / ${esc(labelPart(r.part))}</td>
187
- <td>${Number(r.overall||0).toFixed(1)}%</td>
188
- <td>${Number(r.word_accuracy||0).toFixed(1)}%</td>
189
- <td>${Number(r.wer||0).toFixed(1)}%</td></tr>`).join('')}
190
- </tbody></table>` : '';
191
  };
192
 
193
- const playPronunciations = async items => {
194
- for (const item of items || []) {
195
- if (!item.audio_base64) continue;
196
- try {
197
- const bytes = Uint8Array.from(atob(item.audio_base64), c=>c.charCodeAt(0));
198
- const url = URL.createObjectURL(new Blob([bytes],{type:'audio/mpeg'}));
199
- const audio = new Audio(url);
200
- await audio.play();
201
- await new Promise(resolve => {audio.onended=resolve;audio.onerror=resolve;});
202
- URL.revokeObjectURL(url);
203
- } catch(e) { console.warn('Audio playback failed',e); }
204
  }
205
- };
206
 
207
- const renderEvents = events => {
208
- $('#rise-events').innerHTML = (events || []).map(e => `
209
- <span class="rise-word ${esc(e.type)}" title="${esc(e.feedback||'')}">
210
- ${e.type==='correct'?'✓':'✗'} ${esc(e.word)}
211
- ${e.heard && e.type!=='correct'?' · heard: '+esc(e.heard):''}</span>`).join('');
212
- };
213
 
214
- const renderMetrics = data => {
215
- const m = data.metrics || {};
216
- $('#rise-results').innerHTML = `
217
- <h3>${data.passed?'Passed':'Score report'}</h3>
218
- <div class="rise-results">
219
- <div class="rise-metric"><small>Overall</small><strong>${Number(m.overall||0).toFixed(1)}%</strong></div>
220
- <div class="rise-metric"><small>Word accuracy</small><strong>${Number(m.word_accuracy||0).toFixed(1)}%</strong></div>
221
- <div class="rise-metric"><small>Pronunciation</small><strong>${Number(m.pronunciation||0).toFixed(1)}%</strong></div>
222
- <div class="rise-metric"><small>Completion</small><strong>${Number(m.completion||0).toFixed(1)}%</strong></div>
223
- <div class="rise-metric"><small>WER</small><strong>${Number(data.wer||0).toFixed(1)}%</strong></div>
224
- <div class="rise-metric"><small>Speaking rate</small><strong>${Number(m.speaking_rate||0).toFixed(1)} wpm</strong></div>
225
- <div class="rise-metric"><small>Hesitations</small><strong>${Number(m.hesitations||0)}</strong></div>
226
- <div class="rise-metric"><small>Mismatches</small><strong>${Number(m.mismatches||0)}</strong></div>
227
- <div class="rise-metric"><small>Skipped</small><strong>${Number(m.skipped||0)}</strong></div>
228
- </div>`;
229
- };
230
 
231
- const recordPracticeDay = () => {
232
- try {
233
- const days = JSON.parse(localStorage.getItem('risePracticeDays') || '[]');
234
- const now = new Date();
235
- const today = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')}`;
236
- if (!days.includes(today)) days.push(today);
237
- localStorage.setItem('risePracticeDays', JSON.stringify(days));
238
- } catch(e) { console.warn('Could not save practice day',e); }
239
- };
240
 
241
- const stopTracks = () => {
242
- if (mediaStream) {
243
- mediaStream.getTracks().forEach(t=>t.stop());
244
- mediaStream = null;
245
  }
246
- };
247
 
248
- const setBusy = value => {
249
- busy = value;
250
- $('#rise-start').disabled = value;
251
- $('#rise-record').disabled = value || !session;
252
- $('#rise-stop').disabled = !value;
253
- $('#rise-finish').disabled = value || !session;
254
- $('#rise-gesture').disabled = value || !session;
255
- };
256
 
257
- $('#rise-check').addEventListener('click', async () => {
258
- saveApi();
259
- try {
260
- const data = await request('/api/health');
261
- $('#rise-connection').textContent = 'Backend connected';
262
- setStatus(`Connected. Service: ${data.service || 'RISE'}. Whisper: ${data.models?.whisper ? 'yes' : 'no'}.`,'success');
263
- } catch(e) {
264
- $('#rise-connection').textContent = 'Backend unavailable';
265
- setStatus(e.message,'error');
266
  }
267
- });
268
 
269
- $('#rise-start').addEventListener('click', async () => {
270
- saveApi();
 
271
  try {
272
- setStatus('Starting RISE session…');
273
- const data = await request('/api/session/start',postJSON({
274
- level:$('#rise-level').value, part:'sentence'
275
- }));
276
- session = data;
277
- renderSession(data);
278
- $('#rise-results').innerHTML = '';
279
- $('#rise-decision').classList.add('rise-hidden');
280
- setStatus('Session started. Read the passage aloud.','success');
281
- } catch(e) { setStatus(e.message,'error'); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  });
283
 
284
- $('#rise-record').addEventListener('click', async () => {
285
- if (!session || busy) return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  try {
287
- mediaStream = await navigator.mediaDevices.getUserMedia({audio:{
288
- channelCount:1,echoCancellation:true,noiseSuppression:true,autoGainControl:true
289
- }});
290
- const mime = ['audio/webm;codecs=opus','audio/webm','audio/mp4']
291
- .find(t=>MediaRecorder.isTypeSupported(t));
292
- recorder = mime ? new MediaRecorder(mediaStream,{mimeType:mime}) : new MediaRecorder(mediaStream);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  chunks = [];
294
- recorder.ondataavailable = e => {if(e.data.size) chunks.push(e.data);};
295
- recorder.onstart = () => {
296
- setBusy(true);
297
- setStatus('Recording. Read the phrase, then press Stop & evaluate.');
298
- };
299
- recorder.onstop = async () => {
300
- stopTracks();
301
- setBusy(false);
302
- const blob = new Blob(chunks,{type:recorder.mimeType||'audio/webm'});
303
- if (blob.size < 1500) {
304
- setStatus('Recording was too short. Please try again.','error');
305
- return;
306
  }
307
- const fd = new FormData();
308
- fd.append('session_id',session.session_id);
309
- fd.append('audio',blob,'reading.webm');
310
- try {
311
- setStatus('Sending audio to Whisper for evaluation…');
312
- const data = await request('/api/evaluate',{method:'POST',body:fd});
313
- renderSession(data);
314
- $('#rise-heard').textContent = data.heard ? 'Whisper heard: '+data.heard : '';
315
- renderEvents(data.events);
316
- await playPronunciations(data.pronunciations);
317
- setStatus(data.message||'Evaluation complete.',data.passage_complete?'success':'');
318
- } catch(e) {setStatus(e.message,'error');}
319
- };
320
- recorder.start(200);
321
- } catch(e) {
322
- stopTracks(); setBusy(false);
323
- setStatus('Microphone unavailable. Allow microphone access. '+e.message,'error');
 
 
 
 
 
 
 
 
 
 
324
  }
325
  });
326
 
327
- $('#rise-stop').addEventListener('click', () => {
328
- if (recorder && recorder.state!=='inactive') recorder.stop();
329
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
 
331
- $('#rise-finish').addEventListener('click', async () => {
332
- if (!session || busy) return;
333
- const fd = new FormData();
334
- fd.append('session_id',session.session_id);
335
  try {
336
- setStatus('Calculating reading results…');
337
- const data = await request('/api/session/finish',{method:'POST',body:fd});
338
- recordPracticeDay();
339
- renderMetrics(data);
340
- renderHistory(data.history || (data.record ? [data.record] : []));
341
- setStatus(data.message||'Results ready.',data.passed?'success':'');
342
- if (data.status==='retry_decision') {
343
- $('#rise-decision').classList.remove('rise-hidden');
344
- $('#rise-decision-text').textContent = data.message || 'Would you like to retry?';
345
- $('#rise-record').disabled = true;
346
- } else if (data.status==='completed_all') {
347
- session = {...session,session_ended:true};
348
- $('#rise-passage').textContent = data.message || 'Session completed.';
349
- $('#rise-record').disabled = true;
350
- $('#rise-finish').disabled = true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
  } else {
352
- renderSession(data);
353
- $('#rise-events').innerHTML = '';
354
- $('#rise-heard').textContent = '';
 
 
 
 
355
  }
356
- } catch(e) {setStatus(e.message,'error');}
357
- });
358
 
359
- const decide = async retry => {
360
- try {
361
- const data = await request('/api/session/decision',postJSON({
362
- session_id:session.session_id,retry
363
- }));
364
- $('#rise-decision').classList.add('rise-hidden');
365
- if (data.session_ended) {
366
- session = {...session,session_ended:true};
367
- $('#rise-passage').textContent = data.message || 'Session ended.';
368
- $('#rise-record').disabled = true;
369
- $('#rise-finish').disabled = true;
370
- renderHistory(data.history || []);
371
- setStatus(data.message||'Session ended.');
372
- } else {
373
- renderSession(data);
374
- $('#rise-results').innerHTML = '';
375
- $('#rise-events').innerHTML = '';
376
- setStatus(data.message||'New passage ready.','success');
377
  }
378
- } catch(e) {setStatus(e.message,'error');}
379
- };
 
 
 
 
 
 
 
 
 
 
 
380
 
381
- $('#rise-retry').addEventListener('click',()=>decide(true));
382
- $('#rise-give-up').addEventListener('click',()=>decide(false));
 
 
383
 
384
- $('#rise-pronounce').addEventListener('click',async()=>{
385
- const word = $('#rise-pronounce-word').value.trim();
386
- if (!word) {setStatus('Enter a word first.','error');return;}
387
  try {
388
- const data = await request('/api/pronounce',postJSON({word}));
389
- if (data.audio_base64) {
390
- await playPronunciations([data]);
391
- setStatus('Playing pronunciation for "'+word+'".','success');
392
- } else {
393
- throw new Error(data.audio_error||'Pronunciation audio unavailable.');
394
- }
395
- } catch(e) {setStatus(e.message,'error');}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
396
  });
397
 
398
- $('#rise-gesture').addEventListener('click',async()=>{
399
- if (!session || busy) return;
400
- let stream;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
  try {
402
- setStatus('Opening camera for gesture recognition…');
403
- stream = await navigator.mediaDevices.getUserMedia({video:{facingMode:'user'}});
404
- const video = document.createElement('video');
405
- video.srcObject = stream;
 
 
 
 
406
  video.muted = true;
 
 
 
407
  await video.play();
408
- await new Promise(r=>setTimeout(r,500));
409
- const canvas = document.createElement('canvas');
 
 
 
 
 
 
 
 
410
  canvas.width = video.videoWidth;
411
  canvas.height = video.videoHeight;
412
- canvas.getContext('2d').drawImage(video,0,0);
413
- stream.getTracks().forEach(t=>t.stop());
414
- stream = null;
415
- const data = await request('/api/gesture',postJSON({
416
- session_id:session.session_id,
417
- image_data:canvas.toDataURL('image/jpeg',0.85)
418
- }));
419
- if (data.passage) renderSession(data);
420
- if (data.session_ended) {
421
- session = {...session,session_ended:true};
422
- $('#rise-record').disabled = true;
423
- $('#rise-finish').disabled = true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424
  }
425
- setStatus(data.message||'Gesture check complete.',data.gesture?'success':'');
426
- } catch(e) {
427
- if (stream) stream.getTracks().forEach(t=>t.stop());
428
- setStatus('Gesture check failed. Allow camera access. '+e.message,'error');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  }
430
  });
431
 
432
- if (apiBase) {
433
- request('/api/health')
434
- .then(()=>{$('#rise-connection').textContent='Backend connected';})
435
- .catch(()=>{$('#rise-connection').textContent='Backend not reachable';});
436
- }
437
- })();
438
- '''
439
 
440
- # Save the complete JavaScript in one cell.
441
- output = Path("/content/rise-frontend.js")
442
- output.write_text(code, encoding="utf-8")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
443
 
444
- print(f"Saved complete frontend JavaScript to: {output}")
445
- print(f"File size: {output.stat().st_size:,} bytes")
446
- print("Now replace rise-frontend.js in your Hugging Face Space with this file.")
 
 
1
 
2
+ /*
3
+ * RISE Reading Practice Frontend
4
+ *
5
+ * Connects the reading interface to the FastAPI backend running in Colab.
6
+ * Features:
7
+ * - AI-generated reading passages
8
+ * - Whisper speech recognition
9
+ * - Reading accuracy and pronunciation feedback
10
+ * - Text-to-speech pronunciation playback
11
+ * - Hand gesture controls
12
+ * - Session summary
13
+ *
14
+ * IMPORTANT:
15
+ * Set window.RISE_API_BASE in your HTML before loading this file.
16
+ */
17
+
18
  (() => {
19
+ "use strict";
20
+
21
+ const API = (window.RISE_API_BASE || "").replace(/\/+$/, "");
22
+ const root = document.getElementById("rise-reading-app");
23
 
24
  if (!root) {
25
+ console.error("RISE: Could not find #rise-reading-app.");
26
  return;
27
  }
28
 
29
+ if (!API) {
30
+ root.innerHTML = `
31
+ <p style="color:#b91c1c">
32
+ RISE API is not configured. Set window.RISE_API_BASE
33
+ to your HTTPS backend URL.
34
+ </p>`;
35
+ return;
36
+ }
37
 
38
+ // --------------------------------------------------
39
+ // READING INTERFACE
40
+ // --------------------------------------------------
 
 
41
 
42
  root.innerHTML = `
43
+ <style>
44
+ #rise-reading-app {
45
+ font-family: system-ui, sans-serif;
46
+ color: #172033;
47
+ max-width: 900px;
48
+ margin: 20px auto;
49
+ }
50
+
51
+ #rise-reading-app .rise-card {
52
+ border: 1px solid #dbe3ef;
53
+ border-radius: 16px;
54
+ padding: 20px;
55
+ margin: 12px 0;
56
+ background: #fff;
57
+ box-shadow: 0 5px 20px #0f172a0d;
58
+ }
59
+
60
+ #rise-reading-app .rise-row {
61
+ display: flex;
62
+ gap: 10px;
63
+ flex-wrap: wrap;
64
+ align-items: center;
65
+ }
66
+
67
+ #rise-reading-app button {
68
+ border: 0;
69
+ border-radius: 10px;
70
+ padding: 10px 14px;
71
+ background: #5746e8;
72
+ color: white;
73
+ font-weight: 650;
74
+ cursor: pointer;
75
+ }
76
+
77
+ #rise-reading-app button.secondary {
78
+ background: #475569;
79
+ }
80
+
81
+ #rise-reading-app button.danger {
82
+ background: #b91c1c;
83
+ }
84
+
85
+ #rise-reading-app button:disabled {
86
+ opacity: 0.5;
87
+ cursor: not-allowed;
88
+ }
89
+
90
+ #rise-reading-app #rise-passage {
91
+ font-size: 1.2rem;
92
+ line-height: 1.9;
93
+ white-space: pre-wrap;
94
+ overflow-wrap: anywhere;
95
+ background: #f8fafc;
96
+ padding: 16px;
97
+ border-radius: 12px;
98
+ }
99
+
100
+ #rise-reading-app .rise-muted {
101
+ color: #64748b;
102
+ font-size: 0.92rem;
103
+ }
104
+
105
+ #rise-reading-app .rise-metrics {
106
+ display: grid;
107
+ grid-template-columns: repeat(
108
+ auto-fit,
109
+ minmax(130px, 1fr)
110
+ );
111
+ gap: 8px;
112
+ }
113
+
114
+ #rise-reading-app .rise-metric {
115
+ background: #f1f5f9;
116
+ border-radius: 10px;
117
+ padding: 10px;
118
+ overflow-wrap: anywhere;
119
+ }
120
+
121
+ #rise-reading-app .rise-metric b {
122
+ display: block;
123
+ font-size: 1.15rem;
124
+ }
125
+
126
+ #rise-reading-app #rise-status {
127
+ min-height: 1.5em;
128
+ }
129
+
130
+ #rise-reading-app .rise-err {
131
+ color: #b91c1c;
132
+ }
133
+
134
+ #rise-reading-app .rise-success {
135
+ color: #15803d;
136
+ }
137
+
138
+ #rise-reading-app video {
139
+ max-width: 100%;
140
+ }
141
+ </style>
142
+
143
+ <section class="rise-card">
144
+ <h2>📖 RISE Reading Practice</h2>
145
+
146
+ <p class="rise-muted">
147
+ AI-generated passages · Whisper speech recognition ·
148
+ pronunciation feedback · hand gestures
149
+ </p>
150
+
151
+ <div class="rise-row">
152
+ <button id="rise-start">Start practice</button>
153
+
154
+ <button id="rise-record" disabled>
155
+ 🎙️ Start recording
156
+ </button>
157
+
158
+ <button id="rise-stop" disabled>
159
+ Stop &amp; evaluate
160
+ </button>
161
+
162
+ <button id="rise-finish" class="danger" disabled>
163
+ Finish session
164
+ </button>
165
  </div>
166
 
167
+ <p id="rise-status" role="status" aria-live="polite">
168
+ Connecting to the RISE backend...
169
+ </p>
170
+
171
+ <p id="rise-level" class="rise-muted">
172
+ Your selected level and activity will appear here.
173
+ </p>
174
+
175
+ <div id="rise-passage">
176
+ Press Start practice to generate your reading passage.
177
  </div>
178
+
179
+ <div id="rise-actions" class="rise-row"
180
+ style="margin-top:12px">
 
 
181
  </div>
182
+ </section>
 
 
183
 
184
+ <section class="rise-card">
185
+ <h3>Speech evaluation</h3>
 
 
186
 
187
+ <p id="rise-transcript">
188
+ Your transcription will appear here.
189
+ </p>
 
 
190
 
191
+ <div id="rise-metrics" class="rise-metrics"></div>
 
 
 
192
 
193
+ <p id="rise-feedback"></p>
194
+
195
+ <div id="rise-errors"></div>
196
+ </section>
197
+
198
+ <section class="rise-card">
199
+ <h3>Hand gesture control</h3>
200
+
201
+ <p class="rise-muted">
202
+ Allow camera access to detect a hand gesture.
203
+ Your backend determines the gesture and its action.
204
+ </p>
205
+
206
+ <div class="rise-row">
207
+ <button id="rise-gesture" class="secondary" disabled>
208
+ 📷 Detect gesture
209
+ </button>
210
+
211
+ <span id="rise-gesture-result" aria-live="polite"></span>
212
+ </div>
213
+ </section>
214
+ `;
215
+
216
+ // --------------------------------------------------
217
+ // STATE AND HELPERS
218
+ // --------------------------------------------------
219
+
220
+ const $ = (id) => root.querySelector(`#${id}`);
221
+
222
+ let sessionId = null;
223
+ let recorder = null;
224
+ let chunks = [];
225
+ let startedAt = 0;
226
+ let stream = null;
227
+ let recordingInProgress = false;
228
+ let evaluationInProgress = false;
229
+ const activeEmail = (localStorage.getItem("riseActiveUserEmail") || "").trim().toLowerCase();
230
+ const profileKey = activeEmail ? "riseUser:" + activeEmail : null;
231
+
232
+ function loadUserProfile() {
233
+ let profile = profileKey ? JSON.parse(localStorage.getItem(profileKey) || "null") : null;
234
+ if (!profile) {
235
+ const starting = Math.min(5, Math.max(1, Number(localStorage.getItem("startingLevel")) || 1));
236
+ profile = { email: activeEmail, startingLevel: starting, unlockedLevel: starting, attempts: [], sessionsCompleted: 0, averageScore: 0 };
237
  }
238
+ profile.startingLevel = Math.min(5, Math.max(1, Number(profile.startingLevel) || 1));
239
+ profile.unlockedLevel = Math.min(5, Math.max(profile.startingLevel, Number(profile.unlockedLevel) || profile.startingLevel));
240
+ if (!Array.isArray(profile.attempts)) profile.attempts = [];
241
+ profile.sessionsCompleted = Number(profile.sessionsCompleted) || 0;
242
+ return profile;
243
+ }
244
 
245
+ function saveEvaluationProgress(data) {
246
+ const profile = loadUserProfile();
247
+ const metrics = data.metrics || {};
248
+ const score = Number(metrics.overall);
249
+ profile.attempts.push({
250
+ timestamp: new Date().toISOString(),
251
+ level: data.level || "beginner",
252
+ part: data.part || "sentence",
253
+ overall: Number.isFinite(score) ? score : 0,
254
+ wordAccuracy: Number(metrics.word_accuracy) || 0,
255
+ pronunciation: Number(metrics.pronunciation) || 0,
256
+ completion: Number(metrics.completion) || 0,
257
+ wer: Number(data.wer) || 0,
258
+ passed: Boolean(data.passed)
259
+ });
260
+ // A level unlocks only after its story is passed at >=80%.
261
+ const levelNumbers = { beginner: 1, elementary: 2, intermediate: 3, upper_intermediate: 4, advanced: 5 };
262
+ const completedLevel = levelNumbers[data.level];
263
+ if (data.passed && data.part === "story" && Number(score) >= 80 && completedLevel) {
264
+ profile.unlockedLevel = Math.max(profile.unlockedLevel, Math.min(5, completedLevel + 1));
265
+ }
266
+ const scores = profile.attempts.map(a => Number(a.overall)).filter(Number.isFinite);
267
+ profile.averageScore = scores.length ? Math.round(scores.reduce((sum, n) => sum + n, 0) / scores.length * 100) / 100 : 0;
268
+ if (profileKey) localStorage.setItem(profileKey, JSON.stringify(profile));
269
+ return profile;
270
+ }
271
+
272
+ function saveCompletedSession() {
273
+ const profile = loadUserProfile();
274
+ profile.sessionsCompleted += 1;
275
+ if (profileKey) localStorage.setItem(profileKey, JSON.stringify(profile));
276
+ }
277
 
278
+ const setStatus = (message, isError = false) => {
279
+ const status = $("rise-status");
280
+ status.textContent = message;
281
+ status.className = isError ? "rise-err" : "";
 
 
 
 
 
 
 
282
  };
283
 
284
+ const stopAudioTracks = () => {
285
+ if (stream) {
286
+ stream.getTracks().forEach((track) => track.stop());
287
+ stream = null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
  }
289
  };
290
 
291
+ const setSessionControls = (active) => {
292
+ $("rise-record").disabled = !active || recordingInProgress;
293
+ $("rise-stop").disabled = !active || !recordingInProgress;
294
+ $("rise-finish").disabled = !active || evaluationInProgress;
295
+ $("rise-gesture").disabled = !active || evaluationInProgress;
 
 
 
 
 
 
296
  };
297
 
298
+ async function api(path, options = {}) {
299
+ const response = await fetch(`${API}${path}`, options);
300
+
301
+ const body = await response.json().catch(() => ({}));
302
+
303
+ if (!response.ok) {
304
+ throw new Error(
305
+ body.detail || `Backend request failed (${response.status})`
306
+ );
 
 
307
  }
 
308
 
309
+ return body;
310
+ }
 
 
 
 
311
 
312
+ function showPassage(data) {
313
+ const level = String(data.level || "beginner")
314
+ .replaceAll("_", " ");
 
 
 
 
 
 
 
 
 
 
 
 
 
315
 
316
+ $("rise-level").textContent =
317
+ `Level: ${level} · Part: ${data.part || "sentence"} · ` +
318
+ `Pass mark: ${data.threshold ?? 80}%`;
319
+
320
+ $("rise-passage").textContent =
321
+ data.passage || "No passage was returned by the backend.";
322
+ }
 
 
323
 
324
+ function formatMetric(value, suffix = "%") {
325
+ if (value === undefined || value === null) {
326
+ return "N/A";
 
327
  }
 
328
 
329
+ return `${value}${suffix}`;
330
+ }
 
 
 
 
 
 
331
 
332
+ // --------------------------------------------------
333
+ // START READING SESSION
334
+ // --------------------------------------------------
335
+
336
+ $("rise-start").addEventListener("click", async () => {
337
+ if (sessionId) {
338
+ setStatus("A session is already active.");
339
+ return;
 
340
  }
 
341
 
342
+ $("rise-start").disabled = true;
343
+ setStatus("Starting your session and generating a passage...");
344
+
345
  try {
346
+ /*
347
+ * practice.html should set RISE_SELECTED_LEVEL.
348
+ * If it is not set, the backend starts at Beginner.
349
+ */
350
+ const selectedLevel =
351
+ window.RISE_SELECTED_LEVEL || "beginner";
352
+
353
+ const data = await api("/api/session/start", {
354
+ method: "POST",
355
+ headers: {
356
+ "Content-Type": "application/json"
357
+ },
358
+ body: JSON.stringify({
359
+ level: selectedLevel,
360
+ part: "sentence"
361
+ })
362
+ });
363
+
364
+ if (!data.session_id) {
365
+ throw new Error("The backend did not return a session ID.");
366
+ }
367
+
368
+ sessionId = data.session_id;
369
+
370
+ showPassage(data);
371
+
372
+ $("rise-transcript").textContent =
373
+ "Your transcription will appear here.";
374
+
375
+ $("rise-metrics").innerHTML = "";
376
+ $("rise-feedback").textContent = "";
377
+ $("rise-errors").innerHTML = "";
378
+
379
+ setStatus(
380
+ `Your session is ready. Text model: ${data.model || "loaded"}`
381
+ );
382
+
383
+ setSessionControls(true);
384
+
385
+ $("rise-start").disabled = true;
386
+
387
+ } catch (error) {
388
+ console.error("RISE session-start error:", error);
389
+
390
+ setStatus(
391
+ `Could not start the session: ${error.message}`,
392
+ true
393
+ );
394
+
395
+ $("rise-start").disabled = false;
396
+ }
397
  });
398
 
399
+ // --------------------------------------------------
400
+ // START AUDIO RECORDING
401
+ // --------------------------------------------------
402
+
403
+ $("rise-record").addEventListener("click", async () => {
404
+ if (!sessionId || recordingInProgress || evaluationInProgress) {
405
+ return;
406
+ }
407
+
408
+ if (!navigator.mediaDevices?.getUserMedia ||
409
+ typeof MediaRecorder === "undefined") {
410
+ setStatus(
411
+ "Audio recording is not supported by this browser. " +
412
+ "Use a recent browser over HTTPS.",
413
+ true
414
+ );
415
+ return;
416
+ }
417
+
418
  try {
419
+ stream = await navigator.mediaDevices.getUserMedia({
420
+ audio: {
421
+ channelCount: 1,
422
+ echoCancellation: true,
423
+ noiseSuppression: true
424
+ }
425
+ });
426
+
427
+ let mimeType = "";
428
+
429
+ if (MediaRecorder.isTypeSupported("audio/webm;codecs=opus")) {
430
+ mimeType = "audio/webm;codecs=opus";
431
+ } else if (MediaRecorder.isTypeSupported("audio/webm")) {
432
+ mimeType = "audio/webm";
433
+ }
434
+
435
+ recorder = mimeType
436
+ ? new MediaRecorder(stream, { mimeType })
437
+ : new MediaRecorder(stream);
438
+
439
  chunks = [];
440
+
441
+ recorder.addEventListener("dataavailable", (event) => {
442
+ if (event.data && event.data.size > 0) {
443
+ chunks.push(event.data);
 
 
 
 
 
 
 
 
444
  }
445
+ });
446
+
447
+ recorder.start(150);
448
+
449
+ startedAt = Date.now();
450
+ recordingInProgress = true;
451
+
452
+ setSessionControls(true);
453
+
454
+ setStatus(
455
+ "Recording... Read the displayed passage aloud, " +
456
+ "then press Stop & evaluate."
457
+ );
458
+
459
+ } catch (error) {
460
+ console.error("RISE recording error:", error);
461
+
462
+ stopAudioTracks();
463
+
464
+ recordingInProgress = false;
465
+ setSessionControls(Boolean(sessionId));
466
+
467
+ setStatus(
468
+ `Could not start the microphone: ${error.message}. ` +
469
+ "Check your browser's microphone permission.",
470
+ true
471
+ );
472
  }
473
  });
474
 
475
+ // --------------------------------------------------
476
+ // STOP RECORDING AND EVALUATE SPEECH
477
+ // --------------------------------------------------
478
+
479
+ $("rise-stop").addEventListener("click", async () => {
480
+ if (!recorder ||
481
+ recorder.state === "inactive" ||
482
+ evaluationInProgress) {
483
+ return;
484
+ }
485
+
486
+ evaluationInProgress = true;
487
+ setSessionControls(Boolean(sessionId));
488
+
489
+ setStatus("Uploading audio and evaluating your reading with Whisper...");
490
+
491
+ const activeRecorder = recorder;
492
 
 
 
 
 
493
  try {
494
+ const audioBlob = await new Promise((resolve, reject) => {
495
+ activeRecorder.addEventListener("stop", () => {
496
+ if (chunks.length === 0) {
497
+ reject(new Error("No audio was recorded. Please try again."));
498
+ return;
499
+ }
500
+
501
+ resolve(
502
+ new Blob(chunks, {
503
+ type: activeRecorder.mimeType || "audio/webm"
504
+ })
505
+ );
506
+ }, { once: true });
507
+
508
+ activeRecorder.stop();
509
+ });
510
+
511
+ stopAudioTracks();
512
+
513
+ recordingInProgress = false;
514
+
515
+ const elapsedSeconds = (Date.now() - startedAt) / 1000;
516
+
517
+ const formData = new FormData();
518
+
519
+ formData.append("audio", audioBlob, "reading.webm");
520
+ formData.append(
521
+ "elapsed_seconds",
522
+ String(elapsedSeconds)
523
+ );
524
+
525
+ const data = await api(
526
+ `/api/session/${encodeURIComponent(sessionId)}/evaluate`,
527
+ {
528
+ method: "POST",
529
+ body: formData
530
+ }
531
+ );
532
+
533
+ // Show the speech recognition result.
534
+ $("rise-transcript").textContent =
535
+ `Heard: ${data.transcript || "(No speech recognized)"}`;
536
+
537
+ // Show evaluation metrics.
538
+ const metrics = data.metrics || {};
539
+
540
+ const metricItems = [
541
+ ["Overall score", formatMetric(metrics.overall)],
542
+ ["Word accuracy", formatMetric(metrics.word_accuracy)],
543
+ ["Pronunciation", formatMetric(metrics.pronunciation)],
544
+ ["Completion", formatMetric(metrics.completion)],
545
+ ["Word error rate", formatMetric(data.wer)],
546
+ ["Speaking rate", formatMetric(metrics.speaking_rate, " wpm")]
547
+ ];
548
+
549
+ $("rise-metrics").replaceChildren();
550
+
551
+ metricItems.forEach(([label, value]) => {
552
+ const card = document.createElement("div");
553
+ card.className = "rise-metric";
554
+
555
+ const name = document.createElement("span");
556
+ name.textContent = label;
557
+
558
+ const result = document.createElement("b");
559
+ result.textContent = value;
560
+
561
+ card.append(name, result);
562
+ $("rise-metrics").appendChild(card);
563
+ });
564
+
565
+ const passed = Boolean(data.passed);
566
+ saveEvaluationProgress(data);
567
+
568
+ $("rise-feedback").textContent =
569
+ `${passed ? "✅ Passed! " : "🔁 Try again. "}` +
570
+ (data.message || "");
571
+
572
+ $("rise-feedback").className =
573
+ passed ? "rise-success" : "";
574
+
575
+ // Show detected words and pronunciation playback controls.
576
+ $("rise-errors").replaceChildren();
577
+
578
+ const events = Array.isArray(data.events) ? data.events : [];
579
+
580
+ events
581
+ .filter((event) => event.type !== "correct")
582
+ .forEach((event) => {
583
+ const row = document.createElement("div");
584
+ row.className = "rise-row";
585
+ row.style.margin = "6px 0";
586
+
587
+ const label = document.createElement("span");
588
+
589
+ label.textContent =
590
+ `${event.word || "Word"}: ${event.type || "mismatch"}` +
591
+ (event.heard ? ` (heard "${event.heard}")` : "");
592
+
593
+ const button = document.createElement("button");
594
+ button.className = "secondary";
595
+ button.textContent =
596
+ `🔊 Hear "${event.word || "word"}"`;
597
+
598
+ button.addEventListener("click", async () => {
599
+ try {
600
+ const audio = new Audio(
601
+ `${API}/api/pronounce/${encodeURIComponent(
602
+ event.word || ""
603
+ )}`
604
+ );
605
+
606
+ await audio.play();
607
+
608
+ } catch (error) {
609
+ setStatus(
610
+ `Could not play pronunciation: ${error.message}`,
611
+ true
612
+ );
613
+ }
614
+ });
615
+
616
+ row.append(label, button);
617
+ $("rise-errors").appendChild(row);
618
+ });
619
+
620
+ // Handle progression returned by the backend.
621
+ if (data.completed) {
622
+ setStatus(
623
+ data.message ||
624
+ "Congratulations! You completed the reading levels."
625
+ );
626
+
627
+ $("rise-passage").textContent =
628
+ "Reading session completed. Finish the session to view your summary.";
629
+
630
+ sessionId = null;
631
+ $("rise-start").disabled = false;
632
+ setSessionControls(false);
633
+
634
+ } else if (data.next_passage) {
635
+ showPassage({
636
+ level: data.next_level,
637
+ part: data.next_part,
638
+ passage: data.next_passage,
639
+ threshold: data.threshold
640
+ });
641
+
642
+ setStatus(
643
+ data.message ||
644
+ (passed
645
+ ? "Great work! Continue with the next activity."
646
+ : "You need to try this activity again.")
647
+ );
648
+
649
+ // The backend determines whether the next passage changes.
650
+ setSessionControls(true);
651
+
652
  } else {
653
+ setStatus(
654
+ data.message ||
655
+ "Evaluation completed, but the backend did not return a next passage.",
656
+ !passed
657
+ );
658
+
659
+ setSessionControls(true);
660
  }
 
 
661
 
662
+ } catch (error) {
663
+ console.error("RISE evaluation error:", error);
664
+
665
+ stopAudioTracks();
666
+ recordingInProgress = false;
667
+
668
+ setStatus(
669
+ `Could not evaluate the recording: ${error.message}`,
670
+ true
671
+ );
672
+
673
+ setSessionControls(Boolean(sessionId));
674
+
675
+ } finally {
676
+ evaluationInProgress = false;
677
+
678
+ if (sessionId) {
679
+ setSessionControls(true);
680
  }
681
+ }
682
+ });
683
+
684
+ // --------------------------------------------------
685
+ // FINISH SESSION AND DISPLAY SUMMARY
686
+ // --------------------------------------------------
687
+
688
+ $("rise-finish").addEventListener("click", async () => {
689
+ if (!sessionId || recordingInProgress || evaluationInProgress) {
690
+ return;
691
+ }
692
+
693
+ const finishedSessionId = sessionId;
694
 
695
+ $("rise-finish").disabled = true;
696
+ $("rise-gesture").disabled = true;
697
+
698
+ setStatus("Preparing your session summary...");
699
 
 
 
 
700
  try {
701
+ const data = await api(
702
+ `/api/session/${encodeURIComponent(finishedSessionId)}/finish`,
703
+ {
704
+ method: "POST"
705
+ }
706
+ );
707
+
708
+ saveCompletedSession();
709
+ setStatus(
710
+ `Session finished. Attempts: ${data.attempts ?? "N/A"}; ` +
711
+ `average overall score: ${data.average_overall ?? "N/A"}%; ` +
712
+ `average word error rate: ${data.average_wer ?? "N/A"}%.`
713
+ );
714
+
715
+ $("rise-feedback").textContent =
716
+ JSON.stringify(data.text_generation ?? {}, null, 2);
717
+
718
+ sessionId = null;
719
+
720
+ $("rise-start").disabled = false;
721
+ setSessionControls(false);
722
+
723
+ } catch (error) {
724
+ console.error("RISE finish-session error:", error);
725
+
726
+ setStatus(
727
+ `Could not finish the session: ${error.message}`,
728
+ true
729
+ );
730
+
731
+ setSessionControls(Boolean(sessionId));
732
+ }
733
  });
734
 
735
+ // --------------------------------------------------
736
+ // HAND GESTURE DETECTION
737
+ // --------------------------------------------------
738
+
739
+ $("rise-gesture").addEventListener("click", async () => {
740
+ if (!sessionId || evaluationInProgress || recordingInProgress) {
741
+ return;
742
+ }
743
+
744
+ if (!navigator.mediaDevices?.getUserMedia) {
745
+ setStatus(
746
+ "Camera access is not supported by this browser.",
747
+ true
748
+ );
749
+ return;
750
+ }
751
+
752
+ let cameraStream = null;
753
+
754
+ $("rise-gesture").disabled = true;
755
+ $("rise-gesture-result").textContent = "Opening camera...";
756
+
757
  try {
758
+ cameraStream = await navigator.mediaDevices.getUserMedia({
759
+ video: {
760
+ facingMode: "user"
761
+ }
762
+ });
763
+
764
+ const video = document.createElement("video");
765
+
766
  video.muted = true;
767
+ video.playsInline = true;
768
+ video.srcObject = cameraStream;
769
+
770
  await video.play();
771
+
772
+ // Allow the camera to produce a frame.
773
+ await new Promise((resolve) => setTimeout(resolve, 700));
774
+
775
+ if (!video.videoWidth || !video.videoHeight) {
776
+ throw new Error("The camera did not provide a usable image.");
777
+ }
778
+
779
+ const canvas = document.createElement("canvas");
780
+
781
  canvas.width = video.videoWidth;
782
  canvas.height = video.videoHeight;
783
+
784
+ const context = canvas.getContext("2d");
785
+
786
+ if (!context) {
787
+ throw new Error("Could not capture the camera image.");
788
+ }
789
+
790
+ context.drawImage(video, 0, 0);
791
+
792
+ const imageBlob = await new Promise((resolve, reject) => {
793
+ canvas.toBlob(
794
+ (blob) => {
795
+ if (blob) {
796
+ resolve(blob);
797
+ } else {
798
+ reject(new Error("Could not encode the camera image."));
799
+ }
800
+ },
801
+ "image/jpeg",
802
+ 0.85
803
+ );
804
+ });
805
+
806
+ cameraStream.getTracks().forEach((track) => track.stop());
807
+ cameraStream = null;
808
+
809
+ const formData = new FormData();
810
+ formData.append("image", imageBlob, "gesture.jpg");
811
+
812
+ const data = await api(
813
+ `/api/session/${encodeURIComponent(sessionId)}/gesture`,
814
+ {
815
+ method: "POST",
816
+ body: formData
817
+ }
818
+ );
819
+
820
+ $("rise-gesture-result").textContent =
821
+ `Detected: ${data.gesture || "unknown"} · ` +
822
+ `Action: ${data.action || "none"}`;
823
+
824
+ if (data.passage) {
825
+ showPassage({
826
+ level: data.level,
827
+ part: data.part,
828
+ passage: data.passage,
829
+ threshold: data.threshold || 80
830
+ });
831
  }
832
+
833
+ if (data.ended) {
834
+ setStatus("Session ended by the hand gesture.");
835
+
836
+ sessionId = null;
837
+ $("rise-start").disabled = false;
838
+ setSessionControls(false);
839
+
840
+ } else if (data.action && data.action !== "none") {
841
+ setStatus(`Gesture applied: ${data.action}.`);
842
+ }
843
+
844
+ } catch (error) {
845
+ console.error("RISE gesture error:", error);
846
+
847
+ setStatus(
848
+ `Camera or gesture error: ${error.message}`,
849
+ true
850
+ );
851
+
852
+ $("rise-gesture-result").textContent = "Gesture detection failed.";
853
+
854
+ } finally {
855
+ if (cameraStream) {
856
+ cameraStream.getTracks().forEach((track) => track.stop());
857
+ }
858
+
859
+ $("rise-gesture").disabled = !sessionId;
860
  }
861
  });
862
 
863
+ // --------------------------------------------------
864
+ // CHECK BACKEND CONNECTIVITY
865
+ // --------------------------------------------------
 
 
 
 
866
 
867
+ api("/api/health")
868
+ .then((health) => {
869
+ if (!health.ok) {
870
+ throw new Error("The backend health check did not return OK.");
871
+ }
872
+
873
+ const models = health.models || {};
874
+
875
+ setStatus(
876
+ `Backend connected. Whisper: ${
877
+ models.whisper ? "ready" : "unavailable"
878
+ }; text generation: ${
879
+ models.text_generation ? "ready" : "unavailable"
880
+ }; gestures: ${
881
+ models.gesture ? "ready" : "unavailable"
882
+ }.`
883
+ );
884
+ })
885
+ .catch((error) => {
886
+ console.error("RISE health-check error:", error);
887
+
888
+ setStatus(
889
+ "Backend not reachable. Check the API URL and make sure " +
890
+ "the Colab server and Cloudflare tunnel are running.",
891
+ true
892
+ );
893
+ });
894
 
895
+ })();
 
 
speaking.html CHANGED
@@ -135,7 +135,7 @@
135
 
136
  </footer>
137
  <script>
138
- window.RISE_API_BASE = "https://easter-fraction-rna-tommy.trycloudflare.com/";
139
  </script>
140
  <script src="rise-frontend.js"></script>
141
  </body>
 
135
 
136
  </footer>
137
  <script>
138
+ window.RISE_API_BASE = "https://gmbh-highly-travelers-inputs.trycloudflare.com/";
139
  </script>
140
  <script src="rise-frontend.js"></script>
141
  </body>