Skip to navigation

Tutorial: Fix How Names Are Pronounced

Build a small Python script that makes Lightning say names and brands the way you want, step by step.
View as Markdown

In this tutorial you build pronounce.py, a short Python script that reads a message aloud and says every name in it the way you want.

The message is: “Hi Saoirse, your Hermes bag has shipped. Niamh from our team will call you tomorrow.” Saoirse is said “Seersha”, Niamh is said “Neev”, and the brand Hermes is said “Air mez”. The voice can’t know that from the spelling.

This is the message before the script fixes it:

And this is what your script makes by the end:

You get there in five steps. You run the script at the end of every step, so you always have something that works:

  1. Set up a project folder.
  2. Hear the names said wrong.
  3. Create a pronunciation dictionary.
  4. Use the dictionary in your request.
  5. Add another word to the dictionary.

It takes about 10 minutes. The script uses only the Python standard library, so there is nothing to install.

Before you start

You need:

  • Python 3.9 or later. Check with python3 --version.
  • A Smallest AI API key. If you don’t have one yet, follow Step 1 of the Quickstart, then come back.
  • About 1,000 characters of TTS credit. That’s all the text the tutorial sends, from start to finish.

Step 1: Set up a project folder

Make a folder for the tutorial and move into it:

mkdir pronounce-tutorial
cd pronounce-tutorial

Export your API key in the same terminal. The script reads it from there:

export SMALLEST_API_KEY="your-api-key-here"

You are in an empty pronounce-tutorial folder, and SMALLEST_API_KEY is exported in this terminal.

Step 2: Hear the names said wrong

Start with the problem. Turn the message into audio the normal way, with no dictionary.

Create a file called pronounce.py in the folder and paste in this code:

pronounce.py
import json
import os
import urllib.request
API_KEY = os.environ["SMALLEST_API_KEY"]
API_URL = "https://api.smallest.ai/waves/v1"
MESSAGE = "Hi Saoirse, your Hermes bag has shipped. Niamh from our team will call you tomorrow."
def api_request(method, endpoint, body):
"""Send a JSON request to the API and return the raw response."""
request = urllib.request.Request(
f"{API_URL}/{endpoint}",
data=json.dumps(body).encode(),
method=method,
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
},
)
with urllib.request.urlopen(request) as response:
return response.read()
def synthesize(text, path):
"""Turn text into a WAV file."""
body = {
"text": text,
"voice_id": "meher",
"model": "lightning_v3.1_pro",
"sample_rate": 24000,
"output_format": "wav",
}
audio = api_request("POST", "tts", body)
with open(path, "wb") as f:
f.write(audio)
print(f"Saved {path}")
if __name__ == "__main__":
synthesize(MESSAGE, "before.wav")

Run it:

python3 pronounce.py

You should see one line:

Saved before.wav

Open before.wav and listen. The voice meher reads the names the way they are spelled, so Saoirse doesn’t sound like “Seersha” and Niamh doesn’t sound like “Neev”.

before.wav plays the message, and the two names sound wrong.

api_request sends one request to the API and returns what comes back. synthesize uses it to turn text into a WAV file. You’ll use both in every step from here on.

What you seeWhat to do
KeyError: 'SMALLEST_API_KEY'The key isn’t exported in this terminal. Run the export line from Step 1, then run the script again
urllib.error.HTTPError: HTTP Error 401: UnauthorizedThe key is wrong or was revoked. Copy it again from the API Keys page and export it
CERTIFICATE_VERIFY_FAILED on macOSPython from python.org starts without root certificates. Open your Python folder in Applications, run Install Certificates.command, then try again

Step 3: Create a pronunciation dictionary

A pronunciation dictionary is a list of words, each with how it should sound. You create it once, and the API gives you back an ID. You use that ID in your requests.

Write each pronunciation the way you’d spell it for a friend, in plain letters. Don’t use phonetic symbols.

Replace everything in pronounce.py with this code. The highlighted lines are new:

