Spaces:
Running on Zero
Running on Zero
Update app/main.py
Browse files- app/main.py +17 -6
app/main.py
CHANGED
|
@@ -16,33 +16,44 @@ class ModerationResponse(BaseModel):
|
|
| 16 |
original_text: str
|
| 17 |
detected_categories: dict
|
| 18 |
is_flagged: bool
|
| 19 |
-
rewritten_text: list[str] | None
|
| 20 |
|
| 21 |
@app.post("/moderate", response_model=ModerationResponse)
|
| 22 |
async def moderate_text(request: TextRequest):
|
| 23 |
text = request.text
|
| 24 |
|
| 25 |
profanity_result = profanity_filter.check_profanity(text)
|
| 26 |
-
toxicity_scores = toxicity_pipe(text)[0]
|
| 27 |
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
rewritten = None
|
| 31 |
if is_flagged:
|
| 32 |
-
#
|
| 33 |
outputs = detox_pipe(
|
| 34 |
text,
|
| 35 |
max_length=100,
|
| 36 |
num_return_sequences=5,
|
| 37 |
do_sample=True,
|
|
|
|
| 38 |
top_p=0.9
|
| 39 |
)
|
| 40 |
-
# Extract just the text from the output dictionaries
|
| 41 |
rewritten = [out['generated_text'] for out in outputs]
|
| 42 |
|
| 43 |
return ModerationResponse(
|
| 44 |
original_text=text,
|
| 45 |
-
detected_categories={
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
is_flagged=is_flagged,
|
| 47 |
rewritten_text=rewritten
|
| 48 |
)
|
|
|
|
| 16 |
original_text: str
|
| 17 |
detected_categories: dict
|
| 18 |
is_flagged: bool
|
| 19 |
+
rewritten_text: list[str] | None
|
| 20 |
|
| 21 |
@app.post("/moderate", response_model=ModerationResponse)
|
| 22 |
async def moderate_text(request: TextRequest):
|
| 23 |
text = request.text
|
| 24 |
|
| 25 |
profanity_result = profanity_filter.check_profanity(text)
|
|
|
|
| 26 |
|
| 27 |
+
# 1. Get the full result from the toxicity model
|
| 28 |
+
tox_result = toxicity_pipe(text)[0]
|
| 29 |
+
|
| 30 |
+
# 2. Check if the LABEL is actually toxic AND the confidence is high
|
| 31 |
+
# (The model usually outputs 'toxic' or 'neutral' / 'LABEL_1' or 'LABEL_0')
|
| 32 |
+
is_toxic_by_model = (tox_result['label'].lower() in ['toxic', 'label_1']) and (tox_result['score'] > 0.5)
|
| 33 |
+
|
| 34 |
+
# 3. Final Flag Decision
|
| 35 |
+
is_flagged = profanity_result["contains_profanity"] or is_toxic_by_model
|
| 36 |
|
| 37 |
rewritten = None
|
| 38 |
if is_flagged:
|
| 39 |
+
# Added temperature=0.8 to make the 5 sentences more diverse
|
| 40 |
outputs = detox_pipe(
|
| 41 |
text,
|
| 42 |
max_length=100,
|
| 43 |
num_return_sequences=5,
|
| 44 |
do_sample=True,
|
| 45 |
+
temperature=0.8,
|
| 46 |
top_p=0.9
|
| 47 |
)
|
|
|
|
| 48 |
rewritten = [out['generated_text'] for out in outputs]
|
| 49 |
|
| 50 |
return ModerationResponse(
|
| 51 |
original_text=text,
|
| 52 |
+
detected_categories={
|
| 53 |
+
"profanity": profanity_result["contains_profanity"],
|
| 54 |
+
"model_label": tox_result['label'],
|
| 55 |
+
"model_score": tox_result['score']
|
| 56 |
+
},
|
| 57 |
is_flagged=is_flagged,
|
| 58 |
rewritten_text=rewritten
|
| 59 |
)
|