Skip to main content

Neuwo API SDK - Python SDK client for the Neuwo content classification API.

Project description

Neuwo API Python SDK

Python SDK client for the Neuwo content classification API.

Support

Installation

Install the package using pip:

pip install neuwo_api

Install with optional development dependencies:

# For development
pip install neuwo_api[dev]

# For testing
pip install neuwo_api[test]

Requirements

  • Python 3.8 or higher
  • requests library (automatically installed)

Quick Start

For more detailed examples and use cases, see the examples folder in the repository.

REST API Client

from neuwo_api import NeuwoRestClient

# Initialize client
client = NeuwoRestClient(
    token="your-rest-api-token",
    base_url="https://custom.api.com",
)

# Analyze text content
response = client.get_ai_topics(
    content="Cats make wonderful pets for modern households.",
    document_id="article-123",
    headline="Why Cats Make Great Pets"
)

# Access results
print(f"Tags: {len(response.tags)}")
for tag in response.tags:
    print(f"  - {tag.value} (score: {tag.score})")

print(f"Brand Safe: {response.brand_safety.is_safe}")
print(f"IAB Categories: {len(response.marketing_categories.iab_tier_1)}")

EDGE API Client

from neuwo_api import NeuwoEdgeClient

# Initialize client
client = NeuwoEdgeClient(
    token="your-edge-api-token",
    base_url="https://custom.api.com",
    origin="https://yourwebsite.com"  # Optional: default origin for requests
)

# Analyze article by URL
response = client.get_ai_topics(url="https://example.com/article")

# Or wait for analysis to complete (with automatic retry)
response = client.get_ai_topics_wait(
    url="https://example.com/new-article",
    max_retries=10,
    retry_interval=6
)

print(f"Found {len(response.tags)} tags for the article")

Configuration

REST Client Parameters

Parameter Type Default Description
token str Required REST API authentication token
base_url str Required Base URL for the API
timeout int 60 Request timeout in seconds

Example:

client = NeuwoRestClient(
    token="your-token",
    base_url="https://custom.api.com",
    timeout=120
)

EDGE Client Parameters

Parameter Type Default Description
token str Required EDGE API authentication token
base_url str Required Base URL for the API
timeout int 60 Request timeout in seconds
origin str None Default Origin header for requests

Example:

client = NeuwoEdgeClient(
    token="your-token",
    base_url="https://custom.api.com",
    origin="https://yoursite.com",
    timeout=90
)

API Methods

REST API

Get AI Topics
response = client.get_ai_topics(
    content="Text to analyze",           # Required
    document_id="doc123",                 # Optional: save to database
    lang="en",                            # Optional: ISO 639-1 code
    publication_id="pub1",                # Optional
    headline="Article Headline",          # Optional
    tag_limit=15,                         # Optional: max tags (default: 15)
    tag_min_score=0.1,                    # Optional: min score (default: 0.1)
    marketing_limit=None,                 # Optional
    marketing_min_score=0.3,              # Optional (default: 0.3)
    include_in_sim=True,                  # Optional (default: True)
    article_url="https://example.com"     # Optional
)
Get Similar Articles
articles = client.get_similar(
    document_id="doc123",                 # Required
    max_rows=10,                          # Optional: limit results
    past_days=30,                         # Optional: limit by date
    publication_ids=["pub1", "pub2"]      # Optional: filter by publication
)
Update Article
from datetime import date

article = client.update_article(
    document_id="doc123",                 # Required
    published=date(2024, 1, 15),          # Optional
    headline="Updated Headline",          # Optional
    writer="Author Name",                 # Optional
    category="News",                      # Optional
    content="Updated content",            # Optional
    summary="Summary",                    # Optional
    publication_id="pub1",                # Optional
    article_url="https://example.com",    # Optional
    include_in_sim=True                   # Optional
)
Train AI Topics
training_tags = client.train_ai_topics(
    document_id="doc123",                 # Required
    tags=["tag1", "tag2", "tag3"],        # Required
)

EDGE API

Get AI Topics (Single URL)
response = client.get_ai_topics(
    url="https://example.com/article",    # Required
    origin="https://yoursite.com"         # Optional: override default origin
)
Get AI Topics with Auto-Retry
response = client.get_ai_topics_wait(
    url="https://example.com/article",    # Required
    origin="https://yoursite.com",        # Optional
    max_retries=10,                       # Optional (default: 10)
    retry_interval=6,                     # Optional (default: 6s)
    initial_delay=2                       # Optional (default: 2s)
)
Get AI Topics (Multiple URLs)
# From list
results = client.get_ai_topics_list(
    urls=["https://example.com/1", "https://example.com/2"],
    origin="https://yoursite.com"
)

