Skip to main content

Enhanced Python SDK for LemonSlice API with retry logic and better error handling

Project description

๐Ÿ‹ LemonMeringue

v0.1.2 โ€” Upcoming in a future LemonMeringue release: Support for Instagram!

A fluffy layer of reliability and ease-of-use on top of the LemonSlice API

Enhanced Python SDK for the LemonSlice API with automatic retry logic, progress tracking, better error handling, and batch processing.

PyPI version Python Support License: MIT

๐Ÿ“š Table of Contents

๐ŸŽฏ Why LemonMeringue?

Before (Raw LemonSlice API):

# 20+ lines of boilerplate code
import requests
import time

response = requests.post("https://lemonslice.com/api/v2/generate",
    headers={"Authorization": "Bearer your_key"},
    json={"img_url": "...", "voice_id": "...", "text": "..."}
)

job_id = response.json()["job_id"]

# Manual polling loop
while True:
    status = requests.get(f"https://lemonslice.com/api/v2/generations/{job_id}")
    if status.json()["status"] == "completed":
        break
    time.sleep(5)  # Hope nothing goes wrong!

# Manual error handling, no retries, no progress tracking...

After (LemonMeringue):

# 3 lines of code - everything handled automatically
from lemonmeringue import LemonSliceClient, Voices

async def main():
    async with LemonSliceClient(api_key) as client:
        result = await client.quick_generate_text(
            img_url=img_url,
            voice_id=Voices.ANDREA,
            text="Hello world!"
        )
        print(f"โœ… Video ready: {result.video_url}")

# ... existing code ...
### ๐Ÿš€ **Convenience Functions**

- **Problem**: Setting up clients and making requests is verbose
- **Solution**: `client.quick_generate_text()` and `client.quick_generate_audio()` for simple use cases, context managers for complex ones

## โœจ Key Features

### ๐Ÿ”„ **Automatic Retry Logic**

- **Problem**: LemonSlice API sometimes has temporary issues (500 errors, rate limits)
- **Solution**: Exponential backoff retries with configurable settings

### ๐Ÿ“Š **Progress Tracking**

- **Problem**: Users don't know how long generation takes or current status
- **Solution**: Real-time progress callbacks with status updates

### โœ… **Input Validation**

- **Problem**: Invalid parameters cause confusing API errors
- **Solution**: Pre-validation with clear error messages before API calls

### ๐Ÿ“ฆ **Batch Processing**

- **Problem**: Generating 10 videos = 10 separate API calls + manual management
- **Solution**: Concurrent batch processing with automatic queue management

### ๐Ÿš€ **Convenience Functions**

- **Problem**: Setting up clients and making requests is verbose
- **Solution**: `client.quick_generate_text()` and `client.quick_generate_audio()` for simple use cases, context managers for complex ones

### ๐ŸŽฏ **Type Hints & IDE Support**

- **Problem**: Users don't know what parameters are available
- **Solution**: Full type hints for auto-completion and error detection

## ๐Ÿš€ Quick Start

### Installation

