Skip to main content

Python SDK for Extract Monster - Extract structured data from files and text using AI

Project description

Extract Monster Python SDK

PyPI version License: MIT

Official Python SDK for Extract Monster - Extract structured data from files and text using AI.

Features

  • 🎯 Type-Safe Schema Support - Use Pydantic models for type-safe data extraction
  • 📄 Multi-Format Support - Extract from PDFs, images, videos, audio, and text documents
  • 🔒 Secure Authentication - API key-based authentication
  • 📦 Easy to Use - Simple, intuitive API design
  • 🎨 Flexible Schemas - Support for Pydantic models and raw JSON schemas

Installation

pip install extract-monster

For Pydantic support (recommended):

pip install extract-monster[pydantic]

Quick Start

from extract_monster import ExtractMonster
from pydantic import BaseModel, Field

# Initialize client
client = ExtractMonster(api_key="your_api_key")

# Define schema with Pydantic
class Invoice(BaseModel):
    invoice_number: str = Field(description="Invoice number")
    date: str = Field(description="Invoice date")
    total: float = Field(description="Total amount")
    vendor: str = Field(description="Vendor name")

# Extract from file
result = client.extract_file("invoice.pdf", schema=Invoice)
print(result.extracted_data)
# {"invoice_number": "INV-001", "date": "2024-01-15", "total": 1250.00, "vendor": "Acme Corp"}

# Extract from text
class Contact(BaseModel):
    name: str = Field(description="Full name")
    phone: str = Field(description="Phone number")
    email: str = Field(description="Email address")

result = client.extract_text(
    "Contact John Doe at john@example.com or 555-1234",
    schema=Contact
)
print(result.extracted_data)
# {"name": "John Doe", "phone": "555-1234", "email": "john@example.com"}

Authentication

Get your API key from the Extract Monster Dashboard.

Option 1: Pass API key directly

client = ExtractMonster(api_key="your_api_key")

Option 2: Use environment variable

export EXTRACT_MONSTER_API_KEY="your_api_key"
client = ExtractMonster()  # Automatically uses environment variable

Usage

Extract from Files

Extract structured data from any supported file format:

from extract_monster import ExtractMonster
from pydantic import BaseModel, Field
from typing import List

client = ExtractMonster(api_key="your_api_key")

# Define your schema
class MenuItem(BaseModel):
    name: str = Field(description="Dish or item name")
    price: float = Field(description="Price in local currency")
    description: str = Field(description="Item description or ingredients")

class Menu(BaseModel):
    restaurant_name: str = Field(description="Restaurant name")
    items: List[MenuItem] = Field(description="List of menu items")

# Extract from PDF, image, or other file
result = client.extract_file("menu.pdf", schema=Menu)
print(result.extracted_data)

Supported File Formats:

  • Documents (Visual): PDF - Full visual understanding with charts, diagrams
  • Documents (Text): TXT, MD, HTML, XML, JSON, CSV, RTF
  • Images: PNG, JPG, JPEG, WEBP, HEIC, HEIF
  • Videos: MP4, MPEG, MOV, AVI, FLV, MPG, WEBM, WMV, 3GP
  • Audio: WAV, MP3, AIFF, AAC, OGG, FLAC

Extract from Text

Extract structured data from plain text:

from pydantic import BaseModel, Field
from typing import List

class Person(BaseModel):
    name: str = Field(description="Person's full name")
    role: str = Field(description="Job title or role")
    email: str = Field(description="Email address")

class Meeting(BaseModel):
    date: str = Field(description="Meeting date")
    attendees: List[Person] = Field(description="List of meeting attendees")
    topics: List[str] = Field(description="Topics discussed in the meeting")

text = """
Meeting on Jan 15, 2024
Attendees:
- John Doe (CEO) - john@company.com
- Jane Smith (CTO) - jane@company.com

Topics discussed:
1. Q1 Product Roadmap
2. Budget Review
"""

result = client.extract_text(text, schema=Meeting)
print(result.extracted_data)

Schema Options

1. Pydantic Models (Recommended)

from pydantic import BaseModel, Field

class Product(BaseModel):
    name: str = Field(description="Product name")
    price: float = Field(description="Price in USD")
    in_stock: bool = Field(description="Availability status")

