Speech Recognition Case Study
This example demonstrates how to define a scalar UDF for speech recognition, converting binary audio data into text using the Whisper model. It highlights the UDF's capabilities in multimodal data processing.
Scenario
In audio data processing scenarios, binary audio data stored in database tables needs to be converted into text using a speech recognition model (Whisper). By defining a scalar UDF in class form, the Whisper model is loaded in the __init__ method, and speech recognition is performed on each audio segment in the __call__ method, returning the text result. This example downloads a real speech audio file from sample-files.com as test data, writes it into a database table, and processes it using the UDF.
Notes and Constraints
- The transformers package must be installed via pip during UDF runtime. Ensure the runtime environment has network access.
- The __init__ parameters of a scalar UDF only support constant values.
- It is recommended to call delete_function to clean up functions with the same name before registering a UDF to avoid errors during repeated execution.
Prerequisites
- The Aura DataFrame SDK has been installed. For details, see Obtaining and Installing the Aura DataFrame SDK.
- An AuraJobV2 endpoint has been created, and the endpoint name has been obtained. For details, see Creating an Aura Engine Endpoint.
- A LakeFormation instance has been created, where a catalog and a database are ready. For details, see Creating a LakeFormation Instance and Planning Metadata.
- A parallel file system has been created. For details, see Creating a Parallel File System.
- The parameters in os.getenv() involved in the code have been configured as environment variables.
- The Python 3.11 has been installed.
Preparations
This example uses the Whisper speech recognition model. You need to prepare the model files, audio files, and Python dependencies.
- Install the Python dependencies.
pip install torch==2.6.0 pip install transformers==5.3.0 pip install av pip install scipy
- Install the Hugging Face command line tool.
pip install huggingface-hub
- Download the test audio file to the same directory as the example script and rename it test_audio.wav.
.
- Download the Whisper base model file to the same directory as the example script.
hf download openai/whisper-base --local-dir ./whisper_base
If the hf download command is unavailable, manually download the file using a browser.
- Search for openai/whisper-base on the Hugging Face website and go to the model homepage.
- Click the Files and versions tab.
- Download the following files and save them to the local whisper_base directory:
- config.json
- pytorch_model.bin
- preprocessor_config.json
- tokenizer_config.json
- tokenizer.json
- vocab.json
- merges.txt
- normalizer.json
- special_tokens_map.json
- added_tokens.json
- generation_config.json
- Place the whisper_base directory in the same directory as the example script.
Example
This example defines a scalar UDF for speech recognition based on the Whisper model. After writing the test audio into the database, it calls the UDF via the map_batches method to convert binary audio data into text.
- Define the class UDF class SpeechRecognitionUDF. Load the Whisper speech recognition model via transformers in __init__. In __call__, decode the audio binary data using the AV library, resample it to 16 kHz, and perform recognition.
- Connect to the Aura service and set the UDF workspace.
- Read the test audio file, create a table, and insert the binary audio data.
- Delete the existing UDF with the same name (repeated execution is supported).
- Register the scalar UDF to the target database, specifying dependency packages and model files.
- Load the audio_data dataset.
- Call the UDF for speech recognition via the map_batches method, generating the hyp_text column.
- Select the related columns, execute the query, and print the results.
- Disable the Aura connection.
import os
import ibis
import aura_frame
from aura_frame.multimodal import ai_lake
# Define a scalar UDF for speech recognition.
class SpeechRecognitionUDF:
def __init__(self, model_path: str) -> None:
import torch
from transformers import pipeline
self._pipeline = pipeline(
"automatic-speech-recognition",
model=model_path,
device=0 if torch.cuda.is_available() else -1,
)
def __call__(self, audios: bytes) -> str:
import numpy as np
import av
import io
from scipy.signal import resample_poly
container = av.open(io.BytesIO(audios))
stream = container.streams.audio[0]
frames = []
for frame in container.decode(stream):
frames.append(frame.to_ndarray())
if not frames:
raise ValueError("Audio data is None.")
audio_np = np.concatenate(frames, axis=1)
if audio_np.ndim > 1:
audio_np = audio_np.mean(axis=0)
if audio_np.dtype == np.int16:
audio_np = audio_np.astype(np.float32) / 32768.0
elif audio_np.dtype == np.int32:
audio_np = audio_np.astype(np.float32) / 2147483648.0
elif audio_np.dtype != np.float32:
audio_np = audio_np.astype(np.float32)
# Resample to 16 kHz (required by Whisper).
target_sr = 16000
if stream.rate != target_sr:
audio_np = resample_poly(audio_np, target_sr, stream.rate)
result = self._pipeline({"raw": audio_np, "sampling_rate": target_sr})
return result["text"]
try:
# Read the test audio file.
audio_path = "test_audio.wav"
with open(audio_path, "rb") as f:
audio_bytes = f.read()
# Create a table and insert audio data.
table_name = "audio_data"
table_schema = ibis.schema({"id": "int32", "audio_data": "binary"})
con.sql(f'DROP TABLE IF EXISTS "{target_database}"."{table_name}";')
con.create_table(
table_name,
schema=table_schema,
database=target_database,
table_format="orc",
if_not_exists=True,
)
hex_str = audio_bytes.hex()
con.sql(f'''
INSERT INTO "{target_database}"."{table_name}" (id, audio_data) VALUES
(1, '\\x{hex_str}'::bytea)
''')
print("Audio data is written.")
# Delete the existing UDF with the same name (repeated execution is supported).
con.delete_function("speechrecognitionudf", database=target_database, if_it_exists=True)
# Register a scalar UDF for speech recognition.
con.create_scalar_function(
SpeechRecognitionUDF,
database=target_database,
packages=["transformers==5.3.0"],
imports=["./whisper_base"],
)
# Load the audio dataset.
ds = con.load_dataset("audio_data", database=target_database)
# Use the scalar UDF for speech recognition.
udf = con.get_function("speechrecognitionudf", database=target_database)
ds = ds.map_batches(
fn=udf,
on=[ds.audio_data],
as_col="hyp_text",
num_cpus=2,
memory=4096,
arch="x86",
model_path="./whisper_base",
)
ds = ds.select_columns(ds.id, ds.audio_data, ds.hyp_text)
df = ds.execute()
print(df)
finally:
con.close() Helpful Links
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot