abdull4h commited on
Commit
2a8f039
·
verified ·
1 Parent(s): a94b356

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +217 -1059
app.py CHANGED
@@ -1,1153 +1,311 @@
1
  import gradio as gr
2
  import spaces
3
- import json
4
- import datetime
5
- import random
6
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
7
  import torch
8
  import time
9
- import warnings
10
 
11
- # Suppress warnings for cleaner output
12
- warnings.filterwarnings("ignore")
13
-
14
- # Enhanced CSS for beautiful design
15
- beautiful_css = """
16
- /* Import Google Fonts */
17
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
18
-
19
- /* Global Styles */
20
  .gradio-container {
21
- max-width: 1400px !important;
22
  margin: 0 auto !important;
23
- font-family: 'Inter', sans-serif !important;
24
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
25
- min-height: 100vh;
26
- }
27
-
28
- /* Header Styling */
29
- .header-container {
30
- background: rgba(255, 255, 255, 0.95);
31
- backdrop-filter: blur(10px);
32
- border-radius: 20px;
33
- padding: 2rem;
34
- margin: 1rem;
35
- box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
36
- border: 1px solid rgba(255, 255, 255, 0.2);
37
- }
38
-
39
- /* Main Content Cards */
40
- .content-card {
41
- background: rgba(255, 255, 255, 0.98);
42
- backdrop-filter: blur(15px);
43
- border-radius: 16px;
44
- padding: 1.5rem;
45
- margin: 0.5rem;
46
- box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
47
- border: 1px solid rgba(255, 255, 255, 0.3);
48
- transition: all 0.3s ease;
49
- }
50
-
51
- .content-card:hover {
52
- transform: translateY(-2px);
53
- box-shadow: 0 15px 40px rgba(0, 0, 0, 0.12);
54
- }
55
-
56
- /* Status Indicators */
57
- .status-success {
58
- background: linear-gradient(135deg, #4CAF50, #45a049);
59
- color: white;
60
- padding: 12px 20px;
61
- border-radius: 12px;
62
- font-weight: 500;
63
- box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
64
- border: none;
65
- }
66
-
67
- .status-warning {
68
- background: linear-gradient(135deg, #FF9800, #F57C00);
69
- color: white;
70
- padding: 12px 20px;
71
- border-radius: 12px;
72
- font-weight: 500;
73
- box-shadow: 0 4px 15px rgba(255, 152, 0, 0.3);
74
- }
75
-
76
- .status-error {
77
- background: linear-gradient(135deg, #f44336, #d32f2f);
78
- color: white;
79
- padding: 12px 20px;
80
- border-radius: 12px;
81
- font-weight: 500;
82
- box-shadow: 0 4px 15px rgba(244, 67, 54, 0.3);
83
  }
84
 
85
- /* GPT-OSS Badge */
86
- .gpt-oss-badge {
87
- background: linear-gradient(135deg, #667eea, #764ba2);
88
- color: white;
89
- padding: 8px 16px;
90
- border-radius: 20px;
91
- font-weight: 600;
92
- font-size: 0.9rem;
93
- display: inline-block;
94
- box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
95
- margin: 0.5rem 0;
96
  }
97
 
98
- /* Alert Severity Badges */
99
- .severity-critical {
100
- background: linear-gradient(135deg, #dc3545, #c82333);
101
- color: white;
102
- padding: 4px 12px;
103
- border-radius: 20px;
104
- font-weight: 600;
105
- font-size: 0.8rem;
106
- display: inline-block;
107
- box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3);
108
- }
109
-
110
- .severity-high {
111
- background: linear-gradient(135deg, #fd7e14, #e8680a);
112
- color: white;
113
- padding: 4px 12px;
114
- border-radius: 20px;
115
- font-weight: 600;
116
- font-size: 0.8rem;
117
- display: inline-block;
118
- box-shadow: 0 2px 8px rgba(253, 126, 20, 0.3);
119
- }
120
-
121
- .severity-medium {
122
- background: linear-gradient(135deg, #ffc107, #e0a800);
123
- color: #212529;
124
- padding: 4px 12px;
125
- border-radius: 20px;
126
- font-weight: 600;
127
- font-size: 0.8rem;
128
- display: inline-block;
129
- box-shadow: 0 2px 8px rgba(255, 193, 7, 0.3);
130
  }
131
 
132
- /* Button Styling */
133
- .primary-button {
134
- background: linear-gradient(135deg, #667eea, #764ba2) !important;
135
  border: none !important;
136
- border-radius: 12px !important;
137
- padding: 12px 24px !important;
 
138
  font-weight: 600 !important;
139
- font-size: 1rem !important;
140
- transition: all 0.3s ease !important;
141
- box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important;
142
- }
143
-
144
- .primary-button:hover {
145
- transform: translateY(-2px) !important;
146
- box-shadow: 0 8px 25px rgba(102, 126, 234, 0.5) !important;
147
- }
148
-
149
- .secondary-button {
150
- background: linear-gradient(135deg, #6c757d, #5a6268) !important;
151
- border: none !important;
152
- border-radius: 12px !important;
153
- padding: 10px 20px !important;
154
- font-weight: 500 !important;
155
  color: white !important;
156
- transition: all 0.3s ease !important;
157
- }
158
-
159
- /* Input Styling */
160
- .custom-input {
161
- border-radius: 12px !important;
162
- border: 2px solid #e9ecef !important;
163
- padding: 12px !important;
164
- transition: all 0.3s ease !important;
165
- background: rgba(255, 255, 255, 0.9) !important;
166
- }
167
-
168
- .custom-input:focus {
169
- border-color: #667eea !important;
170
- box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1) !important;
171
- }
172
-
173
- /* Section Headers */
174
- .section-header {
175
- font-size: 1.5rem;
176
- font-weight: 700;
177
- color: #2d3436;
178
- margin-bottom: 1rem;
179
- padding-bottom: 0.5rem;
180
- border-bottom: 3px solid #667eea;
181
- display: flex;
182
- align-items: center;
183
- gap: 0.5rem;
184
- }
185
-
186
- /* Alert Timeline */
187
- .timeline-item {
188
- background: rgba(102, 126, 234, 0.05);
189
- border-left: 4px solid #667eea;
190
- padding: 1rem;
191
- margin: 0.5rem 0;
192
- border-radius: 0 8px 8px 0;
193
- transition: all 0.3s ease;
194
  }
195
 
196
- .timeline-item:hover {
197
- background: rgba(102, 126, 234, 0.1);
198
- transform: translateX(4px);
199
- }
200
-
201
- /* Analysis Output Styling */
202
- .analysis-container {
203
- background: linear-gradient(135deg, #f8f9fa, #e9ecef);
204
- border-radius: 16px;
205
- padding: 1.5rem;
206
- border: 1px solid #dee2e6;
207
- box-shadow: inset 0 2px 10px rgba(0, 0, 0, 0.05);
208
- }
209
-
210
- /* Confidence Meter */
211
- .confidence-meter {
212
- height: 8px;
213
- background: #e9ecef;
214
- border-radius: 10px;
215
- overflow: hidden;
216
- margin: 0.5rem 0;
217
- }
218
-
219
- .confidence-fill {
220
- height: 100%;
221
- background: linear-gradient(90deg, #28a745, #20c997, #17a2b8);
222
- border-radius: 10px;
223
- transition: width 0.5s ease;
224
- }
225
-
226
- /* Responsive Design */
227
- @media (max-width: 768px) {
228
- .gradio-container {
229
- padding: 0.5rem;
230
- }
231
-
232
- .content-card {
233
- margin: 0.25rem;
234
- padding: 1rem;
235
- }
236
-
237
- .section-header {
238
- font-size: 1.25rem;
239
- }
240
  }
241
 
242
- /* Loading Animation */
243
- .loading-spinner {
244
- border: 3px solid #f3f3f3;
245
- border-top: 3px solid #667eea;
246
- border-radius: 50%;
247
- width: 20px;
248
- height: 20px;
249
- animation: spin 1s linear infinite;
250
- display: inline-block;
251
- margin-right: 0.5rem;
252
- }
253
-
254
- @keyframes spin {
255
- 0% { transform: rotate(0deg); }
256
- 100% { transform: rotate(360deg); }
257
- }
258
-
259
- /* Alert Cards */
260
- .alert-card {
261
- background: white;
262
- border-radius: 12px;
263
- padding: 1.5rem;
264
- margin: 0.5rem 0;
265
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
266
- border-left: 5px solid #667eea;
267
- transition: all 0.3s ease;
268
- }
269
-
270
- .alert-card:hover {
271
- transform: translateY(-2px);
272
- box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
273
- }
274
-
275
- /* Network Flow Visualization */
276
- .network-flow {
277
- display: flex;
278
- align-items: center;
279
- gap: 1rem;
280
- padding: 1rem;
281
- background: rgba(102, 126, 234, 0.05);
282
- border-radius: 12px;
283
- margin: 0.5rem 0;
284
- }
285
-
286
- .network-node {
287
- background: #667eea;
288
- color: white;
289
- padding: 0.5rem 1rem;
290
- border-radius: 8px;
291
- font-weight: 500;
292
- font-size: 0.9rem;
293
- }
294
-
295
- .network-arrow {
296
- color: #667eea;
297
- font-size: 1.5rem;
298
- font-weight: bold;
299
- }
300
-
301
- /* MITRE ATT&CK Styling */
302
- .mitre-tag {
303
- background: linear-gradient(135deg, #e74c3c, #c0392b);
304
- color: white;
305
- padding: 6px 12px;
306
- border-radius: 20px;
307
- font-size: 0.85rem;
308
- font-weight: 600;
309
- display: inline-block;
310
- box-shadow: 0 3px 10px rgba(231, 76, 60, 0.3);
311
- }
312
-
313
- /* Custom Scrollbar */
314
- ::-webkit-scrollbar {
315
- width: 8px;
316
- }
317
-
318
- ::-webkit-scrollbar-track {
319
- background: #f1f1f1;
320
- border-radius: 10px;
321
- }
322
-
323
- ::-webkit-scrollbar-thumb {
324
- background: linear-gradient(135deg, #667eea, #764ba2);
325
- border-radius: 10px;
326
- }
327
-
328
- ::-webkit-scrollbar-thumb:hover {
329
- background: linear-gradient(135deg, #5a6fd8, #6a4c93);
330
- }
331
-
332
- /* Statistics Cards */
333
- .stat-card {
334
- background: white;
335
- border-radius: 12px;
336
- padding: 1.5rem;
337
- text-align: center;
338
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
339
- transition: all 0.3s ease;
340
- border-top: 4px solid #667eea;
341
- }
342
-
343
- .stat-card:hover {
344
- transform: translateY(-3px);
345
- box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
346
- }
347
-
348
- .stat-number {
349
- font-size: 2rem;
350
- font-weight: 700;
351
- color: #667eea;
352
- margin-bottom: 0.5rem;
353
- }
354
-
355
- .stat-label {
356
- color: #6c757d;
357
- font-weight: 500;
358
- text-transform: uppercase;
359
- font-size: 0.85rem;
360
- letter-spacing: 0.5px;
361
  }
362
  """
