-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
496 lines (411 loc) · 16.8 KB
/
Copy pathscript.js
File metadata and controls
496 lines (411 loc) · 16.8 KB
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// VidSynth AI - Frontend JavaScript
class VidSynthApp {
constructor() {
this.chatMessages = [];
this.vectorStore = null;
this.initializeEventListeners();
}
initializeEventListeners() {
// Submit button event listener
document.getElementById('submitBtn').addEventListener('click', () => {
this.handleSubmit();
});
// Chat input event listeners
document.getElementById('sendChatBtn').addEventListener('click', () => {
this.sendChatMessage();
});
document.getElementById('chatInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.sendChatMessage();
}
});
}
async handleSubmit() {
const youtubeUrl = document.getElementById('youtubeUrl').value.trim();
const language = document.getElementById('language').value.trim() || 'en';
const taskOption = document.querySelector('input[name="taskOption"]:checked').value;
if (!youtubeUrl) {
this.showError('Please enter a YouTube URL');
return;
}
if (!this.isValidYouTubeUrl(youtubeUrl)) {
this.showError('Please enter a valid YouTube URL');
return;
}
try {
// Clear previous data for new video
this.clearPreviousData();
this.showLoading('Step 1/3: Fetching Transcript.....');
this.hideResults();
// Extract video ID and get transcript
const videoId = this.extractVideoId(youtubeUrl);
if (!videoId) {
throw new Error('Invalid YouTube URL');
}
const transcriptData = await this.fetchTranscript(videoId, language);
if (language !== 'en') {
this.showLoading('Step 1.5/3: Translating Transcript into English, This may take few moments......');
transcriptData.transcript = await this.translateTranscript(transcriptData.transcript);
}
if (taskOption === 'Notes For You') {
await this.handleNotesGeneration(transcriptData.transcript);
} else if (taskOption === 'Chat with Video') {
await this.handleChatSetup(transcriptData.transcript);
}
} catch (error) {
this.hideLoading();
this.showError(`Error: ${error.message}`);
}
}
clearPreviousData() {
// Clear vector store
this.vectorStore = null;
// Clear chat messages
this.chatMessages = [];
// Reset chat interface
const chatMessages = document.getElementById('chatMessages');
if (chatMessages) {
chatMessages.innerHTML = `
<div class="welcome-message text-center p-4">
<i class="fas fa-robot fa-3x text-primary mb-3"></i>
<h5>Hi! I'm your AI assistant</h5>
<p class="text-muted">Ask me anything about the video content. I'm here to help!</p>
</div>
`;
}
console.log('Previous data cleared for new video');
}
async handleNotesGeneration(transcript) {
try {
this.showLoading('Step 2/3: Extracting important Topics...');
const topics = await this.getImportantTopics(transcript);
this.showLoading('Step 3/3: Generating Notes for you.');
const notes = await this.generateNotes(transcript);
this.hideLoading();
this.showNotesResults(topics, notes);
} catch (error) {
this.hideLoading();
this.showError(`Error generating notes: ${error.message}`);
}
}
async handleChatSetup(transcript) {
try {
this.showLoading('Step 2/3: Creating chunks and vector store....');
console.log('Creating chunks...');
const chunksResponse = await this.createChunks(transcript);
console.log('Chunks created:', chunksResponse);
console.log('Creating vector store...');
const vectorStoreResponse = await this.createVectorStore(chunksResponse.chunks);
console.log('Vector store created:', vectorStoreResponse);
this.hideLoading();
this.showChatReady();
this.chatMessages = [];
this.displayChatSection();
} catch (error) {
console.error('Error in handleChatSetup:', error);
this.hideLoading();
this.showError(`Error setting up chat: ${error.message}`);
}
}
async sendChatMessage() {
const chatInput = document.getElementById('chatInput');
const message = chatInput.value.trim();
if (!message || !this.vectorStore) return;
// Add user message to chat
this.addChatMessage('user', message);
chatInput.value = '';
try {
// Show typing indicator
this.showTypingIndicator();
// Get AI response
const response = await this.getRagAnswer(message);
// Hide typing indicator and show response
this.hideTypingIndicator();
this.addChatMessage('assistant', response);
} catch (error) {
this.hideTypingIndicator();
this.addChatMessage('assistant', 'Sorry, I encountered an error processing your question. Please try again.');
}
}
// API calls to Flask backend
async fetchTranscript(videoId, language) {
const response = await fetch('/api/transcript', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ video_id: videoId, language: language })
});
if (!response.ok) {
throw new Error('Failed to fetch transcript');
}
return await response.json();
}
async translateTranscript(transcript) {
const response = await fetch('/api/translate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ transcript: transcript })
});
if (!response.ok) {
throw new Error('Failed to translate transcript');
}
const data = await response.json();
return data.translated_transcript;
}
async getImportantTopics(transcript) {
const response = await fetch('/api/topics', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ transcript: transcript })
});
if (!response.ok) {
throw new Error('Failed to get important topics');
}
const data = await response.json();
return data.topics;
}
async generateNotes(transcript) {
const response = await fetch('/api/notes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ transcript: transcript })
});
if (!response.ok) {
throw new Error('Failed to generate notes');
}
const data = await response.json();
return data.notes;
}
async createChunks(transcript) {
const response = await fetch('/api/chunks', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ transcript: transcript })
});
if (!response.ok) {
throw new Error('Failed to create chunks');
}
const data = await response.json();
return data;
}
async createVectorStore(chunks) {
const response = await fetch('/api/vectorstore', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chunks: chunks })
});
if (!response.ok) {
throw new Error('Failed to create vector store');
}
const data = await response.json();
this.vectorStore = data.vector_store_id;
return data;
}
async getRagAnswer(question) {
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
question: question,
vector_store_id: this.vectorStore
})
});
if (!response.ok) {
throw new Error('Failed to get answer');
}
const data = await response.json();
return data.answer;
}
// Utility functions
extractVideoId(url) {
const match = url.match(/(?:v=|\/)([0-9A-Za-z_-]{11}).*/);
return match ? match[1] : null;
}
isValidYouTubeUrl(url) {
const youtubeRegex = /^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/.+/;
return youtubeRegex.test(url);
}
// UI functions
showLoading(text) {
document.getElementById('loadingText').textContent = text;
document.getElementById('loadingSpinner').classList.remove('d-none');
}
hideLoading() {
document.getElementById('loadingSpinner').classList.add('d-none');
}
hideResults() {
document.getElementById('resultsSection').classList.add('d-none');
document.getElementById('chatSection').classList.add('d-none');
document.getElementById('topicsSection').classList.add('d-none');
document.getElementById('notesSection').classList.add('d-none');
document.getElementById('successMessage').classList.add('d-none');
document.getElementById('chatReadyMessage').classList.add('d-none');
}
showNotesResults(topics, notes) {
document.getElementById('topicsContent').innerHTML = this.formatContent(topics);
document.getElementById('notesContent').innerHTML = this.formatContent(notes);
document.getElementById('resultsSection').classList.remove('d-none');
document.getElementById('topicsSection').classList.remove('d-none');
document.getElementById('notesSection').classList.remove('d-none');
document.getElementById('successMessage').classList.remove('d-none');
// Add fade-in animation
document.getElementById('resultsSection').classList.add('fade-in');
}
showChatReady() {
document.getElementById('resultsSection').classList.remove('d-none');
document.getElementById('chatReadyMessage').classList.remove('d-none');
}
displayChatSection() {
document.getElementById('chatSection').classList.remove('d-none');
// Keep the welcome message, don't clear it
const welcomeMessage = document.querySelector('.welcome-message');
if (welcomeMessage) {
welcomeMessage.style.display = 'block';
}
}
addChatMessage(role, content) {
const chatMessages = document.getElementById('chatMessages');
// Hide welcome message when first message is added
const welcomeMessage = document.querySelector('.welcome-message');
if (welcomeMessage && this.chatMessages.length === 0) {
welcomeMessage.style.display = 'none';
}
const messageDiv = document.createElement('div');
messageDiv.className = `chat-message ${role}`;
messageDiv.innerHTML = this.formatContent(content);
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
// Store message
this.chatMessages.push({ role, content });
}
showTypingIndicator() {
const chatMessages = document.getElementById('chatMessages');
const typingDiv = document.createElement('div');
typingDiv.className = 'typing-indicator';
typingDiv.id = 'typingIndicator';
typingDiv.innerHTML = `
<span>VidSynth AI is typing</span>
<div class="typing-dots">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
`;
chatMessages.appendChild(typingDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
hideTypingIndicator() {
const typingIndicator = document.getElementById('typingIndicator');
if (typingIndicator) {
typingIndicator.remove();
}
}
formatContent(content) {
// Convert markdown-like formatting to HTML
return content
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.*?)\*/g, '<em>$1</em>')
.replace(/\n/g, '<br>')
.replace(/(\d+\.\s)/g, '<br><strong>$1</strong>');
}
showError(message) {
const alertDiv = document.createElement('div');
alertDiv.className = 'alert alert-danger alert-dismissible fade show';
alertDiv.innerHTML = `
<i class="fas fa-exclamation-triangle"></i> ${message}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
`;
const mainContent = document.querySelector('.main-content .container-fluid');
mainContent.insertBefore(alertDiv, mainContent.firstChild);
// Auto-dismiss after 5 seconds
setTimeout(() => {
if (alertDiv.parentNode) {
alertDiv.remove();
}
}, 5000);
}
}
// Initialize the app when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
const app = new VidSynthApp();
// Add mobile menu toggle functionality
const mobileMenuToggle = document.getElementById('mobileMenuToggle');
const sidebar = document.getElementById('sidebar');
if (mobileMenuToggle) {
mobileMenuToggle.addEventListener('click', () => {
sidebar.classList.toggle('show');
});
}
// Add clear chat functionality
const clearChatBtn = document.getElementById('clearChatBtn');
if (clearChatBtn) {
clearChatBtn.addEventListener('click', () => {
const chatMessages = document.getElementById('chatMessages');
chatMessages.innerHTML = `
<div class="welcome-message text-center p-4">
<i class="fas fa-robot fa-3x text-primary mb-3"></i>
<h5>Hi! I'm your AI assistant</h5>
<p class="text-muted">Ask me anything about the video content. I'm here to help!</p>
</div>
`;
app.chatMessages = [];
});
}
// Add back to top functionality
const backToTopBtn = document.getElementById('backToTop');
if (backToTopBtn) {
window.addEventListener('scroll', () => {
if (window.pageYOffset > 300) {
backToTopBtn.style.display = 'block';
} else {
backToTopBtn.style.display = 'none';
}
});
backToTopBtn.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
}
// Add form validation
const youtubeUrlInput = document.getElementById('youtubeUrl');
if (youtubeUrlInput) {
youtubeUrlInput.addEventListener('input', (e) => {
const url = e.target.value.trim();
const isValid = app.isValidYouTubeUrl(url) || url === '';
if (isValid) {
e.target.classList.remove('is-invalid');
e.target.classList.add('is-valid');
} else {
e.target.classList.remove('is-valid');
e.target.classList.add('is-invalid');
}
});
}
// Add Enter key support for chat input
const chatInput = document.getElementById('chatInput');
if (chatInput) {
chatInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
app.sendChatMessage();
}
});
}
// Add progress bar animation during processing
const originalShowLoading = app.showLoading;
app.showLoading = function(text) {
originalShowLoading.call(this, text);
// Animate progress bar
const progressBar = document.getElementById('progressBar');
if (progressBar) {
let progress = 0;
const interval = setInterval(() => {
progress += Math.random() * 15;
if (progress > 90) progress = 90;
progressBar.style.width = progress + '%';
if (!document.getElementById('loadingSpinner').classList.contains('d-none')) {
clearInterval(interval);
progressBar.style.width = '100%';
}
}, 200);
}
};
});