Update main.py
Browse files
main.py
CHANGED
|
@@ -801,6 +801,7 @@ async def process_account_endpoint(account: str):
|
|
| 801 |
if crop_url:
|
| 802 |
print(f"✨ [{time.time()-t_start:.1f}s] Usando vídeo já cortado (crop_content_url). Pulando processamento de crop.")
|
| 803 |
cropped_video_path = video_path_to_analyze
|
|
|
|
| 804 |
files_to_send.append(cropped_video_path)
|
| 805 |
|
| 806 |
# Adicionar o original como segundo anexo para contexto
|
|
@@ -907,8 +908,25 @@ async def process_account_endpoint(account: str):
|
|
| 907 |
|
| 908 |
result_json = titles_data if isinstance(titles_data, list) else [titles_data]
|
| 909 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 910 |
final_content_url = None
|
| 911 |
srt_for_export = None
|
|
|
|
| 912 |
if result_json:
|
| 913 |
result_data = result_json[0] if isinstance(result_json[0], dict) else {}
|
| 914 |
title_text = result_data.get("title", "")
|
|
@@ -1269,22 +1287,15 @@ LEGENDA ORIGINAL:
|
|
| 1269 |
if srt_for_export:
|
| 1270 |
response_data["subtitle_srt"] = srt_for_export
|
| 1271 |
|
| 1272 |
-
# Notificação de conclusão:
|
| 1273 |
try:
|
| 1274 |
import urllib.parse as _up
|
| 1275 |
_r0 = result_json[0] if result_json else {}
|
| 1276 |
legenda_done = _r0.get("description", "")
|
| 1277 |
-
|
| 1278 |
-
|
| 1279 |
-
|
| 1280 |
-
|
| 1281 |
-
if final_content_url:
|
| 1282 |
-
process_dc_msg += f"\n\n{final_content_url}"
|
| 1283 |
-
_process_dc_url = "https://discordmsg.arthurmribeiro51.workers.dev/?" + _up.urlencode({"mensagem": process_dc_msg, "id": discord_id})
|
| 1284 |
-
requests.get("https://proxy.onrecurve.com/", params={"quest": _process_dc_url}, timeout=5)
|
| 1285 |
-
|
| 1286 |
-
# ID 0 (sistema): marcou como finalizada + legenda completa
|
| 1287 |
-
_sys_end_msg = f"✅ **{agent_name}** marcou a postagem #{record_id} como finalizada.\n\n💬 **Legenda:** {legenda_done}"
|
| 1288 |
_sys_end_url = "https://discordmsg.arthurmribeiro51.workers.dev/?" + _up.urlencode({"mensagem": _sys_end_msg, "id": system_discord_id})
|
| 1289 |
requests.get("https://proxy.onrecurve.com/", params={"quest": _sys_end_url}, timeout=5)
|
| 1290 |
except Exception as _e:
|
|
@@ -1346,10 +1357,10 @@ async def safe_call_publish(account: str):
|
|
| 1346 |
|
| 1347 |
@app.api_route("/filter/{account}", methods=["GET", "POST"])
|
| 1348 |
async def filter_account_endpoint(account: str, background_tasks: BackgroundTasks):
|
| 1349 |
-
background_tasks.add_task(run_filter_account, account)
|
| 1350 |
return {"status": "ok", "message": "Solicitação enviada com sucesso! O processo continuará em background."}
|
| 1351 |
|
| 1352 |
-
async def run_filter_account(account: str):
|
| 1353 |
if not client:
|
| 1354 |
raise HTTPException(status_code=500, detail="Gemini client is not initialized")
|
| 1355 |
temp_file = None
|
|
@@ -1562,7 +1573,13 @@ async def run_filter_account(account: str):
|
|
| 1562 |
if not res_patch.ok:
|
| 1563 |
print(f"⚠️ Erro ao atualizar Supabase: {res_patch.text}")
|
| 1564 |
|
| 1565 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1566 |
return {
|
| 1567 |
"success": True,
|
| 1568 |
"record_id": record_id,
|
|
@@ -1578,7 +1595,7 @@ async def run_filter_account(account: str):
|
|
| 1578 |
import urllib.parse as _up
|
| 1579 |
sys_err_msg = f"<@1331348103806189675> 🚨 **ERRO CRÍTICO** ao filtrar post #{record_id if record_id else 'desconhecido'}:\n\n`{err_msg}`\n\nNão foi possível concluir a solicitação."
|
| 1580 |
sys_err_url = "https://discordmsg.arthurmribeiro51.workers.dev/?" + _up.urlencode({"mensagem": sys_err_msg, "id": system_discord_id})
|
| 1581 |
-
requests.get("https://proxy.onrecurve.com/", params={"quest":
|
| 1582 |
except Exception as dc_e:
|
| 1583 |
print(f"⚠️ Erro ao enviar Discord de falha: {dc_e}")
|
| 1584 |
|
|
@@ -1587,7 +1604,12 @@ async def run_filter_account(account: str):
|
|
| 1587 |
# Só salvará quando de fato o filtro não aprovar.
|
| 1588 |
pass
|
| 1589 |
|
| 1590 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1591 |
return JSONResponse(status_code=500, content={"error": f"Erro interno: {err_msg}", "next_steps": {"process": process_res}})
|
| 1592 |
finally:
|
| 1593 |
if temp_file and os.path.exists(temp_file.name): os.unlink(temp_file.name)
|
|
|
|
| 801 |
if crop_url:
|
| 802 |
print(f"✨ [{time.time()-t_start:.1f}s] Usando vídeo já cortado (crop_content_url). Pulando processamento de crop.")
|
| 803 |
cropped_video_path = video_path_to_analyze
|
| 804 |
+
cropped_video_url = crop_url
|
| 805 |
files_to_send.append(cropped_video_path)
|
| 806 |
|
| 807 |
# Adicionar o original como segundo anexo para contexto
|
|
|
|
| 908 |
|
| 909 |
result_json = titles_data if isinstance(titles_data, list) else [titles_data]
|
| 910 |
|
| 911 |
+
# ETAPA IMEDIATA: Notificar Discord (Vicky) e salvar Títulos no Supabase
|
| 912 |
+
try:
|
| 913 |
+
print(f"📢 [{time.time()-t_start:.1f}s] Notificando Discord sobre criação do conteúdo...")
|
| 914 |
+
import urllib.parse as _up
|
| 915 |
+
_r0 = result_json[0] if result_json else {}
|
| 916 |
+
process_natural_msg = _r0.get("process_message", "Oi! Acabei de criar o conteúdo e as legendas. Agora estou preparando o vídeo final... ⏳")
|
| 917 |
+
|
| 918 |
+
# Vicky manda a mensagem natural dela
|
| 919 |
+
vicky_url = "https://discordmsg.arthurmribeiro51.workers.dev/?" + _up.urlencode({"mensagem": process_natural_msg, "id": discord_id})
|
| 920 |
+
requests.get("https://proxy.onrecurve.com/", params={"quest": vicky_url}, timeout=5)
|
| 921 |
+
|
| 922 |
+
# Atualizar Supabase com dados parciais (Títulos/Descrição)
|
| 923 |
+
requests.patch(f"{supabase_url}/rest/v1/posts?id=eq.{record_id}", headers=headers, json={"result": result_json}, timeout=10)
|
| 924 |
+
except Exception as _early_dc:
|
| 925 |
+
print(f"⚠️ Erro na notificação imediata do Discord: {_early_dc}")
|
| 926 |
+
|
| 927 |
final_content_url = None
|
| 928 |
srt_for_export = None
|
| 929 |
+
cropped_video_url = record.get("crop_content_url") # Garantir que pegamos a URL do banco se já existir
|
| 930 |
if result_json:
|
| 931 |
result_data = result_json[0] if isinstance(result_json[0], dict) else {}
|
| 932 |
title_text = result_data.get("title", "")
|
|
|
|
| 1287 |
if srt_for_export:
|
| 1288 |
response_data["subtitle_srt"] = srt_for_export
|
| 1289 |
|
| 1290 |
+
# 10. Notificação de conclusão: Sistema (ID 0) avisando que mídia está pronta
|
| 1291 |
try:
|
| 1292 |
import urllib.parse as _up
|
| 1293 |
_r0 = result_json[0] if result_json else {}
|
| 1294 |
legenda_done = _r0.get("description", "")
|
| 1295 |
+
|
| 1296 |
+
# ID 0 (sistema): marcou como finalizada + legenda completa + link
|
| 1297 |
+
final_msg_add = f"\n\n🔗 **Vídeo Final:** {final_content_url}" if final_content_url else ""
|
| 1298 |
+
_sys_end_msg = f"✅ **{agent_name}** finalizou a renderização para o post #{record_id}.\n\n💬 **Legenda:** {legenda_done}{final_msg_add}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1299 |
_sys_end_url = "https://discordmsg.arthurmribeiro51.workers.dev/?" + _up.urlencode({"mensagem": _sys_end_msg, "id": system_discord_id})
|
| 1300 |
requests.get("https://proxy.onrecurve.com/", params={"quest": _sys_end_url}, timeout=5)
|
| 1301 |
except Exception as _e:
|
|
|
|
| 1357 |
|
| 1358 |
@app.api_route("/filter/{account}", methods=["GET", "POST"])
|
| 1359 |
async def filter_account_endpoint(account: str, background_tasks: BackgroundTasks):
|
| 1360 |
+
background_tasks.add_task(run_filter_account, account, background_tasks)
|
| 1361 |
return {"status": "ok", "message": "Solicitação enviada com sucesso! O processo continuará em background."}
|
| 1362 |
|
| 1363 |
+
async def run_filter_account(account: str, background_tasks: BackgroundTasks = None):
|
| 1364 |
if not client:
|
| 1365 |
raise HTTPException(status_code=500, detail="Gemini client is not initialized")
|
| 1366 |
temp_file = None
|
|
|
|
| 1573 |
if not res_patch.ok:
|
| 1574 |
print(f"⚠️ Erro ao atualizar Supabase: {res_patch.text}")
|
| 1575 |
|
| 1576 |
+
# Desacoplar processamento: não dar 'await' se tivermos background_tasks
|
| 1577 |
+
if background_tasks:
|
| 1578 |
+
background_tasks.add_task(safe_call_process, account)
|
| 1579 |
+
process_res = {"status": "started", "message": "Processamento iniciado em background."}
|
| 1580 |
+
else:
|
| 1581 |
+
process_res = await safe_call_process(account)
|
| 1582 |
+
|
| 1583 |
return {
|
| 1584 |
"success": True,
|
| 1585 |
"record_id": record_id,
|
|
|
|
| 1595 |
import urllib.parse as _up
|
| 1596 |
sys_err_msg = f"<@1331348103806189675> 🚨 **ERRO CRÍTICO** ao filtrar post #{record_id if record_id else 'desconhecido'}:\n\n`{err_msg}`\n\nNão foi possível concluir a solicitação."
|
| 1597 |
sys_err_url = "https://discordmsg.arthurmribeiro51.workers.dev/?" + _up.urlencode({"mensagem": sys_err_msg, "id": system_discord_id})
|
| 1598 |
+
requests.get("https://proxy.onrecurve.com/", params={"quest": _sys_url}, timeout=5)
|
| 1599 |
except Exception as dc_e:
|
| 1600 |
print(f"⚠️ Erro ao enviar Discord de falha: {dc_e}")
|
| 1601 |
|
|
|
|
| 1604 |
# Só salvará quando de fato o filtro não aprovar.
|
| 1605 |
pass
|
| 1606 |
|
| 1607 |
+
# Mesmo em erro no filtro, tentamos rodar o process (talvez pra outros posts)
|
| 1608 |
+
if background_tasks:
|
| 1609 |
+
background_tasks.add_task(safe_call_process, account)
|
| 1610 |
+
process_res = {"status": "started", "message": "Processamento iniciado em background."}
|
| 1611 |
+
else:
|
| 1612 |
+
process_res = await safe_call_process(account)
|
| 1613 |
return JSONResponse(status_code=500, content={"error": f"Erro interno: {err_msg}", "next_steps": {"process": process_res}})
|
| 1614 |
finally:
|
| 1615 |
if temp_file and os.path.exists(temp_file.name): os.unlink(temp_file.name)
|