Spaces:
Sleeping
Sleeping
| import os | |
| import re | |
| import subprocess | |
| from openai import OpenAI | |
| from constantes import YOUTUBE_COOKIE_PATH | |
| from file_util import File_Util | |
| class Audio_Util: | |
| """ | |
| Manipulação de audio | |
| """ | |
| def download_audio_from_url(url: str, output_path: str, audio_file_name: str) -> str: | |
| """ | |
| Baixa um arquivo de áudio a partir de uma URL. | |
| Args: | |
| url: url do audio | |
| output_path: local esperado para gravação do audio | |
| audio_file_name: nome do arquivo que deve ser utilizado para download | |
| """ | |
| audio_path = f'{output_path}/{audio_file_name}.%(ext)s' | |
| print(f"Baixando áudio de {url} para {audio_path}...") | |
| try: | |
| # Comando yt-dlp para baixar o melhor áudio disponível e convertê-lo para mp3 | |
| command = [ | |
| 'yt-dlp', | |
| "--cookies", YOUTUBE_COOKIE_PATH, | |
| '-f', 'bestaudio[ext=m4a]', | |
| '-o', audio_path, | |
| url | |
| ] | |
| result = subprocess.run(command, check=True, capture_output=True, text=True) | |
| lista_arquivos = File_Util.retirar_sufixo_codec_arquivo(output_path) | |
| print("Download de áudio concluído com sucesso.") | |
| return f"{output_path}/{lista_arquivos[0]}" | |
| except subprocess.CalledProcessError as e: | |
| print(f"Erro ao baixar o áudio: {e}") | |
| print(f"Saída do erro: {e.stderr}") | |
| return False | |
| except FileNotFoundError: | |
| print("Erro: O comando 'yt-dlp' não foi encontrado. Certifique-se de que ele está instalado e no PATH do sistema.") | |
| return False | |
| def extract_text_from_audio_file(audio_path: str) -> str: | |
| """ | |
| Usa a API Whisper da OpenAI para transcrever o áudio em texto com quebras de linha naturais, | |
| removendo timestamps e IDs. Salva em arquivo .txt se o caminho for fornecido. | |
| """ | |
| client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) | |
| try: | |
| audio_path = f"{audio_path}" | |
| print(f"Iniciando transcrição (formato SRT simplificado): {audio_path}") | |
| with open(audio_path, "rb") as audio_file: | |
| transcription = client.audio.transcriptions.create( | |
| model="whisper-1", | |
| file=audio_file, | |
| response_format="srt" | |
| ) | |
| # Remove linhas com números e timestamps | |
| lines = transcription.splitlines() | |
| only_text = [line.strip() for line in lines if not re.match(r"^\d+$", line) and "-->" not in line] | |
| formatted_text = "\n".join(only_text) | |
| print("========== Texto do Audio ===========") | |
| print(only_text) | |
| print("======================================") | |
| return formatted_text | |
| except Exception as e: | |
| print(f"Erro ao transcrever áudio: {e}") | |
| return "" | |