Spaces:
Paused

miracle / scripts /worker_dashboard.py
dushyantsingh0
backend stabilization
4405ca9
Raw History Blame Contribute Delete
3.05 kB
import asyncio
import os
import sys
from datetime import datetime
# Add project root to sys.path
sys.path.append(os.getcwd())
# Ensure all models are registered and SQLAlchemy is ready
from sqlalchemy import select
from core.database import async_session_factory
from models.ai_interaction import AIInteraction
from core.config import get_settings
settings = get_settings()
GREEN = "\033[92m"
RED = "\033[91m"
CYAN = "\033[96m"
YELLOW = "\033[93m"
RESET = "\033[0m"
BOLD = "\033[1m"
def format_time(dt: datetime):
return dt.strftime("%H:%M:%S")
async def get_recent_ai_tasks(limit=10):
async with async_session_factory() as db:
stmt = select(AIInteraction).order_by(AIInteraction.created_at.desc()).limit(limit)
result = await db.execute(stmt)
return result.scalars().all()
async def monitor_loop():
print(f"{BOLD}{CYAN}=== AI PROCESSING DASHBOARD (RESILIENT) ==={RESET}")
print(f"Monitoring: {settings.REDIS_URL}")
print("Schema status: Synchronized")
print("Press Ctrl+C to stop.\n")
seen_ids = set()
while True:
try:
tasks = await get_recent_ai_tasks()
# Print new tasks (newest last)
for task in reversed(tasks):
if task.id not in seen_ids:
# Robust status handling
status = (task.status or "success").upper()
status_color = GREEN if status == "SUCCESS" else RED
# Robust duration handling
duration_data = task.duration_ms or {}
duration = duration_data.get("total", "??")
print(f"[{format_time(task.created_at)}] "
f"{BOLD}{CYAN}{task.agent_name:<20}{RESET} | "
f"Ticket: {str(task.ticket_id)[:8]} | "
f"Status: {status_color}{status:<8}{RESET} | "
f"Duration: {duration}ms")
if status == "ERROR":
error_detail = (task.output_data or {}).get("error", "Unknown Fault")
print(f" {RED}FAULT DETAIL: {error_detail}{RESET}")
seen_ids.add(task.id)
# Keep seen_ids from growing too large
if len(seen_ids) > 100:
seen_ids = set(list(seen_ids)[-50:])
await asyncio.sleep(2)
except KeyboardInterrupt:
print(f"\n{BOLD}{YELLOW}Dashboard stopped by user.{RESET}")
break
except Exception as e:
# This handles cases where SQLAlchemy mappers are still initializing
print(f"{YELLOW}Waiting for database synchronization... ({str(e)[:50]}){RESET}")
await asyncio.sleep(5)
if __name__ == "__main__":
try:
asyncio.run(monitor_loop())
except KeyboardInterrupt:
pass
finally:
print(f"{RESET}")