I'll create a sentiment analysis web application based on your requirements. Here's the complete implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sentiment Analysis Tool</title>
<style>
:root {
--primary-color: #4a6fa5;
--positive-color: #4caf50;
--negative-color: #f44336;
--neutral-color: #ff9800;
--light-bg: #f5f7fa;
--dark-text: #333;
--border-radius: 8px;
--box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background-color: var(--light-bg);
color: var(--dark-text);
line-height: 1.6;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
header {
text-align: center;
margin-bottom: 30px;
}
h1 {
color: var(--primary-color);
margin-bottom: 10px;
}
.upload-section {
background: white;
border-radius: var(--border-radius);
padding: 30px;
box-shadow: var(--box-shadow);
margin-bottom: 30px;
transition: opacity 0.3s ease;
}
.upload-section.disabled {
opacity: 0.5;
pointer-events: none;
}
.dropzone {
border: 2px dashed var(--primary-color);
border-radius: var(--border-radius);
padding: 40px;
text-align: center;
cursor: pointer;
transition: background-color 0.3s ease;
}
.dropzone:hover {
background-color: rgba(74, 111, 165, 0.05);
}
.dropzone p {
margin-bottom: 15px;
}
.file-types {
font-size: 0.9rem;
color: #666;
margin-top: 10px;
}
.error-message {
color: var(--negative-color);
margin-top: 15px;
font-weight: bold;
display: none;
}
.loading {
display: none;
text-align: center;
margin: 20px 0;
}
.spinner {
border: 4px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
border-top: 4px solid var(--primary-color);
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 0 auto 15px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.results-section {
display: none;
background: white;
border-radius: var(--border-radius);
padding: 30px;
box-shadow: var(--box-shadow);
margin-bottom: 30px;
}
.stats-container {
display: flex;
justify-content: space-around;
margin-bottom: 30px;
flex-wrap: wrap;
}
.stat-box {
text-align: center;
padding: 15px;
border-radius: var(--border-radius);
min-width: 150px;
margin: 10px;
box-shadow: var(--box-shadow);
}
.positive {
background-color: rgba(76, 175, 80, 0.1);
border-left: 4px solid var(--positive-color);
}
.negative {
background-color: rgba(244, 67, 54, 0.1);
border-left: 4px solid var(--negative-color);
}
.neutral {
background-color: rgba(255, 152, 0, 0.1);
border-left: 4px solid var(--neutral-color);
}
.text-positive {
background-color: rgba(76, 175, 80, 0.2);
}
.text-negative {
background-color: rgba(244, 67, 54, 0.2);
}
.text-neutral {
background-color: rgba(255, 152, 0, 0.2);
}
.analyzed-content {
max-height: 500px;
overflow-y: auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: var(--border-radius);
line-height: 1.8;
margin-bottom: 20px;
}
.btn {
background-color: var(--primary-color);
color: white;
border: none;
padding: 12px 24px;
border-radius: var(--border-radius);
cursor: pointer;
font-size: 1rem;
transition: background-color 0.3s ease;
}
.btn:hover {
background-color: #3a5a8c;
}
.btn:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.download-btn {
display: block;
margin: 0 auto;
}
@media (max-width: 768px) {
.stats-container {
flex-direction: column;
align-items: center;
}
.stat-box {
width: 100%;
max-width: 300px;
}
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>Sentiment Analysis Tool</h1>
<p>Upload your text data for sentiment analysis</p>
</header>
<section class="upload-section" id="uploadSection">
<div class="dropzone" id="dropzone">
<p>Drag & drop your file here</p>
<p>or</p>
<button class="btn" id="browseBtn">Browse Files</button>
<input type="file" id="fileInput" accept=".csv,.xlsx,.json" style="display: none;">
<p class="file-types">Supported file types: .csv, .xlsx, .json</p>
</div>
<div class="error-message" id="errorMessage"></div>
</section>
<div class="loading" id="loadingIndicator">
<div class="spinner"></div>
<p>Analyzing your data...</p>
</div>
<section class="results-section" id="resultsSection">
<h2>Analysis Results</h2>
<div class="stats-container">
<div class="stat-box positive">
<h3>Positive</h3>
<p id="positiveCount">0</p>
</div>
<div class="stat-box neutral">
<h3>Neutral</h3>
<p id="neutralCount">0</p>
</div>
<div class="stat-box negative">
<h3>Negative</h3>
<p id="negativeCount">0</p>
</div>
</div>
<div class="analyzed-content" id="analyzedContent"></div>
<button class="btn download-btn" id="downloadBtn">Download Analysis</button>
</section>
</div>
<!-- Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.2/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sentiment@5.0.2/build/sentiment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script>
// Use strict mode for better error catching and to avoid common JS pitfalls
'use strict';
// Create a self-executing function to avoid polluting the global namespace
(() => {
// DOM Elements
const elements = Object.freeze({
dropzone: document.getElementById('dropzone'),
fileInput: document.getElementById('fileInput'),
browseBtn: document.getElementById('browseBtn'),
uploadSection: document.getElementById('uploadSection'),
errorMessage: document.getElementById('errorMessage'),
loadingIndicator: document.getElementById('loadingIndicator'),
resultsSection: document.getElementById('resultsSection'),
analyzedContent: document.getElementById('analyzedContent'),
positiveCount: document.getElementById('positiveCount'),
neutralCount: document.getElementById('neutralCount'),
negativeCount: document.getElementById('negativeCount'),
downloadBtn: document.getElementById('downloadBtn')
});
// State management
const state = {
isProcessing: false,
analysisResults: {
positive: 0,
neutral: 0,
negative: 0,
data: []
},
// Reset analysis results
resetResults() {
this.analysisResults.positive = 0;
this.analysisResults.neutral = 0;
this.analysisResults.negative = 0;
this.analysisResults.data = [];
}
};
// Utility functions
const utils = {
// Show error message
showError(message) {
elements.errorMessage.textContent = message;
elements.errorMessage.style.display = 'block';
// Hide error after 5 seconds
setTimeout(() => {
elements.errorMessage.style.display = 'none';
}, 5000);
},
// Toggle loading state
toggleLoading(isLoading) {
state.isProcessing = isLoading;
elements.uploadSection.classList.toggle('disabled', isLoading);
elements.loadingIndicator.style.display = isLoading ? 'block' : 'none';
},
// Show results section
showResults() {
elements.resultsSection.style.display = 'block';
elements.positiveCount.textContent = state.analysisResults.positive;
elements.neutralCount.textContent = state.analysisResults.neutral;
elements.negativeCount.textContent = state.analysisResults.negative;
},
// Validate file type
isValidFileType(file) {
const validTypes = [
'text/csv',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/json'
];
return validTypes.includes(file.type) ||
/\.(csv|xlsx|json)$/i.test(file.name);
},
// Debounce function to prevent multiple rapid executions
debounce(func, wait = 300) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
};
// File processing functions
const fileProcessor = {
// Process the uploaded file based on its type
async processFile(file) {
try {
if (!utils.isValidFileType(file)) {
throw new Error('Invalid file type. Please upload a CSV, XLSX, or JSON file.');
}
utils.toggleLoading(true);
state.resetResults();
let textData = [];
// Process based on file extension
if (/\.csv$/i.test(file.name)) {
textData = await this.parseCSV(file);
} else if (/\.xlsx$/i.test(file.name)) {
textData = await this.parseExcel(file);
} else if (/\.json$/i.test(file.name)) {
textData = await this.parseJSON(file);
}
if (textData.length === 0) {
throw new Error('No text data found in the file.');
}
// Analyze the text data
await sentimentAnalyzer.analyzeTexts(textData);
// Display results
this.displayResults();
utils.toggleLoading(false);
utils.showResults();
} catch (error) {
utils.toggleLoading(false);
utils.showError(error.message);
console.error('Error processing file:', error);
}
},
// Parse CSV file
parseCSV(file) {
return new Promise((resolve, reject) => {
Papa.parse(file, {
complete: (results) => {
try {
const textData = this.extractTextFromParsedData(results.data);
resolve(textData);
} catch (error) {
reject(error);
}
},
error: (error) => {
reject(new Error(`Error parsing CSV: ${error.message}`));
},
header: true,
skipEmptyLines: true
});
});
},
// Parse Excel file
async parseExcel(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
try {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
// Get first sheet
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
// Convert to JSON
const jsonData = XLSX.utils.sheet_to_json(worksheet);
const textData = this.extractTextFromParsedData(jsonData);
resolve(textData);
} catch (error) {
reject(new Error(`Error parsing Excel: ${error.message}`));
}
};
reader.onerror = () => {
reject(new Error('Error reading Excel file'));
};
reader.readAsArrayBuffer(file);
});
},
// Parse JSON file
async parseJSON(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
try {
const jsonData = JSON.parse(e.target.result);
const textData = this.extractTextFromParsedData(
Array.isArray(jsonData) ? jsonData : [jsonData]