File size: 12,899 Bytes
d08043e
650485d
2f158c7
650485d
 
 
 
 
e625432
0f5e454
d08043e
 
c166c74
ef42326
650485d
 
6923eb0
c166c74
ef42326
650485d
 
 
 
0f5e454
c166c74
650485d
 
 
 
 
 
 
cb22125
650485d
 
 
 
 
262bac6
0f5e454
d08043e
 
c166c74
d750081
650485d
d08043e
 
650485d
d08043e
 
c166c74
 
650485d
0f5e454
c166c74
 
 
d08043e
2b125aa
650485d
d08043e
 
0f5e454
 
c166c74
c5f4625
 
 
c166c74
 
 
 
 
0f5e454
650485d
d08043e
650485d
0f5e454
d08043e
c166c74
ef42326
 
 
0f5e454
650485d
d08043e
0f5e454
c166c74
c5f4625
c166c74
 
 
2b125aa
 
d08043e
 
 
 
 
 
 
 
0f5e454
c166c74
 
 
 
 
 
0f5e454
 
ef42326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80211c4
ef42326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d750081
 
 
 
 
 
 
 
 
 
 
 
 
 
ef42326
d750081
 
 
 
 
 
 
 
 
 
 
 
 
 
ef42326
 
 
 
 
 
 
 
 
 
d08043e
0f5e454
d08043e
 
 
 
 
 
0f5e454
d08043e
 
 
 
 
 
 
 
0f5e454
 
c166c74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5f4625
d08043e
2b125aa
0f5e454
 
 
 
d08043e
 
 
c166c74
d08043e
 
 
c166c74
 
 
d08043e
 
c166c74
 
 
 
 
d08043e
 
 
 
 
 
 
 
650485d
 
d08043e
 
0f5e454
d08043e
 
 
0f5e454
d08043e
 
 
0f5e454
650485d
0f5e454
d08043e
0f5e454
d08043e
 
 
 
 
c166c74
d08043e
 
 
c166c74
 
 
d08043e
 
c166c74
 
 
 
 
d08043e
 
 
 
 
 
 
 
 
 
 
 
 
650485d
 
c166c74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d08043e
0f5e454
 
d08043e
 
0f5e454
c166c74
 
 
 
 
 
 
 
 
650485d
0f5e454
 
d08043e
 
 
 
0f5e454
d08043e
 
 
0f5e454
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
import { Component, OnInit, OnDestroy, ViewChild, ElementRef, AfterViewChecked } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormBuilder, ReactiveFormsModule, Validators, FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatCardModule } from '@angular/material/card';
import { MatSelectModule } from '@angular/material/select';
import { MatDividerModule } from '@angular/material/divider';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatDialog } from '@angular/material/dialog';
import { Subscription } from 'rxjs';

import { ApiService } from '../../services/api.service';
import { EnvironmentService } from '../../services/environment.service';
import { Router } from '@angular/router';

interface ChatMessage {
  author: 'user' | 'assistant';
  text: string;
  timestamp?: Date;
  audioUrl?: string;  // For TTS audio
}

@Component({
  selector: 'app-chat',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    MatButtonModule,
    MatIconModule,
    MatFormFieldModule,
    MatInputModule,
    MatCardModule,
    MatSelectModule,
    MatDividerModule,
    MatTooltipModule,
    MatProgressSpinnerModule,
    MatCheckboxModule
  ],
  templateUrl: './chat.component.html',
  styleUrls: ['./chat.component.scss']
})
export class ChatComponent implements OnInit, OnDestroy, AfterViewChecked {
  @ViewChild('scrollMe') private myScrollContainer!: ElementRef;
  @ViewChild('audioPlayer') private audioPlayer!: ElementRef<HTMLAudioElement>;
  @ViewChild('waveformCanvas') private waveformCanvas!: ElementRef<HTMLCanvasElement>;

  projects: string[] = [];
  selectedProject: string | null = null;
  useTTS = false;
  ttsAvailable = false;

  sessionId: string | null = null;
  messages: ChatMessage[] = [];
  input = this.fb.control('', Validators.required);
  
  loading = false;
  error = '';
  playingAudio = false;
  useSTT = false;
  sttAvailable = false;
  isListening = false;
  
  // Audio visualization
  audioContext?: AudioContext;
  analyser?: AnalyserNode;
  animationId?: number;
  
  private subs = new Subscription();
  private shouldScroll = false;

  constructor(
    private fb: FormBuilder, 
    private api: ApiService,
    private environmentService: EnvironmentService,
    private dialog: MatDialog,
    private router: Router  
  ) {}

  ngOnInit(): void {
    this.loadProjects();
    this.checkTTSAvailability();
    this.checkSTTAvailability();
    
    // Initialize Audio Context
    this.audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
  }

