Skip to main content
Version: 2.0.0

Python

Learn how to create multiple clips using through the Resemble AI Batch API with Python.

In order to best use this guide ensure that you have:

  • Signed up for a Resemble.ai account and confirmed your e-mail
  • Obtained your API key for use with the API - for additional information see the Authentication page

Guide

First, you will need to initialize your Python project, it’s virtual environment.

# Create virtual environment
python3 -m venv venv

# Activate virtual environment
source venv/bin/activate

With your project setup, we can install the Resemble Python SDK via pip install and freeze our dependency list for later use:

# Install Resemble python SDK
pip install resemble

# Freeze dependencies
pip freeze > requirements.txt

Create a new main.py file - this file will contain a small CLI program we can use to create a piece of audio content using the Resemble AI platform.

We will initialize the script by creating a run_example function responsible for running our process. This function will take a single parameter called arguments containing a dictionary of arguments for the program. Fill in main.py with the code snippet below.

# resemble-batch/main.py

# This is the main function that contains the example
def run_example(arguments):
# TODO: Fill me in!

# Empty arguments array
arguments = {}

if __name__ == '__main__':
run_example(arguments)

Import the Resemble class from the resemble sdk, the argparse, typing, and os module from Python’s standard library and add a setup function to initialize the API client called initialize_resemble_client:

# resemble-batch/main.py

from resemble import Resemble
from typing import List
import os
import argparse

# This function sets up the Resemble Python SDK
def initialize_resemble_client():
try:
# Attempt to retrieve the value of the environment variable
resemble_api_key = os.environ['RESEMBLE_API_KEY']

Resemble.api_key(resemble_api_key)
except KeyError:
# If the environment variable is not found, raise an error
raise EnvironmentError(f"The 'RESEMBLE_API_KEY' environment variable is not set.")

# This is the main function that contains the example
def run_example(arguments):
# TODO: Fill me in!

# -- snipped --

The program expects the environment variable RESEMBLE_API_KEY to be present containing the necessary API key in order to initialize the Resemble AI python client.

Every Clip created on the Resemble AI platform is associated with a Project and synthesized using a Voice. To create an Clip you will need the UUID of both the Project and Voice you want to use to synthesize a Clip. You can refer to the Project and Voice documentation to learn how to find your Project and Voice UUID.

We want to build our program in way that the user can specify their desired Project, Voice, a list of clip content (e.g., [“A word aptly uttered or written cannot be cut away by an axe.”, "But youth has a future.", "The things these scribblers write!"]) using command line options. For example:

python main.py --project_uuid PROJECT_UUID --voice_uuid VOICE_UUID --clips CLIP,CLIP2,CLIP3

To do this, we can use Python’s argparse library. Just above the script entry point add the following parsing logic:

resemble-batch/main.py

import argparse
from resemble import Resemble
from typing import List
import os

# -- snipped --

def run_example(arguments):
# TODO: Fill me in!

# Create an argument parser
parser = argparse.ArgumentParser(description="A script that creates audio clips using the Resemble AI Batch API")

# Add option flags to the parser
parser.add_argument("--project_uuid", required=True, help="Project UUID to store this clip under")
parser.add_argument("--voice_uuid", required=True, help="Voice UUID to use for this clip content")
parser.add_argument('--clips', required=True, help='A comma-separated list of clip body content')

# Parse the command-line arguments
args = parser.parse_args()

# Create a dictionary of arguments
arguments = {
"project_uuid": args.project_uuid,
"voice_uuid": args.voice_uuid,
"clips": args.clips
}

# Call the 'run_example' function with the provided arguments
if __name__ == '__main__':
run_example(arguments)

In the above code snippet, using the argparse library we specify the program arguments and provide them as parameters to the run_example function. Next, let’s create a skeleton function to fill in later called batch_create_clips that will make a batch clip creation request to the Resemble API.

# NOTE: to specify keyword argument type of List[str]
# you will need to import the List type from
# pythons "typing" library.
#
# Example:
# # resemble-batch/main.py
#
# from typing import List
#
def batch_create_clips(
project_uuid: str,
clips: List[str],
voice_uuid: str):

# Not yet implemented
pass

Now, complete the function body of the run_example function to provide the Batch details using the snippet of code below

import argparse

# -- snipped --

# This is the main function that contains the example
def run_example(arguments):
# Initialize the client using the environment variable RESEMBLE_API_KEY set
initialize_resemble_client()

project_uuid = arguments.get("project_uuid")
voice_uuid = arguments.get("voice_uuid")
clips_arg = arguments.get("clips")

# Split the comma-separated list into a List[Str]
clips = clips_arg.split(',')

# Run the batch clip creation function to call the Resemble API
batch_create_clips(
project_uuid=project_uuid,
clips=clips,
voice_uuid=voice_uuid,
)

# Create an argument parser
parser = argparse.ArgumentParser(description="A script that creates audio clips using the Resemble AI Batch API")

# -- snipped --

Finally, we will complete the batch_create_clips function body to send the Clip creation request to the Resemble API.

# -- snipped -

def batch_create_clips(
project_uuid: str,
clips: List[str],
voice_uuid: str):

# Make request to the API, note that we do not provide a callback_uri so this
# will request will execute synchronously.
response = Resemble.v2.batches.create(
project_uuid,
voice_uuid,
body=clips,
sample_rate=None,
output_format=None,
precision=None
)

if response['success']:
batch = response['item']
batch_uuid = batch['uuid']
count = batch['total_count']

print(f"Response was successful! Batch of {count} clips has been created with UUID {batch_uuid}.")
else:
print("Response was unsuccessful!")

# In case of an error, print the error to STDOUT
print(response)

# -- snipped --

Finally, test your script by running the command via CLI :

# Be sure to prepend your API key to the command
RESEMBLE_API_KEY=... python3 main.py --project_uuid 6ccbf285 --voice_uuid 48d7ed16 --clips Hello,Hi,Goodbye

Response was successful! Batch of 3 clips has been created with UUID a09ed077-a1ba-4e8f-bb31-2b8e3dee6b14.

Congratulations, you have successfully created a clip batch via the API. You can view the clip synthesis details in the response body, or alternatively navigating to your project in the web application.