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
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
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 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.")
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
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}...")
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')
# 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!")
# 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()
Corrigir a indentação do código envolve ajustar o recuo de todos os blocos de código para garantir que estejam alinhados corretamente. Aqui está a versão corrigida:
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
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
# 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 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.")
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
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 principal
def main():
# URL do arquivo .txt contendo os HWIDs autorizados online
hwids_url = "https://raw.githubusercontent.com/wendelcassiano/Projetos-Design/main/hwid.txt"
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
# 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')
# 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(len(VideoFileClip('video.mp4').duration), 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 > len(VideoFileClip('video.mp4').duration):
print(f"O vídeo tem {len(VideoFileClip('video.mp4').duration)/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
Claro, aqui está o código novamente com a indentação corrigida:
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
import subprocess
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 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}")
def 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 = [
"",
""
]
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 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...")
model = whisper.load_model("base")
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 = ""
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
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:
parts = split_segment(current_segment, current_start, end, min_duration, max_duration)
conversation_segments.extend(parts)
current_segment = ""
current_start = None
if current_segment:
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)
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:
parts.append({
'text': current_part,
'start': current_start,
'end': end
})
return parts
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, 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']
cut = video.subclip(start, end)
cut = cut.set_duration(end - start)
if vertical_format:
cut = resize_and_crop_vertical(cut)
else:
cut = resize_and_crop_horizontal(cut)
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.")
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:
if 600 <= video_length <= 1800:
min_duration = 300
max_duration = 300
elif video_length > 1800:
min_duration = 600
max_duration = 600
else:
raise ValueError("Vídeo fora do intervalo de duração suportado.")
return min_duration, max_duration
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
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
if current_segment:
conversation_segments.append({
'text': current_segment,
'start': current_start,
'end': end
})
return conversation_segments
def 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):
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')
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':
try:
min_duration, max_duration = automatic_cut(len(VideoFileClip('video.mp4').duration), 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 > len(VideoFileClip('video.mp4').duration):
print(f"O vídeo tem {len(VideoFileClip('video.mp4').duration)/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)
output_video_path = f"{sanitized_title}_#_{i + 1}.mp4"
with VideoFileClip('video.mp4') as video:
conversation_clip = video.subclip(start_time, end_time)
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)
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()
Todos os blocos de código agora estão corretamente indentados e alinhados. Certifique-se de que todas as funções e blocos de código estejam uniformemente recuados, especialmente dentro de estruturas condicionais, loops e definições de funções.