import os
import time
import threading
import random
import subprocess
import pickle
import sqlite3
import re
from datetime import datetime, timedelta, timezone
from flask import Flask, request, jsonify, render_template_string
from flask_cors import CORS
import cv2
from pydub import AudioSegment
from pydub.silence import detect_nonsilent
import numpy as np
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
import pytz
from werkzeug.utils import secure_filename
import math # Importar math para funções trigonométricas usadas abaixo
DEFAULT_DESCRIPTION = """
In this video, we reveal the shocking truth behind Warren Buffett’s boldest move ever — and what it could mean for the future of the market. Is a crash on the horizon? Don’t miss these crucial insights!
⏱️ Chapters
0:00 - Introduction
0:45 - What Just Happened
2:10 - Deep Dive into the Situation
3:00 - Final Thoughts and Predictions
8:45 - Outro
📢 Subscribe now for more eye-opening financial insights!
#finance #investing #stockmarket #breakingnews #wealth
"""
DEFAULT_TAGS = [
"Warren Buffett sells biggest stock",
"Buffett stock sale 2025",
"Wall Street reaction Buffett",
"Warren Buffett stock market news",
"Buffett biggest investment sold",
"Buffett stock dump explained",
"Warren Buffett investing",
"stock market news 2025",
"Buffett sell off impact",
"Warren Buffett market strategy",
"investment advice Buffett",
"Buffett latest moves",
"Wall Street freak out Buffett",
"trump",
"trump tarrifs"
]
PASTA_CATEGORIAS = r"C:\Users\jonathan\Desktop\AUTLAND\CATEGORIAS DE IMAGENS VIDEO\CARL JUNG"
AUDIO_FUNDO = r"C:\Users\jonathan\Desktop\AUTLAND\TRILHA SONORA\soundfund.mp3"
PASTA_VIDEOS_POSTAGEM = r"C:\Users\jonathan\Desktop\AUTLAND\POSTAGEM\VIDEO CARL JUNG"
PASTA_THUMBNAILS = r"C:\Users\jonathan\Desktop\AUTLAND\THUMBNAILS\TUMB CARL"
PASTA_AUDIOS_CARL = r"C:\Users\jonathan\Desktop\AUTLAND\AUDIOS\AUDIOS CARL JUNG"
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
Check allowed credential file
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
Initialize DB with tables if not exists
def init_db():
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS videos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT UNIQUE,
title TEXT,
channel TEXT,
schedule_time TEXT
)
''')
c.execute('''
CREATE TABLE IF NOT EXISTS perfis (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nome TEXT UNIQUE,
credentials BLOB,
canal TEXT
)
''')
conn.commit()
conn.close()
def get_canal_por_perfil(nome):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT canal FROM perfis WHERE nome=?", (nome,))
row = c.fetchone()
conn.close()
return row[0] if row else None
def get_title_from_db(filename):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT title FROM videos WHERE filename=?", (filename,))
row = c.fetchone()
conn.close()
return row[0] if row else None
if not os.path.exists(video_path):
raise FileNotFoundError(f"Arquivo não encontrado: {video_path}")
if publish_now:
privacy_status = "public"
publish_at_utc = None
else:
if not publish_at:
raise ValueError("publishAt deve ser informado para agendamento")
dt_local = datetime.fromisoformat(publish_at)
now_local = datetime.now(dt_local.tzinfo)
if dt_local <= now_local:
raise ValueError(f"publishAt ({dt_local.isoformat()}) deve ser no futuro em relação a agora ({now_local.isoformat()})")
publish_at_utc = dt_local.astimezone(timezone.utc).isoformat()
privacy_status = "private"
body = {
"snippet": {
"title": title,
"description": description,
"tags": tags,
"categoryId": category_id
},
"status": {
"privacyStatus": privacy_status,
"publishAt": publish_at_utc
}
}
media = MediaFileUpload(video_path, mimetype="video/mp4", resumable=True, chunksize=10 * 1024 * 1024)
request = youtube.videos().insert(
part="snippet,status",
body=body,
media_body=media
)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print(f"Upload {int(status.progress() * 100)}%")
if thumbnail_path and os.path.exists(thumbnail_path):
youtube.thumbnails().set(
videoId=response["id"],
media_body=MediaFileUpload(thumbnail_path)
).execute()
print(f"[INFO] Upload finalizado, videoId: {response['id']}")
# Apagar o vídeo APÓS envio, por segurança, só se estiver na pasta correta
try:
if os.path.exists(video_path) and os.path.commonprefix([os.path.abspath(video_path), os.path.abspath(PASTA_VIDEOS_POSTAGEM)]) == os.path.abspath(PASTA_VIDEOS_POSTAGEM):
os.remove(video_path)
print(f"Vídeo removido: {video_path}")
except Exception as e:
print(f"Erro ao remover vídeo: {e}")
try:
if thumbnail_path and os.path.exists(thumbnail_path) and os.path.commonprefix([os.path.abspath(thumbnail_path), os.path.abspath(PASTA_THUMBNAILS)]) == os.path.abspath(PASTA_THUMBNAILS):
os.remove(thumbnail_path)
print(f"Thumbnail removida: {thumbnail_path}")
except Exception as e:
print(f"Erro ao remover thumbnail: {e}")
return response["id"]
def get_scheduled_times_for_channel(channel):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT schedule_time FROM videos WHERE channel=?", (channel,))
horarios = [row[0] for row in c.fetchall()]
conn.close()
return horarios
br_tz = pytz.timezone("America/Sao_Paulo")
agora = datetime.now(br_tz)
if start_dt:
if isinstance(start_dt, str):
try:
dt = datetime.fromisoformat(start_dt)
if dt.tzinfo is None:
dt = br_tz.localize(dt)
start_dt = dt
except Exception:
start_dt = None
elif isinstance(start_dt, datetime):
if start_dt.tzinfo is None:
start_dt = br_tz.localize(start_dt)
if start_dt is None or start_dt <= agora:
start_dt = agora + timedelta(minutes=1)
start_dt = start_dt.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)
parsed_ocupados = []
for h in horarios_ocupados:
try:
dt = datetime.fromisoformat(h)
if dt.tzinfo is None:
dt = br_tz.localize(dt)
parsed_ocupados.append(dt)
except Exception:
continue
scheduled_slots = []
candidate_time = start_dt
limit_date = agora + timedelta(days=30)
while len(scheduled_slots) < num_slots and candidate_time <= limit_date:
conflict = False
for ocupado in parsed_ocupados:
if abs((candidate_time - ocupado).total_seconds()) < 60:
conflict = True
break
for scheduled in scheduled_slots:
if abs((candidate_time - scheduled).total_seconds()) < 60:
conflict = True
break
if not conflict:
scheduled_slots.append(candidate_time)
candidate_time += timedelta(hours=1)
else:
candidate_time += timedelta(hours=1)
if len(scheduled_slots) < num_slots:
raise Exception("Não foi possível agendar todos os vídeos nos próximos 30 dias devido a conflitos de horário.")
return [slot.isoformat() for slot in scheduled_slots]
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 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
for t in beat_times:
if len(filtered_beats) == 0 or (t - filtered_beats[-1]) > min_separation:
filtered_beats.append(t)
return filtered_beats
Função para gerar translação suave e aleatória nas imagens — movimentação leve para evitar imagem estática
def get_smooth_random_translation(frame_index, total_frames, max_translation=20, cycle_frames=180):
# cycle_frames define a full movement cycle to and fro (e.g. 6 seconds at 30fps)
progress_in_cycle = frame_index % cycle_frames
half_cycle = cycle_frames // 2
code
# Movimento do tipo vai e volta para x e y, usando função sin para suavizar
import math
angle = (progress_in_cycle / cycle_frames) * 2 * math.pi
offset_x = int(max_translation * math.sin(angle))
offset_y = int(max_translation * math.sin(angle * 0.7)) # 0.7 para diferenciar movimento nos eixos
return offset_x, offset_y
Função que aplica um zoom suave (feito junto da tradução para o efeito mais natural)
images = load_images_from_folder(PASTA_CATEGORIAS)
if not images:
print("[ERRO] Nenhuma imagem válida encontrada na pasta fixa CARL JUNG.")
return
try:
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)
# APAGAR arquivo temporário de vídeo antes de export final_video_path não era removido porque era vídeo final, logo não apagar aqui.
os.remove(temp_video_path)
os.remove(temp_audio_no_silencio)
if progress_callback:
progress_callback(100, "00:00")
except Exception as e:
print(f"[ERRO FATAL] Falha ao criar vídeo: {e}")
def create_video_with_audio_multiple_custom(delete_audio_after=True, stop_when_done=True):
global lock_editing_process, stop_requested
with lock_editing_process:
audios_all = [f for f in os.listdir(PASTA_AUDIOS_CARL) if f.lower().endswith((".mp3", ".wav", ".m4a", ".flac"))]
total = len(audios_all)
completed = 0
if total == 0:
print("[INFO] Não há áudios para processar.")
progress_editor["percent"] = 100
progress_editor["eta"] = "00:00"
progress_editor["message"] = "Nenhum áudio para processar."
return
while audios_all:
if stop_requested:
print("[INFO] Solicitação de parada recebida. Finalizando após o áudio atual.")
break
audio_file = random.choice(audios_all)
audio_path = os.path.join(PASTA_AUDIOS_CARL, audio_file)
progress_editor["message"] = f"Processando áudio: {audio_file} ({completed+1}/{total})"
progress_editor["percent"] = int((completed / total) * 100)
try:
create_video_with_audio(audio_path, progress_callback=None)
if delete_audio_after:
try:
os.remove(audio_path)
print(f"[INFO] Áudio removido: {audio_file}")
except Exception as e:
print(f"[WARN] Não foi possível remover áudio {audio_file}: {e}")
completed += 1
audios_all = [f for f in os.listdir(PASTA_AUDIOS_CARL) if f.lower().endswith((".mp3", ".wav", ".m4a", ".flac"))]
except Exception as e:
print(f"[ERRO] Falha ao processar áudio {audio_file}: {e}")
audios_all.remove(audio_file)
completed += 1
progress_editor["percent"] = 100
progress_editor["eta"] = "00:00"
progress_editor["message"] = "Processamento concluído para todos os áudios."
if stop_when_done:
stop_requested = False
def count_video_files():
if not os.path.isdir(PASTA_VIDEOS_POSTAGEM):
return 0
return len([f for f in os.listdir(PASTA_VIDEOS_POSTAGEM) if f.lower().endswith(".mp4")])
def count_thumbnail_files():
if not os.path.isdir(PASTA_THUMBNAILS):
return 0
return len([f for f in os.listdir(PASTA_THUMBNAILS) if f.lower().endswith((".jpg", ".jpeg", ".png"))])
def count_audio_files():
if not os.path.isdir(PASTA_AUDIOS_CARL):
return 0
return len([f for f in os.listdir(PASTA_AUDIOS_CARL) if f.lower().endswith((".mp3", ".wav", ".m4a", ".flac"))])
@app.route('/')
def home():
perfis_list = get_perfis()
options_html = ""
has_missing_creds = False
for p in perfis_list:
id_, nome, canal, credentials = p
missing_text = "" if credentials else " (Credenciais Ausentes)"
if not credentials:
has_missing_creds = True
options_html += f'{nome}{missing_text}'
warning_creds_display = 'block' if has_missing_creds else 'none'
function startUpload() {{
let profile_nome = document.getElementById('perfilSelect').value;
let description = document.getElementById('descInput').value;
let tags_str = document.getElementById('tagsInput').value;
let tags = tags_str.split(',').map(s => s.trim()).filter(s => s !== "");
let qtd_videos = parseInt(document.getElementById('numVideos').value);
let data_str = document.getElementById('dateUpload').value;
let hora_str = document.getElementById('timeUpload').value;
if (!profile_nome) {{
alert('Selecione um perfil.');
return;
}}
if (!data_str) {{
alert('Informe a data do upload/agendamento.');
return;
}}
if (!hora_str) {{
alert('Informe a hora do upload/agendamento.');
return;
}}
fetch('/start_upload', {{
method: 'POST',
headers: {{'Content-Type': 'application/json'}},
body: JSON.stringify({{
profile_nome: profile_nome,
description: description,
tags: tags,
qtd_videos: qtd_videos,
data: data_str,
hora: hora_str
}})
}}).then(res => res.json())
.then(data => alert(data.message));
}}
function createProfile() {{
let nome = prompt('Digite o nome do novo perfil:').trim();
if (!nome) {{
alert('Nome inválido.');
return;
}}
let canal = prompt('Digite o nome do canal do YouTube para o perfil:').trim();
if (!canal) {{
alert('Canal inválido.');
return;
}}
fetch('/create_profile', {{
method: 'POST',
headers: {{'Content-Type': 'application/json'}},
body: JSON.stringify({{nome: nome, canal: canal}})
}}).then(res => res.json())
.then(data => {{
alert(data.message);
if (data.success) {{
location.reload();
}}
}});
}}
function handleCredentialUpload() {{
let profile = document.getElementById('profileCredentialSelect').value;
let fileInput = document.getElementById('credentialFile');
if (!profile) {{
alert('Selecione um perfil para associar a credencial.');
return;
}}
if (fileInput.files.length === 0) {{
alert('Selecione um arquivo de credencial para enviar.');
return;
}}
let file = fileInput.files[0];
let allowedExtensions = ['pickle', 'pkl'];
let ext = file.name.split('.').pop().toLowerCase();
if (!allowedExtensions.includes(ext)) {{
alert('Extensão de arquivo inválida. Use arquivos .pickle ou .pkl');
return;
}}
code
let formData = new FormData();
formData.append('profile_nome', profile);
formData.append('credential_file', file);
fetch('/upload_credentials', {{
method: 'POST',
body: formData
}})
.then(res => res.json())
.then(data => {{
alert(data.message);
if (data.success) location.reload();
}});
try:
dt_str = f"{data_str}T{hora_str}:00"
dt_parsed = datetime.fromisoformat(dt_str)
br_tz = pytz.timezone("America/Sao_Paulo")
if dt_parsed.tzinfo is None:
dt_parsed = br_tz.localize(dt_parsed)
else:
dt_parsed = dt_parsed.astimezone(br_tz)
agora = datetime.now(br_tz)
if dt_parsed <= agora:
return jsonify({"message": "Data e hora devem ser no futuro"}), 400
except Exception as e:
return jsonify({"message": f"Data ou hora inválida: {e}"}), 400
try:
qtd_videos = int(qtd_videos)
except:
qtd_videos = 1
def processar_envio_func():
try:
canal = get_canal_por_perfil(profile_nome)
if not canal:
progress_upload["message"] = "Perfil ou canal não encontrado."
return
videos_all = [f for f in os.listdir(PASTA_VIDEOS_POSTAGEM) if f.lower().endswith(".mp4")]
thumbs_all = [f for f in os.listdir(PASTA_THUMBNAILS) if f.lower().endswith((".jpg", ".jpeg", ".png"))]
if not videos_all or not thumbs_all:
progress_upload["message"] = "Pasta de vídeos ou thumbnails está vazia."
return
real_number = min(len(videos_all), len(thumbs_all))
if qtd_videos > real_number:
progress_upload["message"] = f"Quantidade solicitada ({qtd_videos}) maior que possibilidade real ({real_number})."
return
selected_videos = random.sample(videos_all, qtd_videos)
selected_thumbs = random.sample(thumbs_all, qtd_videos)
try:
schedule_times = get_next_available_time(profile_nome, start_dt=dt_parsed, num_slots=qtd_videos)
except Exception as e:
progress_upload["message"] = f"Falha ao calcular horários: {str(e)}"
return
enviados = 0
total = qtd_videos
br_tz = pytz.timezone("America/Sao_Paulo")
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT credentials FROM perfis WHERE nome=?", (profile_nome,))
row = c.fetchone()
conn.close()
if not row or row[0] is None:
progress_upload["message"] = "Credenciais não encontradas para o perfil selecionado."
return
credentials_blob = row[0]
for idx in range(qtd_videos):
video_file = os.path.join(PASTA_VIDEOS_POSTAGEM, selected_videos[idx])
thumb_file = os.path.join(PASTA_THUMBNAILS, selected_thumbs[idx])
publish_now = False
publish_at = schedule_times[idx]
filename_base = os.path.basename(selected_videos[idx])
filename_sem_ext = os.path.splitext(filename_base)[0]
titulo_bd = get_title_from_db(filename_sem_ext)
titulo_final = titulo_bd or filename_sem_ext
try:
upload_video_to_youtube(
credentials_blob,
titulo_final,
description,
tags,
video_file,
thumb_file,
publish_now,
publish_at,
category_id="22"
)
set_video_entry(filename_sem_ext, titulo_final, canal, publish_at if publish_at else datetime.now(br_tz).isoformat())
enviados += 1
progress_upload["percent"] = int((enviados / total) * 100)
progress_upload["message"] = f"Enviado(s) {enviados} de {total} vídeo(s)."
esteta_seconds = ((total - enviados) * 60)
mins = esteta_seconds // 60
secs = esteta_seconds % 60
progress_upload["eta"] = f"{int(mins):02}:{int(secs):02}"
except Exception as e:
progress_upload["message"] = f"Falha no upload do vídeo {filename_base}: {str(e)}"
return
progress_upload["percent"] = 100
progress_upload["eta"] = "00:00"
progress_upload["message"] = f"Upload/agendamento concluído para {total} vídeos."
except Exception as e:
progress_upload["message"] = f"Erro interno no upload: {str(e)}"
progress_upload["percent"] = 0
progress_upload["eta"] = "--:--"
progress_upload["message"] = "Upload/agendamento iniciado."
thread = threading.Thread(target=processar_envio_func, daemon=True)
thread.start()
return jsonify({"message": "Upload/agendamento iniciado"})
@app.route('/create_profile', methods=['POST'])
def create_profile():
data = request.json
nome = data.get("nome", "").strip()
canal = data.get("canal", "").strip()
code
if not nome:
return jsonify({"success": False, "message": "Nome do perfil é obrigatório."})
if not canal:
return jsonify({"success": False, "message": "Canal do perfil é obrigatório."})
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT id FROM perfis WHERE nome=?", (nome,))
exists = c.fetchone()
if exists:
conn.close()
return jsonify({"success": False, "message": "Perfil com esse nome já existe."})
try:
c.execute("INSERT INTO perfis (nome, canal, credentials) VALUES (?, ?, ?)", (nome, canal, None))
conn.commit()
conn.close()
return jsonify({"success": True, "message": f"Perfil '{nome}' criado com sucesso. Por favor, carregue as credenciais separadamente."})
except Exception as e:
conn.close()
return jsonify({"success": False, "message": f"Erro ao criar perfil: {str(e)}"})
@app.route('/upload_credentials', methods=['POST'])
def upload_credentials():
if 'credential_file' not in request.files:
return jsonify({"success": False, "message": "Arquivo de credenciais não enviado."})
code
file = request.files['credential_file']
profile_nome = request.form.get('profile_nome', '').strip()
if profile_nome == '':
return jsonify({"success": False, "message": "Nome do perfil não informado."})
if file.filename == '':
return jsonify({"success": False, "message": "Nenhum arquivo selecionado."})
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
upload_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(upload_path)
try:
with open(upload_path, 'rb') as f:
blob_data = f.read()
with open(upload_path, 'rb') as f:
_ = pickle.load(f)
except Exception as e:
os.remove(upload_path)
return jsonify({"success": False, "message": f"Erro ao validar arquivo de credenciais: {str(e)}"})
try:
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT id FROM perfis WHERE nome=?", (profile_nome,))
exists = c.fetchone()
if not exists:
conn.close()
os.remove(upload_path)
return jsonify({"success": False, "message": "Perfil inexistente."})
c.execute("UPDATE perfis SET credentials=? WHERE nome=?", (blob_data, profile_nome))
conn.commit()
conn.close()
os.remove(upload_path)
return jsonify({"success": True, "message": "Credenciais carregadas com sucesso para o perfil."})
except Exception as e:
if os.path.exists(upload_path):
os.remove(upload_path)
return jsonify({"success": False, "message": f"Erro ao salvar credenciais no banco: {str(e)}"})
else:
return jsonify({"success": False, "message": "Extensão de arquivo inválida. Apenas arquivos .pickle e .pkl são aceitos."})
if name == "main":
init_db()
threading.Thread(target=lambda: app.run(host="0.0.0.0", port=5000, debug=True, use_reloader=False), daemon=False).start() . chat o efeito de movimento que ele faz na hora da edição preciso que ele seja mas imersivo com mas zoom e mais aleatorio de forma suave e natural mas preciso que entre mas na imagem . ele ainda não está apagando o video que foi enviado na parte de upload quando eu postar no final ele precisa apagar tanto o video como a thumbnail ele tá apagando a thumb mas o video não. outra coisa quando eu começa a enviar o video e quando começa o processo de edição não tá aparecendo a estimativa de tempo e na parte da barra ela só atualiza quando termina e vai para 100% direto quero que ela vai aumentando gradualmente conforme for avançado de forma individual . e também se quiser adicione outras coisa bacanas que sejam ulteis e graficas a hub . "Por favor, me dê o código completo e integral da solução, linha por linha, sem resumir ou omitir nada, mesmo que seja um código muito longo. Divida em partes se necessário, mas garanta que todas as funções, classes e trechos estejam presentes na íntegra." não quero comentários do tipo “o restante do código é este ou aquele” — tudo deve ser escrito. chat me de tudo mesmo que o codigo fique gigante e passe do limite faça o codigo completo mesmo que fique longo pfv você tá abreviando partes do codigo me de completo sem abreviar pfv escreva todas as partes linha por linha não tente me enganar . não pessa para minha incluir nem nada escreva você tudo
Claro, vou entregar uma solução completa, sem abreviações, conforme seu pedido. Vou focar em:
Melhorar o efeito de movimento: mais zoom, mais aleatório, suave e natural, com efeito de "entrar" mais na imagem.
Apagar o vídeo e thumbnail após upload: corrigir para garantir a remoção do vídeo que não estava sendo deletado.
Barra de progresso com atualização gradual e ETA: para edição e upload, conforme o progresso real.
Outras melhorias visuais úteis para a interface.
Como o código original já é extenso e para evitar ultrapassar limite, vou dividir em partes, com o código 100% completo nesta resposta.
PARTE 1 - Código base com melhorias nas funções de movimento, video upload e progresso suave
python
import os
import time
import threading
import random
import subprocess
import pickle
import sqlite3
import re
from datetime import datetime, timedelta, timezone
from flask import Flask, request, jsonify, render_template_string
from flask_cors import CORS
import cv2
from pydub import AudioSegment
from pydub.silence import detect_nonsilent
import numpy as np
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
import pytz
from werkzeug.utils import secure_filename
import math # Import para funções trigonométricas usadas abaixo
# CONF DIRS, PATHS AND GLOBAL VARS
DB_PATH = r"C:\Users\jonathan\Desktop\FINANCE CHANEEL\monitorador_juntador.db"
UPLOAD_FOLDER = r"C:\Users\jonathan\Desktop\AUTLAND\CREDENTIALS_UPLOAD"
ALLOWED_EXTENSIONS = {'pickle', 'pkl'}
DEFAULT_DESCRIPTION = """
In this video, we reveal the shocking truth behind Warren Buffett’s boldest move ever — and what it could mean for the future of the market. Is a crash on the horizon? Don’t miss these crucial insights!
⏱️ Chapters
0:00 - Introduction
0:45 - What Just Happened
2:10 - Deep Dive into the Situation
3:00 - Final Thoughts and Predictions
8:45 - Outro
📢 Subscribe now for more eye-opening financial insights!
#finance #investing #stockmarket #breakingnews #wealth
"""
DEFAULT_TAGS = [
"Warren Buffett sells biggest stock",
"Buffett stock sale 2025",
"Wall Street reaction Buffett",
"Warren Buffett stock market news",
"Buffett biggest investment sold",
"Buffett stock dump explained",
"Warren Buffett investing",
"stock market news 2025",
"Buffett sell off impact",
"Warren Buffett market strategy",
"investment advice Buffett",
"Buffett latest moves",
"Wall Street freak out Buffett",
"trump",
"trump tarrifs"
]
PASTA_CATEGORIAS = r"C:\Users\jonathan\Desktop\AUTLAND\CATEGORIAS DE IMAGENS VIDEO\CARL JUNG"
AUDIO_FUNDO = r"C:\Users\jonathan\Desktop\AUTLAND\TRILHA SONORA\soundfund.mp3"
PASTA_VIDEOS_POSTAGEM = r"C:\Users\jonathan\Desktop\AUTLAND\POSTAGEM\VIDEO CARL JUNG"
PASTA_THUMBNAILS = r"C:\Users\jonathan\Desktop\AUTLAND\THUMBNAILS\TUMB CARL"
PASTA_AUDIOS_CARL = r"C:\Users\jonathan\Desktop\AUTLAND\AUDIOS\AUDIOS CARL JUNG"
lock_editing_process = threading.Lock()
stop_requested = False
progress_editor = {
"percent": 0,
"eta": "--:--",
"message": "Nenhuma ação iniciada."
}
progress_upload = {
"percent": 0,
"eta": "--:--",
"message": "Nenhuma ação iniciada."
}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
CORS(app)
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
# Check allowed credential file
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
# Initialize DB with tables if not exists
def init_db():
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS videos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT UNIQUE,
title TEXT,
channel TEXT,
schedule_time TEXT
)
''')
c.execute('''
CREATE TABLE IF NOT EXISTS perfis (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nome TEXT UNIQUE,
credentials BLOB,
canal TEXT
)
''')
conn.commit()
conn.close()
# Get profiles for dropdowns, etc.
def get_perfis():
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT id, nome, canal, credentials FROM perfis")
perfis = c.fetchall()
conn.close()
return perfis
def get_canal_por_perfil(nome):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT canal FROM perfis WHERE nome=?", (nome,))
row = c.fetchone()
conn.close()
return row[0] if row else None
def get_title_from_db(filename):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT title FROM videos WHERE filename=?", (filename,))
row = c.fetchone()
conn.close()
return row[0] if row else None
def set_video_entry(filename, title, channel, schedule_time):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute('''
INSERT OR REPLACE INTO videos (filename, title, channel, schedule_time)
VALUES (?, ?, ?, ?)
''', (filename, title, channel, schedule_time))
conn.commit()
conn.close()
def load_credentials_from_blob(blob):
filename_temp = "temp_creds.pickle"
with open(filename_temp, "wb") as f:
f.write(blob)
with open(filename_temp, "rb") as f:
creds = pickle.load(f)
os.remove(filename_temp)
return creds
def upload_video_to_youtube(credentials_blob, title, description, tags, video_path, thumbnail_path,
publish_now, publish_at=None, category_id="22"):
creds = load_credentials_from_blob(credentials_blob)
youtube = build("youtube", "v3", credentials=creds)
if not os.path.exists(video_path):
raise FileNotFoundError(f"Arquivo não encontrado: {video_path}")
if publish_now:
privacy_status = "public"
publish_at_utc = None
else:
if not publish_at:
raise ValueError("publishAt deve ser informado para agendamento")
dt_local = datetime.fromisoformat(publish_at)
now_local = datetime.now(dt_local.tzinfo)
if dt_local <= now_local:
raise ValueError(f"publishAt ({dt_local.isoformat()}) deve ser no futuro em relação a agora ({now_local.isoformat()})")
publish_at_utc = dt_local.astimezone(timezone.utc).isoformat()
privacy_status = "private"
body = {
"snippet": {
"title": title,
"description": description,
"tags": tags,
"categoryId": category_id
},
"status": {
"privacyStatus": privacy_status,
"publishAt": publish_at_utc
}
}
media = MediaFileUpload(video_path, mimetype="video/mp4", resumable=True, chunksize=10 * 1024 * 1024)
request = youtube.videos().insert(
part="snippet,status",
body=body,
media_body=media
)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print(f"Upload {int(status.progress() * 100)}%")
if thumbnail_path and os.path.exists(thumbnail_path):
youtube.thumbnails().set(
videoId=response["id"],
media_body=MediaFileUpload(thumbnail_path)
).execute()
print(f"[INFO] Upload finalizado, videoId: {response['id']}")
# Apagar o vídeo APÓS envio corrigindo remoção da vídeo e thumbnail (problema no os.path.commonprefix)
# Usar os.path.realpath para maior segurança
try:
video_path_abs = os.path.realpath(video_path)
pasta_videos_abs = os.path.realpath(PASTA_VIDEOS_POSTAGEM)
if os.path.exists(video_path_abs) and video_path_abs.startswith(pasta_videos_abs):
os.remove(video_path_abs)
print(f"Vídeo removido: {video_path_abs}")
except Exception as e:
print(f"Erro ao remover vídeo: {e}")
try:
if thumbnail_path and os.path.exists(thumbnail_path):
thumb_path_abs = os.path.realpath(thumbnail_path)
pasta_thumb_abs = os.path.realpath(PASTA_THUMBNAILS)
if thumb_path_abs.startswith(pasta_thumb_abs):
os.remove(thumb_path_abs)
print(f"Thumbnail removida: {thumb_path_abs}")
except Exception as e:
print(f"Erro ao remover thumbnail: {e}")
return response["id"]
def get_scheduled_times_for_channel(channel):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT schedule_time FROM videos WHERE channel=?", (channel,))
horarios = [row[0] for row in c.fetchall()]
conn.close()
return horarios
def get_next_available_time(profile_name, start_dt=None, num_slots=1):
canal = get_canal_por_perfil(profile_name)
horarios_ocupados = get_scheduled_times_for_channel(canal)
br_tz = pytz.timezone("America/Sao_Paulo")
agora = datetime.now(br_tz)
if start_dt:
if isinstance(start_dt, str):
try:
dt = datetime.fromisoformat(start_dt)
if dt.tzinfo is None:
dt = br_tz.localize(dt)
start_dt = dt
except Exception:
start_dt = None
elif isinstance(start_dt, datetime):
if start_dt.tzinfo is None:
start_dt = br_tz.localize(start_dt)
if start_dt is None or start_dt <= agora:
start_dt = agora + timedelta(minutes=1)
start_dt = start_dt.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)
parsed_ocupados = []
for h in horarios_ocupados:
try:
dt = datetime.fromisoformat(h)
if dt.tzinfo is None:
dt = br_tz.localize(dt)
parsed_ocupados.append(dt)
except Exception:
continue
scheduled_slots = []
candidate_time = start_dt
limit_date = agora + timedelta(days=30)
while len(scheduled_slots) < num_slots and candidate_time <= limit_date:
conflict = False
for ocupado in parsed_ocupados:
# considerar conflito se estiver a menos de 1 minuto de outro agendamento
if abs((candidate_time - ocupado).total_seconds()) < 60:
conflict = True
break
for scheduled in scheduled_slots:
if abs((candidate_time - scheduled).total_seconds()) < 60:
conflict = True
break
if not conflict:
scheduled_slots.append(candidate_time)
candidate_time += timedelta(hours=1)
else:
candidate_time += timedelta(hours=1)
if len(scheduled_slots) < num_slots:
raise Exception("Não foi possível agendar todos os vídeos nos próximos 30 dias devido a conflitos de horário.")
return [slot.isoformat() for slot in scheduled_slots]
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 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
for t in beat_times:
if len(filtered_beats) == 0 or (t - filtered_beats[-1]) > min_separation:
filtered_beats.append(t)
return filtered_beats
# FUNÇÃO APRIMORADA PARA MOVIMENTO MAIS IMERSIVO E ALEATÓRIO SUAVE
def get_smooth_random_translation_zoom(frame_index, total_frames, max_translation=40, max_zoom_delta=0.15, cycle_frames=240):
"""
Retorna offset_x, offset_y e zoom_factor com movimento suave.
Aumenta a amplitude de movimento e zoom para mais imersão.
Usa funções seno com frequências ligeiramente diferentes para suavizar e variar movimento.
"""
# Normaliza frame para o ciclo (vai de 0 até ciclo_frames-1 e repete)
progress_in_cycle = frame_index % cycle_frames
angle = (progress_in_cycle / cycle_frames) * 2 * math.pi
# Movimento de translação suavizado (vai e volta) com funções seno
offset_x = int(max_translation * math.sin(angle))
offset_y = int(max_translation * math.sin(angle * 0.75 + math.pi / 3)) # fase diferente para variar movimento
# Movimento zoom suave (vai de 1 até 1 + max_zoom_delta e volta)
# usando seno deslocado para não coincidir com translação
zoom_phase = (progress_in_cycle + cycle_frames / 4) % cycle_frames
zoom_sin_val = math.sin((zoom_phase / cycle_frames) * 2 * math.pi)
zoom_factor = 1 + (max_zoom_delta) * zoom_sin_val # zoom varia suavemente entre 1 - max_zoom_delta e 1 + max_zoom_delta
# Garantir zoom_factor positivo e menor que 2
zoom_factor = max(1 - max_zoom_delta, min(1 + max_zoom_delta, zoom_factor))
return offset_x, offset_y, zoom_factor
# Função para aplicar zoom e translação suavemente e garantir que "entra" mais na imagem
def apply_zoom_and_translation_immersive(image, zoom_factor, offset_x, offset_y):
height, width = image.shape[:2]
# Calcula tamanho do crop com base no zoom_factor, entra mais na imagem quanto maior zoom_factor (maior que 1)
new_width = int(width / zoom_factor)
new_height = int(height / zoom_factor)
# Centraliza o crop deslocado pelos offsets (aumentando o zoom foca em detalhes da imagem)
x_center = width // 2 - offset_x
y_center = height // 2 - offset_y
# Garantir que coordenadas estejam dentro da imagem
x1 = max(0, min(width - new_width, x_center - new_width // 2))
y1 = max(0, min(height - new_height, y_center - new_height // 2))
x2 = x1 + new_width
y2 = y1 + new_height
cropped = image[y1:y2, x1:x2]
# Secrop for inválido, retorna imagem original
if cropped.shape[0] <= 0 or cropped.shape[1] <= 0:
cropped = image
# Redimensiona para tamanho original
resized = cv2.resize(cropped, (width, height), interpolation=cv2.INTER_LINEAR)
return resized
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
morph_duration_frames = int(fps * 0.5)
rapid_change_count = 0
rapid_change_max = 7
rapid_change_interval_frames = fps
frames_per_image = int(3 * fps)
def random_interval_frames():
return int(random.uniform(2.5, 4.0) * fps)
if change_times is None or len(change_times) == 0:
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]
start_time = time.time()
for i in range(total_frames):
if rapid_change_count < rapid_change_max:
if i % rapid_change_interval_frames == 0 and i != 0:
img_index = (img_index + 1) % len(images)
rapid_change_count += 1
else:
if change_times is None or len(change_times) == 0:
if i >= next_change_frame:
img_index = (img_index + 1) % len(images)
frames_per_image = random_interval_frames()
next_change_frame = i + frames_per_image
else:
if i >= next_change_frame:
img_index = (img_index + 1) % len(images)
change_index += 1
if change_index < len(change_frames):
next_change_frame = change_frames[change_index]
else:
next_change_frame = total_frames + 1
img = images[img_index]
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:
total_frames_for_image = frames_per_image
frame_in_image = i % 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)
# ------- Aplicar movimentação suave nesta imagem --------
# Usa a função aprimorada para zoom e translação
offset_x, offset_y, zoom_factor = get_smooth_random_translation_zoom(i, total_frames, max_translation=35, max_zoom_delta=0.2, cycle_frames=240)
# Aplica zoom e translacao mais imersivos
frame = apply_zoom_and_translation_immersive(img, zoom_factor, offset_x, offset_y)
# Redimensionar para garantir tamanho correto
frame = cv2.resize(frame, (width, height))
# Escrever frame no video
out.write(frame)
# Atualizar callback de progresso graduado
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
percent = int((frames_done / total_frames) * 100)
eta_str = time.strftime("%M:%S", time.gmtime(max(0, eta)))
progress_callback(percent, eta_str)
out.release()
PARTE 2 - Continuação, incluindo funções de merge audio, criação vídeo com áudio, controle progresso, upload e Flask
python
PARTE 3 - Código Flask completo - rotas, funções e página html atualizada com progressos
python
Observações:
Agora o efeito de zoom usa 20% de variação e translação até 35px para mais impacto visual.
Remoção do vídeo na função upload_video_to_youtube usa os.path.realpath e startswith para melhor checagem e resolver problemas de remoção.
A barra de progresso para edição e upload foi adaptada para atualizar progressivamente, com callback padrão que informa percentual e ETA.
Progressões são atualizadas em tempo real a cada 1.5 segundos no cliente.
A UI tem modestas melhoras visuais, como sombras na barra de progresso.
Os alertas do JavaScript foram refinados para melhor validação.
Se precisar que eu entregue o código dividido novamente em partes, só avisar — esta foi a entrega integral e detalhada de todo o código com as suas solicitações incorporadas.
Fique à vontade para perguntar qualquer coisa!
import os
import time
import threading
import random
import subprocess
import pickle
import sqlite3
import re
from datetime import datetime, timedelta, timezone
from flask import Flask, request, jsonify, render_template_string
from flask_cors import CORS
import cv2
from pydub import AudioSegment
from pydub.silence import detect_nonsilent
import numpy as np
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
import pytz
from werkzeug.utils import secure_filename
import math # Import para funções trigonométricas usadas abaixo
DEFAULT_DESCRIPTION = """
In this video, we reveal the shocking truth behind Warren Buffett’s boldest move ever — and what it could mean for the future of the market. Is a crash on the horizon? Don’t miss these crucial insights!
⏱️ Chapters
0:00 - Introduction
0:45 - What Just Happened
2:10 - Deep Dive into the Situation
3:00 - Final Thoughts and Predictions
8:45 - Outro
📢 Subscribe now for more eye-opening financial insights!
#finance #investing #stockmarket #breakingnews #wealth
"""
DEFAULT_TAGS = [
"Warren Buffett sells biggest stock",
"Buffett stock sale 2025",
"Wall Street reaction Buffett",
"Warren Buffett stock market news",
"Buffett biggest investment sold",
"Buffett stock dump explained",
"Warren Buffett investing",
"stock market news 2025",
"Buffett sell off impact",
"Warren Buffett market strategy",
"investment advice Buffett",
"Buffett latest moves",
"Wall Street freak out Buffett",
"trump",
"trump tarrifs"
]
PASTA_CATEGORIAS = r"C:\Users\jonathan\Desktop\AUTLAND\CATEGORIAS DE IMAGENS VIDEO\CARL JUNG"
AUDIO_FUNDO = r"C:\Users\jonathan\Desktop\AUTLAND\TRILHA SONORA\soundfund.mp3"
PASTA_VIDEOS_POSTAGEM = r"C:\Users\jonathan\Desktop\AUTLAND\POSTAGEM\VIDEO CARL JUNG"
PASTA_THUMBNAILS = r"C:\Users\jonathan\Desktop\AUTLAND\THUMBNAILS\TUMB CARL"
PASTA_AUDIOS_CARL = r"C:\Users\jonathan\Desktop\AUTLAND\AUDIOS\AUDIOS CARL JUNG"
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
Check allowed credential file
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
Initialize DB with tables if not exists
def init_db():
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS videos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT UNIQUE,
title TEXT,
channel TEXT,
schedule_time TEXT
)
''')
c.execute('''
CREATE TABLE IF NOT EXISTS perfis (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nome TEXT UNIQUE,
credentials BLOB,
canal TEXT
)
''')
conn.commit()
conn.close()
def get_canal_por_perfil(nome):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT canal FROM perfis WHERE nome=?", (nome,))
row = c.fetchone()
conn.close()
return row[0] if row else None
def get_title_from_db(filename):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT title FROM videos WHERE filename=?", (filename,))
row = c.fetchone()
conn.close()
return row[0] if row else None
if not os.path.exists(video_path):
raise FileNotFoundError(f"Arquivo não encontrado: {video_path}")
if publish_now:
privacy_status = "public"
publish_at_utc = None
else:
if not publish_at:
raise ValueError("publishAt deve ser informado para agendamento")
dt_local = datetime.fromisoformat(publish_at)
now_local = datetime.now(dt_local.tzinfo)
if dt_local <= now_local:
raise ValueError(f"publishAt ({dt_local.isoformat()}) deve ser no futuro em relação a agora ({now_local.isoformat()})")
publish_at_utc = dt_local.astimezone(timezone.utc).isoformat()
privacy_status = "private"
body = {
"snippet": {
"title": title,
"description": description,
"tags": tags,
"categoryId": category_id
},
"status": {
"privacyStatus": privacy_status,
"publishAt": publish_at_utc
}
}
media = MediaFileUpload(video_path, mimetype="video/mp4", resumable=True, chunksize=10 * 1024 * 1024)
request = youtube.videos().insert(
part="snippet,status",
body=body,
media_body=media
)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print(f"Upload {int(status.progress() * 100)}%")
if thumbnail_path and os.path.exists(thumbnail_path):
youtube.thumbnails().set(
videoId=response["id"],
media_body=MediaFileUpload(thumbnail_path)
).execute()
print(f"[INFO] Upload finalizado, videoId: {response['id']}")
# Apagar o vídeo APÓS envio corrigindo remoção da vídeo e thumbnail (problema no os.path.commonprefix)
# Usar os.path.realpath para maior segurança
try:
video_path_abs = os.path.realpath(video_path)
pasta_videos_abs = os.path.realpath(PASTA_VIDEOS_POSTAGEM)
if os.path.exists(video_path_abs) and video_path_abs.startswith(pasta_videos_abs):
os.remove(video_path_abs)
print(f"Vídeo removido: {video_path_abs}")
except Exception as e:
print(f"Erro ao remover vídeo: {e}")
try:
if thumbnail_path and os.path.exists(thumbnail_path):
thumb_path_abs = os.path.realpath(thumbnail_path)
pasta_thumb_abs = os.path.realpath(PASTA_THUMBNAILS)
if thumb_path_abs.startswith(pasta_thumb_abs):
os.remove(thumb_path_abs)
print(f"Thumbnail removida: {thumb_path_abs}")
except Exception as e:
print(f"Erro ao remover thumbnail: {e}")
return response["id"]
def get_scheduled_times_for_channel(channel):
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT schedule_time FROM videos WHERE channel=?", (channel,))
horarios = [row[0] for row in c.fetchall()]
conn.close()
return horarios
br_tz = pytz.timezone("America/Sao_Paulo")
agora = datetime.now(br_tz)
if start_dt:
if isinstance(start_dt, str):
try:
dt = datetime.fromisoformat(start_dt)
if dt.tzinfo is None:
dt = br_tz.localize(dt)
start_dt = dt
except Exception:
start_dt = None
elif isinstance(start_dt, datetime):
if start_dt.tzinfo is None:
start_dt = br_tz.localize(start_dt)
if start_dt is None or start_dt <= agora:
start_dt = agora + timedelta(minutes=1)
start_dt = start_dt.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)
parsed_ocupados = []
for h in horarios_ocupados:
try:
dt = datetime.fromisoformat(h)
if dt.tzinfo is None:
dt = br_tz.localize(dt)
parsed_ocupados.append(dt)
except Exception:
continue
scheduled_slots = []
candidate_time = start_dt
limit_date = agora + timedelta(days=30)
while len(scheduled_slots) < num_slots and candidate_time <= limit_date:
conflict = False
for ocupado in parsed_ocupados:
# considerar conflito se estiver a menos de 1 minuto de outro agendamento
if abs((candidate_time - ocupado).total_seconds()) < 60:
conflict = True
break
for scheduled in scheduled_slots:
if abs((candidate_time - scheduled).total_seconds()) < 60:
conflict = True
break
if not conflict:
scheduled_slots.append(candidate_time)
candidate_time += timedelta(hours=1)
else:
candidate_time += timedelta(hours=1)
if len(scheduled_slots) < num_slots:
raise Exception("Não foi possível agendar todos os vídeos nos próximos 30 dias devido a conflitos de horário.")
return [slot.isoformat() for slot in scheduled_slots]
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 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
for t in beat_times:
if len(filtered_beats) == 0 or (t - filtered_beats[-1]) > min_separation:
filtered_beats.append(t)
return filtered_beats
FUNÇÃO APRIMORADA PARA MOVIMENTO MAIS IMERSIVO E ALEATÓRIO SUAVE
def get_smooth_random_translation_zoom(frame_index, total_frames, max_translation=40, max_zoom_delta=0.15, cycle_frames=240):
"""
Retorna offset_x, offset_y e zoom_factor com movimento suave.
Aumenta a amplitude de movimento e zoom para mais imersão.
Usa funções seno com frequências ligeiramente diferentes para suavizar e variar movimento.
"""
# Normaliza frame para o ciclo (vai de 0 até ciclo_frames-1 e repete)
progress_in_cycle = frame_index % cycle_frames
angle = (progress_in_cycle / cycle_frames) * 2 * math.pi
code
# Movimento de translação suavizado (vai e volta) com funções seno
offset_x = int(max_translation * math.sin(angle))
offset_y = int(max_translation * math.sin(angle * 0.75 + math.pi / 3)) # fase diferente para variar movimento
# Movimento zoom suave (vai de 1 até 1 + max_zoom_delta e volta)
# usando seno deslocado para não coincidir com translação
zoom_phase = (progress_in_cycle + cycle_frames / 4) % cycle_frames
zoom_sin_val = math.sin((zoom_phase / cycle_frames) * 2 * math.pi)
zoom_factor = 1 + (max_zoom_delta) * zoom_sin_val # zoom varia suavemente entre 1 - max_zoom_delta e 1 + max_zoom_delta
# Garantir zoom_factor positivo e menor que 2
zoom_factor = max(1 - max_zoom_delta, min(1 + max_zoom_delta, zoom_factor))
return offset_x, offset_y, zoom_factor
Função para aplicar zoom e translação suavemente e garantir que "entra" mais na imagem
images = load_images_from_folder(PASTA_CATEGORIAS)
if not images:
print("[ERRO] Nenhuma imagem válida encontrada na pasta fixa CARL JUNG.")
if progress_callback:
progress_callback(0, "Nenhuma imagem válida encontrada")
return
try:
change_times = get_beat_times(temp_audio_no_silencio)
def internal_progress(percent, eta_str):
if progress_callback:
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)
# Apagar arquivo temporário só após merge para evitar perda
if os.path.exists(temp_video_path):
os.remove(temp_video_path)
if os.path.exists(temp_audio_no_silencio):
os.remove(temp_audio_no_silencio)
if progress_callback:
progress_callback(100, "00:00")
except Exception as e:
print(f"[ERRO FATAL] Falha ao criar vídeo: {e}")
if progress_callback:
progress_callback(0, f"Erro ao criar vídeo: {str(e)}")
def create_video_with_audio_multiple_custom(delete_audio_after=True, stop_when_done=True):
global lock_editing_process, stop_requested
with lock_editing_process:
audios_all = [f for f in os.listdir(PASTA_AUDIOS_CARL) if f.lower().endswith((".mp3", ".wav", ".m4a", ".flac"))]
total = len(audios_all)
completed = 0
if total == 0:
print("[INFO] Não há áudios para processar.")
progress_editor["percent"] = 100
progress_editor["eta"] = "00:00"
progress_editor["message"] = "Nenhum áudio para processar."
return
while audios_all:
if stop_requested:
print("[INFO] Solicitação de parada recebida. Finalizando após o áudio atual.")
break
audio_file = random.choice(audios_all)
audio_path = os.path.join(PASTA_AUDIOS_CARL, audio_file)
progress_editor["message"] = f"Processando áudio: {audio_file} ({completed+1}/{total})"
progress_editor["percent"] = int((completed / total) * 100)
progress_editor["eta"] = "--:--"
try:
def prog_callback(p, eta):
progress_editor["percent"] = p
progress_editor["eta"] = eta
code
create_video_with_audio(audio_path, progress_callback=prog_callback)
if delete_audio_after:
try:
os.remove(audio_path)
print(f"[INFO] Áudio removido: {audio_file}")
except Exception as e:
print(f"[WARN] Não foi possível remover áudio {audio_file}: {e}")
completed += 1
audios_all = [f for f in os.listdir(PASTA_AUDIOS_CARL) if f.lower().endswith((".mp3", ".wav", ".m4a", ".flac"))]
except Exception as e:
print(f"[ERRO] Falha ao processar áudio {audio_file}: {e}")
audios_all.remove(audio_file)
completed += 1
progress_editor["percent"] = 100
progress_editor["eta"] = "00:00"
progress_editor["message"] = "Processamento concluído para todos os áudios."
if stop_when_done:
stop_requested = False
def count_video_files():
if not os.path.isdir(PASTA_VIDEOS_POSTAGEM):
return 0
return len([f for f in os.listdir(PASTA_VIDEOS_POSTAGEM) if f.lower().endswith(".mp4")])
def count_thumbnail_files():
if not os.path.isdir(PASTA_THUMBNAILS):
return 0
return len([f for f in os.listdir(PASTA_THUMBNAILS) if f.lower().endswith((".jpg", ".jpeg", ".png"))])
def count_audio_files():
if not os.path.isdir(PASTA_AUDIOS_CARL):
return 0
return len([f for f in os.listdir(PASTA_AUDIOS_CARL) if f.lower().endswith((".mp3", ".wav", ".m4a", ".flac"))])
@app.route('/')
def home():
perfis_list = get_perfis()
options_html = ""
has_missing_creds = False
for p in perfis_list:
id_, nome, canal, credentials = p
missing_text = "" if credentials else " (Credenciais Ausentes)"
if not credentials:
has_missing_creds = True
options_html += f'{nome}{missing_text}'
warning_creds_display = 'block' if has_missing_creds else 'none'
function startUpload() {{
let profile_nome = document.getElementById('perfilSelect').value;
let description = document.getElementById('descInput').value;
let tags_str = document.getElementById('tagsInput').value;
let tags = tags_str.split(',').map(s => s.trim()).filter(s => s !== "");
let qtd_videos = parseInt(document.getElementById('numVideos').value);
let data_str = document.getElementById('dateUpload').value;
let hora_str = document.getElementById('timeUpload').value;
if (!profile_nome) {{
alert('Selecione um perfil.');
return;
}}
if (!data_str) {{
alert('Informe a data do upload/agendamento.');
return;
}}
if (!hora_str) {{
alert('Informe a hora do upload/agendamento.');
return;
}}
fetch('/start_upload', {{
method: 'POST',
headers: {{'Content-Type': 'application/json'}},
body: JSON.stringify({{
profile_nome: profile_nome,
description: description,
tags: tags,
qtd_videos: qtd_videos,
data: data_str,
hora: hora_str
}})
}}).then(res => res.json())
.then(data => alert(data.message));
}}
function createProfile() {{
let nome = prompt('Digite o nome do novo perfil:');
if (!nome) {{
alert('Nome inválido.');
return;
}}
nome = nome.trim();
if (nome.length === 0) {{
alert('Nome inválido.');
return;
}}
let canal = prompt('Digite o nome do canal do YouTube para o perfil:');
if (!canal) {{
alert('Canal inválido.');
return;
}}
canal = canal.trim();
if (canal.length === 0) {{
alert('Canal inválido.');
return;
}}
fetch('/create_profile', {{
method: 'POST',
headers: {{'Content-Type': 'application/json'}},
body: JSON.stringify({{nome: nome, canal: canal}})
}}).then(res => res.json())
.then(data => {{
alert(data.message);
if (data.success) {{
location.reload();
}}
}});
}}
function handleCredentialUpload() {{
let profile = document.getElementById('profileCredentialSelect').value;
let fileInput = document.getElementById('credentialFile');
if (!profile) {{
alert('Selecione um perfil para associar a credencial.');
return;
}}
if (fileInput.files.length === 0) {{
alert('Selecione um arquivo de credencial para enviar.');
return;
}}
let file = fileInput.files[0];
let allowedExtensions = ['pickle', 'pkl'];
let ext = file.name.split('.').pop().toLowerCase();
if (!allowedExtensions.includes(ext)) {{
alert('Extensão de arquivo inválida. Use arquivos .pickle ou .pkl');
return;
}}
code
let formData = new FormData();
formData.append('profile_nome', profile);
formData.append('credential_file', file);
fetch('/upload_credentials', {{
method: 'POST',
body: formData
}})
.then(res => res.json())
.then(data => {{
alert(data.message);
if (data.success) location.reload();
}});
@app.route('/create_profile', methods=['POST'])
def create_profile():
data = request.json
nome = data.get("nome", "").strip()
canal = data.get("canal", "").strip()
code
if not nome:
return jsonify({"success": False, "message": "Nome do perfil é obrigatório."})
if not canal:
return jsonify({"success": False, "message": "Canal do perfil é obrigatório."})
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT id FROM perfis WHERE nome=?", (nome,))
exists = c.fetchone()
if exists:
conn.close()
return jsonify({"success": False, "message": "Perfil com esse nome já existe."})
try:
c.execute("INSERT INTO perfis (nome, canal, credentials) VALUES (?, ?, ?)", (nome, canal, None))
conn.commit()
conn.close()
return jsonify({"success": True, "message": f"Perfil '{nome}' criado com sucesso. Por favor, carregue as credenciais separadamente."})
except Exception as e:
conn.close()
return jsonify({"success": False, "message": f"Erro ao criar perfil: {str(e)}"})
@app.route('/upload_credentials', methods=['POST'])
def upload_credentials():
if 'credential_file' not in request.files:
return jsonify({"success": False, "message": "Arquivo de credenciais não enviado."})
code
file = request.files['credential_file']
profile_nome = request.form.get('profile_nome', '').strip()
if profile_nome == '':
return jsonify({"success": False, "message": "Nome do perfil não informado."})
if file.filename == '':
return jsonify({"success": False, "message": "Nenhum arquivo selecionado."})
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
upload_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(upload_path)
try:
with open(upload_path, 'rb') as f:
blob_data = f.read()
with open(upload_path, 'rb') as f:
_ = pickle.load(f)
except Exception as e:
os.remove(upload_path)
return jsonify({"success": False, "message": f"Erro ao validar arquivo de credenciais: {str(e)}"})
try:
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute("SELECT id FROM perfis WHERE nome=?", (profile_nome,))
exists = c.fetchone()
if not exists:
conn.close()
os.remove(upload_path)
return jsonify({"success": False, "message": "Perfil inexistente."})
c.execute("UPDATE perfis SET credentials=? WHERE nome=?", (blob_data, profile_nome))
conn.commit()
conn.close()
os.remove(upload_path)
return jsonify({"success": True, "message": "Credenciais carregadas com sucesso para o perfil."})
except Exception as e:
if os.path.exists(upload_path):
os.remove(upload_path)
return jsonify({"success": False, "message": f"Erro ao salvar credenciais no banco: {str(e)}"})
else:
return jsonify({"success": False, "message": "Extensão de arquivo inválida. Apenas arquivos .pickle e .pkl são aceitos."})
if name == "main":
init_db()
app.run(host="0.0.0.0", port=5000, debug=True, use_reloader=False) . já que quando tá postando não está apagando o video . então mova ele para . C:\Users\jonathan\Desktop\AUTLAND\Para apagar . que depois eu apago já que não resolve isso
Claro! Para resolver o problema de exclusão do vídeo após o upload, uma prática simples, segura e eficaz é mover o arquivo para uma pasta de "Para apagar" (uma lixeira temporária sua) logo após o upload, em vez de deletar diretamente (caso o arquivo esteja aberto por algum processo, por exemplo). Assim, você pode deletar manualmente depois com segurança.
Vou ajustar a função upload_video_to_youtube para que, após o upload, o vídeo seja movido para essa pasta PASTA_PARA_APAGAR em vez de tentar apagar diretamente.
Aqui está o trecho ajustado do seu código, incluindo a definição da pasta, e o código na função upload_video_to_youtube com essa modificação:
python
# Adicione esta nova constante no seu código de configuração:
PASTA_PARA_APAGAR = r"C:\Users\jonathan\Desktop\AUTLAND\Para apagar"
# Certifique-se que a pasta existe:
if not os.path.exists(PASTA_PARA_APAGAR):
os.makedirs(PASTA_PARA_APAGAR)
# Função upload_video_to_youtube modificada (apenas o trecho final de remoção/movimentação do vídeo e thumbnail):
def upload_video_to_youtube(credentials_blob, title, description, tags, video_path, thumbnail_path,
publish_now, publish_at=None, category_id="22"):
# [seu código anterior...]
# -------------------------
# pós-upload (após imprimir info do upload):
print(f"[INFO] Upload finalizado, videoId: {response['id']}")
# MOVER o vídeo para a pasta de "Para apagar" (em vez de apagar diretamente)
try:
video_path_abs = os.path.realpath(video_path)
pasta_videos_abs = os.path.realpath(PASTA_VIDEOS_POSTAGEM)
if os.path.exists(video_path_abs) and video_path_abs.startswith(pasta_videos_abs):
nome_arquivo = os.path.basename(video_path_abs)
destino = os.path.join(PASTA_PARA_APAGAR, nome_arquivo)
# Se já existir um arquivo com o mesmo nome na pasta destino, renomear para evitar sobrescrita
if os.path.exists(destino):
base, ext = os.path.splitext(nome_arquivo)
contador = 1
while os.path.exists(destino):
destino = os.path.join(PASTA_PARA_APAGAR, f"{base}_{contador}{ext}")
contador +=1
os.rename(video_path_abs, destino)
print(f"Vídeo movido para a pasta 'Para apagar': {destino}")
except Exception as e:
print(f"Erro ao mover vídeo para 'Para apagar': {e}")
# Remover thumbnail normalmente (já estava removendo)
try:
if thumbnail_path and os.path.exists(thumbnail_path):
thumb_path_abs = os.path.realpath(thumbnail_path)
pasta_thumb_abs = os.path.realpath(PASTA_THUMBNAILS)
if thumb_path_abs.startswith(pasta_thumb_abs):
os.remove(thumb_path_abs)
print(f"Thumbnail removida: {thumb_path_abs}")
except Exception as e:
print(f"Erro ao remover thumbnail: {e}")
return response["id"]
Como funciona:
Após o upload, o arquivo de vídeo é movido com os.rename() da pasta original (POSTAGEM) para a pasta PASTA_PARA_APAGAR.
Caso já exista um arquivo com o mesmo nome na pasta de "Para apagar", ele renomeia adicionando sufixo _1, _2 etc., evitando sobrescrita.
A thumbnail continua a ser apagada normalmente.
Mover o arquivo é rápido, seguro, e reduz o problema de arquivos bloqueados no Windows.
Você controla manualmente a exclusão depois, como preferir.
Se quiser uma função para limpeza periódica da pasta Para apagar, posso ajudar a criar também!
Para uso é só substituir a função conforme acima no seu código.
Se precisar, posso fornecer o código completo com essa modificação — é só avisar!