fix
Browse filesFiles changed (2)
47 unmodified lines48495051525354555657585960616247 unmodified linesreturn 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 });}// ✅ Updated to carry source_ids so follow-ups stay in the same textbook pages47 unmodified lines484950515253545556575859606162636465666747 unmodified linesreturn this.http.post<any>(`${this.baseUrl}/generate-questions`, body, { headers });}// Accept either a string (legacy) or an object { question, synthesize_audio, synthesize_video }explainGrammar(payload: string | any): Observable<any> {const grade = this.getGrade();const headers = this.makeHeaders(grade);// Normalize payload into an objectconst body = typeof payload === 'string' ? { question: payload } : { ...payload };// Ensure backend gets db_level and model so it selects the right vectorstore/LLMif (!body.db_level) body.db_level = this.toDbLevel(grade);if (!body.model) body.model = 'gpt-4o-mini';const url = `${this.baseUrl}/explain-grammar`;return this.http.post(url, body, { headers });}// ✅ Updated to carry source_ids so follow-ups stay in the same textbook pages
67 unmodified lines686970717273747576777879804 unmodified lines8586878889909142 unmodified lines134135136137138139140143 unmodified lines2842852862872882892905 unmodified lines29629729829930030130221 unmodified lines324325326327328329330233 unmodified lines5645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116123 unmodified lines6166176186196206216226236243 unmodified lines628629630631632633634635636637638639640641642643178 unmodified lines822823824825826827828149 unmodified lines97897998098198298398417 unmodified lines10021003100410051006100775 unmodified lines10831084108510861087108810891090217 unmodified lines130813091310131113121313131438 unmodified lines135313541355135613571358135992 unmodified lines145214531454145514561457145842 unmodified lines1501150215031504150515061507243 unmodified lines17511752175317541755175667 unmodified linesisSynthesizing?: boolean;isVideoSynthesizing?: boolean;}> = [];isTyping: boolean = false;@ViewChild('chatBox') chatBox!: ElementRef;/** Speech / mic state */isLoadingSpeech: boolean = false;selectedVoice: SpeechSynthesisVoice | null = null;speechSynthesisInstance: SpeechSynthesisUtterance | null = null;isListening: boolean = false;isProcessingSpeech: boolean = false;4 unmodified linessuggestions: string[] = [];isInputValid = false;/** Popup *//** Subscriptions */private responseSub?: Subscription;42 unmodified linescurrentFollowups: string[] = [];/*private shouldAutoScroll = true;*/videoUrl = '';aiResponseInterval: any = null;143 unmodified lines}}ngOnInit(): void {this.ensureGradeLevel();5 unmodified linesthis.loadVoices();}ngOnDestroy(): void {if (this.currentExplainSub) { this.currentExplainSub.unsubscribe(); this.currentExplainSub = null; }21 unmodified lines});}scrollToBottom(): void {if (this.shouldAutoScroll) {233 unmodified linesthis.shouldAutoScroll = true;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();const sourceIds: string[] = Array.isArray(response?.source_ids)? response.source_ids.filter((s: any) => typeof s === 'string' && s.trim().length > 0): [];// Store question + source ids *now*.this.lastQuestion = message;this.lastSourceIds = sourceIds;const notFound = /No information available in the provided textbook content/i.test(explanation);const hasContext = !!sourceIds.length && !notFound;// IMPORTANT:// Do NOT set this.lastAnswer here.// We will set it only after the streaming animation has finished.this.streamAiAnswer(explanation, sourceIds, hasContext);},error: (err) => {console.error('API Error:', err);this.isTyping = false;const errorMessage = 'Error: Could not get a response from the server.';// We can still stream the error text (or you can show it directly if you prefer)this.streamAiAnswer(errorMessage, [], false);}});}/** Show AI answer word-by-word and start audio *//** Show AI answer word-by-word and start audio */private streamAiAnswer(explanation: string, sourceIds: string[], hasContext: boolean): void {const text = (explanation || '').trim() || 'No explanation available.';const timestamp = new Date().toLocaleTimeString();3 unmodified linestext: '',timestamp,source_ids: sourceIds,pending: true} as any) - 1;this.isAiResponding = true;this.shouldAutoScroll = true;this.cdr.detectChanges();3 unmodified lines// When streaming is finished, we finally store lastAnswerthis.lastAnswer = text;this.lastAnswerHasContext = hasContext;});// Play audio at the same time (only if voice is enabled)this.speakResponse(text);}displaySource(tag: string): string {if (!tag) return '';178 unmodified lines}resumeAudio(): void {if (this.serverAudio && this.serverAudio.paused) {149 unmodified lines});}openMessageVideo(i: number): void {const msg = this.messages[i] as any;if (!msg?.videoUrl) return;17 unmodified linesconst vid = document.getElementById(`inline-video-${i}`) as HTMLVideoElement | null;if (!vid) { this.isVideoPlayingIndex = null; this.cdr.detectChanges(); return; }vid.onplay = () => { this.isVideoPlayingIndex = i; this.cdr.detectChanges(); };vid.onpause = () => { this.cdr.detectChanges(); };vid.onended = () => { this.onMessageVideoEnded(i); };75 unmodified lines}}stopListening(): void {this.isListening = false;217 unmodified lines}}addNewLine(event: KeyboardEvent): void {if (event.key === 'Enter' && event.shiftKey) {38 unmodified lines//if (this.serverAudio) {// try { this.serverAudio.volume = this.isMuted ? 0 : 1; } catch { /* noop */ }//}//this.saveToggleStates();}92 unmodified linesgoToHomePageShortcut(): void { this.router.navigate(['/home']); }openUserGuide(): void { this.showUserGuide = true; }closeUserGuide(): void { this.showUserGuide = false; }42 unmodified linesalert("Please check your browser's settings to enable the microphone.");}} catch (err) {console.error('openMicrophoneSettings error:', err);alert("Unable to open settings automatically. Please check your browser's microphone/privacy settings.");}this.cdr.detectChanges();243 unmodified linesanalyser.smoothingTimeConstant = 0.85;source.connect(analyser);this.analyser = analyser;const bufferLength = analyser.fftSize;this.dataArray = new Uint8Array(bufferLength);67 unmodified lines686970717273747576777879804 unmodified lines8586878889909142 unmodified lines134135136137138139140143 unmodified lines2842852862872882892905 unmodified lines29629729829930030130221 unmodified lines324325326327328329330233 unmodified lines5645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166173 unmodified lines6216226236246256266276286296306316326336346356366373 unmodified lines641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696178 unmodified lines875876877878879880881149 unmodified lines103110321033103410351036103717 unmodified lines105510561057105810591060106110621063106410651066106775 unmodified lines11431144114511461147114811491150217 unmodified lines136813691370137113721373137438 unmodified lines141314141415141614171418141992 unmodified lines151215131514151515161517151842 unmodified lines1561156215631564156515661567243 unmodified lines181118121813181418151816181767 unmodified linesisSynthesizing?: boolean;isVideoSynthesizing?: boolean;}> = [];isTyping: boolean = false;@ViewChild('chatBox') chatBox!: ElementRef;/** Speech / mic state */isLoadingSpeech: boolean = false;selectedVoice: SpeechSynthesisVoice | null = null;speechSynthesisInstance: SpeechSynthesisUtterance | null = null;isListening: boolean = false;isProcessingSpeech: boolean = false;4 unmodified linessuggestions: string[] = [];isInputValid = false;/** Popup *//** Subscriptions */private responseSub?: Subscription;42 unmodified linescurrentFollowups: string[] = [];/*private shouldAutoScroll = true;*/videoUrl = '';aiResponseInterval: any = null;143 unmodified lines}}ngOnInit(): void {this.ensureGradeLevel();5 unmodified linesthis.loadVoices();}ngOnDestroy(): void {if (this.currentExplainSub) { this.currentExplainSub.unsubscribe(); this.currentExplainSub = null; }21 unmodified lines});}scrollToBottom(): void {if (this.shouldAutoScroll) {233 unmodified linesthis.shouldAutoScroll = true;this.scrollToBottom();this.responseSub = this.apiService.explainGrammar({question: message,// ask backend to synthesize audio/video only when user toggles are ONsynthesize_audio: Boolean(this.isVoiceEnabled),synthesize_video: Boolean(this.isTutorEnabled)}).pipe(finalize(() => {this.isSubmitting = false;})).subscribe({next: (response) => {this.isTyping = false;const explanation =(response?.answer || response?.response || response?.text || 'No explanation available.').trim();const sourceIds: string[] = Array.isArray(response?.source_ids)? response.source_ids.filter((s: any) => typeof s === 'string' && s.trim().length > 0): [];const audioUrl = (response?.audio_url || response?.audioUrl || '') as string;const videoUrl = (response?.video_url || response?.videoUrl || '') as string;// Store question + source ids *now*.this.lastQuestion = message;this.lastSourceIds = sourceIds;const notFound = /No information available in the provided textbook content/i.test(explanation);const hasContext = !!sourceIds.length && !notFound;// Pass URLs along to the stream/attach to messagethis.streamAiAnswer(explanation, sourceIds, hasContext, audioUrl || undefined, videoUrl || undefined);},error: (err) => {console.error('API Error:', err);this.isTyping = false;const errorMessage = 'Error: Could not get a response from the server.';this.streamAiAnswer(errorMessage, [], false);}});}/** Show AI answer word-by-word and start audio *//** Show AI answer word-by-word and start audio */private streamAiAnswer(explanation: string, sourceIds: string[], hasContext: boolean, audioUrl?: string, videoUrl?: string): void {const text = (explanation || '').trim() || 'No explanation available.';const timestamp = new Date().toLocaleTimeString();3 unmodified linestext: '',timestamp,source_ids: sourceIds,pending: true,audioUrl: audioUrl || '',videoUrl: videoUrl || '',playingVideoUrl: ''} as any) - 1;// ensure video-enabled index has an entry for this messageif (this.isVideoEnabledIndex.length <= aiIndex) {this.isVideoEnabledIndex[aiIndex] = false;}this.isAiResponding = true;this.shouldAutoScroll = true;this.cdr.detectChanges();3 unmodified lines// When streaming is finished, we finally store lastAnswerthis.lastAnswer = text;this.lastAnswerHasContext = hasContext;// After the AI text finishes streaming, automatically play server media when toggles are enabled.// If both audio and video are present and both toggles are enabled, video takes precedence.this.autoPlayMediaForMessage(aiIndex);});// Only run client-side TTS when there is no server-provided audio URL.if (!audioUrl && this.isVoiceEnabled) {this.speakResponse(text);}}/*** Decide and start playback for a message that already has `audioUrl` and/or `videoUrl`.* Behavior:* - If both videoUrl && audioUrl && both video and audio toggles are ON -> play video (video wins)* - Else if videoUrl && video toggle ON -> play video* - Else if audioUrl && voice toggle ON -> play audio*/private autoPlayMediaForMessage(index: number): void {const msg = this.messages[index] as any;if (!msg) return;const hasVideo = !!(msg.videoUrl && msg.videoUrl.trim());const hasAudio = !!(msg.audioUrl && msg.audioUrl.trim());// If both present and user enabled both, prefer videoif (hasVideo && this.isTutorEnabled) {try { this.stopServerAudio(); } catch { /* noop */ }try { window.speechSynthesis?.cancel(); } catch { /* noop */ }// request autoplay (will mute to allow autoplay)this.openMessageVideo(index, true);return;}// If video present but tutor (video) is not enabled, do not auto-play it.// Only auto-play audio if user enabled voiceif (hasAudio && this.isVoiceEnabled) {// play server audio (this will stop videos if any)// ensure inline videos are stoppedtry { this.stopAllVideo(); } catch { /* noop */ }// If message already has audioUrl, play itthis.playServerAudioForMessage(index);return;}// If no server media played and no TTS, do nothing (user may manually click synth).}displaySource(tag: string): string {if (!tag) return '';178 unmodified lines}resumeAudio(): void {if (this.serverAudio && this.serverAudio.paused) {149 unmodified lines});}openMessageVideo(i: number, autoPlay: boolean = false): void {const msg = this.messages[i] as any;if (!msg?.videoUrl) return;17 unmodified linesconst vid = document.getElementById(`inline-video-${i}`) as HTMLVideoElement | null;if (!vid) { this.isVideoPlayingIndex = null; this.cdr.detectChanges(); return; }// If autoplay requested, mute to satisfy browser autoplay policies.if (autoPlay) {try { vid.muted = true; } catch { /* noop */ }} else {try { vid.muted = false; } catch { /* noop */ }}vid.onplay = () => { this.isVideoPlayingIndex = i; this.cdr.detectChanges(); };vid.onpause = () => { this.cdr.detectChanges(); };vid.onended = () => { this.onMessageVideoEnded(i); };75 unmodified lines}}stopListening(): void {this.isListening = false;217 unmodified lines}}addNewLine(event: KeyboardEvent): void {if (event.key === 'Enter' && event.shiftKey) {38 unmodified lines//if (this.serverAudio) {// try { this.serverAudio.volume = this.isMuted ? 0 : 1; } catch { /* noop */ }// }//this.saveToggleStates();}92 unmodified linesgoToHomePageShortcut(): void { this.router.navigate(['/home']); }openUserGuide(): void { this.showUserGuide = true; }closeUserGuide(): void { this.showUserGuide = false; }42 unmodified linesalert("Please check your browser's settings to enable the microphone.");}} catch (err) {console.error('openMicrophoneSettings error', err);alert("Unable to open settings automatically. Please check your browser's microphone/privacy settings.");}this.cdr.detectChanges();243 unmodified linesanalyser.smoothingTimeConstant = 0.85;source.connect(analyser);// assign to instance fieldthis.analyser = analyser;const bufferLength = analyser.fftSize;this.dataArray = new Uint8Array(bufferLength);
src/app/chat/api.service.ts+12-7
src/app/chat/chat.component.ts+116-55