anycoder-5609dbb0 / utils.py
00Boobs00's picture
Update utils.py from anycoder
3e6c1d4 verified
import json
import time
import random
import hashlib
from datetime import datetime
from typing import Dict, Any, Optional
from dataclasses import dataclass, field
@dataclass
class SecurityMetrics:
"""Track security metrics for the dashboard"""
encryption_level: str = "AES-256"
threats_blocked: int = 0
data_processed: int = 0
uptime: str = "100%"
recent_activity: str = "No recent activity"
_activity_log: list = field(default_factory=list)
def get_metrics(self) -> dict:
"""Get current metrics with recent activity"""
if not self._activity_log:
self._activity_log = ["System initialized"]
# Simulate new activity
if random.random() > 0.7:
activities = [
"Threat detected and blocked",
"Data encrypted successfully",
"Access logged to audit trail",
"Security scan completed",
"Encryption key rotated"
]
new_activity = random.choice(activities)
self._activity_log.insert(0, new_activity)
self._activity_log = self._activity_log[:5]
if "threat" in new_activity.lower():
self.threats_blocked += 1
self.data_processed += random.randint(1, 5)
self.recent_activity = "\n".join([f"β€’ {act}" for act in self._activity_log[:3]])
return {
"encryption_level": self.encryption_level,
"threats_blocked": self.threats_blocked,
"data_processed": self.data_processed,
"uptime": self.uptime,
"recent_activity": self.recent_activity
}
def get_agents_data() -> list:
"""Return the 6 security agents with their capabilities"""
return [
{
"id": "text-analyzer",
"name": "Text Analyzer",
"status": "active",
"type": "NLP",
"capabilities": ["Sentiment analysis", "Entity extraction", "Threat detection"],
"lastSeen": datetime.now().isoformat()
},
{
"id": "image-processor",
"name": "Image Processor",
"status": "active",
"type": "Computer Vision",
"capabilities": ["Object detection", "Face blur", "Metadata removal"],
"lastSeen": datetime.now().isoformat()
},
{
"id": "audio-guard",
"name": "Audio Guard",
"status": "active",
"type": "Audio Processing",
"capabilities": ["Voice anonymization", "Noise removal", "Transcription"],
"lastSeen": datetime.now().isoformat()
},
{
"id": "video-shield",
"name": "Video Shield",
"status": "active",
"type": "Video Analysis",
"capabilities": ["Frame analysis", "License plate blur", "Person detection"],
"lastSeen": datetime.now().isoformat()
},
{
"id": "security-auditor",
"name": "Security Auditor",
"status": "monitoring",
"type": "Security",
"capabilities": ["Vulnerability scan", "Encryption check", "Access log"],
"lastSeen": datetime.now().isoformat()
},
{
"id": "creative-solver",
"name": "Creative Solver",
"status": "active",
"type": "Problem Solving",
"capabilities": ["Pattern recognition", "Solution generation", "Risk assessment"],
"lastSeen": datetime.now().isoformat()
}
]
def simulate_secure_processing(data: Dict[str, Any], operation: str, agent_id: str) -> Dict[str, Any]:
"""Simulate secure processing with encryption and security features"""
timestamp = datetime.now().isoformat()
# Generate security hash
data_str = json.dumps(data, sort_keys=True)
secure_hash = hashlib.sha256(f"{data_str}{timestamp}{agent_id}".encode()).hexdigest()
# Simulate processing based on operation
processed_data = data.copy() if isinstance(data, dict) else {"content": str(data)}
if operation == "analyze":
processed_data["analysis"] = {
"sentiment": "positive" if random.random() > 0.5 else "negative",
"confidence": random.randint(70, 100),
"findings": [
"Pattern detected in input",
"Anomaly flagged for review",
"Security verification passed"
]
}
elif operation == "encrypt":
processed_data["encrypted"] = True
processed_data["cipher"] = f"enc_{secure_hash[:16]}..."
elif operation == "sanitize":
processed_data["sanitized"] = True
processed_data["removed"] = ["PII data", "Sensitive metadata", "Tracking elements"]
processed_data["processed"] = True
processed_data["timestamp"] = timestamp
return {
"data": processed_data,
"security": {
"hash": secure_hash,
"timestamp": timestamp,
"agentId": agent_id,
"encryption": "AES-256" if operation == "encrypt" else "TLS-1.3"
}
}
def process_with_agent(agent_id: str, operation: str, text_input: str, file_input, metrics: SecurityMetrics) -> Dict[str, Any]:
"""Process input with selected agent"""
agents = get_agents_data()
agent = next((a for a in agents if a['id'] == agent_id), None)
if not agent:
raise ValueError(f"Agent {agent_id} not found")
# Prepare input data
data = {}
if text_input:
data["text"] = text_input
if file_input:
data["file"] = {
"name": getattr(file_input, 'name', 'unknown'),
"size": getattr(file_input, 'size', 0),
"type": getattr(file_input, 'type', 'unknown')
}
# Simulate processing time
time.sleep(1.5)
# Process data
result = simulate_secure_processing(data, operation, agent_id)
# Update metrics
metrics.data_processed += 1
return {
"agent_name": agent["name"],
"data": result["data"],
"security": result["security"]
}
This Gradio 6 application provides:
βœ… **All 6 Security Agents** - Text Analyzer, Image Processor, Audio Guard, Video Shield, Security Auditor, and Creative Solver
βœ… **4 Operation Types** - Analyze, Encrypt, Sanitize, and Process
βœ… **Dual Input Support** - Text input or file upload (images, audio, video, documents)
βœ… **Live Privacy Dashboard** - Auto-updating metrics every 2 seconds
βœ… **Security Details** - Hash, encryption type, and processing metadata
βœ… **Dark Theme** - Professional dark interface with blue accents
βœ… **Built with anycoder** - Clear link in the header
βœ… **Error Handling** - Graceful handling of missing inputs or processing failures
The interface is cleaner, more maintainable, and eliminates all the React complexity while preserving every feature from your original application. The live dashboard simulates real-time security monitoring just like your React version.