speech-to-text / app.py
oarab's picture
Update app.py
daa5eef verified
Raw History Blame Contribute Delete
2.3 kB
import torch
# import gradio as gr
from transformers import pipeline
import numpy as np
from flask import Flask, jsonify, request
from werkzeug.utils import secure_filename
from flask_cors import CORS
import os
ALLOWED_EXTENSIONS = set(['xls', 'csv', 'png', 'jpeg', 'jpg','wav'])
UPLOAD_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), 'Downloads'))
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 500 * 1000 * 1000 # 500 MB
app.config['CORS_HEADER'] = 'application/json'
device = 0 if torch.cuda.is_available() else "cpu"
transcriber = pipeline("automatic-speech-recognition", model="jonatasgrosman/wav2vec2-large-xlsr-53-english",device=device)
def allowedFile(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def home():
return 'Hello, World!'
@app.route('/upload', methods=['POST', 'GET'])
def fileUpload():
if request.method == 'POST':
file = request.files.getlist('files')
filename = ""
print(request.files, "....")
for f in file:
textz = transcribe(f.read())
print(textz)
print(f.filename)
filename = secure_filename(f.filename)
print(allowedFile(filename))
if allowedFile(filename):
f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
else:
return jsonify({'message': 'File type not allowed'}), 400
return jsonify({"name": filename, "status": "success"})
else:
return jsonify({"status": "Upload API GET Request Running"})
@app.route('/speech-to-text', methods=['POST'])
def speech_to_text():
print(flask.request.data)
return flask.request.files
# Convert audio data to numpy array
y = np.frombuffer(audio_data, dtype=np.float32)
# Reshape the array if needed (depends on the format of the audio data)
# y = np.reshape(y, (-1,))
# Call the transcribe function
text = transcribe(y)
# Return the transcription
return flask.jsonify({'text': text})
def transcribe(new_chunk):
y = np.frombuffer(new_chunk, dtype=np.float32)
sr = 16000
return transcriber({"sampling_rate": sr, "raw": y})["text"]