Skip to main content

Python

Learn how to create custom clips via Resemble platform by building a small command line application in 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-static-audio/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, and os module from Python’s standard library and add a setup function to initialize the API client called initialize_resemble_client:

# resemble-static-audio/main.py

from resemble import Resemble
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, clip title, clip body and whether or not this clip is archived using command line options. For example:

python main.py --project_uuid PROJECT_UUID --voice_uuid VOICE_UUID --title TITLE --body BODY

To accomplish this, we will use Python’s argparse library you imported previously to specify the required arguments for use. Just above the script entry point add the following parsing logic:

resemble-static-audio/main.py

import argparse
from resemble import Resemble
import os

# -- snipped --

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

# Create an argument parser
parser = argparse.ArgumentParser(description="A script that creates static audio content using Resemble AI")

# 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("--title", required=True, help="The title of the clip")
parser.add_argument("--body", required=True, help="The text to synthesize audio content with, can be SSML or plain text")
parser.add_argument("--archived", action="store_true", help="Set to archive (default: False)")

# 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,
"title": args.title,
"body": args.body,
"archived": args.archived
}

# 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 create_audio_clip responsible for initiating the Clip creation request to the Resemble API.

def create_audio_clip(
project_uuid: str,
title: str,
body: str,
voice_uuid: str,
is_archived: bool = False):

# Not yet implemented
pass

With this function in place, we can complete the function body of the run_example method to pass along the necessary Clip information:

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")
title = arguments.get("title")
body = arguments.get("body")
archived = arguments.get("archived", False)

# Run the clip creation function to call the Resemble API
create_audio_clip(
project_uuid=project_uuid,
title=title,
body=body,
voice_uuid=voice_uuid,
is_archived=archived
)

# Create an argument parser
parser = argparse.ArgumentParser(description="A script that creates static audio content using Resemble AI")

# -- snipped --

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

# -- snipped -

def create_audio_clip(
project_uuid: str,
title: str,
body: str,
voice_uuid: str,
is_archived: bool = False):

print(f"Submitting request to Resemble to create audio clip content: {body}")

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


if response['success']:
clip = response['item']
clip_uuid = clip['uuid']
clip_url = clip['audio_src']

print(f"Response was successful! {title} has been created with UUID {clip_uuid}.")
print(clip_url)
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 --title "My Title" --body "My Body"

Submitting request to Resemble to create audio clip content: My Body
Response was successful! My Title has been created with UUID abcdef123.

<url to clip>

Congratulations, you have successfully created a Clip via the API you can download it via the provided URL or use the web application to view your new clip.