363
 
364
- # Global variables for model management
365
- model = None
366
- tokenizer = None
367
- model_status = "🔄 Initializing..."
368
 
369
  @spaces.GPU
370
- def initialize_gpt_oss_safe():
371
- """Initialize GPT-OSS-20B with multiple fallback strategies"""
372
- global model, tokenizer, model_status
373
-
374
- strategies = [
375
- {
376
- "model_id": "openai/gpt-oss-20b",
377
- "name": "GPT-OSS-20B (Original)",
378
- "config": {
379
- "torch_dtype": "auto",
380
- "device_map": "auto",
381
- "trust_remote_code": True,
382
- "low_cpu_mem_usage": True,
383
- "use_safetensors": True
384
- }
385
- },
386
- {
387
- "model_id": "openai/gpt-oss-20b",
388
- "name": "GPT-OSS-20B (BF16)",
389
- "config": {
390
- "torch_dtype": torch.bfloat16,
391
- "device_map": "auto",
392
- "trust_remote_code": True,
393
- "low_cpu_mem_usage": True
394
- }
395
- },
396
- {
397
- "model_id": "microsoft/DialoGPT-large",
398
- "name": "DialoGPT-Large (Fallback)",
399
- "config": {
400
- "torch_dtype": torch.float16 if torch.cuda.is_available() else torch.float32,
401
- "device_map": "auto" if torch.cuda.is_available() else None
402
- }
403
- }
404
  ]
405
 
406
- device = "cuda" if torch.cuda.is_available() else "cpu"
407
-
408
- for i, strategy in enumerate(strategies):
409
  try:
410
- model_id = strategy["model_id"]
411
- config = strategy["config"]
412
- name = strategy["name"]
413
 
414
- print(f"🔄 Trying {name}...")
415
-
416
- tokenizer = AutoTokenizer.from_pretrained(
417
- model_id,
418
- trust_remote_code=True,
419
- use_fast=True
420
- )
421
-
422
- if tokenizer.pad_token is None:
423
- tokenizer.pad_token = tokenizer.eos_token
424
-
425
- model = AutoModelForCausalLM.from_pretrained(
426
- model_id,
427
- **config
428
- )
429
-
430
- # Test generation
431
- test_messages = [{"role": "user", "content": "Test"}]
432
- test_pipe = pipeline(
433
  "text-generation",
434
- model=model,
435
- tokenizer=tokenizer,
436
- torch_dtype=config.get("torch_dtype", "auto"),
437
- device_map="auto" if torch.cuda.is_available() else None
438
  )
439
 
440
- test_pipe(test_messages, max_new_tokens=5, do_sample=False)
 
441
 
442
- model_status = f"✅ {name} loaded successfully on {device}"
443
- return f'<div class="status-success">🎉 {model_status}</div>'
 
444
 
445
  except Exception as e:
446
- print(f"❌ Strategy {i+1} failed: {str(e)[:100]}")
447
- model, tokenizer = None, None
448
  if torch.cuda.is_available():
449
  torch.cuda.empty_cache()
