Oviya commited on
Commit ·
b366f52
1
Parent(s): e5dcd83
fix
Browse filesFiles changed (4)
123456715 unmodified lines2324252627282930313233343536373839404142434445import { Component } from '@angular/core';import { AuthService } from './auth.service';import { Router } from '@angular/router';@Component({selector: 'app-auth',templateUrl: './auth.component.html',15 unmodified lineslogin(): void {this.authService.login(this.username, this.password).subscribe((response) => {console.log('✅ Login success. Redirecting to /home...');this.authService.setLoggedIn(true);this.authService.startAutoRefresh();/*this.router.navigate(['/home']); // Redirect to dashboard after login*/// 🔁 Redirect to stored URL or default to /homeconst redirectUrl = localStorage.getItem('redirectAfterLogin') || '/home';localStorage.removeItem('redirectAfterLogin');this.router.navigate([redirectUrl]);},(error) => {this.errorMessage = 'Invalid username or password';});}// ✅ Check if user is logged inisLoggedIn(): boolean {123456715 unmodified lines23242526272829303132333435363738394041424344454647484950515253545556575859606162import { Component } from '@angular/core';import { AuthService } from './auth.service';import { Router } from '@angular/router';type GradeLevel = 'lowergrade' | 'midgrade' | 'highergrade';@Component({selector: 'app-auth',templateUrl: './auth.component.html',15 unmodified lineslogin(): void {this.authService.login(this.username, this.password).subscribe((response) => {// 1) Prefer grade coming from backend if it existslet level = this.normalizeGrade((response?.gradeLevel ?? response?.grade ?? response?.role ?? ''));// 2) Otherwise derive it from the USERNAME exactly as you requestedif (!level) level = this.normalizeGrade(this.username);// 3) Persist for ApiService -> sets X-User per requestif (!level) level = 'highergrade'; // final fallback (optional)localStorage.setItem('gradeLevel', level);// 4) Proceed as beforethis.authService.setLoggedIn(true);this.authService.startAutoRefresh();const redirectUrl = localStorage.getItem('redirectAfterLogin') || '/home';localStorage.removeItem('redirectAfterLogin');this.router.navigate([redirectUrl]);},() => {this.errorMessage = 'Invalid username or password';});}private normalizeGrade(v: string): GradeLevel | '' {const s = (v || '').trim().toLowerCase();if (s === 'lowergrade' || s === 'lower' || s === 'low' || s === 'l') return 'lowergrade';if (s === 'midgrade' || s === 'mid' || s === 'm') return 'midgrade';if (s === 'highergrade' || s === 'higher' || s === 'high' || s === 'h') return 'highergrade';return '';}// ✅ Check if user is logged inisLoggedIn(): boolean {
123456789101112131415161718192021222324252627282930313233import { Injectable } from '@angular/core';import { HttpClient, HttpHeaders } from '@angular/common/http';import { Observable } from 'rxjs';@Injectable({providedIn: 'root'})export class ApiService {private baseUrl = location.hostname.endsWith('hf.space')? 'https://pykara-py-learn-backend.hf.space/media': 'http://localhost:5000/media';//private baseUrl = 'http://localhost:5012';//private apiUrl = 'http://localhost:5012/explain-grammar';constructor(private http: HttpClient) { }askQuestion(userInput: string, sessionId: string | null): Observable<any> {const headers = { 'Content-Type': 'application/json' };const data = sessionId ? { topic: userInput, session_id: sessionId } : { topic: userInput };return this.http.post<any>(`${this.baseUrl}/explain-grammar`, data, { headers });}getGrammarSuggestions(input: string): Observable<any> {const headers = { 'Content-Type': 'application/json' };return this.http.post<any>(`${this.baseUrl}/suggest-grammar-questions`, { input }, { headers });}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import { Injectable } from '@angular/core';import { HttpClient, HttpHeaders } from '@angular/common/http';import { Observable } from 'rxjs';type Grade = 'lowergrade' | 'midgrade' | 'highergrade';type DbLevel = 'low' | 'mid' | 'high';function resolveBaseUrl(): string {const isHF = location.hostname.endsWith('hf.space');if (isHF) return 'https://pykara-py-learn-backend.hf.space/rag';if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') {return 'http://localhost:5000/rag';}return '/rag';}@Injectable({ providedIn: 'root' })export class ApiService {private baseUrl = resolveBaseUrl();// ---- NEW: grade/db-level helpers ----private getGrade(): Grade {const g = (localStorage.getItem('gradeLevel') || 'highergrade').toLowerCase();if (g === 'lowergrade' || g === 'midgrade' || g === 'highergrade') return g as Grade;return 'highergrade';}private toDbLevel(g: Grade): DbLevel {return g === 'lowergrade' ? 'low' : g === 'midgrade' ? 'mid' : 'high';}private makeHeaders(g: Grade): HttpHeaders {return new HttpHeaders({'Content-Type': 'application/json','X-User': g, // this is what your Postman test sets});}// -------------------------------------constructor(private http: HttpClient) { }generateOpenQuestions(payload: { qtype: 'OPEN'; n?: number; topic?: string }): Observable<any> {const grade = this.getGrade();const headers = this.makeHeaders(grade);const body = {qtype: 'OPEN',n: payload.n ?? 5,topic: payload.topic ?? '',model: 'gpt-4o-mini',db_level: this.toDbLevel(grade) // also tell the backend in the body};return this.http.post<any>(`${this.baseUrl}/generate-questions`, body, { headers });}explainGrammar(question: string): Observable<any> {const grade = this.getGrade();const headers = this.makeHeaders(grade);const body = {question,model: 'gpt-4o-mini',db_level: this.toDbLevel(grade)};return this.http.post<any>(`${this.baseUrl}/explain-grammar`, body, { headers });}suggestFollowups(payload: { last_question: string; last_answer: string; n?: number }): Observable<any> {const grade = this.getGrade();const headers = this.makeHeaders(grade);const body = {last_question: payload.last_question,last_answer: payload.last_answer,n: payload.n ?? 5,model: 'gpt-4o-mini',db_level: this.toDbLevel(grade)};return this.http.post<any>(`${this.baseUrl}/suggest-followups`, body, { headers });}// Back-compataskQuestion(userInput: string, _sessionId: string | null): Observable<any> {return this.explainGrammar(userInput);}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899<div class="chat-container"><header class="header-container"><div class="logo"><a (click)="goToHome()" routerLink="/home" class="brand-link"><img src="assets/images/pykara-logo.png" alt="Pykara Logo" /></a><span class="product-name">Py-Learn</span></div><div class="header-title"><h1>Grammar Chat</h1></div><div class="home-btn"><a (click)="goToHome()" routerLink="/home"><img src="assets/images/home.png" alt="Home" class="home-icon" /></a></div></header><main class="chat-box" #chatBox><img src="assets/images/chat/chatbg.png" alt="Chat Background" class="chat-bg" /><ng-container *ngFor="let message of messages"><div *ngIf="message.from === 'user'" class="message-wrapper user"><div class="profile-pic"><img src="assets/images/chat/rabbit.png" alt="User Profile Picture" /></div><div class="message">{{ message.text }}<div class="message-timestamp">{{ message.timestamp }}</div></div></div><div *ngIf="message.from === 'ai'" class="message-wrapper ai"><div class="profile-pic"><img src="assets/images/chat/lion.png" alt="AI Profile Picture" /></div><div class="message structured-response"><div [innerHTML]="formatStructuredResponse(message.text)"></div><div class="message-timestamp">{{ message.timestamp }}</div></div></div></ng-container><div *ngIf="isTyping" class="typing-indicator" role="status" aria-live="polite">AI is typing<span></span><span></span><span></span></div></main><section class="input-container"><div class="input-box"><textarea [(ngModel)]="userInput"(focus)="showHardcodedQuestions()"(blur)="hideHardcodedQuestions()"(input)="adjustTextareaHeight($event); getSuggestions()"(keydown)="handleEnterPress($event)"placeholder="Type your message here..."[disabled]="isSpeaking"aria-label="Message input"></textarea><button (click)="isSpeaking ? stopSpeaking() : handleButtonClick()"[disabled]="isSubmitting"aria-label="Send or voice"><img [src]="isSpeaking ? 'assets/images/chat/stop.png' : getButtonIcon()"alt="Action"class="button-icon" /></button></div><div class="hardcoded-questions-container" *ngIf="showQuestions"><div class="hardcoded-question" (click)="selectHardcodedQuestion('What is grammar?')">What is grammar?</div><div class="hardcoded-question" (click)="selectHardcodedQuestion('What are the rules to be followed in grammar?')">What are the rules to be followed in grammar?</div><div class="hardcoded-question" (click)="selectHardcodedQuestion('What are the types of tenses?')">What are the types of tenses?</div><div class="hardcoded-question" (click)="selectHardcodedQuestion('Why do we need to follow grammar rules while writing and speaking?')">Why do we need to follow grammar rules while writing and speaking?</div><div class="hardcoded-question" (click)="selectHardcodedQuestion('How do you identify a subject and a predicate in a sentence?')">How do you identify a subject and a predicate in a sentence?</div></div></section><div class="listening-box" *ngIf="isListening" role="dialog" aria-modal="true"><div class="listening-content"><img src="assets/images/chat/microphone-icon.png" alt="Microphone" class="microphone-image" /><p *ngIf="!errorMessage">Listening...</p><div class="listening-actions"><button class="mute-btn" (click)="muteMicrophone()"><img src="assets/images/chat/mic.png" alt="Mute" /></button><button class="close-btn" (click)="stopListening()"><img src="assets/images/chat/cross.png" alt="Close" /></button></div><p *ngIf="errorMessage" class="error-text" (click)="openMicrophoneSettings()">{{ errorMessage }}</p></div></div><div class="popup-overlay" *ngIf="showMicPopup"><div class="popup-box"><h3>Microphone access required</h3><p>To use voice mode, you'll need to enable your microphone and try again.</p><button class="popup-button" (click)="closeMicrophonePopup()">OK</button></div></div></div>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120<div class="chat-container"><header class="header-container"><div class="logo"><a (click)="goToHome()" routerLink="/home" class="brand-link"><img src="assets/images/pykara-logo.png" alt="Pykara Logo" /></a><span class="product-name">Py-Learn</span></div><div class="header-title"><h1>Grammar Chat</h1></div><div class="home-btn"><a (click)="goToHome()" routerLink="/home"><img src="assets/images/home.png" alt="Home" class="home-icon" /></a></div></header><main class="chat-box" #chatBox><img src="assets/images/chat/chatbg.png" alt="Chat Background" class="chat-bg" /><ng-container *ngFor="let message of messages"><div *ngIf="message.from === 'user'" class="message-wrapper user"><div class="profile-pic"><img src="assets/images/chat/rabbit.png" alt="User Profile Picture" /></div><div class="message">{{ message.text }}<div class="message-timestamp">{{ message.timestamp }}</div></div></div><div *ngIf="message.from === 'ai'" class="message-wrapper ai"><div class="profile-pic"><img src="assets/images/chat/lion.png" alt="AI Profile Picture" /></div><div class="message structured-response"><div [innerHTML]="formatStructuredResponse(message.text)"></div><div class="sources" *ngIf="message.source_ids?.length"><span class="sources-label">Sources:</span><span class="source-chip" *ngFor="let s of message.source_ids">{{ displaySource(s) }}</span></div><div class="message-timestamp">{{ message.timestamp }}</div></div></div></ng-container><div *ngIf="isTyping" class="typing-indicator" role="status" aria-live="polite">AI is typing<span></span><span></span><span></span></div></main><section class="input-container"><div class="input-box"><textarea [(ngModel)]="userInput"(focus)="showHardcodedQuestions()"(blur)="hideHardcodedQuestions()"(input)="adjustTextareaHeight($event); getSuggestions()"(keydown)="handleEnterPress($event)"placeholder="Type your message here..."[disabled]="isSpeaking"aria-label="Message input"></textarea><button (click)="isSpeaking ? stopSpeaking() : handleButtonClick()"[disabled]="isSubmitting"aria-label="Send or voice"><img [src]="isSpeaking ? 'assets/images/chat/stop.png' : getButtonIcon()"alt="Action"class="button-icon" /></button></div><div class="hardcoded-questions-container" *ngIf="showQuestions"><!-- Loading --><div class="hardcoded-question" *ngIf="pdfLoading">Loading questions…</div><!-- Generated questions list --><div class="hardcoded-question"*ngFor="let q of pdfQuestions; let i = index"(click)="selectGeneratedQuestion(q)"role="button"tabindex="0"(keydown.enter)="selectGeneratedQuestion(q)"aria-label="Suggested question">{{ q }}</div><!-- Empty state --><div class="hardcoded-question" *ngIf="!pdfLoading && !pdfQuestions.length">No questions available from the textbook.</div></div></section><div class="listening-box" *ngIf="isListening" role="dialog" aria-modal="true"><div class="listening-content"><img src="assets/images/chat/microphone-icon.png" alt="Microphone" class="microphone-image" /><p *ngIf="!errorMessage">Listening...</p><div class="listening-actions"><button class="mute-btn" (click)="muteMicrophone()"><img src="assets/images/chat/mic.png" alt="Mute" /></button><button class="close-btn" (click)="stopListening()"><img src="assets/images/chat/cross.png" alt="Close" /></button></div><p *ngIf="errorMessage" class="error-text" (click)="openMicrophoneSettings()">{{ errorMessage }}</p></div></div><div class="popup-overlay" *ngIf="showMicPopup"><div class="popup-box"><h3>Microphone access required</h3><p>To use voice mode, you'll need to enable your microphone and try again.</p><button class="popup-button" (click)="closeMicrophonePopup()">OK</button></div></div></div>
6 unmodified lines789101112133 unmodified lines17181920212223242526273 unmodified lines313233343536373839404142434445464748495051525354551 unmodified line5758596061629 unmodified lines727374757677785 unmodified lines848586878889909192939495969798991001012 unmodified lines1041051061071081091101111121131141151161171181191201211223 unmodified lines1261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611622 unmodified lines1651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532547 unmodified lines2622632642652662672682692702712722732742752762772782 unmodified lines2812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173181 unmodified line3203213223233243253263273283293303313323333343353363373383393403413423433443453462 unmodified lines3493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114 unmodified lines4164174184194204214221 unmodified line4244254264274284294304314324334344 unmodified lines4394404414424434444454464474485 unmodified lines45445545645745845946046146246346446546646746846947047147247347447547647747847948048148248312 unmodified lines4964974984995005015025035045055065075085095109 unmodified lines5205215225235245255265275285295305315325335345355365375385395405415425435445455465472 unmodified lines5505515525535545555565575585595605615625635645655665675685695705715725735745755765775786 unmodified linesimport { ViewChild, ElementRef } from '@angular/core';import { Renderer2 } from '@angular/core';import { Subscription } from 'rxjs';@Component({selector: 'app-chat',standalone: true,3 unmodified lines})export class ChatComponent implements OnDestroy {showQuestions: boolean = false;userInput: string = '';messages: { from: string, text: string, timestamp: string; isPlaying?: boolean }[] = [];isTyping: boolean = false;@ViewChild('chatBox') chatBox!: ElementRef;isLoadingSpeech: boolean = false;selectedVoice: SpeechSynthesisVoice | null = null;errorMessage: string = "";3 unmodified linesisProcessingSpeech: boolean = false;isSpeaking: boolean = false;isAudioPaused: boolean = false;isInputValid: boolean = false;suggestions: string[] = [];showMicPopup: boolean = false;isSubmitting: boolean = false;private responseSub?: Subscription;private lastFullAiText: string = '';ngAfterViewChecked() {setTimeout(() => {this.scrollToBottom();}, 100);}private scrollToBottom(): void {try {this.chatBox.nativeElement.scrollTop = this.chatBox.nativeElement.scrollHeight;} catch (err) { }}constructor(private apiService: ApiService,private cdr: ChangeDetectorRef,1 unmodified lineprivate router: Router,private renderer: Renderer2) {window.speechSynthesis.onvoiceschanged = () => {console.log("Available Voices:", window.speechSynthesis.getVoices());};9 unmodified linesthis.recognition.onresult = (event: any) => {if (event.results && event.results[0]) {const transcript = event.results[0][0].transcript.trim();console.log('Recognized speech:', transcript);this.userInput = transcript;this.sendMessage();this.recognition.stop();5 unmodified linesconsole.error('Speech Recognition Error:', event.error);this.isProcessingSpeech = false;};} else {console.warn('Speech Recognition is not supported in this browser.');}window.addEventListener('beforeunload', this.handleUnload);}}private handleUnload = (): void => {if (window.speechSynthesis) {window.speechSynthesis.cancel();}};ngOnDestroy(): void {if (isPlatformBrowser(this.platformId)) {2 unmodified lines}window.removeEventListener('beforeunload', this.handleUnload);}}openMicrophonePopup(): void {this.showMicPopup = true;}closeMicrophonePopup(): void {this.showMicPopup = false;}showHardcodedQuestions(): void {setTimeout(() => {this.showQuestions = true;}, 100);}3 unmodified lines}, 200);}selectHardcodedQuestion(question: string): void {this.userInput = question;this.showQuestions = false;setTimeout(() => {this.sendMessage();this.userInput = '';}, 100);}getSuggestions(): void {if (!this.userInput || this.userInput.trim().length < 1 || this.isSpeaking) {this.suggestions = [];return;}this.apiService.getGrammarSuggestions(this.userInput).subscribe((response) => {console.log("API Response:", response);if (response.suggestions) {this.suggestions = response.suggestions.filter((s: string) => s && s.trim().length > 0).map((s: string) => s.replace(/^\d+\.\s*/, ""));} else {this.suggestions = [];}},(error) => {console.error("Error fetching suggestions:", error);this.suggestions = [];});}selectSuggestion(suggestion: string): void {2 unmodified linesthis.sendMessage();}sendMessage(inputText?: string): void {const message = inputText ? inputText.trim() : this.userInput.trim();if (!message) {return;}let sessionId = localStorage.getItem('session_id');this.messages.push({ from: 'user', text: message, timestamp: new Date().toLocaleTimeString() });this.userInput = '';this.isTyping = true;this.cdr.detectChanges();this.scrollToBottom();this.responseSub = this.apiService.askQuestion(message, sessionId).subscribe((response) => {this.isTyping = false;const explanation = (response?.response || 'No explanation available.').trim();if (response.session_id && !sessionId) {localStorage.setItem('session_id', response.session_id);}const lines: string[] = String(explanation).split('\n');const formatted: string = lines.map((line: string) => line.trim()).join('\n');this.messages.push({from: 'ai',text: formatted,timestamp: new Date().toLocaleTimeString(),});this.cdr.detectChanges();this.scrollToBottom();this.lastFullAiText = formatted;this.speakResponse(explanation);},(error) => {this.isTyping = false;const errorMessage = 'Error: Could not get a response from the server.';console.error('API Error:', error);this.messages.push({from: 'ai',text: errorMessage,timestamp: new Date().toLocaleTimeString(),});this.cdr.detectChanges();this.scrollToBottom();this.lastFullAiText = errorMessage;this.speakResponse(errorMessage);});}formatStructuredResponse(text: string): string {let formattedText = text.replace(/\n/g, '<br>').replace(/(\d+)\.\s/g, '<b>$1.</b> ').replace(/\•\s/g, '✔️ ').replace(/\-\s/g, '🔹 ').replace(/(\*\*)(.*?)\1/g, '<b>$2</b>');return formattedText;}speakResponse(responseText: string): void {if (!responseText) {console.warn('No response text provided for speech.');return;}console.log('Initiating text-to-speech with response:', responseText);let lastAiMessage = this.messages.slice().reverse().find((msg) => msg.from === 'ai');if (!lastAiMessage) {lastAiMessage = { from: 'ai', text: '', timestamp: new Date().toLocaleTimeString() };this.messages.push(lastAiMessage);} else {lastAiMessage.text = '';}this.cdr.detectChanges();const words = responseText.split(' ');7 unmodified linesthis.isSpeaking = true;const voices = window.speechSynthesis.getVoices();let femaleVoice = voices.find(voice => voice.name === "Microsoft Zira - English (United States)");if (femaleVoice) {speech.voice = femaleVoice;console.log("Using voice:", femaleVoice.name);} else {console.warn("Microsoft Zira not found, using default.");}speech.onboundary = (event) => {if (event.name === 'word' && currentWordIndex < words.length) {lastAiMessage!.text = words.slice(0, currentWordIndex + 1).join(' ');currentWordIndex++;2 unmodified lines};speech.onend = () => {console.log('Speech ended.');this.isSpeaking = false;lastAiMessage!.text = responseText;this.cdr.detectChanges();};console.log('Starting speech synthesis...');window.speechSynthesis.speak(speech);}ngOnInit(): void {if (window.speechSynthesis.onvoiceschanged !== undefined) {window.speechSynthesis.onvoiceschanged = () => {this.loadVoices();};}this.loadVoices();}loadVoices(): void {const voices = window.speechSynthesis.getVoices();if (!voices.length) {console.warn("No voices available yet, retrying...");setTimeout(() => this.loadVoices(), 500);return;}console.log("Available Voices:", voices.map(v => v.name));const preferredVoices = ["Google UK English Female","Google US English Female","Microsoft Zira - English (United States)",1 unmodified line"Google en-GB Female","Google en-US Female"];for (let voiceName of preferredVoices) {const foundVoice = voices.find(voice => voice.name === voiceName);if (foundVoice) {this.selectedVoice = foundVoice;break;}}if (!this.selectedVoice) {this.selectedVoice = voices.find(voice => voice.name.toLowerCase().includes("female")) || voices[0];}console.log("Selected AI Voice:", this.selectedVoice?.name);}pauseAudio(): void {if (window.speechSynthesis.speaking && !window.speechSynthesis.paused) {window.speechSynthesis.pause();this.isAudioPaused = true;console.log('AI Speech Paused');this.cdr.detectChanges();}}2 unmodified linesif (window.speechSynthesis.paused) {window.speechSynthesis.resume();this.isAudioPaused = false;console.log('AI Speech Resumed');this.cdr.detectChanges();}}muteMicrophone(): void {console.log("Microphone muted");}startListening(): void {this.isListening = true;this.isProcessingSpeech = false;if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {navigator.mediaDevices.getUserMedia({ audio: true }).then(() => {if (this.recognition) {console.log('Starting speech recognition...');this.recognition.start();this.recognition.onaudiostart = () => console.log('Audio capturing started.');this.recognition.onspeechstart = () => console.log('Speech has been detected.');this.recognition.onspeechend = () => console.log('Speech ended, processing...');this.recognition.onaudioend = () => console.log('Audio capturing ended.');this.recognition.onresult = (event: any) => {if (event.results && event.results[0]) {const transcript = event.results[0][0].transcript.trim();console.log('Recognized speech:', transcript);this.userInput = transcript;if (this.userInput.trim()) {console.log('Sending question automatically:', this.userInput);this.sendMessage();}this.recognition.stop();this.isListening = false;}};this.recognition.onnomatch = () =>alert('No speech detected. Please try again.');this.recognition.onend = () => {console.log('Speech recognition service disconnected.');this.isListening = false;};this.recognition.onerror = (error: any) => {console.error('Speech Recognition Error:', error);this.isListening = false;if (error.error === 'not-allowed') {alert('Microphone permission denied.');} else if (error.error === 'no-speech') {alert('No speech detected. Please try speaking clearly.');}};} else {alert('Speech Recognition is not supported in this browser.');4 unmodified linesthis.errorMessage = 'Please enable microphone access to use this feature.';this.isListening = true;});} else {alert('Microphone access is not supported in this browser.');}1 unmodified linestopListening(): void {this.isListening = false;if (this.recognition) {this.recognition.stop();}}toggleAudio(message: { text: string, isPlaying?: boolean }): void {if (this.speechSynthesisInstance && this.speechSynthesisInstance.text === message.text) {if (message.isPlaying) {4 unmodified linesmessage.isPlaying = true;}} else {if (this.speechSynthesisInstance) {window.speechSynthesis.cancel();}this.messages.forEach((msg) => (msg.isPlaying = false));message.isPlaying = true;this.speechSynthesisInstance = new SpeechSynthesisUtterance(message.text);5 unmodified linesmessage.isPlaying = false;this.speechSynthesisInstance = null;};window.speechSynthesis.speak(this.speechSynthesisInstance);}}goToHome() {this.router.navigate(['/home']);}copySuccessIndex: number | null = null;copyToClipboard(text: string, index: number): void {navigator.clipboard.writeText(text).then(() => {this.copySuccessIndex = index;setTimeout(() => {this.copySuccessIndex = null;}, 2000);}).catch(err => {console.error('Failed to copy: ', err);});}checkInput() {this.isInputValid = this.userInput.trim().length > 0;}handleButtonClick(): void {12 unmodified lines}getButtonIcon(): string {if (this.userInput.trim().length > 0) {return 'assets/images/chat/send-icon.png';} else if (this.isSpeaking) {return 'assets/images/chat/pause-icon.png';} else if (this.isAudioPaused) {return 'assets/images/chat/resume-icon.png';} else {return 'assets/images/chat/microphone-icon.png';}}addNewLine(event: KeyboardEvent): void {9 unmodified linestextarea.style.height = `${textarea.scrollHeight}px`;}getButtonIconClass(): string {return this.userInput.trim().length > 0? 'send-icon': this.isSpeaking? 'pause-icon': this.isAudioPaused? 'resume-icon': 'microphone-icon';}openMicrophoneSettings(): void {const userAgent = navigator.userAgent;if (userAgent.includes("Chrome")) {window.open("chrome://settings/content/microphone", "_blank");} else if (userAgent.includes("Firefox")) {window.open("about:preferences#privacy", "_blank");} else if (userAgent.includes("Edge")) {window.open("edge://settings/content/microphone", "_blank");} else {alert("Please check your browser's settings to enable the microphone.");}}stopSpeaking(): void {2 unmodified lineswindow.speechSynthesis.cancel();}} catch { }(this as any).speechSynthesisInstance = null;if (this.responseSub && !this.responseSub.closed) {this.responseSub.unsubscribe();}this.isSpeaking = false;this.isAudioPaused = false;this.isTyping = false;}handleEnterPress(event: KeyboardEvent): void {if (this.isSpeaking) {event.preventDefault();return;}if (event.key === 'Enter' && !event.shiftKey) {event.preventDefault();const text = (this.userInput || '').trim();if (text) this.sendMessage();}}}6 unmodified lines78910111213143 unmodified lines1819202122232425262728293031323334353 unmodified lines394041424344454647484950515253545556575859601 unmodified line626364656667689 unmodified lines7879808182835 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231242 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611623 unmodified lines1661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452 unmodified lines2482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453467 unmodified lines3543553563573583593603613623632 unmodified lines3663673683693703713723733743753763773783793803813823833843853861 unmodified line3883893903913923933943953963973983994004014024034044054064072 unmodified lines4104114124134144154164174184194204214224234244254264274284294304314324334344354364374 unmodified lines4424434444454464471 unmodified line4494504514524534544554564574584 unmodified lines4634644654664674684694705 unmodified lines47647747847948048148248348448548648748848949049149249349412 unmodified lines5075085095105115125135145155169 unmodified lines5265275285295305315325335345355365372 unmodified lines5405415425435445455465475485495505515525535545555565575586 unmodified linesimport { ViewChild, ElementRef } from '@angular/core';import { Renderer2 } from '@angular/core';import { Subscription } from 'rxjs';import { finalize } from 'rxjs/operators';type Grade = 'lowergrade' | 'midgrade' | 'highergrade';@Component({selector: 'app-chat',standalone: true,3 unmodified lines})export class ChatComponent implements OnDestroy {showQuestions: boolean = false;isSubmitting: boolean = false;/** Generated (initial) or follow-up questions shown on focus */pdfQuestions: string[] = [];pdfLoading: boolean = false;/** Chat state */userInput: string = '';messages: { from: string, text: string, timestamp: string; isPlaying?: boolean, source_ids?: string[]; }[] = [];isTyping: boolean = false;@ViewChild('chatBox') chatBox!: ElementRef;/** Speech / mic state */isLoadingSpeech: boolean = false;selectedVoice: SpeechSynthesisVoice | null = null;errorMessage: string = "";3 unmodified linesisProcessingSpeech: boolean = false;isSpeaking: boolean = false;isAudioPaused: boolean = false;/** Suggestions for typed input (powered by PDF too) */suggestions: string[] = [];/** Popup */showMicPopup: boolean = false;/** Subscriptions */private responseSub?: Subscription;/** Store last Q/A to drive follow-ups */private lastQuestion: string | null = null;private lastAnswer: string | null = null;private lastSourceIds: string[] = [];// lowergrade | midgrade | highergradeconstructor(private apiService: ApiService,private cdr: ChangeDetectorRef,1 unmodified lineprivate router: Router,private renderer: Renderer2) {// Log voiceswindow.speechSynthesis.onvoiceschanged = () => {console.log("Available Voices:", window.speechSynthesis.getVoices());};9 unmodified linesthis.recognition.onresult = (event: any) => {if (event.results && event.results[0]) {const transcript = event.results[0][0].transcript.trim();this.userInput = transcript;this.sendMessage();this.recognition.stop();5 unmodified linesconsole.error('Speech Recognition Error:', event.error);this.isProcessingSpeech = false;};}window.addEventListener('beforeunload', this.handleUnload);}}private ensureGradeLevel(defaultGrade: Grade = 'lowergrade'): void {const g = (localStorage.getItem('gradeLevel') || '').toLowerCase();if (g !== 'lowergrade' && g !== 'midgrade' && g !== 'highergrade') {localStorage.setItem('gradeLevel', defaultGrade);console.info('[Chat] gradeLevel not set; defaulted to', defaultGrade);} else {console.info('[Chat] gradeLevel =', g);}}ngOnInit(): void {this.ensureGradeLevel();if (window.speechSynthesis.onvoiceschanged !== undefined) {window.speechSynthesis.onvoiceschanged = () => {this.loadVoices();};}this.loadVoices();}ngAfterViewChecked() {setTimeout(() => {this.scrollToBottom();}, 100);}ngOnDestroy(): void {if (isPlatformBrowser(this.platformId)) {2 unmodified lines}window.removeEventListener('beforeunload', this.handleUnload);}if (this.responseSub && !this.responseSub.closed) {this.responseSub.unsubscribe();}}private handleUnload = (): void => {if (window.speechSynthesis) {window.speechSynthesis.cancel();}};private scrollToBottom(): void {try {this.chatBox.nativeElement.scrollTop = this.chatBox.nativeElement.scrollHeight;} catch (err) { }}/** Popup controls */openMicrophonePopup(): void { this.showMicPopup = true; }closeMicrophonePopup(): void { this.showMicPopup = false; }/** Show questions on focus: initial (no answer yet) or follow-ups (after an answer) */showHardcodedQuestions(): void {setTimeout(async () => {this.showQuestions = true;if (this.lastAnswer) {this.fetchFollowupQuestions();} else {this.fetchInitialQuestions();}}, 100);}3 unmodified lines}, 200);}/** Initial questions generated from PDFs (topicless OPEN) */private fetchInitialQuestions(n: number = 5): void {this.pdfLoading = true;this.pdfQuestions = [];this.apiService.generateOpenQuestions({ qtype: 'OPEN', n, topic: '' }).subscribe({next: (resp) => {const items = Array.isArray(resp?.questions) ? resp.questions : [];this.pdfQuestions = items.map((q: any) => typeof q === 'string' ? q : (q?.question || '')).filter(Boolean);if (!this.pdfQuestions.length && resp?.note) {console.warn('Question generator note:', resp.note);}this.pdfLoading = false;this.cdr.detectChanges();},error: () => { this.pdfLoading = false; this.pdfQuestions = []; this.cdr.detectChanges(); }});}/** Follow-ups after an answer */private fetchFollowupQuestions(n: number = 5): void {if (!this.lastQuestion || !this.lastAnswer) {this.fetchInitialQuestions(n);return;}this.pdfLoading = true;this.pdfQuestions = [];this.apiService.suggestFollowups({last_question: this.lastQuestion,last_answer: this.lastAnswer,n}).subscribe({next: (resp) => {const list = Array.isArray(resp?.suggestions) ? resp.suggestions : [];this.pdfQuestions = list.filter((s: string) => !!s);this.pdfLoading = false;this.cdr.detectChanges();},error: () => {this.pdfLoading = false;this.pdfQuestions = [];this.cdr.detectChanges();}});}/** Click on one generated question */selectGeneratedQuestion(question: string): void {this.userInput = question;this.showQuestions = false;setTimeout(() => {this.sendMessage();this.userInput = '';}, 80);}/** Type-ahead suggestions sourced from PDFs (OPEN on the typed topic) */getSuggestions(): void {if (!this.userInput || this.userInput.trim().length < 1 || this.isSpeaking) {this.suggestions = [];return;}this.apiService.generateOpenQuestions({ qtype: 'OPEN', n: 5, topic: this.userInput }).subscribe({next: (resp) => {const items = Array.isArray(resp?.questions) ? resp.questions : [];this.suggestions = items.map((q: any) => (typeof q === 'string' ? q : (q?.question || ''))).filter((s: string) => !!s);},error: () => { this.suggestions = []; }});}selectSuggestion(suggestion: string): void {2 unmodified linesthis.sendMessage();}/** Send question to backend for an answer */sendMessage(inputText?: string): void {const message = inputText ? inputText.trim() : this.userInput.trim();if (!message) return;this.isSubmitting = true; // <— start submittingconst timestamp = new Date().toLocaleTimeString();this.messages.push({ from: 'user', text: message, timestamp });this.userInput = '';this.isTyping = true;this.cdr.detectChanges();this.scrollToBottom();this.responseSub = this.apiService.explainGrammar(message).pipe(finalize(() => {this.isSubmitting = false;})).subscribe({next: (response) => {this.isTyping = false;const explanation =(response?.answer || response?.response || response?.text || 'No explanation available.').trim();// NEW: collect source IDs safelyconst sourceIds: string[] = Array.isArray(response?.source_ids)? response.source_ids.filter((s: any) => typeof s === 'string' && s.trim().length > 0): [];this.messages.push({from: 'ai',text: explanation,timestamp: new Date().toLocaleTimeString(),source_ids: sourceIds});this.cdr.detectChanges();this.scrollToBottom();this.lastQuestion = message;this.lastAnswer = explanation;this.lastSourceIds = sourceIds;this.speakResponse(explanation);},error: (err) => {console.error('API Error:', err);this.isTyping = false;const errorMessage = 'Error: Could not get a response from the server.';// Use an empty array here (no undefined variable)this.messages.push({from: 'ai',text: errorMessage,timestamp: new Date().toLocaleTimeString(),source_ids: []});this.cdr.detectChanges();this.scrollToBottom();this.speakResponse(errorMessage);}});}displaySource(tag: string): string {if (!tag) return '';const [path, pagePart] = tag.split('#p');const file = path.split(/[/\\]/).pop() || path; // works for Windows/Unix pathsreturn pagePart ? `${file} p${pagePart}` : file;}/** Render helpers */formatStructuredResponse(text: string): string {return text.replace(/\n/g, '<br>').replace(/(\d+)\.\s/g, '<b>$1.</b> ').replace(/\•\s/g, '✔️ ').replace(/\-\s/g, '🔹 ').replace(/(\*\*)(.*?)\1/g, '<b>$2</b>');}/** TTS helpers */speakResponse(responseText: string): void {if (!responseText) return;let lastAiMessage = this.messages.slice().reverse().find((msg) => msg.from === 'ai');if (!lastAiMessage) {lastAiMessage = { from: 'ai', text: '', timestamp: new Date().toLocaleTimeString() };this.messages.push(lastAiMessage);} else {lastAiMessage.text = '';}this.cdr.detectChanges();const words = responseText.split(' ');7 unmodified linesthis.isSpeaking = true;const voices = window.speechSynthesis.getVoices();const femaleVoice = voices.find(v => v.name === "Microsoft Zira - English (United States)");if (femaleVoice) speech.voice = femaleVoice;speech.onboundary = (event: any) => {if (event.name === 'word' && currentWordIndex < words.length) {lastAiMessage!.text = words.slice(0, currentWordIndex + 1).join(' ');currentWordIndex++;2 unmodified lines};speech.onend = () => {this.isSpeaking = false;lastAiMessage!.text = responseText;this.cdr.detectChanges();};window.speechSynthesis.speak(speech);}loadVoices(): void {const voices = window.speechSynthesis.getVoices();if (!voices.length) {setTimeout(() => this.loadVoices(), 500);return;}const preferred = ["Google UK English Female","Google US English Female","Microsoft Zira - English (United States)",1 unmodified line"Google en-GB Female","Google en-US Female"];for (let name of preferred) {const v = voices.find(voice => voice.name === name);if (v) { this.selectedVoice = v; break; }}if (!this.selectedVoice) {this.selectedVoice = voices.find(voice => voice.name.toLowerCase().includes("female")) || voices[0];}}/** Global audio controls */pauseAudio(): void {if (window.speechSynthesis.speaking && !window.speechSynthesis.paused) {window.speechSynthesis.pause();this.isAudioPaused = true;this.cdr.detectChanges();}}2 unmodified linesif (window.speechSynthesis.paused) {window.speechSynthesis.resume();this.isAudioPaused = false;this.cdr.detectChanges();}}/** Mic controls */muteMicrophone(): void { console.log("Microphone muted"); }startListening(): void {this.isListening = true;this.isProcessingSpeech = false;if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {navigator.mediaDevices.getUserMedia({ audio: true }).then(() => {if (this.recognition) {this.recognition.start();this.recognition.onend = () => { this.isListening = false; };this.recognition.onerror = (error: any) => {console.error('Speech Recognition Error:', error);this.isListening = false;if (error.error === 'not-allowed') alert('Microphone permission denied.');else if (error.error === 'no-speech') alert('No speech detected. Please try again.');};} else {alert('Speech Recognition is not supported in this browser.');4 unmodified linesthis.errorMessage = 'Please enable microphone access to use this feature.';this.isListening = true;});} else {alert('Microphone access is not supported in this browser.');}1 unmodified linestopListening(): void {this.isListening = false;if (this.recognition) this.recognition.stop();}/** Per-message read toggle (kept from your code) */toggleAudio(message: { text: string, isPlaying?: boolean }): void {if (this.speechSynthesisInstance && this.speechSynthesisInstance.text === message.text) {if (message.isPlaying) {4 unmodified linesmessage.isPlaying = true;}} else {if (this.speechSynthesisInstance) window.speechSynthesis.cancel();this.messages.forEach((m) => (m.isPlaying = false));message.isPlaying = true;this.speechSynthesisInstance = new SpeechSynthesisUtterance(message.text);5 unmodified linesmessage.isPlaying = false;this.speechSynthesisInstance = null;};window.speechSynthesis.speak(this.speechSynthesisInstance);}}/** UI helpers */goToHome() { this.router.navigate(['/home']); }copySuccessIndex: number | null = null;copyToClipboard(text: string, index: number): void {navigator.clipboard.writeText(text).then(() => {this.copySuccessIndex = index;setTimeout(() => { this.copySuccessIndex = null; }, 2000);}).catch(err => { console.error('Failed to copy: ', err); });}handleButtonClick(): void {12 unmodified lines}getButtonIcon(): string {if (this.userInput.trim().length > 0) return 'assets/images/chat/send-icon.png';if (this.isSpeaking) return 'assets/images/chat/pause-icon.png';if (this.isAudioPaused) return 'assets/images/chat/resume-icon.png';return 'assets/images/chat/microphone-icon.png';}addNewLine(event: KeyboardEvent): void {9 unmodified linestextarea.style.height = `${textarea.scrollHeight}px`;}openMicrophoneSettings(): void {const ua = navigator.userAgent;if (ua.includes("Chrome")) window.open("chrome://settings/content/microphone", "_blank");else if (ua.includes("Firefox")) window.open("about:preferences#privacy", "_blank");else if (ua.includes("Edge")) window.open("edge://settings/content/microphone", "_blank");else alert("Please check your browser's settings to enable the microphone.");}stopSpeaking(): void {2 unmodified lineswindow.speechSynthesis.cancel();}} catch { }(this as any).speechSynthesisInstance = null;if (this.responseSub && !this.responseSub.closed) this.responseSub.unsubscribe();this.isSpeaking = false;this.isAudioPaused = false;this.isTyping = false;}handleEnterPress(event: KeyboardEvent): void {if (this.isSpeaking) { event.preventDefault(); return; }if (event.key === 'Enter' && !event.shiftKey) {event.preventDefault();const text = (this.userInput || '').trim();if (text) this.sendMessage();}}}
src/app/auth/auth.component.ts+24-7
src/app/chat/api.service.ts+67-19
src/app/chat/chat.component.html+107-86
src/app/chat/chat.component.ts+228-248