Skip to main content

Python client library for the Respectify API

Project description

Respectify Python Client

PyPI version Python 3.9+ License: MIT

A Python client library for the Respectify API, providing both synchronous and asynchronous interfaces for comment moderation, spam detection, toxicity analysis, and dogwhistle detection.

Respectify aims to be more than comment moderation: it tries to teach and edify users when a comment is rejected.

For bloggers, companies with articles, etc it provides a way to keep discourse civil and on-topic without censorship.

Features

  • Supports the full Resepctify feature set for analysing comments and discussion
  • Both synchronous (RespectifyClient) and asynchronous (RespectifyAsyncClient) clients
  • The Megacall endpoint allows multiple analyses in a single request

Installation

pip install respectify

Quick Start

Synchronous Client

from respectify import RespectifyClient

# Initialize client
client = RespectifyClient(
    email="your-email@example.com",
    api_key="your-api-key"
)

# Initialize a topic
# Comments on a discussion are in the context of the discussion -- this is any starting material
topic = client.init_topic_from_text("This is my article content")
article_id = topic.article_id

# Evaluate comment quality and toxicity
score = client.evaluate_comment("This is a thoughtful comment", article_id)
print(f"Quality: {score.overall_score}/5, Toxicity: {score.toxicity_score:.2f}")

# Check if a comment is spam
spam_result = client.check_spam("Great post!", article_id)
print(f"Is spam: {spam_result.is_spam}")

# Perspective-compatible scoring for migrations from Google's Perspective API
perspective = client.perspective.analyze_comment(
    {
        "comment": {"text": "You clearly did not read the article."},
        "requestedAttributes": {
            "TOXICITY": {},
            "INSULT": {},
        },
    }
)
print(perspective.attributeScores["TOXICITY"].summaryScore.value)

Asynchronous Client

import asyncio
from respectify import RespectifyAsyncClient

async def main():
    client = RespectifyAsyncClient(
        email="your-email@example.com",
        api_key="your-api-key"
    )
    
    # Initialize topic
    topic = await client.init_topic_from_text("Article content")
    article_id = topic.article_id
    
    # Run multiple analyses concurrently
    spam_task = client.check_spam("Great post!", article_id)
    score_task = client.evaluate_comment("Thoughtful comment", article_id)
    
    spam_result, score_result = await asyncio.gather(spam_task, score_task)
    
    print(f"Spam: {spam_result.is_spam}, Quality: {score_result.overall_score}/5")

asyncio.run(main())

Megacall for Efficiency

Perform multiple analyses in a single API call:

# Instead of multiple separate calls...
result = client.megacall(
    comment="Test comment",
    article_id=article_id, # pre-registered with init_topic_from_url() (reads a page) or init_topic_from_text() (anything you send it)
    include_spam=True,
    include_relevance=True, 
    include_comment_score=True,
    include_dogwhistle=True
)

# Access individual results
print(f"Spam: {result.spam.is_spam if result.spam else 'N/A'}")
print(f"Quality: {result.comment_score.overall_score if result.comment_score else 'N/A'}/5")
print(f"On topic: {result.relevance.on_topic.is_on_topic if result.relevance else 'N/A'}")
print(f"Dogwhistles: {result.dogwhistle.detection.dogwhistles_detected if result.dogwhistle else 'N/A'}")

API Reference

Available Methods

Topic Management:

  • init_topic_from_text(text, topic_description=None) - Initialize topic from text content
  • init_topic_from_url(url, topic_description=None) - Initialize topic from URL

Comment Analysis:

  • evaluate_comment(comment, article_id) - Evaluates a comment on logical fallacies, objectionable phrases, negative tone, low effort
  • check_relevance(comment, article_id, banned_topics=None) - Relevance and banned topic detection
  • check_dogwhistle(comment, sensitive_topics=None, dogwhistle_examples=None) - Dogwhistle detection
  • check_spam(comment, article_id) - Spam detection

Batch Operations:

  • megacall(comment, article_id, **options) - Multiple analyses in one call

Perspective Compatibility:

  • client.perspective.analyze_comment(request) - Public Perspective-compatible analyzeComment
  • client.perspective.suggest_comment_score(request) - Public Perspective-compatible suggestCommentScore