450
  continue
451
 
452
- model_status = "⚠️ Using fallback analysis mode"
453
- return f'<div class="status-warning">{model_status}</div>'
454
 
455
- # Enhanced attack scenarios
456
- ATTACK_SCENARIOS = {
457
- "🔄 Lateral Movement": {
458
- "description": "Advanced Persistent Threat (APT) - Attacker moving laterally through network after initial compromise",
459
- "severity": "Critical",
460
- "icon": "🔄",
461
- "color": "#dc3545",
462
- "alerts": [
463
- {
464
- "id": "ALR-001",
465
- "timestamp": "2025-08-10 14:30:45",
466
- "source_ip": "192.168.1.100",
467
- "destination_ip": "192.168.1.25",
468
- "user": "corp\\john.doe",
469
- "alert_type": "Suspicious Process Execution",
470
- "severity": "High",
471
- "description": "Unusual PowerShell execution with encoded commands detected",
472
- "raw_log": "Process: powershell.exe -WindowStyle Hidden -enc ZXhlYyBjYWxjLmV4ZQ== Parent: winword.exe",
473
- "threat_intel": "Base64 encoded PowerShell commonly used by APT29 (Cozy Bear) for initial access",
474
- "mitre_tactic": "T1059.001 - PowerShell",
475
- "confidence": 85
476
- },
477
- {
478
- "id": "ALR-002",
479
- "timestamp": "2025-08-10 14:35:12",
480
- "source_ip": "192.168.1.100",
481
- "destination_ip": "192.168.1.50",
482
- "user": "corp\\john.doe",
483
- "alert_type": "Credential Dumping Attempt",
484
- "severity": "Critical",
485
- "description": "LSASS memory access detected - possible credential harvesting",
486
- "raw_log": "Process: rundll32.exe comsvcs.dll MiniDump [PID] lsass.dmp full",
487
- "threat_intel": "LSASS dumping technique associated with credential theft operations",
488
- "mitre_tactic": "T1003.001 - LSASS Memory",
489
- "confidence": 92
490
- },
491
- {
492
- "id": "ALR-003",
493
- "timestamp": "2025-08-10 14:42:18",
494
- "source_ip": "192.168.1.100",
495
- "destination_ip": "10.0.0.15",
496
- "user": "SYSTEM",
497
- "alert_type": "Abnormal Network Connection",
498
- "severity": "Medium",
499
- "description": "Connection to unusual internal subnet using stolen credentials",
500
- "raw_log": "TCP connection established to 10.0.0.15:445 from 192.168.1.100:51234",
501
- "threat_intel": "SMB connections to sensitive subnets often indicate lateral movement",
502
- "mitre_tactic": "T1021.002 - SMB/Windows Admin Shares",
503
- "confidence": 78
504
- }
505
- ]
506
- },
507
- "📧 Phishing Campaign": {
508
- "description": "Email-based social engineering attack leading to credential theft and data exfiltration",
509
- "severity": "High",
510
- "icon": "📧",
511
- "color": "#fd7e14",
512
- "alerts": [
513
- {
514
- "id": "ALR-004",
515
- "timestamp": "2025-08-10 09:15:30",
516
- "source_ip": "203.0.113.50",
517
- "destination_ip": "192.168.1.75",
518
- "user": "corp\\sarah.wilson",
519
- "alert_type": "Malicious Email Detected",
520
- "severity": "High",
521
- "description": "Suspicious email with credential harvesting link detected",
522
- "raw_log": "From: [email protected] Subject: URGENT: Account Suspended - Verify Now",
523
- "threat_intel": "Domain registered 48 hours ago, hosted on bulletproof hosting provider",
524
- "mitre_tactic": "T1566.002 - Spearphishing Link",
525
- "confidence": 88
526
- },
527
- {
528
- "id": "ALR-005",
529
- "timestamp": "2025-08-10 09:45:22",
530
- "source_ip": "192.168.1.75",
531
- "destination_ip": "203.0.113.50",
532
- "user": "corp\\sarah.wilson",
533
- "alert_type": "Credential Submission",
534
- "severity": "Critical",
535
- "description": "User credentials submitted to suspicious external site",
536
- "raw_log": "HTTPS POST to https://203.0.113.50/login.php - Credentials: username=sarah.wilson&password=[REDACTED]",
537
- "threat_intel": "IP address hosting multiple phishing kits targeting financial institutions",
538
- "mitre_tactic": "T1056.003 - Web Portal Capture",
539
- "confidence": 95
540
- }
541
- ]
542
- },
543
- "🔒 Ransomware Attack": {
544
- "description": "File encryption attack with ransom demand - likely REvil/Sodinokibi variant",
545
- "severity": "Critical",
546
- "icon": "🔒",
547
- "color": "#dc3545",
548
- "alerts": [
549
- {
550
- "id": "ALR-006",
551
- "timestamp": "2025-08-10 16:20:10",
552
- "source_ip": "192.168.1.85",
553
- "destination_ip": "192.168.1.85",
554
- "user": "corp\\admin.backup",
555
- "alert_type": "Mass File Encryption",
556
- "severity": "Critical",
557
- "description": "Rapid file modifications detected across multiple directories",
558
- "raw_log": "Files encrypted: 1,247 in C:\\Users\\Documents\\ Extensions changed to: .locked2025",
559
- "threat_intel": "Encryption pattern and extension match REvil ransomware family signatures",
560
- "mitre_tactic": "T1486 - Data Encrypted for Impact",
561
- "confidence": 97
562
- },
563
- {
564
- "id": "ALR-007",
565
- "timestamp": "2025-08-10 16:25:33",
566
- "source_ip": "192.168.1.85",
567
- "destination_ip": "45.33.22.11",
568
- "user": "SYSTEM",
569
- "alert_type": "Command and Control Communication",
570
- "severity": "High",
571
- "description": "Encrypted communication to known ransomware C2 infrastructure",
572
- "raw_log": "TLS 1.3 connection established to 45.33.22.11:8443 - Data exchanged: 2.3KB",
573
- "threat_intel": "IP address previously associated with REvil ransomware C2 operations",
574
- "mitre_tactic": "T1071.001 - Web Protocols",
575
- "confidence": 91
576
- }
577
- ]
578
- }
579
- }
580
 
581
- def get_severity_class(severity):
582
- """Get CSS class for severity level"""
583
- classes = {
584
- "Critical": "severity-critical",
585
- "High": "severity-high",
586
- "Medium": "severity-medium",
587
- "Low": "severity-low"
588
- }
589
- return classes.get(severity, "severity-medium")
590
 
591
- def create_confidence_meter(confidence):
592
- """Create a visual confidence meter"""
593
- return f"""
594
- <div class="confidence-meter">
595
- <div class="confidence-fill" style="width: {confidence}%"></div>
596
- </div>
597
- <small style="color: #6c757d;">{confidence}% Confidence</small>
598
- """
599
 
600
- @spaces.GPU
601
- def generate_analysis_safe(alert_data, analyst_level):
602
- """Generate analysis with safe error handling"""
603
 
604
- if not model or not tokenizer:
605
- return get_beautiful_fallback(alert_data, analyst_level)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
606
 
