Oviya commited on
Commit ·
e20fbf3
1
Parent(s): 61c407f
update pronounciation
Browse filesFiles changed (4)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582.pron-container { display: flex; padding: 2vw; font-family: Raleway, Roboto, Helvetica Neue, sans-serif; border: 10px solid #009688; height: 100%; border-radius: 1vw; flex-direction: column;}
.header { text-align: center;}
.title { font-size: 2.5vw; color: #006780; margin-bottom: 1vw; font-weight: 800; font-family: Raleway, Roboto, Helvetica Neue, sans-serif;}
.main-content { display: flex; gap: 5vw;}
.image-section { display: flex; align-items: center; justify-content: center; width: 20vw;}
.apple-image { width: 20vw; height: 20vw; object-fit: contain; filter: drop-shadow(0 25px 25px rgba(0, 0, 0, 0.15)); animation: float 3s ease-in-out infinite;}
@keyframes float { 0%, 100% { transform: translateY(0px); }
50% { transform: translateY(-20px); }}
.controls-section { display: flex; flex-direction: column; justify-content: center; gap: 2vw; width: 30vw;}
.word-section { text-align: center; display: flex; flex-direction: column; gap: 1vw;}
.word { font-size: 3rem; font-weight: bold; color: hsl(222, 47%, 11%); text-transform: capitalize; margin-bottom: 0.5rem; font-family: Raleway, Roboto, Helvetica Neue, sans-serif;}
.phonetics { font-size: 1.5vw; color: hsl(215, 16%, 47%); font-family: Raleway, Roboto, Helvetica Neue, sans-serif;}
.teacher-section { display: flex; align-items: center; gap: 1rem; padding: 1rem; background: hsla(217, 91%, 60%, 0.1); border-radius: 1rem; border: 2px solid hsla(217, 91%, 60%, 0.2);}
.student-section { display: flex; align-items: center; gap: 1rem; padding: 1rem; background: hsla(142, 76%, 36%, 0.1); border-radius: 1rem; border: 2px solid hsla(142, 76%, 36%, 0.2);}
.avatar { width: 3rem; height: 3rem; border-radius: 9999px; object-fit: cover;}
.button-group { display: flex; gap: 0.5rem; flex-wrap: wrap;}
.btn { display: inline-flex; align-items: center; justify-content: center; gap: 0.5rem; padding: 0.8vw; font-size: 1rem; font-weight: 500; border-radius: 0.5rem; border: none; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); position: relative; box-shadow: 0 10px 20px -5px rgba(0, 0, 0, 0.2); width: 11vw;}
.btn:hover { transform: scale(1.05); }
.btn:active { transform: scale(0.95); }
.btn:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
.btn-primary { background: hsl(217, 91%, 60%); color: white;}
.btn-secondary { background: hsl(142, 76%, 36%); color: white;}
.btn-accent { background: hsl(280, 100%, 70%); color: white;}
.btn-success { background: hsl(142, 76%, 36%); color: white;}
.btn-outline { background: transparent; border: 2px solid hsl(214, 32%, 91%); color: hsl(222, 47%, 11%);}
.full-width { width: 100%;}
.icon { width: 1.25rem; height: 1.25rem;}
.spinner { width: 1.25rem; height: 1.25rem; animation: spin 1s linear infinite;}
.spinner-circle { fill: none; stroke: currentColor; stroke-width: 3; stroke-dasharray: 50; stroke-dashoffset: 25;}
@keyframes spin { to { transform: rotate(360deg); }}
.hidden { display: none !important;}
.results-section { width: 30vw; height: 30vw; display: flex; flex-direction: column; align-items: center; justify-content: space-between;}
.gauge-wrapper { position: relative; width: 20vw; height: 10vw;}
.gauge { position: absolute; left: 50%; top: 0; transform: translateX(-50%); width: 100%; height: 100%; border-radius: 260px 260px 0 0; overflow: hidden; background: #f3f3f3; box-shadow: 0 4px 10px rgba(0,0,0,0.25) inset;}
.gauge-arc { position: absolute; inset: 0; border-radius: 50%; background: conic-gradient( from 270deg, #e53935 0deg 45deg, #fb8c00 45deg 90deg, #fbc02d 90deg 135deg, #43a047 135deg 180deg, transparent 180deg 360deg ); height: 20vw;}
.needle { position: absolute; bottom: 0vw; left: 50%; width: 0.7vw; height: 8vw; background: #333; transform: translateX(-50%) rotate(var(--angle, -90deg)); transform-origin: 50% 100%; transition: transform 700ms cubic-bezier(.2,.9,.2,1); border-radius: 10px; box-shadow: 0 2px 6px rgba(0,0,0,0.5);}
.mic-badge { position: absolute; bottom: -0.3vw; left: 50%; transform: translate(-50%, 35%); width: 3vw; height: 3vw; border-radius: 50%; background: #000; box-shadow: 0 8px 18px rgba(0,0,0,0.4); display: flex; align-items: center; justify-content: center;}
.score-span { color: white; font-size: 1vw; font-weight: bold;}
.nav-buttons { position: absolute; right: 2rem; bottom: 2rem; display: flex; align-items: center; gap: 0.75rem; z-index: 30;}
.btn-nav { padding: 0.5rem 0.75rem; font-size: 1vw; white-space: nowrap; background: #009688; width: 7vw; height: 2.5vw; font-weight: bold; color: white;}
.nav-info { font-weight: 600; color: hsl(222, 47%, 11%); min-width: 4.5rem; text-align: center; font-size: 1vw;}
.suggestions-section { background-color: azure; box-shadow: 0 6px 18px rgba(0, 0, 0, 0.06); padding: 1vw;}
.suggestions-title { font-size: 1.25rem; font-weight: 600; color: hsl(222, 47%, 11%); margin-bottom: 1rem; font-family: Raleway, Roboto, Helvetica Neue, sans-serif;}
.suggestions-page { display: flex; gap: 1vw; flex-direction: column;}
.suggestion-card { display: flex; gap: 1rem; align-items: flex-start; background: #fff; border-radius: 12px; padding: 1rem 1.25rem; box-shadow: 0 6px 18px rgba(10, 30, 60, 0.06); border: 1px solid rgba(0,0,0,0.04); transition: transform .15s ease, box-shadow .15s ease;}
.suggestion-card:hover { transform: translateY(-4px); box-shadow: 0 10px 30px rgba(10, 30, 60, 0.08); }
.suggestion-badge { min-width: 36px; height: 36px; border-radius: 999px; background: linear-gradient(180deg, #eaf3ff, #dbeeff); color: #0b57a4; display: flex; align-items: center; justify-content: center; font-weight: 700; box-shadow: 0 4px 10px rgba(11,87,164,0.08); flex-shrink: 0; font-size: 0.95rem;}
.suggestion-body { flex: 1;}
.suggestion-point { font-size: 1rem; font-weight: 700; color: hsl(222, 47%, 11%); margin-bottom: 0.25rem;}
.suggestion-feedback { color: hsl(215, 16%, 47%); font-size: 0.95rem; line-height: 1.45;}
.suggestion-nav { display: flex; align-items: center; justify-content: center; padding:1vw;}
/* Existing .voice-selection-container */.voice-selection-container { display: flex; align-items: center; justify-content: flex-start; /* Aligns to the left/start of the section */ gap: 12px; /* Add margin/padding to separate it visually */ margin: 0.5rem 0;}
/* NEW: Segmented Control Wrapper Style */.voice-toggle-control { display: flex; align-items: center; /* Pill shape for the entire control */ border-radius: 9999px; /* Soft border to define the area */ border: 2px solid #009688; /* Use a color that stands out from the teacher-section bg */ background-color: #f0f8ff; /* Light background */ padding: 4px; /* Padding inside the control */}
/* Label Group Styles */.voice-label-group { /* Make segments clickable and give them an initial look */ padding: 0.5rem 1rem; font-size: 0.95rem; /* Slightly smaller for compactness */ color: #006780; font-weight: 500; cursor: pointer; transition: all 0.3s ease; white-space: nowrap; user-select: none; min-width: 6vw; /* Ensure minimum width for visibility */ text-align: center;}
.voice-text { /* Ensure the span font properties are appealing */ font-weight: 600; /* Bolder text for visibility */ font-size: 0.9vw; /* Adjusted to fit the new design */}
/* Active Segment Style (Unique UI) */.voice-label-group.active { /* Highlight the active selection */ background-color: #006780; /* Strong, contrasting background */ color: white; /* White text on active background */ font-weight: 700; box-shadow: 0 4px 10px rgba(0, 103, 128, 0.3); /* Subtle lift */}
/* Specific border-radius for segments */.toggle-label-left { border-radius: 9999px 0 0 9999px; /* Rounded on the left */}
.toggle-label-right { border-radius: 0 9999px 9999px 0; /* Rounded on the right */}
/* Angular Material Toggle Styles for Integration *//* Target the slide toggle container */.voice-toggle-slider { /* Hide the toggle itself but keep its functionality space (optional) */ height: 24px; width: 4px; /* Acts as a vertical separator */ background-color: transparent; /* Ensure no residual background */ opacity: 1; /* Keep visible for debugging if needed, but its children are hidden */ margin: 0 -2px; /* Maintain small gap/separator illusion */ position: relative; overflow: hidden; /* Crucial to clip any remaining visual elements */}
/* IMPORTANT: Aggressive Hiding for all internal Material elements */ .voice-toggle-slider .mdc-switch__track, .voice-toggle-slider .mdc-switch__icons, .voice-toggle-slider .mdc-switch__thumb-handle, .voice-toggle-slider .mat-mdc-slide-toggle-ripple, .voice-toggle-slider .mat-mdc-slide-toggle-focus-ring, .voice-toggle-slider .mdc-switch__handle { /* Set width/height to zero and hide completely */ width: 0 !important; height: 0 !important; padding: 0 !important; margin: 0 !important; opacity: 0 !important; visibility: hidden !important; /* Critical to ensure hiding */ display: none !important; /* The most aggressive hide */ }
/* Optional: If you want a visual separator line, add it here */ .voice-toggle-slider::before { content: ''; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 2px; height: 80%; /* Height of the separator */ background-color: rgba(0, 150, 136, 0.4); /* Divider color (lighter than the border) */ border-radius: 1px; }
/* Adjust the original span's font-size to be slightly bigger since the toggle is now prominent */span { font-weight: bold; font-size: 1vw; /* Increased from 0.8vw for better legibility */}
/* Override existing label group for the new look */.voice-label-group { /* Resetting previous style from your original CSS for segments */ font-size: 1rem; /* Use a fixed size instead of 'vw' for consistency in labels */ color: #006780; transition: all 0.3s; font-weight: 500; line-height: 1; /* Ensure text fits */ display: flex; align-items: center; justify-content: center;}
.record-btn { display: inline-flex; align-items: center; gap: 8px;}
.record-btn.recording { background-color: #e53935; border-color: #d32f2f; color: #ffffff; box-shadow: 0 2px 6px rgba(229, 57, 53, 0.24); }
.record-btn.recording .icon, .record-btn.recording .stop-icon { color: #fff; fill: #fff; stroke: none; }
.stop-icon { width: 18px; height: 18px; display: inline-block; vertical-align: middle;}
.user-guide-close-icon { position: fixed; top: 3vw; right: 4vw; background: #009688; border: none; width: 44px; height: 44px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 2vw; color: black; cursor: pointer; z-index: 2010; box-shadow: 0 2px 8px rgba(93, 145, 195, 0.18); transition: background 0.2s, color 0.2s;}
/* Responsive */@media (max-width: 768px) { .title { font-size: 1.75rem; }
.word { font-size: 2rem; }
.phonetics { font-size: 1.25rem; }
.apple-image { width: 12rem; height: 12rem; }
.btn { padding: 0.625rem 1.25rem; font-size: 0.875rem; }}
span { font-weight: bold; font-size:0.8vw;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193<div class="pron-container"> <!-- Header --> <div class="header">
<h2 class="title">Pronunciation Trainer</h2> </div>
<!-- Main Content --> <div class="main-content"> <!-- Left Side - Apple Image --> <div class="image-section"> <img [src]="imgsrc" [alt]="word" class="apple-image"> </div>
<!-- Right Side - Word and Controls --> <div class="controls-section"> <!-- Word with Phonetics --> <div class="word-section"> <h2 class="word">{{ word }}</h2> <p class="phonetics">{{ phonetics }}</p> </div>
<!-- Teacher Audio Button --> <div class="teacher-section"> <img src="assets/images/chat/natasha.png" alt="Teacher" class="avatar"> <button class="btn btn-primary" id="playTeacherBtn" (click)="playTeacherAudio()" [disabled]="isTeacherLoading" [attr.aria-busy]="isTeacherLoading"> <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <polygon points="5 3 19 12 5 21 5 3"></polygon> </svg> <span class="btn-text" *ngIf="!isTeacherLoading">Play Teacher</span> <span class="btn-text" *ngIf="isTeacherLoading">Loading...</span> <svg class="spinner" viewBox="0 0 24 24" [class.hidden]="!isTeacherLoading"> <circle class="spinner-circle" cx="12" cy="12" r="10"></circle> </svg> </button>
<div class="voice-selection-container"> <div class="voice-toggle-control"> <div class="voice-label-group toggle-label-left" [class.active]="!isOriginal" (click)="isOriginal = false; updateSelection()"> <span class="voice-text">Original Voice</span> </div>
<div class="voice-label-group toggle-label-right" [class.active]="isOriginal" (click)="isOriginal = true; updateSelection()"> <span class="voice-text">Cloned Voice</span> </div> </div> </div> </div>
<!-- Student Recording Section --> <div class="student-section"> <img src="assets/images/pron/student.png" alt="Student" class="avatar"> <div class="button-group"> <button class="btn btn-secondary record-btn" id="recordBtn" (click)="isRecording ? stopRecording() : startRecording()" [class.recording]="isRecording" [attr.aria-pressed]="isRecording"> <ng-container *ngIf="!isRecording; else stopTpl"> <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="20" height="20"> <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"></path> <path d="M19 10v2a7 7 0 0 1-14 0v-2"></path> <line x1="12" x2="12" y1="19" y2="22"></line> </svg> <span class="btn-text">Start Recording</span> </ng-container>
<ng-template #stopTpl> <svg class="icon stop-icon" viewBox="0 0 24 24" fill="currentColor" stroke="none" width="18" height="18" aria-hidden="true"> <rect x="6" y="6" width="12" height="12" rx="2"></rect> </svg> <span class="btn-text">Stop</span> </ng-template> </button>
<!-- Play Student Recording (shows when a recording exists) --> <button class="btn btn-accent" id="playStudentBtn" *ngIf="recordedBlobUrl" (click)="playRecorded()"> <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <polygon points="5 3 19 12 5 21 5 3"></polygon> </svg> <span class="btn-text">Play My Recording</span> </button> </div> </div>
<!-- Check Button --> <button class="btn btn-success full-width" id="checkBtn" (click)="checkPronunciation()" [disabled]="isChecking || !recordedBlobUrl" [attr.aria-busy]="isChecking" [attr.aria-disabled]="isChecking || !recordedBlobUrl" aria-label="Check pronunciation"> <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" *ngIf="!isChecking"> <polyline points="20 6 9 17 4 12"></polyline> </svg>
<span class="btn-text" *ngIf="!isChecking">Check Pronunciation</span> <span class="btn-text" *ngIf="isChecking">Checking...</span>
<svg class="spinner" viewBox="0 0 24 24" *ngIf="isChecking"> <circle class="spinner-circle" cx="12" cy="12" r="10"></circle> </svg> </button>
</div>
<div class="results-section" id="resultsSection">
<!-- Score Display: always show speakometer when result exists --> <div class="gauge-wrapper"> <div class="gauge"> <div class="gauge-arc"></div> <!-- set CSS variable from Angular --> <div class="needle" [style.--angle]="needleAngle + 'deg'" aria-hidden="true"></div> </div>
<div class="mic-badge"> <span class="score-span" aria-live="polite">{{ result?.score ?? 0 }}%</span> </div> </div>
<!-- Suggestions (paged, 2 per page) --> <div class="suggestions-section" *ngIf="result"> <h3 class="suggestions-title">Feedback & Suggestions</h3>
<!-- If structured suggestions exist, show current page (2 items) --> <div class="sugg-div" *ngIf="suggestions.length > 0; else legacySingleString"> <div class="suggestions-page"> <div class="suggestion-card" *ngFor="let s of pagedSuggestions; let i = index"> <div class="suggestion-badge" aria-hidden="true">{{ s.id ?? (suggestionPage * suggestionsPerPage + i + 1) }}</div> <div class="suggestion-body"> <div class="suggestion-point">{{ s.title }}</div> <div class="suggestion-feedback" [innerHTML]="s.message"></div> </div> </div> </div>
<!-- Pagination controls --> <div class="suggestion-nav"> <button class="btn btn-outline btn-nav pagebtn" (click)="prevSuggestion()" [disabled]="suggestionPage === 0" aria-label="Previous feedback">◀</button>
<div class="nav-info"> {{ suggestionPage + 1 }} / {{ totalSuggestionPages }} </div>
<button class="btn btn-outline btn-nav pagebtn" (click)="nextSuggestion()" [disabled]="suggestionPage >= totalSuggestionPages - 1" aria-label="Next feedback">▶</button> </div> </div>
<!-- Fallback when suggestion was provided as a single string --> <ng-template #legacySingleString> <div class="suggestion-item" *ngIf="result.suggestion"> <div class="suggestion-content"> <p class="suggestion-feedback">{{ result.suggestion }}</p> </div> </div> </ng-template> </div>
<div> <div class="nav-buttons"> <button class="btn btn-outline btn-nav" (click)="prevQuestion()" [disabled]="currentIndex === 0" aria-label="Previous"> ◀ Prev </button>
<div class="nav-info"> {{ currentIndex + 1 }} / {{ questions.length }} </div>
<button class="btn btn-outline btn-nav" (click)="nextQuestion()" [disabled]="currentIndex === questions.length - 1" aria-label="Next"> Next ▶ </button> </div> </div> </div>
<button aria-label="Close" class="user-guide-close-icon" (click)="closePopup()">×</button> <!-- Add a hidden audio element for programmatic playback --> </div> </div>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614// (trimmed waveform/canvas logic; kept recording/playback, API and pagination)import { Component, OnDestroy, ChangeDetectorRef, Inject, OnInit } from '@angular/core';import { HttpClient } from '@angular/common/http';import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';import { ApiService } from './pronunciation.service'; // adjust path if needed
@Component({ selector: 'app-pronunciation', templateUrl: './pronunciation.component.html', styleUrls: ['./pronunciation.component.css']})export class PronunciationComponent implements OnDestroy, OnInit { // Word UI word = 'Apple'; phonetics = '/ˈæpəl/'; imgsrc = 'assets/images/pron/letter-a.png';
// navigation state questions: Array<{ word: string; imgsrc: string; phonetics?: string }> = [ { word: 'Apple', imgsrc: 'assets/images/pron/letter-a.png', phonetics: '/ˈæpəl/' }, { word: 'Ball', imgsrc: 'assets/images/pron/letter-b.png', phonetics: '/bɔːl/' }, { word: 'Cat', imgsrc: 'assets/images/pron/letter-c.png', phonetics: '/kæt/' }, { word: 'Dog', imgsrc: 'assets/images/pron/letter-d.png', phonetics: '/dɒɡ/' }, { word: 'Egg', imgsrc: 'assets/images/pron/letter-e.png', phonetics: '/eɡ/' }, { word: 'Fish', imgsrc: 'assets/images/pron/letter-f.png', phonetics: '/fɪʃ/' }, { word: 'Grapes', imgsrc: 'assets/images/pron/letter-g.png', phonetics: '/ɡreɪps/' }, { word: 'Hat', imgsrc: 'assets/images/pron/letter-h.png', phonetics: '/hæt/' }, { word: 'Ice cream', imgsrc: 'assets/images/pron/letter-i.png', phonetics: '/ˈaɪs ˌkriːm/' }, { word: 'Jar', imgsrc: 'assets/images/pron/letter-j.png', phonetics: '/dʒɑːr/' }, { word: 'Kite', imgsrc: 'assets/images/pron/letter-k.png', phonetics: '/kaɪt/' }, { word: 'Lion', imgsrc: 'assets/images/pron/letter-l.png', phonetics: '/ˈlaɪən/' }, { word: 'Moon', imgsrc: 'assets/images/pron/letter-m.png', phonetics: '/muːn/' }, { word: 'Nest', imgsrc: 'assets/images/pron/letter-n.png', phonetics: '/nest/' }, { word: 'Orange', imgsrc: 'assets/images/pron/letter-o.png', phonetics: '/ˈɒrɪndʒ/' }, { word: 'Pig', imgsrc: 'assets/images/pron/letter-p.png', phonetics: '/pɪɡ/' }, { word: 'Queen', imgsrc: 'assets/images/pron/letter-q.png', phonetics: '/kwiːn/' }, { word: 'Rabbit', imgsrc: 'assets/images/pron/letter-r.png', phonetics: '/ˈræbɪt/' }, { word: 'Sun', imgsrc: 'assets/images/pron/letter-s.png', phonetics: '/sʌn/' }, { word: 'Tree', imgsrc: 'assets/images/pron/letter-t.png', phonetics: '/triː/' }, { word: 'Umbrella', imgsrc: 'assets/images/pron/letter-u.png', phonetics: '/ʌmˈbrelə/' }, { word: 'Van', imgsrc: 'assets/images/pron/letter-v.png', phonetics: '/væn/' }, { word: 'Watch', imgsrc: 'assets/images/pron/letter-w.png', phonetics: '/wɒtʃ/' }, { word: 'Xylophone', imgsrc: 'assets/images/pron/letter-x.png', phonetics: '/ˈzaɪləfəʊn/' }, { word: 'Yarn', imgsrc: 'assets/images/pron/letter-y.png', phonetics: '/jɑːn/' }, { word: 'Zebra', imgsrc: 'assets/images/pron/letter-z.png', phonetics: '/ˈzebrə/' } ];
currentIndex = 0;
// Backend (match ApiService host logic so you don't get host mismatches) backendURL = location.hostname.endsWith('hf.space') ? 'https://pykara-py-learn-backend.hf.space' : 'http://localhost:5000';
// Teacher playback teacherAudio?: HTMLAudioElement;
// Cache teacher audio URLs per word to avoid repeated API calls private teacherAudioCache = new Map<string, string>();
// Loading state for teacher audio request isTeacherLoading = false;
// Recording isRecording = false; private mediaRecorder?: MediaRecorder; private recordedBlobs: Blob[] = []; recordedBlobUrl?: string; private recordedAudio?: HTMLAudioElement;
// Result result: { score?: number; suggestion?: string; feedbackAudioUrl?: string; phonemeScore?: number; acousticScore?: number } | null = null;
// Structured suggestions array (one card per item from backend) suggestions: Array<{ id?: number; title?: string; type?: string; message?: string }> = [];
// Pagination for suggestions (page index) public suggestionPage = 0; public suggestionsPerPage = 1;
// Media Recording Variables private audioChunks: Blob[] = []; audioBlobUrl: string | null = null;
// Timer Variables recordingDuration: number = 0; private timer: any; isOriginal: boolean = false; private micStream?: MediaStream;
// Helper promise/resolver so callers can await the mediaRecorder.onstop completion private recordingStopPromise?: Promise<void>; private recordingStopResolver?: (() => void) | null = null;
constructor(private http: HttpClient, private cdr: ChangeDetectorRef, public dialogRef: MatDialogRef<PronunciationComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private api: ApiService) { // minimal constructor; init in ngOnInit }
ngOnInit(): void { this.showQuestion(0); }
// Called when the toggle changes updateSelection() { // stop any current teacher playback and clear cache so selection change takes immediate effect this.stopTeacherPlayback(); this.teacherAudioCache.clear(); this.cdr.detectChanges(); }
// Helper: build static asset path for a word (normalize to lowercase, underscores) private getStaticTeacherAudioPath(word: string): string { const clean = (word || '') .toLowerCase() .trim() .replace(/\s+/g, '_') // spaces -> underscores .replace(/[^a-z0-9_]/g, ''); // remove other chars return `assets/audio/original/${clean}.m4a`; }
// Play teacher audio: use local static file when original voice selected, otherwise fall back to existing flow. async playTeacherAudio(): Promise<void> { // If original voice selected, prefer a local static asset if (!this.isOriginal) { const staticPath = this.getStaticTeacherAudioPath(this.word); this.isTeacherLoading = true; try { const resp = await fetch(staticPath, { method: 'HEAD' }); if (resp.ok) { this.teacherAudioCache.set(this.word, staticPath); this.playAudioWithWaveform(staticPath, 'teacher'); this.isTeacherLoading = false; return; } } catch (err) { console.warn('Static teacher audio check failed, will use generated audio', err); } this.isTeacherLoading = false; }
const cached = this.teacherAudioCache.get(this.word); if (cached) { this.isTeacherLoading = true; this.playAudioWithWaveform(cached, 'teacher'); this.isTeacherLoading = false; return; }
this.isTeacherLoading = true;
// Try streaming audio bytes from the backend (no server-side file). Fallback to existing blob/url flows. this.api.generateTeacherAudioStream(this.word, this.selectedFile).subscribe({ next: (blob) => { try { const objUrl = URL.createObjectURL(blob); const prev = this.teacherAudioCache.get(this.word); if (prev && prev.startsWith('blob:')) { try { URL.revokeObjectURL(prev); } catch { } } this.teacherAudioCache.set(this.word, objUrl); this.playAudioWithWaveform(objUrl, 'teacher'); } finally { this.isTeacherLoading = false; } }, error: (err) => { console.warn('generateTeacherAudioStream failed, falling back to generateTeacherAudioBlob/url', err); // fallback to existing behavior (request URL then fetch) this.api.generateTeacherAudioBlob(this.word, this.selectedFile).subscribe({ next: ({ audioUrl, blob }) => { const objUrl = URL.createObjectURL(blob); const prev = this.teacherAudioCache.get(this.word); if (prev && prev.startsWith('blob:')) { try { URL.revokeObjectURL(prev); } catch { } } this.teacherAudioCache.set(this.word, objUrl); this.playAudioWithWaveform(objUrl, 'teacher'); this.isTeacherLoading = false; }, error: (e) => { console.error('generateTeacherAudioBlob fallback failed', e); // as a last resort, try URL-only endpoint this.api.generateTeacherAudio(this.word, this.selectedFile).subscribe({ next: ({ audioUrl }) => { this.teacherAudioCache.set(this.word, audioUrl); this.playAudioWithWaveform(audioUrl, 'teacher'); this.isTeacherLoading = false; }, error: (ee) => { console.error('generateTeacherAudio fallback failed', ee); this.isTeacherLoading = false; } }); } }); } }); }
// Simplified playback: no waveform/canvas support in finalized HTML public playAudioWithWaveform(src: string, type: 'teacher' | 'recorded'): void { if (!src) return;
if (type === 'teacher') { this.stopTeacherPlayback(); this.teacherAudio = new Audio(); try { if (!src.startsWith('blob:')) { this.teacherAudio.crossOrigin = 'anonymous'; } } catch { /* ignore */ } this.teacherAudio.preload = 'auto'; this.teacherAudio.src = src; this.teacherAudio.oncanplay = () => { this.teacherAudio!.play().catch(() => { /* ignore */ }); }; this.teacherAudio.onended = () => { /* no-op */ }; try { this.teacherAudio.load(); } catch { /* ignore */ } } else { // recorded playback this.stopRecordedPlayback(); this.recordedAudio = new Audio(); try { if (!src.startsWith('blob:')) { this.recordedAudio.crossOrigin = 'anonymous'; } } catch { /* ignore */ } this.recordedAudio.preload = 'auto'; this.recordedAudio.src = src; this.recordedAudio.oncanplay = () => { this.recordedAudio!.play().catch(() => { /* ignore */ }); }; this.recordedAudio.onended = () => this.stopRecordedPlayback(); try { this.recordedAudio.load(); } catch { /* ignore */ } } }
private stopTeacherPlayback(): void { if (this.teacherAudio) { try { this.teacherAudio.pause(); this.teacherAudio.onended = null; } catch { } this.teacherAudio = undefined; } }
private stopRecordedPlayback(): void { if (this.recordedAudio) { try { this.recordedAudio.pause(); this.recordedAudio.onended = null; } catch { } this.recordedAudio = undefined; } }
// Loading state for check pronunciation request isChecking = false;
// Updated checkPronunciation: ensure recording has stopped, build a reliable Blob and fall back to object URL if needed. async checkPronunciation(): Promise<void> { // If currently recording, stop and wait for onstop handler to finish. if (this.isRecording && this.mediaRecorder) { try { this.mediaRecorder.stop(); if (this.recordingStopPromise) { await this.recordingStopPromise; } } catch (e) { console.warn('Error stopping recorder before check:', e); } }
// If there is an object URL for the finalized recording, prefer fetching it. let audioBlob: Blob | null = null;
if (this.recordedBlobs && this.recordedBlobs.length > 0) { // merge recorded chunk blobs const inferredType = this.recordedBlobs[0]?.type || 'audio/webm'; audioBlob = new Blob(this.recordedBlobs, { type: inferredType }); } else if (this.audioBlobUrl) { // fetch blob from the object URL created in onstop try { const resp = await fetch(this.audioBlobUrl); audioBlob = await resp.blob(); } catch (e) { console.warn('Failed to fetch audioBlob from audioBlobUrl:', e); } }
if (!audioBlob || audioBlob.size === 0) { // nothing recorded or still not available this.result = { score: 0, suggestion: 'No audio recorded. Please record and try again.' }; this.suggestions = [{ id: 1, title: 'No Audio', message: 'No audio was found. Record again and ensure microphone permissions are allowed.' }]; this.suggestionPage = 0; this.cdr.detectChanges(); return; }
this.isChecking = true; this.cdr.detectChanges();
// Choose a filename extension that matches the blob type if possible let ext = '.webm'; try { const t = audioBlob.type || ''; if (t.includes('wav')) ext = '.wav'; else if (t.includes('ogg')) ext = '.ogg'; else if (t.includes('webm')) ext = '.webm'; else if (t.includes('mpeg') || t.includes('mp3')) ext = '.mp3'; } catch { /* ignore */ }
const filename = `${this.word}${ext}`; const form = new FormData(); form.append('audio', audioBlob, filename); form.append('word', this.word);
try { const res = await this.http.post<any>(`${this.backendURL}/check_pronunciation`, form).toPromise();
// Compute phonemic score (backend provides phoneme_similarity in range 0..1) const phonemeSimilarity = Number(res?.phoneme_similarity ?? res?.phonemeSimilarity ?? 0); const phonemePct = Math.round(Math.max(0, Math.min(1, phonemeSimilarity)) * 100);
// Keep acoustic score if you want to display/use later const acousticScore = Number(res?.acoustic_score ?? res?.score ?? res?.score_acoustic ?? 0);
// Set the speakometer to show phonemic score scaled to 0..100 this.result = { score: phonemePct, suggestion: (typeof res?.suggestion === 'string') ? res.suggestion : '', feedbackAudioUrl: res?.audio_url ? `${this.backendURL}/${res.audio_url}` : undefined, phonemeScore: phonemePct, acousticScore: isNaN(acousticScore) ? undefined : acousticScore };
// Build structured suggestions with sanitized messages and derived titles if (Array.isArray(res?.suggestion)) { this.suggestions = res.suggestion.map((s: any, idx: number) => { const raw = (typeof s === 'string') ? s : (s.message ?? JSON.stringify(s)); const msg = this.sanitizeFeedbackText(raw); const explicitTitle = (s && s.title) ? this.sanitizeFeedbackText(String(s.title)) : ''; const title = explicitTitle || this.deriveTitleFromMessage(msg, idx); return { id: s?.id ?? (idx + 1), title, type: s?.type ?? '', message: msg }; }); } else if (typeof res?.suggestion === 'string' && res.suggestion.trim()) { const msg = this.sanitizeFeedbackText(res.suggestion); this.suggestions = [{ id: 1, title: this.deriveTitleFromMessage(msg, 0), type: '', message: msg }]; } else { this.suggestions = []; }
// Reset suggestion pagination this.suggestionPage = 0;
} catch (err) { console.error('check_pronunciation error', err); this.result = { score: 0, suggestion: 'Server error' }; this.suggestions = [{ id: 1, title: 'Error', message: 'Server error' }]; this.suggestionPage = 0; } finally { this.isChecking = false; this.cdr.detectChanges(); } }
// Remove leading non-alphanumeric markers (tick marks, bullets) and trim private sanitizeFeedbackText(text: string): string { if (!text) return ''; // strip leading non-alphanumeric characters and extra whitespace const cleaned = text.replace(/^[^A-Za-z0-9]+/, '').trim(); return cleaned; }
// Derive a short human-friendly title from message text using keyword rules private deriveTitleFromMessage(msg: string, idx: number): string { if (!msg) return `Feedback ${idx + 1}`;
const m = msg.toLowerCase();
if (m.includes('vowel')) return 'Vowel'; if (m.includes('consonant')) return 'Consonant'; if (m.includes('missing') || m.includes('missing sounds') || m.includes('missing sound')) return 'Missing Sounds'; if (m.includes('filler') || m.startsWith('uh ') || m.startsWith('ah ')) return 'Extra Sounds'; if (m.includes('syllable')) return 'Syllables'; if (m.includes('stress')) return 'Stress'; if (m.includes('timing') || m.includes('speed') || m.includes('pace')) return 'Timing & Pace'; if (m.includes('quiet') || m.includes('soft') || m.includes('loud') || m.includes('volume')) return 'Volume'; if (m.includes('whisper') || m.includes('system heard') || m.includes('recognized') || m.includes('heard')) return 'Word Match'; if (m.includes('natural')) return 'Naturalness'; if (m.includes('clarity') || m.includes('noise') || m.includes('unclear')) return 'Clarity'; if (m.includes('audio') && m.includes('noise')) return 'Audio Quality';
// Fallback: first 4 words, trimmed and capitalized const words = msg.split(/\s+/).slice(0, 4).map(w => w.replace(/[^a-zA-Z0-9'-]/g, '')); let title = words.join(' '); if (!title) title = `Feedback ${idx + 1}`; // Capitalize first letter of each word for tidy display title = title.split(' ').map(p => p.charAt(0).toUpperCase() + p.slice(1)).join(' '); return title; }
ngOnDestroy(): void { this.stopTeacherPlayback(); this.stopRecordedPlayback(); if (this.micStream) { try { this.micStream.getTracks().forEach(t => t.stop()); } catch { } this.micStream = undefined; } }
selectedFile?: File;
onFileSelected(ev: Event) { const input = ev.target as HTMLInputElement; if (input.files && input.files.length) { this.selectedFile = input.files[0]; if (this.teacherAudioCache.has(this.word)) { this.teacherAudioCache.delete(this.word); } } }
requestTeacherAudio() { const cached = this.teacherAudioCache.get(this.word); if (cached) { const a = new Audio(cached); a.play().catch(err => console.warn('play failed', err)); return; }
this.api.generateTeacherAudio(this.word, this.selectedFile).subscribe({ next: ({ audioUrl }) => { this.teacherAudioCache.set(this.word, audioUrl); const a = new Audio(audioUrl); a.play().catch(err => console.warn('play failed', err)); }, error: err => { console.error('generateTeacherAudio failed', err); } }); }
async startRecording() { // Reset previous state this.audioBlobUrl = null; this.audioChunks = []; this.recordedBlobs = []; this.isRecording = true; this.recordingDuration = 0;
// Prepare promise so callers can await onstop this.recordingStopPromise = new Promise<void>((resolve) => { this.recordingStopResolver = resolve; });
// Start timer this.timer = setInterval(() => { this.recordingDuration++; this.cdr.detectChanges(); }, 1000);
try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); this.micStream = stream; this.mediaRecorder = new MediaRecorder(stream);
this.mediaRecorder.ondataavailable = (event: BlobEvent) => { if (event.data && event.data.size > 0) { this.audioChunks.push(event.data); this.recordedBlobs.push(event.data); } };
this.mediaRecorder.onstop = async () => { clearInterval(this.timer);
const audioBlob = new Blob(this.audioChunks, { type: 'audio/webm; codecs=opus' });
if (this.audioBlobUrl) { try { URL.revokeObjectURL(this.audioBlobUrl); } catch { } } this.audioBlobUrl = URL.createObjectURL(audioBlob); this.recordedBlobUrl = this.audioBlobUrl;
try { if (this.micStream) this.micStream.getTracks().forEach((t: any) => t.stop()); } catch { } this.micStream = undefined;
this.isRecording = false; this.cdr.detectChanges();
// resolve any waiter if (this.recordingStopResolver) { try { this.recordingStopResolver(); } catch { } this.recordingStopResolver = null; this.recordingStopPromise = undefined; } };
// Start actual recording this.mediaRecorder.start(); } catch (err) { this.isRecording = false; clearInterval(this.timer); console.error('Error accessing microphone:', err); alert('Could not access microphone. Ensure permissions are granted.'); // resolve promise to avoid deadlocks if start failed if (this.recordingStopResolver) { try { this.recordingStopResolver(); } catch { } this.recordingStopResolver = null; this.recordingStopPromise = undefined; } } }
stopRecording() { if (this.mediaRecorder && this.isRecording) { this.mediaRecorder.stop(); this.isRecording = false; } else { clearInterval(this.timer); this.isRecording = false; } }
// Public playback for recorded audio public playRecorded(): void { if (!this.recordedBlobUrl) return; this.playAudioWithWaveform(this.recordedBlobUrl, 'recorded'); }
public get needleAngle(): number { const score = Math.max(0, Math.min(100, Number(this.result?.score ?? 0))); return -90 + (score / 100) * 180; }
public get suggestionCount(): number { return this.suggestions?.length ?? 0; }
public get totalSuggestionPages(): number { return Math.max(1, Math.ceil(this.suggestionCount / this.suggestionsPerPage)); }
public get pagedSuggestions(): Array<{ id?: number; title?: string; type?: string; message?: string }> { if (!this.suggestions || this.suggestions.length === 0) return []; const start = this.suggestionPage * this.suggestionsPerPage; return this.suggestions.slice(start, start + this.suggestionsPerPage); }
public prevSuggestion(): void { if (this.suggestionPage > 0) { this.suggestionPage--; } }
public nextSuggestion(): void { if (this.suggestionPage < this.totalSuggestionPages - 1) { this.suggestionPage++; } }
public showSuggestionAt(pageIndex: number): void { if (pageIndex >= 0 && pageIndex < this.totalSuggestionPages) { this.suggestionPage = pageIndex; } }
closePopup(): void { this.dialogRef.close(); }
public prevQuestion(): void { if (this.currentIndex > 0) { this.showQuestion(this.currentIndex - 1); } }
public nextQuestion(): void { if (this.currentIndex < this.questions.length - 1) { this.showQuestion(this.currentIndex + 1); } }
public showQuestion(index: number): void { if (index < 0 || index >= this.questions.length) return;
this.stopTeacherPlayback(); this.stopRecordedPlayback();
if (this.audioBlobUrl && this.audioBlobUrl.startsWith('blob:')) { try { URL.revokeObjectURL(this.audioBlobUrl); } catch { /* ignore */ } } this.audioBlobUrl = null; this.recordedBlobUrl = undefined; this.recordedBlobs = []; this.audioChunks = [];
this.result = null; this.suggestions = []; this.suggestionPage = 0;
this.currentIndex = index; const q = this.questions[index]; this.word = q.word; this.phonetics = q.phonetics ?? ''; this.imgsrc = q.imgsrc ?? this.imgsrc;
this.cdr.detectChanges(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116import { Injectable } from '@angular/core';import { HttpClient } from '@angular/common/http';import { Observable, throwError } from 'rxjs';import { tap, catchError, map, switchMap } from 'rxjs/operators';
@Injectable({ providedIn: 'root'})export class ApiService {
// Use single rag host (adjust port to match your backend) private ragHost = location.hostname.endsWith('hf.space') ? 'https://pykara-py-learn-backend.hf.space' : 'http://localhost:5000'; // <-- ensure this matches your Flask app port
// Pronunciation blueprint base path (matches backend blueprint url_prefix '/pron') private pronBase = `${this.ragHost}/`;
constructor(private http: HttpClient) { }
generateTeacherAudio(word: string, reference?: File): Observable<{ audioUrl: string }> { const url = `${this.pronBase}/generate_teacher_audio`;
if (reference) { const form = new FormData(); form.append('word', word); form.append('reference', reference, reference.name);
// Do NOT set Content-Type header for FormData; browser sets the boundary. return this.http.post<any>(url, form).pipe( map(res => ({ audioUrl: `${this.pronBase}/${res.audio_url}` })), tap(r => console.log('[API] generateTeacherAudio (with ref) ->', r)), catchError(err => { console.error('[API] generateTeacherAudio error', err); return throwError(() => err); }) ); } else { const headers = { 'Content-Type': 'application/json' }; return this.http.post<any>(url, { word }, { headers }).pipe( map(res => ({ audioUrl: `${this.pronBase}/${res.audio_url}` })), tap(r => console.log('[API] generateTeacherAudio ->', r)), catchError(err => { console.error('[API] generateTeacherAudio error', err); return throwError(() => err); }) ); } }
// New: request teacher audio as raw bytes (no server-side persistent file) // Expects a backend endpoint that returns audio bytes (wav) directly. generateTeacherAudioStream(word: string, reference?: File): Observable<Blob> { const streamUrl = `${this.pronBase}/generate_teacher_audio_stream`;
if (reference) { const form = new FormData(); form.append('word', word); form.append('reference', reference, reference.name); // post form and expect blob response return this.http.post(streamUrl, form, { responseType: 'blob' }).pipe( tap(() => console.log('[API] generateTeacherAudioStream (with ref)')), map((b: any) => b as Blob), catchError(err => { console.error('[API] generateTeacherAudioStream error', err); return throwError(() => err); }) ); } else { const headers = { 'Content-Type': 'application/json' }; return this.http.post(streamUrl, { word }, { headers, responseType: 'blob' as 'json' }).pipe( tap(() => console.log('[API] generateTeacherAudioStream')), map((b: any) => b as Blob), catchError(err => { console.error('[API] generateTeacherAudioStream error', err); return throwError(() => err); }) ); } }
// Helper: generate teacher audio then download it as a Blob // Returns { audioUrl, blob } where audioUrl is the full URL and blob is the audio bytes. generateTeacherAudioBlob(word: string, reference?: File): Observable<{ audioUrl: string; blob: Blob }> { const postUrl = `${this.pronBase}/generate_teacher_audio`;
const post$ = reference ? (() => { const form = new FormData(); form.append('word', word); form.append('reference', reference, reference.name); return this.http.post<any>(postUrl, form); })() : (() => { const headers = { 'Content-Type': 'application/json' }; return this.http.post<any>(postUrl, { word }, { headers }); })();
return post$.pipe( switchMap((res: any) => { // backend returns e.g. "audio/teacher-xxxx.wav" — build full URL under /pron const audioUrl = `${this.pronBase}/${res.audio_url}`; // fetch blob return this.http.get(audioUrl, { responseType: 'blob' }).pipe( map((b: Blob) => ({ audioUrl, blob: b })), tap(() => console.log('[API] downloaded teacher audio as blob', audioUrl)) ); }), catchError(err => { console.error('[API] generateTeacherAudioBlob error', err); return throwError(() => err); }) ); }}src/app/pronunciation/pronunciation.component.cssAdded+582
src/app/pronunciation/pronunciation.component.htmlAdded+193
src/app/pronunciation/pronunciation.component.tsAdded+614
src/app/pronunciation/pronunciation.service.tsAdded+116