Skip to main content

Magic Hour Python SDK

Requires Python 3.10 or newer.

PyPI - Version

The Magic Hour Python Library provides convenient access to the Magic Hour API. This library offers both synchronous and asynchronous clients powered by httpx.

Documentation

For full documentation of all APIs, please visit https://docs.magichour.ai

If you have any questions, please reach out to us via discord.

Install

pip install magic_hour

Cookbook

For end-to-end examples demonstrating all available Magic Hour APIs, check out our interactive Google Colab cookbook:

The cookbook includes:

  • Setup instructions
  • Examples for all available APIs (image generation, face swap, lip sync, video generation, and more)
  • Display helpers for previewing outputs
  • Production-ready patterns and best practices

Synchronous Client Usage

from magic_hour import Client

# generate your API Key at https://magichour.ai/developer
client = Client(token="my api key")

response = client.v1.face_swap_photo.generate(
    assets={
        "face_swap_mode": "all-faces",
        "source_file_path": "/path/to/source/image.png",
        "target_file_path": "/path/to/target/image.png",
    },
    name="Face Swap image",
    wait_for_completion=True,
    download_outputs=True,
    download_directory=".",
)
print(f"Project ID: {response.id}")
print(f"Status: {response.status}")
print(f"Downloaded files: {response.downloaded_paths}")

Asynchronous Client Usage

from magic_hour import AsyncClient

# generate your API Key at https://magichour.ai/developer
client = AsyncClient(token="my api key")

response = await client.v1.face_swap_photo.generate(
    assets={
        "face_swap_mode": "all-faces",
        "source_file_path": "/path/to/source/image.png",
        "target_file_path": "/path/to/target/image.png",
    },
    name="Face Swap image",
    wait_for_completion=True,
    download_outputs=True,
    download_directory=".",
)
print(f"Project ID: {response.id}")
print(f"Status: {response.status}")
print(f"Downloaded files: {response.downloaded_paths}")

Client Functions

Most resources that generate media content support two methods:

  • generate() - A high-level convenience method that handles the entire workflow
  • create() - A low-level method that only initiates the generation process

Generate Function

The generate() function provides a complete end-to-end solution:

  • Uploads local file to Magic Hour storage
  • Calls the API to start generation
  • Automatically polls for completion
  • Downloads generated files to your local machine
  • Returns both API response data and local file paths

Additional Parameters:

  • wait_for_completion (bool, default True): Whether to wait for the project to complete.
  • download_outputs (bool, default True): Save completed files locally when wait_for_completion is true.
  • download_directory (str, optional): Directory to save downloaded files (defaults to current directory)
  • max_wait_seconds (float, optional): Maximum seconds to keep polling. See Bounding Polling.

Downloads preserve existing files. If a filename is occupied, the SDK adds a numeric suffix, such as output_1.png. Use downloaded_paths for the saved filenames. Downloading a completed project again saves another copy.

# Generate function - handles everything automatically
response = client.v1.ai_image_generator.generate(
    style={"prompt": "A beautiful sunset over mountains"},
    name="Sunset Image",
    wait_for_completion=True,       # Wait for status to be complete/error/canceled
    download_outputs=True,          # Download files automatically
    download_directory="./outputs/" # Where to save files
)

# You get both the API response AND downloaded file paths
print(f"Project ID: {response.id}")
print(f"Status: {response.status}")
print(f"Downloaded files: {response.downloaded_paths}")

Create Function

The create() function provides granular control:

  • Only calls the API to start the generation process
  • Returns immediately with a project ID and amount of credits used
  • Requires manual status checking and file downloading
# Create function - only starts the process
create_response = client.v1.ai_image_generator.create(
    style={"prompt": "A beautiful sunset over mountains"},
    name="Sunset Image"
)

# You get just the project ID and initial response
project_id = create_response.id
print(f"Started project: {project_id}")

