Update main.py
Browse files
main.py
CHANGED
|
@@ -257,6 +257,22 @@ async def process_account_endpoint(account: str):
|
|
| 257 |
comments = record.get("comments") # Se existir no banco, pode ser uma lista
|
| 258 |
contains_image = record.get("contains_image", False)
|
| 259 |
filter_message = record.get("filter_message", "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
if not video_url:
|
| 262 |
raise HTTPException(status_code=400, detail=f"Registro ID {record_id} falhou: ig_post_url inválida.")
|
|
@@ -766,21 +782,38 @@ async def run_filter_account(account: str):
|
|
| 766 |
if not url_to_download:
|
| 767 |
raise HTTPException(status_code=400, detail=f"Registro ID {record_id} falhou: ig_post_url inválida.")
|
| 768 |
|
|
|
|
| 769 |
try:
|
| 770 |
-
import urllib.parse
|
| 771 |
sys_msg = f"🏃♀️ **{agent_name}** começou a filtrar uma postagem...\n\n📎 **Mídia:** {url_to_download}"
|
| 772 |
sys_target_url = "https://discordmsg.arthurmribeiro51.workers.dev/?" + urllib.parse.urlencode({
|
| 773 |
"mensagem": sys_msg,
|
| 774 |
"id": system_discord_id
|
| 775 |
})
|
| 776 |
-
requests.get(
|
| 777 |
-
"https://proxy.onrecurve.com/",
|
| 778 |
-
params={"quest": sys_target_url},
|
| 779 |
-
timeout=5
|
| 780 |
-
)
|
| 781 |
except Exception as e:
|
| 782 |
print(f"⚠️ Erro ao enviar mensagem de sistema para o Discord: {e}")
|
| 783 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 784 |
print(f"📥 Baixando mídia para filtro: {url_to_download}")
|
| 785 |
response = download_file_with_retry(url_to_download, timeout=600)
|
| 786 |
|
|
@@ -798,6 +831,8 @@ async def run_filter_account(account: str):
|
|
| 798 |
media_path_to_analyze = temp_file.name
|
| 799 |
cropped_file_path = None
|
| 800 |
|
|
|
|
|
|
|
| 801 |
# Se for imagem, faz o crop e prepara dois anexos
|
| 802 |
if 'image' in content_type:
|
| 803 |
print(f"✂️ Processando imagem: detectando e cortando...")
|
|
@@ -816,6 +851,9 @@ async def run_filter_account(account: str):
|
|
| 816 |
date_str=time.strftime('%d/%m/%Y'),
|
| 817 |
contexto_add=contexto_add
|
| 818 |
)
|
|
|
|
|
|
|
|
|
|
| 819 |
|
| 820 |
# get_gemini_model("flash") chamará "Model.G_3_0_FLASH", que é o modelo Flash rápido.
|
| 821 |
# A demora de alguns segundos é comum porque a mídia precisa ser enviada e processada.
|
|
|
|
| 257 |
comments = record.get("comments") # Se existir no banco, pode ser uma lista
|
| 258 |
contains_image = record.get("contains_image", False)
|
| 259 |
filter_message = record.get("filter_message", "")
|
| 260 |
+
shortcode = record.get("ig_id")
|
| 261 |
+
|
| 262 |
+
if not comments and shortcode:
|
| 263 |
+
try:
|
| 264 |
+
# Chama a API do worker para pegar os comentários se for necessário
|
| 265 |
+
print(f"📥 Buscando comentários do post {shortcode}...")
|
| 266 |
+
bot_worker_url = "https://bot.arthurmribeiro51.workers.dev/comments"
|
| 267 |
+
c_res = requests.get(bot_worker_url, params={"shortcode": shortcode}, timeout=15)
|
| 268 |
+
if c_res.ok:
|
| 269 |
+
c_data = c_res.json()
|
| 270 |
+
fetched_comments = c_data.get("comments", [])
|
| 271 |
+
if fetched_comments:
|
| 272 |
+
comments = fetched_comments
|
| 273 |
+
print(f"✅ Encontrado {len(comments)} comentários para o post.")
|
| 274 |
+
except Exception as e:
|
| 275 |
+
print(f"⚠️ Erro ao buscar comentários: {e}")
|
| 276 |
|
| 277 |
if not video_url:
|
| 278 |
raise HTTPException(status_code=400, detail=f"Registro ID {record_id} falhou: ig_post_url inválida.")
|
|
|
|
| 782 |
if not url_to_download:
|
| 783 |
raise HTTPException(status_code=400, detail=f"Registro ID {record_id} falhou: ig_post_url inválida.")
|
| 784 |
|
| 785 |
+
import urllib.parse
|
| 786 |
try:
|
|
|
|
| 787 |
sys_msg = f"🏃♀️ **{agent_name}** começou a filtrar uma postagem...\n\n📎 **Mídia:** {url_to_download}"
|
| 788 |
sys_target_url = "https://discordmsg.arthurmribeiro51.workers.dev/?" + urllib.parse.urlencode({
|
| 789 |
"mensagem": sys_msg,
|
| 790 |
"id": system_discord_id
|
| 791 |
})
|
| 792 |
+
requests.get("https://proxy.onrecurve.com/", params={"quest": sys_target_url}, timeout=5)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 793 |
except Exception as e:
|
| 794 |
print(f"⚠️ Erro ao enviar mensagem de sistema para o Discord: {e}")
|
| 795 |
|
| 796 |
+
# Buscar duplicados para verificação rigorosa (últimos 50 posts publicados)
|
| 797 |
+
print("🔍 Buscando as últimas postagens para evitar duplicação...")
|
| 798 |
+
dups_url = f"{supabase_url}/rest/v1/posts?select=result&account_target=eq.{account}&published=eq.true&result=not.is.null&limit=50&order=created_at.desc"
|
| 799 |
+
res_dups = requests.get(dups_url, headers=headers, timeout=10)
|
| 800 |
+
recent_posts_text = ""
|
| 801 |
+
if res_dups.ok:
|
| 802 |
+
dups = res_dups.json()
|
| 803 |
+
dup_list = []
|
| 804 |
+
for d in dups:
|
| 805 |
+
res = d.get("result")
|
| 806 |
+
if res and isinstance(res, list) and len(res) > 0:
|
| 807 |
+
r0 = res[0] if isinstance(res[0], dict) else {}
|
| 808 |
+
t = r0.get("title", "")
|
| 809 |
+
desc = r0.get("description", "")
|
| 810 |
+
if t or desc:
|
| 811 |
+
dup_list.append(f"Título: {t}\nDescrição: {desc}")
|
| 812 |
+
if dup_list:
|
| 813 |
+
recent_posts_text = "\n\n=== ATENÇÃO: VERIFICAÇÃO RIGOROSA DE DUPLICAÇÃO ===\nVerifique rigorosamente se o conteúdo atual (vídeo/imagem e contexto) relata ou mostra EXATAMENTE a mesma situação de alguma dessas postagens recentes que já fizemos. Se for repetido e já tivermos publicado, REJEITE IMEDIATAMENTE! Histórico recente de postagens:\n"
|
| 814 |
+
for i, text in enumerate(dup_list, 1):
|
| 815 |
+
recent_posts_text += f"\nPost {i}:\n{text}\n"
|
| 816 |
+
|
| 817 |
print(f"📥 Baixando mídia para filtro: {url_to_download}")
|
| 818 |
response = download_file_with_retry(url_to_download, timeout=600)
|
| 819 |
|
|
|
|
| 831 |
media_path_to_analyze = temp_file.name
|
| 832 |
cropped_file_path = None
|
| 833 |
|
| 834 |
+
# ... logic continues inside the function
|
| 835 |
+
|
| 836 |
# Se for imagem, faz o crop e prepara dois anexos
|
| 837 |
if 'image' in content_type:
|
| 838 |
print(f"✂️ Processando imagem: detectando e cortando...")
|
|
|
|
| 851 |
date_str=time.strftime('%d/%m/%Y'),
|
| 852 |
contexto_add=contexto_add
|
| 853 |
)
|
| 854 |
+
|
| 855 |
+
if recent_posts_text:
|
| 856 |
+
prompt += recent_posts_text
|
| 857 |
|
| 858 |
# get_gemini_model("flash") chamará "Model.G_3_0_FLASH", que é o modelo Flash rápido.
|
| 859 |
# A demora de alguns segundos é comum porque a mídia precisa ser enviada e processada.
|