  ngAfterViewChecked() {
    if (this.shouldScroll) {
      this.scrollToBottom();
      this.shouldScroll = false;
    }
  }

  ngOnDestroy(): void {
    this.subs.unsubscribe();
    if (this.animationId) {
      cancelAnimationFrame(this.animationId);
    }
    if (this.audioContext) {
      this.audioContext.close();
    }
  }

  private checkSTTAvailability(): void {
    this.api.getEnvironment().subscribe({
      next: (env) => {
        this.sttAvailable = env.stt_engine !== 'no_stt';
        if (!this.sttAvailable) {
          this.useSTT = false;
        }
      },
      error: (err) => {
        console.error('Failed to check STT availability:', err);
        this.sttAvailable = false;
      }
    });
  }
  
  startRealtimeChat(): void {
    if (!this.selectedProject) {
      this.error = 'Please select a project first';
      return;
    }
    
    if (!this.sttAvailable) {
      this.error = 'STT is not configured. Please configure it in Environment settings.';
      return;
    }
    
    this.loading = true;
    this.error = '';
    
    // Start a new session for realtime chat
    const sub = this.api.startChat(this.selectedProject).subscribe({
      next: res => {
        // Store session ID for realtime component
        localStorage.setItem('current_session_id', res.session_id);
        localStorage.setItem('current_project', this.selectedProject || '');
        
        // Open realtime chat dialog
        this.openRealtimeDialog(res.session_id);
        
        this.loading = false;
      },
      error: (err) => {
        this.error = err.error?.detail || 'Failed to start realtime session';
        this.loading = false;
        console.error('Start realtime chat error:', err);
      }
    });
    
    this.subs.add(sub);
  }
  
  private openRealtimeDialog(sessionId: string): void {
    // Dinamik import kullan
    import('./realtime-chat.component').then(module => {
      const dialogRef = this.dialog.open(module.RealtimeChatComponent, {
        width: '90%',
        maxWidth: '900px',
        height: '85vh',
        maxHeight: '800px',
        disableClose: false,
        panelClass: 'realtime-chat-dialog',
        data: { 
          sessionId: sessionId,
          projectName: this.selectedProject 
        }
      });
      
      dialogRef.afterClosed().subscribe(result => {
        // Clean up session data
        localStorage.removeItem('current_session_id');
        localStorage.removeItem('current_project');
        
        // If session was active, we might want to end it
        if (result === 'session_active') {
          // Optionally end the session on backend
          this.api.endSession(sessionId).subscribe({
            next: () => console.log('Session ended'),
            error: (err: any) => console.error('Failed to end session:', err)
          });
        }
      });
    });
  }
  
  // Alternatif: Route navigasyonu kullanmak isterseniz
  private navigateToRealtimeChat(sessionId: string): void {
    this.router.navigate(['/realtime-chat', sessionId], {
      queryParams: { project: this.selectedProject }
    });
  }
  
  loadProjects(): void {
    this.loading = true;
    const sub = this.api.getChatProjects().subscribe({
      next: projects => {
        this.projects = projects;
        this.loading = false;
        if (projects.length === 0) {
          this.error = 'No enabled projects found. Please enable a project with published version.';
        }
      },
      error: (err) => {
        this.error = 'Failed to load projects';
        this.loading = false;
        console.error('Load projects error:', err);
      }
    });
    this.subs.add(sub);
  }

  checkTTSAvailability(): void {
    const sub = this.environmentService.environment$.subscribe(env => {
      if (env) {
        this.ttsAvailable = env.tts_engine !== 'no_tts';
        if (!this.ttsAvailable) {
          this.useTTS = false;
        }
      }
    });
    this.subs.add(sub);
    
    // Also get current environment
    this.api.getEnvironment().subscribe({
      next: (env) => {
        this.ttsAvailable = env.tts_engine !== 'no_tts';
        if (!this.ttsAvailable) {
          this.useTTS = false;
        }
      }
    });
  }
  
  startChat(): void {
    if (!this.selectedProject) return;
    
    this.loading = true;
    this.error = '';
    
    const sub = this.api.startChat(this.selectedProject).subscribe({
      next: res => {
        this.sessionId = res.session_id;
        const message: ChatMessage = { 
          author: 'assistant', 
          text: res.answer,
          timestamp: new Date()
        };
        
        this.messages = [message];
        this.loading = false;
        this.shouldScroll = true;
        
        // Generate TTS if enabled
        if (this.useTTS) {
          this.generateTTS(res.answer, this.messages.length - 1);
        }
      },
      error: (err) => {
        this.error = err.error?.detail || 'Failed to start session';
        this.loading = false;
        console.error('Start chat error:', err);
      }
    });
    this.subs.add(sub);
  }