607
- security_prompts = {
608
- "L1": f"""As a Level 1 SOC analyst, provide immediate triage for this security alert:
 
 
609
 
610
- Alert: {alert_data['alert_type']} | Severity: {alert_data['severity']}
611
- Source: {alert_data['source_ip']} → {alert_data['destination_ip']}
612
- User: {alert_data['user']}
613
- Evidence: {alert_data['raw_log']}
614
- MITRE: {alert_data['mitre_tactic']}
615
 
616
- Provide: immediate actions, risk assessment, escalation decision.""",
 
617
 
618
- "L2": f"""As a Level 2 SOC analyst, investigate this cybersecurity incident:
 
 
 
 
619
 
620
- Alert: {alert_data['alert_type']} | Severity: {alert_data['severity']}
621
- Network: {alert_data['source_ip']} → {alert_data['destination_ip']}
622
- User: {alert_data['user']}
623
- Evidence: {alert_data['raw_log']}
624
- Intel: {alert_data['threat_intel']}
625
- MITRE: {alert_data['mitre_tactic']}
626
- Confidence: {alert_data['confidence']}%
627
 
628
- Provide: root cause analysis, investigation steps, threat assessment.""",
 
629
 
630
- "L3": f"""As a senior cybersecurity expert, analyze this sophisticated threat:
 
631
 
632
- Attack: {alert_data['description']}
633
- Evidence: {alert_data['raw_log']}
634
- Attribution: {alert_data['threat_intel']}
635
- MITRE: {alert_data['mitre_tactic']}
636
- Confidence: {alert_data['confidence']}%
 
637
 
638
- Provide: strategic assessment, attribution analysis, response plan."""
639
- }
640
-
641
- try:
642
- prompt = security_prompts.get(analyst_level, security_prompts["L2"])
643
-
644
- pipe = pipeline(
645
- "text-generation",
646
- model=model,
647
- tokenizer=tokenizer,
648
- torch_dtype="auto",
649
- device_map="auto" if torch.cuda.is_available() else None
650
- )
651
-
652
- messages = [{"role": "user", "content": prompt}]
653
-
654
- result = pipe(
655
- messages,
656
- max_new_tokens=400,
657
- do_sample=True,
658
- temperature=0.3,
659
- top_p=0.9,
660
- repetition_penalty=1.1,
661
- pad_token_id=tokenizer.eos_token_id
662
- )
663
-
664
- analysis = result[0]["generated_text"][-1]["content"]
665
-
666
- if len(analysis.strip()) < 50:
667
- return get_beautiful_fallback(alert_data, analyst_level)
668
-
669
- return f"""
670
- <div class="analysis-container">
671
- <div class="gpt-oss-badge">
672
- 🤖 OpenAI GPT-OSS-20B Analysis
673
- </div>
674
- <div style="margin-top: 1rem; line-height: 1.6;">
675
- {analysis.strip()}
676
- </div>
677
- <div style="margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #dee2e6; color: #6c757d; font-size: 0.9rem;">
678
- ⚡ Generated using GPT-OSS-20B • 21B parameters • 3.6B active per token
679
- </div>
680
- </div>
681
- """
682
-
683
- except Exception as e:
684
- print(f"Generation error: {e}")
685
- return get_beautiful_fallback(alert_data, analyst_level)
686
 
687
- def get_beautiful_fallback(alert_data, analyst_level):
688
- """Beautiful fallback analysis with enhanced styling"""
689
-
690
- severity_class = get_severity_class(alert_data['severity'])
691
- confidence_meter = create_confidence_meter(alert_data['confidence'])
692
-
693
- templates = {
694
- "L1": f"""
695
- <div class="alert-card">
696
- <div class="section-header">
697
- 🚨 L1 SOC Triage Analysis
698
- </div>
699
-
700
- <div style="margin: 1rem 0;">
701
- <span class="{severity_class}">{alert_data['severity']} Severity</span>
702
- <span class="mitre-tag" style="margin-left: 0.5rem;">{alert_data['mitre_tactic']}</span>
703
- </div>
704
-
705
- <div class="network-flow">
706
- <div class="network-node">{alert_data['source_ip']}</div>
707
- <div class="network-arrow">→</div>
708
- <div class="network-node">{alert_data['destination_ip']}</div>
709
- </div>
710
-
711
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">⚡ Immediate Actions Required</h4>
712
- <div style="background: #fff3cd; padding: 1rem; border-radius: 8px; border-left: 4px solid #ffc107;">
713
- <strong>🔒 Containment:</strong> Isolate system {alert_data['source_ip']}<br>
714
- <strong>👤 User Action:</strong> Disable account {alert_data['user']}<br>
715
- <strong>🌐 Network:</strong> Block connections to {alert_data['destination_ip']}<br>
716
- <strong>📝 Documentation:</strong> Preserve logs and evidence
717
- </div>
718
-
719
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">📊 Threat Assessment</h4>
720
- {confidence_meter}
721
-
722
- <div style="background: #f8d7da; padding: 1rem; border-radius: 8px; border-left: 4px solid #dc3545; margin-top: 1rem;">
723
- <strong>⬆️ Escalation Required:</strong> {alert_data['severity']} severity warrants L2 investigation
724
- </div>
725
- </div>
726
- """,
727
 
728
- "L2": f"""
729
- <div class="alert-card">
730
- <div class="section-header">
731
- 🔍 L2 Investigation Analysis
732
- </div>
733
-
734
- <div style="margin: 1rem 0;">
735
- <span class="{severity_class}">{alert_data['severity']} Severity</span>
736
- <span class="mitre-tag" style="margin-left: 0.5rem;">{alert_data['mitre_tactic']}</span>
737
- </div>
738
-
739
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">🎯 Attack Vector Analysis</h4>
740
- <div style="background: #e2e3e5; padding: 1rem; border-radius: 8px;">
741
- <strong>Technique:</strong> {alert_data['mitre_tactic']}<br>
742
- <strong>Evidence:</strong> {alert_data['raw_log']}<br>
743
- <strong>Context:</strong> {alert_data['description']}
744
- </div>
745
-
746
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">🔬 Investigation Roadmap</h4>
747
- <div class="timeline-item">
748
- <strong>1.</strong> Timeline correlation: ±30min window analysis
749
- </div>
750
- <div class="timeline-item">
751
- <strong>2.</strong> User behavior baseline: {alert_data['user']} comparison
752
- </div>
753
- <div class="timeline-item">
754
- <strong>3.</strong> Network flow analysis: {alert_data['source_ip']} → {alert_data['destination_ip']}
755
- </div>
756
- <div class="timeline-item">
757
- <strong>4.</strong> Process tree examination and artifact collection
758
- </div>
759
- <div class="timeline-item">
760
- <strong>5.</strong> Similar IOC hunting across environment
761
- </div>
762
-
763
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">📊 Threat Intelligence</h4>
764
- {confidence_meter}
765
- <div style="background: #d1ecf1; padding: 1rem; border-radius: 8px; border-left: 4px solid #17a2b8; margin-top: 1rem;">
766
- <strong>Attribution Context:</strong> {alert_data['threat_intel']}
767
- </div>
768
- </div>
769
- """,
770
 
771
- "L3": f"""
772
- <div class="alert-card">
773
- <div class="section-header">
774
- 🎯 L3 Expert Strategic Analysis
775
- </div>
776
-
777
- <div style="margin: 1rem 0;">
778
- <span class="{severity_class}">{alert_data['severity']} Severity</span>
779
- <span class="mitre-tag" style="margin-left: 0.5rem;">{alert_data['mitre_tactic']}</span>
780
- </div>
781
-
782
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">🎭 Adversary Assessment</h4>
783
- <div style="background: #f8d7da; padding: 1rem; border-radius: 8px;">
784
- <strong>Sophistication:</strong> Advanced (based on {alert_data['mitre_tactic']})<br>
785
- <strong>Campaign Context:</strong> {alert_data['threat_intel']}<br>
786
- <strong>Success Probability:</strong> {alert_data['confidence']}%
787
- </div>
788
-
789
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">💼 Business Impact</h4>
790
- {confidence_meter}
791
- <div style="background: #fff3cd; padding: 1rem; border-radius: 8px; margin-top: 1rem;">
792
- <strong>🔴 Executive Notification:</strong> Required for {alert_data['severity']} severity<br>
793
- <strong>📋 Regulatory Impact:</strong> Under compliance review<br>
794
- <strong>⏰ Response Timeline:</strong> Immediate action required
795
- </div>
796
-
797
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">🛡️ Strategic Response Plan</h4>
798
- <div class="timeline-item" style="background: #d4edda;">
799
- <strong>Immediate:</strong> Threat hunting deployment across infrastructure
800
- </div>
801
- <div class="timeline-item" style="background: #cce5ff;">
802
- <strong>Short-term:</strong> Enhanced monitoring and detection rules
803
- </div>
804
- <div class="timeline-item" style="background: #e2e3e5;">
805
- <strong>Medium-term:</strong> Security architecture review
806
- </div>
807
- <div class="timeline-item" style="background: #f8d7da;">
808
- <strong>Long-term:</strong> Threat intelligence integration
809
- </div>
810
- </div>
811
- """
812
- }
813
-
814
- return templates.get(analyst_level, templates["L2"])
815
 
