File size: 2,628 Bytes
82283a2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | import os
import httpx
import asyncio
SUPABASE_URL = os.environ.get("SUPABASE_URL", "")
SUPABASE_KEY = os.environ.get("SUPABASE_KEY", "")
HEADERS = {
"apikey": SUPABASE_KEY,
"Authorization": f"Bearer {SUPABASE_KEY}",
"Content-Type": "application/json",
"Prefer": "return=minimal"
}
async def insert(table: str, data: dict):
"""Insert data ke Supabase"""
if not SUPABASE_URL or not SUPABASE_KEY:
return False
try:
async with httpx.AsyncClient(timeout=10) as client:
response = await client.post(
f"{SUPABASE_URL}/rest/v1/{table}",
headers=HEADERS,
json=data
)
return response.status_code in [200, 201]
except Exception:
return False
async def fetch(table: str, limit: int = 50) -> list:
"""Fetch data dari Supabase"""
if not SUPABASE_URL or not SUPABASE_KEY:
return []
try:
async with httpx.AsyncClient(timeout=10) as client:
response = await client.get(
f"{SUPABASE_URL}/rest/v1/{table}",
headers={**HEADERS, "Prefer": "return=representation"},
params={"order": "created_at.desc", "limit": limit}
)
if response.status_code == 200:
return response.json()
except Exception:
pass
return []
async def log_activity(action: str, details: str = ""):
"""Simpan activity log ke Supabase"""
await insert("activity_log", {"action": action, "details": details})
async def log_chat(role: str, message: str, provider: str = ""):
"""Simpan chat history ke Supabase"""
await insert("chat_history", {"role": role, "message": message, "provider": provider})
async def log_module_output(module_name: str, topic: str, output: str, provider: str = ""):
"""Simpan output modul ke Supabase"""
await insert("module_output", {
"module_name": module_name,
"topic": topic,
"output": output,
"provider": provider
})
async def keepalive_ping():
"""Ping untuk keepalive log"""
await insert("keepalive_log", {"status": "alive"})
async def start_keepalive(space_url: str = ""):
"""Auto ping setiap 5 menit biar Space tidak sleep"""
while True:
try:
# Ping Supabase
await keepalive_ping()
# Ping HF Space sendiri
if space_url:
async with httpx.AsyncClient(timeout=10) as client:
await client.get(space_url)
except Exception:
pass
await asyncio.sleep(300) # setiap 5 menit |