Repository navigation
Expand file tree
/
Copy pathreact.js
More file actions
330 lines (304 loc) · 14 KB
/
Copy pathreact.js
File metadata and controls
330 lines (304 loc) · 14 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
import React, { useState, useEffect } from 'react';
import { Brain, AlertTriangle, Heart, Smile, Frown, Phone, MessageCircle } from 'lucide-react';
const BertSentimentAnalyzer = () => {
const [inputText, setInputText] = useState('');
const [analysis, setAnalysis] = useState(null);
const [isAnalyzing, setIsAnalyzing] = useState(false);
// Depression-related keywords with severity weights
const depressionKeywords = {
extreme: {
keywords: ['suicide', 'kill myself', 'end it all', 'no point living', 'better off dead', 'hopeless', 'worthless', 'hate myself', 'want to die', 'no way out'],
weight: 0.9
},
high: {
keywords: ['depressed', 'can\'t cope', 'overwhelming', 'unbearable', 'desperate', 'empty inside', 'meaningless', 'giving up', 'tired of living', 'broken'],
weight: 0.7
},
moderate: {
keywords: ['not feeling good', 'down', 'sad', 'low mood', 'unmotivated', 'tired', 'stressed', 'anxious', 'worried', 'upset', 'disappointed'],
weight: 0.4
},
mild: {
keywords: ['okay', 'alright', 'fine', 'neutral', 'average'],
weight: 0.2
}
};
const positiveKeywords = {
high: {
keywords: ['happy', 'joyful', 'excited', 'amazing', 'wonderful', 'fantastic', 'great', 'excellent', 'love', 'thrilled', 'ecstatic', 'blissful'],
weight: 0.1
},
moderate: {
keywords: ['good', 'nice', 'pleasant', 'content', 'satisfied', 'peaceful', 'calm', 'relaxed', 'hopeful'],
weight: 0.15
}
};
const analyzeText = async (text) => {
setIsAnalyzing(true);
// Simulate BERT processing delay
await new Promise(resolve => setTimeout(resolve, 1500));
const lowerText = text.toLowerCase();
let depressionScore = 0;
let sentiment = 'neutral';
let confidence = 0;
let triggeredKeywords = [];
let severity = 'normal';
// Check for depression indicators
Object.entries(depressionKeywords).forEach(([level, data]) => {
data.keywords.forEach(keyword => {
if (lowerText.includes(keyword)) {
depressionScore = Math.max(depressionScore, data.weight);
triggeredKeywords.push({ keyword, level, type: 'depression' });
}
});
});
// Check for positive indicators (reduces depression score)
Object.entries(positiveKeywords).forEach(([level, data]) => {
data.keywords.forEach(keyword => {
if (lowerText.includes(keyword)) {
depressionScore = Math.max(0, depressionScore - data.weight);
triggeredKeywords.push({ keyword, level, type: 'positive' });
}
});
});
// Determine severity and sentiment
if (depressionScore >= 0.8) {
severity = 'critical';
sentiment = 'extremely negative';
confidence = 0.95;
} else if (depressionScore >= 0.6) {
severity = 'high';
sentiment = 'very negative';
confidence = 0.85;
} else if (depressionScore >= 0.3) {
severity = 'moderate';
sentiment = 'negative';
confidence = 0.75;
} else if (depressionScore >= 0.1) {
severity = 'mild';
sentiment = 'slightly negative';
confidence = 0.65;
} else {
severity = 'normal';
sentiment = depressionScore === 0 ? 'neutral/positive' : 'positive';
confidence = 0.70;
}
// Additional context analysis
const wordCount = text.split(' ').length;
const exclamationCount = (text.match(/!/g) || []).length;
const questionCount = (text.match(/\?/g) || []).length;
setAnalysis({
originalText: text,
depressionLevel: Math.round(depressionScore * 100),
sentiment,
confidence: Math.round(confidence * 100),
severity,
triggeredKeywords,
metrics: {
wordCount,
exclamationCount,
questionCount,
textLength: text.length
},
timestamp: new Date().toLocaleString()
});
setIsAnalyzing(false);
};
const getSeverityColor = (severity) => {
switch (severity) {
case 'critical': return 'text-red-600 bg-red-50 border-red-200';
case 'high': return 'text-orange-600 bg-orange-50 border-orange-200';
case 'moderate': return 'text-yellow-600 bg-yellow-50 border-yellow-200';
case 'mild': return 'text-blue-600 bg-blue-50 border-blue-200';
default: return 'text-green-600 bg-green-50 border-green-200';
}
};
const getSeverityIcon = (severity) => {
switch (severity) {
case 'critical': return <AlertTriangle className="w-5 h-5 text-red-600" />;
case 'high': return <Frown className="w-5 h-5 text-orange-600" />;
case 'moderate': return <Frown className="w-5 h-5 text-yellow-600" />;
case 'mild': return <Smile className="w-5 h-5 text-blue-600" />;
default: return <Heart className="w-5 h-5 text-green-600" />;
}
};
return (
<div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-6">
<div className="max-w-4xl mx-auto">
{/* Header */}
<div className="text-center mb-8">
<div className="flex justify-center items-center gap-3 mb-4">
<Brain className="w-12 h-12 text-indigo-600" />
<h1 className="text-4xl font-bold text-gray-800">BERT Sentiment Analyzer</h1>
</div>
<p className="text-gray-600 text-lg">Advanced depression detection and sentiment analysis</p>
</div>
{/* Input Section */}
<div className="bg-white rounded-lg shadow-lg p-6 mb-6">
<label className="block text-gray-700 text-sm font-medium mb-3">
Enter your text for analysis:
</label>
<textarea
value={inputText}
onChange={(e) => setInputText(e.target.value)}
className="w-full p-4 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent resize-none"
rows="4"
placeholder="Share your thoughts, feelings, or any text you'd like to analyze..."
/>
<div className="flex justify-between items-center mt-4">
<span className="text-sm text-gray-500">{inputText.length} characters</span>
<button
onClick={() => analyzeText(inputText)}
disabled={!inputText.trim() || isAnalyzing}
className="px-6 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{isAnalyzing ? 'Analyzing...' : 'Analyze Text'}
</button>
</div>
</div>
{/* Loading */}
{isAnalyzing && (
<div className="bg-white rounded-lg shadow-lg p-8 text-center mb-6">
<Brain className="w-12 h-12 text-indigo-600 animate-pulse mx-auto mb-4" />
<p className="text-gray-600">Processing with BERT model...</p>
</div>
)}
{/* Analysis Results */}
{analysis && !isAnalyzing && (
<div className="space-y-6">
{/* Main Results */}
<div className="bg-white rounded-lg shadow-lg p-6">
<h2 className="text-2xl font-bold text-gray-800 mb-4">Analysis Results</h2>
<div className="grid md:grid-cols-2 gap-6">
{/* Depression Level */}
<div className={`p-4 rounded-lg border-2 ${getSeverityColor(analysis.severity)}`}>
<div className="flex items-center gap-2 mb-2">
{getSeverityIcon(analysis.severity)}
<h3 className="font-semibold">Depression Level</h3>
</div>
<div className="text-3xl font-bold mb-2">{analysis.depressionLevel}%</div>
<div className="w-full bg-gray-200 rounded-full h-3">
<div
className={`h-3 rounded-full transition-all duration-1000 ${
analysis.severity === 'critical' ? 'bg-red-500' :
analysis.severity === 'high' ? 'bg-orange-500' :
analysis.severity === 'moderate' ? 'bg-yellow-500' :
analysis.severity === 'mild' ? 'bg-blue-500' : 'bg-green-500'
}`}
style={{ width: `${analysis.depressionLevel}%` }}
/>
</div>
<p className="text-sm mt-2 font-medium">Severity: {analysis.severity.charAt(0).toUpperCase() + analysis.severity.slice(1)}</p>
</div>
{/* Sentiment */}
<div className="p-4 rounded-lg border-2 border-gray-200 bg-gray-50">
<h3 className="font-semibold text-gray-700 mb-2">Overall Sentiment</h3>
<div className="text-2xl font-bold text-gray-800 mb-2">{analysis.sentiment}</div>
<div className="text-sm text-gray-600">
Confidence: {analysis.confidence}%
</div>
</div>
</div>
</div>
{/* Triggered Keywords */}
{analysis.triggeredKeywords.length > 0 && (
<div className="bg-white rounded-lg shadow-lg p-6">
<h3 className="text-xl font-bold text-gray-800 mb-4">Detected Keywords</h3>
<div className="flex flex-wrap gap-2">
{analysis.triggeredKeywords.map((item, index) => (
<span
key={index}
className={`px-3 py-1 rounded-full text-sm font-medium ${
item.type === 'depression'
? 'bg-red-100 text-red-800'
: 'bg-green-100 text-green-800'
}`}
>
{item.keyword} ({item.level})
</span>
))}
</div>
</div>
)}
{/* Text Metrics */}
<div className="bg-white rounded-lg shadow-lg p-6">
<h3 className="text-xl font-bold text-gray-800 mb-4">Text Analysis</h3>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="text-center">
<div className="text-2xl font-bold text-indigo-600">{analysis.metrics.wordCount}</div>
<div className="text-sm text-gray-600">Words</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-indigo-600">{analysis.metrics.textLength}</div>
<div className="text-sm text-gray-600">Characters</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-indigo-600">{analysis.metrics.exclamationCount}</div>
<div className="text-sm text-gray-600">Exclamations</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-indigo-600">{analysis.metrics.questionCount}</div>
<div className="text-sm text-gray-600">Questions</div>
</div>
</div>
</div>
{/* Crisis Support */}
{analysis.severity === 'critical' && (
<div className="bg-red-50 border-l-4 border-red-400 p-4 rounded-lg">
<div className="flex items-center mb-3">
<AlertTriangle className="w-6 h-6 text-red-600 mr-2" />
<h3 className="text-lg font-semibold text-red-800">Immediate Support Available</h3>
</div>
<p className="text-red-700 mb-4">
The analysis indicates you may be experiencing significant distress. Please consider reaching out for support:
</p>
<div className="space-y-2">
<div className="flex items-center text-red-700">
<Phone className="w-4 h-4 mr-2" />
<span>Crisis Hotline: 988 (US) or your local emergency services</span>
</div>
<div className="flex items-center text-red-700">
<MessageCircle className="w-4 h-4 mr-2" />
<span>Text "HELLO" to 741741 for Crisis Text Line</span>
</div>
</div>
</div>
)}
{/* Timestamp */}
<div className="text-center text-sm text-gray-500">
Analysis completed: {analysis.timestamp}
</div>
</div>
)}
{/* Sample Inputs */}
<div className="bg-white rounded-lg shadow-lg p-6 mt-6">
<h3 className="text-xl font-bold text-gray-800 mb-4">Try Sample Inputs</h3>
<div className="grid gap-3">
<button
onClick={() => setInputText("I'm feeling so hopeless and don't see any point in continuing. Everything feels meaningless.")}
className="text-left p-3 bg-red-50 hover:bg-red-100 rounded-lg border border-red-200 transition-colors"
>
<span className="font-medium text-red-800">High Depression:</span>
<span className="text-red-600 ml-2">"I'm feeling so hopeless..."</span>
</button>
<button
onClick={() => setInputText("I'm not feeling good today, kind of down and unmotivated to do anything.")}
className="text-left p-3 bg-yellow-50 hover:bg-yellow-100 rounded-lg border border-yellow-200 transition-colors"
>
<span className="font-medium text-yellow-800">Moderate:</span>
<span className="text-yellow-600 ml-2">"I'm not feeling good today..."</span>
</button>
<button
onClick={() => setInputText("I'm so happy and joyful today! Everything feels wonderful and amazing!")}
className="text-left p-3 bg-green-50 hover:bg-green-100 rounded-lg border border-green-200 transition-colors"
>
<span className="font-medium text-green-800">Positive:</span>
<span className="text-green-600 ml-2">"I'm so happy and joyful today!"</span>
</button>
</div>
</div>
</div>
</div>
);
};
export default BertSentimentAnalyzer;