pronounce.py
import json
import os
import urllib.request
API_KEY = os.environ["SMALLEST_API_KEY"]
API_URL = "https://api.smallest.ai/waves/v1"
MESSAGE = "Hi Saoirse, your Hermes bag has shipped. Niamh from our team will call you tomorrow."
WORDS = [
{"word": "Saoirse", "pronunciation": "Seersha"},
{"word": "Niamh", "pronunciation": "Neev"},
]
DICTIONARY_FILE = "dictionary_id.txt"
def api_request(method, endpoint, body):
"""Send a JSON request to the API and return the raw response."""
request = urllib.request.Request(
f"{API_URL}/{endpoint}",
data=json.dumps(body).encode(),
method=method,
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
},
)
with urllib.request.urlopen(request) as response:
return response.read()
def synthesize(text, path):
"""Turn text into a WAV file."""
body = {
"text": text,
"voice_id": "meher",
"model": "lightning_v3.1_pro",
"sample_rate": 24000,
"output_format": "wav",
}
audio = api_request("POST", "tts", body)
with open(path, "wb") as f:
f.write(audio)
print(f"Saved {path}")
def create_dictionary(words):
"""Create a pronunciation dictionary and return its ID."""
result = json.loads(api_request("POST", "pronunciation-dicts", {"items": words}))
print(f"Created dictionary {result['id']} with {len(result['items'])} words")
return result["id"]
if __name__ == "__main__":
synthesize(MESSAGE, "before.wav")
if os.path.exists(DICTIONARY_FILE):
dictionary_id = open(DICTIONARY_FILE).read().strip()
print(f"Using dictionary {dictionary_id}")
else:
dictionary_id = create_dictionary(WORDS)
with open(DICTIONARY_FILE, "w") as f:
f.write(dictionary_id)

What changed:

  • WORDS lists the two names and how to say them.
  • A new create_dictionary function sends WORDS to the API and returns the new dictionary’s ID.
  • The bottom of the file saves the ID in dictionary_id.txt. On the next run, the script reads the ID from that file instead of creating a second dictionary.

Run it:

python3 pronounce.py

You should see two lines. Your dictionary ID will be different:

Saved before.wav
Created dictionary 6b0e71c9fc23bb270783e44c with 2 words

Run it once more:

python3 pronounce.py

This time the script finds dictionary_id.txt and uses the same dictionary:

Saved before.wav
Using dictionary 6b0e71c9fc23bb270783e44c

Your folder has a dictionary_id.txt file with one ID in it, and the second run said Using dictionary.

Step 4: Use the dictionary in your request

Creating a dictionary doesn’t change anything by itself. You turn it on for a request by sending its ID in the pronunciation_dicts field.

Replace everything in pronounce.py with this code. The highlighted lines are new:

pronounce.py
import json
import os
import urllib.request
API_KEY = os.environ["SMALLEST_API_KEY"]
API_URL = "https://api.smallest.ai/waves/v1"
MESSAGE = "Hi Saoirse, your Hermes bag has shipped. Niamh from our team will call you tomorrow."
WORDS = [
{"word": "Saoirse", "pronunciation": "Seersha"},
{"word": "Niamh", "pronunciation": "Neev"},
]
DICTIONARY_FILE = "dictionary_id.txt"
def api_request(method, endpoint, body):
"""Send a JSON request to the API and return the raw response."""
request = urllib.request.Request(
f"{API_URL}/{endpoint}",
data=json.dumps(body).encode(),
method=method,
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
},
)
with urllib.request.urlopen(request) as response:
return response.read()
def synthesize(text, path, dictionary_id=None):
"""Turn text into a WAV file, using a pronunciation dictionary if given."""
body = {
"text": text,
"voice_id": "meher",
"model": "lightning_v3.1_pro",
"sample_rate": 24000,
"output_format": "wav",
}
if dictionary_id:
body["pronunciation_dicts"] = [dictionary_id]
audio = api_request("POST", "tts", body)
with open(path, "wb") as f:
f.write(audio)
print(f"Saved {path}")
def create_dictionary(words):
"""Create a pronunciation dictionary and return its ID."""
result = json.loads(api_request("POST", "pronunciation-dicts", {"items": words}))
print(f"Created dictionary {result['id']} with {len(result['items'])} words")
return result["id"]
if __name__ == "__main__":
synthesize(MESSAGE, "before.wav")
if os.path.exists(DICTIONARY_FILE):
dictionary_id = open(DICTIONARY_FILE).read().strip()
print(f"Using dictionary {dictionary_id}")
else:
dictionary_id = create_dictionary(WORDS)
with open(DICTIONARY_FILE, "w") as f:
f.write(dictionary_id)
synthesize(MESSAGE, "after.wav", dictionary_id)

What changed:

  • synthesize takes a new, optional dictionary_id. When you pass one, it goes into the request as pronunciation_dicts.
  • The last line makes a second file, after.wav, with the dictionary turned on.

Run it:

python3 pronounce.py

You should see three lines:

Saved before.wav
Using dictionary 6b0e71c9fc23bb270783e44c
Saved after.wav

Play before.wav, then after.wav. In after.wav, Saoirse sounds like “Seersha” and Niamh sounds like “Neev”. Hermes still sounds like the English word, because it isn’t in the dictionary yet.

In after.wav, both names sound right. Hermes still sounds wrong.

A word only matches when the capitals match, too. Saoirse in the dictionary doesn’t fix saoirse or SAOIRSE in the text. If your text can use different capitals, add each form as its own word.

Step 5: Add another word to the dictionary