# You must handle the rest:
# 1. Poll for completion. We provide a helper function to handle polling for you
result = client.v1.image_projects.check_result(
    id=project_id,
    wait_for_completion=True,
    download_outputs=False,
)
# 2. Download files using the download URLs
download_urls = result.downloads
# download the files using your preferred way

Choosing Between Which Function to use

Use generate() when:

  • You want a simple, one-call solution
  • You're building a straightforward application
  • You don't need custom polling or download logic

Use create() when:

  • You need custom status checking logic
  • You're integrating with existing job processing systems
  • You want to separate generation initiation from completion handling
  • You need fine-grained control over the entire workflow

Bounding Polling

By default, polling continues until the project is complete, error or canceled. Pass max_wait_seconds, or set MAGIC_HOUR_MAX_WAIT_SECONDS, to stop polling after that many seconds. The SDK then returns the latest response as is (for example status="rendering"), without downloads. The project is not canceled and keeps running, so do not create a new one. Call client.v1.video_projects.check_result(id=...) to resume. It bounds the polling loop only; per-request HTTP timeouts are separate. Values not greater than 0 are ignored.

from magic_hour import Client

client = Client(token=getenv("API_TOKEN"))

result = client.v1.text_to_video.generate(
    end_seconds=5.0,
    style={"prompt": "a dog running through a meadow"},
    max_wait_seconds=300,
)

if result.status in ("queued", "rendering"):
    result = client.v1.video_projects.check_result(
        id=result.id,
        wait_for_completion=True,
        download_outputs=True,
    )

Idempotent Requests

Project create endpoints accept an Idempotency-Key header, so you can safely retry a request without creating or paying for a second project. Repeating a key within 24 hours returns the original project. Keys are shared across your account, so use a new key, such as a UUID, for each project.

client.v1.ai_image_generator.create(
    image_count=1,
    style={"prompt": "Cool image"},
    request_options={"additional_headers": {"Idempotency-Key": "5f3c1b9e-8a41-4a0e-9d3e-2f6a1c7b9e10"}},
)

With generate():

client.v1.ai_image_generator.generate(
    image_count=1,
    style={"prompt": "Cool image"},
    request_options={"additional_headers": {"Idempotency-Key": "5f3c1b9e-8a41-4a0e-9d3e-2f6a1c7b9e10"}},
)

Webhooks

Webhooks notify your server when a project starts, completes or fails. webhooks.construct_event checks that a request was signed with your webhook secret and that its timestamp is within 5 minutes of now, then returns the event with the same typed payload as video_projects.get, image_projects.get or audio_projects.get.

Pass it the raw request body and the request headers. It reads the signature and timestamp headers itself, from request.headers in FastAPI, Flask or Django, or from a plain dict.

The webhook secret is read from the MAGIC_HOUR_WEBHOOK_SECRET environment variable. Pass secret to use another one, and tolerance to change the 5-minute window, in seconds.

It raises webhooks.WebhookVerificationError if the signature or timestamp check fails, ValueError if there is no webhook secret, and pydantic.ValidationError if the body is not a video.*, image.* or audio.* event known to this SDK version.

The signature covers the raw request body, so read the body as bytes or text instead of parsed JSON:

from fastapi import FastAPI, HTTPException, Request
from magic_hour import webhooks

app = FastAPI()


@app.post("/webhook")
async def webhook(request: Request):
    try:
        event = webhooks.construct_event(await request.body(), request.headers)
    except webhooks.WebhookVerificationError:
        raise HTTPException(status_code=400)

    if event.type == "video.completed":
        print(event.payload.id, event.payload.downloads)
    return {"success": True}

Module Documentation and Snippets

v1.account

  • list - Get account details

v1.account.checkout

v1.ai_clothes_changer

  • create - AI Clothes Changer
  • generate - AI Clothes Changer Generate Workflow

v1.ai_face_editor

v1.ai_gif_generator

  • create - AI GIF Generator
  • generate - Ai Gif Generator Generate Workflow

v1.ai_headshot_generator

  • create - AI Headshot Generator
  • generate - Ai Headshot Generator Generate Workflow