Authentication:

  • check_user_credentials() - Verify API credentials work without calling any normal API

Response Schemas

All API responses are parsed into strongly-typed Pydantic models:

  • InitTopicResponse - Topic initialization result
  • SpamDetectionResult - Spam analysis with confidence scores
  • CommentScore - Quality metrics and toxicity analysis
  • CommentRelevanceResult - Topic relevance and banned topic detection
  • DogwhistleResult - Dogwhistle detection with detailed analysis
  • MegaCallResult - Container for multiple analysis results
  • UserCheckResponse - Authentication verification result

Error Handling

from respectify import (
    RespectifyError,           # Base exception
    AuthenticationError,       # Invalid credentials (401)
    BadRequestError,          # Invalid parameters (400)
    PaymentRequiredError,     # Subscription required (402)
    ServerError              # Server issues (500+)
)

try:
    result = client.check_spam("test", article_id)
except AuthenticationError:
    print("Please check your API credentials")
except PaymentRequiredError:
    print("This feature requires a paid plan")
except BadRequestError as e:
    print(f"Invalid request: {e.message}")

Response Sanitization

All string values in API responses are automatically HTML-encoded to prevent XSS. API responses echo back user-submitted comment text (in quoted fallacies, objectionable phrases, etc.) so this encoding is applied by default to make responses safe to render in HTML.

Configuration

Client Options

client = RespectifyClient(
    email="your-email@example.com",
    api_key="your-api-key"
)

Development

Running Tests

You will need to provide real Respectify credentials, because this will make calls against the actual API - not a mocked version. Use a key dedicated to testing to separate this from your normal usage.

Create a .env file for testing:

RESPECTIFY_EMAIL=your-email@example.com
RESPECTIFY_API_KEY=your-api-key
REAL_ARTICLE_ID=a-genuine-initialised-article
# Install development dependencies
pip install -e ".[dev]"

# Run tests with real API (requires .env file with real credentials)
pytest tests/ -v

# Run tests with coverage
pytest tests/ --cov=respectify --cov-report=html

Building Documentation

# Install documentation dependencies  
pip install -e ".[docs]"

# Build documentation
cd docs
make html

# Serve documentation locally
python -m http.server 8000 --directory _build/html

Code Quality

# Run ruff linting and formatting
ruff check respectify/
ruff format respectify/

# Beartype provides runtime type checking automatically
# Big fans of beartype here

Requirements

  • Python 3.9+
  • httpx >= 0.24.0
  • pydantic >= 2.0.0
  • beartype >= 0.15.0

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Changelog

v0.1.0 (2025-01-XX)

  • Initial release
  • Synchronous and asynchronous client support
  • Complete API coverage for all Respectify endpoints
  • Comprehensive type safety with Pydantic schemas
  • Megacall support for efficient batch operations
  • Full test suite with real API integration
  • Sphinx documentation with examples

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

respectify-0.5.0.tar.gz (32.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

respectify-0.5.0-py3-none-any.whl (19.8 kB view details)

Uploaded Python 3

File details

Details for the file respectify-0.5.0.tar.gz.

File metadata

  • Download URL: respectify-0.5.0.tar.gz
  • Upload date:
  • Size: 32.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.4

File hashes

Hashes for respectify-0.5.0.tar.gz
Algorithm Hash digest
SHA256 107a9214d70b1fa3fe83c43158c1383a27117c731ed78a68b11211b11ce7f4ac
MD5 210d641805ebd41cc2a1f0e199e72076
BLAKE2b-256 25b20e8155e82e7988b58b22b2a3bc78517316ac81ff250662d05b93ffcba03c

See more details on using hashes here.

File details

Details for the file respectify-0.5.0-py3-none-any.whl.

File metadata

  • Download URL: respectify-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 19.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.4

File hashes

Hashes for respectify-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f944df8c10ce9ae806abca37fdbd8c7d80f366b6350e3da080c2d17d294a2bbd
MD5 850146d84db2088e08711f0ea446da79
BLAKE2b-256 6bdcb7ed9efa2d70743e97e65cb4889dbb9aa52c62c724f2c5394b27dd9c8caa

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page