import os from flask import Flask, request, jsonify from flaskswaggerui import…
- User
import os from flask import Flask, request, jsonify from flask_swagger_ui import get_swaggerui_blueprint from transformers import pipeline import torch
class Config: MODEL_NAME = "openai/whisper-large-v3-turbo" BATCH_SIZE = 8 DEVICE = 0 if torch.cuda.is_available() else "cpu" TEMP_DIR = './temp_files'
# Swagger configuration SWAGGER_URL = '/swagger' API_URL = '/static/swagger.json'class TranscriptionService: def init(self, model_name=Config.MODEL_NAME): self.pipeline = pipeline( task="automatic-speech-recognition", model=model_name, chunk_length_s=30, device=Config.DEVICE, ) os.makedirs(Config.TEMP_DIR, exist_ok=True)
def transcribe_audio(self, audio_path, task="transcribe"): try: result = self.pipeline(audio_path, batch_size=Config.BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True) return result['text'] except Exception as exc: raise RuntimeError(f"Error during transcription: {exc}") @staticmethod def save_file(file): temp_file_path = os.path.join(Config.TEMP_DIR, file.filename) file.save(temp_file_path) return temp_file_path @staticmethod def delete_file(file_path): if os.path.exists(file_path): os.remove(file_path)app = Flask(name) transcription_service = TranscriptionService()
@app.route('/transcribe', methods=['POST']) def transcribe_audio(): if 'file' not in request.files: return jsonify({'error': 'No file uploaded'}), 400
file = request.files['file'] file_path = transcription_service.save_file(file) try: transcription = transcription_service.transcribe_audio(file_path) return jsonify({'transcription': transcription}) except Exception as e: return jsonify({'error': str(e)}), 500 finally: transcription_service.delete_file(file_path)Setup Swagger
swaggerui_blueprint = get_swaggerui_blueprint( Config.SWAGGER_URL, Config.API_URL, config={ 'app_name': "Audio Transcription API" } )
app.register_blueprint(swaggerui_blueprint, url_prefix=Config.SWAGGER_URL)
if name == 'main': app.run(host='0.0.0.0', port=9091, debug=True)
Как мне добавить поддержек формата .m4a
- Assistant
To add support for .m4a audio files in your Flask transcription service, you need to make sure that the library you are using to perform transcription can handle this format. The Transformers library (specifically the pipeline you are using) relies on certain backend dependencies to process audio files. One common library for audio file handling is
ffmpeg, which can decode .m4a files.Here is a step-by-step guide to ensure your application can handle .m4a files:
-
Install ffmpeg:
Make sure that
ffmpegis installed on your system. You can typically install it via package managers likeapt,brew, or by downloading the binaries directly.For example, on a Debian-based system, you can use:
sudo apt update sudo apt install ffmpeg -
Verify ffmpeg Installation:
Check that
ffmpegis accessible by running:ffmpeg -versionIf
ffmpegis correctly installed, this command will display the version information. -
Adapt Your Code:
With
ffmpeginstalled, the Transformers library should be able to read .m4a files directly since it relies on tools likeffmpegto handle different audio formats. -
Test the Application:
Upload an .m4a file through your application to ensure it gets processed correctly. The transcription process should go through without any errors if everything is set up correctly.
-
Error Handling:
Consider adding specific error handling for unsupported file types or issues related to file processing, in case users upload a format
ffmpegcan't handle or ifffmpegis not properly installed.
Here is a revised version of relevant error handling to account for file format issues:
# In your transcribe_audio function if 'file' not in request.files: return jsonify({'error': 'No file uploaded'}), 400 file = request.files['file'] file_path = transcription_service.save_file(file) try: transcription = transcription_service.transcribe_audio(file_path) return jsonify({'transcription': transcription}) except RuntimeError as e: return jsonify({'error': f'Transcription error: {str(e)}'}), 500 except Exception as e: return jsonify({'error': f'Unexpected error: {str(e)}'}), 500 finally: transcription_service.delete_file(file_path)With
ffmpeginstalled, your application should be able to transcribe audio files in .m4a format if there are no underlying compatibility issues with the audio file itself. -