v1.ai_image_editor

  • create - AI Image Editor
  • generate - Ai Image Editor Generate Workflow

v1.ai_image_generator

  • create - AI Image Generator
  • generate - Ai Image Generator Generate Workflow

v1.ai_image_upscaler

  • create - AI Image Upscaler
  • generate - Ai Image Upscaler Generate Workflow

v1.ai_meme_generator

  • create - AI Meme Generator
  • generate - Ai Meme Generator Generate Workflow

v1.ai_music_generator

v1.ai_qr_code_generator

  • create - AI QR Code Generator
  • generate - Ai Qr Code Generator Generate Workflow

v1.ai_talking_photo

  • create - AI Talking Photo
  • generate - Ai Talking Photo Generate Workflow

v1.ai_ugc_ad

  • create - AI UGC Ad Generator

v1.ai_video_editor

  • create - AI Video Editor
  • generate - AI Video Editor Generate Workflow

v1.ai_video_translator

v1.ai_video_upscaler

v1.ai_voice_cloner

v1.ai_voice_generator

  • create - AI Voice Generator
  • generate - Ai Voice Generator Generate Workflow

v1.animation

v1.audio_projects

v1.audio_to_video

v1.auto_subtitle_generator

  • create - Auto Subtitle Generator
  • generate - Auto Subtitle Generator Generate Workflow

v1.body_swap

v1.character_replace

  • create - Character Replace
  • generate - Character Replace Generate Workflow

v1.estimate.audio

  • list - Estimate audio credits

v1.estimate.image

  • list - Estimate image credits

v1.estimate.video

  • list - Estimate video credits

v1.face_detection

  • create - Face Detection
  • generate - Face Detection Generate Workflow
  • get - Get face detection details

v1.face_swap

v1.face_swap_photo

  • create - Face Swap Photo
  • generate - Face Swap Photo Generate Workflow

v1.files

v1.files.upload_urls

  • create - Generate asset upload urls

v1.head_swap

v1.image_background_remover

  • create - Image Background Remover
  • generate - Image Background Remover Generate Workflow

v1.image_projects

v1.image_to_video

v1.lip_sync

v1.photo_colorizer

  • create - Photo Colorizer
  • generate - Photo Colorizer Generate Workflow

v1.saved_items

  • list - List saved items

v1.text_to_video

v1.video_projects

v1.video_to_video

v1.voices

  • list - List voices

Metadata

Release files for magic-hour 0.105.5

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

Source distribution (sdist)

Source distribution for magic-hour 0.105.5
File Size Uploaded Provenance Actions
magic_hour-0.105.5.tar.gz 203.8 kB With provenance Details for magic_hour-0.105.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for magic-hour 0.105.5
File Interpreter ABI Platform Actions
magic_hour-0.105.5-py3-none-any.whl Python 3 none any Details for magic_hour-0.105.5-py3-none-any.whl

Total release size: 611.2 kB

Release files / magic_hour-0.105.5.tar.gz

Download URL magic_hour-0.105.5.tar.gz
Size 203.8 kB
Tags Source
SHA-256 checksum
How to use checksums
8cb9afcfa5611a6fd4ac286f84efe6ed1b50263bf00a057bc292d3d2239dcffb
BLAKE2b-256 checksum
How to use checksums
f8fd140a6b5eb4b46b533edacfe3d922bcb6bd13f5dde40ab79d0a0f0dea83fa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Release files / magic_hour-0.105.5-py3-none-any.whl

Download URL magic_hour-0.105.5-py3-none-any.whl
Size 407.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
67cf285da736d748641e1e60c31ce530e3c5e8936564537a30cbc186cdf38e50
BLAKE2b-256 checksum
How to use checksums
baacd80db7b9de4d9454c563f668ed934c8829737f406c2cfdcc93fc4dfc7d7f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Security for magic-hour 0.105.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for magic_hour-0.105.5.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.105.5 This release

2 release files Full provenance

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