AlexandreScriptsMT commited on
Commit
3f205eb
·
verified ·
1 Parent(s): 95b12c5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -18
app.py CHANGED
@@ -1,24 +1,91 @@
1
  import gradio as gr
2
- import shutil
3
  import os
 
 
 
4
 
5
- # Define onde salvar (pasta temporária)
6
- def upload_file(file):
7
- if not file:
8
- return None
9
-
10
- # O Gradio recebe o arquivo num caminho temporário
11
- # Vamos mover para uma pasta pública estática se necessário,
12
- # mas o próprio Gradio já gera um link acessível via /file/
13
- return file.name # Retorna o caminho absoluto do arquivo no servidor
14
 
15
- # Cria uma interface API (sem interface visual pesada)
16
- with gr.Blocks() as demo:
17
- # Um componente invisível apenas para receber o arquivo
18
- file_input = gr.File()
19
- output_text = gr.Textbox()
20
-
21
- # Quando o arquivo sobe, retorna o caminho
22
- file_input.upload(upload_file, file_input, output_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  demo.launch()
 
1
  import gradio as gr
 
2
  import os
3
+ import requests
4
+ import subprocess
5
+ import time
6
 
7
+ # SEUS SEGREDOS (Configure isso nas Settings do Space em "Repository Secrets")
8
+ IG_USER_ID = os.environ.get("IG_USER_ID")
9
+ ACCESS_TOKEN = os.environ.get("IG_ACCESS_TOKEN")
 
 
 
 
 
 
10
 
11
+ def converter_e_publicar(video_webm):
12
+ if not video_webm:
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
+ # Comando FFmpeg para converter garantindo compatibilidade com Instagram
20
+ # -c:v libx264 (Vídeo H.264)
21
+ # -c:a aac (Áudio AAC)
22
+ # -pix_fmt yuv420p (Formato de pixel exigido pelo player mobile)
23
+ command = [
24
+ "ffmpeg", "-y", "-i", video_webm,
25
+ "-c:v", "libx264", "-c:a", "aac",
26
+ "-pix_fmt", "yuv420p", "-movflags", "+faststart",
27
+ output_path
28
+ ]
29
+
30
+ subprocess.run(command, check=True)
31
+
32
+ # 2. GERAR URL PÚBLICA (Truque do Gradio)
33
+ # O arquivo agora está salvo no servidor. Precisamos da URL completa.
34
+ # Em Spaces públicos, a URL segue esse padrão. Ajuste SEU_USER e SEU_SPACE.
35
+ # O Gradio expõe arquivos na pasta /file/
36
+ filename = os.path.basename(output_path)
37
+ # ATENÇÃO: O caminho interno do gradio costuma ser /tmp/gradio/...,
38
+ # a URL pública pega o caminho absoluto.
39
+ public_url = f"https://SEU_USER-SEU_SPACE.hf.space/file={output_path}"
40
+
41
+ # 3. PUBLICAR NO INSTAGRAM
42
+
43
+ # Passo A: Criar Container
44
+ url_container = f"https://graph.facebook.com/v19.0/{IG_USER_ID}/media"
45
+ payload = {
46
+ "media_type": "REELS", # Ou VIDEO
47
+ "video_url": public_url,
48
+ "caption": "Vídeo gerado automaticamente via Gemini App Builder 🚀",
49
+ "access_token": ACCESS_TOKEN
50
+ }
51
+
52
+ r = requests.post(url_container, data=payload)
53
+ if r.status_code != 200:
54
+ return f"Erro ao criar container: {r.text}"
55
+
56
+ container_id = r.json().get("id")
57
+
58
+ # Passo B: Esperar processamento (Polling)
59
+ status = "IN_PROGRESS"
60
+ while status == "IN_PROGRESS":
61
+ time.sleep(5) # Espera 5 segundos
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("status_code")
65
+ print(f"Status do vídeo: {status}")
66
+
67
+ if status == "ERROR":
68
+ return "Erro no processamento do vídeo pelo Instagram."
69
+
70
+ # Passo C: Publicar Oficialmente
71
+ publish_url = f"https://graph.facebook.com/v19.0/{IG_USER_ID}/media_publish"
72
+ pub_payload = {
73
+ "creation_id": container_id,
74
+ "access_token": ACCESS_TOKEN
75
+ }
76
+
77
+ final_r = requests.post(publish_url, data=pub_payload)
78
+
79
+ if final_r.status_code == 200:
80
+ return "Sucesso! Vídeo publicado no Instagram."
81
+ else:
82
+ return f"Erro na publicação final: {final_r.text}"
83
+
84
+ # Interface simples (API mode)
85
+ demo = gr.Interface(
86
+ fn=converter_e_publicar,
87
+ inputs=gr.Video(label="Envie seu WebM"),
88
+ outputs="text"
89
+ )
90
 
91
  demo.launch()