Oviya commited on
Commit ·
0b92c10
1
Parent(s): 3f95782
update pron component
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- package.json+1
- src/app/pronunciation/pronunciation.component.css+66-3
- src/app/pronunciation/pronunciation.component.html+39-16
- src/app/pronunciation/pronunciation.component.ts+274-17
- src/app/pronunciation/pronunciation.service.ts+30-58
- src/assets/audio/apple.mp3Added+3
- src/assets/audio/ball.mp3Added+3
- src/assets/audio/cat.mp3Added+3
- src/assets/audio/dog.mp3Added+3
- src/assets/audio/egg.mp3Added+3
- src/assets/audio/fish.mp3Added+3
- src/assets/audio/grapes.mp3Added+3
- src/assets/audio/hat.mp3Added+3
- src/assets/audio/ice_cream.mp3Added+3
- src/assets/audio/jar.mp3Added+3
- src/assets/audio/kite.mp3Added+3
- src/assets/audio/lion.mp3Added+3
- src/assets/audio/moon.mp3Added+3
- src/assets/audio/nest.mp3Added+3
- src/assets/audio/orange.mp3Added+3
- src/assets/audio/original/ball.m4aDeleted
- src/assets/audio/original/cat.m4aDeleted
- src/assets/audio/original/dog.m4aDeleted
- src/assets/audio/original/egg.m4aDeleted
- src/assets/audio/original/fish.m4aDeleted
- src/assets/audio/original/grapes.m4aDeleted
- src/assets/audio/original/hat.m4aDeleted
- src/assets/audio/original/ice_cream.m4aDeleted
- src/assets/audio/original/jar.m4aDeleted
- src/assets/audio/original/kite.m4aDeleted
- src/assets/audio/original/lion.m4aDeleted
- src/assets/audio/original/moon.m4aDeleted
- src/assets/audio/original/nest.m4aDeleted
- src/assets/audio/original/orange.m4aDeleted
- src/assets/audio/original/pig.m4aDeleted
- src/assets/audio/original/queen.m4aDeleted
- src/assets/audio/original/rabbit.m4aDeleted
- src/assets/audio/original/sun.m4aDeleted
- src/assets/audio/original/tree.m4aDeleted
- src/assets/audio/original/van.m4aDeleted
- src/assets/audio/original/watch.m4aDeleted
- src/assets/audio/original/xylophone.m4aDeleted
- src/assets/audio/original/yarn.m4aDeleted
- src/assets/audio/original/zebra.m4aDeleted
- src/assets/audio/pig.mp3Added+3
- src/assets/audio/queen.mp3Added+3
- src/assets/audio/rabbit.mp3Added+3
- src/assets/audio/sun.mp3Added+3
- src/assets/audio/tree.mp3Added+3
- src/assets/audio/umbrella.mp3Added+3
29 unmodified lines30313233343529 unmodified lines"rxjs": "~7.8.0","tailwindcss": "^3.4.17","tslib": "^2.3.0","zone.js": "~0.14.3"},"devDependencies": {29 unmodified lines3031323334353629 unmodified lines"rxjs": "~7.8.0","tailwindcss": "^3.4.17","tslib": "^2.3.0","wavesurfer.js": "^7.11.1","zone.js": "~0.14.3"},"devDependencies": {
7 unmodified lines8910111213141537 unmodified lines53545556575859607 unmodified linesflex-direction: column;}.header {text-align: center;}.title {37 unmodified lines.controls-section {display: flex;flex-direction: column;justify-content: center;gap: 2vw;width: 30vw;}7 unmodified lines8910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777837 unmodified lines1161171181191201211221237 unmodified linesflex-direction: column;}/* Keep the dropdown at the start */.dropdown-row {display: flex;align-items: center;}/* Accessible helper — hide visually but keep available to screen readers */.visually-hidden {position: absolute !important;height: 1px;width: 1px;overflow: hidden;clip: rect(1px, 1px, 1px, 1px);white-space: nowrap;border: 0;padding: 0;margin: -1px;}/* Styled select that fits the app button styles */.select-dropdown {appearance: none;-webkit-appearance: none;-moz-appearance: none;display: inline-block;min-width: 180px;height: 36px;padding: 6px 36px 6px 12px; /* extra right padding for custom arrow */font-size: 14px;line-height: 1;color: #111827;background-color: #ffffff;border: 1px solid #d1d5db;border-radius: 8px;background-image: linear-gradient(45deg, transparent 50%, #6b7280 50%), linear-gradient(135deg, #6b7280 50%, transparent 50%), linear-gradient(to right, #fff, #fff);background-position: calc(100% - 18px) calc(1em + 2px), calc(100% - 13px) calc(1em + 2px), 100% 0;background-size: 6px 6px, 6px 6px, 2.5em 2.5em;background-repeat: no-repeat;cursor: pointer;}/* Hover / focus states for accessibility */.select-dropdown:hover {border-color: #9ca3af;}.select-dropdown:focus {outline: none;box-shadow: 0 0 0 3px rgba(59,130,246,0.14);border-color: #3b82f6;}/* Smaller variant if needed */.select-dropdown.small {min-width: 140px;height: 32px;font-size: 13px;border-radius: 6px;}.header {/*text-align: center;*/display:flex;gap:13vw;}.title {37 unmodified lines.controls-section {display: flex;flex-direction: column;justify-content: space-evenly;gap: 0.5vw;width: 30vw;}
123456736 unmodified lines4445464748495043 unmodified lines94959697989918 unmodified lines1181191201211221231246 unmodified lines13113213313413513613713813914014114215 unmodified lines15815916016116216316416516616716816917017117215 unmodified lines188189190191192193<div class="pron-container"><!-- Header --><div class="header"><h2 class="title">Pronunciation Trainer</h2></div>36 unmodified lines[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"43 unmodified lines</div></div><!-- Check Button --><button class="btn btn-success full-width"id="checkBtn"18 unmodified lines<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>6 unmodified lines</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>15 unmodified lines<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>15 unmodified lines<button aria-label="Close" class="user-guide-close-icon" (click)="closePopup()">×</button><!-- Add a hidden audio element for programmatic playback --></div></div>1234567891011121314151636 unmodified lines5354555657585943 unmodified lines10310410510610710810911011111211311411511611711811912012118 unmodified lines1401411421431441451466 unmodified lines15315415515615715815916016116216316415 unmodified lines18018118218318418518618718818919019119219319419515 unmodified lines211212213214215216<div class="pron-container"><!-- Header --><div class="header"><div class="dropdown-row" aria-hidden="false"><label for="pronModeSelect" class="visually-hidden">Pronunciation Mode</label><select id="pronModeSelect" class="select-dropdown" aria-label="Pronunciation Mode" (change)="onModeChange($any($event.target).value)"><option value="phonetics">Phoneme-Level Accuracy Check</option><option value="waveform">Audio Similarity Check</option><option value="normaltext" disabled>Speech-to-Text Accuracy Check</option><option value="prosody" disabled>Prosody Check</option><option value="embedding" disabled>Embedding Similarity Check</option></select></div><h2 class="title">Pronunciation Trainer</h2></div>36 unmodified lines[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"43 unmodified lines</div></div><!-- Waveform containers (shown only in Audio Similarity Check mode) --><div *ngIf="pronMode === 'waveform'" class="waveform-row"><div class="waveform-block"><div class="waveform-title">Teacher</div><div id="teacherWaveform" class="waveform-canvas"></div></div><div class="waveform-block"><div class="waveform-title">Student</div><div id="studentWaveform" class="waveform-canvas"></div></div></div><!-- Check Button --><button class="btn btn-success full-width"id="checkBtn"18 unmodified lines<div class="results-section" id="resultsSection"><!-- Score Display: always shown (initially 0) so speakometer is visible from start --><div class="gauge-wrapper"><div class="gauge"><div class="gauge-arc"></div>6 unmodified lines</div></div><!-- Suggestions: show whenever we have suggestions, regardless of result --><div class="suggestions-section" *ngIf="suggestions.length > 0"><h3 class="suggestions-title">Feedback & Suggestions</h3><!-- Structured suggestions --><div class="sugg-div"><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>15 unmodified lines<button class="btn btn-outline btn-nav pagebtn" (click)="nextSuggestion()" [disabled]="suggestionPage >= totalSuggestionPages - 1" aria-label="Next feedback">▶</button></div></div></div><!-- Legacy single-string suggestion: hide in select mode and only show when not using structured suggestions --><div class="suggestions-section" *ngIf="pronMode !== 'select' && (!suggestions || suggestions.length === 0) && result?.suggestion"><h3 class="suggestions-title">Feedback & Suggestions</h3><div class="suggestion-item"><div class="suggestion-content"><p class="suggestion-feedback">{{ result?.suggestion }}</p></div></div></div><div>15 unmodified lines<button aria-label="Close" class="user-guide-close-icon" (click)="closePopup()">×</button><!-- Add a hidden audio element for programmatic playback --></div></div>
1234567883 unmodified lines9293949596975 unmodified lines1031041051061071081091101111121131141151161 unmodified line11811912012112212312475 unmodified lines20020120220320420520620720820928 unmodified lines2382392402412422432442452462472481 unmodified line25025125225325425513 unmodified lines26927027127227327427527627727827928028128228329 unmodified lines3133143153163173183193203213223233243253263273283292 unmodified lines33233333433533633733813 unmodified lines35235335435535635735835946 unmodified lines40640740840941041115 unmodified lines4274284294304314322 unmodified lines43543643743843944044144243 unmodified lines486487488489490491117 unmodified lines609610611612613614// (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',83 unmodified linesprivate 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,5 unmodified linesthis.showQuestion(0);}// Called when the toggle changesupdateSelection() {// stop any current teacher playback and clear cache so selection change takes immediate effectthis.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 || '')1 unmodified line.trim().replace(/\s+/g, '_') // spaces -> underscores.replace(/[^a-z0-9_]/g, ''); // remove other charsreturn `assets/audio/original/${clean}.m4a`;}// Play teacher audio: use local static file when original voice selected, otherwise fall back to existing flow.75 unmodified lines});}// Simplified playback: no waveform/canvas support in finalized HTMLpublic playAudioWithWaveform(src: string, type: 'teacher' | 'recorded'): void {if (!src) return;if (type === 'teacher') {this.stopTeacherPlayback();this.teacherAudio = new Audio();28 unmodified lines}}private stopTeacherPlayback(): void {if (this.teacherAudio) {try { this.teacherAudio.pause(); this.teacherAudio.onended = null; } catch { }this.teacherAudio = undefined;}}private stopRecordedPlayback(): void {1 unmodified linetry { this.recordedAudio.pause(); this.recordedAudio.onended = null; } catch { }this.recordedAudio = undefined;}}// Loading state for check pronunciation request13 unmodified lines}}// 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 blobsconst 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 onstoptry {const resp = await fetch(this.audioBlobUrl);audioBlob = await resp.blob();29 unmodified linesform.append('audio', audioBlob, filename);form.append('word', this.word);try {const res = await this.http.post<any>(`${this.backendURL}/pron/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 laterconst acousticScore = Number(res?.acoustic_score ?? res?.score ?? res?.score_acoustic ?? 0);// Set the speakometer to show phonemic score scaled to 0..100this.result = {score: phonemePct,suggestion: (typeof res?.suggestion === 'string') ? res.suggestion : '',2 unmodified linesacousticScore: isNaN(acousticScore) ? undefined : acousticScore};// Build structured suggestions with sanitized messages and derived titlesif (Array.isArray(res?.suggestion)) {this.suggestions = res.suggestion.map((s: any, idx: number) => {const raw = (typeof s === 'string') ? s : (s.message ?? JSON.stringify(s));13 unmodified lines} else {this.suggestions = [];}// Reset suggestion paginationthis.suggestionPage = 0;} catch (err) {46 unmodified linesngOnDestroy(): void {this.stopTeacherPlayback();this.stopRecordedPlayback();if (this.micStream) {try { this.micStream.getTracks().forEach(t => t.stop()); } catch { }this.micStream = undefined;15 unmodified linesrequestTeacherAudio() {const cached = this.teacherAudioCache.get(this.word);if (cached) {const a = new Audio(cached);a.play().catch(err => console.warn('play failed', err));return;2 unmodified linesthis.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);43 unmodified linesthis.audioBlobUrl = URL.createObjectURL(audioBlob);this.recordedBlobUrl = this.audioBlobUrl;try { if (this.micStream) this.micStream.getTracks().forEach((t: any) => t.stop()); } catch { }this.micStream = undefined;117 unmodified linesthis.phonetics = q.phonetics ?? '';this.imgsrc = q.imgsrc ?? this.imgsrc;this.cdr.detectChanges();}}1234567883 unmodified lines92939495969798991001011025 unmodified lines1081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761 unmodified line17817918018118218318475 unmodified lines26026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131228 unmodified lines3413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713721 unmodified line37437537637737837938038138213 unmodified lines39639739839940040140240340440540640729 unmodified lines4374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645652 unmodified lines56856957057157257357413 unmodified lines58858959059159259346 unmodified lines64064164264364464564615 unmodified lines6626636646656666676686696706716722 unmodified lines67567667767867968068168268368468568643 unmodified lines730731732733734735736737738739740117 unmodified lines858859860861862863864865866867868869870871import { 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 neededimport WaveSurfer from 'wavesurfer.js';@Component({selector: 'app-pronunciation',83 unmodified linesprivate recordingStopPromise?: Promise<void>;private recordingStopResolver?: (() => void) | null = null;// WaveSurfer statepronMode: string = 'phonetics'; // current dropdown modeprivate teacherWaveSurfer: any;private studentWaveSurfer: any;constructor(private http: HttpClient, private cdr: ChangeDetectorRef,public dialogRef: MatDialogRef<PronunciationComponent>,@Inject(MAT_DIALOG_DATA) public data: any,5 unmodified linesthis.showQuestion(0);}// handle dropdown mode changepublic onModeChange(mode: string | null | undefined) {const m = (mode ?? 'phonetics').toString().trim().toLowerCase();console.log('[Pronunciation] onModeChange ->', { raw: mode, normalized: m });this.pronMode = m;if (m === 'waveform') {this.initWaveSurfers();const cached = this.teacherAudioCache.get(this.word);if (cached && this.teacherWaveSurfer) {try { this.teacherWaveSurfer.load(cached); } catch { /* ignore */ }}if (this.recordedBlobUrl && this.studentWaveSurfer) {try { this.studentWaveSurfer.load(this.recordedBlobUrl); } catch { /* ignore */ }}} else {this.destroyWaveSurfers();}}// Added: updateSelection used by template togglepublic updateSelection(): void {// stop any current teacher playback and clear cache so selection change takes immediate effectthis.stopTeacherPlayback();this.teacherAudioCache.clear();this.cdr.detectChanges();}private initWaveSurfers(): void {// avoid re-creatingif (!this.teacherWaveSurfer) {try {this.teacherWaveSurfer = WaveSurfer.create({container: '#teacherWaveform',waveColor: '#d0e9ff',progressColor: '#007acc',cursorColor: '#333',height: 80});} catch (err) { console.warn('could not create teacher WaveSurfer', err); }}if (!this.studentWaveSurfer) {try {this.studentWaveSurfer = WaveSurfer.create({container: '#studentWaveform',waveColor: '#ffdcd0',progressColor: '#ff6b3d',cursorColor: '#333',height: 80});} catch (err) { console.warn('could not create student WaveSurfer', err); }}}private destroyWaveSurfers(): void {try {if (this.teacherWaveSurfer) { try { this.teacherWaveSurfer.destroy(); } catch { } this.teacherWaveSurfer = undefined; }if (this.studentWaveSurfer) { try { this.studentWaveSurfer.destroy(); } catch { } this.studentWaveSurfer = undefined; }} catch { /* ignore */ }}// Helper: build static asset path for a word (normalize to lowercase, underscores)private getStaticTeacherAudioPath(word: string): string {const clean = (word || '')1 unmodified line.trim().replace(/\s+/g, '_') // spaces -> underscores.replace(/[^a-z0-9_]/g, ''); // remove other charsreturn `assets/audio/${clean}.mp3`;}// Play teacher audio: use local static file when original voice selected, otherwise fall back to existing flow.75 unmodified lines});}// Simplified playback: now supports WaveSurfer modepublic playAudioWithWaveform(src: string, type: 'teacher' | 'recorded'): void {if (!src) return;// If the dropdown is in waveform mode, use WaveSurfer instancesif (this.pronMode === 'waveform') {// ensure wavesurfer instances existthis.initWaveSurfers();if (type === 'teacher') {try {if (this.teacherWaveSurfer) {// load will accept blob/object URL or remote URLthis.teacherWaveSurfer.load(src);// autoplay when readythis.teacherWaveSurfer.once('ready', () => {try { this.teacherWaveSurfer.play(); } catch { /* ignore */ }});} else {// fallback to simple audio elementthis.fallbackAudioPlay(src, 'teacher');}} catch (e) {console.warn('WaveSurfer teacher play failed, fallback', e);this.fallbackAudioPlay(src, 'teacher');}} else {// recordedtry {if (this.studentWaveSurfer) {this.studentWaveSurfer.load(src);this.studentWaveSurfer.once('ready', () => {try { this.studentWaveSurfer.play(); } catch { /* ignore */ }});} else {this.fallbackAudioPlay(src, 'recorded');}} catch (e) {console.warn('WaveSurfer student play failed, fallback', e);this.fallbackAudioPlay(src, 'recorded');}}return;}// Non-waveform fallback (existing behavior)if (type === 'teacher') {this.stopTeacherPlayback();this.teacherAudio = new Audio();28 unmodified lines}}// Simple fallback audio creation used when wavesurfer errorsprivate fallbackAudioPlay(src: string, type: 'teacher' | 'recorded') {if (type === 'teacher') {this.stopTeacherPlayback();const a = new Audio(src);try { if (!src.startsWith('blob:')) a.crossOrigin = 'anonymous'; } catch { }a.play().catch(() => { /* ignore */ });this.teacherAudio = a;} else {this.stopRecordedPlayback();const a = new Audio(src);try { if (!src.startsWith('blob:')) a.crossOrigin = 'anonymous'; } catch { }a.play().catch(() => { /* ignore */ });this.recordedAudio = a;}}private stopTeacherPlayback(): void {if (this.teacherAudio) {try { this.teacherAudio.pause(); this.teacherAudio.onended = null; } catch { }this.teacherAudio = undefined;}// also pause wavesurfer if presentif (this.teacherWaveSurfer) {try { this.teacherWaveSurfer.pause(); } catch { }}}private stopRecordedPlayback(): void {1 unmodified linetry { this.recordedAudio.pause(); this.recordedAudio.onended = null; } catch { }this.recordedAudio = undefined;}if (this.studentWaveSurfer) {try { this.studentWaveSurfer.pause(); } catch { }}}// Loading state for check pronunciation request13 unmodified lines}}let audioBlob: Blob | null = null;if (this.recordedBlobs && this.recordedBlobs.length > 0) {const inferredType = this.recordedBlobs[0]?.type || 'audio/webm';audioBlob = new Blob(this.recordedBlobs, { type: inferredType });} else if (this.audioBlobUrl) {try {const resp = await fetch(this.audioBlobUrl);audioBlob = await resp.blob();29 unmodified linesform.append('audio', audioBlob, filename);form.append('word', this.word);// ensure mode normalized and appendedconst modeToSend = (this.pronMode ?? 'phonetics').toString().trim().toLowerCase();form.append('mode', modeToSend);// optional: include reference fileif (this.selectedFile) {form.append('reference', this.selectedFile);}// Debug: log mode and FormData entries (inspect network panel to confirm)console.log('[Pronunciation] sending check_pronunciation', { word: this.word, mode: modeToSend });try {// enumerate FormData entries for verificationfor (const [k, v] of (form as any).entries()) {// for files, log name and sizeif (v instanceof File) {console.log(' FormData entry:', k, 'File name=', v.name, 'size=', v.size);} else {console.log(' FormData entry:', k, v);}}} catch (e) {console.warn('Could not enumerate FormData entries for logging', e);}try {const res = await this.http.post<any>(`${this.backendURL}/pron/check_pronunciation`, form).toPromise();// Waveform mode response handlingif (res?.mode === 'waveform' || typeof res?.waveform_similarity !== 'undefined') {const sim = Number(res.waveform_similarity ?? 0);const matched = Boolean(res.waveform_match);// Put similarity on your speakometer / needlethis.result = {score: Math.round(sim),suggestion: matched ? 'Audio matches teacher' : 'Audio does not match teacher',feedbackAudioUrl: undefined,phonemeScore: sim,acousticScore: undefined};// Show simple structured feedbackthis.suggestions = [{id: 1,title: 'Waveform Match',message: `Similarity: ${sim}% — Matched: ${matched ? 'Yes' : 'No'}`}];// If backend returned teacher audio path, load it into WaveSurfer; otherwise request teacher audio and loadif (this.pronMode === 'waveform') {// load student into wavesurferif (this.recordedBlobUrl && this.studentWaveSurfer) {try { this.studentWaveSurfer.load(this.recordedBlobUrl); } catch { /* ignore */ }}// prefer backend-provided teacher url if presentif (res.teacher_audio_url) {const teacherUrl = res.teacher_audio_url.startsWith('http') ? res.teacher_audio_url : `${this.backendURL}/${res.teacher_audio_url}`;this.teacherAudioCache.set(this.word, teacherUrl);if (this.teacherWaveSurfer) {try { this.teacherWaveSurfer.load(teacherUrl); } catch { /* ignore */ }}} else {// otherwise try cached or request generationconst cached = this.teacherAudioCache.get(this.word);if (cached && this.teacherWaveSurfer) {try { this.teacherWaveSurfer.load(cached); } catch { /* ignore */ }} else {// call API to get teacher URL (generate_teacher_audio returns url)this.api.generateTeacherAudio(this.word, this.selectedFile).subscribe({next: ({ audioUrl }) => {this.teacherAudioCache.set(this.word, audioUrl);if (this.teacherWaveSurfer) {try { this.teacherWaveSurfer.load(audioUrl); } catch { /* ignore */ }}},error: () => { /* ignore */ }});}}}this.suggestionPage = 0;this.isChecking = false;this.cdr.detectChanges();return;}// If frontend is in "select" mode do NOT bind score or suggestion — only populate suggestions returned by backend.const isSelectMode = modeToSend === 'select' || this.pronMode === 'select';if (isSelectMode) {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 = [];}// Do not set this.result.score or this.result.suggestion for select modethis.suggestionPage = 0;this.isChecking = false;this.cdr.detectChanges();return;}// --- existing phoneme/ASR handling (unchanged) ---const phonemeSimilarity = Number(res?.phoneme_similarity ?? res?.phonemeSimilarity ?? 0);const phonemePct = Math.round(Math.max(0, Math.min(1, phonemeSimilarity)) * 100);const acousticScore = Number(res?.acoustic_score ?? res?.score ?? res?.score_acoustic ?? 0);this.result = {score: phonemePct,suggestion: (typeof res?.suggestion === 'string') ? res.suggestion : '',2 unmodified linesacousticScore: isNaN(acousticScore) ? undefined : acousticScore};// existing suggestion building...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));13 unmodified lines} else {this.suggestions = [];}this.suggestionPage = 0;} catch (err) {46 unmodified linesngOnDestroy(): void {this.stopTeacherPlayback();this.stopRecordedPlayback();this.destroyWaveSurfers();if (this.micStream) {try { this.micStream.getTracks().forEach(t => t.stop()); } catch { }this.micStream = undefined;15 unmodified linesrequestTeacherAudio() {const cached = this.teacherAudioCache.get(this.word);if (cached) {// if in waveform mode, load into wavesurfer instead of creating new audioif (this.pronMode === 'waveform' && this.teacherWaveSurfer) {try { this.teacherWaveSurfer.load(cached); this.teacherWaveSurfer.once('ready', () => this.teacherWaveSurfer.play()); } catch { /* ignore */ }return;}const a = new Audio(cached);a.play().catch(err => console.warn('play failed', err));return;2 unmodified linesthis.api.generateTeacherAudio(this.word, this.selectedFile).subscribe({next: ({ audioUrl }) => {this.teacherAudioCache.set(this.word, audioUrl);if (this.pronMode === 'waveform' && this.teacherWaveSurfer) {try { this.teacherWaveSurfer.load(audioUrl); this.teacherWaveSurfer.once('ready', () => this.teacherWaveSurfer.play()); } catch { /* ignore */ }} else {const a = new Audio(audioUrl);a.play().catch(err => console.warn('play failed', err));}},error: err => {console.error('generateTeacherAudio failed', err);43 unmodified linesthis.audioBlobUrl = URL.createObjectURL(audioBlob);this.recordedBlobUrl = this.audioBlobUrl;// If in waveform mode, load the student waveform for immediate playback/visualizationif (this.pronMode === 'waveform' && this.studentWaveSurfer) {try { this.studentWaveSurfer.load(this.recordedBlobUrl); } catch { /* ignore */ }}try { if (this.micStream) this.micStream.getTracks().forEach((t: any) => t.stop()); } catch { }this.micStream = undefined;117 unmodified linesthis.phonetics = q.phonetics ?? '';this.imgsrc = q.imgsrc ?? this.imgsrc;// If in waveform mode and teacher audio cached, load it for the new wordif (this.pronMode === 'waveform' && this.teacherWaveSurfer) {const cached = this.teacherAudioCache.get(this.word);if (cached) {try { this.teacherWaveSurfer.load(cached); } catch { /* ignore */ }}}this.cdr.detectChanges();}}
17 unmodified lines181920212223242526272829303132333435363738394041424344454647484950511 unmodified line5354555657585960616263646566676869707172737475767778798081821 unmodified line8485868788899091929394959697989910010110217 unmodified linesconstructor(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)1 unmodified linegenerateTeacherAudioStream(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 responsereturn 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 Blob1 unmodified linegenerateTeacherAudioBlob(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 /pronconst audioUrl = `${this.pronBase}/${res.audio_url}`;17 unmodified lines181920212223242526272829303132333435363738394041421 unmodified line444546474849505152535455565758596061621 unmodified line646566676869707172737417 unmodified linesconstructor(private http: HttpClient) { }generateTeacherAudio(word: string, reference?: File): Observable<{ audioUrl: string }> {const url = `${this.pronBase}/generate_teacher_audio`;// Always send FormData so Flask can read request.form (and accept optional reference file).const form = new FormData();form.append('word', word);if (reference) {form.append('reference', reference, reference.name);}return this.http.post<any>(url, form).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)1 unmodified linegenerateTeacherAudioStream(word: string, reference?: File): Observable<Blob> {const streamUrl = `${this.pronBase}/generate_teacher_audio_stream`;const form = new FormData();form.append('word', word);if (reference) form.append('reference', reference, reference.name);// Request blob response. Using 'blob' as 'json' keeps TS happy with HttpClient overloads.return this.http.post(streamUrl, form, { 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 Blob1 unmodified linegenerateTeacherAudioBlob(word: string, reference?: File): Observable<{ audioUrl: string; blob: Blob }> {const postUrl = `${this.pronBase}/generate_teacher_audio`;const form = new FormData();form.append('word', word);if (reference) form.append('reference', reference, reference.name);return this.http.post<any>(postUrl, form).pipe(switchMap((res: any) => {// backend returns e.g. "audio/teacher-xxxx.wav" — build full URL under /pronconst audioUrl = `${this.pronBase}/${res.audio_url}`;
123version https://git-lfs.github.com/spec/v1oid sha256:36b263be26c27afa3d24960fc53ce9d6b5363714dda95e22b230ce8eb8c607c9size 12408123version https://git-lfs.github.com/spec/v1oid sha256:e04526715ad4a8ec31f85eed6db1c377bf669e00a9bd2d551d19daec5460418fsize 10392123version https://git-lfs.github.com/spec/v1oid sha256:f28d8a06857382b8e7cd0b51712696ecb17d9fcdfd2a6928afb7b199b081e23esize 12912123version https://git-lfs.github.com/spec/v1oid sha256:988790d50de59b4422a425aa3ee3bc0b38e5e03ec14354d525a57cd313f6a23asize 11184123version https://git-lfs.github.com/spec/v1oid sha256:f50aecc9e38956f68572510ee93c00223f4a3f684125b4580635f13963ebaa8fsize 9936123version https://git-lfs.github.com/spec/v1oid sha256:2bb0887b2bc028a2d454e6bd9bf4f3c80a5dc6bccfd9ea1417b3693f3424da24size 9456123version https://git-lfs.github.com/spec/v1oid sha256:fa8a75e85c457f948c0b810c16665667c99c095c71224c267f222b5dceabdb2fsize 13008123version https://git-lfs.github.com/spec/v1oid sha256:a2a6e1d6d94fdbfdf3615e352715c652d72bc104fa3ff5ce7eb20b987b1a5468size 10800123version https://git-lfs.github.com/spec/v1oid sha256:33cf0de8e2225a9eddfc0083c9a50e1f3ad5cf78a1b937d04694a250ed62ac83size 14784123version https://git-lfs.github.com/spec/v1oid sha256:1cbb5f8dcc21cc4c78a3e2c61a6bb1a8f16eb2ed6e656a2b5b5c606a577d68cfsize 12432123version https://git-lfs.github.com/spec/v1oid sha256:7a1f086fbe0b46c4281d49cfdc4497259322f37c35aebee88e7ecba8bc507d47size 12216123version https://git-lfs.github.com/spec/v1oid sha256:97e8dfeb933de825ddccb7ab23616f0544fb1bf13dfbe7174d79dcd5769c3493size 14112123version https://git-lfs.github.com/spec/v1oid sha256:08b408ab5d8d19c22a4ff80da95e954553473ace618347e67a65525a1296743dsize 11016123version https://git-lfs.github.com/spec/v1oid sha256:1a6d84024ed543fc47619bce66d258cc9d89ed86d0960c6b02b3ff984947d2cfsize 11376123version https://git-lfs.github.com/spec/v1oid sha256:28e970be8938cdae9ba382519ad8df8f59006474ae0dccc3a1026537b6916f6asize 15408123version https://git-lfs.github.com/spec/v1oid sha256:b73eb1b22b1e2615a6336c813a974ddc71e6e9e047453a92b5ab7c1714318007size 9504123version https://git-lfs.github.com/spec/v1oid sha256:f822d6e09e355dd10e6ec9a86567da8c8865a4e9207711dc6c6f91fe73a0fae4size 11568123version https://git-lfs.github.com/spec/v1oid sha256:5fce73c31d372c8e310bc5d3e47bb973b203410a3b599bb6322ecdf2fd096672size 10776123version https://git-lfs.github.com/spec/v1oid sha256:b4e405e94eb7a7a9ce89b7b69fca109ccceac1b41c01fc165d882a8a9f1e7a8esize 11904123version https://git-lfs.github.com/spec/v1oid sha256:9159be7faa03940ac783d589827efbf9666d3daf15e67a5953b7af8db2ac9703size 13008123version https://git-lfs.github.com/spec/v1oid sha256:ec6c59c06372515022b65731f2f22804b469d342e8d477d1b7c13a030ec33650size 14472package.json+1
src/app/pronunciation/pronunciation.component.css+66-3
src/app/pronunciation/pronunciation.component.html+39-16
src/app/pronunciation/pronunciation.component.ts+274-17
src/app/pronunciation/pronunciation.service.ts+30-58
src/assets/audio/apple.mp3Added+3
src/assets/audio/ball.mp3Added+3
src/assets/audio/cat.mp3Added+3
src/assets/audio/dog.mp3Added+3
src/assets/audio/egg.mp3Added+3
src/assets/audio/fish.mp3Added+3
src/assets/audio/grapes.mp3Added+3
src/assets/audio/hat.mp3Added+3
src/assets/audio/ice_cream.mp3Added+3
src/assets/audio/jar.mp3Added+3
src/assets/audio/kite.mp3Added+3
src/assets/audio/lion.mp3Added+3
src/assets/audio/moon.mp3Added+3
src/assets/audio/nest.mp3Added+3
src/assets/audio/orange.mp3Added+3
src/assets/audio/original/ball.m4aDeleted
src/assets/audio/original/cat.m4aDeleted
src/assets/audio/original/dog.m4aDeleted
src/assets/audio/original/egg.m4aDeleted
src/assets/audio/original/fish.m4aDeleted
src/assets/audio/original/grapes.m4aDeleted
src/assets/audio/original/hat.m4aDeleted
src/assets/audio/original/ice_cream.m4aDeleted
src/assets/audio/original/jar.m4aDeleted
src/assets/audio/original/kite.m4aDeleted
src/assets/audio/original/lion.m4aDeleted
src/assets/audio/original/moon.m4aDeleted
src/assets/audio/original/nest.m4aDeleted
src/assets/audio/original/orange.m4aDeleted
src/assets/audio/original/pig.m4aDeleted
src/assets/audio/original/queen.m4aDeleted
src/assets/audio/original/rabbit.m4aDeleted
src/assets/audio/original/sun.m4aDeleted
src/assets/audio/original/tree.m4aDeleted
src/assets/audio/original/van.m4aDeleted
src/assets/audio/original/watch.m4aDeleted
src/assets/audio/original/xylophone.m4aDeleted
src/assets/audio/original/yarn.m4aDeleted
src/assets/audio/original/zebra.m4aDeleted
src/assets/audio/pig.mp3Added+3
src/assets/audio/queen.mp3Added+3
src/assets/audio/rabbit.mp3Added+3
src/assets/audio/sun.mp3Added+3
src/assets/audio/tree.mp3Added+3
src/assets/audio/umbrella.mp3Added+3