Skip to content

🎥 Make videos programmatically with React

lambda-python: Implement S3 payload compression for large input props

copilot-swe-agent[bot]f1bc1e5f315b
diff --git a/packages/docs/docs/lambda/python.mdx b/packages/docs/docs/lambda/python.mdx
index eb494729be..fde7baabad 100644
--- a/packages/docs/docs/lambda/python.mdx
+++ b/packages/docs/docs/lambda/python.mdx
@@ -14,7 +14,9 @@ You first need to [complete the Lambda setup](/docs/lambda/setup).
## Limitations
-Sending large input props (>200KB) is not supported with Python at the moment.
+~~Sending large input props (>200KB) is not supported with Python at the moment.~~ _available from v4.0.315_
+
+Starting from v4.0.315, the Python SDK automatically handles large input props by uploading them to S3 when they exceed AWS Lambda payload limits. Props larger than 200KB for video renders and 5MB for still renders are automatically compressed using the same logic as the JavaScript SDK.
## Rendering a video
@@ -47,6 +49,13 @@ client = RemotionClient(region=REMOTION_APP_REGION,
serve_url=REMOTION_APP_SERVE_URL,
function_name=REMOTION_APP_FUNCTION_NAME)
+# For large input props, optionally specify a bucket name
+# If not specified, a bucket will be created automatically
+# client = RemotionClient(region=REMOTION_APP_REGION,
+# serve_url=REMOTION_APP_SERVE_URL,
+# function_name=REMOTION_APP_FUNCTION_NAME,
+# bucket_name="my-remotion-bucket")
+
# Set render request
render_params = RenderMediaParams(
composition="react-svg",
@@ -76,6 +85,32 @@ if render_response:
print("Render done!", progress_response.outputFile)
```
+## Large input props _available from v4.0.315_
+
+The Python SDK automatically handles large input props by uploading them to S3 when they exceed AWS Lambda payload limits:
+
+- Video/audio renders: Props larger than ~194KB
+- Still renders: Props larger than ~4.9MB
+
+When large props are detected, they are automatically uploaded to S3 and referenced by the Lambda function. This process is transparent to the user.
+
+```python title="large_props_example.py"
+# Large input props are handled automatically
+large_props = {
+ 'bigData': ['x' * 1000] * 250, # ~250KB of data
+ 'description': 'This will be automatically uploaded to S3'
+}
+
+render_params = RenderMediaParams(
+ composition="my-composition",
+ input_props=large_props, # Automatically compressed
+ # ... other parameters
+)
+
+# The render works the same way, compression is handled internally
+response = client.render_media_on_lambda(render_params)
+```
+
## Rendering an image
Below is a snippet showing how to initiate a still image render. Note that it does not require monitoring the render progress.
diff --git a/packages/lambda-python/remotion_lambda/remotionclient.py b/packages/lambda-python/remotion_lambda/remotionclient.py
index a5d391a852..051a3a1fd2 100644
--- a/packages/lambda-python/remotion_lambda/remotionclient.py
+++ b/packages/lambda-python/remotion_lambda/remotionclient.py
@@ -1,10 +1,14 @@
# pylint: disable=too-few-public-methods, missing-module-docstring, broad-exception-caught
from dataclasses import asdict
import json
+import hashlib
+import uuid
from math import ceil
from typing import Optional, Union
from enum import Enum
import boto3
+from botocore.exceptions import ClientError
+from botocore.config import Config
from .models import (CostsInfo, CustomCredentials, RenderMediaParams, RenderMediaProgress,
RenderMediaResponse, RenderProgressParams, RenderStillResponse,
RenderStillParams, RenderType)
@@ -14,7 +18,8 @@ class RemotionClient:
"""A client for interacting with the Remotion service."""
# pylint: disable=too-many-arguments
- def __init__(self, region, serve_url, function_name, access_key=None, secret_key=None):
+ def __init__(self, region, serve_url, function_name, access_key=None, secret_key=None,
+ bucket_name=None, force_path_style=False):
"""
Initialize the RemotionClient.
@@ -24,12 +29,131 @@ class RemotionClient:
function_name (str): Name of the AWS Lambda function.
access_key (str): AWS access key (optional).
secret_key (str): AWS secret key (optional).
+ bucket_name (str): S3 bucket name for large payloads (optional).
+ force_path_style (bool): Force path-style S3 URLs (optional).
"""
self.access_key = access_key
self.secret_key = secret_key
self.region = region
self.serve_url = serve_url
self.function_name = function_name
+ self.bucket_name = bucket_name
+ self.force_path_style = force_path_style
+
+ def _generate_hash(self, payload):
+ """Generate a hash for the payload."""
+ return hashlib.sha256(payload.encode('utf-8')).hexdigest()
+
+ def _generate_random_hash(self):
+ """Generate a random hash for bucket operations."""
+ return uuid.uuid4().hex
+
+ def _make_bucket_name(self):
+ """Generate a bucket name following Remotion conventions."""
+ random_suffix = self._generate_random_hash()[:8]
+ return f"remotion-render-{self.region}-{random_suffix}"
+
+ def _input_props_key(self, hash_value):
+ """Generate S3 key for input props."""
+ return f"input-props/{hash_value}.json"
+
+ def _create_s3_client(self):
+ """Create S3 client with appropriate credentials."""
+ config = None
+ if self.force_path_style:
+ config = Config(s3={'addressing_style': 'path'})
+
+ if self.access_key and self.secret_key:
+ return boto3.client('s3',
+ aws_access_key_id=self.access_key,
+ aws_secret_access_key=self.secret_key,
+ region_name=self.region,
+ config=config)
+ return boto3.client('s3', region_name=self.region, config=config)
+
+ def _get_remotion_buckets(self):
+ """Get existing Remotion buckets in the region."""
+ s3_client = self._create_s3_client()
+ try:
+ response = s3_client.list_buckets()
+ buckets = []
+ for bucket in response['Buckets']:
+ bucket_name = bucket['Name']
+ if bucket_name.startswith('remotion-render-'):
+ # Check if bucket is in the correct region
+ try:
+ bucket_region = s3_client.get_bucket_location(Bucket=bucket_name)
+ location = bucket_region.get('LocationConstraint')
+ # us-east-1 returns None for LocationConstraint
+ if location == self.region or (location is None and self.region == 'us-east-1'):
+ buckets.append(bucket_name)
+ except ClientError:
+ # Ignore buckets we can't access
+ continue
+ return buckets
+ except ClientError:
+ return []
+
+ def _get_or_create_bucket(self):
+ """Get existing bucket or create a new one."""
+ if self.bucket_name:
+ return self.bucket_name
+
+ buckets = self._get_remotion_buckets()
+ if len(buckets) > 1:
+ raise ValueError(
+ f"You have multiple buckets ({', '.join(buckets)}) in your S3 region "
+ f"({self.region}) starting with 'remotion-render-'. Please specify a bucket_name."
+ )
+
+ if len(buckets) == 1:
+ return buckets[0]
+
+ # Create new bucket
+ bucket_name = self._make_bucket_name()
+ s3_client = self._create_s3_client()
+
+ try:
+ if self.region == 'us-east-1':
+ s3_client.create_bucket(Bucket=bucket_name)
+ else:
+ s3_client.create_bucket(
+ Bucket=bucket_name,
+ CreateBucketConfiguration={'LocationConstraint': self.region}
+ )
+ return bucket_name
+ except ClientError as e:
+ raise ValueError(f"Failed to create bucket: {str(e)}") from e
+
+ def _upload_to_s3(self, bucket_name, key, payload):
+ """Upload payload to S3."""
+ s3_client = self._create_s3_client()
+ try:
+ s3_client.put_object(
+ Bucket=bucket_name,
+ Key=key,
+ Body=payload,
+ ContentType='application/json'
+ )
+ except ClientError as e:
+ raise ValueError(f"Failed to upload to S3: {str(e)}") from e
+
+ def _needs_upload(self, payload_size, render_type):
+ """Determine if payload needs to be uploaded to S3."""
+ # Constants based on AWS Lambda limits with margin for other payload data
+ MARGIN = 5_000 + 1024 # 5KB margin + 1KB for webhook data
+ MAX_STILL_INLINE_SIZE = 5_000_000 - MARGIN
+ MAX_VIDEO_INLINE_SIZE = 200_000 - MARGIN
+
+ max_size = MAX_STILL_INLINE_SIZE if render_type == 'still' else MAX_VIDEO_INLINE_SIZE
+
+ if payload_size > max_size:
+ # Log warning similar to JavaScript implementation
+ print(f"Warning: The props are over {round(max_size / 1000)}KB "
+ f"({ceil(payload_size / 1024)}KB) in size. Uploading them to S3 to "
+ f"circumvent AWS Lambda payload size, which may lead to slowdown.")
+ return True
+ return False
def _serialize_input_props(self, input_props, render_type):
"""
@@ -37,31 +161,35 @@ class RemotionClient:
Args:
input_props (dict): Input properties to be serialized.
- type (str): Type of the render (e.g., 'still' or 'video-or-audio').
-
- Raises:
- ValueError: If the inputProps are too large or cannot be serialized.
+ render_type (str): Type of the render (e.g., 'still' or 'video-or-audio').
Returns:
- dict: Serialized inputProps.
+ dict: Serialized inputProps in either payload or bucket-url format.
"""
try:
payload = json.dumps(input_props, separators=(',', ':'))
- max_inline_payload_size = 5000000 if render_type == 'still' else 200000
-
- if len(payload) > max_inline_payload_size:
- raise ValueError(
- (
- f"InputProps are over {round(max_inline_payload_size / 1000)}KB "
- f"({ceil(len(payload) / 1024)}KB) in size. This is not currently supported."
- )
- )
-
- return {
- 'type': 'payload',
- 'payload': payload if payload not in ('', 'null') else json.dumps({})
- }
- except ValueError as error:
+ payload_size = len(payload.encode('utf-8'))
+
+ if self._needs_upload(payload_size, render_type):
+ # Upload to S3 and return bucket-url format
+ hash_value = self._generate_hash(payload)
+ bucket_name = self._get_or_create_bucket()
+ key = self._input_props_key(hash_value)
+
+ self._upload_to_s3(bucket_name, key, payload)
+
+ return {
+ 'type': 'bucket-url',
+ 'hash': hash_value,
+ 'bucketName': bucket_name
+ }
+ else:
+ # Return payload format for smaller payloads
+ return {
+ 'type': 'payload',
+ 'payload': payload if payload not in ('', 'null') else json.dumps({})
+ }
+ except (ValueError, TypeError) as error:
raise ValueError(
'Error serializing InputProps. Check for circular ' +
'references or reduce the object size.'
diff --git a/packages/lambda-python/testclient_render_media.py b/packages/lambda-python/testclient_render_media.py
index f1135bf64a..7324e968ed 100644
--- a/packages/lambda-python/testclient_render_media.py
+++ b/packages/lambda-python/testclient_render_media.py
@@ -35,7 +35,32 @@ render_params = RenderMediaParams(
},
)
+# Test with large payload to verify S3 compression works
+# Create large input props that exceed the 200KB limit for video-or-audio renders
+large_data = {
+ 'largeArray': ['x' * 1000] * 250, # This creates ~250KB of data
+ 'description': 'This is a test with large input props to verify S3 compression functionality'
+}
+
+large_render_params = RenderMediaParams(
+ composition="react-svg",
+ privacy=Privacy.PUBLIC,
+ image_format=ValidStillImageFormats.JPEG,
+ input_props=large_data,
+)
+
+print("Testing normal payload size...")
render_response = client.render_media_on_lambda(render_params)
+
+print("Testing large payload compression...")
+# For testing large payloads, we would need valid AWS credentials
+# This will demonstrate the compression logic
+try:
+ large_render_response = client.render_media_on_lambda(large_render_params)
+ print("Large payload render succeeded!")
+except Exception as e:
+ print(f"Large payload test failed (expected without valid AWS credentials): {e}")
+
if render_response:
# Execute render request
diff --git a/packages/lambda-python/tests/test_large_payload_compression.py b/packages/lambda-python/tests/test_large_payload_compression.py
new file mode 100644
index 0000000000..95c9b85011
--- /dev/null
+++ b/packages/lambda-python/tests/test_large_payload_compression.py
@@ -0,0 +1,80 @@
+import unittest
+from unittest.mock import patch, MagicMock
+from remotion_lambda.models import RenderMediaParams
+from remotion_lambda.remotionclient import RemotionClient
+
+
+class TestLargePayloadCompression(unittest.TestCase):
+
+ def setUp(self):
+ self.client = RemotionClient(
+ region="us-east-1",
+ serve_url="testbed",
+ function_name="remotion-render",
+ bucket_name="test-bucket"
+ )
+
+ def test_small_payload_uses_payload_format(self):
+ """Test that small payloads use the payload format."""
+ small_props = {'message': 'small'}
+ result = self.client._serialize_input_props(small_props, 'video-or-audio')
+
+ self.assertEqual(result['type'], 'payload')
+ self.assertIn('payload', result)
+ self.assertNotIn('hash', result)
+ self.assertNotIn('bucketName', result)
+
+ @patch('remotion_lambda.remotionclient.RemotionClient._upload_to_s3')
+ @patch('remotion_lambda.remotionclient.RemotionClient._get_or_create_bucket')
+ def test_large_payload_uses_bucket_format(self, mock_get_bucket, mock_upload):
+ """Test that large payloads use the bucket-url format."""
+ mock_get_bucket.return_value = 'test-bucket'
+
+ # Create a large payload that exceeds the limit for video-or-audio (200KB - margin)
+ large_data = 'x' * 200000 # 200KB of data
+ large_props = {'data': large_data}
+
+ result = self.client._serialize_input_props(large_props, 'video-or-audio')
+
+ self.assertEqual(result['type'], 'bucket-url')
+ self.assertIn('hash', result)
+ self.assertIn('bucketName', result)
+ self.assertEqual(result['bucketName'], 'test-bucket')
+
+ # Verify S3 upload was called
+ mock_upload.assert_called_once()
+
+ def test_needs_upload_logic(self):
+ """Test the logic for determining when upload is needed."""
+ # Small payload should not need upload
+ self.assertFalse(self.client._needs_upload(1000, 'video-or-audio'))
+ self.assertFalse(self.client._needs_upload(1000, 'still'))
+
+ # Large payload for video should need upload
+ self.assertTrue(self.client._needs_upload(200000, 'video-or-audio'))
+
+ # Large payload for still should need upload (over 5MB)
+ self.assertTrue(self.client._needs_upload(5000000, 'still'))
+
+ # Medium payload for still should not need upload
+ self.assertFalse(self.client._needs_upload(1000000, 'still'))
+
+ def test_hash_generation(self):
+ """Test that hash generation is consistent."""
+ payload = '{"test": "data"}'
+ hash1 = self.client._generate_hash(payload)
+ hash2 = self.client._generate_hash(payload)
+
+ self.assertEqual(hash1, hash2)
+ self.assertIsInstance(hash1, str)
+ self.assertEqual(len(hash1), 64) # SHA256 hex string length
+
+ def test_input_props_key_generation(self):
+ """Test S3 key generation for input props."""
+ hash_value = 'test123'
+ key = self.client._input_props_key(hash_value)
+ self.assertEqual(key, 'input-props/test123.json')
+
+
+if __name__ == '__main__':
+ unittest.main()
\ No newline at end of file