Skip to main content

Omniparse Python Bindings

Python bindings for Omniparse - a high-performance library for detecting and extracting metadata, text, and content from various file formats.

Features

  • Multi-format Support: Extract content from PDF, Office documents, images, archives, and more
  • Automatic Detection: Intelligent MIME type detection based on file content
  • Rich Metadata: Extract titles, authors, dates, and format-specific metadata
  • High Performance: Native Rust implementation with Python bindings via PyO3
  • Thread-Safe: Release the GIL during I/O and parsing for true concurrent processing
  • Type Hints: Full type stub support for IDE autocomplete and static type checking

Installation

Install from PyPI:

pip install omniparse-rs

Requirements

  • Python 3.8 or higher
  • No additional dependencies required (pre-built wheels available)

Building from Source

If you need to build from source:

# Install maturin
pip install maturin

# Clone the repository
git clone https://github.com/sirhco/omniparse.git
cd omniparse

# Build and install in development mode
maturin develop --release

Quick Start

Basic Usage

Extract content from a file:

import omniparse

# Extract from a file path
result = omniparse.extract_from_path("document.pdf")

print(f"MIME Type: {result.mime_type}")
print(f"Confidence: {result.detection_confidence}")
print(f"Content: {result.content}")
print(f"Metadata: {result.metadata}")

Extract from Bytes

Process file data already in memory:

import omniparse

# Read file into memory
with open("document.pdf", "rb") as f:
    data = f.read()

# Extract with optional MIME type hint
result = omniparse.extract_from_bytes(data, mime_hint="application/pdf")
print(result.content)

Query Supported Formats

Check which formats are supported:

import omniparse

# Get all supported MIME types
formats = omniparse.supported_mime_types()
print(f"Supports {len(formats)} formats")

# Check if a specific format is supported
if omniparse.is_mime_supported("application/pdf"):
    print("PDF extraction is supported")

API Reference

Functions

extract_from_path(path: str) -> ExtractionResult

Extract content and metadata from a file.

Parameters:

  • path (str): Path to the file to extract from

Returns:

  • ExtractionResult: Object containing extracted data

Raises:

  • IOError: If the file cannot be read or does not exist
  • ValueError: If the file format is unsupported or corrupted
  • RuntimeError: If detection fails or extraction is only partially successful

Example:

result = omniparse.extract_from_path("report.pdf")

extract_from_bytes(data: bytes, mime_hint: Optional[str] = None) -> ExtractionResult

Extract content and metadata from raw bytes.

Parameters:

  • data (bytes): Raw bytes of the file content
  • mime_hint (Optional[str]): Optional MIME type hint to assist detection

Returns:

  • ExtractionResult: Object containing extracted data

Raises:

  • ValueError: If the data format is unsupported or corrupted
  • RuntimeError: If detection fails or extraction is only partially successful

Example:

with open("data.json", "rb") as f:
    result = omniparse.extract_from_bytes(f.read())

supported_mime_types() -> List[str]

Get a list of all supported MIME types.

Returns:

  • List[str]: List of supported MIME type strings

Example:

formats = omniparse.supported_mime_types()

is_mime_supported(mime_type: str) -> bool

Check if a specific MIME type is supported.

Parameters:

  • mime_type (str): MIME type string to check

Returns:

  • bool: True if supported, False otherwise

Example:

if omniparse.is_mime_supported("text/csv"):
    # Process CSV file
    pass

Classes

ExtractionResult

Result object containing extracted file data.

Properties:

  • mime_type (str): The detected MIME type (e.g., "application/pdf")
  • content (Optional[Union[str, bytes]]): Extracted content
    • str for text-based formats
    • bytes for binary formats
    • None if no content extracted
  • metadata (Dict[str, Any]): Dictionary of extracted metadata
  • detection_confidence (float): Confidence score (0.0-1.0) for MIME type detection

Common Metadata Keys:

  • title: Document title
  • author: Document author
  • created: Creation date (ISO 8601 string)
  • modified: Last modification date (ISO 8601 string)
  • page_count: Number of pages
  • word_count: Number of words

Error Handling

Omniparse uses standard Python exceptions:

import omniparse

try:
    result = omniparse.extract_from_path("document.pdf")
    print(result.content)
    
except IOError as e:
    # File not found or cannot be read
    print(f"File access error: {e}")
    
except ValueError as e:
    # Unsupported format or corrupted file
    print(f"Format or parsing error: {e}")
    
except RuntimeError as e:
    # Detection failed or partial extraction
    print(f"Processing error: {e}")

Error Types

  • IOError: Raised when file cannot be accessed or read
  • ValueError: Raised for unsupported formats or corrupted files
  • RuntimeError: Raised when detection fails or extraction is incomplete

Supported Formats

Omniparse supports a wide range of file formats:

