Skip to content
The Chat Archive
gpt-4o-2024-08-06· OpenAI WildChat-4.8M (AI2)

import os from flask import Flask, request, jsonify from flaskswaggerui import…

  1. 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

  2. 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:

    1. Install ffmpeg:

      Make sure that ffmpeg is installed on your system. You can typically install it via package managers like apt, brew, or by downloading the binaries directly.

      For example, on a Debian-based system, you can use:

      sudo apt update
      sudo apt install ffmpeg
      
    2. Verify ffmpeg Installation:

      Check that ffmpeg is accessible by running:

      ffmpeg -version
      

      If ffmpeg is correctly installed, this command will display the version information.

    3. Adapt Your Code:

      With ffmpeg installed, the Transformers library should be able to read .m4a files directly since it relies on tools like ffmpeg to handle different audio formats.

    4. 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.

    5. Error Handling:

      Consider adding specific error handling for unsupported file types or issues related to file processing, in case users upload a format ffmpeg can't handle or if ffmpeg is 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 ffmpeg installed, your application should be able to transcribe audio files in .m4a format if there are no underlying compatibility issues with the audio file itself.