import os
import time
import threading
import random
import subprocess
import pickle
import sqlite3
import math
import queue
from datetime import datetime, timedelta, timezone
import cv2
import numpy as np
from pydub import AudioSegment
from pydub.silence import detect_nonsilent
import pytz
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
-------------- CONFIGURAÇÕES --------------
DB_PATH = r"C:\Users\jonathan\Desktop\FINANCE CHANEEL\monitorador_juntador.db"
PASTA_AUDIO_CENTRAL = r"C:\Users\jonathan\Desktop\AUTLAND\CANAIS REDE\CENTRAL AUDIO"
CANAL_BASE_PATH = r"C:\Users\jonathan\Desktop\AUTLAND\CANAIS REDE"
PASTA_VIDEOS_POSTAGEM = r"C:\Users\jonathan\Desktop\AUTLAND\POSTAGEM"
PASTA_THUMBNAILS = r"C:\Users\jonathan\Desktop\AUTLAND\THUMBNAILS\TUMB CARL"
PASTA_PARA_APAGAR = r"C:\Users\jonathan\Desktop\AUTLAND\Para apagar"
AUDIO_FUNDO = r"C:\Users\jonathan\Desktop\AUTLAND\TRILHA SONORA\soundfund.mp3"
VIDEO_FPS = 30
TZ_SP = pytz.timezone("America/Sao_Paulo")
CANAL_PERFIS = {
"Deep Psychology": {
"image_path": os.path.join(CANAL_BASE_PATH, "Deep Psychology"),
"credentials_pickle": os.path.join(CANAL_BASE_PATH, "CREDENCIAL", "Deep.pickle"),
"channel_name": "Deep Psychology"
},
"Doodle Vibes": {
"image_path": os.path.join(CANAL_BASE_PATH, "Doodle Vibes"),
"credentials_pickle": os.path.join(CANAL_BASE_PATH, "CREDENCIAL", "Doodle.pickle"),
"channel_name": "Doodle Vibes"
},
"One Infinite": {
"image_path": os.path.join(CANAL_BASE_PATH, "One Infinite"),
"credentials_pickle": os.path.join(CANAL_BASE_PATH, "CREDENCIAL", "OneInfinite.pickle"),
"channel_name": "One Infinite"
},
"One Realm": {
"image_path": os.path.join(CANAL_BASE_PATH, "One Realm"),
"credentials_pickle": os.path.join(CANAL_BASE_PATH, "CREDENCIAL", "OneRealm.pickle"),
"channel_name": "One Realm"
},
"Sequels": {
"image_path": os.path.join(CANAL_BASE_PATH, "Sequels"),
"credentials_pickle": os.path.join(CANAL_BASE_PATH, "CREDENCIAL", "Sequels.pickle"),
"channel_name": "Sequels"
}
}
DEFAULT_DESCRIPTION = """Neste vídeo, insights sobre o canal {channel}. Não perca!
#finance #education #insights"""
DEFAULT_TAGS = ["finance", "education", "insights"]
EXT_AUDIO = (".mp3", ".wav", ".m4a", ".flac")
EXT_THUMBNAILS = (".jpg", ".jpeg", ".png")
---------- VARIÁVEIS GLOBAIS ----------
lock_editing = threading.Lock()
stop_flag = threading.Event()
LOG_QUEUE = queue.Queue()
PROCESS_THREADS = []
-------- FUNÇÕES DE LOG --------
def log(message):
timestamp = datetime.now(TZ_SP).strftime("%Y-%m-%d %H:%M:%S")
full_message = f"[{timestamp}] {message}"
LOG_QUEUE.put(full_message)
-------- BANCO DE DADOS --------
def init_db():
if os.path.exists(DB_PATH):
os.remove(DB_PATH)
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute('''
CREATE TABLE perfis (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nome TEXT UNIQUE,
canal TEXT UNIQUE,
credentials BLOB
)
''')
c.execute('''
CREATE TABLE videos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT UNIQUE,
title TEXT,
canal TEXT,
schedule_time TEXT,
uploaded INTEGER DEFAULT 0
)
''')
c.execute('''
CREATE TABLE agendamentos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
canal TEXT,
horario TEXT UNIQUE,
video_filename TEXT UNIQUE
)
''')
conn.commit()
for perfil, info in CANAL_PERFIS.items():
cred_blob = None
try:
with open(info["credentials_pickle"], "rb") as f:
cred_blob = f.read()
except Exception as e:
log(f"Erro ao carregar credencial {perfil}: {e}")
c.execute("INSERT INTO perfis (nome, canal, credentials) VALUES (?, ?, ?)",
(perfil, info["channel_name"], cred_blob))
conn.commit()
conn.close()
log("Banco de dados inicializado com perfis carregados.")
---- Funções de banco básicas ----
def executar_query(sql, params=()):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute(sql, params)
conn.commit()
conn.close()
def executar_query_fetch(sql, params=()):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute(sql, params)
res = c.fetchall()
conn.close()
return res
def check_horario_livre(canal, horario_iso):
res = executar_query_fetch("SELECT COUNT(*) FROM agendamentos WHERE canal=? AND horario=?", (canal, horario_iso))
if res[0][0] > 0:
return False
res2 = executar_query_fetch("SELECT COUNT(DISTINCT canal) FROM agendamentos WHERE horario=?", (horario_iso,))
if res2[0][0] >= 5:
return False
return True
def agendar_video(canal, horario_iso, filename):
executar_query("INSERT INTO agendamentos (canal, horario, video_filename) VALUES (?, ?, ?)",
(canal, horario_iso, filename))
def set_video_enviado(filename, titulo, canal, horario):
executar_query('''
INSERT OR REPLACE INTO videos (filename, title, canal, schedule_time, uploaded)
VALUES (?, ?, ?, ?, 1)
''', (filename, titulo, canal, horario))
def get_proximo_horario_disponivel(canal):
agora = datetime.now(TZ_SP).replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)
limite = agora + timedelta(days=30)
atual = agora
while atual <= limite:
iso = atual.isoformat()
if check_horario_livre(canal, iso):
return atual
atual += timedelta(hours=1)
raise Exception("Sem horário disponível para canal: " + canal)
def get_cred_perfil(nome):
res = executar_query_fetch("SELECT credentials FROM perfis WHERE nome=?", (nome,))
if res:
return res[0][0]
return None
----------- ÁUDIO E IMAGEM -----------
def remover_silencio(audio_seg, thresh=-50, min_len=500, padding=300):
parts = detect_nonsilent(audio_seg, min_silence_len=min_len, silence_thresh=thresh)
if not parts:
return audio_seg
final = AudioSegment.empty()
for start, end in parts:
startp = max(start-padding, 0)
endp = min(end+padding, len(audio_seg))
final += audio_seg[startp:endp]
return final
def get_beat_times(audio_file):
audio = AudioSegment.from_file(audio_file).set_channels(1)
frame_ms = 50
n_frames = len(audio) // frame_ms
energies = []
for i in range(n_frames):
frame = audio[i*frame_ms:(i+1)frame_ms]
energies.append(frame.rms)
energies = np.array(energies)
avg_energy = np.mean(energies)
beats = []
for i in range(1, len(energies)-1):
if energies[i] > 1.3 * avg_energy and energies[i] > energies[i-1] and energies[i] > energies[i+1]:
beats.append(i)
times = [i0.05 for i in beats]
filtered = []
for t in times:
if not filtered or t - filtered[-1] > 1.0:
filtered.append(t)
return filtered
def carregar_imagens_canal(canal):
if canal not in CANAL_PERFIS:
raise Exception(f"Canal {canal} não encontrado")
pasta = CANAL_PERFIS[canal]['image_path']
imagens = []
for f in os.listdir(pasta):
if f.lower().endswith(('.png', '.jpg', '.jpeg')):
caminho = os.path.join(pasta, f)
img = cv2.imread(caminho)
if img is not None and img.shape[0]>0 and img.shape[1]>0:
imagens.append(img)
if not imagens:
raise Exception(f"Nenhuma imagem válida no canal {canal}")
random.shuffle(imagens)
return imagens
--------- MOVIMENTO ZOOM E TRANSLACAO ----------
def movimento_zoom_translacao(frame_idx, total_frames, max_trans=40, max_zoom=0.15, ciclo=240):
prog = frame_idx % ciclo
ang = (prog / ciclo) * 2 * math.pi
offset_x = int(max_trans * math.cos(ang))
offset_y = int(max_trans * math.sin(ang))
zoom_fase = (prog + ciclo/4) % ciclo
zoom_sen = math.sin((zoom_fase / ciclo) * 2 * math.pi)
zoom_factor = 1 + max_zoom * zoom_sen
zoom_factor = max(1 - max_zoom, min(1 + max_zoom, zoom_factor))
return offset_x, offset_y, zoom_factor
def aplicar_zoom(frame, zoom, offset_x, offset_y):
h, w = frame.shape[:2]
nw = int(w/zoom)
nh = int(h/zoom)
cx = w//2 - offset_x
cy = h//2 - offset_y
x1 = max(0, min(w-nw, cx - nw//2))
y1 = max(0, min(h-nh, cy - nh//2))
x2 = x1 + nw
y2 = y1 + nh
rec = frame[y1:y2, x1:x2]
if rec.shape[0]<=0 or rec.shape[1]<=0:
return frame
resized = cv2.resize(rec, (w,h))
return resized
----------- CRIAR VÍDEO ----------
def criar_video(path_video, duracao, imagens, fps=VIDEO_FPS, progresso_cb=None, change_times=None):
if not imagens:
raise Exception("Lista de imagens vazia")
h, w, _ = imagens[0].shape
total_frames = int(duracaofps)
out = cv2.VideoWriter(path_video, cv2.VideoWriter_fourcc("mp4v"), fps, (w,h))
idx_img = 0
def rand_intv():
return int(random.uniform(2.5, 4.0)fps)
if not change_times:
frames_img = rand_intv()
prox_cambio = frames_img
else:
trocas = [int(tfps) for t in change_times if t*fps < total_frames]
if trocas[-1] < total_frames-1:
trocas.append(total_frames-1)
i_troca = 0
prox_cambio = trocas[i_troca]
t_start = time.time()
for i in range(total_frames):
if not change_times:
if i >= prox_cambio:
idx_img = (idx_img+1) % len(imagens)
frames_img = rand_intv()
prox_cambio = i + frames_img
else:
if i >= prox_cambio:
idx_img = (idx_img+1) % len(imagens)
i_troca += 1
prox_cambio = trocas[i_troca] if i_troca < len(trocas) else total_frames+5
img = imagens[idx_img]
off_x, off_y, zoom_f = movimento_zoom_translacao(i, total_frames)
frame_final = aplicar_zoom(img, zoom_f, off_x, off_y)
frame_final = cv2.resize(frame_final, (w,h))
out.write(frame_final)
if progresso_cb:
frames_done = i+1
frames_left = total_frames - frames_done
tempo_passado = time.time() - t_start
eta = (tempo_passado / frames_done) * frames_left if frames_done > 0 else 0
pct = int((frames_done / total_frames) * 100)
eta_str = time.strftime("%M:%S", time.gmtime(max(0, eta)))
progresso_cb(pct, eta_str)
out.release()
------------ MESCLAR ÁUDIO E VÍDEO -------------
def mesclar_audio_video(video_path, audio_path, output_path):
audio1 = AudioSegment.from_file(audio_path).set_channels(2)
audio2 = AudioSegment.from_file(AUDIO_FUNDO).set_channels(2)
audio2 = audio2 - 1
if len(audio2) < len(audio1):
r = (len(audio1) // len(audio2)) + 1
audio2 = audio2 * r
audio2 = audio2[:len(audio1)]
combinado = audio1.overlay(audio2)
temp_audio = "temp_audio_mix.mp3"
combinado.export(temp_audio, format="mp3")
cmd = [
"ffmpeg","-y","-i",video_path,"-i",temp_audio,
"-c:v","copy","-c:a","aac","-shortest",output_path]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if os.path.exists(temp_audio):
os.remove(temp_audio)
--------- CRIAR VÍDEO COMPLETO (áudio + imagens) ---------
def criar_video_com_audio(audio_path, canal, progresso_cb=None):
try:
audio = AudioSegment.from_file(audio_path)
except Exception as e:
log(f"Erro carregando audio: {e}")
if progresso_cb:
progresso_cb(0,"Erro audio")
return None
seuil = audio.dBFS - 14
audio_sem = remover_silencio(audio, thresh=seuil)
tmp_audio = f"temp_audio_{random.randint(1000,9999)}.mp3"
audio_sem.export(tmp_audio, format="mp3")
dur = audio_sem.duration_seconds
temp_video = f"temp_video_{random.randint(10000,99999)}.mp4"
nome_out = f"{canal}{datetime.now(TZ_SP).strftime('%Y%m%d%H%M%S')}.mp4"
out_path = os.path.join(PASTA_VIDEOS_POSTAGEM, nome_out)
imgs = carregar_imagens_canal(canal)
try:
change_times = get_beat_times(tmp_audio)
except Exception:
change_times = None
def interno_cb(pct, eta):
if progresso_cb:
progresso_cb(pct, eta)
try:
criar_video(temp_video, dur, imgs, fps=VIDEO_FPS, progresso_cb=interno_cb, change_times=change_times)
mesclar_audio_video(temp_video, tmp_audio, out_path)
if os.path.exists(temp_video):
os.remove(temp_video)
if os.path.exists(tmp_audio):
os.remove(tmp_audio)
except Exception as e:
log(f"Erro criando vídeo completo: {e}")
if progresso_cb:
progresso_cb(0,"Erro video")
return None
log(f"Vídeo criado em {out_path}")
return out_path
-------- UPLOAD ---------
def carregar_cred_blob(blob):
tmp = "tmp_cred.pickle"
with open(tmp, "wb") as f:
f.write(blob)
try:
with open(tmp,"rb") as f:
c = pickle.load(f)
os.remove(tmp)
except:
if os.path.exists(tmp):
os.remove(tmp)
raise
return c
def upload_youtube(cred_blob, titulo, desc, tags, video_path, thumb_path, publicar_ja=False,
publicar_em=None, categoria="22"):
creds = carregar_cred_blob(cred_blob)
youtube = build("youtube", "v3", credentials=creds)
if not os.path.exists(video_path):
raise FileNotFoundError("Vídeo não encontrado")
privacy = "public" if publicar_ja else "private"
publishAt = None
if not publicar_ja:
if not publicar_em:
raise Exception("Horário de publicação obrigatório para agendamento")
dt_local = datetime.fromisoformat(publicar_em)
now_local = datetime.now(dt_local.tzinfo)
if dt_local <= now_local:
raise Exception("Horário deve ser no futuro")
publishAt = dt_local.astimezone(timezone.utc).isoformat()
corpo = {
"snippet": {
"title": titulo,
"description": desc,
"tags": tags,
"categoryId": categoria,
},
"status": {
"privacyStatus": privacy,
"publishAt": publishAt
}
}
media = MediaFileUpload(video_path, mimetype="video/mp4", resumable=True, chunksize=1010241024)
req = youtube.videos().insert(part="snippet,status", body=corpo, media_body=media)
resposta = None
while resposta is None:
status, resposta = req.next_chunk()
if status:
log(f"Upload {int(status.progress()*100)}%")
if thumb_path and os.path.exists(thumb_path):
youtube.thumbnails().set(videoId=resposta["id"], media_body=MediaFileUpload(thumb_path)).execute()
log(f"Upload finalizado, Video ID: {resposta['id']}")
return resposta["id"]
def mover_arquivos(video_path, thumb_path):
try:
vp_abs = os.path.realpath(video_path)
pv_abs = os.path.realpath(PASTA_VIDEOS_POSTAGEM)
ppa_abs = os.path.realpath(PASTA_PARA_APAGAR)
if os.path.exists(vp_abs) and vp_abs.startswith(pv_abs):
nome = os.path.basename(vp_abs)
destino = os.path.join(ppa_abs, nome)
base, ext = os.path.splitext(nome)
c = 1
while os.path.exists(destino):
destino = os.path.join(ppa_abs, f"{base}_{c}{ext}")
c+=1
os.rename(vp_abs, destino)
log(f"Vídeo movido para apagar: {destino}")
except Exception as e:
log(f"Erro movendo vídeo: {e}")
try:
if thumb_path and os.path.exists(thumb_path):
thumb_abs = os.path.realpath(thumb_path)
pt_abs = os.path.realpath(PASTA_THUMBNAILS)
if thumb_abs.startswith(pt_abs):
os.remove(thumb_abs)
log(f"Thumbnail removida: {thumb_abs}")
except Exception as e:
log(f"Erro removendo thumbnail: {e}")
def escolher_thumbnail():
thumbs = [f for f in os.listdir(PASTA_THUMBNAILS) if f.lower().endswith(EXT_THUMBNAILS)]
if not thumbs:
return None
return os.path.join(PASTA_THUMBNAILS, random.choice(thumbs))
-------- FLUXO COMPLETO --------
def processar_audio_canal(audio_path, canal_nome):
log(f"Processando áudio {audio_path} para canal {canal_nome}")
def cb(pct, eta):
log(f"{canal_nome}: {pct}% restante {eta}")
video_path = criar_video_com_audio(audio_path, canal_nome, cb)
if not video_path:
log(f"Falha criando vídeo para {canal_nome}")
return False
nome_base = os.path.splitext(os.path.basename(video_path))[0]
titulo = nome_base
cred_blob = get_cred_perfil(canal_nome)
canal_real = CANAL_PERFIS[canal_nome]["channel_name"]
if not cred_blob:
log("Credenciais não encontradas para canal " + canal_nome)
return False
try:
horario_pub = get_proximo_horario_disponivel(canal_nome)
except Exception as e:
log("Sem horário disponível canal {}: {}".format(canal_nome, e))
return False
thumb_path = escolher_thumbnail()
desc = DEFAULT_DESCRIPTION.format(channel=canal_nome)
tags = DEFAULT_TAGS.copy()
try:
video_id = upload_youtube(cred_blob, titulo, desc, tags, video_path, thumb_path,
publicar_ja=False, publicar_em=horario_pub.isoformat())
except Exception as e:
log(f"Upload falhou para canal {canal_nome}: {e}")
return False
agendar_video(canal_real, horario_pub.isoformat(), nome_base)
set_video_enviado(nome_base, titulo, canal_real, horario_pub.isoformat())
mover_arquivos(video_path, thumb_path)
try:
if os.path.exists(audio_path):
os.remove(audio_path)
log(f"Áudio removido: {audio_path}")
except Exception as e:
log(f"Não foi possível remover áudio: {e}")
log(f"Processamento completo para {canal_nome}")
return True
--------------- MONITORAMENTO THREAD -----------------
def monitorar_audio():
while not stop_flag.is_set():
try:
audios = [f for f in os.listdir(PASTA_AUDIO_CENTRAL) if f.lower().endswith(EXT_AUDIO)]
if not audios:
time.sleep(5)
continue
for audio_file in audios:
audio_path = os.path.join(PASTA_AUDIO_CENTRAL, audio_file)
candidatos = []
for canal_nome in CANAL_PERFIS.keys():
try:
prox_horario = get_proximo_horario_disponivel(canal_nome)
candidatos.append((canal_nome, prox_horario))
except Exception:
pass
if not candidatos:
log("Todos os horários estão ocupados. Aguardando.")
time.sleep(15)
continue
candidatos.sort(key=lambda x: x[1])
canal_escolhido = candidatos[0][0]
if lock_editing.acquire(blocking=False):
log(f"Iniciando thread para {canal_escolhido} com áudio {audio_file}")
t = threading.Thread(target=processar_audio_canal, args=(audio_path, canal_escolhido))
t.daemon = True
t.start()
PROCESS_THREADS.append(t)
lock_editing.release()
time.sleep(1)
else:
log("Edição ocupada, aguardando para tentar novamente...")
time.sleep(3)
break
time.sleep(3)
except Exception as e:
log(f"Erro no monitoramento: {e}")
time.sleep(10)
--------------- INTERFACE Tkinter -----------------
class App(tk.Tk):
def init(self):
super().init()
self.title("Carl Jung Automation")
self.geometry("900x600")
self.monitor_thread = None
# Widgets
frm_top = ttk.Frame(self)
frm_top.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
self.btn_start = ttk.Button(frm_top, text="Iniciar Monitoramento", command=self.iniciar_monitoramento)
self.btn_start.pack(side=tk.LEFT, padx=5)
self.btn_stop = ttk.Button(frm_top, text="Parar Monitoramento", command=self.parar_monitoramento, state=tk.DISABLED)
self.btn_stop.pack(side=tk.LEFT, padx=5)
self.btn_status = ttk.Button(frm_top, text="Mostrar Estado Atual", command=self.mostrar_estado)
self.btn_status.pack(side=tk.LEFT, padx=5)
self.btn_estatisticas = ttk.Button(frm_top, text="Mostrar Estatísticas", command=self.mostrar_estatisticas)
self.btn_estatisticas.pack(side=tk.LEFT, padx=5)
self.btn_limpar = ttk.Button(frm_top, text="Limpar Log", command=self.limpar_log)
self.btn_limpar.pack(side=tk.RIGHT, padx=5)
self.txt_logs = scrolledtext.ScrolledText(self, state='disabled', height=30)
self.txt_logs.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
self.after(1000, self.atualizar_logs)
init_db()
def iniciar_monitoramento(self):
if self.monitor_thread and self.monitor_thread.is_alive():
messagebox.showinfo("Info", "Monitoramento já está ativo.")
return
stop_flag.clear()
self.monitor_thread = threading.Thread(target=monitorar_audio)
self.monitor_thread.daemon = True
self.monitor_thread.start()
self.btn_start.config(state=tk.DISABLED)
self.btn_stop.config(state=tk.NORMAL)
self.adicionar_log("Monitoramento iniciado.")
def parar_monitoramento(self):
stop_flag.set()
self.btn_start.config(state=tk.NORMAL)
self.btn_stop.config(state=tk.DISABLED)
self.adicionar_log("Monitoramento parado.")
def mostrar_estado(self):
info = f"Monitoramento ativo? {'Sim' if self.monitor_thread and self.monitor_thread.is_alive() else 'Não'}\n"
vivos = sum(1 for t in PROCESS_THREADS if t.is_alive())
info += f"Threads de processamento ativos: {vivos}\n"
ags = executar_query_fetch("SELECT canal, horario FROM agendamentos ORDER BY horario DESC LIMIT 5")
info += "Últimos agendamentos:\n"
for canal,hora in ags:
info += f" Canal: {canal} - Horário: {hora}\n"
messagebox.showinfo("Estado Atual", info)
def mostrar_estatisticas(self):
audios = len([f for f in os.listdir(PASTA_AUDIO_CENTRAL) if f.lower().endswith(EXT_AUDIO)])
videos = len([f for f in os.listdir(PASTA_VIDEOS_POSTAGEM) if f.lower().endswith(".mp4")])
thumbs = len([f for f in os.listdir(PASTA_THUMBNAILS) if f.lower().endswith(EXT_THUMBNAILS)])
info = f"Áudios pendentes: {audios}\nVídeos na pasta postagem: {videos}\nThumbnails disponíveis: {thumbs}"
messagebox.showinfo("Estatísticas", info)
def limpar_log(self):
self.txt_logs.config(state='normal')
self.txt_logs.delete(1.0, tk.END)
self.txt_logs.config(state='disabled')
def adicionar_log(self, mensagem):
self.txt_logs.config(state='normal')
self.txt_logs.insert(tk.END, mensagem + "\n")
self.txt_logs.see(tk.END)
self.txt_logs.config(state='disabled')
def atualizar_logs(self):
while not LOG_QUEUE.empty():
msg = LOG_QUEUE.get()
self.adicionar_log(msg)
self.after(1000, self.atualizar_logs)
-------------------- EXECUÇÃO ---------------------
if name == "main":
app = App()
app.mainloop() . chat tem certeza que esse codigo tá completo?