class Wave2Vec2frisian: def init(self,…
- User
class Wave2Vec2_frisian: def init(self, model_id="wietsedv/wav2vec2-large-xlsr-53-frisian"): self.processor = Wav2Vec2Processor.from_pretrained(model_id) self.model = Wav2Vec2ForCTC.from_pretrained(model_id) self.resampler = torchaudio.transforms.Resample(48_000, 16_000)
def preprocess_audio_data(self, audio_data): audio_stream = BytesIO(audio_data) speech_array, _ = torchaudio.load(audio_stream, format="mp3") speech = self.resampler(speech_array).squeeze(0).numpy() return speech def speech_to_text(self, speech): inputs = self.processor(speech, sampling_rate=16_000, return_tensors="pt", padding=True) with torch.no_grad(): logits = self.model(inputs.input_values, attention_mask=inputs.attention_mask).logits predicted_ids = torch.argmax(logits, dim=-1) return self.processor.batch_decode(predicted_ids)[0] def predict(self, audio_data): speech = self.preprocess_audio_data(audio_data) return self.speech_to_text(speech)def file_upload(): file = request.files.get("audio_data") if not file: return jsonify({"error": "No file provided"}), 400
audio_data = file.read() task_id = str(uuid.uuid4()) tasks[task_id] = { "status": "in_progress", "result": None } thread = threading.Thread(target=run_llama_prediction, args=(task_id, audio_data)) thread.start() return jsonify({"task_id": task_id})Change the code to also support audio/webm, and not just audio/mpeg
- Assistant
To support both
audio/webmandaudio/mpegformats, you'll need to adjust your code to handle different audio formats and sample rates dynamically. Here's how you can modify your code:-
Remove the hardcoded format "mp3" from the
torchaudio.loadfunction. This will allowtorchaudioto automatically detect the audio format based on the file content. -
Set the audio backend to "ffmpeg" to ensure that
torchaudiocan handle a wide range of audio formats, includingwebm. -
Adjust the resampling logic to handle any incoming sample rate, not just 48,000 Hz.
Here's the updated code:
import torchaudio from io import BytesIO import torch import threading import uuid from flask import request, jsonify class Wave2Vec2_frisian: def __init__(self, model_id="wietsedv/wav2vec2-large-xlsr-53-frisian"): self.processor = Wav2Vec2Processor.from_pretrained(model_id) self.model = Wav2Vec2ForCTC.from_pretrained(model_id) # Remove the fixed resampler since sample rates may vary def preprocess_audio_data(self, audio_data): audio_stream = BytesIO(audio_data) torchaudio.set_audio_backend("ffmpeg") # Set the backend to 'ffmpeg' for wider format support speech_array, sample_rate = torchaudio.load(audio_stream) # Remove format specification if sample_rate != 16000: # Resample to 16,000 Hz if necessary resampler = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000) speech_array = resampler(speech_array) speech = speech_array.squeeze(0).numpy() return speech def speech_to_text(self, speech): inputs = self.processor(speech, sampling_rate=16000, return_tensors="pt", padding=True) with torch.no_grad(): logits = self.model(inputs.input_values, attention_mask=inputs.attention_mask).logits predicted_ids = torch.argmax(logits, dim=-1) return self.processor.batch_decode(predicted_ids)[0] def predict(self, audio_data): speech = self.preprocess_audio_data(audio_data) return self.speech_to_text(speech) # Assuming 'tasks' is a global dictionary to keep track of tasks tasks = {} def run_llama_prediction(task_id, audio_data): model = Wave2Vec2_frisian() result = model.predict(audio_data) tasks[task_id]["status"] = "completed" tasks[task_id]["result"] = result def file_upload(): file = request.files.get("audio_data") if not file: return jsonify({"error": "No file provided"}), 400 audio_data = file.read() task_id = str(uuid.uuid4()) tasks[task_id] = { "status": "in_progress", "result": None } thread = threading.Thread(target=run_llama_prediction, args=(task_id, audio_data)) thread.start() return jsonify({"task_id": task_id})Explanation of Changes:
-
Removed Hardcoded Format:
- In
preprocess_audio_data, theformat="mp3"argument is removed fromtorchaudio.load(audio_stream). This allowstorchaudioto automatically detect the audio format.
- In
-
Set Audio Backend to "ffmpeg":
- Before loading the audio,
torchaudio.set_audio_backend("ffmpeg")is called. This ensures thattorchaudiocan handle formats likewebmwhich may not be supported by the default backend.
- Before loading the audio,
-
Dynamic Resampling:
- Removed the fixed resampler from the
__init__method. - In
preprocess_audio_data, the sample rate is obtained from the loaded audio. If it's not 16,000 Hz (which is required by the model), it's resampled usingtorchaudio.transforms.Resample.
- Removed the fixed resampler from the
-
Handling Different Audio Formats:
- With these changes, the code can now handle both
audio/webm(commonly using the Opus codec) andaudio/mpegformats, as well as other formats supported by FFmpeg.
- With these changes, the code can now handle both
Additional Notes:
-
Ensure FFmpeg is Installed:
- For
torchaudioto use the FFmpeg backend, FFmpeg must be installed on your system. You can install it using package managers like apt (sudo apt-get install ffmpeg) or brew (brew install ffmpeg), or by downloading it from the official website.
- For
-
Compatibility with Different TorchAudio Versions:
- The FFmpeg backend is available in
torchaudioversions 0.7.0 and above. Ensure that your environment uses a compatible version.
- The FFmpeg backend is available in
-
Thread Safety:
- If you're running this in a multi-threaded environment, ensure that model loading and inference are thread-safe. If not, consider loading the model once and sharing it across threads or using thread-safe mechanisms.
With these modifications, your application should now be able to accept and process both
audio/webmandaudio/mpegfiles. -