816
- def analyze_alert_beautiful(scenario_name, alert_index, analyst_level):
817
- """Enhanced analysis function with beautiful output"""
818
- start_time = time.time()
819
-
820
- if scenario_name not in ATTACK_SCENARIOS:
821
- return "❌ Invalid scenario selected.", "", "Error: Invalid scenario"
822
-
823
- scenario = ATTACK_SCENARIOS[scenario_name]
824
- alerts = scenario["alerts"]
825
-
826
- if alert_index >= len(alerts):
827
- return "❌ Invalid alert index.", "", "Error: Invalid alert index"
828
-
829
- selected_alert = alerts[alert_index]
830
-
831
- # Generate analysis
832
- analysis = generate_analysis_safe(selected_alert, analyst_level)
833
-
834
- # Create beautiful alert details
835
- severity_class = get_severity_class(selected_alert['severity'])
836
- confidence_meter = create_confidence_meter(selected_alert['confidence'])
837
-
838
- alert_details = f"""
839
- <div class="alert-card">
840
- <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
841
- <h3 style="margin: 0; color: #2d3436;">🎫 ALERT {selected_alert['id']}</h3>
842
- <small style="color: #6c757d;">🕐 {selected_alert['timestamp']}</small>
843
- </div>
844
-
845
- <div class="network-flow" style="margin: 1rem 0;">
846
- <div class="network-node">{selected_alert['source_ip']}</div>
847
- <div class="network-arrow">→</div>
848
- <div class="network-node">{selected_alert['destination_ip']}</div>
849
- </div>
850
-
851
- <div style="margin: 1rem 0;">
852
- <strong>👤 User Account:</strong> {selected_alert['user']}<br>
853
- <strong>🎯 Alert Type:</strong> {selected_alert['alert_type']}<br>
854
- </div>
855
-
856
- <div style="margin: 1.5rem 0;">
857
- <span class="{severity_class}">{selected_alert['severity']}</span>
858
- <span class="mitre-tag" style="margin-left: 0.5rem;">{selected_alert['mitre_tactic']}</span>
859
- </div>
860
-
861
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">📝 Description</h4>
862
- <div style="background: #f8f9fa; padding: 1rem; border-radius: 8px; border-left: 4px solid #6c757d;">
863
- {selected_alert['description']}
864
- </div>
865
-
866
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">🔍 Technical Evidence</h4>
867
- <div style="background: #2d3436; color: #ffffff; padding: 1rem; border-radius: 8px; font-family: 'Courier New', monospace; font-size: 0.9rem; overflow-x: auto;">
868
- {selected_alert['raw_log']}
869
- </div>
870
-
871
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">🧠 Threat Intelligence</h4>
872
- <div style="background: #d1ecf1; padding: 1rem; border-radius: 8px; border-left: 4px solid #17a2b8;">
873
- {selected_alert['threat_intel']}
874
- </div>
875
-
876
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">📊 Confidence Assessment</h4>
877
- {confidence_meter}
878
- </div>
879
- """
880
-
881
- processing_time = round(time.time() - start_time, 2)
882
- device_info = "GPU" if torch.cuda.is_available() else "CPU"
883
- status = f"""
884
- <div class="status-success">
885
- ✅ {analyst_level} analysis completed in {processing_time}s | Device: {device_info} | {model_status}
886
- </div>
887
- """
888
-
889
- return alert_details, analysis, status
890
 
