Convert Speech to Text in Python
Send an audio file from Python, get back a transcript with speaker labels, and handle the errors a production job hits. Every script on this page runs against the live API with nothing but requests.
Python speech-to-text options compared
You either run a model yourself or call a hosted API. Local Whisper keeps audio on your machine but wants a GPU. A hosted API needs one HTTP library, and then the question is where the provider processes your audio.
| Option | Accuracy | Setup | Data leaves AU? |
|---|---|---|---|
| Australian Transcription API | High | pip install requests | No |
| OpenAI Whisper (local) | High | pip install openai-whisper + GPU recommended | No |
| OpenAI Whisper API | High | pip install openai | Yes (US) |
| AssemblyAI | High | pip install assemblyai | Yes (US by default; EU option) |
| SpeechRecognition library | Medium (Google/Sphinx) | pip install SpeechRecognition | Google Web Speech: yes (Google cloud). Sphinx: no (runs locally) |
| AWS Transcribe | High | pip install boto3 | AU region available |
If your recordings hold personal information (call centre calls, medical consultations, legal proceedings), that question has a legal edge. Sending audio overseas is a cross-border disclosure, which is what APP 8 of the Privacy Act 1988 (Cth) covers. Most businesses under $3M annual turnover are exempt from the Act. Australian Transcription processes your audio in Sydney and does not send it overseas, so there is no cross-border transfer for APP 8 to cover.
Prerequisites
- Python 3.8 or later
requestslibrary (pip install requests)- An Australian Transcription API key (sign up free; 90 minutes included, no credit card)
- An audio file: MP3, WAV, OGG, FLAC, M4A, MP4, or WebM (up to 200 MB)
Convert speech to text in Python in 5 minutes
The API is asynchronous. You submit a file to POST /api/v1/transcribe, receive a job_id, then poll GET /api/v1/jobs/{job_id} until it reads completed. During AEST business hours a typical file finishes in under 2 minutes. Outside business hours the backend scales to zero and a cold start adds 5 to 15 minutes, so every example here polls for at least 20 minutes.
The transcript comes back once, in the first completed response. Later polls return null, so your code has to keep it from that response.
import time
import requests
API_KEY = "sk_your_api_key_here"
BASE_URL = "https://api.icana.ai/api/v1"
HEADERS = {"X-API-Key": API_KEY}
def transcribe(audio_path: str) -> str:
"""Convert speech to text in Python — submit and poll."""
# Step 1: Submit the audio file
with open(audio_path, "rb") as f:
response = requests.post(
f"{BASE_URL}/transcribe",
headers=HEADERS,
files={"file": f},
data={"language": "en", "num_speakers": 2},
)
response.raise_for_status()
job_id = response.json()["job_id"]
print(f"Job submitted: {job_id}")
# Step 2: Poll until complete (every 10 s, up to 120 attempts = 20 min)
for _ in range(120):
result = requests.get(f"{BASE_URL}/jobs/{job_id}", headers=HEADERS)
result.raise_for_status()
data = result.json()
status = data["status"]
print(f"Status: {status}")
if status == "completed":
return data["transcription"]
elif status == "failed":
raise RuntimeError(f"Transcription failed: {data.get('error_message')}")
time.sleep(10)
raise TimeoutError(f"Job {job_id} did not complete within 20 minutes")
if __name__ == "__main__":
transcript = transcribe("recording.mp3")
print("\nTranscript:")
print(transcript)
Automatic speech recognition (ASR) with speaker labels
Every completed job also carries a diarization string: one line per segment, with a speaker label and start and end times. Speaker diarization is included in the per-minute price. Set num_speakers (1 to 10, default 2) to the number of people in the recording:
import time
import requests
API_KEY = "sk_your_api_key_here"
BASE_URL = "https://api.icana.ai/api/v1"
HEADERS = {"X-API-Key": API_KEY}
def transcribe_with_speakers(audio_path: str, num_speakers: int = 2) -> dict:
"""Submit audio and return both transcription and speaker diarization."""
with open(audio_path, "rb") as f:
resp = requests.post(
f"{BASE_URL}/transcribe",
headers=HEADERS,
files={"file": f},
data={"language": "en", "num_speakers": num_speakers},
)
resp.raise_for_status()
job_id = resp.json()["job_id"]
for _ in range(120): # every 10 s, up to 20 min
time.sleep(10)
data = requests.get(f"{BASE_URL}/jobs/{job_id}", headers=HEADERS).json()
if data["status"] == "completed":
return data # transcript is only returned in this response
elif data["status"] == "failed":
raise RuntimeError(f"Transcription failed: {data.get('error_message')}")
raise TimeoutError(f"Job {job_id} did not complete within 20 minutes")
result = transcribe_with_speakers("meeting.mp3", num_speakers=3)
print("Full transcript:")
print(result["transcription"])
print("\nBy speaker:")
print(result["diarization"])
# Output:
# SPEAKER_00 [00:00:00.000 - 00:00:02.480]: Good morning everyone, let's get started.
# SPEAKER_01 [00:00:02.900 - 00:00:03.760]: Thanks for joining.
# SPEAKER_02 [00:00:04.100 - 00:00:05.200]: Happy to be here.
The diarization field is a string, not a list. To work with speakers and timestamps as fields, split it on newlines and match each line with a regular expression; the speaker diarization guide has the pattern.
Improve Python speech recognition accuracy with vocab hints
The prompt parameter gives our speech recognition the drug names, product names, surnames and acronyms it would otherwise misspell:
import requests
API_KEY = "sk_your_api_key_here"
BASE_URL = "https://api.icana.ai/api/v1"
HEADERS = {"X-API-Key": API_KEY}
# Keep under 60 words — only the last ~200 tokens are used
MEDICAL_TERMS = "metformin, HbA1c, hypertension, dyslipidaemia, myocardial infarction, ECG"
LEGAL_TERMS = "indemnification, liquidated damages, Anton Piller, Mareva injunction, subrogation"
FINANCE_TERMS = "ACME Corp, KPIs, Q3 review, EBITDA, CRM, AML obligations"
def submit(audio_path: str, vocab: str) -> str:
with open(audio_path, "rb") as f:
resp = requests.post(
f"{BASE_URL}/transcribe",
headers=HEADERS,
files={"file": f},
data={"language": "en", "prompt": vocab},
)
resp.raise_for_status()
return resp.json()["job_id"]
job_id = submit("consultation.mp3", MEDICAL_TERMS)
print(f"Job submitted: {job_id}")
Error handling and retry logic
Handle four status codes explicitly:
429means you hit the rate limit (10 requests a minute on/transcribe). Sleep for theRetry-Afterheader's value, then retry.402means your credit has run out. CheckGET /api/v1/creditand top up.401means the API key is missing or wrong.400means the file format or a parameter is invalid.
Only a 429 is worth retrying. The poller below also backs off, so long jobs make fewer requests:
import time
import requests
API_KEY = "sk_your_api_key_here"
BASE_URL = "https://api.icana.ai/api/v1"
HEADERS = {"X-API-Key": API_KEY}
def submit_with_retry(audio_path: str, max_retries: int = 3) -> str:
"""Submit a transcription job with retry logic for rate limiting."""
for attempt in range(max_retries):
with open(audio_path, "rb") as f:
response = requests.post(
f"{BASE_URL}/transcribe",
headers=HEADERS,
files={"file": f},
data={"language": "en"},
)
if response.status_code == 200:
return response.json()["job_id"]
elif response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", 10))
print(f"Rate limited. Retrying in {retry_after}s (attempt {attempt + 1}/{max_retries})")
time.sleep(retry_after)
elif response.status_code == 402:
raise RuntimeError(
"Insufficient credit. Top up at "
"https://www.australiantranscription.com.au/billing"
)
elif response.status_code == 401:
raise ValueError("Invalid API key. Check your X-API-Key header.")
else:
response.raise_for_status()
raise RuntimeError(f"Failed after {max_retries} attempts.")
def poll_with_backoff(job_id: str, max_wait_seconds: int = 1800) -> dict:
"""Poll with exponential backoff — gentler on the API."""
interval = 5.0
elapsed = 0.0
while elapsed < max_wait_seconds:
time.sleep(interval)
elapsed += interval
data = requests.get(f"{BASE_URL}/jobs/{job_id}", headers=HEADERS).json()
status = data["status"]
if status == "completed":
return data
elif status == "failed":
raise RuntimeError(f"Job failed: {data.get('error_message', 'unknown')}")
print(f"Status: {status} ({int(elapsed)}s elapsed)")
interval = min(interval * 1.2, 60.0) # cap at 60s
raise TimeoutError(f"Job {job_id} did not complete within {max_wait_seconds}s")
Optimise performance for large audio files
Jobs are independent, so a batch doesn't need to run one file at a time. Submit them all (staying under 10 submissions a minute), then poll each job on its own thread:
import time
import threading
import requests
API_KEY = "sk_your_api_key_here"
BASE_URL = "https://api.icana.ai/api/v1"
HEADERS = {"X-API-Key": API_KEY}
def submit(path: str) -> str:
with open(path, "rb") as f:
r = requests.post(
f"{BASE_URL}/transcribe",
headers=HEADERS,
files={"file": f},
data={"language": "en"},
)
r.raise_for_status()
return r.json()["job_id"]
def poll(job_id: str, results: dict):
interval = 5.0
deadline = time.monotonic() + 1800 # 30 min max
while time.monotonic() < deadline:
time.sleep(interval)
data = requests.get(f"{BASE_URL}/jobs/{job_id}", headers=HEADERS).json()
if data["status"] == "completed":
results[job_id] = data["transcription"]
return
elif data["status"] == "failed":
results[job_id] = None
return
interval = min(interval * 1.2, 60.0)
# Submit up to 10 jobs (rate limit: 10/min on /transcribe)
files = ["call_1.mp3", "call_2.mp3", "call_3.mp3"]
job_ids = [submit(f) for f in files]
# Poll all jobs concurrently
results = {}
threads = [threading.Thread(target=poll, args=(jid, results)) for jid in job_ids]
for t in threads:
t.start()
for t in threads:
t.join()
for jid, transcript in results.items():
print(f"{jid}: {transcript[:100] if transcript else 'FAILED'}...")
Check your credit balance in Python
The /api/v1/credit endpoint returns your AUD balance and how many minutes it buys. Check it before a batch so you don't get a 402 halfway through:
import requests
API_KEY = "sk_your_api_key_here"
BASE_URL = "https://api.icana.ai/api/v1"
HEADERS = {"X-API-Key": API_KEY}
resp = requests.get(f"{BASE_URL}/credit", headers=HEADERS)
resp.raise_for_status()
credit = resp.json()
print(f"Balance: ${credit['balance_aud']} AUD")
print(f"Rate: ${credit['price_per_minute_aud']}/min")
print(f"Estimated remaining: {credit['estimated_remaining_minutes']} minutes")
API reference summary
| Endpoint | Method | Description |
|---|---|---|
| /api/v1/transcribe | POST | Submit audio. Returns job_id. |
| /api/v1/jobs/{job_id} | GET | Poll status. Returns transcription + diarization once, in the first completed response. |
| /api/v1/jobs | GET | List all jobs (paginated). |
| /api/v1/credit | GET | AUD balance and usage summary. |
POST /api/v1/transcribe parameters
file: audio file (multipart/form-data, required, up to 200 MB): MP3, WAV, OGG, FLAC, M4A, MP4, WebMlanguage: ISO 639-1 code, default"en"prompt: comma-separated vocabulary hints (optional, ~60 words max)num_speakers: number of speakers, 1 to 10 (optional, default 2)
Frequently asked questions
How do I convert speech to text in Python?
requests and an API key. You don't need an SDK, a GPU or a model download. Give your poll loop 20 minutes so a job submitted outside AEST business hours survives the cold start.
How do I improve transcription accuracy?
prompt, and set num_speakers for any recording with more or fewer than two people, since it defaults to 2.
What are the rate limits?
/transcribe and 60 a minute on every other endpoint. A 10-second poll uses 6 a minute per job, so poll big batches with a growing interval.
Can I fetch a transcript again later?
completed response, and the files are deleted after that. Store it in the same code path that reads the response.
Does this send my audio data overseas?
Run these scripts on your own audio
Sign up, paste your key into API_KEY and point the script at a real recording. Your first 90 minutes are free and we don't ask for a card.
Related reading: