Python
Learn how to import a phoneme library from a CSV using the Resemble API AI platform 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](http://main.py)
file which will contain our script to import phonemes.
Initialize the script by creating a basic run_main
function and fill in your [main.py](http://main.py)
with the code snippet below.
# resemble-import-phonemes/main.py
# This is the main function that contains the example
def run_main():
# TODO: Fill me in!
if __name__ == '__main__':
run_main()
Next, 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-import-phonemes/main.py
import os
import argparse
from resemble import Resemble
# 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_main():
# TODO: Fill me in!
# -- snipped --
Notice that the Python script expects the environment variable RESEMBLE_API_KEY
to be present containing the necessary API key.
Next, build the import_phonemes
function responsible for parsing a CSV containing your phonemes and uploading to the API (don’t forget to import csv
).
Add the following code snippet below to main.py
file.
# resemble-import-phonemes/main.py
import os
from resemble import Resemble
import csv
def import_phonemes(csv_file_path):
# Keep track of successful and failed imports (possibly due to already existing)
successful_imports = 0
failed_imports = 0
try:
with open(csv_file_path, 'r') as file:
# Create a CSV reader object
reader = csv.reader(file)
# Skip the header row if it exists
next(reader, None)
# Iterate over each row in the CSV file
for row in reader:
# Ensure the row has at least two elements (word and phonetic_transcription)
if len(row) >= 2:
word, phonetic_transcription = row[0], row[1]
try:
# Make a POST request to create a new widget entry
response = Resemble.v2.phonemes.create(word, phonetic_transcription)
if response['success']:
successful_imports += 1
print(f"Imported phoneme pair: {word} and {phonetic_transcription}")
else:
# Failed to import for some reason
raise Exception(response)
except Exception as e:
failed_imports += 1
print(f"ERROR: Could not import phoneme pair: {word} and {phonetic_transcription} - {e}")
except FileNotFoundError:
print(f"ERROR: File not found - {csv_file_path}")
# Print summary
print(f"\nCompleted\nSuccessfully imported phonemes: {successful_imports}\nFailed to import phonemes: {failed_imports}")
# This function sets up the Resemble Python SDK
def initialize_resemble_client():
# -- snipped --
# -- snipped --
In the above snippet, the import_phonemes
file parses through the a CSV in the following format and creates a pair entry using the Resemble API. Note the headers will be skipped!
# example-phoneme.csv
word,phonentic_transcription
vodaphone,voduhphone
cosmic,kozmik
Once you have completed the import_phonemes
, function update run_main
function to accept an input file from the command line and execute the import_phonemes
process.
# -- snipped -
# This is the main function that contains the example
def run_main(arguments):
# Initialize the client using the environment variable RESEMBLE_API_KEY set
initialize_resemble_client()
# Run the voice creation function to call the Resemble API
import_phonemes(arguments['csv_file'])
parser = argparse.ArgumentParser(description="A script that imports phonemes using Resemble AI")
# Add option flags to the parser
parser.add_argument("--csv-file", required=True, help="The CSV file containing phonemes to import")
# Parse the command-line arguments
args = parser.parse_args()
arguments = { 'csv_file': args.csv_file }
if __name__ == '__main__':
run_main(arguments)
Finally, test your script by running the same command via CLI as before:
# Be sure to prepend your API key to the command
RESEMBLE_API_KEY=... python3 main.py --csv-file path/to/example-csv.csv
Imported phoneme pair: vodaphone and voduhphone
Imported phoneme pair: cosmic and kozmik
Completed
Successfully imported phonemes: 2
Failed to import phonemes: 0
Congratulations, you have successfully imported your phoneme library! To check the status of your library, you can programmatically access via the API or use the web application as well.