-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
235 lines (197 loc) · 7.44 KB
/
Copy pathscript.js
File metadata and controls
235 lines (197 loc) · 7.44 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
let apiKey = "";
// Analysis prompts for different types
const analysisPrompts = {
basic: `Analyze the sentiment of the following text and provide a JSON response with:
- sentiment: "positive", "negative", or "neutral"
- score: number between -1 (very negative) and 1 (very positive)
- confidence: percentage (0-100)
- reasoning: brief explanation
Text to analyze:`,
detailed: `Analyze the emotional content of the following text and provide a JSON response with:
- sentiment: "positive", "negative", or "neutral"
- score: number between -1 and 1
- confidence: percentage (0-100)
- emotions: object with scores (0-1) for joy, anger, fear, sadness, surprise, disgust, trust, anticipation
- reasoning: brief explanation
Text to analyze:`,
comprehensive: `Perform a comprehensive sentiment and emotion analysis of the following text. Provide a JSON response with:
- sentiment: "positive", "negative", or "neutral"
- score: number between -1 and 1
- confidence: percentage (0-100)
- emotions: detailed emotion scores (0-1) for joy, anger, fear, sadness, surprise, disgust, trust, anticipation
- key_phrases: array of emotionally significant phrases
- reasoning: detailed explanation
Text to analyze:`,
};
// Main analysis function
async function analyzeSentiment() {
apiKey = document.getElementById("apiKey").value.trim();
const inputText = document.getElementById("inputText").value.trim();
const analysisType = document.getElementById("analysisType").value;
// Validate inputs
if (!apiKey) {
showError("Please enter your OpenAI API Key");
return;
}
if (!inputText) {
showError("Please enter text to analyze");
return;
}
if (inputText.length < 10) {
showError("Text too short. Please enter at least 10 characters");
return;
}
// Show loading
showLoading(true);
hideError();
hideResults();
try {
// Call OpenAI API
const analysis = await callOpenAI(inputText, analysisType);
// Display results
displayResults(analysis, inputText);
} catch (error) {
console.error("Error:", error);
showError("Analysis failed: " + error.message);
} finally {
showLoading(false);
}
}
// Call OpenAI API
async function callOpenAI(text, type) {
const prompt = analysisPrompts[type];
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content:
"You are an expert sentiment analyst. Always respond with valid JSON only, no additional text.",
},
{
role: "user",
content: `${prompt}\n\n"${text}"`,
},
],
max_tokens: 800,
temperature: 0.3,
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error?.message || "API request failed");
}
const data = await response.json();
const responseText = data.choices[0].message.content.trim();
try {
return JSON.parse(responseText);
} catch (e) {
throw new Error("Invalid response format from AI");
}
}
// Display analysis results
function displayResults(analysis, originalText) {
// Basic sentiment display
const score = analysis.score || 0;
const sentiment = analysis.sentiment || "neutral";
const confidence = analysis.confidence || 0;
document.getElementById("sentimentScore").textContent = score.toFixed(2);
document.getElementById("sentimentLabel").textContent =
sentiment.toUpperCase();
document.getElementById("confidenceScore").textContent =
`Confidence: ${confidence}%`;
// Update score styling
const scoreElement = document.getElementById("sentimentScore");
scoreElement.className = `sentiment-score ${sentiment}`;
// Update sentiment meter
const meterFill = document.getElementById("sentimentMeter");
const meterWidth = ((score + 1) / 2) * 100; // Convert -1 to 1 range to 0 to 100%
meterFill.style.width = `${meterWidth}%`;
meterFill.className = `meter-fill ${sentiment}`;
// Display emotions if available
displayEmotions(analysis.emotions || {});
// Display text statistics
displayTextStats(originalText, analysis.key_phrases || []);
// Show results
document.getElementById("resultsContainer").classList.add("show");
}
// Display emotion breakdown
function displayEmotions(emotions) {
const container = document.getElementById("emotionBreakdown");
container.innerHTML = "";
const emotionLabels = {
joy: "😊 Joy",
anger: "😠 Anger",
fear: "😨 Fear",
sadness: "😢 Sadness",
surprise: "😮 Surprise",
disgust: "🤢 Disgust",
trust: "🤝 Trust",
anticipation: "🤔 Anticipation",
};
Object.entries(emotions).forEach(([emotion, score]) => {
const emotionDiv = document.createElement("div");
emotionDiv.className = "emotion-item";
emotionDiv.innerHTML = `
<span class="emotion-name">${emotionLabels[emotion] || emotion}</span>
<span class="emotion-score">${(score * 100).toFixed(0)}%</span>
`;
container.appendChild(emotionDiv);
});
if (Object.keys(emotions).length === 0) {
container.innerHTML =
'<p style="color: #8b4513; font-style: italic;">No detailed emotions available</p>';
}
}
// Display text statistics and key phrases
function displayTextStats(text, keyPhrases) {
const wordCount = text.trim().split(/\s+/).length;
const charCount = text.length;
document.getElementById("wordCount").textContent = `Words: ${wordCount}`;
document.getElementById("charCount").textContent = `Characters: ${charCount}`;
const phrasesContainer = document.getElementById("phrasesContainer");
phrasesContainer.innerHTML = "";
if (keyPhrases && keyPhrases.length > 0) {
keyPhrases.forEach((phrase) => {
const phraseSpan = document.createElement("span");
phraseSpan.style.cssText =
"background: #ffb6c1; padding: 2px 6px; border-radius: 3px; margin: 2px; display: inline-block; font-size: 12px;";
phraseSpan.textContent = phrase;
phrasesContainer.appendChild(phraseSpan);
});
} else {
phrasesContainer.innerHTML =
'<span style="color: #8b4513; font-style: italic;">No key phrases identified</span>';
}
}
// Show/hide loading
function showLoading(show) {
document.getElementById("loadingDiv").style.display = show ? "block" : "none";
document.querySelector(".analyze-btn").disabled = show;
}
// Show error
function showError(message) {
document.getElementById("errorDiv").textContent = message;
document.getElementById("errorDiv").style.display = "block";
}
// Hide error
function hideError() {
document.getElementById("errorDiv").style.display = "none";
}
// Hide results
function hideResults() {
document.getElementById("resultsContainer").classList.remove("show");
}
// Initialize page
document.addEventListener("DOMContentLoaded", function () {
// Optional: Add sample text for testing
const sampleText =
"I'm absolutely thrilled about this new opportunity! It's going to be an amazing adventure, though I'm a bit nervous about the challenges ahead.";
// document.getElementById('inputText').value = sampleText;
});