manhteky123
Initial commit: Vietnamese Sentiment Analysis App with Flask and Transformers
244aaa1
// Khởi tạo khi trang load
document.addEventListener('DOMContentLoaded', function() {
loadHistory();
// Event listeners
document.getElementById('analyzeBtn').addEventListener('click', analyzeSentiment);
document.getElementById('refreshBtn').addEventListener('click', loadHistory);
document.querySelector('.popup-close').addEventListener('click', closePopup);
// Enter key để phân tích
document.getElementById('inputText').addEventListener('keypress', function(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
analyzeSentiment();
}
});
});
// Hàm phân loại cảm xúc
async function analyzeSentiment() {
const inputText = document.getElementById('inputText').value.trim();
const loading = document.getElementById('loading');
const analyzeBtn = document.getElementById('analyzeBtn');
// Validate input
if (!inputText) {
showPopup('Vui lòng nhập câu cần phân loại!');
return;
}
if (inputText.length < 5) {
showPopup('Câu quá ngắn! Vui lòng nhập ít nhất 5 ký tự.');
return;
}
// Show loading
loading.style.display = 'block';
analyzeBtn.disabled = true;
try {
const response = await fetch('/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ text: inputText })
});
const data = await response.json();
if (data.success) {
displayResult(data.result);
loadHistory(); // Refresh history
document.getElementById('inputText').value = ''; // Clear input
} else {
showPopup(data.error || 'Đã xảy ra lỗi khi phân loại');
}
} catch (error) {
showPopup('Không thể kết nối đến server. Vui lòng thử lại!');
console.error('Error:', error);
} finally {
loading.style.display = 'none';
analyzeBtn.disabled = false;
}
}
// Hiển thị kết quả phân loại
function displayResult(result) {
const resultSection = document.getElementById('resultSection');
const sentimentBadge = document.getElementById('sentimentBadge');
const analyzedText = document.getElementById('analyzedText');
const confidenceScore = document.getElementById('confidenceScore');
// Map sentiment to Vietnamese
const sentimentMap = {
'POSITIVE': { text: '😊 Tích cực', class: 'sentiment-positive' },
'NEGATIVE': { text: '😞 Tiêu cực', class: 'sentiment-negative' },
'NEUTRAL': { text: '😐 Trung tính', class: 'sentiment-neutral' }
};
const sentiment = sentimentMap[result.sentiment] || sentimentMap['NEUTRAL'];
// Update badge
sentimentBadge.textContent = sentiment.text;
sentimentBadge.className = 'sentiment-badge ' + sentiment.class;
// Update text
analyzedText.textContent = `"${result.text}"`;
// Update confidence
if (result.score) {
confidenceScore.textContent = `Độ tin cậy: ${(result.score * 100).toFixed(0)}%`;
} else {
confidenceScore.textContent = '';
}
// Show result section
resultSection.style.display = 'block';
// Scroll to result
resultSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
// Load lịch sử phân loại
async function loadHistory() {
const historyList = document.getElementById('historyList');
try {
const response = await fetch('/history');
const data = await response.json();
if (data.success && data.history.length > 0) {
historyList.innerHTML = data.history.map(item => createHistoryItem(item)).join('');
} else {
historyList.innerHTML = '<p class="empty-message">Chưa có lịch sử phân loại</p>';
}
} catch (error) {
console.error('Error loading history:', error);
historyList.innerHTML = '<p class="empty-message">Không thể tải lịch sử</p>';
}
}
// Tạo HTML cho item lịch sử
function createHistoryItem(item) {
const sentimentMap = {
'POSITIVE': { text: 'Tích cực', class: 'sentiment-positive' },
'NEGATIVE': { text: 'Tiêu cực', class: 'sentiment-negative' },
'NEUTRAL': { text: 'Trung tính', class: 'sentiment-neutral' }
};
const sentiment = sentimentMap[item.sentiment] || sentimentMap['NEUTRAL'];
return `
<div class="history-item">
<div class="history-item-header">
<span class="history-sentiment ${sentiment.class}">${sentiment.text}</span>
<span class="history-timestamp">${item.timestamp}</span>
</div>
<div class="history-text">${item.text}</div>
</div>
`;
}
// Hiển thị popup thông báo
function showPopup(message) {
const popup = document.getElementById('popup');
const popupMessage = document.getElementById('popupMessage');
popupMessage.textContent = message;
popup.style.display = 'flex';
// Auto close after 3 seconds
setTimeout(closePopup, 3000);
}
// Đóng popup
function closePopup() {
document.getElementById('popup').style.display = 'none';
}
// Close popup when clicking outside
window.addEventListener('click', function(e) {
const popup = document.getElementById('popup');
if (e.target === popup) {
closePopup();
}
});