Spaces:
Sleeping
Sleeping
File size: 2,629 Bytes
2d9a408 | 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 | """
alerting.py -- ops integration: Slack alert (real Incoming Webhook if the
`SLACK_WEBHOOK_URL` secret is set) with a clearly-labelled preview fallback
otherwise, plus an email preview. Mirrors llm_client.py's pattern: real
integration when configured, never silently pretends to have sent anything.
"""
import os
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Optional
try:
import requests
except ImportError: # pragma: no cover
requests = None
@dataclass
class AlertResult:
sent: bool
channel: str # "slack" | "preview-only"
message_preview: str
error: Optional[str] = None
def _fmt(zone: str, r: dict, score: float) -> str:
ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
return (
f":rotating_light: *Equipment anomaly detected* -- {zone}\n"
f"*Time:* {ts}\n*Anomaly score:* {score:.2f} / 1.00\n"
f"*Readings:* temp={r.get('motor_temp_c','?')}°C, vibration={r.get('vibration_mm_s','?')} mm/s, "
f"current={r.get('current_amps','?')} A, belt_speed={r.get('belt_speed_mps','?')} m/s\n"
f"*Recommended action:* flag for inspection before next shift (bearing wear / "
f"misalignment / motor overload pattern)."
)
def send_anomaly_alert(zone: str, reading: dict, score: float) -> AlertResult:
text = _fmt(zone, reading, score)
url = os.environ.get("SLACK_WEBHOOK_URL")
if not url:
return AlertResult(False, "preview-only", text)
if requests is None:
return AlertResult(False, "preview-only", text, "`requests` not installed")
try:
resp = requests.post(url, json={"text": text}, timeout=5)
if resp.status_code == 200:
return AlertResult(True, "slack", text)
return AlertResult(False, "preview-only", text, f"Slack HTTP {resp.status_code}: {resp.text[:200]}")
except Exception as e: # noqa: BLE001
return AlertResult(False, "preview-only", text, f"{type(e).__name__}: {e}")
def format_email_preview(zone: str, reading: dict, score: float) -> str:
ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
return (
f"To: maintenance-team@example.com\nSubject: [ALERT] Equipment anomaly detected -- {zone}\n\n"
f"Detected at {ts}. Anomaly score: {score:.2f} / 1.00\n"
f"Temp {reading.get('motor_temp_c','?')} C | Vibration {reading.get('vibration_mm_s','?')} mm/s | "
f"Current {reading.get('current_amps','?')} A | Belt {reading.get('belt_speed_mps','?')} m/s\n"
f"Recommended action: flag for inspection before the next shift.\n"
)
|