Update routers/profanity.py
Browse files- routers/profanity.py +36 -43
routers/profanity.py
CHANGED
@@ -1,53 +1,46 @@
|
|
1 |
# routers/profanity.py
|
2 |
|
3 |
-
from fastapi import APIRouter, Query
|
4 |
from better_profanity import profanity
|
5 |
|
6 |
-
#
|
7 |
router = APIRouter()
|
8 |
|
9 |
-
# Define a rota para verificar o texto
|
10 |
@router.get("/profanity/check/")
|
11 |
def check_profanity(text: str = Query(..., description="Text to be checked for profanity")):
|
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 |
-
"offensive_words": offensive_words,
|
49 |
-
"offensive_word_count": offensive_word_count,
|
50 |
-
"total_word_count": total_word_count,
|
51 |
-
"offensive_percentage": round(offensive_percentage, 2),
|
52 |
-
"severity": severity
|
53 |
-
}
|
|
|
1 |
# routers/profanity.py
|
2 |
|
3 |
+
from fastapi import APIRouter, Query, HTTPException
|
4 |
from better_profanity import profanity
|
5 |
|
6 |
+
# Create a router for the profanity API
|
7 |
router = APIRouter()
|
8 |
|
|
|
9 |
@router.get("/profanity/check/")
|
10 |
def check_profanity(text: str = Query(..., description="Text to be checked for profanity")):
|
11 |
"""
|
12 |
+
Check if the text contains profanity and return the percentage of offensive words.
|
13 |
"""
|
14 |
+
try:
|
15 |
+
# Validate input
|
16 |
+
if not text.strip():
|
17 |
+
raise HTTPException(status_code=400, detail="The text must not be empty.")
|
18 |
+
|
19 |
+
# Load default dictionary of offensive words
|
20 |
+
profanity.load_censor_words()
|
21 |
+
|
22 |
+
# Split the text into words
|
23 |
+
words = text.split()
|
24 |
+
total_word_count = len(words)
|
25 |
+
|
26 |
+
# Validate word count
|
27 |
+
if total_word_count == 0:
|
28 |
+
raise HTTPException(status_code=400, detail="The text must contain at least one word.")
|
29 |
+
|
30 |
+
# Identify offensive words
|
31 |
+
offensive_words = [
|
32 |
+
word for word in words if profanity.contains_profanity(word)
|
33 |
+
]
|
34 |
+
offensive_word_count = len(offensive_words)
|
35 |
+
|
36 |
+
# Calculate the percentage of offensive words
|
37 |
+
offensive_percentage = (offensive_word_count / total_word_count * 100)
|
38 |
+
|
39 |
+
# Return the percentage rounded to 2 decimal places
|
40 |
+
return {
|
41 |
+
"offensive_percentage": round(offensive_percentage, 2)
|
42 |
+
}
|
43 |
+
|
44 |
+
except Exception as e:
|
45 |
+
# Catch unexpected errors and return a generic error message
|
46 |
+
raise HTTPException(status_code=500, detail="An unexpected error occurred.") from e
|
|
|
|
|
|
|
|
|
|
|
|