import hashlib
import wmi
import requests
from urllib.parse import urlparse
import yt_dlp as youtube_dl
import subprocess
from moviepy.editor import VideoFileClip, concatenate_videoclips
import whisper
import time
import cv2
Função para baixar vídeo do YouTube ou da Twitch usando yt-dlp
def download_video(url, output_path='video.mp4'):
print(f"Baixando vídeo de {url}...")
code
ydl_opts = {
'format': 'bestvideo[height>=720]+bestaudio/best',
'outtmpl': output_path,
'quiet': False
}
try:
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}")
raise
Função para processar um vídeo do YouTube ou da Twitch
def process_video(url):
try:
video_title = download_video(url)
extract_audio('video.mp4')
transcribed_text, segments = transcribe_audio_whisper('audio.wav')
conversation_segments = analyze_transcription(segments)
output_filename = f'{video_title}_processed.mp4'
cut_video('video.mp4', conversation_segments, output_filename)
print(f"Processamento concluído com sucesso! Vídeo processado salvo como {output_filename}")
except Exception as e:
print(f"Ocorreu um erro durante o processamento do vídeo: {e}")
Função para obter o HWID do cliente usando WMI e formatar como UUID
def get_hwid():
c = wmi.WMI()
serial_number = None
for disk in c.Win32_DiskDrive():
serial_number = disk.SerialNumber.strip()
break # Para pegar apenas o primeiro disco encontrado
code
if serial_number is None:
raise ValueError("Não foi possível gerar o HWID.")
# Gerar um UUID baseado no número serial do disco usando MD5
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
Função para verificar o HWID localmente
def check_hwid_local(hwid):
# Lista de HWIDs autorizados locais (pode ser omitida se for utilizar apenas verificação online)
hwids_autorizados = [
"",
""
# Adicione mais HWIDs autorizados conforme necessário
]
return hwid in hwids_autorizados
Assistant
User
me entregue o código corrigido de forma completa
Assistant
Função para verificar o HWID online usando o arquivo .txt no GitHub
def check_hwid_online(hwids_url, hwid):
try:
# Faz a requisição GET para obter o conteúdo do arquivo .txt no GitHub
response = requests.get(hwids_url)
code
# Verifica se a requisição foi bem sucedida (código 200)
if response.status_code == 200:
# Separa as linhas do arquivo .txt
hwids = response.text.strip().split('\n')
# Verifica se a HWID do cliente está na lista
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
for i, segment in enumerate(segments):
text = segment['text']
start = segment['start']
end = segment['end']
duration = end - (current_start if current_start is not None else start)
if current_start is None:
current_start = start
if current_segment:
current_segment += " "
current_segment += text
# Verificar se há pontuação final e se a duração está dentro do intervalo
if any(punct in text for punct in [".", "!", "?"]):
if min_duration <= duration <= max_duration:
conversation_segments.append({
'text': current_segment,
'start': current_start,
'end': end
})
current_segment = ""
current_start = None
elif duration > max_duration:
# Se a duração for maior que o máximo, dividir o segmento
parts = split_segment(current_segment, current_start, end, min_duration, max_duration)
conversation_segments.extend(parts)
current_segment = ""
current_start = None
if current_segment: # Adicionar qualquer texto restante como um segmento
duration = segments[-1]['end'] - current_start
if min_duration <= duration <= max_duration:
conversation_segments.append({
'text': current_segment,
'start': current_start,
'end': segments[-1]['end']
})
print(f"Identificadas {len(conversation_segments)} Conversas Analisadas.")
return conversation_segments
Função para dividir um segmento longo em partes menores dentro dos limites de duração
def split_segment(text, start, end, min_duration, max_duration):
words = text.split()
parts = []
current_part = ""
current_start = start
current_end = start
duration = end - start
code
if duration <= max_duration:
parts.append({
'text': text,
'start': start,
'end': end
})
return parts
for word in words:
if current_part:
current_part += " "
current_part += word
current_end += (end - start) / len(words) # Estimar o tempo por palavra
duration = current_end - current_start
if duration >= min_duration and any(punct in word for punct in [".", "!", "?"]):
parts.append({
'text': current_part,
'start': current_start,
'end': current_end
})
current_part = ""
current_start = current_end
if current_part: # Adicionar qualquer texto restante como um segmento
parts.append({
'text': current_part,
'start': current_start,
'end': end
})
return parts
Função para redimensionar e ajustar o vídeo para a resolução vertical 1080x1920
hwid = get_hwid()
# Verifica localmente e, se necessário, verifica online
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 Número HWID para o vendedor...")
return
while True:
video_url = input("Insira o link do vídeo do YouTube ou da Twitch (ou 'sair' para sair): ").strip()
if video_url.lower() == 'sair':
break
try:
process_video(video_url)
time.sleep(60) # Aguarda 60 segundos antes de verificar novamente
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. Entre em contato com o Suporte!")
if name == "main":
main()
analize e me diga porque esse código acima faz downloads dos videos do twitch sem problemas enquanto o codigo de baixo esta dando erros:
import hashlib
import wmi
import requests
from urllib.parse import urlparse
import yt_dlp as youtube_dl
from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip
import whisper
import time
import cv2
import re
from twitchAPI.twitch import Twitch
from twitchAPI.helper import first
from urllib.parse import urlparse
import subprocess
Função para baixar vídeo do YouTube ou da Twitch usando yt-dlp
def download_video(url, output_path='video.mp4'):
print(f"Baixando vídeo de {url}...")
code
ydl_opts = {
'format': 'bestvideo[height>=720]+bestaudio/best',
'outtmpl': output_path,
'quiet': False
}
try:
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}")
raise
Função para processar um vídeo do YouTube ou da Twitch
def process_video(url):
try:
video_title = download_video(url)
extract_audio('video.mp4')
transcribed_text, segments = transcribe_audio_whisper('audio.wav')
conversation_segments = analyze_transcription(segments)
output_filename = f'{video_title}_processed.mp4'
cut_video('video.mp4', conversation_segments, output_filename)
print(f"Processamento concluído com sucesso! Vídeo processado salvo como {output_filename}")
except Exception as e:
print(f"Ocorreu um erro durante o processamento do vídeo: {e}")
Função para obter o HWID do cliente usando WMI e formatar como UUID
def get_hwid():
c = wmi.WMI()
serial_number = None
for disk in c.Win32_DiskDrive():
serial_number = disk.SerialNumber.strip()
break # Para pegar apenas o primeiro disco encontrado
code
if serial_number is None:
raise ValueError("Não foi possível Gerar o HWID.")
# Gerar um UUID baseado no número serial do disco usando MD5
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
Função para verificar o HWID localmente
def check_hwid_local(hwid):
# Lista de HWIDs autorizados locais (pode ser omitida se for utilizar apenas verificação online)
hwids_autorizados = [
"",
""
# Adicione mais HWIDs autorizados conforme necessário
]
return hwid in hwids_autorizados
Função para verificar o HWID online usando o arquivo .txt no GitHub
def check_hwid_online(hwids_url, hwid):
try:
# Faz a requisição GET para obter o conteúdo do arquivo .txt no GitHub
response = requests.get(hwids_url)
code
# Verifica se a requisição foi bem sucedida (código 200)
if response.status_code == 200:
# Separa as linhas do arquivo .txt
hwids = response.text.strip().split('\n')
# Verifica se a HWID do cliente está na lista
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
Função para normalizar a URL (adicionar https:// se necessário)
def normalize_url(url):
if not url.startswith('http://') and not url.startswith('https://'):
url = 'https://' + url
return url
Função para baixar o vídeo do YouTube com preferência por 1080p ou 720p usando yt-dlp
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.")
code
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]', # Escolhe a melhor qualidade de vídeo de pelo menos 720p em formato MP4
'outtmpl': output_path, # Nome do arquivo de saída
'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) # Espera por 2 segundos antes de tentar novamente
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.")
Função para extrair o áudio do vídeo
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()
Função para transcrever o áudio usando Whisper
def transcribe_audio_whisper(audio_path):
print("Analizando as Falas...")
model = whisper.load_model("base")
result = model.transcribe(audio_path)
print("Analize completa.")
return result['text'], result['segments']
Função para analisar a transcrição e identificar conversas completas dentro do tempo estipulado
for i, segment in enumerate(segments):
text = segment['text']
start = segment['start']
end = segment['end']
duration = end - (current_start if current_start is not None else start)
if current_start is None:
current_start = start
if current_segment:
current_segment += " "
current_segment += text
# Verificar se há pontuação final e se a duração está dentro do intervalo
if any(punct in text for punct in [".", "!", "?"]):
if min_duration <= duration <= max_duration:
conversation_segments.append({
'text': current_segment,
'start': current_start,
'end': end
})
current_segment = ""
current_start = None
elif duration > max_duration:
# Se a duração for maior que o máximo, dividir o segmento
parts = split_segment(current_segment, current_start, end, min_duration, max_duration)
conversation_segments.extend(parts)
current_segment = ""
current_start = None
if current_segment: # Adicionar qualquer texto restante como um segmento
duration = segments[-1]['end'] - current_start
if min_duration <= duration <= max_duration:
conversation_segments.append({
'text': current_segment,
'start': current_start,
'end': segments[-1]['end']
})
print(f"Identificadas {len(conversation_segments)} Conversas Analizadas.")
return conversation_segments
def split_segment(text, start, end, min_duration, max_duration):
words = text.split()
parts = []
current_part = ""
current_start = start
current_end = start
duration = end - start
code
if duration <= max_duration:
parts.append({
'text': text,
'start': start,
'end': end
})
return parts
for word in words:
if current_part:
current_part += " "
current_part += word
current_end += (end - start) / len(words) # Estimar o tempo por palavra
duration = current_end - current_start
if duration >= min_duration and any(punct in word for punct in [".", "!", "?"]):
parts.append({
'text': current_part,
'start': current_start,
'end': current_end
})
current_part = ""
current_start = current_end
if current_part: # Adicionar qualquer texto restante como um segmento
parts.append({
'text': current_part,
'start': current_start,
'end': end
})
return parts
Função para redimensionar e ajustar o vídeo para a resolução vertical 1080x1920
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
# Se a duração atual for maior ou igual à duração de corte desejada, mas não quebra a fala
if current_duration >= cut_duration_seconds:
if any(punct in text for punct in [".", "!", "?"]):
conversation_segments.append({
'text': current_segment,
'start': current_start,
'end': end
})
current_segment = ""
current_start = None
current_duration = 0
# Adicionar qualquer segmento restante
if current_segment:
conversation_segments.append({
'text': current_segment,
'start': current_start,
'end': end
})
return conversation_segments
hwid = get_hwid()
# Verifica localmente e, se necessário, verifica online
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
# Função para baixar vídeo da Twitch usando yt-dlp
def download_video_twitch(video_url):
print(f"Baixando vídeo da Twitch de {video_url}...")
code
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
Parte do código que verifica e baixa vídeos do YouTube ou da Twitch
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
code
if is_valid_url(video_url):
if 'twitch.tv' in video_url:
# Baixar vídeo da Twitch
video_title = download_video_twitch(video_url)
elif 'youtube.com' in video_url or 'youtu.be' in video_url:
# Baixar vídeo do YouTube
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:
video_title = download_video(video_url)
extract_audio('video.mp4', 'audio.wav')
text, segments = transcribe_audio_whisper('audio.wav')
video_length = VideoFileClip('video.mp4').duration
# Escolha do formato vertical (V) ou horizontal (H)
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
# Escolha entre corte automático ou manual
while True:
automatic_option = input("Deseja corte automático ou manual? (automatico/manual): ").lower()
if automatic_option == 'automatico':
try:
min_duration, max_duration = automatic_cut(video_length, vertical_format)
break
except ValueError as e:
print(e)
continue
elif automatic_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
if cut_duration_seconds > video_length:
print(f"O vídeo tem {video_length/60:.2f} minutos, que é menor que o tempo de corte escolhido ({cut_duration} minutos). Por favor, escolha um tempo menor.")
else:
min_duration = cut_duration_seconds
max_duration = cut_duration_seconds
break
break
else:
print("Opção inválida. Por favor, escolha 'automatico' para corte automático ou 'manual' para corte manual.")
continue
conversations = analyze_transcription(segments, min_duration=min_duration, max_duration=max_duration)
for i, conversation in enumerate(conversations):
start_time = conversation['start']
end_time = conversation['end']
sanitized_title = "".join(x if x.isalnum() else "_" for x in video_title) # Sanitize the title
output_video_path = f"{sanitized_title}_#_{i+1}.mp4"
with VideoFileClip('video.mp4') as video:
conversation_clip = video.subclip(start_time, end_time)
# Redimensionar de acordo com a escolha do usuário
if vertical_format:
resized_clip = resize_and_crop_vertical(conversation_clip)
else:
resized_clip = resize_and_crop_horizontal(conversation_clip)
resized_clip.write_videofile(output_video_path, codec='libx264')
print(f"Vídeo {i+1} exportado para {output_video_path}")
print("Processamento concluído.")
time.sleep(60) # Aguarda 60 segundos antes de verificar novamente
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()
esse é o erro que aparece:
Insira o link do vídeo do YouTube e de Enter (ou 'sair' para sair): https://www.twitch.tv/videos/2171477131
Baixando vídeo da Twitch de https://www.twitch.tv/videos/2171477131...
[twitch:vod] Extracting URL: https://www.twitch.tv/videos/2171477131
[twitch:vod] 2171477131: Downloading stream metadata GraphQL
[twitch:vod] 2171477131: Downloading video access token GraphQL
[twitch:vod] 2171477131: Downloading m3u8 information
[twitch:vod] 2171477131: Downloading storyboard metadata JSON
[info] v2171477131: Downloading 1 format(s): 1080p60
[download] video.mp4 has already been downloaded
[download] 100% of 290.77MiB
Título do vídeo: 🟢 AO VIVO - IRL POR LOS ANGELES CHURASCO COM A TROPA - Siga @jonvlogs nas redes s ociais
Tentativa de download 1...
[twitch:vod] Extracting URL: https://www.twitch.tv/videos/2171477131
[twitch:vod] 2171477131: Downloading stream metadata GraphQL
[twitch:vod] 2171477131: Downloading video access token GraphQL
[twitch:vod] 2171477131: Downloading m3u8 information
[twitch:vod] 2171477131: Downloading storyboard metadata JSON
ERROR: [twitch:vod] v2171477131: Requested format is not available. Use --list-formats for a list of available formats
Erro ao baixar vídeo: ERROR: [twitch:vod] v2171477131: Requested format is not available. Use --list-formats for a list of available formats
Tentativa de download 2...
[twitch:vod] Extracting URL: https://www.twitch.tv/videos/2171477131
[twitch:vod] 2171477131: Downloading stream metadata GraphQL
Ao analisar os códigos fornecidos e o erro encontrado no segundo código, podemos observar algumas diferenças significativas e potenciais problemas.
Diferenças Chave e Problemas Potenciais
Tentativa Redundante de Download:
No segundo código, existe uma redundância ao tentar baixar o vídeo duas vezes:
A primeira tentativa de download já aconteceu usando a função download_video_twitch, e depois disso, download_video é chamada novamente, o que pode causar conflitos ou redundâncias desnecessárias.
Formato de Download:
O erro específico aponta para "Requested format is not available", sugerindo que o formato especificado no ydl_opts não está disponível para o vídeo fornecido.
Tentativas de Solução
Evitar Dowload Redundante:
Remova a tentativa redundante de baixar o vídeo após ter utilizado download_video_twitch.
Ajustar o Formato de Download:
Tente ajustar as opções de download para formatos que são mais provavelmente disponíveis no Twitch. Você pode listar os formatos disponíveis usando yt-dlp e ajustar os parâmetros de acordo:
python
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
E remova a chamada redundante de download_video:
python
if is_valid_url(video_url):
if 'twitch.tv' in video_url:
# Baixar vídeo da Twitch
video_title = download_video_twitch(video_url)
elif 'youtube.com' in video_url or 'youtu.be' in video_url:
# Baixar vídeo do YouTube
video_title = download_video(video_url)
else:
raise ValueError("Link de vídeo não suportado. Insira um link do YouTube ou da Twitch.")
Com isso, você garante que a tentativa de download é feita apenas uma vez.
Verificação de Formatos Disponíveis
Se for necessário verificar quais formatos estão disponíveis antes de tentar baixar o vídeo, você pode fazer o seguinte ajuste na função de download:
python
def list_formats(video_url):
print(f"Listando formatos para {video_url}...")
ydl_opts = {
'listformats': True,
'quiet': False
}
try:
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.extract_info(video_url, download=False)
except Exception as e:
print(f"Erro ao listar formatos: {e}")
raise
Então, chame list_formats(video_url) antes de tentar baixar o vídeo para ver quais formatos estão disponíveis e ajuste o ydl_opts em conformidade.
Versão Final do Código Ajustado
Após aplicar as correções, seu código final para download de vídeos do Twitch deve parecer com o seguinte:
python
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
# Parte do código que verifica e baixa vídeos do YouTube ou da Twitch
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):
if 'twitch.tv' in video_url:
# Baixar vídeo da Twitch
video_title = download_video_twitch(video_url)
elif 'youtube.com' in video_url ou 'youtu.be' em video_url:
# Baixar vídeo do YouTube
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')
# Continue with the rest of the processing...
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!")
Com essas mudanças, o código deve funcionar corretamente para baixar vídeos do Twitch sem encontrar os problemas de formato anterior.
Claro, aqui está o código corrigido, com redundâncias removidas e ajustes feitos para garantir o download adequado dos vídeos do Twitch:
python
import hashlib
import wmi
import requests
from urllib.parse import urlparse
import yt_dlp as youtube_dl
from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip
import whisper
import time
import cv2
import re
# Função para baixar vídeo do YouTube ou da Twitch usando yt-dlp
def download_video(url, output_path='video.mp4'):
print(f"Baixando vídeo de {url}...")
ydl_opts = {
'format': 'bestvideo[height>=720]+bestaudio/best',
'outtmpl': output_path,
'quiet': False
}
try:
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}")
raise
# Função para processar um vídeo do YouTube ou da Twitch
def process_video(url):
try:
video_title = download_video(url)
extract_audio('video.mp4')
transcribed_text, segments = transcribe_audio_whisper('audio.wav')
conversation_segments = analyze_transcription(segments)
output_filename = f'{video_title}_processed.mp4'
cut_video('video.mp4', conversation_segments, output_filename)
print(f"Processamento concluído com sucesso! Vídeo processado salvo como {output_filename}")
except Exception as e:
print(f"Ocorreu um erro durante o processamento do vídeo: {e}")
# Função para obter o HWID do cliente usando WMI e formatar como UUID
def get_hwid():
c = wmi.WMI()
serial_number = None
for disk in c.Win32_DiskDrive():
serial_number = disk.SerialNumber.strip()
break # Para pegar apenas o primeiro disco encontrado
if serial_number is None:
raise ValueError("Não foi possível Gerar o HWID.")
# Gerar um UUID baseado no número serial do disco usando MD5
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
# Função para verificar o HWID localmente
def check_hwid_local(hwid):
# Lista de HWIDs autorizados locais (pode ser omitida se for utilizar apenas verificação online)
hwids_autorizados = [
"",
""
# Adicione mais HWIDs autorizados conforme necessário
]
return hwid in hwids_autorizados
# Função para verificar o HWID online usando o arquivo .txt no GitHub
def check_hwid_online(hwids_url, hwid):
try:
# Faz a requisição GET para obter o conteúdo do arquivo .txt no GitHub
response = requests.get(hwids_url)
# Verifica se a requisição foi bem sucedida (código 200)
if response.status_code == 200:
# Separa as linhas do arquivo .txt
hwids = response.text.strip().split('\n')
# Verifica se a HWID do cliente está na lista
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
# Função para validar a URL
def is_valid_url(url):
try:
result = urlparse(url)
return all([result.scheme, result.netloc, result.path])
except ValueError:
return False
# Função para normalizar a URL (adicionar https:// se necessário)
def normalize_url(url):
if not url.startswith('http://') and not url.startswith('https://'):
url = 'https://' + url
return url
# Função para extrair o áudio do vídeo
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()
# Função para transcrever o áudio usando Whisper
def transcribe_audio_whisper(audio_path):
print("Analizando as Falas...")
model = whisper.load_model("base")
result = model.transcribe(audio_path)
print("Analize completa.")
return result['text'], result['segments']
# Função para analisar a transcrição e identificar conversas completas dentro do tempo estipulado
def analyze_transcription(segments, min_duration=30, max_duration=60):
print("Analisando Conversas...")
conversation_segments = []
current_segment = ""
segment_start = 0
current_start = None
for i, segment in enumerate(segments):
text = segment['text']
start = segment['start']
end = segment['end']
duration = end - (current_start if current_start is not None else start)
if current_start is None:
current_start = start
if current_segment:
current_segment += " "
current_segment += text
# Verificar se há pontuação final e se a duração está dentro do intervalo
if any(punct in text for punct in [".", "!", "?"]):
if min_duration <= duration <= max_duration:
conversation_segments.append({
'text': current_segment,
'start': current_start,
'end': end
})
current_segment = ""
current_start = None
elif duration > max_duration:
# Se a duração for maior que o máximo, dividir o segmento
parts = split_segment(current_segment, current_start, end, min_duration, max_duration)
conversation_segments.extend(parts)
current_segment = ""
current_start = None
if current_segment: # Adicionar qualquer texto restante como um segmento
duration = segments[-1]['end'] - current_start
if min_duration <= duration <= max_duration:
conversation_segments.append({
'text': current_segment,
'start': current_start,
'end': segments[-1]['end']
})
print(f"Identificadas {len(conversation_segments)} Conversas Analizadas.")
return conversation_segments
def split_segment(text, start, end, min_duration, max_duration):
words = text.split()
parts = []
current_part = ""
current_start = start
current_end = start
duration = end - start
if duration <= max_duration:
parts.append({
'text': text,
'start': start,
'end': end
})
return parts
for word in words:
if current_part:
current_part += " "
current_part += word
current_end += (end - start) / len(words) # Estimar o tempo por palavra
duration = current_end - current_start
if duration >= min_duration and any(punct in word for punct in [".", "!", "?"]):
parts.append({
'text': current_part,
'start': current_start,
'end': current_end
})
current_part = ""
current_start = current_end
if current_part: # Adicionar qualquer texto restante como um segmento
parts.append({
'text': current_part,
'start': current_start,
'end': end
})
return parts
# Função para redimensionar e ajustar o vídeo para a resolução vertical 1080x1920
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:
# Se o vídeo for mais alto, redimensionar pela largura e cortar as bordas superior e inferior
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:
# Se o vídeo for mais largo, redimensionar pela altura e cortar as bordas laterais
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)
# Função para redimensionar e ajustar o vídeo para a resolução horizontal 1920x1080
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:
# Se o vídeo for mais largo, redimensionar pela altura e cortar as bordas laterais
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:
# Se o vídeo for mais alto, redimensionar pela largura e cortar as bordas superior e inferior
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)
# Função para cortar o vídeo com base nos segmentos identificados
def cut_video(video_path, segments, output_prefix='output', vertical_format=True):
print("Iniciando o Corte de Video...")
video = VideoFileClip(video_path)
for i, segment in enumerate(segments):
start = segment['start']
end = segment['end']
text = segment['text']
# Adicionar o texto como overlay no vídeo
cut = video.subclip(start, end)
cut = cut.set_duration(end - start)
# Ajustar para o formato vertical ou horizontal
if vertical_format:
cut = resize_and_crop_vertical(cut)
else:
cut = resize_and_crop_horizontal(cut)
# Adicionar overlay de texto
txt_clip = (TextClip(text, fontsize=24, color='white', size=(cut.w, None), method='caption')
.set_position(('center', 'bottom'))
.set_duration(cut.duration))
video_with_text = CompositeVideoClip([cut, txt_clip])
output_filename = f"{output_prefix}_{i+1}.mp4"
video_with_text.write_videofile(output_filename, codec='libx264')
print(f'Segmento {i+1} salvo como {output_filename}')
video.close()
print("Corte de Video Completo.")
# Função para calcular a duração mínima e máxima com base na duração total do vídeo
def automatic_cut(video_length, vertical_format=True):
if vertical_format:
if 600 <= video_length <= 1800:
min_duration = 30
max_duration = 60
elif video_length > 1800:
min_duration = 60
max_duration = 60
else:
raise ValueError("Vídeo fora do intervalo de duração suportado.")
else: # Horizontal
if 600 <= video_length <= 1800:
min_duration = 300 # 5 minutos em segundos
max_duration = 300
elif video_length > 1800:
min_duration = 600 # 10 minutos em segundos
max_duration = 600
else:
raise ValueError("Vídeo fora do intervalo de duração suportado.")
return min_duration, max_duration
# Função para corte manual garantindo que não interrompa no meio de uma palavra ou fala
def manual_cut(segments, cut_duration_seconds):
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
# Se a duração atual for maior ou igual à duração de corte desejada, mas não quebra a fala
if current_duration >= cut_duration_seconds:
if any(punct in text for punct in [".", "!", "?"]):
conversation_segments.append({
'text': current_segment,
'start': current_start,
'end': end
})
current_segment = ""
current_start = None
current_duration = 0
# Adicionar qualquer segmento restante
if current_segment:
conversation_segments.append({
'text': current_segment,
'start': current_start,
'end': end
})
return conversation_segments
# Função para baixar vídeo da Twitch usando yt-dlp
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
# Parte do código que verifica e baixa vídeos do YouTube ou da Twitch
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):
if 'twitch.tv' in video_url:
# Baixar vídeo da Twitch
video_title = download_video_twitch(video_url)
elif 'youtube.com' in video_url or 'youtu.be' in video_url:
# Baixar vídeo do YouTube
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_length = VideoFileClip('video.mp4').duration
# Escolha do formato vertical (V) ou horizontal (H)
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
# Escolha entre corte automático ou manual
while True:
automatic_option = input("Deseja corte automático ou manual? (automatico/manual): ").lower()
if automatic_option == 'automatico':
try:
min_duration, max_duration = automatic_cut(video_length, vertical_format)
break
except ValueError as e:
print(e)
continue
elif automatic_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
if cut_duration_seconds > video_length:
print(f"O vídeo tem {video_length/60:.2f} minutos, que é menor que o tempo de corte escolhido ({cut_duration} minutos). Por favor, escolha um tempo menor.")
else:
min_duration = cut_duration_seconds
max_duration = cut_duration_seconds
break
break
else:
print("Opção inválida. Por favor, escolha 'automatico' para corte automático ou 'manual' para corte manual.")
continue
conversations = analyze_transcription(segments, min_duration=min_duration, max_duration=max_duration)
for i, conversation in enumerate(conversations):
start_time = conversation['start']
end_time = conversation['end']
sanitized_title = "".join(x if x.isalnum() else "_" for x in video_title) # Sanitize the title
output_video_path = f"{sanitized_title}_#_{i+1}.mp4"
with VideoFileClip('video.mp4') as video:
conversation_clip = video.subclip(start_time, end_time)
# Redimensionar de acordo com a escolha do usuário
if vertical_format:
resized_clip = resize_and_crop_vertical(conversation_clip)
else:
resized_clip = resize_and_crop_horizontal(conversation_clip)
resized_clip.write_videofile(output_video_path, codec='libx264')
print(f"Vídeo {i+1} exportado para {output_video_path}")
print("Processamento concluído.")
time.sleep(60) # Aguarda 60 segundos antes de verificar novamente
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()
Este código corrige a redundância no download e ajusta as opções de formato para garantir que os vídeos do Twitch sejam baixados e processados corretamente. Certifique-se de que o link fornecido ao código seja válido e que o ambiente de execução contenha todas as dependências necessárias.