891
- def get_beautiful_scenario_info(scenario_name):
892
- """Create beautiful scenario information display"""
893
- if scenario_name in ATTACK_SCENARIOS:
894
- scenario = ATTACK_SCENARIOS[scenario_name]
895
-
896
- info = f"""
897
- <div class="content-card">
898
- <div class="section-header">
899
- {scenario['icon']} Attack Scenario: {scenario_name}
900
- </div>
901
-
902
- <div style="margin: 1.5rem 0;">
903
- <div class="stat-card" style="display: inline-block; margin-right: 1rem; min-width: 150px;">
904
- <div class="stat-number">{len(scenario['alerts'])}</div>
905
- <div class="stat-label">Security Events</div>
906
- </div>
907
- <span class="{get_severity_class(scenario['severity'])}" style="vertical-align: top;">
908
- {scenario['severity']} Severity
909
- </span>
910
- </div>
911
-
912
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">📋 Scenario Description</h4>
913
- <div style="background: #f8f9fa; padding: 1.5rem; border-radius: 12px; border-left: 5px solid {scenario.get('color', '#667eea')};">
914
- {scenario['description']}
915
- </div>
916
-
917
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">🔍 Alert Timeline</h4>
918
- """
919
-
920
- for i, alert in enumerate(scenario['alerts']):
921
- severity_class = get_severity_class(alert['severity'])
922
- info += f"""
923
- <div class="timeline-item" style="margin: 0.5rem 0;">
924
- <div style="display: flex; justify-content: space-between; align-items: center;">
925
- <div>
926
- <strong>[{i+1}] {alert['timestamp']}</strong> - {alert['alert_type']}
927
- </div>
928
- <div>
929
- <span class="{severity_class}" style="font-size: 0.7rem; padding: 2px 8px;">
930
- {alert['severity']}
931
- </span>
932
- <span style="margin-left: 0.5rem; color: #6c757d; font-size: 0.8rem;">
933
- {alert['confidence']}% confidence
934
- </span>
935
- </div>
936
- </div>
937
- </div>
938
- """
939
-
940
- info += """
941
- <h4 style="color: #2d3436; margin: 1.5rem 0 1rem 0;">🤖 AI Analysis Capabilities</h4>
942
- <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-top: 1rem;">
943
- <div class="stat-card">
944
- <div style="font-size: 1.5rem; margin-bottom: 0.5rem;">🧠</div>
945
- <div class="stat-label">GPT-OSS-20B Reasoning</div>
946
- </div>
947
- <div class="stat-card">
948
- <div style="font-size: 1.5rem; margin-bottom: 0.5rem;">⚡</div>
949
- <div class="stat-label">Multi-Strategy Loading</div>
950
- </div>
951
- <div class="stat-card">
952
- <div style="font-size: 1.5rem; margin-bottom: 0.5rem;">🛡️</div>
953
- <div class="stat-label">Robust Error Handling</div>
954
- </div>
955
- <div class="stat-card">
956
- <div style="font-size: 1.5rem; margin-bottom: 0.5rem;">🎯</div>
957
- <div class="stat-label">Expert Templates</div>
958
- </div>
959
- </div>
960
- </div>
961
- """
962
-
963
- return info
964
- return '<div class="status-warning">⚠️ No scenario selected. Please choose an attack scenario to begin analysis.</div>'
965
 
966
- # Create beautiful Gradio interface
967
- with gr.Blocks(title="SOC Assistant - Beautiful Edition", theme=gr.themes.Soft(), css=beautiful_css) as demo:
968
 
969
- # Header
970
- gr.HTML("""
971
- <div class="header-container">
972
- <div style="text-align: center;">
973
- <h1 style="margin: 0; font-size: 2.5rem; background: linear-gradient(135deg, #667eea, #764ba2); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-weight: 700;">
974
- 🛡️ SOC LLM Assistant
975
- </h1>
976
- <p style="margin: 0.5rem 0 0 0; font-size: 1.2rem; color: #6c757d; font-weight: 400;">
977
- Beautiful Edition • Powered by GPT-OSS-20B
978
- </p>
979
- <div class="gpt-oss-badge" style="margin-top: 1rem;">
980
- 🚀 Multi-Strategy AI Model Loading • Enhanced UI/UX
981
- </div>
982
- </div>
983
- </div>
984
  """)
985
 
986
- # Model status display
987
- status_display = gr.HTML('<div class="status-warning">🔄 Initializing AI models...</div>')
 
 
 
 
 
988
 
 
989
  with gr.Row():
990
- # Left Panel - Controls
991
- with gr.Column(scale=1, min_width=350):
992
- gr.HTML('<div class="section-header">🎮 Attack Simulation Control</div>')
993
-
994
- scenario_dropdown = gr.Dropdown(
995
- choices=list(ATTACK_SCENARIOS.keys()),
996
- label="🎭 Select Attack Scenario",
997
- value="🔄 Lateral Movement",
998
- interactive=True,
999
- elem_classes=["custom-input"]
1000
- )
1001
-
1002
- scenario_info = gr.HTML()
1003
-
1004
- gr.HTML('<div style="margin: 2rem 0 1rem 0; height: 2px; background: linear-gradient(90deg, #667eea, #764ba2); border-radius: 2px;"></div>')
1005
- gr.HTML('<div class="section-header">⚙️ Analysis Configuration</div>')
1006
-
1007
- alert_slider = gr.Slider(
1008
- minimum=0,
1009
- maximum=2,
1010
- step=1,
1011
- value=0,
1012
- label="📋 Alert Selection",
1013
- info="Choose which alert from the scenario to analyze",
1014
- elem_classes=["custom-input"]
1015
  )
1016
 
 
1017
  analyst_level = gr.Radio(
1018
  choices=["L1", "L2", "L3"],
1019
- label="👤 Analyst Experience Level",
1020
  value="L2",
1021
- info="🔹 L1: Triage • 🔹 L2: Investigation • 🔹 L3: Expert Analysis",
1022
- elem_classes=["custom-input"]
1023
  )
1024
 
 
1025
  analyze_btn = gr.Button(
1026
- "🚀 Analyze Alert with AI",
1027
  variant="primary",
1028
  size="lg",
1029
- elem_classes=["primary-button"]
1030
  )
1031
 
1032
- init_btn = gr.Button(
1033
- "🔄 Reinitialize Models",
1034
- variant="secondary",
1035
- elem_classes=["secondary-button"]
1036
- )
1037
-
1038
- gr.HTML('<div style="margin: 2rem 0 1rem 0; height: 2px; background: linear-gradient(90deg, #667eea, #764ba2); border-radius: 2px;"></div>')
1039
- gr.HTML("""
1040
- <div class="content-card">
1041
- <div class="section-header">🔧 System Features</div>
1042
- <div style="margin-top: 1rem;">
1043
- <div class="timeline-item" style="background: rgba(102, 126, 234, 0.1);">
1044
- <strong>🧠 GPT-OSS-20B:</strong> OpenAI's latest reasoning model
1045
- </div>
1046
- <div class="timeline-item" style="background: rgba(40, 167, 69, 0.1);">
1047
- <strong>⚡ Multi-Strategy:</strong> Automatic model fallback
1048
- </div>
1049
- <div class="timeline-item" style="background: rgba(253, 126, 20, 0.1);">
1050
- <strong>🛡️ Error Recovery:</strong> Robust failure handling
1051
- </div>
1052
- <div class="timeline-item" style="background: rgba(220, 53, 69, 0.1);">
1053
- <strong>🎯 Expert Analysis:</strong> High-quality templates
1054
- </div>
1055
- </div>
1056
- </div>
1057
  """)
1058
 
1059
- # Right Panel - Results
1060
  with gr.Column(scale=2):
1061
- gr.HTML('<div class="section-header">📋 Security Alert Details</div>')
1062
- alert_output = gr.HTML(
1063
- '<div class="content-card"><p style="text-align: center; color: #6c757d; padding: 2rem;">Alert details will appear here after analysis...</p></div>'
1064
- )
1065
 
1066
- gr.HTML('<div class="section-header">🤖 AI-Powered Security Analysis</div>')
1067
- analysis_output = gr.HTML(
1068
- '<div class="content-card"><p style="text-align: center; color: #6c757d; padding: 2rem;">AI analysis will appear here after processing...</p></div>'
 
 
 
 
1069
  )
1070
 
1071
- status_output = gr.HTML()
 
 
 
 
 
1072
 
