import os
import time
import threading
import random
import subprocess
import string
import math
from tkinter import (
Tk, Frame, Button, Text, Entry, Label, messagebox, END, Scrollbar, filedialog, simpledialog, Listbox, VERTICAL, SINGLE, RIGHT, Y, LEFT, BOTH
)
import tkinter as tk
from tkinter.ttk import Notebook, Progressbar, Combobox, Style
import pyperclip
import shutil
import queue
# Para o vídeo e áudio
import cv2
from pydub import AudioSegment
from pydub.silence import detect_nonsilent
import numpy as np
#################################
# Configurações e constantes
#################################
PASTA_CATEGORIAS = r"C:\Users\jonathan\Desktop\AUTLAND\CATEGORIAS DE IMAGENS VIDEO"
AUDIO_FUNDO = r"C:\Users\jonathan\Desktop\AUTLAND\TRILHA SONORA\soundfund.mp3"
PASTA_DESTINO_VIDEOS = r"C:\Users\jonathan\Desktop\FINANCE CHANEEL\VIDEO PARA POSTAR PRONTOS"
PASTA_TRUMP_AUDIOS = r"C:\Users\jonathan\Desktop\AUTLAND\AUDIOS\AUDIOS TRUMP"
PASTA_WARREN_AUDIOS = r"C:\Users\jonathan\Desktop\AUTLAND\AUDIOS\AUDIOS WARREN"
PASTA_TRUMP_IMAGENS = r"C:\Users\jonathan\Desktop\AUTLAND\CATEGORIAS DE IMAGENS VIDEO\TRUMP"
PASTA_WARREN_IMAGENS = r"C:\Users\jonathan\Desktop\AUTLAND\CATEGORIAS DE IMAGENS VIDEO\WARREN"
PASTA_TRUMP_DESTINO = r"C:\Users\jonathan\Desktop\AUTLAND\POSTAGEM\VIDEO TRUMP"
PASTA_WARREN_DESTINO = r"C:\Users\jonathan\Desktop\AUTLAND\POSTAGEM\VIDEO WARREN"
#################################
# Funções e efeitos para edição de vídeo com sincronização e progressão
#################################
def gerar_prompt(titulo):
return f"""Agora você é um roteirista profissional de YouTube e vai criar um script sobre:{titulo}.
Por favor, faça isso sem marcações de transições ou cenas, quero apenas a frase do narrador não coloque o titulo no começoapenas texto. . Introdução (300-500 palavras): Apresente o tema de forma clara e envolvente. Use uma anedota ou pergunta intrigante para capturar a atenção. Explique brevemente o que será abordado no vídeo e por que é relevante para o espectador. Desenvolvimento (2.000-2.200 palavras): Divida em seções claras e bem organizadas, cada uma abordando um ponto específico. Mantenha a fluidez e transições suaves entre as seções. Ofereça informações relevantes, dados, exemplos, e insights que agreguem valor. Faça perguntas retóricas para estimular o pensamento e a reflexão. Interação com o Público (200-300 palavras): No meio do vídeo, introduza um momento para incentivar os espectadores a se inscreverem no canal. Relacione isso ao conteúdo que está sendo apresentado. Peça para os espectadores compartilharem suas opiniões nos comentários sobre o tema abordado. Conclusão (300-500 palavras): Resuma os pontos principais discutidos no vídeo. Reforce a importância do tema e convide os espectadores a aplicarem o que aprenderam. Finalize com um convite para que assistam a outros vídeos do canal e deixem o like se gostaram do conteúdo. Dicas Adicionais: Mantenha um tom de conversa natural e envolvente. Evite longas explicações e vá direto ao ponto. Use exemplos práticos e histórias pessoais para conectar com o público. E se você quer ir além, assista esse vídeo aqui do lado que aprofunda ainda mais no passo 2 que falei aqui."O vídeo deve terminar com um gancho para outro conteúdo (evitando um final seco). Incentive a interação de forma natural. Exemplo: “Se achou isso absurdo, espere até descobrir o que acontece no Catar…” Forneça um script contendo aproximadamente 3000 palavras para um vídeo do YouTube, vou contar as palavras, então, não tente me enganar!. totalizando 3000 palavras. Forneça o texto em inglês, adaptando para a cultura daquele país quando necessário, deixando ele fluído e natural, adicione o título escolhido e por favor não divida o texto, quero apenas o que deve ser dito pelo narrador. É importante que seja um texto longo sobre [assunto]. Não inclua títulos, subtítulos, perguntas ou qualquer tipo de formatação extra. Quero apenas o texto bruto, sem nada além da escrita. Nada disso "Sure. Here’s Part 1 of the full script, written exactly as requested — dense, conversational, and designed for YouTube high-retention storytelling, all in English. It contains exactly 3000 words." nada disso no final. "Let me know se você quer que eu continue com a Parte 2, com mais 3000 palavras, seguindo exatamente o mesmo estilo." não pergunte e nem escreva nada no final quero que você crie algo único que nunca tenha feito"""
class CriadorEnredoFrame(Frame):
COR_FUNDO = "#000000"
COR_TEXTO = "#FFFFFF"
COR_BOTAO = "#00FF00"
COR_BOTAO_HOVER = "#00CC00"
COR_TEXTO_BOTAO = "#FFFFFF"
FONT_TITULO = ("Segoe UI Semibold", 14)
FONT_DEFAULT = ("Segoe UI", 11)
FONT_LOG = ("Consolas", 11)
def __init__(self, parent):
super().__init__(parent, bg=self.COR_FUNDO)
self.titulos = []
self.index = 0
self.titulo_atual = ""
Label(self, text="Criador de Enredo", font=self.FONT_TITULO,
bg=self.COR_FUNDO, fg=self.COR_TEXTO).pack(pady=7)
Label(self, text="Cole os títulos (um por linha):",
bg=self.COR_FUNDO, fg=self.COR_TEXTO, font=self.FONT_DEFAULT).pack()
self.text_input = Text(self, height=10, width=80,
bg="#101010", fg=self.COR_TEXTO,
insertbackground=self.COR_TEXTO, font=self.FONT_DEFAULT)
self.text_input.pack()
btn_copiar_titulo_frame = Frame(self, bg=self.COR_FUNDO)
btn_copiar_titulo_frame.pack(pady=(7, 12))
self.btn_copiar_titulo_atual = Button(btn_copiar_titulo_frame, text="Copiar Título Atual", command=self.copiar_titulo_atual,
state="disabled", bg=self.COR_BOTAO, fg=self.COR_TEXTO_BOTAO,
relief="flat", activebackground=self.COR_BOTAO_HOVER, activeforeground=self.COR_TEXTO_BOTAO,
font=self.FONT_DEFAULT, padx=10, pady=5)
self.btn_copiar_titulo_atual.pack()
self.avancar_button = Button(self, text="Avançar", command=self.iniciar_prompts,
bg=self.COR_BOTAO, fg=self.COR_TEXTO_BOTAO,
relief="flat", activebackground=self.COR_BOTAO_HOVER, activeforeground=self.COR_TEXTO_BOTAO,
font=self.FONT_DEFAULT, padx=12, pady=6)
self.avancar_button.pack(pady=12)
self.prompt_output = Text(self, height=20, width=100, wrap="word",
bg="#101010", fg=self.COR_TEXTO, insertbackground=self.COR_TEXTO,
font=self.FONT_LOG)
self.prompt_output.pack()
self.prompt_output.config(state="disabled")
btn_frame = Frame(self, bg=self.COR_FUNDO)
btn_frame.pack(pady=8)
Button(btn_frame, text="Copiar Prompt", command=self.copiar_prompt,
bg=self.COR_BOTAO, fg=self.COR_TEXTO_BOTAO, relief="flat",
activebackground=self.COR_BOTAO_HOVER, activeforeground=self.COR_TEXTO_BOTAO,
font=self.FONT_DEFAULT, padx=10, pady=5).grid(row=0, column=0, padx=8)
Button(btn_frame, text="Próximo", command=self.proxima_prompt,
bg=self.COR_BOTAO, fg=self.COR_TEXTO_BOTAO, relief="flat",
activebackground=self.COR_BOTAO_HOVER, activeforeground=self.COR_TEXTO_BOTAO,
font=self.FONT_DEFAULT, padx=10, pady=5).grid(row=0, column=1, padx=8)
def iniciar_prompts(self):
self.titulos = [linha.strip() for linha in self.text_input.get("1.0", END).splitlines() if linha.strip()]
self.index = 0
if not self.titulos:
messagebox.showerror("Erro", "Por favor, insira pelo menos um título.")
self.btn_copiar_titulo_atual.config(state="disabled")
return
self.mostrar_prompt()
def mostrar_prompt(self):
if self.index < len(self.titulos):
self.titulo_atual = self.titulos[self.index]
self.btn_copiar_titulo_atual.config(state="normal")
prompt = gerar_prompt(self.titulo_atual)
self.prompt_output.config(state="normal")
self.prompt_output.delete("1.0", END)
self.prompt_output.insert(END, prompt)
self.prompt_output.config(state="disabled")
else:
self.titulo_atual = ""
self.btn_copiar_titulo_atual.config(state="disabled")
self.prompt_output.config(state="normal")
self.prompt_output.delete("1.0", END)
self.prompt_output.insert(END, "Todos os prompts foram gerados.")
self.prompt_output.config(state="disabled")
def copiar_prompt(self):
texto = self.prompt_output.get("1.0", END).strip()
pyperclip.copy(texto)
messagebox.showinfo("Copiado", "Prompt copiado para a área de transferência!")
def copiar_titulo_atual(self):
if self.titulo_atual:
pyperclip.copy(self.titulo_atual)
messagebox.showinfo("Copiado", f"Título '{self.titulo_atual}' copiado para a área de transferência!")
else:
messagebox.showwarning("Aviso", "Nenhum título para copiar.")
def proxima_prompt(self):
self.index += 1
self.mostrar_prompt()
##############################################
def zoom_effect(image, progress, zoom_in=True, direction="center"):
h, w = image.shape[:2]
zoom_strength = 0.05
scale = 1 + (zoom_strength * progress) if zoom_in else 1 + (zoom_strength * (1 - progress))
new_w, new_h = int(w * scale), int(h * scale)
resized = cv2.resize(image, (new_w, new_h))
if direction == "top":
x, y = (new_w - w) // 2, 0
elif direction == "bottom":
x, y = (new_w - w) // 2, new_h - h
elif direction == "left":
x, y = 0, (new_h - h) // 2
elif direction == "right":
x, y = new_w - w, (new_h - h) // 2
elif direction == "top_left":
x, y = 0, 0
elif direction == "top_right":
x, y = new_w - w, 0
elif direction == "bottom_left":
x, y = 0, new_h - h
elif direction == "bottom_right":
x, y = new_w - w, new_h - h
else:
x, y = (new_w - w) // 2, (new_h - h) // 2
x = max(min(x, new_w - w), 0)
y = max(min(y, new_h - h), 0)
cropped = resized[y:y + h, x:x + w]
return cropped
def move_effect(image, progress, direction="left_to_right"):
h, w = image.shape[:2]
dx = int(w * 0.05 * progress)
dy = int(h * 0.05 * progress)
if direction == "left_to_right":
M = np.float32([[1, 0, dx], [0, 1, 0]])
elif direction == "right_to_left":
M = np.float32([[1, 0, -dx], [0, 1, 0]])
elif direction == "top_to_bottom":
M = np.float32([[1, 0, 0], [0, 1, dy]])
elif direction == "bottom_to_top":
M = np.float32([[1, 0, 0], [0, 1, -dy]])
else:
return image
moved = cv2.warpAffine(image, M, (w, h))
return moved
def ken_burns_effect(image, progress, zoom_in=True, direction="left_to_right"):
h, w = image.shape[:2]
zoom_strength = 0.1
scale = 1 + (zoom_strength * progress) if zoom_in else 1 + (zoom_strength * (1 - progress))
new_w, new_h = int(w * scale), int(h * scale)
resized = cv2.resize(image, (new_w, new_h))
dx = int((new_w - w) * progress)
dy = int((new_h - h) * progress)
if direction == "left_to_right":
x, y = dx, 0
elif direction == "right_to_left":
x, y = (new_w - w) - dx, 0
elif direction == "top_to_bottom":
x, y = 0, dy
elif direction == "bottom_to_top":
x, y = 0, (new_h - h) - dy
elif direction == "top_left_to_bottom_right":
x, y = dx, dy
elif direction == "bottom_right_to_top_left":
x, y = (new_w - w) - dx, (new_h - h) - dy
else:
x, y = (new_w - w) // 2, (new_h - h) // 2
x = max(min(x, new_w - w), 0)
y = max(min(y, new_h - h), 0)
cropped = resized[y:y + h, x:x + w]
return cropped
def ok_bye_effect(image, progress):
h, w = image.shape[:2]
zoom_strength = 0.15
scale = 1 + (zoom_strength * (1 - progress))
new_w, new_h = int(w * scale), int(h * scale)
resized = cv2.resize(image, (new_w, new_h))
x = (new_w - w) // 2
y = (new_h - h) // 2
cropped = resized[y:y + h, x:x + w]
fade = np.zeros_like(cropped)
frame = cv2.addWeighted(cropped, 1 - progress, fade, progress, 0)
return frame
def load_images_from_folder(folder):
images = []
for filename in os.listdir(folder):
if filename.lower().endswith((".png", ".jpg", ".jpeg")):
path = os.path.join(folder, filename)
img = cv2.imread(path)
if img is not None and img.shape[0] > 0 and img.shape[1] > 0:
images.append(img)
random.shuffle(images)
return images
def get_beat_times(audio_path, frame_ms=50, energy_threshold_factor=1.3):
audio = AudioSegment.from_file(audio_path).set_channels(1)
frame_length = frame_ms
n_frames = len(audio) // frame_length
energies = []
for i in range(n_frames):
frame = audio[i * frame_length:(i + 1) * frame_length]
energies.append(frame.rms)
energies = np.array(energies)
avg_energy = np.mean(energies)
beat_indices = []
for i in range(1, len(energies) - 1):
if energies[i] > energy_threshold_factor * avg_energy and energies[i] > energies[i - 1] and energies[i] > energies[i + 1]:
beat_indices.append(i)
beat_times = [i * frame_length / 1000.0 for i in beat_indices]
filtered_beats = []
min_separation = 1.0 # modifica aqui a distância natural entre beats
for t in beat_times:
if len(filtered_beats) == 0 or (t - filtered_beats[-1]) > min_separation:
filtered_beats.append(t)
return filtered_beats
# ==> NOVA FUNÇÃO PARA REMOVER SILÊNCIOS DO ÁUDIO, mantem espaço "natural" nos cortes <==
def remover_silencio(audio_segment, silence_thresh=-50, min_silence_len=500, padding=300):
"""
Remove segmentos silenciosos do áudio.
silence_thresh: limiar de silêncio em dBFS (ex: -50)
min_silence_len: duração mínima do silêncio em ms
padding: adiciona ms de "silêncio" natural nas bordas dos segmentos para evitar cortes abruptos
"""
nao_silencioso = detect_nonsilent(audio_segment, min_silence_len=min_silence_len, silence_thresh=silence_thresh)
if not nao_silencioso:
return audio_segment
partes = []
for start, end in nao_silencioso:
# Ajusta os limites incluindo padding para deixar espaço natural
start_pad = max(0, start - padding)
end_pad = min(len(audio_segment), end + padding)
partes.append(audio_segment[start_pad:end_pad])
audio_sem_silencio = partes[0]
for part in partes[1:]:
# Adiciona uma pequena pausa natural entre segmentos para evitar cortes secos
audio_sem_silencio += AudioSegment.silent(duration=150) + part
return audio_sem_silencio
def create_video_only(video_path, duration, images, fps=30, progress_callback=None,
change_times=None):
if not images:
raise ValueError("Lista de imagens vazia.")
height, width, _ = images[0].shape
total_frames = int(duration * fps)
out = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))
img_index = 0
# Lista de efeitos disponíveis (REMOVIDO efeito de fade 'ok_bye')
efeitos = ["zoom", "move", "ken_burns"]
current_effect = random.choice(efeitos)
zoom_in_random = random.choice([True, False])
direction_zoom = random.choice([
"center", "top", "bottom", "left", "right",
"top_left", "top_right", "bottom_left", "bottom_right"
])
direction_move = random.choice([
"left_to_right", "right_to_left",
"top_to_bottom", "bottom_to_top"
])
direction_ken = random.choice([
"left_to_right", "right_to_left",
"top_to_bottom", "bottom_to_top",
"top_left_to_bottom_right", "bottom_right_to_top_left"
])
start_time = time.time()
if change_times is None or len(change_times) == 0:
def random_interval_frames():
# Distância natural entre as trocas: entre 2.5 a 4 segundos (feito para suavizar)
return int(random.uniform(2.5, 4.0) * fps)
frames_per_image = random_interval_frames()
next_change_frame = frames_per_image
else:
change_frames = [int(t * fps) for t in change_times if t * fps < total_frames]
if change_frames[-1] < total_frames - 1:
change_frames.append(total_frames - 1)
change_index = 0
next_change_frame = change_frames[change_index]
for i in range(total_frames):
if i >= next_change_frame:
img_index = (img_index + 1) % len(images)
if change_times is None or len(change_times) == 0:
frames_per_image = random_interval_frames()
next_change_frame = i + frames_per_image
else:
change_index += 1
if change_index < len(change_frames):
next_change_frame = change_frames[change_index]
else:
next_change_frame = total_frames + 1
current_effect = random.choice(efeitos)
zoom_in_random = random.choice([True, False])
direction_zoom = random.choice([
"center", "top", "bottom", "left", "right",
"top_left", "top_right", "bottom_left", "bottom_right"
])
direction_move = random.choice([
"left_to_right", "right_to_left",
"top_to_bottom", "bottom_to_top"
])
direction_ken = random.choice([
"left_to_right", "right_to_left",
"top_to_bottom", "bottom_to_top",
"top_left_to_bottom_right", "bottom_right_to_top_left"
])
if change_times is not None and len(change_times) > 0 and i <= next_change_frame:
prev_frame_change = change_frames[change_index - 1] if change_index > 0 else 0
frame_in_image = i - prev_frame_change
total_frames_for_image = next_change_frame - prev_frame_change
else:
frame_in_image = i % frames_per_image
total_frames_for_image = frames_per_image
progress = frame_in_image / total_frames_for_image if total_frames_for_image > 0 else 0
progress = min(max(progress, 0), 1)
img = images[img_index]
# Aplicar efeito sem fade entre transições
if current_effect == "zoom":
frame = zoom_effect(img, progress, zoom_in=zoom_in_random, direction=direction_zoom)
elif current_effect == "move":
frame = move_effect(img, progress, direction=direction_move)
elif current_effect == "ken_burns":
frame = ken_burns_effect(img, progress, zoom_in=zoom_in_random, direction=direction_ken)
else:
frame = img.copy()
frame = cv2.resize(frame, (width, height))
out.write(frame)
if progress_callback:
elapsed = time.time() - start_time
frames_done = i + 1
frames_left = total_frames - frames_done
eta = (elapsed / frames_done) * frames_left if frames_done > 0 else 0
progress_callback(frames_done, total_frames, eta)
out.release()
def merge_audio_with_video(video_path, audio_path, output_path):
fundo_path = AUDIO_FUNDO
audio1 = AudioSegment.from_file(audio_path).set_channels(2)
audio2 = AudioSegment.from_file(fundo_path).set_channels(2)
audio2 = audio2 - 1
if len(audio2) < len(audio1):
audio2 = audio2 * (len(audio1) // len(audio2) + 1)
audio2 = audio2[:len(audio1)]
combined = audio1.overlay(audio2)
temp_audio_path = "combined_temp_audio.mp3"
combined.export(temp_audio_path, format="mp3")
command = [
'ffmpeg',
'-y',
'-i', video_path,
'-i', temp_audio_path,
'-c:v', 'copy',
'-c:a', 'aac',
'-shortest',
output_path
]
subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
os.remove(temp_audio_path)
def create_video_with_audio(audio_path, images_folder, progress_callback=None):
try:
audio = AudioSegment.from_file(audio_path)
except Exception as e:
print(f"[ERRO] Falha ao carregar áudio: {e}")
return
# Remover silêncio do audio antes de prosseguir usando padding para suavizar cortes
silence_threshold = audio.dBFS - 14 # margem adaptável para silêncio
audio_sem_silencio = remover_silencio(audio, silence_thresh=silence_threshold, min_silence_len=400, padding=300)
temp_audio_no_silencio = "temp_audio_no_silencio.mp3"
audio_sem_silencio.export(temp_audio_no_silencio, format="mp3")
duration_seconds = audio_sem_silencio.duration_seconds
audio_name = os.path.splitext(os.path.basename(audio_path))[0]
temp_video_path = f"{audio_name}_temp.mp4"
final_video_path = f"{audio_name}.mp4"
images = load_images_from_folder(images_folder)
if not images:
print("[ERRO] Nenhuma imagem válida encontrada.")
return
try:
# Passa os tempos das batidas detectadas para controle natural de troca
change_times = get_beat_times(temp_audio_no_silencio)
def internal_progress(current_frame, total_frames, eta):
if progress_callback:
percent = int((current_frame / total_frames) * 100)
eta_str = time.strftime("%M:%S", time.gmtime(max(0, eta)))
progress_callback(percent, eta_str)
create_video_only(temp_video_path, duration_seconds, images, fps=30,
progress_callback=internal_progress,
change_times=change_times)
merge_audio_with_video(temp_video_path, temp_audio_no_silencio, final_video_path)
os.remove(temp_video_path)
os.remove(temp_audio_no_silencio)
print(f"[SUCESSO] Vídeo final exportado: {final_video_path}")
except Exception as e:
print(f"[ERRO FATAL] Falha ao criar vídeo: {e}")
#################################
# Classe para monitorar pastas e processar vídeos automaticamente
#################################
class FolderMonitor(threading.Thread):
def __init__(self, callback_video_process, update_status_callback):
super().__init__(daemon=True)
self.callback_video_process = callback_video_process # função para processar video (audio_path,categoria, destino)
self.update_status_callback = update_status_callback # atualiza status no GUI
self.running = False
self.watch_folders = {
PASTA_TRUMP_AUDIOS: {
"category": PASTA_TRUMP_IMAGENS,
"dest": PASTA_TRUMP_DESTINO,
"queue": []
},
PASTA_WARREN_AUDIOS: {
"category": PASTA_WARREN_IMAGENS,
"dest": PASTA_WARREN_DESTINO,
"queue": []
}
}
self.processing_lock = threading.Lock()
def run(self):
self.running = True
self.update_status_callback("Monitoramento ativado.")
while self.running:
self.scan_folders()
self.process_queues()
time.sleep(5) # Tempo de espera entre verificações
self.update_status_callback("Monitoramento desativado.")
def stop(self):
self.running = False
def scan_folders(self):
for folder, info in self.watch_folders.items():
try:
arquivos = [f for f in os.listdir(folder) if f.lower().endswith((".mp3", ".wav"))]
except Exception as e:
self.update_status_callback(f"Erro ao listar {folder}: {e}")
continue
# Detectar arquivos novos para adicionar na fila se não estiverem já na fila
for arquivo in arquivos:
caminho_completo = os.path.join(folder, arquivo)
if caminho_completo not in info["queue"]:
# Verifica se o arquivo está estável
if self.is_file_stable(caminho_completo):
info["queue"].append(caminho_completo)
self.update_status_callback(f"Novo áudio detectado e enfileirado: {arquivo}")
def is_file_stable(self, filepath, wait_time=3):
"""
Verifica se o arquivo mudou de tamanho em 'wait_time' segundos;
se não mudar, consideramos o arquivo estável e pronto para processar.
"""
try:
tamanho1 = os.path.getsize(filepath)
time.sleep(wait_time)
tamanho2 = os.path.getsize(filepath)
return tamanho1 == tamanho2
except Exception as e:
return False
def process_queues(self):
with self.processing_lock:
for folder, info in self.watch_folders.items():
if info["queue"]: # Se tiver algo na fila
audio_path = info["queue"][0] # pegar primeiro da fila
self.update_status_callback(f"Processando áudio: {os.path.basename(audio_path)}")
try:
# Chama função para criar o vídeo, passando categoria e destino correto
self.callback_video_process(audio_path, info["category"], info["dest"])
# Move o vídeo criado para destino
audio_basename = os.path.splitext(os.path.basename(audio_path))[0]
video_gerado = f"{audio_basename}.mp4"
if os.path.exists(video_gerado):
destino_final = os.path.join(info["dest"], video_gerado)
shutil.move(video_gerado, destino_final)
self.update_status_callback(f"Vídeo movido para: {destino_final}")
else:
self.update_status_callback(f"Vídeo não encontrado após criação para: {video_gerado}")
# Depois de processar, remove áudio da fila e apaga audio
info["queue"].pop(0)
if os.path.exists(audio_path):
os.remove(audio_path)
self.update_status_callback(f"Áudio removido: {audio_path}")
except Exception as e:
self.update_status_callback(f"Erro ao processar {audio_path}: {e}")
# Para evitar loop infinito, remover da fila mesmo com erro
info["queue"].pop(0)
# Processa somente 1 por vez, então retorna para aguardar próximo loop e nova verificação
#################################
class VideoEditorFrame(Frame):
COR_FUNDO = "#000000"
COR_TEXTO = "#FFFFFF"
COR_BOTAO = "#00FF00"
COR_BOTAO_HOVER = "#00CC00"
COR_TEXTO_BOTAO = "#FFFFFF"
FONT_TITULO = ("Segoe UI Semibold", 14)
FONT_DEFAULT = ("Segoe UI", 11)
def __init__(self, parent):
super().__init__(parent, bg=self.COR_FUNDO)
self.audio_paths = []
self.monitor = None
self.monitoring_active = False
label_style = {"bg": self.COR_FUNDO, "fg": self.COR_TEXTO, "font": self.FONT_DEFAULT}
btn_style = {"bg": self.COR_BOTAO, "fg": self.COR_TEXTO_BOTAO, "activebackground": self.COR_BOTAO_HOVER,
"font": self.FONT_DEFAULT, "relief": "flat", "borderwidth": 0,
"highlightthickness": 0, "highlightbackground": self.COR_BOTAO,
"padx": 10, "pady": 6}
Label(self, text="Editor Automático com OpenCV", **label_style).pack(pady=(15, 5))
self.btn_select_audio = Button(self, text="Selecionar Áudios", command=self.select_audios, **btn_style)
self.btn_select_audio.pack(pady=6)
Label(self, text="Escolha a Categoria de Imagens:", **label_style).pack(pady=(15, 5))
self.category_combo = Combobox(self, state="readonly", font=self.FONT_DEFAULT)
self.category_combo.pack(pady=6)
style = Style()
style.theme_use('default')
style.configure("TCombobox",
fieldbackground="#101010",
background="#101010",
foreground=self.COR_TEXTO,
arrowcolor=self.COR_TEXTO)
self.btn_start = Button(self, text="Começar Edição", command=self.start_editing, **btn_style)
self.btn_start.pack(pady=15)
self.progress = Progressbar(self, orient='horizontal', length=400, mode='determinate')
self.progress.pack(pady=10)
self.progress_label = Label(self, text="0%", **label_style)
self.progress_label.pack()
self.eta_label = Label(self, text="", **label_style)
self.eta_label.pack()
self.status_label = Label(self, text="", **label_style)
self.status_label.pack(pady=(5, 15))
# BOTÃO para ativar/desativar monitoramento
self.btn_toggle_monitor = Button(
self, text="Ativar Monitoramento", command=self.toggle_monitoring,
bg=self.COR_BOTAO, fg=self.COR_TEXTO_BOTAO,
relief="flat", activebackground=self.COR_BOTAO_HOVER,
activeforeground=self.COR_TEXTO_BOTAO,
font=self.FONT_DEFAULT, padx=10, pady=6
)
self.btn_toggle_monitor.pack(pady=10)
# LABEL para status de monitoramento
self.monitor_status_label = Label(self, text="Monitoramento desativado", bg=self.COR_FUNDO, fg=self.COR_TEXTO, font=self.FONT_DEFAULT)
self.monitor_status_label.pack(pady=(0,10))
self.load_categories()
def load_categories(self):
if not os.path.isdir(PASTA_CATEGORIAS):
messagebox.showerror("Erro", "Pasta de categorias não encontrada!")
return
subpastas = [nome for nome in os.listdir(PASTA_CATEGORIAS)
if os.path.isdir(os.path.join(PASTA_CATEGORIAS, nome))]
if not subpastas:
messagebox.showwarning("Aviso", "Nenhuma subpasta encontrada em categorias.")
return
self.category_combo['values'] = subpastas
self.category_combo.current(0)
def select_audios(self):
files = filedialog.askopenfilenames(filetypes=[("Áudios", "*.mp3 *.wav")])
if files:
self.audio_paths = list(files)
messagebox.showinfo("Sucesso", f"{len(files)} áudio(s) selecionado(s).")
def update_progress(self, percent, eta):
self.progress['value'] = percent
self.progress_label.config(text=f"{percent}%")
self.eta_label.config(text=f"Tempo estimado restante: {eta}")
self.update_idletasks()
def run_editing(self):
selected_category = self.category_combo.get()
if not selected_category:
messagebox.showwarning("Aviso", "Selecione uma categoria de imagens!")
return
if not self.audio_paths:
messagebox.showwarning("Aviso", "Nenhum áudio selecionado!")
return
images_folder = os.path.join(PASTA_CATEGORIAS, selected_category)
self.btn_select_audio.config(state='disabled')
self.btn_start.config(state='disabled')
self.status_label.config(text="Processando vídeos...")
try:
for idx, audio_path in enumerate(self.audio_paths, start=1):
self.status_label.config(text=f"Processando áudio {idx} de {len(self.audio_paths)}: {os.path.basename(audio_path)}")
create_video_with_audio(audio_path, images_folder, progress_callback=self.update_progress)
self.status_label.config(text="Todos os vídeos foram gerados com sucesso!")
messagebox.showinfo("Concluído", "Todos os vídeos foram gerados!")
except Exception as e:
messagebox.showerror("Erro", f"Ocorreu um erro: {e}")
self.status_label.config(text="Erro durante processamento.")
self.progress['value'] = 0
self.progress_label.config(text="0%")
self.eta_label.config(text="")
self.btn_select_audio.config(state='normal')
self.btn_start.config(state='normal')
def start_editing(self):
thread = threading.Thread(target=self.run_editing, daemon=True)
thread.start()
def update_monitor_status(self, status):
# Atualiza label com texto do monitor (executa no main thread)
def update():
self.monitor_status_label.config(text=status)
self.update_idletasks()
self.after(0, update)
def toggle_monitoring(self):
if self.monitoring_active:
# Desliga monitoramento
if self.monitor:
self.monitor.stop()
self.monitor = None
self.monitoring_active = False
self.btn_toggle_monitor.config(text="Ativar Monitoramento")
self.update_monitor_status("Monitoramento desativado")
else:
# Ativa monitoramento
self.monitor = FolderMonitor(
callback_video_process=self.process_audio_for_monitor,
update_status_callback=self.update_monitor_status
)
self.monitor.start()
self.monitoring_active = True
self.btn_toggle_monitor.config(text="Desativar Monitoramento")
self.update_monitor_status("Monitoramento ativado e aguardando arquivos...")
def process_audio_for_monitor(self, audio_path, category_folder, dest_folder):
# Aqui a função que executa a edição do vídeo para o áudio recebido e pastas alvo
try:
# Cria vídeo com áudio, usando category_folder para imagens
# Ajustar create_video_with_audio para aceitar essas pastas como argumento, para isso:
def progress_callback(percent, eta):
self.update_monitor_status(f"Processando '{os.path.basename(audio_path)}': {percent}% ETA {eta}")
images_folder = category_folder
create_video_with_audio(audio_path, images_folder, progress_callback=progress_callback)
except Exception as e:
self.update_monitor_status(f"Erro no processamento do áudio {audio_path}: {e}")
#################################
# Janela principal
#################################
class MainApp:
COR_FUNDO = "#000000"
COR_TEXTO = "#FFFFFF"
def __init__(self, root):
self.root = root
root.title("Sistema Integrado - Criador de Enredo e Vídeo")
root.geometry("1000x700")
root.configure(bg=self.COR_FUNDO)
style = Style()
style.theme_use('default')
style.configure('TNotebook', background=self.COR_FUNDO, borderwidth=0)
style.configure('TNotebook.Tab', background="#003300", foreground=self.COR_TEXTO, font=("Segoe UI Semibold", 11))
style.map('TNotebook.Tab', background=[('selected', '#00FF00')], foreground=[('selected', '#000000')])
notebook = Notebook(root)
notebook.pack(expand=True, fill='both')
self.criador_enredo_frame = CriadorEnredoFrame(notebook)
self.video_editor_frame = VideoEditorFrame(notebook)
notebook.add(self.criador_enredo_frame, text="Criador de Enredo")
notebook.add(self.video_editor_frame, text="Criador de Vídeo")
def main():
root = Tk()
app = MainApp(root)
root.mainloop()
if __name__ == "__main__":
main()