Documents

  • PDF (.pdf)
  • Microsoft Word (.doc, .docx)
  • Microsoft PowerPoint (.ppt, .pptx)
  • Microsoft Excel (.xls, .xlsx)
  • OpenDocument (.odt, .ods, .odp)
  • Rich Text Format (.rtf)

Text Formats

  • Plain Text (.txt)
  • JSON (.json)
  • XML (.xml)
  • CSV (.csv)
  • HTML (.html, .htm)
  • CSS (.css)

Images

  • JPEG (.jpg, .jpeg)
  • PNG (.png)
  • TIFF (.tiff, .tif)

Archives

  • ZIP (.zip)
  • TAR (.tar)

Performance Tips

Concurrent Processing

Omniparse releases the Python GIL during I/O and parsing, enabling true concurrent processing:

import omniparse
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

def process_file(file_path):
    """Process a single file."""
    try:
        result = omniparse.extract_from_path(str(file_path))
        return {
            'path': file_path,
            'mime_type': result.mime_type,
            'success': True
        }
    except Exception as e:
        return {
            'path': file_path,
            'error': str(e),
            'success': False
        }

# Process multiple files concurrently
files = list(Path("documents").glob("*.pdf"))

with ThreadPoolExecutor(max_workers=4) as executor:
    results = list(executor.map(process_file, files))

# Print results
for result in results:
    if result['success']:
        print(f"✓ {result['path']}: {result['mime_type']}")
    else:
        print(f"✗ {result['path']}: {result['error']}")

Batch Processing

For processing many files efficiently:

import omniparse
from pathlib import Path

def batch_extract(directory, pattern="*.*"):
    """Extract content from all files matching pattern."""
    results = []
    
    for file_path in Path(directory).glob(pattern):
        if file_path.is_file():
            try:
                result = omniparse.extract_from_path(str(file_path))
                results.append({
                    'file': file_path.name,
                    'mime_type': result.mime_type,
                    'content_length': len(result.content) if result.content else 0,
                    'metadata': result.metadata
                })
            except Exception as e:
                print(f"Error processing {file_path}: {e}")
    
    return results

# Process all PDFs in a directory
results = batch_extract("documents", "*.pdf")
print(f"Processed {len(results)} files")

Memory Efficiency

For large files, consider processing in chunks or streaming:

import omniparse

# For very large files, extract metadata only if possible
result = omniparse.extract_from_path("large_document.pdf")

# Access metadata without loading full content
print(f"Pages: {result.metadata.get('page_count', 'unknown')}")
print(f"Author: {result.metadata.get('author', 'unknown')}")

# Only access content if needed
if result.content:
    # Process content in chunks or save to disk
    content_preview = result.content[:1000]  # First 1000 chars
    print(f"Preview: {content_preview}")

Performance Characteristics

  • Extraction Overhead: < 10% compared to native Rust implementation
  • Thread Scalability: Linear scaling up to CPU core count
  • Memory Overhead: < 5% compared to native Rust implementation
  • Type Conversion: < 1ms for typical results

Examples

Extract Metadata Only

import omniparse

result = omniparse.extract_from_path("document.pdf")

# Access metadata
metadata = result.metadata
print(f"Title: {metadata.get('title', 'Untitled')}")
print(f"Author: {metadata.get('author', 'Unknown')}")
print(f"Created: {metadata.get('created', 'Unknown')}")
print(f"Pages: {metadata.get('page_count', 'Unknown')}")

Process Multiple Formats

import omniparse
from pathlib import Path

def extract_all(directory):
    """Extract content from all supported files in directory."""
    for file_path in Path(directory).iterdir():
        if not file_path.is_file():
            continue
        
        try:
            result = omniparse.extract_from_path(str(file_path))
            print(f"\n{file_path.name}")
            print(f"  Type: {result.mime_type}")
            print(f"  Confidence: {result.detection_confidence:.2f}")
            
            if result.content:
                preview = result.content[:100]
                print(f"  Preview: {preview}...")
                
        except ValueError as e:
            print(f"  Skipped: {e}")

extract_all("mixed_documents")

Validate File Format

import omniparse

def validate_file_type(file_path, expected_mime):
    """Validate that a file matches expected MIME type."""
    result = omniparse.extract_from_path(file_path)
    
    if result.mime_type == expected_mime:
        print(f"✓ Valid {expected_mime}")
        return True
    else:
        print(f"✗ Expected {expected_mime}, got {result.mime_type}")
        return False

# Validate a PDF file
validate_file_type("document.pdf", "application/pdf")

Type Checking

Omniparse includes full type hints for static type checking with mypy:

import omniparse
from typing import List, Dict, Any

def process_documents(paths: List[str]) -> List[Dict[str, Any]]:
    """Process multiple documents and return metadata."""
    results: List[Dict[str, Any]] = []
    
    for path in paths:
        result: omniparse.ExtractionResult = omniparse.extract_from_path(path)
        results.append({
            'mime_type': result.mime_type,
            'metadata': result.metadata
        })
    
    return results

