-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
113 lines (91 loc) · 2.52 KB
/
index.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
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
const express = require('express');
const fs = require('fs');
const app = express();
const cors = require('cors');
// Specify allowed origin
const allowedOrigins = ['https://nirmol.pages.dev'];
const corsOptions = {
origin: function (origin, callback) {
if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
};
//Enable CORS with specific origin
app.use(cors(corsOptions));
// Receive request as json
app.use(express.json());
// Read the list of bad words from the Nirmol JSON file
const word_list = new Set(JSON.parse(fs.readFileSync('nirmol.json', 'utf-8')));
// Read the prefixes and suffixes from the JSON file
const prefixesSuffixes = JSON.parse(fs.readFileSync('prefixes_suffixes.json', 'utf-8'));
const prefixes = prefixesSuffixes.prefixes;
const suffixes = prefixesSuffixes.suffixes;
function isBadWord(word) {
word = word.toLowerCase();
if (word_list.has(word)) {
return true;
}
for (const prefix of prefixes) {
if (word.startsWith(prefix)) {
return true;
}
}
for (const suffix of suffixes) {
if (word.endsWith(suffix)) {
return true;
}
}
return false;
}
const processResponse = (sentence, res) => {
sentence = sentence.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, '').replace(/।/g, '').replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, '');
const words = sentence.split(' ');
let badWordFound = [];
let nonbadWordFound = [];
for (const word of words) {
if (isBadWord(word)) {
badWordFound.push(word);
} else {
nonbadWordFound.push(word);
}
}
const totalWords = words.length;
const fruitRate = (badWordFound.length / totalWords) * 100;
if (badWordFound.length > 0) {
res.json({
bad_sentence: true,
bad_word_list: badWordFound,
normal_words: nonbadWordFound,
badness: `${fruitRate.toFixed(2)}%`
});
} else {
res.json({
bad_sentence: false,
bad_word_list: badWordFound,
normal_words: nonbadWordFound,
badness: `0%`
});
}
};
app.get("/:sentence", (req, res) => {
const sentence = req.params.sentence.toLowerCase();
processResponse(sentence, res);
});
/*
POST REQUEST:
Request body format-
{
"sentence": "your sentence here"
}
*/
app.post("/", (req, res) => {
const sentence = req.body.sentence.toLowerCase();
processResponse(sentence, res);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port http://localhost:${PORT}`);
});