import hashlib import wmi import requests from urllib.parse import urlparse import ytdlp…
- User
import hashlib import wmi import requests from urllib.parse import urlparse import yt_dlp as youtube_dl from moviepy.editor import VideoFileClip import whisper import torch import time import cv2 import re from twitchAPI.twitch import Twitch from twitchAPI.helper import first import os import subprocess import random
def download_video_twitch(video_url): print(f"Baixando vídeo da Twitch de {video_url}…") ydl_opts = { 'format': 'best', 'outtmpl': 'video.mp4', 'quiet': False } try: with youtube_dl.YoutubeDL(ydl_opts) as ydl: info_dict = ydl.extract_info(video_url, download=True) print(f'Título do vídeo: {info_dict.get("title", "N/A")}') return info_dict.get('title', 'N/A') except Exception as e: print(f"Erro ao baixar vídeo da Twitch: {e}") raise
def extract_audio(video_path, audio_path='audio.wav'): print("Processando Audio…") video = VideoFileClip(video_path) audio = video.audio audio.write_audiofile(audio_path) print(f'Áudio Processado para {audio_path}') audio.close() video.close()
def transcribe_audio_whisper(audio_path): print("Analizando as Falas…") if torch.cuda.is_available(): device = "cuda" print("Usando GPU com CUDA") else: device = "cpu" print("Usando CPU") model = whisper.load_model("base", device=device) result = model.transcribe(audio_path) print("Analize completa.") return result['text'], result['segments']
def analyze_transcription(segments, min_duration=30, max_duration=60): print("Analisando Conversas…") conversation_segments = [] current_segment = "" current_start = None current_end = None
for segment in segments: text = segment['text'] start = segment['start'] end = segment['end'] duration = end - start if current_start is None: current_start = start current_end = end current_segment = text else: silence_duration = start - current_end if silence_duration > 3: # Ajuste se necessário if len(current_segment) > 0 and (min_duration <= (current_end - current_start) <= max_duration): conversation_segments.append({ 'text': current_segment.strip(), 'start': current_start, 'end': current_end }) current_segment = text current_start = start current_end = end else: current_segment += f" {text}" current_end = end if (current_end - current_start) >= max_duration: if len(current_segment) > 0: conversation_segments.append({ 'text': current_segment.strip(), 'start': current_start, 'end': current_end }) current_segment = "" current_start = None current_end = None if len(current_segment) > 0 and (min_duration <= (current_end - current_start) <= max_duration): conversation_segments.append({ 'text': current_segment.strip(), 'start': current_start, 'end': current_end }) print(f"Identificadas {len(conversation_segments)} Conversas Analizadas.") return conversation_segmentsdef manual_cut(segments, cut_duration_seconds): def is_end_of_sentence(text): return any(punct in text for punct in [".", "!", "?", ","])
conversation_segments = [] current_segment = "" current_start = None current_duration = 0 for segment in segments: text = segment['text'] start = segment['start'] end = segment['end'] duration = end - start if current_start is None: current_start = start if current_segment: current_segment += " " current_segment += text current_duration += duration if current_duration >= cut_duration_seconds and is_end_of_sentence(text): conversation_segments.append({ 'text': current_segment.strip(), 'start': current_start, 'end': end }) current_segment = "" current_start = None current_duration = 0 if current_segment: conversation_segments.append({ 'text': current_segment.strip(), 'start': current_start, 'end': end }) return conversation_segmentsdef get_hwid(): c = wmi.WMI() serial_number = None for disk in c.Win32_DiskDrive(): serial_number = disk.SerialNumber.strip() break if serial_number is None: raise ValueError("Não foi possível Gerar o HWID.") uuid_hash = hashlib.md5(serial_number.encode('utf-8')).hexdigest() formatted_uuid = f"{uuid_hash[:8]}-{uuid_hash[8:12]}-{uuid_hash[12:16]}-{uuid_hash[16:20]}-{uuid_hash[20:]}" return formatted_uuid
def check_hwid_local(hwid): hwids_autorizados = [ "", # Adicione os HWIDs autorizados aqui ] return hwid in hwids_autorizados
def check_hwid_online(hwids_url, hwid): try: response = requests.get(hwids_url) if response.status_code == 200: hwids = response.text.strip().split('\n') if hwid in hwids: return True else: return False else: print(f"Erro ao acessar Link: {response.status_code}") return False except requests.exceptions.RequestException as e: print(f"Erro de requisição: {e}") return False
def is_valid_url(url): try: result = urlparse(url) return all([result.scheme, result.netloc, result.path]) except ValueError: return False
def normalize_url(url): if not url.startswith('http://') and not url.startswith('https://'): url = 'https://'+url return url
def download_video(url, output_path='video.mp4', max_attempts=10): if not is_valid_url(url): raise ValueError("Link inválido. Verifique o Link e tente novamente.") url = normalize_url(url) attempts = 0 while attempts < max_attempts: try: print(f"Tentativa de download {attempts + 1}…") ydl_opts = { 'format': 'bestvideo[height>=720][ext=mp4]+bestaudio[ext=m4a]/best[height>=720][ext=mp4]+bestaudio[ext=m4a]', 'outtmpl': output_path, 'quiet': False } with youtube_dl.YoutubeDL(ydl_opts) as ydl: info_dict = ydl.extract_info(url, download=True) print(f'Título do vídeo: {info_dict.get("title", "N/A")}') return info_dict.get('title', 'N/A') except Exception as e: print(f"Erro ao baixar vídeo: {e}") attempts += 1 time.sleep(2) print(f"Não foi possível baixar o vídeo após {max_attempts} tentativas. Encerrando o programa.") raise RuntimeError("Falha ao baixar o vídeo após várias tentativas.")
def resize_and_crop_vertical(clip): target_width = 1080 target_height = 1920 def process_frame(frame): frame_height, frame_width = frame.shape[:2] aspect_ratio = frame_width / frame_height target_aspect_ratio = target_width / target_height if (aspect_ratio < target_aspect_ratio): new_width = target_width new_height = int(target_width / aspect_ratio) resized_frame = cv2.resize(frame, (new_width, new_height)) crop_y = (new_height - target_height) // 2 return resized_frame[crop_y:crop_y + target_height, :] else: new_height = target_height new_width = int(target_height * aspect_ratio) resized_frame = cv2.resize(frame, (new_width, new_height)) crop_x = (new_width - target_width) // 2 return resized_frame[:, crop_x:crop_x + target_width] return clip.fl_image(process_frame)
def resize_and_crop_horizontal(clip): target_width = 1920 target_height = 1080 def process_frame(frame): frame_height, frame_width = frame.shape[:2] aspect_ratio = frame_width / frame_height target_aspect_ratio = target_width / target_height if aspect_ratio > target_aspect_ratio: new_height = target_height new_width = int(target_height * aspect_ratio) resized_frame = cv2.resize(frame, (new_width, new_height)) crop_x = (new_width - target_width) // 2 return resized_frame[:, crop_x:crop_x + target_width] else: new_width = target_width new_height = int(target_width / aspect_ratio) resized_frame = cv2.resize(frame, (new_width, new_height)) crop_y = (new_height - target_height) // 2 return resized_frame[crop_y:crop_y + target_height, :] return clip.fl_image(process_frame)
def cut_video(video_path, segments, vertical_format=True, title=""): print("Iniciando o Corte de Vídeo…") video = VideoFileClip(video_path) for i, segment in enumerate(segments): start = segment['start'] end = segment['end'] cut = video.subclip(start, end)
if vertical_format: cut = resize_and_crop_vertical(cut) else: cut = resize_and_crop_horizontal(cut) # Aqui mantenho o título do vídeo com espaços e adiciono a numeração output_filename = f"{title} #{i + 1}.mp4" cut.write_videofile(output_filename, codec='libx264') print(f'Segmento {i + 1} salvo como {output_filename}') video.close() print("Corte de Vídeo Completo.")def automatic_cut(video_length, vertical_format=True): print(f"Em automatic_cut: {video_length}, vertical_format: {vertical_format}") if vertical_format: if video_length < 600: min_total_duration = 30 max_total_duration = 60 elif 600 <= video_length <= 1800: min_total_duration = 30 max_total_duration = 60 elif video_length > 1800: min_total_duration = 60 max_total_duration = 120 else: raise ValueError("Vídeo fora do intervalo de duração suportado.") else: if 600 <= video_length <= 1800: min_total_duration = 300 max_total_duration = 300 elif video_length > 1800: min_total_duration = 600 max_total_duration = 1200 else: raise ValueError("Vídeo fora do intervalo de duração suportado.")
min_duration = random.randint(min_total_duration, max_total_duration) max_duration = random.randint(min_total_duration, max_total_duration) print(f"Retornando min_duration: {min_duration}, max_duration: {max_duration}") return min_duration, max_durationdef main(): hwids_url = "https://raw.githubusercontent.com/wendelcassiano/Projetos-Design/main/hwid.txt" hwid = get_hwid() if not check_hwid_local(hwid): if not check_hwid_online(hwids_url, hwid): print(f"HWID do cliente: {hwid}") input("HWID não autorizado. Envie o Numero HWID para o vendedor…") return while True: video_url = input("Insira o link do vídeo do YouTube e de Enter (ou 'sair' para sair): ").strip() if video_url.lower() == 'sair': break if is_valid_url(video_url): while True: video_format = input("Deseja o vídeo em formato vertical (1080x1920) ou horizontal (1920x1080)? (V/H): ").lower() if video_format == 'v': vertical_format = True break elif video_format == 'h': vertical_format = False break else: print("Opção inválida. Por favor, escolha 'V' para vertical ou 'H' para horizontal.") continue
while True: automatic_option = input("Deseja corte automático ou manual? (automatico/manual): ").lower() if automatic_option == 'automatico': cut_option = 'automatico' break elif automatic_option == 'manual': cut_option = 'manual' break else: print("Opção inválida. Por favor, escolha 'automatico' para corte automático ou 'manual' para corte manual.") continue if cut_option == 'manual': while True: cut_duration = int(input("Digite o tempo de corte em minutos (máximo de 99 minutos): ")) cut_duration_seconds = cut_duration * 60 break if 'twitch.tv' in video_url: video_title = download_video_twitch(video_url) elif 'youtube.com' in video_url or 'youtu.be' in video_url: video_title = download_video(video_url) else: raise ValueError("Link de vídeo não suportado. Insira um link do YouTube ou da Twitch.") try: extract_audio('video.mp4', 'audio.wav') text, segments = transcribe_audio_whisper('audio.wav') video_duration = VideoFileClip('video.mp4').duration print(f"Video duration: {video_duration}") if cut_option == 'automatico': try: min_duration, max_duration = automatic_cut(video_duration, vertical_format) except ValueError as e: print(e) continue elif cut_option == 'manual': min_duration = cut_duration_seconds max_duration = cut_duration_seconds print(f"min_duration: {min_duration}, max_duration: {max_duration}") conversations = analyze_transcription(segments, min_duration=min_duration, max_duration=max_duration) cut_video('video.mp4', conversations, vertical_format=vertical_format, title=video_title) print("Processamento concluído.") time.sleep(60) except Exception as e: print(f"Ocorreu um erro durante o processamento do vídeo: {e}") print("O tempo de uso do software expirou. O software será bloqueado. Fale com o Suporte!")if name == "main": main()
nao esta analisando nem fazendo os cortes!
- Assistant
Vamos analisar o problema passo a passo para identificar onde ele pode estar falhando. Aqui estão algumas etapas para ajudar a depurar esse problema:
-
Verifique se a Transcrição está Funcionando:
- A função
transcribe_audio_whisper()é responsável por transcrever o áudio do vídeo. Certifique-se de que o arquivoaudio.wavestá sendo criado corretamente e que esta função está retornando um texto e segmentos válidos. - Adicione uma linha de impressão dos resultados obtidos após a transcrição para verificar se o Whisper conseguiu interpretar corretamente o áudio.
- A função
-
Confirme a Análise das Transcrições:
- A função
analyze_transcription()é usada para analisar as transcrições e encontrar segmentos de conversação. Certifique-se de que os parâmetrosmin_durationemax_durationestão passando valores corretos e que a função está sendo chamada com os argumentos certos. - Imprima os
segmentsantes de chamaranalyze_transcription, e também imprima o resultadoconversationspara verificar se ele está obtendo os segmentos desejados.
- A função
-
Verifique se os Cortes do Vídeo Estão Sendo Realizados:
- A função
cut_video()é chamada para fazer o corte dos vídeos com base nos segmentos analisados. Verifique se os segmentos obtidos na etapa anterior são realmente passados para essa função. - Acompanhe o progresso dentro de
cut_video()imprimindo o número de segmentos e o start/end de cada segmento. Isso ajuda a ver se os clipes estão sendo criados com os tempos corretos.
- A função
-
Erros Potenciais:
- Certifique-se de estar capturando exceções de modo a identificar problemas específicos. Isso pode ser feito imprimindo a exceção ou o stack trace.
- Verifique logs ou mensagens de erro que possam indicar mais precisamente onde algo falha.
-
Validação de Dados de Entrada/Saída:
- Confirme se o vídeo está sendo baixado e salvo corretamente como
video.mp4. - Consulte se os inputs fornecidos pelo usuário (URL, formato, etc.) estão corretos e se não há erro antes do processamento.
- Confirme se o vídeo está sendo baixado e salvo corretamente como
Aqui está um exemplo de como você pode adicionar prints de depuração para verificar o fluxo:
text, segments = transcribe_audio_whisper('audio.wav') print("Texto transcrito:", text) print("Número de segmentos:", len(segments)) print("Primeiros 5 segmentos:", segments[:5]) if cut_option == 'automatico': try: min_duration, max_duration = automatic_cut(video_duration, vertical_format) except ValueError as e: print(e) continue elif cut_option == 'manual': min_duration = cut_duration_seconds max_duration = cut_duration_seconds print(f"min_duration: {min_duration}, max_duration: {max_duration}") conversations = analyze_transcription(segments, min_duration=min_duration, max_duration=max_duration) print("Conversations:", conversations) cut_video('video.mp4', conversations, vertical_format=vertical_format, title=video_title)Implementar essas verificações ajudará a isolar o problema. Se o erro ainda persistir, compartilhe a saída do console, especialmente qualquer mensagem de erro que você encontrar durante a execução do código. Isso pode fornecer informações adicionais que podem ajudar no diagnóstico.
-
- User
o video sim esta baixaando corretamente Confirme se o vídeo está sendo baixado e salvo corretamente como video.mp4.
mas na ohora de analisar audio ele aparece que 0 conversas foram analizadas! e nao faz os cortes
- Assistant
Se o vídeo está sendo baixado corretamente mas você não está conseguindo obter conversas analisadas para realizar os cortes, pode haver problemas na transcrição ou na lógica que divide essa transcrição em conversas. Vamos revisar algumas possíveis causas e, em seguida, vou sugerir algumas alterações no código para ajudar a diagnosticar e resolver o problema.
Possíveis Problemas a Verificar
-
Qualidade do Áudio e Presença de Voz:
- Assegure-se de que o áudio no vídeo esteja claro e contenha falas reconhecíveis. Se o áudio estiver muito baixo ou houver muito ruído de fundo, o Whisper pode ter dificuldade em transcrever.
-
Função de Transcrição:
- Verifique se a função
transcribe_audio_whisper()está retornando segmentos válidos. Pode ser útil imprimir o conteúdo desegmentslogo após a transcrição.
- Verifique se a função
-
Segmentação de Conversas:
- Verifique a lógica da função
analyze_transcription(). É possível que nenhuma parte do áudio atenda aos critérios de duração mínima e máxima definidos, resultando em zero conversas detectadas.
- Verifique a lógica da função
Etapas para Diagnóstico e Correção
Aqui estão algumas dicas e modificações no código para ajudar a encontrar o problema e testar as funções:
- Revisar a Transcrição:
- Modifique
transcribe_audio_whisper()para imprimir o retorno deresult['segments'].
- Modifique
def transcribe_audio_whisper(audio_path): print("Analisando as Falas…") device = "cuda" if torch.cuda.is_available() else "cpu" model = whisper.load_model("base", device=device) result = model.transcribe(audio_path) print("Texto:", result['text']) print("Segmentos transcritos:", result['segments']) return result['text'], result['segments']- Checar Lógica de Análise:
- Verifique a função
analyze_transcription()para garantir que os critérios de tempo não sejam muito restritivos. - Imprima a duração de cada segmento e verifique se eles caem dentro do intervalo de
min_durationamax_duration.
- Verifique a função
def analyze_transcription(segments, min_duration=30, max_duration=60): print("Analisando Conversas…") conversation_segments = [] current_segment = "" current_start = None current_end = None for segment in segments: text = segment['text'] start = segment['start'] end = segment['end'] duration = end - start print(f"Segmento: '{text}', início: {start}, fim: {end}, duração: {duration}") if current_start is None: current_start = start current_end = end current_segment = text else: silence_duration = start - current_end if silence_duration > 3: if len(current_segment) > 0 and (min_duration <= (current_end - current_start) <= max_duration): conversation_segments.append({ 'text': current_segment.strip(), 'start': current_start, 'end': current_end }) current_segment = text current_start = start current_end = end else: current_segment += f" {text}" current_end = end if (current_end - current_start) >= max_duration: if len(current_segment) > 0: conversation_segments.append({ 'text': current_segment.strip(), 'start': current_start, 'end': current_end }) current_segment = "" current_start = None current_end = None if len(current_segment) > 0 and (min_duration <= (current_end - current_start) <= max_duration): conversation_segments.append({ 'text': current_segment.strip(), 'start': current_start, 'end': current_end }) print(f"Identificadas {len(conversation_segments)} conversas analisadas.") return conversation_segmentsAo adicionar essas linhas de impressão ao código, você deve conseguir acompanhar a transcrição e a análise dos segmentos para detectar onde as falhas estão ocorrendo. Isso pode ajudar a ajustar os parâmetros e a lógica à medida que você descobre o que está acontecendo com a análise de áudio. Se descobrir que os segmentos não estão sendo classificados corretamente, você pode considerar ajustar os valores de
min_durationemax_durationou a lógica de detecção de silêncio. -