Run mypy to check types:

mypy your_script.py

Contributing

Contributions are welcome! Please see the main repository for contribution guidelines.

License

This project is licensed under either of:

  • MIT License
  • Apache License, Version 2.0

at your option.

Links

Changelog

See CHANGELOG.md for version history and changes.

Metadata

Release files for omniparse-rs 0.2.2

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

Built distributions (wheels)

Table of built distributions (wheels) for omniparse-rs 0.2.2
File
omniparse_rs-0.2.2-cp313-cp313-macosx_11_0_arm64.whl CPython 3.13 CPython 3.13 macOS 11.0+ ARM64 Details
omniparse_rs-0.2.2-cp312-cp312-win_amd64.whl CPython 3.12 CPython 3.12 Windows x86-64 Details
omniparse_rs-0.2.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.12 CPython 3.12 Linux glibc 2.17+ x86-64 Details
omniparse_rs-0.2.2-cp312-cp312-macosx_11_0_arm64.whl CPython 3.12 CPython 3.12 macOS 11.0+ ARM64 Details
omniparse_rs-0.2.2-cp311-cp311-win_amd64.whl CPython 3.11 CPython 3.11 Windows x86-64 Details
omniparse_rs-0.2.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.11 CPython 3.11 Linux glibc 2.17+ x86-64 Details
omniparse_rs-0.2.2-cp311-cp311-macosx_11_0_arm64.whl CPython 3.11 CPython 3.11 macOS 11.0+ ARM64 Details
omniparse_rs-0.2.2-cp310-cp310-win_amd64.whl CPython 3.10 CPython 3.10 Windows x86-64 Details
omniparse_rs-0.2.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.10 CPython 3.10 Linux glibc 2.17+ x86-64 Details
omniparse_rs-0.2.2-cp310-cp310-macosx_11_0_arm64.whl CPython 3.10 CPython 3.10 macOS 11.0+ ARM64 Details
omniparse_rs-0.2.2-cp39-cp39-win_amd64.whl CPython 3.9 CPython 3.9 Windows x86-64 Details
omniparse_rs-0.2.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.9 CPython 3.9 Linux glibc 2.17+ x86-64 Details
omniparse_rs-0.2.2-cp38-cp38-win_amd64.whl CPython 3.8 CPython 3.8 Windows x86-64 Details
omniparse_rs-0.2.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.8 CPython 3.8 Linux glibc 2.17+ x86-64 Details

Total release size: 30.8 MB

Release files / omniparse_rs-0.2.2-cp313-cp313-macosx_11_0_arm64.whl

Download URL omniparse_rs-0.2.2-cp313-cp313-macosx_11_0_arm64.whl
Size 2.1 MB
Tags CPython 3.13 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
437b3f8d802307b03762fab9c7ca0ec6cd778fb1d14ccf0a5222dda1eba09951
BLAKE2b-256 checksum
How to use checksums
410bc7fed3f0d0a14a58161a4788c5dcc0423f2b3c788974394d03475039e5e5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release files / omniparse_rs-0.2.2-cp312-cp312-win_amd64.whl

Download URL omniparse_rs-0.2.2-cp312-cp312-win_amd64.whl
Size 2.0 MB
Tags CPython 3.12 Windows x86-64
SHA-256 checksum
How to use checksums
1353d4bd0c387078b9b6c9a9958658e4af3443e04fd9d1beb0bf33d45cea5104
BLAKE2b-256 checksum
How to use checksums
06c7c311a0dfa2a00e017ad540d84505edd4ddc94507462c9bd7f9b4880b1165
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release files / omniparse_rs-0.2.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL omniparse_rs-0.2.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 2.4 MB
Tags CPython 3.12 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
8e56cac8a68afd0683d82520f783923e9c9058218df1d48ee9dc86a3013a25f7
BLAKE2b-256 checksum
How to use checksums
4192e64c2a288d8cc4ac7d61631000c08ab29bcbfcb51c196cb8239b3083b9e9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release files / omniparse_rs-0.2.2-cp312-cp312-macosx_11_0_arm64.whl

Download URL omniparse_rs-0.2.2-cp312-cp312-macosx_11_0_arm64.whl
Size 2.1 MB
Tags CPython 3.12 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
cdd38a8c90c571ad9980ca4f7532187261f0fea85ad1d287a57b898854c94933
BLAKE2b-256 checksum
How to use checksums
a9399112bb9d00ee3f189a39749e0e19127967fb64054f79595096941a25813a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release files / omniparse_rs-0.2.2-cp311-cp311-win_amd64.whl

