Skip to main content

Intelligent batch processing tool for Replicate models with automatic fallback mechanisms

Project description

Replicate Batch Process

中文版 README | English | PyPI Package

PyPI version Python 3.8+ License: MIT

Intelligent batch processing tool for Replicate models with automatic fallback mechanisms and concurrent processing.

✨ Key Features

  • 🔄 Intelligent Fallback System - Automatic model switching on incompatibility
  • Smart Concurrency Control - Adaptive rate limiting and batch processing
  • 🎯 Three Usage Modes - Single, batch same-model, and mixed-model processing
  • 📝 Custom File Naming - Ordered output with correspondence control
  • 🛡️ Error Resilience - Comprehensive retry and recovery mechanisms
  • Model Validation - Automatic detection of unsupported models with clear error messages

📦 Installation

pip install replicate-batch-process

🚀 Quick Start

1. Initialize Environment

# Set up API keys (first time only)
replicate-init

2. Single Image Generation

from replicate_batch_process import replicate_model_calling

file_paths = replicate_model_calling(
    prompt="A beautiful sunset over mountains",
    model_name="black-forest-labs/flux-dev",
    output_filepath="output/sunset.jpg"
)

3. Batch Processing

import asyncio
from replicate_batch_process import intelligent_batch_process

files = await intelligent_batch_process(
    prompts=["sunset", "city", "forest"],
    model_name="black-forest-labs/flux-dev",
    max_concurrent=8
)

📋 Supported Models

Image Generation Models

Model Price Specialization Reference Image Support
black-forest-labs/flux-dev $0.025 Fast generation, minimal censorship
black-forest-labs/flux-kontext-max $0.08 Image editing, character consistency
qwen/qwen-image $0.025 Text rendering, cover images
google/imagen-4-ultra $0.06 High-quality detailed images

Video Generation Models

Model Price Specialization Reference Image Support
google/veo-3-fast $3.32/call Fast video with audio
kwaivgi/kling-v2.1-master $0.28/sec 1080p video, 5-10 second duration

⚠️ Note: Using unsupported models will return a clear error message: "Model '{model_name}' is not supported. Please use one of the supported models listed above."

🔄 Intelligent Fallback System

Automatic model switching when issues arise:

Reference Image Auto-Detection

# User provides reference image to non-supporting model
replicate_model_calling(
    prompt="Generate based on this image",
    model_name="black-forest-labs/flux-dev",  # Doesn't support reference images
    input_image="path/to/image.jpg"           # → Auto-switches to flux-kontext-max
)

Parameter Compatibility Handling

# Unsupported parameters automatically cleaned and model switched
replicate_model_calling(
    prompt="Generate image",
    model_name="black-forest-labs/flux-kontext-max",
    guidance=3.5,        # Unsupported parameter
    num_outputs=2        # → Auto-switches to compatible model
)

API Error Recovery

Automatic fallback chain: Flux DevQwen ImageImagen 4 Ultra

📋 Usage Scenarios

Mode Use Case Command
Single One-off generation, testing replicate_model_calling()
Batch Same Multiple prompts, same model intelligent_batch_process()
Mixed Models Different models/parameters IntelligentBatchProcessor()

🧠 Smart Processing Strategies

The system automatically selects optimal processing strategy:

  • Immediate Processing: Tasks ≤ available quota → Full concurrency
  • Window Processing: Tasks ≤ 600 but > current quota → Wait then batch
  • Dynamic Queue: Tasks > 600 → Continuous processing with queue management

⚙️ Configuration

API Keys

Get your Replicate API token: replicate.com/account/api-tokens

Custom Fallback Rules

Modify config.py:

FALLBACK_MODELS = {
    'your-model': {
        'fail': {
            'fallback_model': 'backup-model',
            'condition': 'api_error'
        }
    }
}

📊 Rate Limiting

  • Replicate API: 600 requests/minute (shared across all models)
  • Recommended Concurrency: 5-8 (conservative) to 12 (aggressive)
  • Auto-Retry: Built-in 429 error handling with exponential backoff

💡 Best Practices

# For large batches, use chunking
def process_large_batch(prompts, chunk_size=50):
    for chunk in chunks(prompts, chunk_size):
        files = await intelligent_batch_process(chunk, model_name)
        yield files

# Error handling
for result in results:
    if result.success:
        print(f"✅ Generated: {result.file_paths}")
    else:
        print(f"❌ Failed: {result.error}")

🏗️ Project Structure

replicate-batch-process/
├── main.py                      # Single image generation
├── intelligent_batch_processor.py  # Batch processing engine
├── config.py                    # Model configurations & fallbacks
├── init_environment.py          # Environment setup
└── example_usage.py            # Complete examples

🔧 Development

# Clone repository
git clone https://github.com/preangelleo/replicate_batch_process.git

# Install in development mode
pip install -e .

# Run examples
python example_usage.py

📄 License

MIT License - see LICENSE file for details.

🤝 Contributing

  1. Fork the repository
  2. Create your 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

🔗 Links


Made with ❤️ for the AI community

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

replicate_batch_process-1.0.4.tar.gz (59.5 kB view details)

Uploaded Source

Built Distribution

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

replicate_batch_process-1.0.4-py3-none-any.whl (34.1 kB view details)

Uploaded Python 3

File details

Details for the file replicate_batch_process-1.0.4.tar.gz.

File metadata

  • Download URL: replicate_batch_process-1.0.4.tar.gz
  • Upload date:
  • Size: 59.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.23

File hashes

Hashes for replicate_batch_process-1.0.4.tar.gz
Algorithm Hash digest
SHA256 bdc0be4bc455e8c41457fcf8ac80a8119e0f7e45d9744ffff689f4c58d3b1eed
MD5 ad9e7610f2227ae878ca6661d3861eb8
BLAKE2b-256 496b57f5663113c1913176dc4f9957b4b7c118fcfcda9ba9f0ffa59fbc78fc29

See more details on using hashes here.

File details

Details for the file replicate_batch_process-1.0.4-py3-none-any.whl.

File metadata

File hashes

Hashes for replicate_batch_process-1.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 a8183c050f1090e224b6bf872e02ce0a9e632ab22ee05ea8a7f227ab08f75afa
MD5 b09100cf7bfb12ab080add607a4596a5
BLAKE2b-256 501672e10f776bda4c667a0d82853edc21815a5c26dd4c0b9c021759fb63e986

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