pahvalentines/backend/app/services/profanity.py
michael ce95d61796 feat: add server-side profanity filter with real-time validation
Add profanity detection using better-profanity library with:
- Real-time API validation during typing (500ms debounce)
- Defense-in-depth server-side validation on form submission
- Visual feedback with red borders and warning message
- Submit button disabled when profanity detected
- Fail-open behavior on API errors to not block users

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-04 08:29:58 -06:00

38 lines
1 KiB
Python

"""Profanity detection service using better-profanity library."""
from better_profanity import profanity
# Initialize profanity filter once at module load
profanity.load_censor_words()
def contains_profanity(text: str) -> bool:
"""Check if text contains profanity.
Args:
text: The text to check for profanity.
Returns:
True if profanity is detected, False otherwise.
"""
if not text:
return False
return profanity.contains_profanity(text)
def check_fields(fields: dict[str, str | None]) -> dict[str, bool]:
"""Check multiple fields for profanity.
Args:
fields: Dictionary of field_name -> text to check.
None values are skipped.
Returns:
Dictionary of field_name -> has_profanity (bool).
Only includes fields that were checked (non-None values).
"""
results = {}
for field_name, text in fields.items():
if text is not None:
results[field_name] = contains_profanity(text)
return results