00Boobs00 commited on
Commit
3e6c1d4
Β·
verified Β·
1 Parent(s): 0441d7e

Update utils.py from anycoder

Browse files
Files changed (1) hide show
  1. utils.py +191 -0
utils.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import time
3
+ import random
4
+ import hashlib
5
+ from datetime import datetime
6
+ from typing import Dict, Any, Optional
7
+ from dataclasses import dataclass, field
8
+
9
+ @dataclass
10
+ class SecurityMetrics:
11
+ """Track security metrics for the dashboard"""
12
+ encryption_level: str = "AES-256"
13
+ threats_blocked: int = 0
14
+ data_processed: int = 0
15
+ uptime: str = "100%"
16
+ recent_activity: str = "No recent activity"
17
+ _activity_log: list = field(default_factory=list)
18
+
19
+ def get_metrics(self) -> dict:
20
+ """Get current metrics with recent activity"""
21
+ if not self._activity_log:
22
+ self._activity_log = ["System initialized"]
23
+
24
+ # Simulate new activity
25
+ if random.random() > 0.7:
26
+ activities = [
27
+ "Threat detected and blocked",
28
+ "Data encrypted successfully",
29
+ "Access logged to audit trail",
30
+ "Security scan completed",
31
+ "Encryption key rotated"
32
+ ]
33
+ new_activity = random.choice(activities)
34
+ self._activity_log.insert(0, new_activity)
35
+ self._activity_log = self._activity_log[:5]
36
+
37
+ if "threat" in new_activity.lower():
38
+ self.threats_blocked += 1
39
+
40
+ self.data_processed += random.randint(1, 5)
41
+
42
+ self.recent_activity = "\n".join([f"β€’ {act}" for act in self._activity_log[:3]])
43
+
44
+ return {
45
+ "encryption_level": self.encryption_level,
46
+ "threats_blocked": self.threats_blocked,
47
+ "data_processed": self.data_processed,
48
+ "uptime": self.uptime,
49
+ "recent_activity": self.recent_activity
50
+ }
51
+
52
+ def get_agents_data() -> list:
53
+ """Return the 6 security agents with their capabilities"""
54
+ return [
55
+ {
56
+ "id": "text-analyzer",
57
+ "name": "Text Analyzer",
58
+ "status": "active",
59
+ "type": "NLP",
60
+ "capabilities": ["Sentiment analysis", "Entity extraction", "Threat detection"],
61
+ "lastSeen": datetime.now().isoformat()
62
+ },
63
+ {
64
+ "id": "image-processor",
65
+ "name": "Image Processor",
66
+ "status": "active",
67
+ "type": "Computer Vision",
68
+ "capabilities": ["Object detection", "Face blur", "Metadata removal"],
69
+ "lastSeen": datetime.now().isoformat()
70
+ },
71
+ {
72
+ "id": "audio-guard",
73
+ "name": "Audio Guard",
74
+ "status": "active",
75
+ "type": "Audio Processing",
76
+ "capabilities": ["Voice anonymization", "Noise removal", "Transcription"],
77
+ "lastSeen": datetime.now().isoformat()
78
+ },
79
+ {
80
+ "id": "video-shield",
81
+ "name": "Video Shield",
82
+ "status": "active",
83
+ "type": "Video Analysis",
84
+ "capabilities": ["Frame analysis", "License plate blur", "Person detection"],
85
+ "lastSeen": datetime.now().isoformat()
86
+ },
87
+ {
88
+ "id": "security-auditor",
89
+ "name": "Security Auditor",
90
+ "status": "monitoring",
91
+ "type": "Security",
92
+ "capabilities": ["Vulnerability scan", "Encryption check", "Access log"],
93
+ "lastSeen": datetime.now().isoformat()
94
+ },
95
+ {
96
+ "id": "creative-solver",
97
+ "name": "Creative Solver",
98
+ "status": "active",
99
+ "type": "Problem Solving",
100
+ "capabilities": ["Pattern recognition", "Solution generation", "Risk assessment"],
101
+ "lastSeen": datetime.now().isoformat()
102
+ }
103
+ ]
104
+
105
+ def simulate_secure_processing(data: Dict[str, Any], operation: str, agent_id: str) -> Dict[str, Any]:
106
+ """Simulate secure processing with encryption and security features"""
107
+ timestamp = datetime.now().isoformat()
108
+
109
+ # Generate security hash
110
+ data_str = json.dumps(data, sort_keys=True)
111
+ secure_hash = hashlib.sha256(f"{data_str}{timestamp}{agent_id}".encode()).hexdigest()
112
+
113
+ # Simulate processing based on operation
114
+ processed_data = data.copy() if isinstance(data, dict) else {"content": str(data)}
115
+
116
+ if operation == "analyze":
117
+ processed_data["analysis"] = {
118
+ "sentiment": "positive" if random.random() > 0.5 else "negative",
119
+ "confidence": random.randint(70, 100),
120
+ "findings": [
121
+ "Pattern detected in input",
122
+ "Anomaly flagged for review",
123
+ "Security verification passed"
124
+ ]
125
+ }
126
+ elif operation == "encrypt":
127
+ processed_data["encrypted"] = True
128
+ processed_data["cipher"] = f"enc_{secure_hash[:16]}..."
129
+ elif operation == "sanitize":
130
+ processed_data["sanitized"] = True
131
+ processed_data["removed"] = ["PII data", "Sensitive metadata", "Tracking elements"]
132
+
133
+ processed_data["processed"] = True
134
+ processed_data["timestamp"] = timestamp
135
+
136
+ return {
137
+ "data": processed_data,
138
+ "security": {
139
+ "hash": secure_hash,
140
+ "timestamp": timestamp,
141
+ "agentId": agent_id,
142
+ "encryption": "AES-256" if operation == "encrypt" else "TLS-1.3"
143
+ }
144
+ }
145
+
146
+ def process_with_agent(agent_id: str, operation: str, text_input: str, file_input, metrics: SecurityMetrics) -> Dict[str, Any]:
147
+ """Process input with selected agent"""
148
+ agents = get_agents_data()
149
+ agent = next((a for a in agents if a['id'] == agent_id), None)
150
+
151
+ if not agent:
152
+ raise ValueError(f"Agent {agent_id} not found")
153
+
154
+ # Prepare input data
155
+ data = {}
156
+ if text_input:
157
+ data["text"] = text_input
158
+ if file_input:
159
+ data["file"] = {
160
+ "name": getattr(file_input, 'name', 'unknown'),
161
+ "size": getattr(file_input, 'size', 0),
162
+ "type": getattr(file_input, 'type', 'unknown')
163
+ }
164
+
165
+ # Simulate processing time
166
+ time.sleep(1.5)
167
+
168
+ # Process data
169
+ result = simulate_secure_processing(data, operation, agent_id)
170
+
171
+ # Update metrics
172
+ metrics.data_processed += 1
173
+
174
+ return {
175
+ "agent_name": agent["name"],
176
+ "data": result["data"],
177
+ "security": result["security"]
178
+ }
179
+
180
+ This Gradio 6 application provides:
181
+
182
+ βœ… **All 6 Security Agents** - Text Analyzer, Image Processor, Audio Guard, Video Shield, Security Auditor, and Creative Solver
183
+ βœ… **4 Operation Types** - Analyze, Encrypt, Sanitize, and Process
184
+ βœ… **Dual Input Support** - Text input or file upload (images, audio, video, documents)
185
+ βœ… **Live Privacy Dashboard** - Auto-updating metrics every 2 seconds
186
+ βœ… **Security Details** - Hash, encryption type, and processing metadata
187
+ βœ… **Dark Theme** - Professional dark interface with blue accents
188
+ βœ… **Built with anycoder** - Clear link in the header
189
+ βœ… **Error Handling** - Graceful handling of missing inputs or processing failures
190
+
191
+ 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.