Spaces:
Paused
Paused
File size: 13,071 Bytes
f07ec3c | 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 | // Ensure Chart.js uses the right defaults for dark mode
Chart.defaults.color = '#94A3B8';
Chart.defaults.borderColor = 'rgba(255, 255, 255, 0.1)';
// Global chart instances so we can destroy them before re-rendering
let charts = {};
// API Configuration: Set this to your Hugging Face Space URL if deploying separately
// For local development or combined deployment, leave it as an empty string
const API_BASE_URL = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
? ''
: (window.BACKEND_URL || '');
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('uploadForm');
const analyzeBtn = document.getElementById('analyzeBtn');
const btnText = analyzeBtn.querySelector('.btn-text');
const spinner = analyzeBtn.querySelector('.spinner');
const resultsArea = document.getElementById('resultsArea');
const inputSection = document.querySelector('.input-section');
// Tab switching logic
const tabBtns = document.querySelectorAll('.tab-btn');
tabBtns.forEach(btn => {
btn.addEventListener('click', () => {
tabBtns.forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
btn.classList.add('active');
document.getElementById(btn.dataset.tab).classList.add('active');
});
});
// Example button logic
const exampleBtns = document.querySelectorAll('.example-btn');
exampleBtns.forEach(btn => {
btn.addEventListener('click', () => {
const file = btn.dataset.file;
const search = btn.dataset.search;
// Populate search term
document.getElementById('searchTerm').value = search;
// Clear file input since we are using an example file
document.getElementById('pdfFile').value = '';
// Submit form with example data
submitAnalysis(null, search, file);
});
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
const fileInput = document.getElementById('pdfFile');
const searchTerm = document.getElementById('searchTerm').value;
if (!fileInput.files.length) {
alert("Please upload a PDF file or choose an example.");
return;
}
const file = fileInput.files[0];
submitAnalysis(file, searchTerm, null);
});
async function submitAnalysis(file, searchTerm, exampleFile) {
const formData = new FormData();
if (file) {
formData.append('file', file);
} else if (exampleFile) {
formData.append('example_file', exampleFile);
}
formData.append('search_term', searchTerm);
// UI Loading state
analyzeBtn.disabled = true;
btnText.textContent = 'Analyzing...';
spinner.classList.remove('hidden');
resultsArea.classList.add('hidden');
// Reset tabs to Summary
tabBtns.forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
document.querySelector('[data-tab="summary"]').classList.add('active');
document.getElementById('summary').classList.add('active');
console.log("Starting analysis for:", { file: file?.name, searchTerm, exampleFile });
try {
const response = await fetch(`${API_BASE_URL}/analyze`, {
method: 'POST',
body: formData
});
const contentType = response.headers.get("content-type");
if (!response.ok) {
if (contentType && contentType.includes("application/json")) {
const errorData = await response.json();
throw new Error(errorData.detail || 'Analysis failed');
} else {
const errorText = await response.text();
console.error("Backend Error (Non-JSON):", errorText);
throw new Error(`Server Error (${response.status}). The backend might still be starting up or is misconfigured.`);
}
}
if (!contentType || !contentType.includes("application/json")) {
throw new Error("Invalid response from server. Expected JSON but received something else. Check if the Backend URL is correct.");
}
const data = await response.json();
console.log("Analysis data received:", data);
try {
renderResults(data);
} catch (renderError) {
console.error("Error in renderResults:", renderError);
// Continue anyway to show the results area even if some charts fail
}
console.log("Transitioning UI: hiding input, showing results");
// Hide input section and show results
inputSection.classList.add('hidden');
resultsArea.classList.remove('hidden');
window.scrollTo({ top: 0, behavior: 'smooth' });
} catch (error) {
console.error("Analysis error:", error);
alert('Error: ' + error.message);
} finally {
analyzeBtn.disabled = false;
btnText.textContent = 'Analyze Manifesto';
spinner.classList.add('hidden');
}
}
});
// Show input form again (back button)
function showInputForm() {
document.querySelector('.input-section').classList.remove('hidden');
document.getElementById('resultsArea').classList.add('hidden');
window.scrollTo({ top: 0, behavior: 'smooth' });
}
function renderResults(data) {
// 1. Text Content (Markdown)
document.getElementById('summaryContent').innerHTML = marked.parse(data.summary);
document.getElementById('searchContent').innerHTML = marked.parse(data.search_result);
// 2. Topics Grid
const topicsContent = document.getElementById('topicsContent');
topicsContent.innerHTML = '';
// Sort topics by score
const sortedTopics = Object.entries(data.topics)
.filter(([key]) => key !== 'no_data' && key !== 'error' && key !== 'no_content' && key !== 'no_tokens')
.sort((a, b) => b[1] - a[1]);
sortedTopics.forEach(([topic, score]) => {
const tag = document.createElement('div');
tag.className = 'topic-tag';
// Normalize score display
const displayScore = (score * 100).toFixed(1);
tag.innerHTML = `<span class="topic-name">${topic}</span><span class="topic-score">Relevance: ${displayScore}</span>`;
topicsContent.appendChild(tag);
});
// Destroy existing charts
Object.values(charts).forEach(chart => {
try { chart.destroy(); } catch(e) {}
});
charts = {};
// 3. Sentiment & Subjectivity Charts
try {
renderBarChart('sentimentChart', 'Polarity', data.sentiment.polarity, -1, 1,
data.sentiment.polarity > 0 ? '#4CAF50' : data.sentiment.polarity < 0 ? '#F44336' : '#9E9E9E');
} catch (e) { console.error("Sentiment chart failed:", e); }
try {
renderBarChart('subjectivityChart', 'Subjectivity', data.sentiment.subjectivity, 0, 1,
data.sentiment.subjectivity > 0.5 ? '#B667F1' : '#42A5F5');
} catch (e) { console.error("Subjectivity chart failed:", e); }
// 4. Word Cloud
try {
renderWordCloud('wordCloudChart', data.word_cloud_freq);
} catch (e) { console.error("Word cloud failed:", e); }
// 5. Frequency Chart
try {
renderFrequencyChart('frequencyChart', sortedTopics);
} catch (e) { console.error("Frequency chart failed:", e); }
// 6. Dispersion Plot
try {
renderDispersionPlot('dispersionChart', data.dispersion, data.total_tokens);
} catch (e) { console.error("Dispersion plot failed:", e); }
}
function renderBarChart(canvasId, label, value, min, max, color) {
const ctx = document.getElementById(canvasId).getContext('2d');
charts[canvasId] = new Chart(ctx, {
type: 'bar',
data: {
labels: [label],
datasets: [{
label: 'Score',
data: [value],
backgroundColor: color,
borderRadius: 5
}]
},
options: {
indexAxis: 'y',
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false },
tooltip: { callbacks: { label: (ctx) => `Score: ${ctx.raw.toFixed(3)}` } }
},
scales: {
x: { min: min, max: max }
}
}
});
}
function renderWordCloud(canvasId, freqDict) {
if (!freqDict || Object.keys(freqDict).length === 0) return;
const ctx = document.getElementById(canvasId).getContext('2d');
// Format data for chartjs-wordcloud
// Filter out any invalid entries and limit to top 50 for stability
const filteredEntries = Object.entries(freqDict)
.filter(([word, freq]) => word && freq > 0)
.slice(0, 50);
const words = filteredEntries.map(e => e[0]);
const frequencies = filteredEntries.map(e => e[1]);
if (words.length === 0) return;
// Scale frequencies for better sizing
const maxFreq = Math.max(...frequencies);
const scaledFrequencies = frequencies.map(f => (f / maxFreq) * 40 + 10); // Min 10px, Max 50px
charts[canvasId] = new Chart(ctx, {
type: 'wordCloud',
data: {
labels: words,
datasets: [{
label: 'Word Cloud',
data: scaledFrequencies,
color: () => `hsl(${Math.random() * 360}, 70%, 60%)` // Random vibrant colors
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: false } }
}
});
}
function renderFrequencyChart(canvasId, sortedTopics) {
const ctx = document.getElementById(canvasId).getContext('2d');
// sortedTopics is an array of [word, score]
const words = sortedTopics.slice(0, 15).map(item => item[0]);
const scores = sortedTopics.slice(0, 15).map(item => item[1]);
charts[canvasId] = new Chart(ctx, {
type: 'bar',
data: {
labels: words,
datasets: [{
label: 'Relevance Score',
data: scores,
backgroundColor: '#4F46E5',
borderRadius: 4
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: {
y: { beginAtZero: true }
}
}
});
}
function renderDispersionPlot(canvasId, dispersionData, totalTokens) {
const ctx = document.getElementById(canvasId).getContext('2d');
const datasets = [];
const words = Object.keys(dispersionData);
const colors = ['#4F46E5', '#F59E0B', '#10B981', '#EC4899', '#8B5CF6'];
words.forEach((word, index) => {
// Create scatter points
const points = dispersionData[word].map(offset => ({
x: offset,
y: index + 1 // Offset Y by word index
}));
datasets.push({
label: word,
data: points,
backgroundColor: colors[index % colors.length],
pointRadius: 3,
pointHoverRadius: 5,
pointStyle: 'rect' // Use small rectangles like a barcode
});
});
charts[canvasId] = new Chart(ctx, {
type: 'scatter',
data: { datasets: datasets },
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
tooltip: {
callbacks: {
label: (ctx) => `Word: ${ctx.dataset.label}, Position: ${ctx.raw.x}`
}
}
},
scales: {
x: {
title: { display: true, text: 'Position in Text' },
min: 0,
max: totalTokens > 0 ? totalTokens : undefined
},
y: {
title: { display: false },
min: 0,
max: words.length + 1,
ticks: {
stepSize: 1,
callback: function(value) {
if (value > 0 && value <= words.length) {
return words[value - 1];
}
return '';
}
}
}
}
}
});
}
|