-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
771 lines (649 loc) · 22.2 KB
/
Copy pathmain.js
File metadata and controls
771 lines (649 loc) · 22.2 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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
/**
* Text Intelligence HTML Starter - Frontend Application
*
* This is a vanilla JavaScript frontend that provides a text intelligence UI
* for Deepgram's Text Intelligence service. It's designed to be easily
* modified and extended for your own projects.
*
* Key Features:
* - Text or URL input for analysis
* - Multiple intelligence features (summarization, topics, sentiment, intents)
* - History management with localStorage
* - Responsive UI with Deepgram design system
*
* Architecture:
* - Pure vanilla JavaScript (no frameworks required)
* - Uses native Fetch API for HTTP requests
* - LocalStorage for history persistence
* - Event-driven UI updates
*/
// ============================================================================
// CONFIGURATION
// ============================================================================
/**
* API endpoint for text intelligence requests
*/
const API_ENDPOINT = 'api/text-intelligence';
/**
* API endpoint for app metadata
* Returns app title, description, author, repository, etc.
*/
const METADATA_ENDPOINT = 'api/metadata';
/**
* API endpoint for session token
*/
const SESSION_ENDPOINT = 'api/session';
/**
* Cached session token (JWT)
*/
let sessionToken = null;
/**
* Fetches a session token from the backend.
* Caches the token for subsequent requests.
* @returns {Promise<string>} JWT token
*/
async function getSessionToken() {
if (sessionToken) return sessionToken;
const response = await fetch(SESSION_ENDPOINT);
if (!response.ok) throw new Error(`Session failed: ${response.status}`);
const data = await response.json();
sessionToken = data.token;
return sessionToken;
}
/**
* Wraps fetch with Authorization header. Shows session-expired message on 401.
* @param {string} url - The URL to fetch
* @param {Object} options - Fetch options
* @returns {Promise<Response>}
*/
async function authenticatedFetch(url, options = {}) {
const token = await getSessionToken();
const headers = { ...options.headers, Authorization: `Bearer ${token}` };
const response = await fetch(url, { ...options, headers });
if (response.status === 401) {
sessionToken = null;
showError("Session expired, please refresh the page.");
throw new Error("Session expired");
}
return response;
}
/**
* LocalStorage key for history persistence
*/
const HISTORY_KEY = 'deepgram_text_intelligence_history';
/**
* Maximum number of history entries to store
*/
const MAX_HISTORY_ENTRIES = 10;
// ============================================================================
// STATE MANAGEMENT
// ============================================================================
/**
* DOM Elements - Cached references
*/
let textInput;
let urlInput;
let textModeBtn;
let urlModeBtn;
let textInputSection;
let urlInputSection;
let featureSummarize;
let featureTopics;
let featureSentiment;
let featureIntents;
let languageSelect;
let analyzeBtn;
let mainContent;
let statusContainer;
let statusMessage;
let metadataContainer;
let metadataGrid;
let historyTitle;
let historySidebarContent;
let clearHistoryBtn;
/**
* Current input mode ('text' or 'url')
*/
let inputMode = 'text';
/**
* Currently active analysis ID
*/
let activeAnalysisId = null;
// ============================================================================
// METADATA FETCHING
// ============================================================================
/**
* Fetches app metadata from the backend and updates the UI
* Updates page title, description, header title, and repository link
*/
async function fetchMetadata() {
try {
const response = await fetch(METADATA_ENDPOINT);
if (!response.ok) {
console.warn('Failed to fetch metadata, using defaults');
return;
}
const metadata = await response.json();
// Update page title
const pageTitle = document.getElementById('pageTitle');
if (metadata.title && pageTitle) {
pageTitle.textContent = metadata.title;
}
// Update page description
const pageDescription = document.getElementById('pageDescription');
if (metadata.description && pageDescription) {
pageDescription.setAttribute('content', metadata.description);
}
// Update header title
const headerTitle = document.getElementById('headerTitle');
if (metadata.title && headerTitle) {
headerTitle.textContent = metadata.title;
}
// Update repository link
const repoLink = document.getElementById('repoLink');
if (metadata.repository && repoLink) {
repoLink.href = metadata.repository;
}
console.log('Metadata loaded:', metadata);
} catch (error) {
console.warn('Error loading metadata, using defaults:', error);
}
}
// ============================================================================
// INITIALIZATION
// ============================================================================
/**
* Initialize the application when DOM is ready
*/
document.addEventListener('DOMContentLoaded', () => {
// Cache DOM elements
textInput = document.getElementById('textInput');
urlInput = document.getElementById('urlInput');
textModeBtn = document.getElementById('textModeBtn');
urlModeBtn = document.getElementById('urlModeBtn');
textInputSection = document.getElementById('textInputSection');
urlInputSection = document.getElementById('urlInputSection');
featureSummarize = document.getElementById('featureSummarize');
featureTopics = document.getElementById('featureTopics');
featureSentiment = document.getElementById('featureSentiment');
featureIntents = document.getElementById('featureIntents');
languageSelect = document.getElementById('language');
analyzeBtn = document.getElementById('analyzeBtn');
mainContent = document.getElementById('mainContent');
statusContainer = document.getElementById('statusContainer');
statusMessage = document.getElementById('statusMessage');
metadataContainer = document.getElementById('metadataContainer');
metadataGrid = document.getElementById('metadataGrid');
historyTitle = document.getElementById('historyTitle');
historySidebarContent = document.getElementById('historySidebarContent');
clearHistoryBtn = document.getElementById('clearHistoryBtn');
// Set up event listeners
textModeBtn.addEventListener('click', () => switchInputMode('text'));
urlModeBtn.addEventListener('click', () => switchInputMode('url'));
analyzeBtn.addEventListener('click', handleAnalyze);
clearHistoryBtn.addEventListener('click', handleClearHistory);
// Load and render history
renderHistory();
// Fetch and display app metadata
fetchMetadata();
});
// ============================================================================
// INPUT MODE MANAGEMENT
// ============================================================================
/**
* Switch between text and URL input modes
*/
function switchInputMode(mode) {
inputMode = mode;
if (mode === 'text') {
textModeBtn.classList.add('active');
urlModeBtn.classList.remove('active');
textInputSection.style.display = 'block';
urlInputSection.style.display = 'none';
} else {
urlModeBtn.classList.add('active');
textModeBtn.classList.remove('active');
urlInputSection.style.display = 'block';
textInputSection.style.display = 'none';
}
}
// ============================================================================
// API INTERACTION
// ============================================================================
/**
* Handle analyze button click
*/
async function handleAnalyze() {
// Get input value based on mode
const inputValue = inputMode === 'text' ? textInput.value.trim() : urlInput.value.trim();
if (!inputValue) {
showError('Please enter text or URL to analyze');
return;
}
// Get selected features
const features = {
summarize: featureSummarize.checked,
topics: featureTopics.checked,
sentiment: featureSentiment.checked,
intents: featureIntents.checked,
};
// Ensure at least one feature is selected
if (!Object.values(features).some(v => v)) {
showError('Please select at least one intelligence feature');
return;
}
// Build query parameters
const params = new URLSearchParams();
if (features.summarize) params.append('summarize', 'true');
if (features.topics) params.append('topics', 'true');
if (features.sentiment) params.append('sentiment', 'true');
if (features.intents) params.append('intents', 'true');
params.append('language', languageSelect.value);
// Build request body
const body = inputMode === 'text'
? { text: inputValue }
: { url: inputValue };
// Generate request ID
const requestId = `request_${Date.now()}`;
// Show working state
showWorking('Analyzing text...');
setFormDisabled(true);
try {
const response = await authenticatedFetch(`${API_ENDPOINT}?${params.toString()}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error?.message || 'Analysis failed');
}
// Hide status, show results
hideStatus();
// Save to history
const historyEntry = {
id: requestId,
timestamp: new Date().toISOString(),
input: inputValue,
inputMode,
features,
results: data.results,
};
saveToHistory(historyEntry);
// Display results
displayResults(data.results, features);
// Display metadata (use API request_id if available)
displayMetadata(data.metadata?.request_id, inputMode, inputValue);
activeAnalysisId = requestId;
} catch (error) {
console.error('Analysis error:', error);
showError(error.message || 'Failed to analyze text');
} finally {
setFormDisabled(false);
}
}
// ============================================================================
// RESULTS DISPLAY
// ============================================================================
/**
* Display analysis results in main content area
*/
function displayResults(results, features) {
const container = document.createElement('div');
container.className = 'results-container';
// Summary
if (features.summarize && results.summary) {
container.appendChild(createSummarySection(results.summary));
}
// Topics
if (features.topics && results.topics) {
container.appendChild(createTopicsSection(results.topics));
}
// Sentiment
if (features.sentiment && results.sentiments) {
container.appendChild(createSentimentSection(results.sentiments));
}
// Intents
if (features.intents && results.intents) {
container.appendChild(createIntentsSection(results.intents));
}
mainContent.innerHTML = '';
mainContent.appendChild(container);
}
/**
* Create summary section
*/
function createSummarySection(summary) {
const section = document.createElement('div');
section.className = 'result-section';
const heading = document.createElement('h3');
heading.innerHTML = '<i class="fa-solid fa-file-lines"></i> Summary';
section.appendChild(heading);
if (summary.text) {
const text = document.createElement('div');
text.className = 'result-text';
text.textContent = summary.text;
section.appendChild(text);
} else {
const empty = document.createElement('p');
empty.style.color = 'var(--dg-muted, #949498)';
empty.textContent = 'No summary available';
section.appendChild(empty);
}
return section;
}
/**
* Create topics section
*/
function createTopicsSection(topicsData) {
const section = document.createElement('div');
section.className = 'result-section';
const heading = document.createElement('h3');
heading.innerHTML = '<i class="fa-solid fa-tags"></i> Topics';
section.appendChild(heading);
// Extract all topics from segments
const allTopics = [];
if (topicsData && topicsData.segments && Array.isArray(topicsData.segments)) {
topicsData.segments.forEach(segment => {
if (segment.topics && Array.isArray(segment.topics)) {
segment.topics.forEach(topic => {
allTopics.push(topic);
});
}
});
}
if (allTopics.length > 0) {
const list = document.createElement('div');
list.className = 'topics-list';
allTopics.forEach(item => {
const badge = document.createElement('div');
badge.className = 'topic-badge';
const topicText = document.createElement('span');
topicText.textContent = item.topic;
badge.appendChild(topicText);
if (item.confidence_score !== undefined) {
const confidence = document.createElement('span');
confidence.className = 'confidence-score';
confidence.textContent = item.confidence_score.toFixed(2);
badge.appendChild(confidence);
}
list.appendChild(badge);
});
section.appendChild(list);
} else {
const empty = document.createElement('p');
empty.style.color = 'var(--dg-muted, #949498)';
empty.textContent = 'No topics detected';
section.appendChild(empty);
}
return section;
}
/**
* Create sentiment section
*/
function createSentimentSection(sentimentsData) {
const section = document.createElement('div');
section.className = 'result-section';
const heading = document.createElement('h3');
heading.innerHTML = '<i class="fa-solid fa-heart-pulse"></i> Sentiment';
section.appendChild(heading);
if (sentimentsData && sentimentsData.average) {
const display = document.createElement('div');
display.className = 'sentiment-display';
const icon = document.createElement('i');
icon.className = `fa-solid sentiment-icon sentiment-${sentimentsData.average.sentiment}`;
if (sentimentsData.average.sentiment === 'positive') {
icon.classList.add('fa-face-smile');
} else if (sentimentsData.average.sentiment === 'negative') {
icon.classList.add('fa-face-frown');
} else {
icon.classList.add('fa-face-meh');
}
display.appendChild(icon);
const textWrapper = document.createElement('div');
const sentimentText = document.createElement('div');
sentimentText.className = `sentiment-text sentiment-${sentimentsData.average.sentiment}`;
sentimentText.textContent = sentimentsData.average.sentiment;
textWrapper.appendChild(sentimentText);
if (sentimentsData.average.sentiment_score !== undefined) {
const confidence = document.createElement('div');
confidence.className = 'confidence-score';
confidence.textContent = `Score: ${sentimentsData.average.sentiment_score.toFixed(2)}`;
textWrapper.appendChild(confidence);
}
display.appendChild(textWrapper);
section.appendChild(display);
// Optionally show segment breakdown
if (sentimentsData.segments && sentimentsData.segments.length > 0) {
const segmentsInfo = document.createElement('div');
segmentsInfo.className = 'sentiment-segments-info';
segmentsInfo.style.marginTop = '0.5rem';
segmentsInfo.style.fontSize = '0.875rem';
segmentsInfo.style.color = 'var(--dg-muted, #949498)';
segmentsInfo.textContent = `${sentimentsData.segments.length} segment${sentimentsData.segments.length > 1 ? 's' : ''} analyzed`;
section.appendChild(segmentsInfo);
}
} else {
const empty = document.createElement('p');
empty.style.color = 'var(--dg-muted, #949498)';
empty.textContent = 'No sentiment analysis available';
section.appendChild(empty);
}
return section;
}
/**
* Create intents section
*/
function createIntentsSection(intentsData) {
const section = document.createElement('div');
section.className = 'result-section';
const heading = document.createElement('h3');
heading.innerHTML = '<i class="fa-solid fa-bullseye"></i> Intents';
section.appendChild(heading);
// Extract all intents from segments
const allIntents = [];
if (intentsData && intentsData.segments && Array.isArray(intentsData.segments)) {
intentsData.segments.forEach(segment => {
if (segment.intents && Array.isArray(segment.intents)) {
segment.intents.forEach(intent => {
allIntents.push(intent);
});
}
});
}
if (allIntents.length > 0) {
const list = document.createElement('div');
list.className = 'intents-list';
allIntents.forEach(item => {
const badge = document.createElement('div');
badge.className = 'intent-badge';
const intentText = document.createElement('span');
intentText.textContent = item.intent;
badge.appendChild(intentText);
if (item.confidence_score !== undefined) {
const confidence = document.createElement('span');
confidence.className = 'confidence-score';
confidence.textContent = item.confidence_score.toFixed(2);
badge.appendChild(confidence);
}
list.appendChild(badge);
});
section.appendChild(list);
} else {
const empty = document.createElement('p');
empty.style.color = 'var(--dg-muted, #949498)';
empty.textContent = 'No intents detected';
section.appendChild(empty);
}
return section;
}
/**
* Display metadata
*/
function displayMetadata(apiRequestId, inputMode, input) {
metadataGrid.innerHTML = '';
const items = [
...(apiRequestId ? [{ label: 'Request ID', value: apiRequestId }] : []),
{ label: 'Input Mode', value: inputMode === 'text' ? 'Text' : 'URL' },
{ label: 'Input Preview', value: input.substring(0, 50) + (input.length > 50 ? '...' : '') },
{ label: 'Timestamp', value: new Date().toLocaleString() },
];
items.forEach(item => {
const div = document.createElement('div');
div.className = 'metadata-item';
const label = document.createElement('div');
label.className = 'metadata-label';
label.textContent = item.label;
const value = document.createElement('div');
value.className = 'metadata-value';
value.textContent = item.value;
div.appendChild(label);
div.appendChild(value);
metadataGrid.appendChild(div);
});
metadataContainer.style.display = 'block';
}
// ============================================================================
// HISTORY MANAGEMENT
// ============================================================================
/**
* Get history from localStorage
*/
function getHistory() {
try {
const history = localStorage.getItem(HISTORY_KEY);
return history ? JSON.parse(history) : [];
} catch (error) {
console.error('Error reading history:', error);
return [];
}
}
/**
* Save entry to history
*/
function saveToHistory(entry) {
try {
const history = getHistory();
history.unshift(entry);
const trimmed = history.slice(0, MAX_HISTORY_ENTRIES);
localStorage.setItem(HISTORY_KEY, JSON.stringify(trimmed));
renderHistory();
} catch (error) {
console.error('Error saving to history:', error);
}
}
/**
* Render history list
*/
function renderHistory() {
const history = getHistory();
historyTitle.textContent = `History (${history.length})`;
if (history.length === 0) {
historySidebarContent.innerHTML = '<div class="history-empty">No analyses yet</div>';
clearHistoryBtn.style.display = 'none';
return;
}
clearHistoryBtn.style.display = 'block';
const list = document.createElement('div');
list.className = 'history-list';
history.forEach(entry => {
const item = document.createElement('div');
item.className = 'history-item';
if (entry.id === activeAnalysisId) {
item.classList.add('history-item--active');
}
const id = document.createElement('div');
id.className = 'history-item__id';
id.textContent = entry.id;
const time = document.createElement('div');
time.className = 'history-item__time';
time.textContent = new Date(entry.timestamp).toLocaleString();
const features = document.createElement('div');
features.className = 'history-item__features';
const featuresList = Object.entries(entry.features)
.filter(([_, enabled]) => enabled)
.map(([name]) => name)
.join(', ');
features.textContent = featuresList || 'No features';
item.appendChild(id);
item.appendChild(time);
item.appendChild(features);
item.addEventListener('click', () => {
activeAnalysisId = entry.id;
displayResults(entry.results, entry.features);
displayMetadata(entry.id, entry.inputMode, entry.input);
renderHistory();
});
list.appendChild(item);
});
historySidebarContent.innerHTML = '';
historySidebarContent.appendChild(list);
}
/**
* Clear all history
*/
function handleClearHistory() {
if (confirm('Are you sure you want to clear all history?')) {
localStorage.removeItem(HISTORY_KEY);
activeAnalysisId = null;
renderHistory();
mainContent.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon dg-text-primary"><i class="fa-solid fa-brain"></i></div>
<h2 class="dg-section-heading">Analyze Text with AI Intelligence</h2>
<p class="dg-prose">
Enter text or provide a URL, select the intelligence features you want, and click analyze to get insights.
</p>
</div>
`;
metadataContainer.style.display = 'none';
}
}
// ============================================================================
// UI STATE MANAGEMENT
// ============================================================================
/**
* Show working/loading state
*/
function showWorking(message) {
statusMessage.className = 'dg-status dg-status--with-icon dg-status--info';
statusMessage.innerHTML = `
<i class="fa-solid fa-circle-notch fa-spin dg-status__icon"></i>
<span>${message}</span>
`;
statusContainer.style.display = 'block';
}
/**
* Show error state
*/
function showError(message) {
statusMessage.className = 'dg-status dg-status--with-icon dg-status--danger';
statusMessage.innerHTML = `
<i class="fa-solid fa-circle-exclamation dg-status__icon"></i>
<span>${message}</span>
`;
statusContainer.style.display = 'block';
}
/**
* Hide status message
*/
function hideStatus() {
statusContainer.style.display = 'none';
}
/**
* Enable/disable form inputs
*/
function setFormDisabled(disabled) {
textInput.disabled = disabled;
urlInput.disabled = disabled;
featureSummarize.disabled = disabled;
featureTopics.disabled = disabled;
featureSentiment.disabled = disabled;
featureIntents.disabled = disabled;
languageSelect.disabled = disabled;
analyzeBtn.disabled = disabled;
textModeBtn.disabled = disabled;
urlModeBtn.disabled = disabled;
}