-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
175 lines (145 loc) · 6.18 KB
/
script.js
File metadata and controls
175 lines (145 loc) · 6.18 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
const API_BASE_URL = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' ? 'http://localhost:8000' : '';
// Theme Management
const themeToggle = document.getElementById('themeToggle');
const currentTheme = localStorage.getItem('theme') || 'light';
if (currentTheme === 'dark') {
document.documentElement.setAttribute('data-theme', 'dark');
}
themeToggle.addEventListener('click', () => {
let theme = document.documentElement.getAttribute('data-theme');
if (theme === 'dark') {
document.documentElement.removeAttribute('data-theme');
localStorage.setItem('theme', 'light');
} else {
document.documentElement.setAttribute('data-theme', 'dark');
localStorage.setItem('theme', 'dark');
}
});
async function analyzeSentiment() {
const text = document.getElementById('tweetInput').value.trim();
if (!text) return;
// UI State: Loading
setLoading(true);
hideError();
const resultsContainer = document.getElementById('resultsContainer');
resultsContainer.classList.remove('hidden');
// Reset cards to a "calculating" state
resetCard('tfidf');
resetCard('bert');
// Analyze TF-IDF
const tfidfPromise = fetch(`${API_BASE_URL}/predict/tfidf`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text })
}).then(res => res.ok ? res.json() : Promise.reject('TF-IDF Error'))
.then(data => updateResultCard('tfidf', data))
.catch(err => {
console.error(err);
showCardError('tfidf', 'TF-IDF model is not responding (check if server is running)');
});
// Analyze BERT
const bertPromise = fetch(`${API_BASE_URL}/predict/bert`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text })
}).then(res => res.ok ? res.json() : Promise.reject('BERT Error'))
.then(data => updateResultCard('bert', data))
.catch(err => {
console.error(err);
showCardError('bert', 'BERT model failed or is still loading on the server');
});
try {
await Promise.allSettled([tfidfPromise, bertPromise]);
} finally {
setLoading(false);
}
}
function resetCard(modelPrefix) {
const card = document.getElementById(`${modelPrefix}Card`);
card.style.opacity = '0.5';
document.getElementById(`${modelPrefix}Badge`).textContent = '...';
}
function showCardError(modelPrefix, message) {
const chart = document.getElementById(`${modelPrefix}Chart`);
const badge = document.getElementById(`${modelPrefix}Badge`);
const card = document.getElementById(`${modelPrefix}Card`);
card.style.opacity = '1';
badge.textContent = '⚠️ Error';
badge.className = 'sentiment-badge badge-negative';
chart.innerHTML = `<p style="font-size: 0.8rem; color: var(--negative);">${message}</p>`;
}
function updateResultCard(modelPrefix, data) {
const card = document.getElementById(`${modelPrefix}Card`);
const badge = document.getElementById(`${modelPrefix}Badge`);
const progress = document.getElementById(`${modelPrefix}Progress`);
const confValue = document.getElementById(`${modelPrefix}ConfValue`);
const chart = document.getElementById(`${modelPrefix}Chart`);
card.style.opacity = '1';
// Map labels to visuals
const moodMap = {
'Positive': { emoji: '😊', class: 'badge-positive', color: 'var(--positive)' },
'Negative': { emoji: '😠', class: 'badge-negative', color: 'var(--negative)' },
'Neutral': { emoji: '😐', class: 'badge-neutral', color: 'var(--neutral)' }
};
const mood = moodMap[data.label] || moodMap['Neutral'];
// Update Badge
badge.textContent = `${mood.emoji} ${data.label}`;
badge.className = `sentiment-badge ${mood.class}`;
// Update Progress Bar
const confPercent = (data.confidence * 100).toFixed(1);
progress.style.width = '0%'; // Reset first for animation
setTimeout(() => {
progress.style.width = `${confPercent}%`;
progress.style.backgroundColor = mood.color;
}, 50);
confValue.textContent = `${confPercent}%`;
// Update Top Words Chart
chart.innerHTML = '';
if (!data.top_words || data.top_words.length === 0) {
chart.innerHTML = '<p style="font-size: 0.8rem; color: var(--text-secondary);">No significant tokens found.</p>';
return;
}
// Normalize scores for chart (find max absolute score)
const maxScore = Math.max(...data.top_words.map(w => Math.abs(w.score)), 0.0001);
data.top_words.forEach((item, index) => {
const barWidth = (Math.abs(item.score) / maxScore) * 100;
const color = item.score > 0 ? 'var(--positive)' : 'var(--negative)';
const barWrapper = document.createElement('div');
barWrapper.className = 'chart-bar-wrapper';
barWrapper.innerHTML = `
<div class="bar-label">
<span>${item.word}</span>
<span>${(item.score > 0 ? '+' : '') + item.score.toFixed(3)}</span>
</div>
<div class="bar-fill-bg">
<div class="bar-fill" style="width: 0%; background-color: ${color}"></div>
</div>
`;
chart.appendChild(barWrapper);
// Staggered animation for bars
setTimeout(() => {
const fill = barWrapper.querySelector('.bar-fill');
if (fill) fill.style.width = `${barWidth}%`;
}, 100 + (index * 50));
});
}
function setLoading(isLoading) {
const btn = document.getElementById('analyzeBtn');
const text = document.getElementById('btnText');
const spinner = document.getElementById('loadingSpinner');
btn.disabled = isLoading;
if (isLoading) {
text.textContent = 'Analyzing...';
spinner.classList.remove('hidden');
} else {
text.textContent = 'Analyze Sentiment';
spinner.classList.add('hidden');
}
}
function showError() {
document.getElementById('errorMessage').classList.remove('hidden');
document.getElementById('resultsContainer').classList.add('hidden');
}
function hideError() {
document.getElementById('errorMessage').classList.add('hidden');
}