Ala404 commited on
Commit
95e502b
·
verified ·
1 Parent(s): b1be40a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -66
app.py CHANGED
@@ -1,100 +1,86 @@
1
- # app.py
2
- from flask import Flask, request, jsonify
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
- app = Flask(__name__)
21
- CORS(app) # Enable CORS for all routes
 
 
 
 
 
 
 
 
 
22
 
23
  # Load the model and tokenizer
24
- MODEL_NAME = "STT-Darija-ORG/wav2vec2-xlsr-300m-darija-no-augmentation-v2" # You can replace with your fine-tuned model
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.route('/transcribe', methods=['POST'])
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
- audio_file.save(temp_file.name)
54
  temp_path = temp_file.name
55
 
56
- try:
57
- # Preprocess the audio
58
- speech, sample_rate = preprocess_audio(temp_path)
59
-
60
- # Tokenize the audio
61
- input_values = tokenizer(speech, return_tensors="pt", sampling_rate=sample_rate).input_values
62
-
63
- # Perform inference
64
- with torch.no_grad():
65
- logits = model(input_values).logits
66
-
67
- # Decode the predictions
68
- predicted_ids = torch.argmax(logits, dim=-1)
69
- transcription = tokenizer.decode(predicted_ids[0])
70
-
71
- # Clean up the temporary file
72
- os.unlink(temp_path)
73
-
74
- return jsonify({'transcription': transcription})
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
- return jsonify({'error': f'Transcription failed: {str(e)}'}), 500
 
 
 
84
 
85
- @app.route('/health', methods=['GET'])
86
  def health_check():
87
- return jsonify({'status': 'healthy', 'model': MODEL_NAME})
88
 
89
- @app.route('/', methods=['GET'])
90
  def home():
91
- return jsonify({
92
- 'message': 'Speech Recognition API',
93
- 'endpoints': {
94
- '/transcribe': 'POST - Upload audio file for transcription',
95
- '/health': 'GET - Check API health'
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
+ }