# From file bytes
with open("urls.txt", "rb") as f:
    urls_as_bytes = f.read()
result = client.get_ai_topics_list(urls_as_bytes)
Get Similar Articles
articles = client.get_similar(
    document_url="https://example.com/article",  # Required
    max_rows=10,                                 # Optional
    past_days=30,                                # Optional
    publication_ids=["pub1", "pub2"],            # Optional
    origin="https://yoursite.com"                # Optional
)

Raw Response Methods

All methods have _raw variants that return the raw requests.Response object:

# REST
raw_response = client.get_ai_topics_raw(content="Text")
print(raw_response.status_code)
print(raw_response.text)

# EDGE
raw_response = client.get_ai_topics_raw(url="https://example.com")
print(raw_response.json())

Error Handling

The SDK provides specific exceptions for different error scenarios:

from neuwo_api import (
    NeuwoRestClient,
    ValidationError,
    AuthenticationError,
    NoDataAvailableError,
    ContentNotAvailableError,
    NetworkError
)

client = NeuwoRestClient(
    token="your-token"
    base_url="https://custom.api.com",
)

try:
    response = client.get_ai_topics(content="Your content here")
except ValidationError as e:
    print(f"Invalid input: {e}")
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
except NoDataAvailableError as e:
    print(f"Data not yet available: {e}")
except ContentNotAvailableError as e:
    print(f"Content could not be analyzed: {e}")
except NetworkError as e:
    print(f"Network error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")

Exception Hierarchy

  • NeuwoAPIError - Base exception for all API errors
    • AuthenticationError - Invalid or missing token (401)
    • ForbiddenError - Token lacks permissions (403)
    • NotFoundError - Resource not found (404)
      • NoDataAvailableError - URL not yet processed (404)
    • BadRequestError - Malformed request (400)
    • ValidationError - Request validation failed (422)
    • RateLimitError - Rate limit exceeded (429)
    • ServerError - Server error (5xx)
    • NetworkError - Network communication failed
    • ContentNotAvailableError - Content tagging failed

Logging

The SDK uses Python's standard logging module. Enable logging to see detailed API communication:

from neuwo_api import setup_logger
import logging

# Enable debug logging
setup_logger(level=logging.DEBUG)

# Or just warnings and errors (default)
setup_logger(level=logging.WARNING)

# Disable logging
from neuwo_api import disable_logger
disable_logger()

Custom logging configuration:

import logging
from neuwo_api import get_logger

# Get the SDK logger
logger = get_logger()

# Add custom handler
handler = logging.FileHandler('neuwo_api.log')
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

Development

Setup Development Environment

# Clone repository
git clone https://github.com/neuwoai/neuwo-api-sdk-python.git
cd neuwo-api-sdk-python

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in development mode with all dependencies
pip install -e ".[dev]"

Running Tests

# Run all tests
pytest

# Run with coverage
pytest --cov=neuwo_api --cov-report=html

# Run specific test file
pytest tests/test_rest_client.py

# Run with verbose output
pytest -v

Building Distribution

# Install build tools
pip install build twine

# Build
python -m build

# Upload to PyPI
twine upload dist/*

License

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

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

neuwo_api-0.1.0.tar.gz (43.4 kB view details)

Uploaded Source

Built Distribution

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

neuwo_api-0.1.0-py3-none-any.whl (24.9 kB view details)

Uploaded Python 3

File details

Details for the file neuwo_api-0.1.0.tar.gz.

File metadata

  • Download URL: neuwo_api-0.1.0.tar.gz
  • Upload date:
  • Size: 43.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for neuwo_api-0.1.0.tar.gz
Algorithm Hash digest
SHA256 80aed0b2e4f949cb166060818f8e7134ee24cd489b9647cebf5774cd41be6c37
MD5 c78bb397c769df10415277a089ff51d3
BLAKE2b-256 bf0c658120b4a9d7e5bf7f361a16f50d7e556cb8615721efb5b3409489eb80cd

See more details on using hashes here.

File details

Details for the file neuwo_api-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: neuwo_api-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 24.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for neuwo_api-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b633fd80dece85eec84e3cf8680e1e3ac0638f53544228ed40e04200ff57f50c
MD5 4c4b5548ed358d91f49c3bc7fbe43181
BLAKE2b-256 93b5d3f8f72c2bbd088f114bf616bedba78c39f3da02441af32714c002ceeb25

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