import os
import cv2
import random
import threading
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import numpy as np
from pydub import AudioSegment
from pydub.silence import detect_nonsilent
import whisper
import subprocess
import textwrap
import time
IMAGES_FOLDER = r"D:\CANAIS REDE\Deep Psychology"
PASTA DE ENTRADA DE AUDIOS PARA PROCESSAR (novo)
AUDIO_INPUT_FOLDER = r"D:\CANAIS REDE\CENTRAL AUDIO"
PASTA DE SAÍDA ALTERADA PARA O PEDIDO
OUTPUT_FOLDER = r"D:\CANAIS REDE\videos para postar"
AUDIO_BACKGROUND = r"D:\CANAIS REDE\soundfund.mp3"
FONT_FACE = cv2.FONT_HERSHEY_SIMPLEX
(Todas as funções anteriores permanecem iguais, não copio para não poluir)
... suas funções anteriores permanecem iguais ...
def zoom_effect_center(image, progress, zoom_in=True):
return image
def load_images_from_folder(folder):
images = []
for filename in sorted(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 remover_silencio(audio_segment, silence_thresh=-50, min_silence_len=500, padding=300):
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:
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:]:
audio_sem_silencio += AudioSegment.silent(duration=150) + part
return audio_sem_silencio
def add_centered_subtitle(frame, text):
h, w = frame.shape[:2]
font_scale = 1.1
thickness = 3
color = (255, 255, 255)
font = FONT_FACE
text_size, _ = cv2.getTextSize(text, font, font_scale, thickness)
text_w, text_h = text_size
org = ((w - text_w) // 2, (h + text_h) // 2)
cv2.putText(frame, text, org, font, font_scale, (0, 0, 0), thickness + 2, cv2.LINE_AA)
cv2.putText(frame, text, org, font, font_scale, color, thickness, cv2.LINE_AA)
return frame
def split_text_to_lines(text, max_chars=40):
lines = textwrap.wrap(text, width=max_chars, break_long_words=False)
return lines
def create_video_only(video_path, duration, images, fps=30, progress_callback=None, segments=None):
if not images:
raise ValueError("Nenhuma imagem encontrada para criação do vídeo")
height, width, _ = images[0].shape
total_frames = int(duration * fps)
out = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))
current_shift = 0.0
direction = random.choice([-1, 1])
speed = 0.4
max_shift = int(width * 0.03)
movement_state = "moving"
movement_frames_count = 0
movement_frames_duration = random.randint(fps * 5, fps * 10)
pause_frames_duration = random.randint(fps * 3, fps * 5)
current_subtitle = ""
segment_index = 0
current_image_index = 0
subtitle_visible = False
subtitle_timer = 0
subtitle_visible_duration = 0
subtitle_invisible_duration = 0
current_line_index = 0
current_lines = []
for i in range(total_frames):
time_sec = i / fps
if segments and segment_index < len(segments):
segment = segments[segment_index]
if time_sec >= segment['start'] and time_sec <= segment['end']:
if segment['text'].strip() != current_subtitle:
current_subtitle = segment['text'].strip()
current_image_index = min(segment_index, len(images) - 1)
current_lines = split_text_to_lines(current_subtitle, max_chars=40)
current_line_index = 0
subtitle_visible = True
subtitle_timer = 0
subtitle_visible_duration = random.uniform(3, 6)
subtitle_invisible_duration = random.uniform(10, 25)
if subtitle_visible and subtitle_timer >= subtitle_visible_duration * fps:
subtitle_visible = False
subtitle_timer = 0
elif (not subtitle_visible) and subtitle_timer >= subtitle_invisible_duration * fps:
subtitle_visible = True
subtitle_timer = 0
subtitle_visible_duration = random.uniform(3,6)
subtitle_invisible_duration = random.uniform(10, 25)
subtitle_timer += 1
elif time_sec > segment['end']:
current_subtitle = ""
segment_index += 1
subtitle_visible = False
subtitle_timer = 0
current_lines = []
current_line_index = 0
else:
current_subtitle = ""
subtitle_visible = False
current_lines = []
current_line_index = 0
if subtitle_visible and current_lines:
if i % int(fps * 2) == 0 and current_line_index < len(current_lines) -1:
current_line_index += 1
img = images[current_image_index].copy()
if movement_state == "moving":
current_shift += direction * speed
movement_frames_count += 1
if current_shift > max_shift:
current_shift = max_shift
direction = -1
elif current_shift < -max_shift:
current_shift = -max_shift
direction = 1
if movement_frames_count >= movement_frames_duration:
movement_state = "paused"
movement_frames_count = 0
else:
movement_frames_count += 1
if movement_frames_count >= pause_frames_duration:
movement_state = "moving"
movement_frames_count = 0
movement_frames_duration = random.randint(fps * 5, fps * 10)
pause_frames_duration = random.randint(fps * 3, fps * 5)
M = np.float32([[1, 0, current_shift], [0, 1, 0]])
img = cv2.warpAffine(img, M, (width, height))
if subtitle_visible and current_lines:
img = add_centered_subtitle(img, current_lines[current_line_index])
out.write(img)
if progress_callback:
progress_callback(i + 1, total_frames)
out.release()
def merge_audio_with_video(video_path, audio_path, output_path, audio_background_path=None):
audio1 = AudioSegment.from_file(audio_path).set_channels(2)
if audio_background_path and os.path.exists(audio_background_path):
audio2 = AudioSegment.from_file(audio_background_path).set_channels(2)
audio2 = audio2 - 15
if len(audio2) < len(audio1):
audio2 = audio2 * (len(audio1) // len(audio2) + 1)
audio2 = audio2[:len(audio1)]
combined = audio1.overlay(audio2)
else:
combined = audio1
temp_audio_path = "temp_combined_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 criar_video_com_interface():
root = tk.Tk()
root.title("Criador de Vídeo com imagens e áudio")
root.geometry("550x220")
tk.Label(root, text=f"Pasta de imagens: {IMAGES_FOLDER}").pack(pady=5)
tk.Label(root, text=f"Pasta de entrada Áudios: {AUDIO_INPUT_FOLDER}").pack(pady=5)
tk.Label(root, text=f"Pasta de saída Vídeos: {OUTPUT_FOLDER}").pack(pady=5)
progress_var = tk.IntVar()
progress_bar = ttk.Progressbar(root, maximum=100, variable=progress_var, length=500)
progress_bar.pack(pady=5)
progress_label = tk.Label(root, text="Aguardando arquivos na fila...")
progress_label.pack(pady=5)
# ------------------ FILA DE ARQUIVOS A PROCESSAR -----------------
processing_lock = threading.Lock()
queue_audios = []
processing = False # flag se está processando algum arquivo
images = load_images_from_folder(IMAGES_FOLDER)
if not images:
messagebox.showerror("Erro", f"Nenhuma imagem válida encontrada em:\n{IMAGES_FOLDER}")
root.destroy()
return
def update_progress_ui(atual, total):
pct = int(atual / total * 100)
progress_var.set(pct)
progress_label.config(text=f"Progresso: {pct}%")
root.update_idletasks()
def process_audio_file(audio_path):
nonlocal processing
try:
progress_var.set(0)
progress_label.config(text=f"Processando: {os.path.basename(audio_path)}")
root.update_idletasks()
audio = AudioSegment.from_file(audio_path)
silence_thresh = audio.dBFS - 14
audio_sem_silencio = remover_silencio(audio, silence_thresh=silence_thresh, min_silence_len=400, padding=300)
temp_audio_clean = "temp_audio_clean.mp3"
audio_sem_silencio.export(temp_audio_clean, format="mp3")
duration = audio_sem_silencio.duration_seconds
base_name = os.path.splitext(os.path.basename(audio_path))[0]
temp_video = base_name + "_temp.mp4"
video_final = os.path.join(OUTPUT_FOLDER, f"{base_name}.mp4")
model = whisper.load_model("small")
result = model.transcribe(temp_audio_clean)
segments = result.get('segments', [])
create_video_only(temp_video, duration, images, fps=30, progress_callback=update_progress_ui,
segments=segments)
merge_audio_with_video(temp_video, temp_audio_clean, video_final, audio_background_path=AUDIO_BACKGROUND)
# Limpeza dos arquivos temporários e áudio processado
os.remove(temp_video)
os.remove(temp_audio_clean)
try:
os.remove(audio_path)
except Exception as e:
print(f"Erro ao remover arquivo de áudio original: {e}")
messagebox.showinfo("Concluído", f"Vídeo criado: {video_final}")
except Exception as e:
messagebox.showerror("Erro", f"Falha ao criar vídeo para {audio_path}:\n{str(e)}")
finally:
with processing_lock:
processing = False
# Após terminar, tenta processar próximo da fila
root.after(100, check_and_start_process)
def check_and_start_process():
nonlocal processing
with processing_lock:
if processing or not queue_audios:
if not queue_audios:
progress_label.config(text="Fila vazia, aguardando novos arquivos...")
return
next_audio = queue_audios.pop(0)
processing = True
threading.Thread(target=process_audio_file, args=(next_audio,), daemon=True).start()
def scan_for_new_audios():
# Escaneia pasta para buscar arquivos não processados e adiciona à fila
current_files = [f for f in os.listdir(AUDIO_INPUT_FOLDER) if f.lower().endswith((".mp3", ".wav", ".m4a"))]
abs_files = [os.path.join(AUDIO_INPUT_FOLDER, f) for f in current_files]
with processing_lock:
# Evita duplicar na fila ou se já processando
fila_set = set(queue_audios)
todos_na_fila_ou_processando = fila_set.copy()
# Se estiver processando um, vamos assumir que ele não está aqui na fila (porque removemos no start)
# Então vamos assumir só fila.
for fpath in abs_files:
if (fpath not in queue_audios) and (not processing or fpath != currently_processing_file()):
if fpath not in queue_audios:
queue_audios.append(fpath)
def currently_processing_file():
# Aqui se preciso, poderia armazenar o arquivo que está sendo processado
# Para este script simples, vamos retornar None
# Para implementar devidamente, criar variável global para arquivo atual
# Como não temos essa variável, retorno None
return None
def periodic_scan():
try:
scan_for_new_audios()
check_and_start_process()
except Exception as e:
print(f"Erro no scan ou start do processo: {e}")
# Agenda executar daqui 5 segundos novamente
root.after(5000, periodic_scan)
# Start scan automático ao iniciar
periodic_scan()
root.mainloop()
if name == "main":
criar_video_com_interface() . chat as imagens que vão ser usadas precisam ser escolhidas de maneira aleatoria escolha de maneira aleatorias imagens . quando terminar de editar já comece o outro não apareça com mensagem que foi concluido nem quando terminar tudo . quero que faça o seguinte quero que quando for criar um video crie seguindo essa ordem quando for começa a edição de um video escolha para qual canal vai ser caso for para . Deep Psychology ( D:\CANAIS REDE\videos para postar\Deep Psychology ) Doodle Vibes (D:\CANAIS REDE\videos para postar\Doodle Vibes) One Infinite ( D:\CANAIS REDE\videos para postar\One Infinite ) One Realm ( D:\CANAIS REDE\videos para postar\One Realm ) Sequels ( D:\CANAIS REDE\videos para postar\Sequels ) esses endereços são referentes a cada um dos canais ( da parte de final da exportação) e esses agora são das imagens que vão ser usadas para edição . ao invés da (D:\CANAIS REDE\Deep Psychology) ser a padrão será de acordo com aque for escolhida qual criterio você vai escolher para qual mandar o criterio de menor para maior ( numero de videos na pasta de exportação daquele canal) caso todas estejam vazias comece de forma aleatoria depois vai colocando nas vazias até todos terem o mesmo valor depois para o 2 mande aleatorio de novo e assim vai até todos terem 2 resumindo crie um equilibrio entre os canais . depois que saber para qual pasta será o video que vai fazer escolha a pasta de imagens que vai usar ( lembrando que as imagens precisam ser as da pasta refente ao canal entretanto na edição entre as imagens da pasta são escolhidas de forma aleatoria na edição na hora de criar o video . pastas das imagens refentes os canais para edição . Deep Psychology (D:\CANAIS REDE\Deep Psychology) Doodle Vibes (D:\CANAIS REDE\Doodle Vibes) One Infinite (D:\CANAIS REDE\One Infinite) One Realm (D:\CANAIS REDE\One Realm) Sequels (D:\CANAIS REDE\Sequels) . apenas um exemplo caso escolha a pasta one realm vai usar a pasta de edição para pegar a imagens da One Realm (D:\CANAIS REDE\One Realm) e vai exportar para One Realm ( D:\CANAIS REDE\videos para postar\One Realm )