Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,100 +1,86 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
from flask_cors import CORS
|
| 4 |
import torch
|
| 5 |
import torchaudio
|
| 6 |
-
from transformers import Wav2Vec2ForCTC, Wav2Vec2Tokenizer
|
| 7 |
-
import tempfile
|
| 8 |
-
import os
|
| 9 |
import librosa
|
| 10 |
import numpy as np
|
| 11 |
-
|
|
|
|
|
|
|
| 12 |
from huggingface_hub import login
|
| 13 |
|
| 14 |
-
|
| 15 |
# Handle authentication if token is provided
|
| 16 |
hf_token = os.getenv("HF_TOKEN")
|
| 17 |
if hf_token:
|
| 18 |
login(token=hf_token)
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
# Load the model and tokenizer
|
| 24 |
-
MODEL_NAME = "STT-Darija-ORG/wav2vec2-xlsr-300m-darija-no-augmentation-v2"
|
| 25 |
tokenizer = Wav2Vec2Tokenizer.from_pretrained(MODEL_NAME)
|
| 26 |
model = Wav2Vec2ForCTC.from_pretrained(MODEL_NAME)
|
| 27 |
|
| 28 |
def preprocess_audio(audio_path):
|
| 29 |
"""Preprocess audio file for the model"""
|
| 30 |
-
# Load audio file
|
| 31 |
speech, sample_rate = librosa.load(audio_path, sr=16000)
|
| 32 |
-
|
| 33 |
-
# Ensure audio is the right format
|
| 34 |
if len(speech.shape) > 1:
|
| 35 |
speech = speech.mean(axis=1) # Convert to mono if stereo
|
| 36 |
-
|
| 37 |
return speech, sample_rate
|
| 38 |
|
| 39 |
-
@app.
|
| 40 |
-
def transcribe_audio():
|
| 41 |
try:
|
| 42 |
-
# Check if audio file is present
|
| 43 |
-
if 'audio' not in request.files:
|
| 44 |
-
return jsonify({'error': 'No audio file provided'}), 400
|
| 45 |
-
|
| 46 |
-
audio_file = request.files['audio']
|
| 47 |
-
|
| 48 |
-
if audio_file.filename == '':
|
| 49 |
-
return jsonify({'error': 'No file selected'}), 400
|
| 50 |
-
|
| 51 |
# Save the uploaded file temporarily
|
| 52 |
with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_file:
|
| 53 |
-
|
| 54 |
temp_path = temp_file.name
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
except Exception as e:
|
| 77 |
-
# Clean up the temporary file in case of error
|
| 78 |
-
if os.path.exists(temp_path):
|
| 79 |
-
os.unlink(temp_path)
|
| 80 |
-
raise e
|
| 81 |
-
|
| 82 |
except Exception as e:
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
-
@app.
|
| 86 |
def health_check():
|
| 87 |
-
return
|
| 88 |
|
| 89 |
-
@app.
|
| 90 |
def home():
|
| 91 |
-
return
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
}
|
| 97 |
-
}
|
| 98 |
-
|
| 99 |
-
if __name__ == '__main__':
|
| 100 |
-
app.run(host='0.0.0.0', port=7860) # HuggingFace Spaces uses port 7860
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
|
|
|
| 3 |
import torch
|
| 4 |
import torchaudio
|
|
|
|
|
|
|
|
|
|
| 5 |
import librosa
|
| 6 |
import numpy as np
|
| 7 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 8 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
+
from transformers import Wav2Vec2ForCTC, Wav2Vec2Tokenizer
|
| 10 |
from huggingface_hub import login
|
| 11 |
|
|
|
|
| 12 |
# Handle authentication if token is provided
|
| 13 |
hf_token = os.getenv("HF_TOKEN")
|
| 14 |
if hf_token:
|
| 15 |
login(token=hf_token)
|
| 16 |
|
| 17 |
+
# Initialize FastAPI app
|
| 18 |
+
app = FastAPI()
|
| 19 |
+
|
| 20 |
+
# Enable CORS for all origins (you can restrict this as needed)
|
| 21 |
+
app.add_middleware(
|
| 22 |
+
CORSMiddleware,
|
| 23 |
+
allow_origins=["*"], # Allows all origins; adjust for production
|
| 24 |
+
allow_credentials=True,
|
| 25 |
+
allow_methods=["*"], # Allows all methods
|
| 26 |
+
allow_headers=["*"], # Allows all headers
|
| 27 |
+
)
|
| 28 |
|
| 29 |
# Load the model and tokenizer
|
| 30 |
+
MODEL_NAME = "STT-Darija-ORG/wav2vec2-xlsr-300m-darija-no-augmentation-v2"
|
| 31 |
tokenizer = Wav2Vec2Tokenizer.from_pretrained(MODEL_NAME)
|
| 32 |
model = Wav2Vec2ForCTC.from_pretrained(MODEL_NAME)
|
| 33 |
|
| 34 |
def preprocess_audio(audio_path):
|
| 35 |
"""Preprocess audio file for the model"""
|
|
|
|
| 36 |
speech, sample_rate = librosa.load(audio_path, sr=16000)
|
|
|
|
|
|
|
| 37 |
if len(speech.shape) > 1:
|
| 38 |
speech = speech.mean(axis=1) # Convert to mono if stereo
|
|
|
|
| 39 |
return speech, sample_rate
|
| 40 |
|
| 41 |
+
@app.post("/transcribe")
|
| 42 |
+
def transcribe_audio(file: UploadFile = File(...)):
|
| 43 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
# Save the uploaded file temporarily
|
| 45 |
with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_file:
|
| 46 |
+
temp_file.write(file.file.read())
|
| 47 |
temp_path = temp_file.name
|
| 48 |
|
| 49 |
+
# Preprocess the audio
|
| 50 |
+
speech, sample_rate = preprocess_audio(temp_path)
|
| 51 |
+
|
| 52 |
+
# Tokenize the audio
|
| 53 |
+
input_values = tokenizer(speech, return_tensors="pt", sampling_rate=sample_rate).input_values
|
| 54 |
+
|
| 55 |
+
# Perform inference
|
| 56 |
+
with torch.no_grad():
|
| 57 |
+
logits = model(input_values).logits
|
| 58 |
+
|
| 59 |
+
# Decode the predictions
|
| 60 |
+
predicted_ids = torch.argmax(logits, dim=-1)
|
| 61 |
+
transcription = tokenizer.decode(predicted_ids[0])
|
| 62 |
+
|
| 63 |
+
# Clean up the temporary file
|
| 64 |
+
os.unlink(temp_path)
|
| 65 |
+
|
| 66 |
+
return {"transcription": transcription}
|
| 67 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
except Exception as e:
|
| 69 |
+
# Clean up the temporary file in case of error
|
| 70 |
+
if os.path.exists(temp_path):
|
| 71 |
+
os.unlink(temp_path)
|
| 72 |
+
raise HTTPException(status_code=500, detail=f"Transcription failed: {str(e)}")
|
| 73 |
|
| 74 |
+
@app.get("/health")
|
| 75 |
def health_check():
|
| 76 |
+
return {"status": "healthy", "model": MODEL_NAME}
|
| 77 |
|
| 78 |
+
@app.get("/")
|
| 79 |
def home():
|
| 80 |
+
return {
|
| 81 |
+
"message": "Speech Recognition API",
|
| 82 |
+
"endpoints": {
|
| 83 |
+
"/transcribe": "POST - Upload audio file for transcription",
|
| 84 |
+
"/health": "GET - Check API health"
|
| 85 |
}
|
| 86 |
+
}
|
|
|
|
|
|
|
|
|