Now fix Hermes. You change the dictionary you already have, instead of creating a new one.

When you update a dictionary, the API replaces all its words with the list you send. A word you leave out of the update is removed. That’s why the script keeps every word in WORDS and always sends the whole list.

Replace everything in pronounce.py with this code. The highlighted lines are new:

pronounce.py
import json
import os
import urllib.request
API_KEY = os.environ["SMALLEST_API_KEY"]
API_URL = "https://api.smallest.ai/waves/v1"
MESSAGE = "Hi Saoirse, your Hermes bag has shipped. Niamh from our team will call you tomorrow."
WORDS = [
{"word": "Saoirse", "pronunciation": "Seersha"},
{"word": "Niamh", "pronunciation": "Neev"},
{"word": "Hermes", "pronunciation": "Air mez"},
]
DICTIONARY_FILE = "dictionary_id.txt"
def api_request(method, endpoint, body):
"""Send a JSON request to the API and return the raw response."""
request = urllib.request.Request(
f"{API_URL}/{endpoint}",
data=json.dumps(body).encode(),
method=method,
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
},
)
with urllib.request.urlopen(request) as response:
return response.read()
def synthesize(text, path, dictionary_id=None):
"""Turn text into a WAV file, using a pronunciation dictionary if given."""
body = {
"text": text,
"voice_id": "meher",
"model": "lightning_v3.1_pro",
"sample_rate": 24000,
"output_format": "wav",
}
if dictionary_id:
body["pronunciation_dicts"] = [dictionary_id]
audio = api_request("POST", "tts", body)
with open(path, "wb") as f:
f.write(audio)
print(f"Saved {path}")
def create_dictionary(words):
"""Create a pronunciation dictionary and return its ID."""
result = json.loads(api_request("POST", "pronunciation-dicts", {"items": words}))
print(f"Created dictionary {result['id']} with {len(result['items'])} words")
return result["id"]
def update_dictionary(dictionary_id, words):
"""Replace every word in the dictionary with the words given."""
body = {"id": dictionary_id, "items": words}
result = json.loads(api_request("PUT", "pronunciation-dicts", body))
print(f"Updated dictionary {result['id']}, now {len(result['items'])} words")
if __name__ == "__main__":
synthesize(MESSAGE, "before.wav")
if os.path.exists(DICTIONARY_FILE):
dictionary_id = open(DICTIONARY_FILE).read().strip()
update_dictionary(dictionary_id, WORDS)
else:
dictionary_id = create_dictionary(WORDS)
with open(DICTIONARY_FILE, "w") as f:
f.write(dictionary_id)
synthesize(MESSAGE, "after.wav", dictionary_id)

What changed:

  • Hermes is now in WORDS.
  • A new update_dictionary function sends the full WORDS list to the existing dictionary.
  • When dictionary_id.txt exists, the script now updates the dictionary instead of only reading the ID.

Run it:

python3 pronounce.py

You should see four lines:

Saved before.wav
Updated dictionary 6b0e71c9fc23bb270783e44c, now 3 words
Saved after.wav

Play after.wav. All three words now sound the way you want. It should sound like the second sample at the top of this page.

after.wav says “Seersha”, “Air mez” and “Neev”. The update line says the dictionary now has 3 words.

What you seeWhat to do
HTTP Error 404: Not Found when updatingThe dictionary in dictionary_id.txt was deleted. Delete dictionary_id.txt and run the script again to create a new one
HTTP Error 400: Bad RequestA word in WORDS is missing "word" or "pronunciation", or dictionary_id.txt has something other than the ID in it

Your folder now looks like this:

pronounce-tutorial/
├── after.wav
├── before.wav
├── dictionary_id.txt
└── pronounce.py

Clean up

The dictionary stays in your account until you delete it. If you don’t need it any more, delete it with the ID from dictionary_id.txt:

curl -X DELETE "https://api.smallest.ai/waves/v1/pronunciation-dicts" \
-H "Authorization: Bearer $SMALLEST_API_KEY" \
-H "Content-Type: application/json" \
-d "{\"id\": \"$(cat dictionary_id.txt)\"}"

The response ends with "deleted":true. Then delete dictionary_id.txt.

If you send the ID of a deleted dictionary in pronunciation_dicts, the request still works but the dictionary does nothing. The words go back to the default way of saying them, with no error.

What you built

You have a script that says names and brands the way you want. Along the way you:

  • Heard how the voice says words it doesn’t know.
  • Created a pronunciation dictionary and kept its ID to use again.
  • Turned the dictionary on for a request with pronunciation_dicts.
  • Updated the dictionary by sending its full list of words.

Try it with your own words: put the names your customers have in WORDS, change MESSAGE, and run python3 pronounce.py again.

Where to go next

Need Help?