-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
701 lines (617 loc) · 23.1 KB
/
script.js
File metadata and controls
701 lines (617 loc) · 23.1 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
// Sample comments data
const sampleComments = [
{
id: '1',
text: 'Loved this vlog, especially the editing part! The transitions were smooth and kept me engaged throughout.',
author: 'Sarah_Creates',
timestamp: '2 hours ago',
platform: 'youtube'
},
{
id: '2',
text: 'You\'re so dumb, stop making videos! Nobody wants to watch this garbage.',
author: 'ToxicTroll123',
timestamp: '3 hours ago',
platform: 'youtube'
},
{
id: '3',
text: 'Follow me for free giveaways!! Link in bio 🎁🎁 #freebie #giveaway',
author: 'SpamAccount99',
timestamp: '1 hour ago',
platform: 'instagram'
},
{
id: '4',
text: 'Nice bro, check out my channel plz 🙏 I make similar content, would appreciate the support!',
author: 'NewCreator_Hindi',
timestamp: '4 hours ago',
platform: 'youtube'
},
{
id: '5',
text: 'This video helped me understand finance better! Thank you for explaining compound interest so clearly.',
author: 'LearnerMike',
timestamp: '5 hours ago',
platform: 'youtube'
},
{
id: '6',
text: 'The video was okay, but audio quality was poor. Hard to hear you in some parts.',
author: 'HonestViewer',
timestamp: '6 hours ago',
platform: 'youtube'
},
{
id: '7',
text: 'Try using a mic next time for better audio. Maybe consider the Blue Yeti or similar USB mics.',
author: 'TechHelper',
timestamp: '7 hours ago',
platform: 'youtube'
},
{
id: '8',
text: 'Amazing content as always! Keep up the great work 💪',
author: 'FaithfulFan',
timestamp: '8 hours ago',
platform: 'instagram'
},
{
id: '9',
text: 'First! 🥇',
author: 'QuickCommenter',
timestamp: '30 minutes ago',
platform: 'youtube'
},
{
id: '10',
text: 'Could you make a video about investment strategies for beginners? Would be really helpful!',
author: 'AspiringInvestor',
timestamp: '2 days ago',
platform: 'youtube'
}
];
// Analysis steps configuration
const analysisSteps = [
{
id: 1,
title: 'Toxic Comment Detection',
description: 'Filtering harmful and abusive content',
icon: 'fas fa-shield-alt',
status: 'pending'
},
{
id: 2,
title: 'Spam Detection',
description: 'Removing promotional and irrelevant comments',
icon: 'fas fa-exclamation-triangle',
status: 'pending'
},
{
id: 3,
title: 'Sentiment Analysis',
description: 'Analyzing positive, negative, and neutral sentiment',
icon: 'fas fa-heart',
status: 'pending'
},
{
id: 4,
title: 'Type Classification',
description: 'Categorizing feedback vs suggestions',
icon: 'fas fa-lightbulb',
status: 'pending'
}
];
// Global state
let processedComments = [];
let isProcessing = false;
let currentSteps = [...analysisSteps];
// DOM elements
const tabButtons = document.querySelectorAll('.nav-btn');
const tabContents = document.querySelectorAll('.tab-content');
const commentsInput = document.getElementById('comments-input');
const analyzeCustomBtn = document.getElementById('analyze-custom-btn');
const analyzeSampleBtn = document.getElementById('analyze-sample-btn');
const resetBtn = document.getElementById('reset-btn');
const processingSection = document.getElementById('processing-section');
const stepsList = document.getElementById('steps-list');
const commentsList = document.getElementById('comments-list');
const commentCount = document.getElementById('comment-count');
const processingIndicator = document.getElementById('processing-indicator');
const analyticsContent = document.getElementById('analytics-content');
// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
initializeEventListeners();
renderSteps();
renderAnalytics();
});
function initializeEventListeners() {
// Tab switching
tabButtons.forEach(button => {
button.addEventListener('click', () => switchTab(button.dataset.tab));
});
// Button event listeners
analyzeCustomBtn.addEventListener('click', handleAnalyzeCustom);
analyzeSampleBtn.addEventListener('click', handleAnalyzeSample);
resetBtn.addEventListener('click', handleReset);
}
function switchTab(tabName) {
// Update button states
tabButtons.forEach(btn => {
btn.classList.toggle('active', btn.dataset.tab === tabName);
});
// Update tab content visibility
tabContents.forEach(content => {
content.classList.toggle('active', content.id === `${tabName}-tab`);
});
// Refresh analytics if switching to analytics tab
if (tabName === 'analytics') {
renderAnalytics();
}
}
async function handleAnalyzeCustom() {
const inputText = commentsInput.value.trim();
if (!inputText) return;
const customComments = inputText.split('\n')
.filter(line => line.trim())
.map((text, index) => ({
id: `custom-${index}`,
text: text.trim(),
author: `User${index + 1}`,
timestamp: 'Just now',
platform: 'youtube'
}));
await analyzeComments(customComments);
}
async function handleAnalyzeSample() {
await analyzeComments(sampleComments);
}
function handleReset() {
processedComments = [];
currentSteps = analysisSteps.map(step => ({ ...step, status: 'pending' }));
isProcessing = false;
commentsInput.value = '';
processingSection.classList.add('hidden');
renderSteps();
renderComments();
renderAnalytics();
updateButtonStates();
}
async function analyzeComments(comments) {
if (isProcessing) return;
isProcessing = true;
processedComments = [];
currentSteps = analysisSteps.map(step => ({ ...step, status: 'pending' }));
processingSection.classList.remove('hidden');
updateButtonStates();
showProcessingIndicator();
for (let i = 0; i < comments.length; i++) {
const comment = comments[i];
const processedComment = await processComment(comment);
processedComments.push(processedComment);
renderComments();
updateCommentCount();
}
isProcessing = false;
hideProcessingIndicator();
updateButtonStates();
renderAnalytics();
}
async function processComment(comment) {
// Step 1: Toxic Comment Detection
updateStepStatus(1, 'processing');
await sleep(300);
const toxicAnalysis = analyzeToxicity(comment.text);
updateStepStatus(1, 'completed');
if (toxicAnalysis.isToxic) {
updateStepStatus(2, 'skipped');
updateStepStatus(3, 'skipped');
updateStepStatus(4, 'skipped');
return {
...comment,
isProcessed: true,
analysis: {
isToxic: true,
isSpam: false,
sentiment: 'neutral',
type: 'feedback',
confidence: toxicAnalysis.confidence
}
};
}
// Step 2: Spam Detection
updateStepStatus(2, 'processing');
await sleep(300);
const spamAnalysis = analyzeSpam(comment.text);
updateStepStatus(2, 'completed');
if (spamAnalysis.isSpam) {
updateStepStatus(3, 'skipped');
updateStepStatus(4, 'skipped');
return {
...comment,
isProcessed: true,
analysis: {
isToxic: false,
isSpam: true,
sentiment: 'neutral',
type: 'feedback',
confidence: spamAnalysis.confidence
}
};
}
// Step 3: Sentiment Analysis
updateStepStatus(3, 'processing');
await sleep(300);
const sentimentAnalysis = analyzeSentiment(comment.text);
updateStepStatus(3, 'completed');
// Step 4: Type Classification
updateStepStatus(4, 'processing');
await sleep(300);
const typeAnalysis = analyzeType(comment.text);
updateStepStatus(4, 'completed');
return {
...comment,
isProcessed: true,
analysis: {
isToxic: false,
isSpam: false,
sentiment: sentimentAnalysis.sentiment,
type: typeAnalysis.type,
confidence: Math.min(sentimentAnalysis.confidence, typeAnalysis.confidence)
}
};
}
// Analysis functions (mock ML implementations)
function analyzeToxicity(text) {
const toxicKeywords = ['dumb', 'stupid', 'garbage', 'hate', 'terrible', 'awful', 'worst'];
const lowerText = text.toLowerCase();
const toxicScore = toxicKeywords.reduce((score, keyword) => {
return lowerText.includes(keyword) ? score + 0.3 : score;
}, 0);
return {
isToxic: toxicScore > 0.2,
confidence: Math.min(0.95, 0.6 + toxicScore)
};
}
function analyzeSpam(text) {
const spamKeywords = ['follow me', 'check out my', 'link in bio', 'giveaway', 'free', 'subscribe', 'plz', 'first!'];
const lowerText = text.toLowerCase();
let spamScore = spamKeywords.reduce((score, keyword) => {
return lowerText.includes(keyword) ? score + 0.25 : score;
}, 0);
// Check for excessive emojis or caps
const emojiCount = (text.match(/[\u{1f300}-\u{1f6ff}]|[\u{2600}-\u{27bf}]/gu) || []).length;
const capsRatio = (text.match(/[A-Z]/g) || []).length / text.length;
if (emojiCount > 3) spamScore += 0.2;
if (capsRatio > 0.5) spamScore += 0.15;
return {
isSpam: spamScore > 0.3,
confidence: Math.min(0.95, 0.5 + spamScore)
};
}
function analyzeSentiment(text) {
const positiveKeywords = ['love', 'great', 'amazing', 'awesome', 'good', 'nice', 'helped', 'thank', 'appreciate', 'excellent'];
const negativeKeywords = ['bad', 'poor', 'terrible', 'awful', 'hate', 'worst', 'boring', 'disappointing'];
const lowerText = text.toLowerCase();
const positiveScore = positiveKeywords.reduce((score, keyword) => {
return lowerText.includes(keyword) ? score + 1 : score;
}, 0);
const negativeScore = negativeKeywords.reduce((score, keyword) => {
return lowerText.includes(keyword) ? score + 1 : score;
}, 0);
let sentiment = 'neutral';
let confidence = 0.6;
if (positiveScore > negativeScore) {
sentiment = 'positive';
confidence = Math.min(0.95, 0.6 + (positiveScore * 0.1));
} else if (negativeScore > positiveScore) {
sentiment = 'negative';
confidence = Math.min(0.95, 0.6 + (negativeScore * 0.1));
}
return { sentiment, confidence };
}
function analyzeType(text) {
const suggestionKeywords = ['try', 'should', 'could', 'maybe', 'consider', 'suggest', 'recommend', 'next time', 'would be better'];
const feedbackKeywords = ['great', 'good', 'nice', 'love', 'like', 'keep up', 'amazing', 'awesome'];
const lowerText = text.toLowerCase();
const suggestionScore = suggestionKeywords.reduce((score, keyword) => {
return lowerText.includes(keyword) ? score + 1 : score;
}, 0);
const feedbackScore = feedbackKeywords.reduce((score, keyword) => {
return lowerText.includes(keyword) ? score + 1 : score;
}, 0);
const type = suggestionScore > feedbackScore ? 'suggestion' : 'feedback';
const confidence = Math.min(0.95, 0.6 + (Math.max(suggestionScore, feedbackScore) * 0.1));
return { type, confidence };
}
// UI Rendering functions
function renderSteps() {
stepsList.innerHTML = currentSteps.map(step => `
<div class="step-item">
<div class="step-icon ${step.status}">
${step.status === 'processing' ?
'<div class="spinner"></div>' :
`<i class="${step.icon}"></i>`
}
</div>
<div class="step-content">
<h4>${step.title}</h4>
<p>${step.description}</p>
</div>
<div class="step-status">
${getStatusIcon(step.status)}
</div>
</div>
`).join('');
}
function renderComments() {
if (processedComments.length === 0) {
commentsList.innerHTML = `
<div class="empty-state">
<i class="fas fa-comment-slash"></i>
<p>No comments processed yet. Upload some comments to get started!</p>
</div>
`;
return;
}
commentsList.innerHTML = processedComments.map(comment => `
<div class="comment-card">
<div class="comment-header">
<div class="comment-author">
<strong>${comment.author}</strong>
<i class="platform-icon ${comment.platform} ${getPlatformIcon(comment.platform)}"></i>
</div>
<div class="comment-meta">
<span class="comment-timestamp">${comment.timestamp}</span>
<div class="status-badge ${getStatusClass(comment.analysis)}">
<i class="${getStatusIcon(comment.analysis)}"></i>
<span>${getStatusLabel(comment.analysis)}</span>
</div>
</div>
</div>
<div class="comment-text">${comment.text}</div>
${renderCommentAnalysis(comment.analysis)}
</div>
`).join('');
}
function renderCommentAnalysis(analysis) {
if (!analysis || analysis.isToxic || analysis.isSpam) {
return '';
}
return `
<div class="comment-analysis">
<div class="analysis-tags">
<div class="analysis-tag">
<i class="${getSentimentIcon(analysis.sentiment)}"></i>
<span>${analysis.sentiment}</span>
</div>
<div class="analysis-tag">
<i class="${getTypeIcon(analysis.type)}"></i>
<span>${analysis.type}</span>
</div>
</div>
<div class="confidence">
${Math.round(analysis.confidence * 100)}% confidence
</div>
</div>
`;
}
function renderAnalytics() {
const analytics = getAnalytics();
analyticsContent.innerHTML = `
<div class="stats-grid">
<div class="stat-card">
<div class="stat-card-content">
<div class="stat-info">
<h3>Total Comments</h3>
<div class="value">${analytics.totalComments}</div>
<div class="subtitle">Comments processed</div>
</div>
<div class="stat-icon blue">
<i class="fas fa-comment"></i>
</div>
</div>
</div>
<div class="stat-card">
<div class="stat-card-content">
<div class="stat-info">
<h3>Engagement Rate</h3>
<div class="value">${getEngagementRate(analytics)}%</div>
<div class="subtitle">Valid vs total comments</div>
</div>
<div class="stat-icon green">
<i class="fas fa-chart-line"></i>
</div>
</div>
</div>
<div class="stat-card">
<div class="stat-card-content">
<div class="stat-info">
<h3>Toxic Comments</h3>
<div class="value">${analytics.toxicComments}</div>
<div class="subtitle">Harmful content filtered</div>
</div>
<div class="stat-icon red">
<i class="fas fa-shield-alt"></i>
</div>
</div>
</div>
<div class="stat-card">
<div class="stat-card-content">
<div class="stat-info">
<h3>Spam Filtered</h3>
<div class="value">${analytics.spamComments}</div>
<div class="subtitle">Irrelevant content removed</div>
</div>
<div class="stat-icon orange">
<i class="fas fa-exclamation-triangle"></i>
</div>
</div>
</div>
</div>
<div class="analytics-details">
<div class="detail-card">
<div class="detail-header">
<i class="fas fa-heart" style="color: #ec4899;"></i>
<h3>Sentiment Analysis</h3>
</div>
<div class="breakdown-item">
<div class="breakdown-label">
<div class="color-dot green"></div>
<span>Positive</span>
</div>
<div class="breakdown-value">
${analytics.sentimentBreakdown.positive} (${getPositivityRate(analytics)}%)
</div>
</div>
<div class="breakdown-item">
<div class="breakdown-label">
<div class="color-dot red"></div>
<span>Negative</span>
</div>
<div class="breakdown-value">${analytics.sentimentBreakdown.negative}</div>
</div>
<div class="breakdown-item">
<div class="breakdown-label">
<div class="color-dot gray"></div>
<span>Neutral</span>
</div>
<div class="breakdown-value">${analytics.sentimentBreakdown.neutral}</div>
</div>
</div>
<div class="detail-card">
<div class="detail-header">
<i class="fas fa-lightbulb" style="color: #7c3aed;"></i>
<h3>Comment Types</h3>
</div>
<div class="breakdown-item">
<div class="breakdown-label">
<i class="fas fa-comment" style="color: #3b82f6;"></i>
<span>Feedback</span>
</div>
<div class="breakdown-value">${analytics.typeBreakdown.feedback}</div>
</div>
<div class="breakdown-item">
<div class="breakdown-label">
<i class="fas fa-lightbulb" style="color: #7c3aed;"></i>
<span>Suggestions</span>
</div>
<div class="breakdown-value">${analytics.typeBreakdown.suggestions}</div>
</div>
${analytics.typeBreakdown.suggestions > 0 ? `
<div class="insight-box">
<p>💡 You have ${analytics.typeBreakdown.suggestions} actionable suggestions from your audience!</p>
</div>
` : ''}
</div>
</div>
`;
}
// Utility functions
function updateStepStatus(stepId, status) {
currentSteps = currentSteps.map(step =>
step.id === stepId ? { ...step, status } : step
);
renderSteps();
}
function updateCommentCount() {
commentCount.textContent = processedComments.length;
}
function showProcessingIndicator() {
processingIndicator.classList.remove('hidden');
}
function hideProcessingIndicator() {
processingIndicator.classList.add('hidden');
}
function updateButtonStates() {
const buttons = [analyzeCustomBtn, analyzeSampleBtn, resetBtn];
buttons.forEach(btn => {
btn.disabled = isProcessing;
});
}
function getAnalytics() {
const totalComments = processedComments.length;
const toxicComments = processedComments.filter(c => c.analysis?.isToxic).length;
const spamComments = processedComments.filter(c => c.analysis?.isSpam).length;
const validComments = processedComments.filter(c => !c.analysis?.isToxic && !c.analysis?.isSpam).length;
const validCommentsWithAnalysis = processedComments.filter(c =>
!c.analysis?.isToxic && !c.analysis?.isSpam && c.analysis
);
const sentimentBreakdown = {
positive: validCommentsWithAnalysis.filter(c => c.analysis?.sentiment === 'positive').length,
negative: validCommentsWithAnalysis.filter(c => c.analysis?.sentiment === 'negative').length,
neutral: validCommentsWithAnalysis.filter(c => c.analysis?.sentiment === 'neutral').length,
};
const typeBreakdown = {
feedback: validCommentsWithAnalysis.filter(c => c.analysis?.type === 'feedback').length,
suggestions: validCommentsWithAnalysis.filter(c => c.analysis?.type === 'suggestion').length,
};
return {
totalComments,
toxicComments,
spamComments,
validComments,
sentimentBreakdown,
typeBreakdown
};
}
function getEngagementRate(analytics) {
if (analytics.totalComments === 0) return 0;
return Math.round((analytics.validComments / analytics.totalComments) * 100);
}
function getPositivityRate(analytics) {
const validComments = analytics.sentimentBreakdown.positive +
analytics.sentimentBreakdown.negative +
analytics.sentimentBreakdown.neutral;
if (validComments === 0) return 0;
return Math.round((analytics.sentimentBreakdown.positive / validComments) * 100);
}
function getPlatformIcon(platform) {
switch (platform) {
case 'youtube': return 'fab fa-youtube';
case 'instagram': return 'fab fa-instagram';
case 'facebook': return 'fab fa-facebook';
default: return 'fas fa-comment';
}
}
function getStatusClass(analysis) {
if (!analysis) return 'pending';
if (analysis.isToxic) return 'toxic';
if (analysis.isSpam) return 'spam';
return 'valid';
}
function getStatusLabel(analysis) {
if (!analysis) return 'Pending';
if (analysis.isToxic) return 'Toxic';
if (analysis.isSpam) return 'Spam';
return 'Valid';
}
function getStatusIcon(status) {
if (typeof status === 'string') {
switch (status) {
case 'completed': return '<i class="fas fa-check-circle" style="color: #10b981;"></i>';
case 'processing': return '<div class="spinner"></div>';
case 'skipped': return '<i class="fas fa-circle" style="color: #9ca3af;"></i>';
default: return '<i class="fas fa-circle" style="color: #e5e7eb;"></i>';
}
} else {
// Analysis object
if (!status) return 'fas fa-clock';
if (status.isToxic) return 'fas fa-shield-alt';
if (status.isSpam) return 'fas fa-exclamation-triangle';
return 'fas fa-heart';
}
}
function getSentimentIcon(sentiment) {
switch (sentiment) {
case 'positive': return 'fas fa-smile';
case 'negative': return 'fas fa-frown';
default: return 'fas fa-meh';
}
}
function getTypeIcon(type) {
return type === 'suggestion' ? 'fas fa-lightbulb' : 'fas fa-comment';
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}