Speech to Text from a File with Python

Speech to Text from a File with Python Introduction In this post, I want to share a Python implementation that uses the Speech to Text service from Azure Cognitive Services. The challenge lies in handling the events needed to process longer


Introduction

In this post, I want to share a Python implementation that uses the Speech to Text service from Azure Cognitive Services. The challenge lies in handling the events needed to process longer audio transcriptions, as described in the Azure official documentation. You can find the full code in my GitHub repository: GitHub — mdiloreto/azure-speech-to-text-from-file.

Azure supports audio transcriptions for short segments (up to 15 seconds) or until silence is detected. For longer real-time transcripts, callbacks using EventSignals must be implemented. Here are the key events handled by Azure’s SpeechRecognizer:

  • recognizing: Triggered with partial transcriptions during processing.
  • recognized: Indicates a successful portion of the audio has been fully recognized.
  • session_started: Signals the start of a recognition session.
  • session_stopped: Marks the end of the session.
  • canceled: Triggered by user action or a failure in the connection/protocol.

Let’s break down the code and explain its key sections.

Imports and Configuration

Python
import os
import time
import azure.cognitiveservices.speech as speechsdk
  • os: For accessing environment variables (like the Azure API key).
  • time: Used to control timing during speech recognition.
  • azure.cognitiveservices.speech: Azure’s official library for speech services.

Class Definition

The main class ExtractTranscript handles the speech recognition process and saves transcripts.

Function: continuous_recognition_handler

Python
def continuous_recognition_handler(self, evt, transcriptions):
"""Handles the recognized speech."""
if evt.result.reason == speechsdk.ResultReason.RecognizedSpeech:
print(f"RECOGNIZED: {evt.result.text}")
transcriptions.append(evt.result.text)
  • This function processes recognized portions of the audio.
  • When speech is recognized, the transcript is printed and appended to the transcriptions list.

Function: stop_cb

Python
def stop_cb(self, evt, speech_recognizer):
"""Stops recognition when the stop event is received."""
print('CLOSING on {}'.format(evt))
speech_recognizer.stop_continuous_recognition()
global done
done = True
  • This function stops the speech recognition process when the session ends or is canceled.
  • The global done variable is set to True to end the main loop.

Function: extract_transcript

Python
def extract_transcript(self, audio_file):
"""Sets up continuous speech recognition from a file."""
global done
done = False
transcriptions = []
# Set up the speech config
speech_key = os.getenv("AZURE_SPEECH_KEY")
service_region = "eastus"
speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)
auto_detect_source_language_config = speechsdk.languageconfig.AutoDetectSourceLanguageConfig(
languages=["en-US", "es-AR"]
)
# Set up the audio config using audio file
audio_config = speechsdk.audio.AudioConfig(filename=audio_file)
# Initialize the speech recognizer
speech_recognizer = speechsdk.SpeechRecognizer(
speech_config=speech_config,
auto_detect_source_language_config=auto_detect_source_language_config,
audio_config=audio_config
)
# Event callbacks
speech_recognizer.recognizing.connect(lambda evt: print('RECOGNIZING: {}'.format(evt)))
speech_recognizer.recognized.connect(lambda evt: self.continuous_recognition_handler(evt, transcriptions))
speech_recognizer.session_started.connect(lambda evt: print('SESSION STARTED: {}'.format(evt)))
speech_recognizer.session_stopped.connect(lambda evt: self.stop_cb(evt, speech_recognizer))
speech_recognizer.canceled.connect(lambda evt: self.stop_cb(evt, speech_recognizer))
# Start continuous recognition
speech_recognizer.start_continuous_recognition()
# Keep the script running until recognition is complete
while not done:
time.sleep(0.5)
return transcriptions
  • extract_transcript initializes speech recognition from an audio file.
  • The speech_config is set up using Azure API credentials and regional information, and it automatically detects English and Spanish.
  • The SpeechRecognizer is initialized with audio input and event handlers for various stages of recognition.
  • A loop keeps the script running until transcription completes.

Function: save_transcriptions_to_file

Python
def save_transcriptions_to_file(self, transcriptions, file_name="transcriptions.txt"):
"""Save the transcriptions to a text file."""
with open(file_name, 'w', encoding='utf-8') as f:
for line in transcriptions:
f.write(line + '\n')
print(f"Transcriptions saved to {file_name}")
  • Saves the list of transcriptions to a text file, with each transcript on a new line.

Written by Mateo Di Loreto

Thanks for reading. The learning continues in the next article.