```bash
pip install lemonmeringue

Basic Usage

import asyncio
from lemonmeringue import LemonSliceClient, GenerationRequest, Voices

async def main():
    async with LemonSliceClient("your_api_key") as client:
        # Generate a video with progress tracking
        response = await client.generate_video(
            GenerationRequest(
                img_url="https://example.com/image.jpg",
                voice_id=Voices.ANDREA,
                text="Hello, this is a test!",
                expressiveness=0.8
            ),
            on_progress=lambda r: print(f"Status: {r.status.value}")
        )

        print(f"โœ… Video generated: {response.video_url}")
        print(f"โฑ๏ธ  Processing time: {response.processing_time:.1f}s")

asyncio.run(main())

Quick Generate (One-liner)

import asyncio
from lemonmeringue import LemonSliceClient, Voices

async def main():
    async with LemonSliceClient("your_api_key") as client:
        # Quick generate from text and voice
        result = await client.quick_generate_text(
            img_url="https://example.com/image.jpg",
            voice_id=Voices.ANDREA,
            text="Hello world!"
        )
        print(f"Video (text+voice): {result.video_url}")

        # Quick generate from audio file
        result2 = await client.quick_generate_audio(
            img_url="https://example.com/image.jpg",
            audio_url="https://example.com/audio.mp3"
        )
        print(f"Video (audio): {result2.video_url}")

asyncio.run(main())

๐Ÿงช Testing Guide

Note: As of June 19, 2025, running the complete test suite costs approximately $0.60 in LemonSlice API credits.

1. Set Up Your Environment

# In your lemonmeringue repo directory
export LEMONSLICE_API_KEY="your_actual_api_key_here"

2. Run All Tests

python setup_and_test.py

3. Run Comprehensive Feature Tests

python test_all_features.py

4. Quick Test Only

python setup_and_test.py test-only

What Gets Tested

  • โœ… Basic Functionality (video generation)
  • โœ… Progress Tracking (real-time status)
  • โœ… Input Validation (invalid parameters)
  • โœ… Quick Generate (convenience function)
  • โœ… Batch Processing (multiple videos)
  • โœ… Retry Logic (error handling)
  • โœ… Different Voices (voice options)
  • โœ… Error Handling (exceptions)
  • โœ… URL Validation (input checking)
  • โœ… Parameter Testing (models/resolutions)

Example Output

๐Ÿงช Starting LemonMeringue comprehensive test suite...
๐Ÿ”‘ Using API key: sk_1234...
๐Ÿ–ผ๏ธ  Test image: https://6ammc3n5zzf5ljnz...

๐Ÿงช Test 1/10: Basic Functionality
โœ… Basic Functionality: Generated in 45.2s

๐Ÿงช Test 2/10: Progress Tracking
   ๐Ÿ“Š Progress update: processing
   ๐Ÿ“Š Progress update: completed
โœ… Progress Tracking: 2 status updates received

...

๐Ÿ“Š Test Summary: 10/10 passed
๐ŸŽ‰ All tests passed! LemonMeringue is working perfectly!

Ready to Test?
Just set your API key and run python setup_and_test.py to verify all features with the real LemonSlice API. No file uploads neededโ€”public image URLs are used.

๐Ÿ”ง Advanced Usage

Batch Processing

Generate multiple videos concurrently:

requests = [
    {"img_url": "img1.jpg", "voice_id": Voices.ANDREA, "text": "First video"},
    {"img_url": "img2.jpg", "voice_id": Voices.RUSSO, "text": "Second video"},
    {"img_url": "img3.jpg", "voice_id": Voices.EMMA, "text": "Third video"},
]

responses = await client.generate_batch(
    requests,
    on_progress=lambda i, total, response: print(f"Video {i}/{total}: {response.status.value}"),
    max_concurrent=3
)

for i, response in enumerate(responses):
    if isinstance(response, Exception):
        print(f"โŒ Video {i+1} failed: {response}")
    else:
        print(f"โœ… Video {i+1}: {response.video_url}")

Custom Retry Configuration

from lemonmeringue import RetryConfig

retry_config = RetryConfig(
    max_retries=5,
    backoff_factor=1.5,
    max_backoff=120.0
)

client = LemonSliceClient(
    api_key="your_api_key",
    retry_config=retry_config,
    enable_logging=True
)

Input Validation

# Validate URLs before generation
validation = await client.validate_inputs(
    img_url="https://example.com/image.jpg",
    audio_url="https://example.com/audio.mp3"
)

if validation['img_url_valid'] and validation.get('audio_url_valid', True):
    # Proceed with generation
    pass
else:
    print("โŒ Invalid input URLs")

๐ŸŽญ Available Voices

from lemonmeringue import Voices

# Popular voices
Voices.ANDREA    # Young woman, Spanish, calm, soft
Voices.RUSSO     # Middle-aged man, Australian, narrator
Voices.EMMA      # Young woman, German
Voices.GIOVANNI  # Young man, Italian, deep
Voices.RUSSELL   # Middle-aged man, British, dramatic

# Use in requests
request = GenerationRequest(
    img_url="image.jpg",
    voice_id=Voices.ANDREA,
    text="Your text here"
)

๐Ÿ› ๏ธ Configuration Options

Generation Parameters

request = GenerationRequest(
    img_url="https://example.com/image.jpg",
    audio_url="https://example.com/audio.mp3",  # Optional
    voice_id=Voices.ANDREA,                     # For TTS
    text="Text to speak",                       # For TTS
    model="V2.5",                              # V2 or V2.5
    resolution="512",                          # 320, 512, or 640
    crop_head=False,                           # Focus on head region
    animation_style="autoselect",              # autoselect, face_only, entire_image
    expressiveness=1.0,                        # 0.0 to 1.0
)

Client Configuration

client = LemonSliceClient(
    api_key="your_api_key",
    timeout=60,                    # Request timeout in seconds
    enable_logging=True,           # Enable debug logging
    retry_config=RetryConfig(...)  # Custom retry behavior
)

๐Ÿ” Error Handling

from lemonmeringue import APIError, ValidationError

try:
    response = await client.generate_video(request)
except ValidationError as e:
    print(f"โŒ Invalid input: {e}")
except APIError as e:
    print(f"โŒ API error ({e.status_code}): {e}")
    if e.response:
        print(f"Response details: {e.response}")
except Exception as e:
    print(f"โŒ Unexpected error: {e}")

๐Ÿ“Š Response Information

response = await client.generate_video(request)

print(f"Job ID: {response.job_id}")
print(f"Status: {response.status.value}")
print(f"Video URL: {response.video_url}")
print(f"Processing time: {response.processing_time:.1f}s")
print(f"Created at: {response.created_at}")

๐Ÿ”— API Compatibility

This SDK wraps the LemonSlice API v2. You'll need a LemonSlice API key to use this package.

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

๐Ÿ”— Links


Made with ๐Ÿ‹ by Neel Datta

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

lemonmeringue-0.1.2.tar.gz (16.1 kB view details)

Uploaded Source

Built Distribution

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

lemonmeringue-0.1.2-py3-none-any.whl (10.4 kB view details)

Uploaded Python 3

File details

Details for the file lemonmeringue-0.1.2.tar.gz.

File metadata

  • Download URL: lemonmeringue-0.1.2.tar.gz
  • Upload date:
  • Size: 16.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.12

File hashes

Hashes for lemonmeringue-0.1.2.tar.gz
Algorithm Hash digest
SHA256 ab7e01bf063f717ce68e84c2aef9c8562075646b08878a3585030d2eab34550f
MD5 e95e8170f9702cce8b3f4e36a65d5b5d
BLAKE2b-256 050eda40e7e0442b4d3f39d267296c24c07f64d2a145d9a82f88f793780aefc6

See more details on using hashes here.

File details

Details for the file lemonmeringue-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: lemonmeringue-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 10.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.12

File hashes

Hashes for lemonmeringue-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 45933b00b78ee8c58c737c691ddc3095921f8c237afdd346f6f45f48931e2fa7
MD5 5acf64bf20af51a5d9edb002b4bc0339
BLAKE2b-256 6aea7de9a195f7b93058b97c82ae128b762e1f644c1fc43c6bb2fd375c031d95

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