Spaces:
Sleeping
Sleeping
tool de transcrição ok
Browse files- tool_audio_extractor.py +20 -28
tool_audio_extractor.py
CHANGED
@@ -10,15 +10,13 @@ import base64
|
|
10 |
import time
|
11 |
import json
|
12 |
import re
|
13 |
-
import
|
14 |
|
15 |
# --- Configurações (Substitua os placeholders) ---
|
16 |
VIDEO_URL = "https://www.youtube.com/watch?v=1htKBjuUWec" # Substitua pela URL do vídeo do YouTube
|
17 |
OUTPUT_DIR = "./audio_analysis_output" # Diretório para salvar o áudio
|
18 |
AUDIO_FILENAME = "downloaded_audio"
|
19 |
TRANSCRIPT_FILENAME = "transcript.txt"
|
20 |
-
AUDIO_PATH = os.path.join(OUTPUT_DIR, AUDIO_FILENAME)
|
21 |
-
TRANSCRIPT_PATH = os.path.join(OUTPUT_DIR, TRANSCRIPT_FILENAME)
|
22 |
|
23 |
# Verifica se a URL foi definida
|
24 |
if VIDEO_URL == "URL_DO_SEU_VIDEO_AQUI":
|
@@ -44,8 +42,11 @@ def retirar_sufixo_codec_arquivo(directory) -> None:
|
|
44 |
print(f"Renomeado: {filename} → {new_filename}")
|
45 |
|
46 |
|
47 |
-
def download_audio(url
|
48 |
"""Baixa apenas o áudio do YouTube usando yt-dlp."""
|
|
|
|
|
|
|
49 |
print(f"Baixando áudio de {url} para {output_path}...")
|
50 |
try:
|
51 |
# Comando yt-dlp para baixar o melhor áudio disponível e convertê-lo para mp3
|
@@ -53,7 +54,7 @@ def download_audio(url, output_path):
|
|
53 |
|
54 |
command = [
|
55 |
'yt-dlp',
|
56 |
-
'-f', '
|
57 |
'-o', output_path,
|
58 |
url
|
59 |
]
|
@@ -71,32 +72,34 @@ def download_audio(url, output_path):
|
|
71 |
print("Erro: O comando 'yt-dlp' não foi encontrado. Certifique-se de que ele está instalado e no PATH do sistema.")
|
72 |
return False
|
73 |
|
74 |
-
def extract_text_from_audio(
|
75 |
"""
|
76 |
Usa a API Whisper da OpenAI para transcrever o áudio em texto com quebras de linha naturais,
|
77 |
removendo timestamps e IDs. Salva em arquivo .txt se o caminho for fornecido.
|
78 |
"""
|
|
|
|
|
79 |
try:
|
80 |
-
|
81 |
print(f"Iniciando transcrição (formato SRT simplificado): {audio_path}")
|
82 |
|
83 |
with open(audio_path, "rb") as audio_file:
|
84 |
-
|
85 |
model="whisper-1",
|
86 |
file=audio_file,
|
87 |
response_format="srt"
|
88 |
)
|
89 |
|
90 |
# Remove linhas com números e timestamps
|
91 |
-
lines =
|
92 |
only_text = [line.strip() for line in lines if not re.match(r"^\d+$", line) and "-->" not in line]
|
93 |
formatted_text = "\n".join(only_text)
|
94 |
|
95 |
# Salva em .txt se desejado
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
|
101 |
return formatted_text
|
102 |
except Exception as e:
|
@@ -112,24 +115,13 @@ if __name__ == "__main__":
|
|
112 |
# Etapa 1: Baixar o vídeo
|
113 |
video_downloaded_or_exists = False
|
114 |
if VIDEO_URL != "URL_DO_SEU_VIDEO_AQUI":
|
115 |
-
if download_audio(VIDEO_URL
|
116 |
-
print(f"
|
117 |
video_downloaded_or_exists = True
|
118 |
else:
|
119 |
print("Falha no download do vídeo. Pulando etapas dependentes.")
|
120 |
-
elif os.path.exists(AUDIO_PATH):
|
121 |
-
print(f"URL não fornecida, mas vídeo encontrado em {AUDIO_PATH}. Tentando processar.")
|
122 |
-
video_downloaded_or_exists = True
|
123 |
else:
|
124 |
-
print("
|
125 |
-
|
126 |
-
if False:
|
127 |
-
|
128 |
-
# Etapa 2: Extrair frames
|
129 |
-
if video_downloaded_or_exists:
|
130 |
-
extract_text_from_audio(AUDIO_PATH + '.mp3', TRANSCRIPT_PATH)
|
131 |
-
else:
|
132 |
-
print("Pulando extração de frames pois o vídeo não está disponível.")
|
133 |
-
|
134 |
|
135 |
|
|
|
10 |
import time
|
11 |
import json
|
12 |
import re
|
13 |
+
from openai import OpenAI
|
14 |
|
15 |
# --- Configurações (Substitua os placeholders) ---
|
16 |
VIDEO_URL = "https://www.youtube.com/watch?v=1htKBjuUWec" # Substitua pela URL do vídeo do YouTube
|
17 |
OUTPUT_DIR = "./audio_analysis_output" # Diretório para salvar o áudio
|
18 |
AUDIO_FILENAME = "downloaded_audio"
|
19 |
TRANSCRIPT_FILENAME = "transcript.txt"
|
|
|
|
|
20 |
|
21 |
# Verifica se a URL foi definida
|
22 |
if VIDEO_URL == "URL_DO_SEU_VIDEO_AQUI":
|
|
|
42 |
print(f"Renomeado: {filename} → {new_filename}")
|
43 |
|
44 |
|
45 |
+
def download_audio(url):
|
46 |
"""Baixa apenas o áudio do YouTube usando yt-dlp."""
|
47 |
+
|
48 |
+
output_path = f'{OUTPUT_DIR}/{AUDIO_FILENAME}.%(ext)s'
|
49 |
+
|
50 |
print(f"Baixando áudio de {url} para {output_path}...")
|
51 |
try:
|
52 |
# Comando yt-dlp para baixar o melhor áudio disponível e convertê-lo para mp3
|
|
|
54 |
|
55 |
command = [
|
56 |
'yt-dlp',
|
57 |
+
'-f', 'bestaudio[ext=m4a]',
|
58 |
'-o', output_path,
|
59 |
url
|
60 |
]
|
|
|
72 |
print("Erro: O comando 'yt-dlp' não foi encontrado. Certifique-se de que ele está instalado e no PATH do sistema.")
|
73 |
return False
|
74 |
|
75 |
+
def extract_text_from_audio() -> str:
|
76 |
"""
|
77 |
Usa a API Whisper da OpenAI para transcrever o áudio em texto com quebras de linha naturais,
|
78 |
removendo timestamps e IDs. Salva em arquivo .txt se o caminho for fornecido.
|
79 |
"""
|
80 |
+
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
81 |
+
|
82 |
try:
|
83 |
+
audio_path = f"{OUTPUT_DIR}/{AUDIO_FILENAME}.m4a"
|
84 |
print(f"Iniciando transcrição (formato SRT simplificado): {audio_path}")
|
85 |
|
86 |
with open(audio_path, "rb") as audio_file:
|
87 |
+
transcription = client.audio.transcriptions.create(
|
88 |
model="whisper-1",
|
89 |
file=audio_file,
|
90 |
response_format="srt"
|
91 |
)
|
92 |
|
93 |
# Remove linhas com números e timestamps
|
94 |
+
lines = transcription.splitlines()
|
95 |
only_text = [line.strip() for line in lines if not re.match(r"^\d+$", line) and "-->" not in line]
|
96 |
formatted_text = "\n".join(only_text)
|
97 |
|
98 |
# Salva em .txt se desejado
|
99 |
+
output_txt_path = f"{OUTPUT_DIR}/{TRANSCRIPT_FILENAME}"
|
100 |
+
with open(output_txt_path, "w", encoding="utf-8") as f:
|
101 |
+
f.write(formatted_text)
|
102 |
+
print(f"Transcrição salva em: {output_txt_path}")
|
103 |
|
104 |
return formatted_text
|
105 |
except Exception as e:
|
|
|
115 |
# Etapa 1: Baixar o vídeo
|
116 |
video_downloaded_or_exists = False
|
117 |
if VIDEO_URL != "URL_DO_SEU_VIDEO_AQUI":
|
118 |
+
if download_audio(VIDEO_URL):
|
119 |
+
print(f"AUDIO salvo em: {OUTPUT_DIR}")
|
120 |
video_downloaded_or_exists = True
|
121 |
else:
|
122 |
print("Falha no download do vídeo. Pulando etapas dependentes.")
|
|
|
|
|
|
|
123 |
else:
|
124 |
+
print("Vídeo não informado")
|
125 |
+
extract_text_from_audio()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
126 |
|
127 |
|