Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,91 +1,112 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
-
import requests
|
| 4 |
import subprocess
|
|
|
|
| 5 |
import time
|
| 6 |
|
| 7 |
-
#
|
| 8 |
IG_USER_ID = os.environ.get("IG_USER_ID")
|
| 9 |
ACCESS_TOKEN = os.environ.get("IG_ACCESS_TOKEN")
|
| 10 |
|
| 11 |
-
def
|
| 12 |
-
if not
|
| 13 |
-
return "Nenhum vídeo recebido."
|
| 14 |
-
|
| 15 |
-
# 1. CONVERSÃO (WebM -> MP4)
|
| 16 |
-
# O gradio entrega o caminho do arquivo temporário em video_webm
|
| 17 |
-
output_path = video_webm.replace(".webm", ".mp4")
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
command = [
|
| 24 |
-
"ffmpeg", "-y",
|
| 25 |
-
"-
|
| 26 |
-
"-
|
|
|
|
|
|
|
|
|
|
| 27 |
output_path
|
| 28 |
]
|
| 29 |
|
| 30 |
subprocess.run(command, check=True)
|
| 31 |
|
| 32 |
-
#
|
| 33 |
-
# O
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
#
|
| 38 |
-
#
|
| 39 |
-
public_url = f"https://SEU_USER-SEU_SPACE.hf.space/file={output_path}"
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
#
|
| 44 |
-
|
| 45 |
payload = {
|
| 46 |
-
"media_type": "REELS",
|
| 47 |
-
"video_url":
|
| 48 |
-
"caption": "Vídeo
|
| 49 |
"access_token": ACCESS_TOKEN
|
| 50 |
}
|
| 51 |
|
| 52 |
-
|
| 53 |
-
if
|
| 54 |
-
return f"Erro
|
| 55 |
|
| 56 |
-
container_id =
|
| 57 |
|
| 58 |
-
#
|
| 59 |
status = "IN_PROGRESS"
|
| 60 |
while status == "IN_PROGRESS":
|
| 61 |
-
time.sleep(5)
|
| 62 |
status_url = f"https://graph.facebook.com/v19.0/{container_id}?fields=status_code&access_token={ACCESS_TOKEN}"
|
| 63 |
status_resp = requests.get(status_url).json()
|
| 64 |
-
status = status_resp.get(
|
| 65 |
-
print(f"Status
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
return "Erro no processamento do vídeo pelo Instagram."
|
| 69 |
|
| 70 |
-
#
|
| 71 |
-
|
| 72 |
pub_payload = {
|
| 73 |
"creation_id": container_id,
|
| 74 |
"access_token": ACCESS_TOKEN
|
| 75 |
}
|
| 76 |
|
| 77 |
-
|
| 78 |
|
| 79 |
-
if
|
| 80 |
-
return "
|
| 81 |
else:
|
| 82 |
-
return f"Erro
|
| 83 |
|
| 84 |
-
# Interface
|
| 85 |
demo = gr.Interface(
|
| 86 |
-
fn=
|
| 87 |
-
inputs=gr.Video(label="
|
| 88 |
-
outputs="text"
|
| 89 |
)
|
| 90 |
|
| 91 |
-
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
|
|
|
| 3 |
import subprocess
|
| 4 |
+
import requests
|
| 5 |
import time
|
| 6 |
|
| 7 |
+
# 1. Recuperar Segredos
|
| 8 |
IG_USER_ID = os.environ.get("IG_USER_ID")
|
| 9 |
ACCESS_TOKEN = os.environ.get("IG_ACCESS_TOKEN")
|
| 10 |
|
| 11 |
+
def processar_e_publicar(video_webm_path):
|
| 12 |
+
if not video_webm_path:
|
| 13 |
+
return "Erro: Nenhum vídeo recebido."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
# --- ETAPA A: CONVERSÃO (WebM -> MP4) ---
|
| 16 |
+
print("Iniciando conversão...")
|
| 17 |
+
output_filename = "video_final.mp4"
|
| 18 |
+
output_path = os.path.abspath(output_filename)
|
| 19 |
+
|
| 20 |
+
# Comando FFmpeg otimizado para Instagram
|
| 21 |
command = [
|
| 22 |
+
"ffmpeg", "-y",
|
| 23 |
+
"-i", video_webm_path,
|
| 24 |
+
"-c:v", "libx264", "-preset", "fast", "-crf", "23", # Video H.264
|
| 25 |
+
"-c:a", "aac", "-b:a", "128k", # Audio AAC
|
| 26 |
+
"-pix_fmt", "yuv420p", # Garante compatibilidade mobile
|
| 27 |
+
"-movflags", "+faststart",
|
| 28 |
output_path
|
| 29 |
]
|
| 30 |
|
| 31 |
subprocess.run(command, check=True)
|
| 32 |
|
| 33 |
+
# --- ETAPA B: GERAR URL PÚBLICA ---
|
| 34 |
+
# O Gradio serve arquivos estáticos na rota /file/
|
| 35 |
+
# Precisamos descobrir a URL base do Space dinamicamente ou montar manualmente
|
| 36 |
+
|
| 37 |
+
# Truque para pegar a URL do Space atual
|
| 38 |
+
# Se seu usuario é "Joao" e o space é "Bot", a url é https://joao-bot.hf.space
|
| 39 |
+
space_host = os.environ.get("SPACE_HOST") # O HF fornece isso auto em alguns casos
|
|
|
|
| 40 |
|
| 41 |
+
if not space_host:
|
| 42 |
+
# Fallback: Tenta construir baseado no user/space se estiver nas envs,
|
| 43 |
+
# senão, retornaremos o caminho para debug.
|
| 44 |
+
# Mas para simplificar, vamos assumir que o script roda e gera o arquivo local.
|
| 45 |
+
# O Gradio retorna o caminho, o cliente (App Builder) vai precisar da URL completa.
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
# A URL pública do arquivo no Gradio segue este padrão:
|
| 49 |
+
# https://{USER}-{SPACE_NAME}.hf.space/file={CAMINHO_ABSOLUTO}
|
| 50 |
+
# Vamos deixar o Gradio retornar o arquivo processado, e o próprio Gradio gera o link de download.
|
| 51 |
+
# PORÉM, para o Instagram, precisamos passar a URL texto.
|
| 52 |
+
|
| 53 |
+
# Vamos construir a URL pública manualmente para enviar ao Instagram
|
| 54 |
+
# ATENÇÃO: Substitua isso se o HF mudar a estrutura, mas o padrão atual é esse.
|
| 55 |
+
# Para automação total, vamos usar uma variável que você preenche ou pegamos do sistema
|
| 56 |
+
base_url = f"https://{os.environ.get('SPACE_AUTHOR_NAME')}-{os.environ.get('SPACE_REPO_NAME')}.hf.space"
|
| 57 |
+
video_public_url = f"{base_url}/file={output_path}"
|
| 58 |
+
|
| 59 |
+
print(f"URL Gerada para o Instagram: {video_public_url}")
|
| 60 |
+
|
| 61 |
+
# --- ETAPA C: PUBLICAR NO INSTAGRAM ---
|
| 62 |
+
print("Enviando para o Instagram...")
|
| 63 |
|
| 64 |
+
# 1. Criar Container
|
| 65 |
+
url_create = f"https://graph.facebook.com/v19.0/{IG_USER_ID}/media"
|
| 66 |
payload = {
|
| 67 |
+
"media_type": "REELS",
|
| 68 |
+
"video_url": video_public_url,
|
| 69 |
+
"caption": "Vídeo postado via App Builder 🚀 #AI #Automation",
|
| 70 |
"access_token": ACCESS_TOKEN
|
| 71 |
}
|
| 72 |
|
| 73 |
+
req = requests.post(url_create, data=payload)
|
| 74 |
+
if req.status_code != 200:
|
| 75 |
+
return f"Erro Instagram (Container): {req.text}"
|
| 76 |
|
| 77 |
+
container_id = req.json()['id']
|
| 78 |
|
| 79 |
+
# 2. Esperar processamento (Polling)
|
| 80 |
status = "IN_PROGRESS"
|
| 81 |
while status == "IN_PROGRESS":
|
| 82 |
+
time.sleep(5)
|
| 83 |
status_url = f"https://graph.facebook.com/v19.0/{container_id}?fields=status_code&access_token={ACCESS_TOKEN}"
|
| 84 |
status_resp = requests.get(status_url).json()
|
| 85 |
+
status = status_resp.get('status_code', 'ERROR')
|
| 86 |
+
print(f"Status: {status}")
|
| 87 |
+
if status == 'ERROR':
|
| 88 |
+
return "Erro: Instagram falhou ao processar o vídeo."
|
|
|
|
| 89 |
|
| 90 |
+
# 3. Publicar
|
| 91 |
+
url_publish = f"https://graph.facebook.com/v19.0/{IG_USER_ID}/media_publish"
|
| 92 |
pub_payload = {
|
| 93 |
"creation_id": container_id,
|
| 94 |
"access_token": ACCESS_TOKEN
|
| 95 |
}
|
| 96 |
|
| 97 |
+
final_req = requests.post(url_publish, data=pub_payload)
|
| 98 |
|
| 99 |
+
if final_req.status_code == 200:
|
| 100 |
+
return f"SUCESSO! Vídeo publicado. ID: {final_req.json()['id']}"
|
| 101 |
else:
|
| 102 |
+
return f"Erro Instagram (Publish): {final_req.text}"
|
| 103 |
|
| 104 |
+
# Interface (API)
|
| 105 |
demo = gr.Interface(
|
| 106 |
+
fn=processar_e_publicar,
|
| 107 |
+
inputs=gr.Video(label="Upload WebM"), # Recebe o vídeo
|
| 108 |
+
outputs="text" # Retorna a mensagem de sucesso/erro
|
| 109 |
)
|
| 110 |
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
demo.launch()
|