From c42476549e0525a78911a4180d7bf14a3c48cdb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Cavalcanti?= Date: Sat, 22 Feb 2025 08:13:38 -0300 Subject: [PATCH] ajuste audio source download --- main.py | 12 +++++------- services.py | 23 ++++++++++++++++++++++- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/main.py b/main.py index 7fa930d..29db9d5 100644 --- a/main.py +++ b/main.py @@ -5,6 +5,7 @@ from services import ( send_message_to_whatsapp, get_audio_base64, summarize_text_if_needed, + download_remote_audio, ) from models import WebhookRequest from config import logger, settings, redis_client @@ -151,17 +152,14 @@ async def transcreve_audios(request: Request): # Obter áudio try: if "mediaUrl" in body["data"]["message"]: - audio_source = body["data"]["message"]["mediaUrl"] - storage.add_log("DEBUG", "Usando mediaUrl para áudio", { - "mediaUrl": audio_source - }) + media_url = body["data"]["message"]["mediaUrl"] + storage.add_log("DEBUG", "Baixando áudio via URL", {"mediaUrl": media_url}) + audio_source = await download_remote_audio(media_url) # Baixa o arquivo remoto e retorna o caminho local else: storage.add_log("DEBUG", "Obtendo áudio via base64") base64_audio = await get_audio_base64(server_url, instance, apikey, audio_key) audio_source = await convert_base64_to_file(base64_audio) - storage.add_log("DEBUG", "Áudio convertido", { - "source": audio_source - }) + storage.add_log("DEBUG", "Áudio convertido", {"source": audio_source}) # Carregar configurações de formatação output_mode = get_config("output_mode", "both") diff --git a/services.py b/services.py index 9ad8943..1054e11 100644 --- a/services.py +++ b/services.py @@ -763,4 +763,25 @@ async def translate_text(text: str, source_language: str, target_language: str) "error": str(e), "type": type(e).__name__ }) - raise \ No newline at end of file + raise + +# Nova função para baixar áudio remoto +async def download_remote_audio(url: str) -> str: + """ + Baixa um arquivo de áudio remoto e salva localmente como um arquivo temporário. + Retorna o caminho para o arquivo salvo. + """ + try: + async with aiohttp.ClientSession() as session: + async with session.get(url) as response: + if response.status == 200: + audio_data = await response.read() + # Cria um arquivo temporário para armazenar o áudio (pode ajustar o sufixo caso necessário) + with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as temp_file: + temp_file.write(audio_data) + local_path = temp_file.name + return local_path + else: + raise Exception(f"Falha no download, código de status: {response.status}") + except Exception as e: + raise Exception(f"Erro ao baixar áudio remoto: {str(e)}") \ No newline at end of file