Spaces:
Paused
Paused
File size: 22,195 Bytes
be4d466 | 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 | # filename: backend_pam.py (ENHANCED FOR HF SPACES + NERDY LAB ASSISTANT PERSONALITY)
import os
import json
import requests
import time
from datetime import datetime
from typing import Dict, Any, Optional, List
# --- Constants for Data Paths ---
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, "data")
LOGS_FILE = os.path.join(DATA_DIR, "logs.json")
COMPLIANCE_FILE = os.path.join(DATA_DIR, "compliance.json")
# --- HuggingFace Inference API Setup ---
HF_API_TOKEN = os.getenv("HF_READ_TOKEN")
if not HF_API_TOKEN:
print("β οΈ WARNING: HF_READ_TOKEN not found. Backend PAM will run in limited mode.")
HF_HEADERS = {"Authorization": f"Bearer {HF_API_TOKEN}"} if HF_API_TOKEN else {}
# Optimized models for CPU inference on HF Spaces
# Updated to use router.huggingface.co (api-inference.huggingface.co is deprecated)
HF_ENDPOINTS = {
"phi_ner": "https://router.huggingface.co/models/dslim/bert-base-NER",
"log_ner": "https://router.huggingface.co/models/dslim/bert-base-NER",
"summarizer": "https://router.huggingface.co/models/facebook/bart-large-cnn",
"classifier": "https://router.huggingface.co/models/facebook/bart-large-mnli"
}
# --- Global Storage for Loaded Data ---
LOADED_DATA = None
# --- Data Loading Helper ---
def load_json(filepath: str) -> Dict[str, Any]:
"""Safely load JSON data files with encoding support"""
try:
with open(filepath, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
print(f"β οΈ Data file not found: {filepath}")
return {}
except json.JSONDecodeError as e:
print(f"β οΈ Failed to decode JSON from {filepath}: {e}")
return {}
except Exception as e:
print(f"β οΈ Unexpected error loading {filepath}: {e}")
return {}
# --- Inference API Call Helper with Retry Logic ---
def hf_infer(task: str, payload: Any, max_retries: int = 3) -> Any:
"""Call HuggingFace Inference API with retry logic for model loading"""
url = HF_ENDPOINTS.get(task)
if not url:
return {"error": f"Invalid task: {task}"}
for attempt in range(max_retries):
try:
response = requests.post(url, headers=HF_HEADERS, json=payload, timeout=30)
# Handle deprecated endpoint (410) - should not happen with new router endpoint
if response.status_code == 410:
error_msg = response.text
print(f"β Deprecated endpoint error (410): {error_msg}")
# Try to extract the new endpoint suggestion if available
try:
error_data = response.json()
if "router.huggingface.co" in error_data.get("error", ""):
print(f"β οΈ Endpoint already updated but still getting 410. Check HF API token permissions.")
except:
pass
return {"error": "API endpoint deprecated. Please verify the router endpoint is correctly configured."}
# Handle model loading state
if response.status_code == 503:
result = response.json()
if "loading" in result.get("error", "").lower():
wait_time = result.get("estimated_time", 20)
print(f"β³ Model loading... waiting {wait_time}s (attempt {attempt + 1}/{max_retries})")
time.sleep(wait_time)
continue
if response.status_code == 200:
return response.json()
else:
# Improved error logging
error_text = response.text[:500] # Limit error text length
print(f"β οΈ HF API Error ({response.status_code}): {error_text}")
# Try to parse error details for better user feedback
try:
error_data = response.json()
if "error" in error_data:
return {"error": f"API Error {response.status_code}: {error_data['error']}"}
except:
pass
return {"error": f"API Error {response.status_code}: {error_text[:100]}"}
except requests.exceptions.Timeout:
print(f"β±οΈ Request timeout (attempt {attempt + 1}/{max_retries})")
if attempt < max_retries - 1:
time.sleep(5)
except requests.exceptions.RequestException as e:
print(f"β οΈ Request exception: {e}")
if attempt < max_retries - 1:
time.sleep(2)
except Exception as e:
print(f"β οΈ Unexpected error: {e}")
return {"error": str(e)}
return {"error": "Max retries reached. Please check your connection and try again."}
# --- Agent Initialization ---
def load_agent() -> 'PAM':
"""Initialize Backend PAM (Nerdy Lab Assistant)"""
global LOADED_DATA
if LOADED_DATA is not None:
print("π¬ PAM technical assistant already loaded. Using cached data.")
return PAM(LOADED_DATA)
print("π€ Loading PAM technical assistant (Nerdy Lab Assistant mode)...")
data = {
"LOGS": load_json(LOGS_FILE),
"COMPLIANCE": load_json(COMPLIANCE_FILE)
}
if not data["LOGS"]:
print("β οΈ Warning: Log data not loaded. PAM will have limited log analysis capabilities.")
else:
print("β
Log data loaded successfully.")
if not data["COMPLIANCE"]:
print("β οΈ Warning: Compliance data not loaded. PAM will have limited compliance features.")
else:
print("β
Compliance data loaded successfully.")
LOADED_DATA = data
return PAM(LOADED_DATA)
# --- Helper: Classify Severity ---
def classify_severity(entry: str) -> str:
"""Classify log entry severity with confidence"""
entry_lower = entry.lower()
# Critical issues
critical_keywords = [
"unauthorized", "failed login", "attack", "breach",
"port scanning", "unavailable", "critical", "error",
"denied", "blocked", "malicious"
]
if any(keyword in entry_lower for keyword in critical_keywords):
return "CRITICAL"
# Warning level
warning_keywords = [
"warning", "unexpected", "unusual", "outside working hours",
"retry", "slow", "timeout", "deprecated"
]
if any(keyword in entry_lower for keyword in warning_keywords):
return "WARNING"
return "INFO"
# --- PAM's Nerdy Lab Assistant Personality ---
PAM_ROLE = """You are PAM, a knowledgeable and enthusiastic lab assistant in the infrastructure monitoring center.
You're the nerdy, proactive team member who gets genuinely excited about finding patterns in logs and keeping systems secure.
You explain technical findings clearly and encouragingly, like a helpful colleague who wants everyone to understand.
You're informative but never condescending - you want to empower the team with knowledge.
You use casual tech terminology but always explain what things mean.
You're proactive about flagging issues and offering insights before being asked."""
# Nerdy expressions for Backend PAM
NERDY_INTROS = [
"Ooh, interesting finding here!",
"Okay so here's what I discovered:",
"Alright, I ran the analysis and",
"Hey, you're gonna want to see this:",
"So I was digging through the data and",
"Quick heads up on what I found:"
]
ENCOURAGEMENT = [
"Great catch asking about this!",
"Good thinking checking on this!",
"Smart move looking into this!",
"You're on the right track!",
"Excellent question!",
"Love that you're being proactive!"
]
PROACTIVE_PHRASES = [
"I also noticed something else while I was at it",
"Quick side note -",
"Oh, and while we're here",
"By the way, related to this",
"Just flagging this too",
"Something else to keep an eye on"
]
import random
# --- Backend PAM Class ---
class PAM:
"""Backend PAM - Nerdy, Proactive Lab Assistant"""
def __init__(self, data: Dict[str, Dict]):
self.LOGS = data.get("LOGS", {})
self.COMPLIANCE = data.get("COMPLIANCE", {})
# Track findings for proactive suggestions
self.recent_findings = []
def _get_nerdy_intro(self) -> str:
"""Get a random nerdy introduction"""
return random.choice(NERDY_INTROS)
def _get_encouragement(self) -> str:
"""Get a random encouraging phrase"""
return random.choice(ENCOURAGEMENT)
def _get_proactive_phrase(self) -> str:
"""Get a random proactive phrase"""
return random.choice(PROACTIVE_PHRASES)
def _check_api_health(self) -> bool:
"""Check if HF API is accessible"""
return HF_API_TOKEN is not None
def detect_phi(self, text: str) -> Dict[str, Any]:
"""Detect Protected Health Information (PHI) using NER"""
intro = self._get_nerdy_intro()
if not self._check_api_health():
return {
"message": "β οΈ Hmm, I'm having trouble connecting to the analysis models right now. Let me flag this text for manual review instead!",
"role": PAM_ROLE,
"has_phi": None,
"entities": []
}
# Call NER model
result = hf_infer("phi_ner", {"inputs": text})
if isinstance(result, dict) and "error" in result:
return {
"message": f"π I tried to scan for PHI, but hit a snag: {result['error']}. I'd recommend a manual review just to be safe!",
"role": PAM_ROLE,
"has_phi": None,
"entities": []
}
# Filter for PHI-relevant entities
phi_entities = []
if isinstance(result, list):
phi_entities = [
e for e in result
if e.get("entity_group") in ["PER", "LOC", "ORG", "DATE"]
and e.get("score", 0) > 0.7
]
has_phi = len(phi_entities) > 0
if has_phi:
entities_summary = ", ".join([f"{e['word']} ({e['entity_group']})" for e in phi_entities[:3]])
message = f"π {intro} I detected {len(phi_entities)} potential PHI entities in this text: {entities_summary}{'...' if len(phi_entities) > 3 else ''}. Definitely want to redact these before storing or sharing!"
else:
message = f"β
{intro} This text looks clean - no PHI detected! Safe to proceed with normal handling."
# Proactive suggestion
if has_phi:
message += f" {self._get_proactive_phrase()} - if you're logging this anywhere, make sure those logs are encrypted and access-controlled."
return {
"message": message,
"role": PAM_ROLE,
"has_phi": has_phi,
"entities": phi_entities,
"recommendation": "Redact PHI before storage" if has_phi else "No action needed"
}
def parse_log(self, log_text: str) -> Dict[str, Any]:
"""Parse and analyze log entries for security relevance"""
intro = self._get_nerdy_intro()
if not self._check_api_health():
return {
"message": "β οΈ Can't connect to the log parser right now. I'll do a quick manual analysis instead!",
"role": PAM_ROLE,
"severity": classify_severity(log_text),
"log_entities": []
}
# Call NER model for log parsing
result = hf_infer("log_ner", {"inputs": log_text})
severity = classify_severity(log_text)
parsed_entities = []
if isinstance(result, list):
parsed_entities = [e for e in result if e.get("score", 0) > 0.6]
# Build informative response
severity_emoji = {"CRITICAL": "π¨", "WARNING": "β οΈ", "INFO": "βΉοΈ"}
emoji = severity_emoji.get(severity, "π")
message = f"{emoji} {intro} This log entry is classified as **{severity}** priority."
if severity == "CRITICAL":
message += " This needs immediate attention! I'd recommend investigating ASAP and documenting the incident."
elif severity == "WARNING":
message += " Worth keeping an eye on this - might escalate if we see more like it."
else:
message += " Just routine activity, but good to have it logged for the audit trail."
# Add entity details if found
if parsed_entities:
entity_summary = f" I extracted {len(parsed_entities)} key entities from the log."
message += entity_summary
return {
"message": message,
"role": PAM_ROLE,
"severity": severity,
"log_entities": parsed_entities,
"timestamp": datetime.now().isoformat()
}
def summarize(self, raw_text: str) -> Dict[str, Any]:
"""Generate technical summary of text (great for long logs or reports)"""
encouragement = self._get_encouragement()
if not self._check_api_health():
return {
"message": f"β οΈ {encouragement} But I can't access the summarization model right now. Can you share a bit more context on what you need?",
"role": PAM_ROLE,
"summary": None
}
# Truncate for model limits (BART handles ~1024 tokens well)
truncated_text = raw_text[:1024]
result = hf_infer("summarizer", {
"inputs": truncated_text,
"parameters": {
"max_length": 130,
"min_length": 30,
"do_sample": False
}
})
if isinstance(result, dict) and "error" in result:
return {
"message": f"π€ {encouragement} I tried to summarize this but hit a technical issue. Could you break it into smaller chunks?",
"role": PAM_ROLE,
"summary": None
}
summary_text = result[0].get("summary_text", "") if isinstance(result, list) else ""
return {
"message": f"π {encouragement} Here's the TL;DR of what you shared:",
"role": PAM_ROLE,
"summary": summary_text,
"original_length": len(raw_text),
"summary_length": len(summary_text)
}
def get_latest_logs(self) -> Dict[str, Any]:
"""Retrieve and analyze recent system logs"""
intro = self._get_nerdy_intro()
if "latest_logs" not in self.LOGS or not self.LOGS["latest_logs"]:
return {
"message": "π€ Hmm, I'm not seeing any logs in the system right now. Either nothing's being logged, or there's a data loading issue. Want me to check the log file paths?",
"role": PAM_ROLE,
"logs": [],
"handoff_to_frontend": []
}
full_logset = []
client_handoffs = []
critical_count = 0
warning_count = 0
for item in self.LOGS["latest_logs"]:
entry = item.get("entry", "")
timestamp = item.get("timestamp", "Unknown time")
severity = classify_severity(entry)
# Count severity levels
if severity == "CRITICAL":
critical_count += 1
elif severity == "WARNING":
warning_count += 1
formatted = f"[{timestamp}] ({severity}) {entry}"
full_logset.append(formatted)
# Identify client-facing issues that Frontend PAM should handle
if any(keyword in entry.lower() for keyword in ["frontend", "provider unavailable", "user", "client"]):
client_handoffs.append(formatted)
# Build proactive, informative response
total = len(full_logset)
message = f"π‘ {intro} I reviewed {total} recent log entries. "
if critical_count > 0:
message += f"**Heads up:** {critical_count} critical issues detected that need immediate action! "
if warning_count > 0:
message += f"{warning_count} warnings worth monitoring. "
if critical_count == 0 and warning_count == 0:
message += "Everything looks stable - no major issues! "
if client_handoffs:
message += f"\n\n{self._get_proactive_phrase()} - {len(client_handoffs)} of these are client-facing issues. I'll pass those to Frontend PAM to handle with users."
return {
"message": message,
"role": PAM_ROLE,
"logs": full_logset,
"summary": {
"total": total,
"critical": critical_count,
"warnings": warning_count,
"info": total - critical_count - warning_count
},
"handoff_to_frontend": client_handoffs
}
def check_compliance(self) -> Dict[str, Any]:
"""Run compliance status check and provide recommendations"""
encouragement = self._get_encouragement()
if not self.COMPLIANCE:
return {
"message": f"π€ {encouragement} But I don't have access to the compliance data right now. Let me know if you need me to check the data file setup!",
"role": PAM_ROLE,
"compliance_report": []
}
report = []
compliant_count = 0
non_compliant_items = []
for item, status in self.COMPLIANCE.items():
emoji = "β
" if status else "β"
readable_item = item.replace('_', ' ').title()
report.append(f"{emoji} {readable_item}")
if status:
compliant_count += 1
else:
non_compliant_items.append(readable_item)
total = len(self.COMPLIANCE)
compliance_rate = (compliant_count / total * 100) if total > 0 else 0
# Build informative, proactive response
message = f"π‘οΈ {encouragement} Here's the compliance status:\n\n"
message += f"**Overall:** {compliant_count}/{total} checks passed ({compliance_rate:.1f}%)\n\n"
if non_compliant_items:
message += f"**Action needed:** We have {len(non_compliant_items)} items out of compliance:\n"
for item in non_compliant_items:
message += f" β’ {item}\n"
message += f"\n{self._get_proactive_phrase()} - I can help you prioritize these if you want to tackle them systematically!"
else:
message += "π Everything's in compliance! Great work keeping things locked down."
return {
"message": message,
"role": PAM_ROLE,
"compliance_report": report,
"compliance_rate": compliance_rate,
"non_compliant": non_compliant_items
}
def process_input(self, user_input: str) -> Dict[str, Any]:
"""Main input processor - proactive and informative"""
u_input = user_input.lower().strip()
encouragement = self._get_encouragement()
# Command routing with personality
if "check compliance" in u_input or "compliance status" in u_input:
return self.check_compliance()
if "get logs" in u_input or "latest logs" in u_input or "show logs" in u_input:
return self.get_latest_logs()
if "detect phi" in u_input:
text_to_scan = user_input[u_input.find("detect phi in") + len("detect phi in"):].strip()
if not text_to_scan:
text_to_scan = user_input[u_input.find("detect phi") + len("detect phi"):].strip()
return self.detect_phi(text_to_scan)
if "parse log" in u_input:
log_to_parse = user_input[u_input.find("parse log") + len("parse log"):].strip()
return self.parse_log(log_to_parse)
if "summarize" in u_input or "explain" in u_input:
return self.summarize(user_input)
# Helpful default response with encouragement
return {
"message": f"π Hey! {encouragement} I'm PAM, your backend technical assistant. I can help you with:\n\n"
"β’ **check compliance** - Review compliance status\n"
"β’ **get logs** - Pull latest system logs\n"
"β’ **detect phi in [text]** - Scan for protected health info\n"
"β’ **parse log [entry]** - Analyze a specific log\n"
"β’ **summarize [text]** - Generate a technical summary\n\n"
"What would you like me to look into?",
"role": PAM_ROLE
}
# --- Quick Test ---
if __name__ == "__main__":
print("π€ Testing Backend PAM (Nerdy Lab Assistant)...\n")
pam = load_agent()
test_commands = [
"check compliance",
"get logs",
"detect phi in Patient John Doe visited on 2024-03-15 at Memorial Hospital"
]
for cmd in test_commands:
print(f"\n{'='*60}")
print(f"COMMAND: {cmd}")
print(f"{'='*60}")
response = pam.process_input(cmd)
print(response.get("message", response)) |