1073
- # Footer
1074
- gr.HTML("""
1075
- <div class="content-card" style="margin-top: 2rem; text-align: center;">
1076
- <h3 style="color: #2d3436; margin-bottom: 1rem;">🎯 Enhanced Features</h3>
1077
- <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1rem;">
1078
- <div class="stat-card">
1079
- <div style="font-size: 2rem; margin-bottom: 0.5rem;">🎨</div>
1080
- <div class="stat-label">Beautiful Design</div>
1081
- <p style="margin-top: 0.5rem; font-size: 0.8rem; color: #6c757d;">Modern, responsive UI with glassmorphism effects</p>
1082
- </div>
1083
- <div class="stat-card">
1084
- <div style="font-size: 2rem; margin-bottom: 0.5rem;">🚀</div>
1085
- <div class="stat-label">GPT-OSS Integration</div>
1086
- <p style="margin-top: 0.5rem; font-size: 0.8rem; color: #6c757d;">Latest OpenAI open-weight reasoning model</p>
1087
- </div>
1088
- <div class="stat-card">
1089
- <div style="font-size: 2rem; margin-bottom: 0.5rem;">🔧</div>
1090
- <div class="stat-label">Smart Fallbacks</div>
1091
- <p style="margin-top: 0.5rem; font-size: 0.8rem; color: #6c757d;">Automatic error recovery and model switching</p>
1092
- </div>
1093
- <div class="stat-card">
1094
- <div style="font-size: 2rem; margin-bottom: 0.5rem;">📊</div>
1095
- <div class="stat-label">Rich Analytics</div>
1096
- <p style="margin-top: 0.5rem; font-size: 0.8rem; color: #6c757d;">Visual confidence meters and threat timelines</p>
1097
- </div>
1098
- </div>
1099
- <div style="margin-top: 2rem; padding-top: 1.5rem; border-top: 1px solid #dee2e6; color: #6c757d;">
1100
- <strong>👨‍🎓 Research:</strong> Abdullah Alanazi | <strong>🏛️ Institution:</strong> KAUST | <strong>👨‍🏫 Supervisor:</strong> Prof. Ali Shoker
1101
- </div>
1102
- </div>
1103
  """)
1104
 
1105
  # Event handlers
1106
- scenario_dropdown.change(
1107
- fn=get_beautiful_scenario_info,
1108
- inputs=[scenario_dropdown],
1109
- outputs=[scenario_info]
1110
- )
1111
-
1112
- def update_slider_max(scenario_name):
1113
- if scenario_name in ATTACK_SCENARIOS:
1114
- max_alerts = len(ATTACK_SCENARIOS[scenario_name]["alerts"]) - 1
1115
- return gr.Slider(maximum=max_alerts, value=0)
1116
- return gr.Slider(maximum=2, value=0)
1117
-
1118
- scenario_dropdown.change(
1119
- fn=update_slider_max,
1120
- inputs=[scenario_dropdown],
1121
- outputs=[alert_slider]
1122
- )
1123
-
1124
  analyze_btn.click(
1125
- fn=analyze_alert_beautiful,
1126
- inputs=[scenario_dropdown, alert_slider, analyst_level],
1127
- outputs=[alert_output, analysis_output, status_output]
1128
- )
1129
-
1130
- init_btn.click(
1131
- fn=initialize_gpt_oss_safe,
1132
- outputs=[status_display]
1133
- )
1134
-
1135
- # Initialize on startup
1136
- demo.load(
1137
- fn=get_beautiful_scenario_info,
1138
- inputs=[scenario_dropdown],
1139
- outputs=[scenario_info]
1140
  )
1141
 
 
1142
  demo.load(
1143
- fn=initialize_gpt_oss_safe,
1144
  outputs=[status_display]
1145
  )
1146
 
1147
  if __name__ == "__main__":
1148
- demo.launch(
1149
- share=True,
1150
- server_name="0.0.0.0",
1151
- server_port=7860,
1152
- show_error=True
1153
- )
 
1
  import gradio as gr
2
  import spaces
3
+ from transformers import pipeline
 
 
 
4
  import torch
5
  import time
 
6
 
7
+ # Simple CSS for clean design
8
+ simple_css = """
 
 
 
 
 
 
 
9
  .gradio-container {
10
+ max-width: 900px !important;
11
  margin: 0 auto !important;
12
+ font-family: 'Arial', sans-serif;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  }
14
 
15
+ .threat-input {
16
+ border-radius: 8px !important;
17
+ border: 2px solid #e0e0e0 !important;
18
+ padding: 15px !important;
19
+ font-size: 14px !important;
 
 
 
 
 
 
20
  }
21
 
22
+ .threat-input:focus {
23
+ border-color: #667eea !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  }
25
 
26
+ .analyze-btn {
27
+ background: #667eea !important;
 
28
  border: none !important;
29
+ border-radius: 8px !important;
30
+ padding: 12px 30px !important;
31
+ font-size: 16px !important;
32
  font-weight: 600 !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  color: white !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  }
35
 
36
+ .analysis-output {
37
+ background: #f8f9fa !important;
38
+ border-radius: 8px !important;
39
+ border: 1px solid #e0e0e0 !important;
40
+ padding: 20px !important;
41
+ line-height: 1.6 !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  }
43
 
44
+ .status-box {
45
+ background: #d4edda !important;
46
+ border: 1px solid #c3e6cb !important;
47
+ color: #155724 !important;
48
+ padding: 10px !important;
49
+ border-radius: 6px !important;
50
+ margin: 10px 0 !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  }
52
  """
53
 
54
+ # Global model variables
55
+ pipe = None
56
+ model_status = "🔄 Loading model..."
 
57
 
58
  @spaces.GPU
59
+ def load_model():
60
+ """Load the best available model"""
61
+ global pipe, model_status
62
+
63
+ models_to_try = [
64
+ "openai/gpt-oss-20b",
65
+ "microsoft/DialoGPT-large",
66
+ "microsoft/DialoGPT-medium",
67
+ "gpt2-large"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  ]
69
 
70
+ for model_name in models_to_try:
 
 
71
  try:
72
+ print(f"🔄 Loading {model_name}...")
 
 
73
 
74
+ pipe = pipeline(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  "text-generation",
76
+ model=model_name,
77
+ torch_dtype="auto",
78
+ device_map="auto" if torch.cuda.is_available() else None,
79
+ trust_remote_code=True
80
  )
81
 
82
+ # Test the model
83
+ pipe("Test", max_new_tokens=5, do_sample=False)
84
 
85
+ model_status = f"✅ {model_name} ready"
86
+ print(model_status)
87
+ return model_status
88
 
89
  except Exception as e:
90
+ print(f"❌ {model_name} failed: {str(e)[:50]}")
 
91
  if torch.cuda.is_available():
92
  torch.cuda.empty_cache()
93
  continue
94
 
95
+ model_status = "⚠️ Using fallback mode"
96
+ return model_status
97
 
98
+ @spaces.GPU
99
+ def analyze_threat(threat_description, analyst_level):
100
+ """Simple threat analysis"""
101
+
102
+ if not threat_description.strip():
103
+ return "Please enter a threat description first.", ""
104
+
105
+ start_time = time.time()
106
+
107
+ # Create simple prompt
108
+ prompt = f"""As a {analyst_level} cybersecurity analyst, analyze this threat:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
+ THREAT: {threat_description}
 
 
 
 
 
 
 
 
111
 
112
+ Provide a {analyst_level} level security analysis including:
113
+ - Threat assessment
114
+ - Potential impact
115
+ - Recommended actions
 
 
 
 
116
 
117
+ ANALYSIS:"""
 
 
118
 