  send(): void {
    if (!this.sessionId || this.input.invalid) return;
    
    const text = this.input.value!.trim();
    if (!text) return;

    // Add user message
    this.messages.push({ 
      author: 'user', 
      text,
      timestamp: new Date()
    });
    
    this.input.reset();
    this.loading = true;
    this.shouldScroll = true;

    // Send to backend
    const sub = this.api.chat(this.sessionId, text).subscribe({
      next: res => {
        const message: ChatMessage = { 
          author: 'assistant', 
          text: res.answer,
          timestamp: new Date()
        };
        
        this.messages.push(message);
        this.loading = false;
        this.shouldScroll = true;
        
        // Generate TTS if enabled
        if (this.useTTS) {
          this.generateTTS(res.answer, this.messages.length - 1);
        }
      },
      error: (err) => {
        this.messages.push({
          author: 'assistant',
          text: '⚠️ ' + (err.error?.detail || 'Failed to send message. Please try again.'),
          timestamp: new Date()
        });
        this.loading = false;
        this.shouldScroll = true;
        console.error('Chat error:', err);
      }
    });
    this.subs.add(sub);
  }

  generateTTS(text: string, messageIndex: number): void {
    const sub = this.api.generateTTS(text).subscribe({
      next: (audioBlob) => {
        const audioUrl = URL.createObjectURL(audioBlob);
        this.messages[messageIndex].audioUrl = audioUrl;
        
        // Auto-play the latest message
        if (messageIndex === this.messages.length - 1) {
          setTimeout(() => this.playAudio(audioUrl), 100);
        }
      },
      error: (err) => {
        console.error('TTS generation error:', err);
      }
    });
    this.subs.add(sub);
  }

  playAudio(audioUrl: string): void {
    if (!this.audioPlayer) return;
    
    const audio = this.audioPlayer.nativeElement;
    audio.src = audioUrl;
    
    // Set up audio visualization
    this.setupAudioVisualization(audio);
    
    audio.play().then(() => {
      this.playingAudio = true;
    }).catch(err => {
      console.error('Audio play error:', err);
    });
    
    audio.onended = () => {
      this.playingAudio = false;
      if (this.animationId) {
        cancelAnimationFrame(this.animationId);
        this.clearWaveform();
      }
    };
  }

  setupAudioVisualization(audio: HTMLAudioElement): void {
    if (!this.audioContext || !this.waveformCanvas) return;
    
    // Create audio source and analyser
    const source = this.audioContext.createMediaElementSource(audio);
    this.analyser = this.audioContext.createAnalyser();
    this.analyser.fftSize = 256;
    
    // Connect nodes
    source.connect(this.analyser);
    this.analyser.connect(this.audioContext.destination);
    
    // Start visualization
    this.drawWaveform();
  }

  drawWaveform(): void {
    if (!this.analyser || !this.waveformCanvas) return;
    
    const canvas = this.waveformCanvas.nativeElement;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    
    const bufferLength = this.analyser.frequencyBinCount;
    const dataArray = new Uint8Array(bufferLength);
    
    const draw = () => {
      this.animationId = requestAnimationFrame(draw);
      
      this.analyser!.getByteFrequencyData(dataArray);
      
      ctx.fillStyle = 'rgb(240, 240, 240)';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      
      const barWidth = (canvas.width / bufferLength) * 2.5;
      let barHeight;
      let x = 0;
      
      for (let i = 0; i < bufferLength; i++) {
        barHeight = (dataArray[i] / 255) * canvas.height * 0.8;
        
        ctx.fillStyle = `rgb(63, 81, 181)`;
        ctx.fillRect(x, canvas.height - barHeight, barWidth, barHeight);
        
        x += barWidth + 1;
      }
    };
    
    draw();
  }

  clearWaveform(): void {
    if (!this.waveformCanvas) return;
    
    const canvas = this.waveformCanvas.nativeElement;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    
    ctx.fillStyle = 'rgb(240, 240, 240)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
  }

  endSession(): void {
    this.sessionId = null;
    this.messages = [];
    this.selectedProject = null;
    this.input.reset();
    this.error = '';
    
    // Clean up audio
    if (this.audioPlayer) {
      this.audioPlayer.nativeElement.pause();
    }
    if (this.animationId) {
      cancelAnimationFrame(this.animationId);
    }
    this.clearWaveform();
  }

  private scrollToBottom(): void {
    try {
      if (this.myScrollContainer) {
        this.myScrollContainer.nativeElement.scrollTop = 
          this.myScrollContainer.nativeElement.scrollHeight;
      }
    } catch(err) {
      console.error('Scroll error:', err);
    }
  }
}