import gradio as gr
import os
import json
import requests
from datetime import datetime
import tempfile
import subprocess
import shutil
# Configuração - Carregando variáveis de ambiente (com .strip() para remover quebras de linha)
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN", "").strip()
GITHUB_REPO = os.environ.get("GITHUB_REPO", "").strip()
TELEGRAM_TOKEN = os.environ.get("TELEGRAM_TOKEN", "").strip()
TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "").strip()
DRIVE_FOLDER_ID = os.environ.get("GOOGLE_DRIVE_FOLDER_ID", "").strip()
# Debug: Mostrar configuração (sem revelar tokens completos)
print("="*60)
print("🔧 CONFIGURAÇÃO DO BOT 2")
print("="*60)
print(f"GITHUB_TOKEN: {'✅ Configurado' if GITHUB_TOKEN else '❌ NÃO configurado'}")
print(f"GITHUB_REPO: {GITHUB_REPO if GITHUB_REPO else '❌ NÃO configurado'}")
print(f"TELEGRAM_TOKEN: {'✅ Configurado' if TELEGRAM_TOKEN else '❌ NÃO configurado'}")
print(f"TELEGRAM_CHAT_ID: {TELEGRAM_CHAT_ID if TELEGRAM_CHAT_ID else '❌ NÃO configurado'}")
print("="*60)
def send_telegram(message):
"""Envia notificação para o Telegram"""
if not TELEGRAM_TOKEN or not TELEGRAM_CHAT_ID:
print("⚠️ Telegram não configurado - pulando notificação")
return
try:
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
data = {"chat_id": TELEGRAM_CHAT_ID, "text": message, "parse_mode": "HTML"}
response = requests.post(url, data=data, timeout=10)
if response.status_code == 200:
print("✅ Notificação Telegram enviada")
else:
print(f"⚠️ Erro ao enviar Telegram: {response.status_code}")
except Exception as e:
print(f"❌ Erro Telegram: {e}")
def get_github_file(filepath):
"""Baixa arquivo JSON do GitHub"""
print(f"📥 Tentando baixar: {filepath}")
print(f" Repositório: {GITHUB_REPO}")
if not GITHUB_TOKEN:
print("❌ GITHUB_TOKEN não configurado!")
return [], None
if not GITHUB_REPO:
print("❌ GITHUB_REPO não configurado!")
return [], None
try:
url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{filepath}"
print(f" URL: {url}")
headers = {
"Authorization": f"token {GITHUB_TOKEN}",
"Accept": "application/vnd.github.v3+json"
}
response = requests.get(url, headers=headers, timeout=15)
print(f" Status Code: {response.status_code}")
if response.status_code == 200:
import base64
content = base64.b64decode(response.json()["content"]).decode("utf-8")
data = json.loads(content)
print(f"✅ Arquivo baixado com sucesso: {len(data)} items")
return data, response.json().get("sha")
else:
print(f"❌ Erro ao baixar arquivo:")
print(f" Status: {response.status_code}")
print(f" Resposta: {response.text[:200]}")
return [], None
except Exception as e:
print(f"❌ Exceção em get_github_file: {e}")
import traceback
traceback.print_exc()
return [], None
def update_github_file(filepath, content, sha, message):
"""Atualiza arquivo no GitHub"""
print(f"📤 Atualizando: {filepath}")
if not GITHUB_TOKEN or not GITHUB_REPO:
print("❌ Credenciais GitHub não configuradas")
return False
try:
url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{filepath}"
headers = {
"Authorization": f"token {GITHUB_TOKEN}",
"Accept": "application/vnd.github.v3+json"
}
import base64
content_bytes = json.dumps(content, indent=2, ensure_ascii=False).encode("utf-8")
content_b64 = base64.b64encode(content_bytes).decode("utf-8")
data = {
"message": message,
"content": content_b64,
"sha": sha
}
response = requests.put(url, json=data, headers=headers, timeout=15)
if response.status_code in [200, 201]:
print(f"✅ Arquivo atualizado: {filepath}")
return True
else:
print(f"❌ Erro ao atualizar: {response.status_code}")
print(f" Resposta: {response.text[:200]}")
return False
except Exception as e:
print(f"❌ Exceção em update_github_file: {e}")
return False
def download_video(video_url, output_path):
"""Baixa vídeo do YouTube com múltiplas tentativas"""
try:
print(f" 📥 Iniciando download...")
# Lista de formatos em ordem de prioridade
format_options = [
"bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]",
"bestvideo[height<=720]+bestaudio/best[height<=720]",
"bestvideo[height<=480]+bestaudio/best[height<=480]",
"best[ext=mp4]/best",
]
for idx, fmt in enumerate(format_options, 1):
print(f" Tentativa {idx}/{len(format_options)}: formato '{fmt}'")
cmd = [
"yt-dlp",
"-f", fmt,
"-o", output_path,
"--no-warnings",
"--no-check-certificate",
"--no-playlist",
"--user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"--referer", "https://www.youtube.com/",
"--extractor-args", "youtube:player_client=android",
"--socket-timeout", "30",
"--retries", "3",
"--fragment-retries", "3",
video_url
]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
# Mostrar stdout e stderr para debug
if result.stdout:
print(f" STDOUT: {result.stdout[:500]}")
if result.stderr:
print(f" STDERR: {result.stderr[:500]}")
if os.path.exists(output_path) and os.path.getsize(output_path) > 100000:
size_mb = os.path.getsize(output_path) / 1024 / 1024
print(f" ✅ Download OK: {size_mb:.1f}MB (formato: {fmt})")
return True
else:
print(f" ⚠️ Formato '{fmt}' falhou")
print(f" Return code: {result.returncode}")
# Limpar arquivo parcial
if os.path.exists(output_path):
os.remove(output_path)
continue
except subprocess.TimeoutExpired:
print(f" ⏱️ Timeout no formato '{fmt}'")
if os.path.exists(output_path):
os.remove(output_path)
continue
# Se chegou aqui, todas as tentativas falharam
print(f" ❌ Todas as {len(format_options)} tentativas falharam")
return False
except Exception as e:
print(f" ❌ Erro crítico no download: {e}")
import traceback
traceback.print_exc()
return False
def convert_video(input_file, output_60s, output_120s):
"""Converte vídeo para formato vertical 9:16"""
try:
print(f" 🎨 Convertendo para formato vertical...")
# Versão 60s
cmd_60 = [
"ffmpeg", "-i", input_file,
"-vf", "scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2,setsar=1",
"-t", "60",
"-c:v", "libx264", "-preset", "medium", "-crf", "23",
"-c:a", "aac", "-b:a", "128k",
"-y", output_60s
]
subprocess.run(cmd_60, capture_output=True, timeout=180, check=True)
# Versão 120s
cmd_120 = [
"ffmpeg", "-i", input_file,
"-vf", "scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2,setsar=1",
"-t", "120",
"-c:v", "libx264", "-preset", "medium", "-crf", "23",
"-c:a", "aac", "-b:a", "128k",
"-y", output_120s
]
subprocess.run(cmd_120, capture_output=True, timeout=240, check=True)
if os.path.exists(output_60s) and os.path.exists(output_120s):
size_60 = os.path.getsize(output_60s) / 1024 / 1024
size_120 = os.path.getsize(output_120s) / 1024 / 1024
print(f" ✅ Conversão OK: 60s={size_60:.1f}MB, 120s={size_120:.1f}MB")
return True
else:
print(f" ❌ Arquivos de saída não foram criados")
return False
except subprocess.TimeoutExpired:
print(f" ❌ Timeout na conversão")
return False
except Exception as e:
print(f" ❌ Erro na conversão: {e}")
return False
def process_videos():
"""Função principal que processa vídeos pendentes"""
log = ["🤖 Bot 2 - Processamento Iniciado"]
log.append(f"⏰ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
log.append("")
print("\n" + "="*60)
print("🤖 BOT 2 - PROCESSAMENTO DE VÍDEOS")
print("="*60)
try:
# Verificar configuração
if not GITHUB_TOKEN:
msg = "❌ GITHUB_TOKEN não configurado nos secrets!"
log.append(msg)
print(msg)
send_telegram("\n".join(log))
return "\n".join(log)
if not GITHUB_REPO:
msg = "❌ GITHUB_REPO não configurado nos secrets!"
log.append(msg)
print(msg)
send_telegram("\n".join(log))
return "\n".join(log)
log.append(f"📂 Repositório: {GITHUB_REPO}")
# 1. Baixar pending_urls.json
print("\n📥 Baixando pending_urls.json...")
pending, pending_sha = get_github_file("data/pending_urls.json")
if not pending:
msg = "📭 Nenhum vídeo na fila (arquivo vazio ou erro ao baixar)"
log.append(msg)
print(msg)
send_telegram("\n".join(log))
return "\n".join(log)
log.append(f"📊 {len(pending)} vídeos no total")
print(f"📊 Total de vídeos: {len(pending)}")
# 2. Filtrar apenas pendentes (máx 2 por vez)
to_process = [v for v in pending if v.get("status") == "pending"][:2]
if not to_process:
msg = "✅ Todos os vídeos já foram processados"
log.append(msg)
print(msg)
send_telegram("\n".join(log))
return "\n".join(log)
log.append(f"🎬 Processando {len(to_process)} vídeos...")
log.append("")
print(f"🎬 Vídeos para processar: {len(to_process)}")
# 3. Baixar ready_to_post.json
print("📥 Baixando ready_to_post.json...")
ready_to_post, ready_sha = get_github_file("data/ready_to_post.json")
processed_count = 0
temp_dir = tempfile.mkdtemp()
print(f"📁 Diretório temporário: {temp_dir}")
for idx, video in enumerate(to_process, 1):
video_url = video.get("url")
video_id = video.get("videoid")
title = video.get("title", "Sem título")[:50]
log.append(f"{idx}/{len(to_process)} {title}...")
print(f"\n{'='*60}")
print(f"[{idx}/{len(to_process)}] Processando: {title}")
print(f"URL: {video_url}")
try:
# Download
input_file = os.path.join(temp_dir, f"{video_id}.mp4")
if not download_video(video_url, input_file):
log.append(" ❌ Erro no download")
continue
# Conversão
output_60s = os.path.join(temp_dir, f"{video_id}_60s.mp4")
output_120s = os.path.join(temp_dir, f"{video_id}_120s.mp4")
if not convert_video(input_file, output_60s, output_120s):
log.append(" ❌ Erro na conversão")
continue
# Marcar como processado
video["status"] = "processed"
video["processed_date"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Adicionar em ready_to_post
ready_to_post.append({
"url": video_url,
"videoid": video_id,
"title": video.get("title"),
"duration": video.get("duration"),
"local_path_60s": f"{video_id}_60s.mp4",
"local_path_120s": f"{video_id}_120s.mp4",
"processed_date": video["processed_date"],
"posted": False
})
processed_count += 1
log.append(" ✅ Processado com sucesso!")
print(f"✅ Vídeo {idx} processado com sucesso!")
# Limpar arquivo original para economizar espaço
try:
os.remove(input_file)
except:
pass
except Exception as e:
error_msg = f" ❌ Erro: {str(e)[:100]}"
log.append(error_msg)
print(error_msg)
import traceback
traceback.print_exc()
# Limpar diretório temporário
print(f"\n🧹 Limpando diretório temporário...")
shutil.rmtree(temp_dir, ignore_errors=True)
# 4. Atualizar GitHub
if processed_count > 0:
log.append("")
log.append(f"📤 Atualizando GitHub...")
print(f"\n📤 Atualizando arquivos no GitHub...")
success1 = update_github_file(
"data/pending_urls.json",
pending,
pending_sha,
f"Bot2: {processed_count} vídeos processados"
)
success2 = update_github_file(
"data/ready_to_post.json",
ready_to_post,
ready_sha,
f"Bot2: {processed_count} vídeos prontos para postar"
)
if success1 and success2:
log.append(" ✅ Arquivos atualizados no GitHub")
else:
log.append(" ⚠️ Erro ao atualizar alguns arquivos")
log.append("")
log.append(f"✅ Total processado: {processed_count} vídeos")
send_telegram("\n".join(log))
else:
log.append("")
log.append("⚠️ Nenhum vídeo foi processado com sucesso")
except Exception as e:
error_msg = f"❌ Erro fatal: {str(e)}"
log.append("")
log.append(error_msg)
print(f"\n❌ ERRO FATAL: {e}")
import traceback
traceback.print_exc()
send_telegram("\n".join(log))
print("="*60 + "\n")
return "\n".join(log)
# Interface Gradio
with gr.Blocks(title="Bot 2 - Processamento") as demo:
gr.Markdown("# 🤖 Bot 2 - Processamento de Vídeos Flashback")
gr.Markdown("Baixa vídeos do YouTube, converte para formato vertical 9:16 e prepara para postagem")
with gr.Row():
gr.Markdown(f"📂 **Repositório:** `{GITHUB_REPO if GITHUB_REPO else '❌ NÃO CONFIGURADO'}`")
with gr.Row():
process_btn = gr.Button("▶️ Processar Vídeos Agora", variant="primary", size="lg")
output_log = gr.Textbox(label="Log de Processamento", lines=30, max_lines=50)
process_btn.click(fn=process_videos, outputs=output_log)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)