|
import librosa |
|
from transformers import Wav2Vec2ForCTC, AutoProcessor |
|
import torch |
|
import logging |
|
|
|
|
|
logging.basicConfig(level=logging.DEBUG) |
|
|
|
ASR_SAMPLING_RATE = 16_000 |
|
|
|
MODEL_ID = "facebook/wav2vec2-large-960h-lv60-self" |
|
|
|
try: |
|
processor = AutoProcessor.from_pretrained(MODEL_ID) |
|
model = Wav2Vec2ForCTC.from_pretrained(MODEL_ID) |
|
logging.info("ASR model and processor loaded successfully.") |
|
except Exception as e: |
|
logging.error(f"Error loading ASR model or processor: {e}") |
|
|
|
def transcribe(audio): |
|
try: |
|
if audio is None: |
|
logging.error("No audio file provided") |
|
return "ERROR: You have to either use the microphone or upload an audio file" |
|
|
|
logging.info(f"Loading audio file: {audio}") |
|
audio_samples, _ = librosa.load(audio, sr=ASR_SAMPLING_RATE, mono=True) |
|
inputs = processor(audio_samples, sampling_rate=ASR_SAMPLING_RATE, return_tensors="pt") |
|
|
|
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
|
model.to(device) |
|
inputs = inputs.to(device) |
|
|
|
with torch.no_grad(): |
|
outputs = model(**inputs).logits |
|
|
|
ids = torch.argmax(outputs, dim=-1)[0] |
|
transcription = processor.decode(ids) |
|
|
|
logging.info("Transcription completed successfully.") |
|
return transcription |
|
except Exception as e: |
|
logging.error(f"Error during transcription: {e}") |
|
return "ERROR" |
|
|