-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocalapi.js
82 lines (74 loc) · 2.53 KB
/
localapi.js
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
const { spawn } = require('child_process');
const express = require('express');
const cheerio = require('cheerio');
const app = express();
const port = 3001;
const cors = require('cors');
app.use(cors());
app.use(express.json());
const extractLyrics = async (url) => {
try {
const response = await fetch(url);
const data = await response.text();
const $ = cheerio.load(data);
let lyrics = $('div[class="lyrics"]').text().trim();
if (!lyrics) {
lyrics = '';
$('div[class^="Lyrics__Container"]').each((i, elem) => {
if ($(elem).text().length !== 0) {
let snippet = $(elem)
.html()
.replace(/<br>/g, '\n')
.replace(/<(?!\s*br\s*\/?)[^>]+>/gi, '');
lyrics += $('<textarea/>').html(snippet).text().trim() + '\n\n';
}
});
}
if (!lyrics) return null;
lyrics = lyrics.replace(/\d/g, '');
lyrics = lyrics.replace(/[\[(][^\])]*[\])]/g, '');
lyrics = lyrics.replace(/^\s*[\r\n]/gm, '');
lyrics = lyrics.replace(/[^\w\s]/g, '');
lyrics = lyrics.replace(/^\s+|\s+$/gm, '');
lyrics = lyrics.toLowerCase().trim().split('\n');
return lyrics;
} catch (e) {
throw e;
};
};
app.post('/getEmotions', async (req, res) => {
try {
const lyrics = req.body.lyrics;
const pythonProcess = spawn('python', ['./get_emotions.py', ...JSON.parse(lyrics).lyrics]);
pythonProcess.stdout.on('data', (data) => {
emotions = JSON.parse(data.toString().replace(/'/g, '"'));
for (const emotion in emotions) {
emotions[emotion] = Math.round(emotions[emotion]*10000)/100;
}
res.json(emotions);
});
pythonProcess.stderr.on('data', (data) => {
res.status(500).send(data.toString());
});
} catch (error) {
console.error("Error:", error);
res.status(500).send('Server Error');
}
});
app.post('/getLyrics', async (req, res) => {
try {
const url = req.body.url;
const lyrics = await extractLyrics(url);
if (lyrics === null) {
res.status(404).send('No lyrics found');
} else {
res.json({ lyrics });
}
} catch (error) {
console.error("Error:", error);
res.status(500).send('Server Error');
}
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});