Code Examples

View as Markdown

Two end-to-end Python examples: a simple Pulse Pro transcription, and an advanced Pulse transcription that adds gender detection, emotion detection, speaker diarization, and sentence-level timestamps. Both call the unified /waves/v1/stt/ endpoint with the requests library.

For plain English transcription where leaderboard accuracy matters most, use Pulse Pro (?model=pulse-pro). For multilingual audio or advanced features (gender, emotion, diarization with per-utterance speaker labels), use Pulse (?model=pulse). The endpoint and request shape are identical; only the model query param changes.

Pulse Pro: basic transcription

The simplest end-to-end flow. Downloads a sample, preprocesses to 16 kHz mono WAV, transcribes with word timestamps.

import os
import requests
from pydub import AudioSegment
API_KEY = os.environ["SMALLEST_API_KEY"]
ENDPOINT = "https://api.smallest.ai/waves/v1/stt/"
def preprocess_audio(input_path: str, output_path: str) -> str:
"""Convert to 16 kHz mono WAV, normalize levels, strip silence."""
audio = AudioSegment.from_file(input_path)
audio = audio.set_frame_rate(16000).set_channels(1).normalize()
audio = audio.strip_silence(silence_len=100, silence_thresh=-40)
audio.export(output_path, format="wav")
return output_path
def transcribe_pulse_pro(audio_path: str) -> dict:
"""Transcribe English audio with Pulse Pro. Word timestamps on."""
with open(audio_path, "rb") as f:
audio_bytes = f.read()
response = requests.post(
ENDPOINT,
params={"model": "pulse-pro", "language": "en", "word_timestamps": "true"},
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/octet-stream",
},
data=audio_bytes,
timeout=120,
)
response.raise_for_status()
return response.json()
if __name__ == "__main__":
raw_path = "input_audio.mp3"
wav_path = "preprocessed.wav"
preprocess_audio(raw_path, wav_path)
result = transcribe_pulse_pro(wav_path)
print(f"Transcription: {result['transcription']}")
print(f"Duration: {result['metadata']['duration']:.2f}s")
print(f"RTFx: {result['metadata']['rtfx']:.1f}x")
print(f"Words: {len(result.get('words', []))}")
os.remove(wav_path)

Pulse: advanced features (gender, emotion, diarization, utterances)

Pulse supports gender detection, emotion detection, and per-utterance speaker labels. The example below enables all of them.

import os
import requests
from pydub import AudioSegment
API_KEY = os.environ["SMALLEST_API_KEY"]
ENDPOINT = "https://api.smallest.ai/waves/v1/stt/"
def preprocess_audio(input_path: str, output_path: str) -> str:
audio = AudioSegment.from_file(input_path)
audio = audio.set_frame_rate(16000).set_channels(1).normalize()
audio = audio.strip_silence(silence_len=100, silence_thresh=-40)
audio.export(output_path, format="wav")
return output_path
def transcribe_with_features(audio_path: str) -> dict:
"""Transcribe with Pulse + gender, emotion, diarization, utterances."""
with open(audio_path, "rb") as f:
audio_bytes = f.read()
response = requests.post(
ENDPOINT,
params={
"model": "pulse",
"language": "en",
"word_timestamps": "true",
"gender_detection": "true",
"emotion_detection": "true",
"diarize": "true",
},
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/octet-stream",
},
data=audio_bytes,
timeout=120,
)
response.raise_for_status()
return response.json()
def report(result: dict) -> None:
print("=" * 60)
print("TRANSCRIPTION RESULTS")
print("=" * 60)
print(f"\nTranscription: {result.get('transcription', 'N/A')}")
if result.get("gender") is not None:
print(f"\nGender: {result['gender']}")
if result.get("emotions"):
print("\nEmotion scores:")
for emotion, score in result["emotions"].items():
print(f" {emotion.capitalize()}: {score:.4f}")
utterances = result.get("utterances") or []
if utterances:
print(f"\nUtterances ({len(utterances)}):")
for i, u in enumerate(utterances, 1):
print(
f" [{i}] {u.get('start', 0):.2f}s – {u.get('end', 0):.2f}s "
f"(speaker: {u.get('speaker', 'unknown')})"
)
print(f" {u.get('text', '')}")
words = result.get("words") or []
if words:
print(f"\nWord-level timestamps: {len(words)} words")
if __name__ == "__main__":
raw_path = "input_audio.mp3"
wav_path = "preprocessed.wav"
try:
preprocess_audio(raw_path, wav_path)
result = transcribe_with_features(wav_path)
report(result)
finally:
if os.path.exists(wav_path):
os.remove(wav_path)

Prerequisites

pip install requests pydub

pydub requires ffmpeg on PATH for non-WAV input formats.

What each example demonstrates

StepPulse Pro examplePulse advanced example
Audio preprocessing16 kHz mono WAV, normalized, silence-trimmedSame
TranscriptionWord-timestamps onWord-timestamps on
Gender detectionNot available on Pulse Progender field on response
Emotion detectionNot available on Pulse Proemotions object with 5 scores
Speaker diarizationNot available on Pulse Prodiarize=true plus per-utterance speaker labels
Sentence-level utterancesNot available on Pulse Proutterances[] with start/end/speaker

Expected output

The Pulse advanced example prints:

  • Full transcription text
  • Detected gender (male / female)
  • Emotion scores: anger, disgust, fear, sadness, happiness
  • Sentence-level utterances with timestamps and speaker IDs
  • A count of word-level timestamps