result = client.extract_file("product.jpg", schema=Product)

2. JSON Schema Dictionary

schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "price": {"type": "number"},
        "in_stock": {"type": "boolean"}
    },
    "required": ["name", "price"]
}

result = client.extract_file("product.jpg", schema=schema)

3. No Schema (Freeform)

# Let the AI extract relevant information
result = client.extract_file("document.pdf")
print(result.extracted_data)

Context Managers

Use context managers for automatic cleanup:

with ExtractMonster(api_key="your_api_key") as client:
    result = client.extract_file("document.pdf")

Error Handling

from extract_monster import (
    ExtractMonster,
    AuthenticationError,
    QuotaExceededError,
    ValidationError,
    APIError,
)

client = ExtractMonster(api_key="your_api_key")

try:
    result = client.extract_file("document.pdf", schema=MySchema)
except AuthenticationError:
    print("Invalid API key")
except QuotaExceededError:
    print("Usage quota exceeded")
except ValidationError as e:
    print(f"Validation error: {e.message}")
except APIError as e:
    print(f"API error: {e.message}")

Response Object

The ExtractionResponse object provides multiple ways to access data:

result = client.extract_file("invoice.pdf", schema=Invoice)

# Access as dictionary
print(result.extracted_data)

# Dict-like access
print(result["invoice_number"])
print(result.get("total", 0.0))

# Metadata
print(result.status)      # "success"
print(result.filename)    # "invoice.pdf"
print(result.file_type)   # "document"

# Convert to dict
data = result.to_dict()

Configuration

Custom API Endpoint

client = ExtractMonster(
    api_key="your_api_key",
    base_url="https://custom-endpoint.example.com"
)

Custom Timeout

# Default timeout is 300 seconds (5 minutes)
client = ExtractMonster(
    api_key="your_api_key",
    timeout=600  # 10 minutes
)

Examples

Check out the examples directory for more usage examples:

Development

Setup Development Environment

# Clone repository
git clone https://github.com/extract-monster/extract-monster-python.git
cd extract-monster-python

# Install with dev dependencies
pip install -e ".[dev]"

Run Tests

pytest tests/ -v --cov=extract_monster

Code Formatting

# Format code
black extract_monster/ tests/

# Lint code
ruff check extract_monster/ tests/

# Type checking
mypy extract_monster/

Publishing to PyPI

# Build package
python -m build

# Upload to PyPI
python -m twine upload dist/*

API Reference

ExtractMonster

Main client class for interacting with Extract Monster API.

__init__(api_key, base_url, timeout)

Initialize the client.

Parameters:

  • api_key (str, optional): API key for authentication
  • base_url (str, optional): Base URL for API
  • timeout (float, optional): Request timeout in seconds

extract_file(file_path, schema)

Extract data from a file.

Parameters:

  • file_path (str | Path): Path to file
  • schema (Type[BaseModel] | dict, optional): Schema for extraction

Returns: ExtractionResponse

extract_text(text, schema)

Extract data from text.

Parameters:

  • text (str): Text content
  • schema (Type[BaseModel] | dict, optional): Schema for extraction

Returns: ExtractionResponse

Support

License

MIT License - see LICENSE file for details.

Contributing

Contributions are welcome! Please read our Contributing Guidelines first.

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Changelog

See CHANGELOG.md for version history.


Made with ❤️ by the Extract Monster team

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

extract_monster-0.1.0.tar.gz (13.1 kB view details)

Uploaded Source

Built Distribution

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

extract_monster-0.1.0-py3-none-any.whl (10.6 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for extract_monster-0.1.0.tar.gz
Algorithm Hash digest
SHA256 b5d815cb73cb73095df63c69b33fd4dede11000729edafab12db394a53a18c1e
MD5 8ac5dcf11ec9d286ec5093c69d82f91a
BLAKE2b-256 c790776485f1ada6ffcbcb40c34143bff108c0e5113cbbd67112eb9135beeb17

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for extract_monster-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 53a053be79ab4ee3209f07279b7769543c6a1786b169a04ab8de272b1beb6882
MD5 c68d33d216b22afed8b1b57f8ec55efa
BLAKE2b-256 2d1120de8a5e00cd0c30b3e0d8f526d77498e536bd8ed3b8b10ab4037e9e1720

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