Download URL omniparse_rs-0.2.2-cp311-cp311-win_amd64.whl
Size 2.0 MB
Tags CPython 3.11 Windows x86-64
SHA-256 checksum
How to use checksums
e6862f530d586153821039216cddfe744daf2278bd0fb6ba970c07a31b8e741e
BLAKE2b-256 checksum
How to use checksums
644b09433207f0c50e82541866cafaa46e3db3a3e845f70b4ad422df21271cbd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release files / omniparse_rs-0.2.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL omniparse_rs-0.2.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 2.4 MB
Tags CPython 3.11 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
c984dd2f3477a62be1371b61005f5f438940b602840999140ce72bd482796873
BLAKE2b-256 checksum
How to use checksums
ce0b0ddd3f9fe82e8ff673019e5f7b9b03f88111b59235ff64c8f47dd553c099
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release files / omniparse_rs-0.2.2-cp311-cp311-macosx_11_0_arm64.whl

Download URL omniparse_rs-0.2.2-cp311-cp311-macosx_11_0_arm64.whl
Size 2.1 MB
Tags CPython 3.11 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
9139583b0624d13b84a1775ac330027071db3a372fdab5353e60c8d425a6fc62
BLAKE2b-256 checksum
How to use checksums
c51cf49494f99b102c1201986824c337135ea0c727210c3c40f23f00e5711147
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release files / omniparse_rs-0.2.2-cp310-cp310-win_amd64.whl

Download URL omniparse_rs-0.2.2-cp310-cp310-win_amd64.whl
Size 2.0 MB
Tags CPython 3.10 Windows x86-64
SHA-256 checksum
How to use checksums
815be7630ac80dd9f9f0b39c1b87329bc8eb84813d469dd4e2b2fda4919aaec1
BLAKE2b-256 checksum
How to use checksums
4f72cdfcb3c9bbb587c78e5f552804d6ae5a5eb380c0b8b4bf79172816584581
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release files / omniparse_rs-0.2.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL omniparse_rs-0.2.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 2.4 MB
Tags CPython 3.10 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
0914be78c6b1ddbb55bc98b44597d13b832be51f61f1c5f5f7d9949eb53f3981
BLAKE2b-256 checksum
How to use checksums
a46e6f0c72b86d0048207c11933ba0afe05e0b1b1eb66e843ebc0ae35522a892
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release files / omniparse_rs-0.2.2-cp310-cp310-macosx_11_0_arm64.whl

Download URL omniparse_rs-0.2.2-cp310-cp310-macosx_11_0_arm64.whl
Size 2.1 MB
Tags CPython 3.10 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
c723d5bf060d2f249d97662a347a53dd84f96626c0cbfcef1012c7198e29c603
BLAKE2b-256 checksum
How to use checksums
c1edae6497cca77efdfa7889b55bf6cfd424db433c3c790297d12bbf95ae9e7e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release files / omniparse_rs-0.2.2-cp39-cp39-win_amd64.whl

Download URL omniparse_rs-0.2.2-cp39-cp39-win_amd64.whl
Size 2.0 MB
Tags CPython 3.9 Windows x86-64
SHA-256 checksum
How to use checksums
e63fe10dfcdfbcfa820139d42ea1617f18057fcd1be73dd5f7d719b6b725e135
BLAKE2b-256 checksum
How to use checksums
1445d52c1ded2dbbe20a8482522b7a38162cb6d994463b2b1eb0e58e87602f13
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release files / omniparse_rs-0.2.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL omniparse_rs-0.2.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 2.4 MB
Tags CPython 3.9 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
884042bb6f7b68a9bc53c0cc512a996d1f03d422c6716b64a6c73b92839c49ee
BLAKE2b-256 checksum
How to use checksums
36a0ee50ae236b849de4bc1dea1306653a09edddf3099fcaa0574e64ccc344a3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release files / omniparse_rs-0.2.2-cp38-cp38-win_amd64.whl

Download URL omniparse_rs-0.2.2-cp38-cp38-win_amd64.whl
Size 2.0 MB
Tags CPython 3.8 Windows x86-64
SHA-256 checksum
How to use checksums
f25167815fa613657e193de526f520d25a8e2c9e5474f8abce47609290b2bf4f
BLAKE2b-256 checksum
How to use checksums
7c2ac0b069842163107850183d4e8e238447fe615ccb54a03abff75dd482abc6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release files / omniparse_rs-0.2.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL omniparse_rs-0.2.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 2.4 MB
Tags CPython 3.8 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
e4bf960b58711d3fad95eea4e7ddda3ecafb6b4e1a08c9b58988d9ae01cab2fa
BLAKE2b-256 checksum
How to use checksums
780fe706c4c6a0de4ba51d2ca019ae1ed15da2240beba9521d38ef36d9ef8b14
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via maturin/1.10.2

Release history Release notifications | RSS feed

This release

0.2.2 This release

14 release files

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