Skip to main content

A Python library for detecting and extracting metadata, text, and content from various file formats

Project description

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.

Project details


Download files

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

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

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

omniparse_rs-0.2.2-cp313-cp313-macosx_11_0_arm64.whl (2.1 MB view details)

Uploaded CPython 3.13macOS 11.0+ ARM64

omniparse_rs-0.2.2-cp312-cp312-win_amd64.whl (2.0 MB view details)

Uploaded CPython 3.12Windows x86-64

omniparse_rs-0.2.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.4 MB view details)

Uploaded CPython 3.12manylinux: glibc 2.17+ x86-64

omniparse_rs-0.2.2-cp312-cp312-macosx_11_0_arm64.whl (2.1 MB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

omniparse_rs-0.2.2-cp311-cp311-win_amd64.whl (2.0 MB view details)

Uploaded CPython 3.11Windows x86-64

omniparse_rs-0.2.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.4 MB view details)

Uploaded CPython 3.11manylinux: glibc 2.17+ x86-64

omniparse_rs-0.2.2-cp311-cp311-macosx_11_0_arm64.whl (2.1 MB view details)

Uploaded CPython 3.11macOS 11.0+ ARM64

omniparse_rs-0.2.2-cp310-cp310-win_amd64.whl (2.0 MB view details)

Uploaded CPython 3.10Windows x86-64

omniparse_rs-0.2.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.4 MB view details)

Uploaded CPython 3.10manylinux: glibc 2.17+ x86-64

omniparse_rs-0.2.2-cp310-cp310-macosx_11_0_arm64.whl (2.1 MB view details)

Uploaded CPython 3.10macOS 11.0+ ARM64

omniparse_rs-0.2.2-cp39-cp39-win_amd64.whl (2.0 MB view details)

Uploaded CPython 3.9Windows x86-64

omniparse_rs-0.2.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.4 MB view details)

Uploaded CPython 3.9manylinux: glibc 2.17+ x86-64

omniparse_rs-0.2.2-cp38-cp38-win_amd64.whl (2.0 MB view details)

Uploaded CPython 3.8Windows x86-64

omniparse_rs-0.2.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.4 MB view details)

Uploaded CPython 3.8manylinux: glibc 2.17+ x86-64

File details

Details for the file omniparse_rs-0.2.2-cp313-cp313-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp313-cp313-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 437b3f8d802307b03762fab9c7ca0ec6cd778fb1d14ccf0a5222dda1eba09951
MD5 f75db631d7efb34590ca4a6d5a39834d
BLAKE2b-256 410bc7fed3f0d0a14a58161a4788c5dcc0423f2b3c788974394d03475039e5e5

See more details on using hashes here.

File details

Details for the file omniparse_rs-0.2.2-cp312-cp312-win_amd64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 1353d4bd0c387078b9b6c9a9958658e4af3443e04fd9d1beb0bf33d45cea5104
MD5 d544a21619f1eb862a66c34029c77867
BLAKE2b-256 06c7c311a0dfa2a00e017ad540d84505edd4ddc94507462c9bd7f9b4880b1165

See more details on using hashes here.

File details

Details for the file omniparse_rs-0.2.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 8e56cac8a68afd0683d82520f783923e9c9058218df1d48ee9dc86a3013a25f7
MD5 0bfa6086b6ce6bbd95c70e50cfca2bde
BLAKE2b-256 4192e64c2a288d8cc4ac7d61631000c08ab29bcbfcb51c196cb8239b3083b9e9

See more details on using hashes here.

File details

Details for the file omniparse_rs-0.2.2-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 cdd38a8c90c571ad9980ca4f7532187261f0fea85ad1d287a57b898854c94933
MD5 55b958441f66f9d3c0fbbc843cdfdfc6
BLAKE2b-256 a9399112bb9d00ee3f189a39749e0e19127967fb64054f79595096941a25813a

See more details on using hashes here.

File details

