Skip to main content

safetype (Python)

Rule-based content moderation for Python servers: profanity, hate speech and harassment. It's the same engine and dictionaries as the SafeType.js JavaScript packages, so your backend can re-check exactly what the browser checked. It has no dependencies and runs fully offline.

pip install safetype
from safetype import create_moderation_engine

engine = create_moderation_engine(mode="mask")
engine.moderate("What the fuck are you doing?").text
# 'What the f*ck are you doing?'

Server-side enforcement

Client-side moderation can be bypassed (devtools, curl, modified clients). Re-check before you store:

engine = create_moderation_engine(
    mode="mask",
    policy={"hate": {"action": "block"}, "harassment": {"action": "block"}},
)

check = engine.validate(comment)
if not check.valid:
    raise ValidationError([v.category for v in check.violations])
store(check.result.text)                      # profanity masked
if check.result.requires_review:
    queue_for_human_review(comment)           # e.g. quoted or reported speech

FastAPI:

@app.post("/comments")
def create_comment(body: CommentIn):
    check = engine.validate(body.text)
    if not check.valid:
        raise HTTPException(422, detail=[{"category": v.category, "rule": v.rule_id} for v in check.violations])
    return save(check.result.text)

Django form:

def clean_body(self):
    check = engine.validate(self.cleaned_data["body"])
    if not check.valid:
        raise forms.ValidationError("Please keep it respectful.")
    return check.result.text

What it handles

  • Five actions (allow, mask, suggest, warn, block) and per-category policies
  • Profanity is masked deterministically. Hate and harassment rules are lower-confidence signals that context can weaken: quoted or reported speech becomes requires_review instead of being acted on
  • Unicode (accents, full-width, Cyrillic/Greek lookalikes, zero-width), leet (sh1t), repeated letters, spaced letters
  • No Scunthorpe problem, and masking is idempotent
  • English and Hinglish (romanized Hindi: "bhenchod", "chutiya", "teri maa ka...") out of the box; languages=["en"] turns Hinglish off
  • Spanish, French, German, Portuguese and Hindi (Devanagari), opt-in: languages=["en", "es"], language="pt-BR", or language="hi" (both Hindi scripts)
  • Custom words, custom rules, allow lists, mask styles (vowels, partial, full, or a function)

API

engine = create_moderation_engine(
    mode="mask", language="en", languages=None, categories=None, policy=None, packs=None,
    custom_words=None, allow_list=None, rules=None, severity=None,
    mask_char="*", mask_style="vowels", detect_spaced_letters=True,
)
engine.moderate(text)   # ModerationResult(text, suggested_text, matches, action, allowed, requires_review, mapping)
engine.mask(text)       # str
engine.validate(text)   # ValidationResult(valid, result, violations)
engine.add_rule({"id": "app.x", "pattern": "(foo|bar*)", "category": "custom"})
engine.remove_rule("app.x")
engine.set_policy({"harassment": {"action": "block", "min_confidence": 0.7}})
engine.set_mode("warn")
engine.set_severity("damn", "medium")             # by word (covers "damned", "goddamn") or by rule id
engine.reset_severity("damn")                     # back to the dictionary's severity
engine.get_severity_overrides()                   # {"damn": "medium", ...}

safetype.moderate(text); safetype.mask(text)   # shared default engine

Offsets (match.start / match.end) are Python string indices (code points).

Parity with JavaScript

The test suite replays 684 cases recorded from the JavaScript engine and requires identical results. The dictionary is exported from the JavaScript build, so both always share the same rules.

Limitations

Rule-based detection misses novel spellings and sarcasm, and it can flag reclaimed or quoted language. Treat hate and harassment results as signals for review, not verdicts. Contextual (AI) classifiers are available in the JavaScript engine and planned for Python.

MIT licensed.

Metadata

Release files for safetype 1.15.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for safetype 1.15.0
File Size Uploaded Provenance Actions
safetype-1.15.0.tar.gz 145.5 kB With provenance Details for safetype-1.15.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for safetype 1.15.0
File Interpreter ABI Platform Actions
safetype-1.15.0-py3-none-any.whl Python 3 none any Details for safetype-1.15.0-py3-none-any.whl

Total release size: 176.7 kB

Release files / safetype-1.15.0.tar.gz

Download URL safetype-1.15.0.tar.gz
Size 145.5 kB
Tags Source
SHA-256 checksum
How to use checksums
88245d477595e1f67ff52ddc9747a504311e58d63e18facf9f8cb4a500ad8646
BLAKE2b-256 checksum
How to use checksums
8d6b8a3d6bc742cfe65269d8d51d25ed95e80ebda776adf94d4dd6ab597cde30
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Release files / safetype-1.15.0-py3-none-any.whl

Download URL safetype-1.15.0-py3-none-any.whl
Size 31.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
11f921721c1071123b7be831a19ea5d357b8bcef7efaf429eae4097e8b08bd67
BLAKE2b-256 checksum
How to use checksums
ea332ca5d1edb1bb012fd7ab0c5ee014967a175023b1fc6e3e35c2a7f9fcd0c2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Security for safetype 1.15.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for safetype-1.15.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page