-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
43 lines (34 loc) · 1.54 KB
/
server.js
File metadata and controls
43 lines (34 loc) · 1.54 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
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const axios = require("axios");
const app = express();
app.use(express.json());
app.use(cors()); // Allow frontend to access the backend
const API_URL = "https://api-inference.huggingface.co/models/cardiffnlp/twitter-roberta-base-sentiment";
const API_KEY = process.env.HUGGINGFACE_API_KEY;
app.post("/analyze", async (req, res) => {
const { text } = req.body;
if (!text || text.trim() === "") {
return res.status(400).json({ error: "Text input cannot be empty." });
}
try {
const response = await axios.post(
API_URL,
{ inputs: text },
{ headers: { Authorization: `Bearer ${API_KEY}` } }
);
if (!Array.isArray(response.data) || response.data.length === 0) {
throw new Error("Invalid API response.");
}
// Extract the sentiment label with the highest probability
const emotions = response.data[0];
const topEmotion = emotions.reduce((max, obj) => (obj.score > max.score ? obj : max), emotions[0]);
res.json({ label: topEmotion.label, score: topEmotion.score });
} catch (error) {
console.error("Error:", error.response ? error.response.data : error.message);
res.status(500).json({ error: "Failed to analyze sentiment. Please try again later." });
}
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`✅ Server running on port ${PORT}`));