Spaces:
No application file
No application file
File size: 1,795 Bytes
b156b8a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | from tools.interfaces.interface_audio_provider import AudioTranscriptionProvider
import whisper
import requests
import tempfile
import os
class WhisperAudioTranscription(AudioTranscriptionProvider):
def __init__(self, huggingface_token: str, base_url: str,is_local=False):
self.huggingface_token = huggingface_token
self.base_url = base_url
self.supported_formats = ['.mp3']
self.model = whisper.load_model("base")
self.is_local=is_local
def transcribe(self, audio_path_or_url: str) -> str:
try:
# Vérifie le format
if not any(audio_path_or_url.lower().endswith(ext) for ext in self.supported_formats):
return f"Format non supporté. Formats acceptés : {', '.join(self.supported_formats)}"
# Si fichier local
if self.is_local:
if os.path.exists(audio_path_or_url):
tmp_path = audio_path_or_url
else:
# Sinon, on télécharge depuis Hugging Face
headers = {"Authorization": f"Bearer {self.huggingface_token}"}
response = requests.get(self.base_url + audio_path_or_url, headers=headers)
response.raise_for_status()
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as tmp:
tmp.write(response.content)
tmp_path = tmp.name
# Transcription
result = self.model.transcribe(tmp_path)
# Supprime le fichier temporaire si on l’a téléchargé
if not os.path.exists(audio_path_or_url):
os.remove(tmp_path)
return result["text"]
except Exception as e:
return f"Erreur de transcription : {str(e)}"
|