119
+ if pipe:
120
+ try:
121
+ result = pipe(
122
+ prompt,
123
+ max_new_tokens=300,
124
+ do_sample=True,
125
+ temperature=0.3,
126
+ top_p=0.9,
127
+ repetition_penalty=1.1
128
+ )
129
+
130
+ analysis = result[0]['generated_text'][len(prompt):].strip()
131
+
132
+ if len(analysis) < 30:
133
+ analysis = get_simple_fallback(threat_description, analyst_level)
134
+
135
+ except Exception as e:
136
+ analysis = f"AI Error: {str(e)[:100]}\n\n{get_simple_fallback(threat_description, analyst_level)}"
137
+ else:
138
+ analysis = get_simple_fallback(threat_description, analyst_level)
139
 
140
+ processing_time = round(time.time() - start_time, 2)
141
+ status = f" Analysis completed in {processing_time}s | {model_status}"
142
+
143
+ return analysis, status
144
 
145
+ def get_simple_fallback(threat_description, analyst_level):
146
+ """Simple fallback analysis"""
147
+
148
+ if analyst_level == "L1":
149
+ return f"""🚨 L1 TRIAGE ANALYSIS
150
 
151
+ THREAT SUMMARY:
152
+ {threat_description}
153
 
154
+ IMMEDIATE ACTIONS:
155
+ • Assess severity and scope
156
+ • Document all available evidence
157
+ • Isolate affected systems if needed
158
+ • Escalate to L2 if severity is high
159
 
160
+ PRIORITY: Immediate containment and escalation decision required"""
 
 
 
 
 
 
161
 
162
+ elif analyst_level == "L2":
163
+ return f"""🔍 L2 INVESTIGATION ANALYSIS
164
 
165
+ THREAT DETAILS:
166
+ {threat_description}
167
 
168
+ INVESTIGATION STEPS:
169
+ 1. Collect and preserve evidence
170
+ 2. Analyze attack vectors and methods
171
+ 3. Determine scope of compromise
172
+ 4. Identify indicators of compromise (IOCs)
173
+ 5. Assess potential data exposure
174
 
175
+ CONTAINMENT:
176
+ • Implement network segmentation
177
+ • Deploy additional monitoring
178
+ • Review authentication logs
179
+ Check for lateral movement
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
+ NEXT STEPS:
182
+ Continue monitoring for related activity
183
+ • Update security controls as needed
184
+ Consider L3 escalation for complex threats"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
+ else: # L3
187
+ return f"""🎯 L3 EXPERT ANALYSIS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
 
189
+ STRATEGIC THREAT ASSESSMENT:
190
+ {threat_description}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
+ ADVANCED ANALYSIS:
193
+ Threat actor attribution assessment
194
+ Campaign analysis and TTPs
195
+ • Business impact evaluation
196
+ Risk quantification
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
198
+ STRATEGIC RESPONSE:
199
+ Coordinate incident response team
200
+ Executive briefing preparation
201
+ Regulatory compliance review
202
+ • Long-term security posture improvements
203
+
204
+ RECOMMENDATIONS:
205
+ Implement advanced threat hunting
206
+ Enhance detection capabilities
207
+ • Review security architecture
208
+ • Consider external forensics support"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
 
210
+ # Create simple interface
211
+ with gr.Blocks(title="Simple SOC Analyzer", theme=gr.themes.Soft(), css=simple_css) as demo:
212
 
213
+ # Simple header
214
+ gr.Markdown("""
215
+ # 🛡️ SOC Threat Analyzer
216
+ **Simple Fast • Effective**
217
+
218
+ Enter any security threat and get instant AI analysis.
 
 
 
 
 
 
 
 
 
219
  """)
220
 
221
+ # Model status
222
+ status_display = gr.Textbox(
223
+ value="🔄 Loading model...",
224
+ label="System Status",
225
+ interactive=False,
226
+ elem_classes=["status-box"]
227
+ )
228
 
229
+ # Main interface
230
  with gr.Row():
231
+ with gr.Column(scale=1):
232
+
233
+ # Threat input
234
+ threat_input = gr.Textbox(
235
+ label="🚨 Describe the Security Threat",
236
+ placeholder="Example: Suspicious PowerShell execution detected on user workstation with encoded commands...",
237
+ lines=5,
238
+ elem_classes=["threat-input"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  )
240
 
241
+ # Analysis level
242
  analyst_level = gr.Radio(
243
  choices=["L1", "L2", "L3"],
 
244
  value="L2",
245
+ label="Analysis Level",
246
+ info="L1: Quick Triage • L2: Detailed Investigation • L3: Strategic Analysis"
247
  )
248
 
249
+ # Analyze button
250
  analyze_btn = gr.Button(
251
+ "🔍 Analyze Threat",
252
  variant="primary",
253
  size="lg",
254
+ elem_classes=["analyze-btn"]
255
  )
256
 
257
+ # Quick examples
258
+ gr.Markdown("""
259
+ ### 📝 Quick Examples:
260
+ - Suspicious email with malicious attachment
261
+ - Unusual network traffic to external IP
262
+ - User account showing signs of compromise
263
+ - Ransomware indicators detected on server
264
+ - Failed login attempts from multiple locations
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  """)
266
 
 
267
  with gr.Column(scale=2):
 
 
 
 
268
 
269
+ # Analysis output
270
+ analysis_output = gr.Textbox(
271
+ label="🤖 Security Analysis",
272
+ lines=20,
273
+ interactive=False,
274
+ elem_classes=["analysis-output"],
275
+ placeholder="Analysis will appear here..."
276
  )
277
 
278
+ # Processing status
279
+ process_status = gr.Textbox(
280
+ label="Processing Status",
281
+ interactive=False,
282
+ lines=1
283
+ )
284
 
285
+ # Quick action buttons
286
+ with gr.Row():
287
+ gr.Button("💾 Save Analysis", variant="secondary", size="sm")
288
+ gr.Button("📧 Email Report", variant="secondary", size="sm")
289
+ gr.Button("🔄 Clear All", variant="secondary", size="sm")
290
+
291
+ # Simple footer
292
+ gr.Markdown("""
293
+ ---
294
+ **💡 Tips:** Be specific about what you observed, include timestamps, IP addresses, user accounts, or file names when available.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  """)
296
 
297
  # Event handlers
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  analyze_btn.click(
299
+ fn=analyze_threat,
300
+ inputs=[threat_input, analyst_level],
301
+ outputs=[analysis_output, process_status]
 
 
 
 
 
 
 
 
 
 
 
 
302
  )
303
 
304
+ # Initialize model on startup
305
  demo.load(
306
+ fn=load_model,
307
  outputs=[status_display]
308
  )
309
 
310
  if __name__ == "__main__":
311
+ demo.launch(share=True)