import torch from flask import Flask, request, jsonify, sendfromdirectory import whisper…
- User
import torch from flask import Flask, request, jsonify, send_from_directory import whisper from flask_swagger_ui import get_swaggerui_blueprint import os
from transformers import pipeline
MODEL_NAME = "openai/whisper-large-v3-turbo" BATCH_SIZE = 8 device = 0 if torch.cuda.is_available() else "cpu"
class TranscriptionClient: def init(self, model_name="medium"): self.pipe = pipeline( task="automatic-speech-recognition", model=MODEL_NAME, chunk_length_s=30, device=device, )
codedef transcribe(self, audio_path, task="transcribe"): try: result = self.pipe(audio_path, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True) return result.text except Exception as e: raise RuntimeError(f"Ошибка при транскрипции: {e}")app = Flask(name) transcription_client = TranscriptionClient()
SWAGGER_URL = '/swagger' API_URL = '/swagger.json' swaggerui_blueprint = get_swaggerui_blueprint( SWAGGER_URL, API_URL, config={ 'app_name': "Transcription API" } ) app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)
@app.route("/swagger.json") def swagger_json(): return send_from_directory('.', 'swagger.json')
@app.route('/transcribe', methods=['POST']) def transcribe_audio(): try: if 'file' not in request.files: return jsonify({'error': 'Файл не загружен'}), 400
codefile = request.files['file'] transcription = transcription_client.transcribe(file) return jsonify({'transcription': transcription}) except Exception as e: return jsonify({'error': str(e)}), 500if name == 'main': app.run(host='0.0.0.0', port=9091, debug=True)
Что за ошибка: "error": "Ошибка при транскрипции: We expect a numpy ndarray as input, got
<class 'werkzeug.datastructures.file_storage.FileStorage'>" - Assistant
- User
а как потом очищать все эти временные файлы
- Assistant
The use of
tempfile.NamedTemporaryFilewith thedelete=Trueparameter in Python automatically deletes the temporary file once it is closed. In the code I provided, the temporary file is automatically closed and deleted when the with-block is exited, which means you don't have to explicitly delete the files yourself. This is handled by Python's context management.Here's a brief explanation of the process:
-
Creation: The
tempfile.NamedTemporaryFilefunction is used to create a temporary file. Thedelete=Trueparameter ensures that the file is deleted when it is closed. -
Automatic Deletion: When the block of code inside the
withstatement is exited, the temporary file is automatically deleted due to the context manager. This ensures no leftover temporary files on your system.
If you want to manage temporary files manually or if you're using an approach that doesn't automatically handle cleanup, you might consider manually deleting files by tracking their paths and using to delete them once they are no longer needed.
-
- User
"error": "[Errno 13] Permission denied: 'C:\\Users\\crazy\\AppData\\Local\\Temp\\tmpikg1u78e.wav'"
- Assistant
- User
можно сохранять временные файлы в папку с проектом?
- Assistant