Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

class Wave2Vec2frisian: def init(self,…

  1. 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

  2. Assistant

    To support both audio/webm and audio/mpeg formats, you'll need to adjust your code to handle different audio formats and sample rates dynamically. Here's how you can modify your code:

    1. Remove the hardcoded format "mp3" from the torchaudio.load function. This will allow torchaudio to automatically detect the audio format based on the file content.

    2. Set the audio backend to "ffmpeg" to ensure that torchaudio can handle a wide range of audio formats, including webm.

    3. 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, the format="mp3" argument is removed from torchaudio.load(audio_stream). This allows torchaudio to automatically detect the audio format.
    • Set Audio Backend to "ffmpeg":

      • Before loading the audio, torchaudio.set_audio_backend("ffmpeg") is called. This ensures that torchaudio can handle formats like webm which may not be supported by the default backend.
    • 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 using torchaudio.transforms.Resample.
    • Handling Different Audio Formats:

      • With these changes, the code can now handle both audio/webm (commonly using the Opus codec) and audio/mpeg formats, as well as other formats supported by FFmpeg.

    Additional Notes:

    • Ensure FFmpeg is Installed:

      • For torchaudio to 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.
    • Compatibility with Different TorchAudio Versions:

      • The FFmpeg backend is available in torchaudio versions 0.7.0 and above. Ensure that your environment uses a compatible version.
    • 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/webm and audio/mpeg files.