Details for the file omniparse_rs-0.2.2-cp311-cp311-win_amd64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 e6862f530d586153821039216cddfe744daf2278bd0fb6ba970c07a31b8e741e
MD5 bf8ad45c345f4f418b045b2983029ce3
BLAKE2b-256 644b09433207f0c50e82541866cafaa46e3db3a3e845f70b4ad422df21271cbd

See more details on using hashes here.

File details

Details for the file omniparse_rs-0.2.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 c984dd2f3477a62be1371b61005f5f438940b602840999140ce72bd482796873
MD5 c939c5861bd67a0c7cca0021eafb4b9b
BLAKE2b-256 ce0b0ddd3f9fe82e8ff673019e5f7b9b03f88111b59235ff64c8f47dd553c099

See more details on using hashes here.

File details

Details for the file omniparse_rs-0.2.2-cp311-cp311-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp311-cp311-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 9139583b0624d13b84a1775ac330027071db3a372fdab5353e60c8d425a6fc62
MD5 edf90302a49a315e8c79122d0936ba12
BLAKE2b-256 c51cf49494f99b102c1201986824c337135ea0c727210c3c40f23f00e5711147

See more details on using hashes here.

File details

Details for the file omniparse_rs-0.2.2-cp310-cp310-win_amd64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 815be7630ac80dd9f9f0b39c1b87329bc8eb84813d469dd4e2b2fda4919aaec1
MD5 b0002c41ae499556dbec3892aec00c02
BLAKE2b-256 4f72cdfcb3c9bbb587c78e5f552804d6ae5a5eb380c0b8b4bf79172816584581

See more details on using hashes here.

File details

Details for the file omniparse_rs-0.2.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 0914be78c6b1ddbb55bc98b44597d13b832be51f61f1c5f5f7d9949eb53f3981
MD5 2df85a01cae87f20893f30e87b6fe31e
BLAKE2b-256 a46e6f0c72b86d0048207c11933ba0afe05e0b1b1eb66e843ebc0ae35522a892

See more details on using hashes here.

File details

Details for the file omniparse_rs-0.2.2-cp310-cp310-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp310-cp310-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 c723d5bf060d2f249d97662a347a53dd84f96626c0cbfcef1012c7198e29c603
MD5 cb43a801cf560264d20c43b1493de365
BLAKE2b-256 c1edae6497cca77efdfa7889b55bf6cfd424db433c3c790297d12bbf95ae9e7e

See more details on using hashes here.

File details

Details for the file omniparse_rs-0.2.2-cp39-cp39-win_amd64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp39-cp39-win_amd64.whl
Algorithm Hash digest
SHA256 e63fe10dfcdfbcfa820139d42ea1617f18057fcd1be73dd5f7d719b6b725e135
MD5 cd51347fdfdb65925a451bde4a8fc5cf
BLAKE2b-256 1445d52c1ded2dbbe20a8482522b7a38162cb6d994463b2b1eb0e58e87602f13

See more details on using hashes here.

File details

Details for the file omniparse_rs-0.2.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 884042bb6f7b68a9bc53c0cc512a996d1f03d422c6716b64a6c73b92839c49ee
MD5 fca866f8d9e6336bd21b80f3e078ca41
BLAKE2b-256 36a0ee50ae236b849de4bc1dea1306653a09edddf3099fcaa0574e64ccc344a3

See more details on using hashes here.

File details

Details for the file omniparse_rs-0.2.2-cp38-cp38-win_amd64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp38-cp38-win_amd64.whl
Algorithm Hash digest
SHA256 f25167815fa613657e193de526f520d25a8e2c9e5474f8abce47609290b2bf4f
MD5 760fbf3d25cda7e526a5e5e0f1318038
BLAKE2b-256 7c2ac0b069842163107850183d4e8e238447fe615ccb54a03abff75dd482abc6

See more details on using hashes here.

File details

Details for the file omniparse_rs-0.2.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for omniparse_rs-0.2.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 e4bf960b58711d3fad95eea4e7ddda3ecafb6b4e1a08c9b58988d9ae01cab2fa
MD5 2452b86421725dcec999544fef844af5
BLAKE2b-256 780fe706c4c6a0de4ba51d2ca019ae1ed15da2240beba9521d38ef36d9ef8b14

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