Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215313 unmodified lines1671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981 unmodified line2002012022032042052062072082096 unmodified linesimport subprocessimport shutil# ConfiguraçãoGITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")GITHUB_REPO = os.environ.get("GITHUB_REPO", "disleysouzas-afk/flashback-automation")TELEGRAM_TOKEN = os.environ.get("TELEGRAM_TOKEN")TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID")DRIVE_FOLDER_ID = os.environ.get("GOOGLE_DRIVE_FOLDER_ID")def send_telegram(message):"""Envia notificação para o Telegram"""if not TELEGRAM_TOKEN or not TELEGRAM_CHAT_ID:returntry:url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"data = {"chat_id": TELEGRAM_CHAT_ID, "text": message, "parse_mode": "HTML"}requests.post(url, data=data, timeout=10)except Exception as e:print(f"Erro Telegram: {e}")def get_github_file(filepath):"""Baixa arquivo JSON do GitHub"""try:url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{filepath}"headers = {"Authorization": f"token {GITHUB_TOKEN}"}response = requests.get(url, headers=headers, timeout=15)if response.status_code == 200:import base64content = base64.b64decode(response.json()["content"]).decode("utf-8")return json.loads(content), response.json().get("sha")return [], Noneexcept Exception as e:print(f"Erro get_github_file: {e}")return [], Nonedef update_github_file(filepath, content, sha, message):"""Atualiza arquivo no GitHub"""try:url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{filepath}"headers = {"Authorization": f"token {GITHUB_TOKEN}"}import base64content_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)return response.status_code in [200, 201]except Exception as e:print(f"Erro update_github_file: {e}")return Falsedef download_video(video_url, output_path):"""Baixa vídeo do YouTube"""try:cmd = ["yt-dlp", "-f", "best[height<=720][ext=mp4]", "-o", output_path, "--no-warnings", video_url]subprocess.run(cmd, capture_output=True, text=True, timeout=300)if os.path.exists(output_path) and os.path.getsize(output_path) > 10000:print(f"✅ Download OK: {os.path.getsize(output_path)/1024/1024:.1f}MB")return Truereturn Falseexcept Exception as e:print(f"❌ Erro download: {e}")return Falsedef convert_video(input_file, output_60s, output_120s):"""Converte vídeo para formato vertical 9:16"""try:# Versão 60scmd_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)# Versão 120scmd_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)if os.path.exists(output_60s) and os.path.exists(output_120s):print("✅ Conversão OK")return Truereturn Falseexcept Exception as e:print(f"❌ Erro conversão: {e}")return Falsedef process_videos():"""Função principal que processa vídeos pendentes"""log = ["<b>🤖 Bot 2 - Processamento Iniciado</b>"]log.append(f"⏰ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")print("=" * 60)print("BOT 2 - PROCESSAMENTO DE VÍDEOS")print("=" * 60)try:if not GITHUB_TOKEN:log.append("❌ GITHUB_TOKEN não configurado")send_telegram("\n".join(log))return "\n".join(log)# 1. Baixar pending_urls.jsonprint("📥 Baixando pending_urls.json...")pending, pending_sha = get_github_file("data/pending_urls.json")if not pending:log.append("📭 Nenhum vídeo na fila")send_telegram("\n".join(log))return "\n".join(log)log.append(f"📊 {len(pending)} vídeos na fila")# 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:log.append("✅ Todos os vídeos já foram processados")send_telegram("\n".join(log))return "\n".join(log)log.append(f"🎬 Processando {len(to_process)} vídeos...")# 3. Baixar ready_to_post.jsonready_to_post, ready_sha = get_github_file("data/ready_to_post.json")processed_count = 0temp_dir = tempfile.mkdtemp()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"\n{idx}/{len(to_process)} {title}...")print(f"\n[{idx}/{len(to_process)}] Processando: {title}")try:# Downloadprint("📥 Baixando vídeo...")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ãoprint("🎨 Convertendo para vertical...")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 processado13 unmodified lines})processed_count += 1log.append("✅ Processado com sucesso!")# Limpar arquivo originalos.remove(input_file)except Exception as e:log.append(f"❌ Erro: {str(e)[:100]}")print(f"Erro: {e}")# Limpar diretório temporárioshutil.rmtree(temp_dir, ignore_errors=True)# 4. Atualizar GitHubif processed_count > 0:print("📤 Atualizando GitHub...")update_github_file("data/pending_urls.json", pending, pending_sha, f"Bot2: {processed_count} vídeos processados")update_github_file("data/ready_to_post.json", ready_to_post, ready_sha, f"Bot2: {processed_count} vídeos prontos para postar")log.append(f"\n<b>✅ Total processado: {processed_count} vídeos</b>")send_telegram("\n".join(log))except Exception as e:log.append(f"\n<b>❌ Erro fatal:</b> {str(e)}")send_telegram("\n".join(log))print("=" * 60)return "\n".join(log)# Interface Gradio1 unmodified linegr.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():process_btn = gr.Button("▶️ Processar Vídeos Agora", variant="primary", size="lg")output_log = gr.Textbox(label="Log de Processamento", lines=25, max_lines=50)process_btn.click(fn=process_videos, outputs=output_log)6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728813 unmodified lines3023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693701 unmodified line3723733743753763773783793803813823833846 unmodified linesimport subprocessimport shutil# Configuração - Carregando variáveis de ambienteGITHUB_TOKEN = os.environ.get("GITHUB_TOKEN", "")GITHUB_REPO = os.environ.get("GITHUB_REPO", "")TELEGRAM_TOKEN = os.environ.get("TELEGRAM_TOKEN", "")TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "")DRIVE_FOLDER_ID = os.environ.get("GOOGLE_DRIVE_FOLDER_ID", "")# 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")returntry: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 [], Noneif not GITHUB_REPO:print("❌ GITHUB_REPO não configurado!")return [], Nonetry: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 base64content = 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 [], Noneexcept Exception as e:print(f"❌ Exceção em get_github_file: {e}")import tracebacktraceback.print_exc()return [], Nonedef 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 Falsetry:url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{filepath}"headers = {"Authorization": f"token {GITHUB_TOKEN}","Accept": "application/vnd.github.v3+json"}import base64content_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 Trueelse:print(f"❌ Erro ao atualizar: {response.status_code}")print(f" Resposta: {response.text[:200]}")return Falseexcept Exception as e:print(f"❌ Exceção em update_github_file: {e}")return Falsedef download_video(video_url, output_path):"""Baixa vídeo do YouTube"""try:print(f" 📥 Iniciando download...")cmd = ["yt-dlp","-f", "best[height<=720][ext=mp4]","-o", output_path,"--no-warnings","--no-check-certificate",video_url]result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)if os.path.exists(output_path) and os.path.getsize(output_path) > 10000:size_mb = os.path.getsize(output_path) / 1024 / 1024print(f" ✅ Download OK: {size_mb:.1f}MB")return Trueelse:print(f" ❌ Download falhou ou arquivo muito pequeno")if result.stderr:print(f" Erro: {result.stderr[:200]}")return Falseexcept subprocess.TimeoutExpired:print(f" ❌ Timeout no download (>5 minutos)")return Falseexcept Exception as e:print(f" ❌ Erro no download: {e}")return Falsedef 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 60scmd_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 120scmd_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 / 1024size_120 = os.path.getsize(output_120s) / 1024 / 1024print(f" ✅ Conversão OK: 60s={size_60:.1f}MB, 120s={size_120:.1f}MB")return Trueelse:print(f" ❌ Arquivos de saída não foram criados")return Falseexcept subprocess.TimeoutExpired:print(f" ❌ Timeout na conversão")return Falseexcept Exception as e:print(f" ❌ Erro na conversão: {e}")return Falsedef process_videos():"""Função principal que processa vídeos pendentes"""log = ["<b>🤖 Bot 2 - Processamento Iniciado</b>"]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çãoif 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.jsonprint("\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.jsonprint("📥 Baixando ready_to_post.json...")ready_to_post, ready_sha = get_github_file("data/ready_to_post.json")processed_count = 0temp_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"<b>{idx}/{len(to_process)}</b> {title}...")print(f"\n{'='*60}")print(f"[{idx}/{len(to_process)}] Processando: {title}")print(f"URL: {video_url}")try:# Downloadinput_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ãooutput_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 processado13 unmodified lines})processed_count += 1log.append(" ✅ Processado com sucesso!")print(f"✅ Vídeo {idx} processado com sucesso!")# Limpar arquivo original para economizar espaçotry:os.remove(input_file)except:passexcept Exception as e:error_msg = f" ❌ Erro: {str(e)[:100]}"log.append(error_msg)print(error_msg)import tracebacktraceback.print_exc()# Limpar diretório temporárioprint(f"\n🧹 Limpando diretório temporário...")shutil.rmtree(temp_dir, ignore_errors=True)# 4. Atualizar GitHubif 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"<b>✅ Total processado: {processed_count} vídeos</b>")send_telegram("\n".join(log))else:log.append("")log.append("⚠️ Nenhum vídeo foi processado com sucesso")except Exception as e:error_msg = f"<b>❌ Erro fatal:</b> {str(e)}"log.append("")log.append(error_msg)print(f"\n❌ ERRO FATAL: {e}")import tracebacktraceback.print_exc()send_telegram("\n".join(log))print("="*60 + "\n")return "\n".join(log)# Interface Gradio1 unmodified linegr.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)
app.py+229-54