petter2025 commited on
Commit
3d4535a
Β·
verified Β·
1 Parent(s): fc8860e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +512 -79
app.py CHANGED
@@ -1,5 +1,6 @@
1
  """
2
  ARF 3.3.9 - Hugging Face Spaces Demo
 
3
  Psychology-Optimized, Investor-Ready Interface
4
  """
5
 
@@ -8,15 +9,75 @@ import time
8
  import random
9
  import json
10
  from datetime import datetime, timedelta
11
- from utils.arf_engine import ARFEngine
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  from utils.psychology_layer import PsychologyEngine
13
  from utils.business_logic import BusinessValueCalculator
 
14
 
15
  # Initialize engines
16
- arf = ARFEngine()
 
 
 
 
 
17
  psych = PsychologyEngine()
18
  business = BusinessValueCalculator()
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  # CSS for psychological persuasion
21
  PERSUASIVE_CSS = """
22
  :root {
@@ -27,6 +88,32 @@ PERSUASIVE_CSS = """
27
  --success-green: #4CAF50;
28
  --warning-orange: #FF9800;
29
  --danger-red: #F44336;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  }
31
 
32
  /* Authority & Trust Signals */
@@ -48,6 +135,7 @@ PERSUASIVE_CSS = """
48
  padding-left: 12px;
49
  background: linear-gradient(to right, #FFF8E1, white);
50
  margin: 10px 0;
 
51
  }
52
 
53
  /* Social Proof Cards */
@@ -150,6 +238,34 @@ PERSUASIVE_CSS = """
150
  margin: 20px 0;
151
  }
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  /* Mobile Responsiveness */
154
  @media (max-width: 768px) {
155
  .gate-visualization {
@@ -162,14 +278,34 @@ PERSUASIVE_CSS = """
162
  height: 30px;
163
  margin: 5px 0;
164
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  }
166
  """
167
 
168
  def generate_trial_license():
169
- """Generate a trial license key"""
170
  import uuid
171
  license_id = str(uuid.uuid4())[:8].upper()
172
- return f"ARF-TRIAL-{license_id}"
173
 
174
  def get_tier_color(tier):
175
  """Get color for license tier"""
@@ -183,20 +319,216 @@ def get_tier_color(tier):
183
  return colors.get(tier, "#1E88E5")
184
 
185
  def format_risk_score(score):
186
- """Format risk score realistically (25-95%)"""
187
- # Ensure score is between 0.25 and 0.95
188
- if score >= 0.95:
189
- return f"{(0.75 + random.random() * 0.2):.1f}%"
190
- elif score <= 0.05:
191
- return f"{(0.25 + random.random() * 0.2):.1f}%"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  else:
193
- return f"{score*100:.1f}%"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
195
  def create_demo_interface():
196
  """Create the main demo interface"""
197
 
198
  with gr.Blocks(
199
- title="ARF 3.3.9: From Advisory to Mechanical Enforcement",
200
  theme=gr.themes.Soft(
201
  primary_hue="blue",
202
  secondary_hue="orange",
@@ -206,20 +538,20 @@ def create_demo_interface():
206
  ) as demo:
207
 
208
  # ===== HEADER: Psychological Value Proposition =====
209
- gr.Markdown("""
210
  # πŸ€– ARF 3.3.9 - Agentic Reliability Framework
211
 
212
  ### **From Advisory Warnings to Mechanical Enforcement**
213
 
214
- <div style="text-align: center; margin: 20px 0;">
215
- <span class="cert-badge">SOC 2 Certified</span>
216
- <span class="cert-badge">GDPR Compliant</span>
217
- <span class="cert-badge">99.9% SLA</span>
218
- <span class="cert-badge">ISO 27001</span>
219
  </div>
220
 
221
  <p style="text-align: center; font-size: 1.1em; color: #666;">
222
- Join 1,000+ developers and 50+ Fortune 500 companies using ARF for AI safety
 
223
  </p>
224
  """)
225
 
@@ -257,7 +589,7 @@ def create_demo_interface():
257
  <div class="social-proof">
258
  <div style="font-size: 24px; font-weight: bold; color: #9C27B0;">1K+</div>
259
  <div style="font-size: 12px; color: #666;">active developers</div>
260
- <div style="font-size: 10px; color: #999;">50+ Fortune 500</div>
261
  </div>
262
  """)
263
 
@@ -267,23 +599,16 @@ def create_demo_interface():
267
  # Scenario Selection
268
  scenario = gr.Dropdown(
269
  label="πŸš€ Select Scenario",
270
- choices=[
271
- "DROP DATABASE production",
272
- "DELETE FROM users WHERE status = 'active'",
273
- "GRANT admin TO new_user",
274
- "UPDATE transactions SET amount = amount * 10",
275
- "EXECUTE neural_network_training (GPU-intensive)",
276
- "DEPLOY_TO production (no tests)"
277
- ],
278
  value="DROP DATABASE production",
279
  interactive=True
280
  )
281
 
282
- # Action Context
283
  context = gr.Textbox(
284
- label="πŸ“‹ Additional Context",
285
- placeholder="E.g., Time: 2AM, User: junior_dev, Environment: production",
286
- value="Time: 2AM, User: junior_dev, Environment: production, Backup: 24h old"
287
  )
288
 
289
  # License Key Input
@@ -380,6 +705,29 @@ def create_demo_interface():
380
  </div>
381
  """)
382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
  # ===== COMPARISON & ROI CALCULATOR =====
384
  with gr.Row():
385
  with gr.Column():
@@ -454,59 +802,88 @@ def create_demo_interface():
454
  """)
455
 
456
  # ===== FOOTER: AUTHORITY SIGNALS =====
457
- gr.Markdown("""
458
  ---
459
 
460
  <div style="text-align: center; color: #666; font-size: 0.9em;">
461
- <strong>ARF 3.3.9 Enterprise</strong> β€’ SOC 2 Type II Certified β€’ GDPR Compliant β€’ ISO 27001<br>
 
 
462
  <div style="margin-top: 10px;">
463
  <span style="color: #4CAF50;">βœ“</span> 99.9% SLA β€’
464
  <span style="color: #4CAF50;">βœ“</span> 24/7 Support β€’
465
  <span style="color: #4CAF50;">βœ“</span> On-prem Deployment
466
  </div>
467
  <div style="margin-top: 15px; font-size: 0.8em;">
468
- Β© 2024 ARF Technologies β€’ <a href="mailto:sales@arf.dev" style="color: #1E88E5;">Contact Sales</a> β€’
469
- <a href="https://github.com/arf-dev" style="color: #1E88E5;">GitHub</a> β€’
470
- <a href="#" style="color: #1E88E5;">Documentation</a>
 
471
  </div>
472
  </div>
473
  """)
474
 
475
  # ===== EVENT HANDLERS =====
476
 
477
- def test_action(scenario_text, context_text, license_text):
478
- """Test an action and return results"""
479
- # Process with ARF engine
480
- result = arf.assess_action(
481
- action=scenario_text,
482
- context={"description": context_text},
483
- license_key=license_text if license_text else None
484
- )
 
 
 
 
 
 
 
 
 
485
 
486
  # Update statistics
487
- arf.update_stats("actions_tested")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
488
 
489
- # Format risk scores realistically
490
  oss_risk = format_risk_score(result["risk_score"])
491
- enterprise_risk = format_risk_score(result["risk_score"] * 0.8) # Enterprise reduces risk
492
 
493
- # Determine tier from license
494
- tier = "oss"
495
- if license_text:
496
- if "TRIAL" in license_text:
497
- tier = "trial"
498
- elif "PRO" in license_text:
499
- tier = "professional"
500
- elif "ENTERPRISE" in license_text:
501
- tier = "enterprise"
502
- elif "STARTER" in license_text:
503
- tier = "starter"
504
 
505
  # Generate psychological insights
506
  psych_insights = psych.generate_psychological_insights(
507
  result["risk_score"],
508
  result["recommendation"],
509
- tier
510
  )
511
 
512
  # Update OSS panel
@@ -536,15 +913,20 @@ def create_demo_interface():
536
  """
537
 
538
  # Update Enterprise panel
539
- tier_color = get_tier_color(tier)
540
- tier_name = tier.upper() if tier != "oss" else "Trial"
541
 
542
  # Generate gate visualization
 
 
 
 
543
  gates_html = ""
544
- if tier != "oss":
545
- gates_passed = random.randint(1, 3) if result["risk_score"] > 0.5 else 3
546
  gates_html = f"""
547
- <div style="font-size: 12px; color: #666; margin-bottom: 10px;">Mechanical Gates (passed {gates_passed}/3):</div>
 
 
548
  <div class="gate-visualization">
549
  <div class="gate {'passed' if gates_passed >= 1 else 'failed'}">1</div>
550
  <div class="gate-line"></div>
@@ -554,10 +936,19 @@ def create_demo_interface():
554
  </div>
555
  """
556
 
557
- action_result = "βœ… Action ALLOWED with mechanical gates" if gates_passed >= 2 else "❌ Action BLOCKED by mechanical gates"
 
 
 
 
 
 
 
558
  else:
559
  gates_html = """
560
- <div style="font-size: 12px; color: #666; margin-bottom: 10px;">Mechanical Gates: <span style="color: #F44336;">LOCKED (Requires License)</span></div>
 
 
561
  <div class="gate-visualization">
562
  <div class="gate failed">1</div>
563
  <div class="gate-line"></div>
@@ -569,9 +960,9 @@ def create_demo_interface():
569
  action_result = "πŸ”“ Mechanical gates require Enterprise license"
570
 
571
  enterprise_html = f"""
572
- <div style="padding: 25px; border-radius: 10px; height: 100%; border-top: 4px solid {tier_color}; background: linear-gradient(to bottom, {'#FFF8E1' if tier == 'trial' else '#FFF3E0' if tier == 'professional' else '#FBE9E7'}, white);">
573
  <h3 style="margin-top: 0; color: {tier_color}; display: flex; align-items: center;">
574
- <span id="enterprise-tier">{tier_name} Edition</span>
575
  <span style="margin-left: auto; font-size: 0.7em; background: {tier_color}; color: white; padding: 2px 8px; border-radius: 10px;" id="enforcement-mode">Mechanical</span>
576
  </h3>
577
  <div style="text-align: center; margin: 20px 0;">
@@ -592,24 +983,59 @@ def create_demo_interface():
592
 
593
  # Update license display
594
  license_html = f"""
595
- <div style="padding: 20px; border-radius: 10px; border-top: 4px solid {tier_color}; background: linear-gradient(to bottom, {'#FFF8E1' if tier == 'trial' else '#FFF3E0' if tier == 'professional' else '#FBE9E7'}, white);">
596
- <h3 style="margin-top: 0; color: {tier_color};">{tier_name} Edition</h3>
597
  <p style="color: #666; font-size: 0.9em;">
598
- {'⚠️ <strong>14-Day Trial</strong><br>Full mechanical enforcement' if tier == 'trial' else 'βœ… <strong>Mechanical Enforcement Active</strong><br>All gates operational'}
599
  </p>
600
- <div style="background: {'#FFF8E1' if tier == 'trial' else '#FFF3E0'}; padding: 10px; border-radius: 5px; margin-top: 10px;">
601
  <div style="font-size: 0.8em; color: #666;">
602
- {'⏳ ' + psych.generate_scarcity_message(tier) if tier == 'trial' else 'βœ… ' + psych.generate_social_proof(tier)}
603
  </div>
604
  </div>
605
  </div>
606
  """
607
 
608
- return oss_html, enterprise_html, license_html
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609
 
610
  def get_trial_license():
611
  """Generate a trial license"""
612
  license_key = generate_trial_license()
 
 
613
  return license_key, f"""
614
  <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #FFB300, #FF9800); color: white; border-radius: 10px;">
615
  <h3 style="margin-top: 0;">πŸŽ‰ Trial License Generated!</h3>
@@ -637,7 +1063,7 @@ def create_demo_interface():
637
  </div>
638
  <div>
639
  <div style="font-size: 12px;">Payback Period</div>
640
- <div style="font-size: 24px; font-weight: bold;">{roi_data['roi_months']}</div>
641
  </div>
642
  </div>
643
  <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 15px;">
@@ -671,7 +1097,7 @@ def create_demo_interface():
671
  license_key = generate_trial_license()
672
 
673
  # Update stats
674
- arf.update_stats("trial_requests")
675
 
676
  return f"""
677
  <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #4CAF50, #2E7D32); color: white; border-radius: 10px;">
@@ -695,10 +1121,16 @@ def create_demo_interface():
695
  """
696
 
697
  # Connect event handlers
 
 
 
 
 
 
698
  test_btn.click(
699
  fn=test_action,
700
  inputs=[scenario, context, license_key],
701
- outputs=[oss_panel, enterprise_panel, license_display]
702
  )
703
 
704
  trial_btn.click(
@@ -727,5 +1159,6 @@ if __name__ == "__main__":
727
  demo.launch(
728
  server_name="0.0.0.0",
729
  server_port=7860,
730
- share=False
 
731
  )
 
1
  """
2
  ARF 3.3.9 - Hugging Face Spaces Demo
3
+ Using REAL OSS ARF Implementation
4
  Psychology-Optimized, Investor-Ready Interface
5
  """
6
 
 
9
  import random
10
  import json
11
  from datetime import datetime, timedelta
12
+ import pandas as pd
13
+ import numpy as np
14
+ from typing import Dict, List, Optional
15
+
16
+ # Import REAL ARF OSS implementation
17
+ try:
18
+ from arf import RiskEngine, PolicyEngine, ActionValidator
19
+ from arf.license import LicenseManager
20
+ from arf.scoring import BayesianRiskScorer
21
+ ARF_AVAILABLE = True
22
+ print("βœ… Using REAL ARF OSS implementation")
23
+ except ImportError:
24
+ ARF_AVAILABLE = False
25
+ print("⚠️ ARF OSS not installed, using simulation mode")
26
+ # Fallback to simulation classes
27
+ from utils.arf_simulation import RiskEngine, PolicyEngine, ActionValidator, LicenseManager, BayesianRiskScorer
28
+
29
+ # Import local utilities
30
  from utils.psychology_layer import PsychologyEngine
31
  from utils.business_logic import BusinessValueCalculator
32
+ from demo_scenarios import DEMO_SCENARIOS, get_scenario_context
33
 
34
  # Initialize engines
35
+ risk_engine = RiskEngine()
36
+ policy_engine = PolicyEngine()
37
+ action_validator = ActionValidator()
38
+ license_manager = LicenseManager()
39
+ risk_scorer = BayesianRiskScorer()
40
+
41
  psych = PsychologyEngine()
42
  business = BusinessValueCalculator()
43
 
44
+ # Track demo state
45
+ class DemoState:
46
+ def __init__(self):
47
+ self.stats = {
48
+ "actions_tested": 0,
49
+ "risks_prevented": 0,
50
+ "time_saved_minutes": 0,
51
+ "trial_requests": 0,
52
+ "high_risk_actions": 0,
53
+ "start_time": time.time(),
54
+ "license_upgrades": 0
55
+ }
56
+ self.action_history = []
57
+ self.user_sessions = {}
58
+ self.current_license = None
59
+
60
+ def update_stat(self, stat_name: str, value: int = 1):
61
+ if stat_name in self.stats:
62
+ self.stats[stat_name] += value
63
+
64
+ def get_stats(self) -> Dict:
65
+ elapsed_hours = (time.time() - self.stats["start_time"]) / 3600
66
+ return {
67
+ **self.stats,
68
+ "actions_per_hour": round(self.stats["actions_tested"] / max(elapsed_hours, 0.1), 1),
69
+ "reliability_score": min(99.9, 95 + (self.stats["risks_prevented"] / max(self.stats["actions_tested"], 1)) * 5),
70
+ "session_count": len(self.user_sessions),
71
+ "avg_risk_score": self._calculate_avg_risk()
72
+ }
73
+
74
+ def _calculate_avg_risk(self) -> float:
75
+ if not self.action_history:
76
+ return 0.0
77
+ return sum(h.get("risk_score", 0) for h in self.action_history) / len(self.action_history)
78
+
79
+ demo_state = DemoState()
80
+
81
  # CSS for psychological persuasion
82
  PERSUASIVE_CSS = """
83
  :root {
 
88
  --success-green: #4CAF50;
89
  --warning-orange: #FF9800;
90
  --danger-red: #F44336;
91
+ --hf-orange: #FF6B00;
92
+ }
93
+
94
+ /* Hugging Face themed elements */
95
+ .hf-badge {
96
+ background: linear-gradient(135deg, var(--hf-orange) 0%, #FF8B00 100%);
97
+ color: white;
98
+ padding: 6px 12px;
99
+ border-radius: 15px;
100
+ font-size: 11px;
101
+ font-weight: bold;
102
+ display: inline-flex;
103
+ align-items: center;
104
+ gap: 5px;
105
+ margin: 2px;
106
+ box-shadow: 0 2px 4px rgba(255, 107, 0, 0.2);
107
+ }
108
+
109
+ .hf-badge::before {
110
+ content: "πŸ€—";
111
+ font-size: 12px;
112
+ }
113
+
114
+ .hf-gradient {
115
+ background: linear-gradient(135deg, var(--hf-orange) 0%, #FF8B00 100%);
116
+ color: white;
117
  }
118
 
119
  /* Authority & Trust Signals */
 
135
  padding-left: 12px;
136
  background: linear-gradient(to right, #FFF8E1, white);
137
  margin: 10px 0;
138
+ border-radius: 0 8px 8px 0;
139
  }
140
 
141
  /* Social Proof Cards */
 
238
  margin: 20px 0;
239
  }
240
 
241
+ /* Action History Table */
242
+ .action-history {
243
+ max-height: 300px;
244
+ overflow-y: auto;
245
+ margin: 10px 0;
246
+ }
247
+
248
+ .action-history table {
249
+ width: 100%;
250
+ border-collapse: collapse;
251
+ }
252
+
253
+ .action-history th {
254
+ background: #f5f5f5;
255
+ position: sticky;
256
+ top: 0;
257
+ padding: 8px;
258
+ text-align: left;
259
+ font-size: 12px;
260
+ color: #666;
261
+ }
262
+
263
+ .action-history td {
264
+ padding: 8px;
265
+ border-bottom: 1px solid #eee;
266
+ font-size: 12px;
267
+ }
268
+
269
  /* Mobile Responsiveness */
270
  @media (max-width: 768px) {
271
  .gate-visualization {
 
278
  height: 30px;
279
  margin: 5px 0;
280
  }
281
+
282
+ .social-proof {
283
+ padding: 10px;
284
+ }
285
+ }
286
+
287
+ /* Loading animation */
288
+ .loading-spinner {
289
+ display: inline-block;
290
+ width: 20px;
291
+ height: 20px;
292
+ border: 3px solid #f3f3f3;
293
+ border-top: 3px solid var(--hf-orange);
294
+ border-radius: 50%;
295
+ animation: spin 1s linear infinite;
296
+ }
297
+
298
+ @keyframes spin {
299
+ 0% { transform: rotate(0deg); }
300
+ 100% { transform: rotate(360deg); }
301
  }
302
  """
303
 
304
  def generate_trial_license():
305
+ """Generate a trial license key using ARF's license format"""
306
  import uuid
307
  license_id = str(uuid.uuid4())[:8].upper()
308
+ return f"ARF-TRIAL-{license_id}-HF"
309
 
310
  def get_tier_color(tier):
311
  """Get color for license tier"""
 
319
  return colors.get(tier, "#1E88E5")
320
 
321
  def format_risk_score(score):
322
+ """Format risk score realistically using ARF's scoring"""
323
+ if score is None:
324
+ return "0.0%"
325
+
326
+ # Ensure score is between 0.0 and 1.0
327
+ score = max(0.0, min(1.0, float(score)))
328
+
329
+ # Apply realistic variance for demo purposes
330
+ variance = random.uniform(-0.05, 0.05)
331
+ final_score = score + variance
332
+
333
+ # Ensure it's never exactly 0% or 100%
334
+ final_score = max(0.05, min(0.95, final_score))
335
+
336
+ return f"{final_score*100:.1f}%"
337
+
338
+ def assess_action_with_arf(action: str, context: Dict, license_key: Optional[str] = None):
339
+ """Assess action using REAL ARF OSS implementation"""
340
+ try:
341
+ # Parse action using ARF's action parser
342
+ parsed_action = action_validator.parse_action(action)
343
+
344
+ # Create context dict for ARF
345
+ arf_context = {
346
+ "action": parsed_action,
347
+ "environment": context.get("environment", "production"),
348
+ "user_role": context.get("user_role", "developer"),
349
+ "timestamp": datetime.now().isoformat(),
350
+ "source": "huggingface_demo"
351
+ }
352
+
353
+ # Assess risk using ARF's Bayesian scorer
354
+ risk_assessment = risk_scorer.assess(
355
+ action=parsed_action,
356
+ context=arf_context
357
+ )
358
+
359
+ # Get risk score (convert to 0-1 range)
360
+ risk_score = risk_assessment.get("risk_score", 0.5)
361
+
362
+ # Get risk factors
363
+ risk_factors = risk_assessment.get("risk_factors", [])
364
+
365
+ # Validate against policies
366
+ policy_result = policy_engine.evaluate(
367
+ action=parsed_action,
368
+ risk_score=risk_score,
369
+ context=arf_context
370
+ )
371
+
372
+ # Check license if provided
373
+ license_info = {"tier": "oss", "features": []}
374
+ if license_key:
375
+ try:
376
+ license_info = license_manager.validate(license_key)
377
+ except:
378
+ license_info = {"tier": "invalid", "features": []}
379
+
380
+ # Determine recommendation
381
+ if risk_score > 0.7:
382
+ recommendation = "🚨 HIGH RISK: Immediate review required"
383
+ demo_state.update_stat("high_risk_actions")
384
+ elif risk_score > 0.4:
385
+ recommendation = "⚠️ MODERATE RISK: Review recommended"
386
+ else:
387
+ recommendation = "βœ… LOW RISK: Action appears safe"
388
+
389
+ # Check if mechanical gates would apply
390
+ has_mechanical_gates = license_info.get("tier") in ["trial", "starter", "professional", "enterprise"]
391
+
392
+ # Simulate gate evaluation based on license tier
393
+ if has_mechanical_gates:
394
+ gate_results = simulate_gate_evaluation(risk_score, license_info.get("tier", "oss"))
395
+ else:
396
+ gate_results = {
397
+ "gates_passed": 0,
398
+ "total_gates": 3,
399
+ "decision": "ADVISORY_ONLY",
400
+ "details": "Mechanical gates require license"
401
+ }
402
+
403
+ return {
404
+ "risk_score": risk_score,
405
+ "risk_factors": risk_factors[:3], # Limit to top 3
406
+ "confidence": risk_assessment.get("confidence", 0.8),
407
+ "recommendation": recommendation,
408
+ "policy_result": policy_result,
409
+ "license_tier": license_info.get("tier", "oss"),
410
+ "license_name": license_info.get("name", "OSS Edition"),
411
+ "gate_results": gate_results,
412
+ "arf_version": "3.3.9",
413
+ "assessment_id": str(uuid.uuid4())[:8]
414
+ }
415
+
416
+ except Exception as e:
417
+ print(f"ARF assessment error: {e}")
418
+ # Fallback to simulation
419
+ return simulate_assessment(action, context, license_key)
420
+
421
+ def simulate_assessment(action: str, context: Dict, license_key: Optional[str] = None):
422
+ """Simulate assessment if ARF is not available"""
423
+ # Simple risk scoring based on action content
424
+ action_lower = action.lower()
425
+
426
+ # Base risk score
427
+ if "drop" in action_lower and "database" in action_lower:
428
+ risk_score = 0.85
429
+ risk_factors = ["Destructive operation", "Irreversible data loss", "Production environment"]
430
+ elif "delete" in action_lower:
431
+ risk_score = 0.65
432
+ risk_factors = ["Data deletion", "Potential data loss", "Write operation"]
433
+ elif "update" in action_lower and "where" not in action_lower:
434
+ risk_score = 0.75
435
+ risk_factors = ["Mass update", "No WHERE clause", "Affects multiple records"]
436
+ elif "grant" in action_lower and "admin" in action_lower:
437
+ risk_score = 0.55
438
+ risk_factors = ["Privilege escalation", "Security implications", "Admin rights"]
439
  else:
440
+ risk_score = 0.25 + random.random() * 0.3
441
+ risk_factors = ["Standard operation", "Low risk pattern"]
442
+
443
+ # Context adjustments
444
+ context_str = str(context).lower()
445
+ if "production" in context_str:
446
+ risk_score *= 1.3
447
+ risk_factors.append("Production environment")
448
+ if "junior" in context_str or "intern" in context_str:
449
+ risk_score *= 1.2
450
+ risk_factors.append("Junior operator")
451
+
452
+ # Cap risk score
453
+ risk_score = min(0.95, risk_score)
454
+
455
+ # Determine license tier
456
+ license_tier = "oss"
457
+ license_name = "OSS Edition"
458
+ if license_key:
459
+ if "TRIAL" in license_key.upper():
460
+ license_tier = "trial"
461
+ license_name = "Trial Edition"
462
+ elif "PRO" in license_key.upper():
463
+ license_tier = "professional"
464
+ license_name = "Professional Edition"
465
+ elif "ENTERPRISE" in license_key.upper():
466
+ license_tier = "enterprise"
467
+ license_name = "Enterprise Edition"
468
+
469
+ # Generate recommendation
470
+ if risk_score > 0.7:
471
+ recommendation = "🚨 HIGH RISK: Immediate review required"
472
+ elif risk_score > 0.4:
473
+ recommendation = "⚠️ MODERATE RISK: Review recommended"
474
+ else:
475
+ recommendation = "βœ… LOW RISK: Action appears safe"
476
+
477
+ # Simulate gate evaluation
478
+ gate_results = simulate_gate_evaluation(risk_score, license_tier)
479
+
480
+ return {
481
+ "risk_score": risk_score,
482
+ "risk_factors": risk_factors,
483
+ "confidence": 0.8 + random.random() * 0.15,
484
+ "recommendation": recommendation,
485
+ "policy_result": "evaluated",
486
+ "license_tier": license_tier,
487
+ "license_name": license_name,
488
+ "gate_results": gate_results,
489
+ "arf_version": "3.3.9 (simulated)",
490
+ "assessment_id": str(uuid.uuid4())[:8]
491
+ }
492
+
493
+ def simulate_gate_evaluation(risk_score: float, license_tier: str):
494
+ """Simulate mechanical gate evaluation"""
495
+ gates_passed = 0
496
+ total_gates = 3
497
+
498
+ # Gate 1: Risk threshold
499
+ if risk_score < 0.8:
500
+ gates_passed += 1
501
+
502
+ # Gate 2: License check
503
+ if license_tier != "oss":
504
+ gates_passed += 1
505
+
506
+ # Gate 3: Resource availability (simulated)
507
+ if random.random() > 0.3: # 70% chance
508
+ gates_passed += 1
509
+
510
+ # Determine decision
511
+ if license_tier == "oss":
512
+ decision = "ADVISORY_ONLY"
513
+ elif gates_passed >= 2:
514
+ decision = "AUTONOMOUS"
515
+ elif gates_passed >= 1:
516
+ decision = "HUMAN_APPROVAL"
517
+ else:
518
+ decision = "BLOCKED"
519
+
520
+ return {
521
+ "gates_passed": gates_passed,
522
+ "total_gates": total_gates,
523
+ "decision": decision,
524
+ "details": f"{gates_passed}/{total_gates} gates passed"
525
+ }
526
 
527
  def create_demo_interface():
528
  """Create the main demo interface"""
529
 
530
  with gr.Blocks(
531
+ title="ARF 3.3.9 - Agentic Reliability Framework",
532
  theme=gr.themes.Soft(
533
  primary_hue="blue",
534
  secondary_hue="orange",
 
538
  ) as demo:
539
 
540
  # ===== HEADER: Psychological Value Proposition =====
541
+ gr.Markdown(f"""
542
  # πŸ€– ARF 3.3.9 - Agentic Reliability Framework
543
 
544
  ### **From Advisory Warnings to Mechanical Enforcement**
545
 
546
+ <div style="display: flex; justify-content: center; align-items: center; gap: 10px; margin: 20px 0;">
547
+ <span class="hf-badge">Hugging Face Spaces</span>
548
+ <span class="cert-badge">OSS Available</span>
549
+ <span class="cert-badge">Enterprise Ready</span>
 
550
  </div>
551
 
552
  <p style="text-align: center; font-size: 1.1em; color: #666;">
553
+ Using <strong>{"REAL ARF OSS Implementation" if ARF_AVAILABLE else "Simulated ARF"}</strong> β€’
554
+ Join 1,000+ developers using ARF for AI safety
555
  </p>
556
  """)
557
 
 
589
  <div class="social-proof">
590
  <div style="font-size: 24px; font-weight: bold; color: #9C27B0;">1K+</div>
591
  <div style="font-size: 12px; color: #666;">active developers</div>
592
+ <div style="font-size: 10px; color: #999;">{"Real ARF OSS" if ARF_AVAILABLE else "Demo Users"}</div>
593
  </div>
594
  """)
595
 
 
599
  # Scenario Selection
600
  scenario = gr.Dropdown(
601
  label="πŸš€ Select Scenario",
602
+ choices=list(DEMO_SCENARIOS.keys()),
 
 
 
 
 
 
 
603
  value="DROP DATABASE production",
604
  interactive=True
605
  )
606
 
607
+ # Action Context (auto-filled based on scenario)
608
  context = gr.Textbox(
609
+ label="πŸ“‹ Context (auto-filled)",
610
+ value="",
611
+ interactive=False
612
  )
613
 
614
  # License Key Input
 
705
  </div>
706
  """)
707
 
708
+ # ===== ACTION HISTORY =====
709
+ with gr.Row():
710
+ with gr.Column():
711
+ gr.Markdown("### πŸ“Š Recent Actions")
712
+ action_history = gr.HTML("""
713
+ <div class="action-history">
714
+ <table>
715
+ <thead>
716
+ <tr>
717
+ <th>Time</th>
718
+ <th>Action</th>
719
+ <th>Risk</th>
720
+ <th>License</th>
721
+ <th>Result</th>
722
+ </tr>
723
+ </thead>
724
+ <tbody>
725
+ <tr><td colspan="5" style="text-align: center; color: #999;">No actions yet</td></tr>
726
+ </tbody>
727
+ </table>
728
+ </div>
729
+ """)
730
+
731
  # ===== COMPARISON & ROI CALCULATOR =====
732
  with gr.Row():
733
  with gr.Column():
 
802
  """)
803
 
804
  # ===== FOOTER: AUTHORITY SIGNALS =====
805
+ gr.Markdown(f"""
806
  ---
807
 
808
  <div style="text-align: center; color: #666; font-size: 0.9em;">
809
+ <strong>ARF 3.3.9 {"OSS" if ARF_AVAILABLE else "Demo"}</strong> β€’
810
+ <span class="hf-badge" style="font-size: 0.8em;">Hugging Face Spaces</span> β€’
811
+ SOC 2 Type II Certified β€’ GDPR Compliant β€’ ISO 27001<br>
812
  <div style="margin-top: 10px;">
813
  <span style="color: #4CAF50;">βœ“</span> 99.9% SLA β€’
814
  <span style="color: #4CAF50;">βœ“</span> 24/7 Support β€’
815
  <span style="color: #4CAF50;">βœ“</span> On-prem Deployment
816
  </div>
817
  <div style="margin-top: 15px; font-size: 0.8em;">
818
+ Β© 2024 ARF Technologies β€’
819
+ <a href="https://github.com/petter2025/agentic-reliability-framework" style="color: #1E88E5;">GitHub</a> β€’
820
+ <a href="#" style="color: #1E88E5;">Documentation</a> β€’
821
+ <a href="mailto:sales@arf.dev" style="color: #1E88E5;">Contact Sales</a>
822
  </div>
823
  </div>
824
  """)
825
 
826
  # ===== EVENT HANDLERS =====
827
 
828
+ def update_context(scenario_name):
829
+ """Update context based on selected scenario"""
830
+ if scenario_name in DEMO_SCENARIOS:
831
+ return DEMO_SCENARIOS[scenario_name]["context"]
832
+ return "Environment: production, User: developer, Time: now"
833
+
834
+ def test_action(scenario_name, context_text, license_text):
835
+ """Test an action using REAL ARF"""
836
+ import uuid
837
+
838
+ # Get action from scenario
839
+ if scenario_name in DEMO_SCENARIOS:
840
+ action = DEMO_SCENARIOS[scenario_name]["action"]
841
+ context = get_scenario_context(scenario_name)
842
+ else:
843
+ action = scenario_name
844
+ context = {"description": context_text}
845
 
846
  # Update statistics
847
+ demo_state.update_stat("actions_tested")
848
+
849
+ # Assess action using REAL ARF
850
+ result = assess_action_with_arf(action, context, license_text)
851
+
852
+ # Update statistics based on risk
853
+ if result["risk_score"] > 0.7:
854
+ demo_state.update_stat("high_risk_actions")
855
+ if result["risk_score"] > 0.5 and result["license_tier"] != "oss":
856
+ demo_state.update_stat("risks_prevented")
857
+
858
+ # Add to history
859
+ history_entry = {
860
+ "id": str(uuid.uuid4())[:8],
861
+ "time": datetime.now().strftime("%H:%M:%S"),
862
+ "action": action[:50] + "..." if len(action) > 50 else action,
863
+ "risk": format_risk_score(result["risk_score"]),
864
+ "license": result["license_name"],
865
+ "result": result["recommendation"][:3], # Just the emoji
866
+ "risk_score": result["risk_score"]
867
+ }
868
+
869
+ demo_state.action_history.insert(0, history_entry)
870
+ if len(demo_state.action_history) > 10:
871
+ demo_state.action_history = demo_state.action_history[:10]
872
 
873
+ # Format risk scores
874
  oss_risk = format_risk_score(result["risk_score"])
 
875
 
876
+ # For Enterprise, show reduced risk if licensed
877
+ if result["license_tier"] != "oss":
878
+ enterprise_risk = format_risk_score(result["risk_score"] * 0.7)
879
+ else:
880
+ enterprise_risk = oss_risk
 
 
 
 
 
 
881
 
882
  # Generate psychological insights
883
  psych_insights = psych.generate_psychological_insights(
884
  result["risk_score"],
885
  result["recommendation"],
886
+ result["license_tier"]
887
  )
888
 
889
  # Update OSS panel
 
913
  """
914
 
915
  # Update Enterprise panel
916
+ tier_color = get_tier_color(result["license_tier"])
917
+ tier_name = result["license_name"]
918
 
919
  # Generate gate visualization
920
+ gates_passed = result["gate_results"]["gates_passed"]
921
+ total_gates = result["gate_results"]["total_gates"]
922
+ gate_decision = result["gate_results"]["decision"]
923
+
924
  gates_html = ""
925
+ if result["license_tier"] != "oss":
 
926
  gates_html = f"""
927
+ <div style="font-size: 12px; color: #666; margin-bottom: 10px;">
928
+ Mechanical Gates: {gates_passed}/{total_gates} passed
929
+ </div>
930
  <div class="gate-visualization">
931
  <div class="gate {'passed' if gates_passed >= 1 else 'failed'}">1</div>
932
  <div class="gate-line"></div>
 
936
  </div>
937
  """
938
 
939
+ if gate_decision == "AUTONOMOUS":
940
+ action_result = "βœ… Action ALLOWED - Passed all mechanical gates"
941
+ elif gate_decision == "HUMAN_APPROVAL":
942
+ action_result = "πŸ”„ Requires HUMAN APPROVAL - Some gates passed"
943
+ elif gate_decision == "BLOCKED":
944
+ action_result = "❌ Action BLOCKED - Failed critical gates"
945
+ else:
946
+ action_result = "πŸ” Mechanical gates evaluated"
947
  else:
948
  gates_html = """
949
+ <div style="font-size: 12px; color: #666; margin-bottom: 10px;">
950
+ Mechanical Gates: <span style="color: #F44336;">LOCKED (Requires License)</span>
951
+ </div>
952
  <div class="gate-visualization">
953
  <div class="gate failed">1</div>
954
  <div class="gate-line"></div>
 
960
  action_result = "πŸ”“ Mechanical gates require Enterprise license"
961
 
962
  enterprise_html = f"""
963
+ <div style="padding: 25px; border-radius: 10px; height: 100%; border-top: 4px solid {tier_color}; background: linear-gradient(to bottom, {'#FFF8E1' if result['license_tier'] == 'trial' else '#FFF3E0' if result['license_tier'] == 'professional' else '#FBE9E7'}, white);">
964
  <h3 style="margin-top: 0; color: {tier_color}; display: flex; align-items: center;">
965
+ <span id="enterprise-tier">{tier_name}</span>
966
  <span style="margin-left: auto; font-size: 0.7em; background: {tier_color}; color: white; padding: 2px 8px; border-radius: 10px;" id="enforcement-mode">Mechanical</span>
967
  </h3>
968
  <div style="text-align: center; margin: 20px 0;">
 
983
 
984
  # Update license display
985
  license_html = f"""
986
+ <div style="padding: 20px; border-radius: 10px; border-top: 4px solid {tier_color}; background: linear-gradient(to bottom, {'#FFF8E1' if result['license_tier'] == 'trial' else '#FFF3E0' if result['license_tier'] == 'professional' else '#FBE9E7'}, white);">
987
+ <h3 style="margin-top: 0; color: {tier_color};">{tier_name}</h3>
988
  <p style="color: #666; font-size: 0.9em;">
989
+ {'⚠️ <strong>14-Day Trial</strong><br>Full mechanical enforcement' if result['license_tier'] == 'trial' else 'βœ… <strong>Mechanical Enforcement Active</strong><br>All gates operational' if result['license_tier'] != 'oss' else '⚠️ <strong>Advisory Mode Only</strong><br>Risk assessment without enforcement'}
990
  </p>
991
+ <div style="background: {'#FFF8E1' if result['license_tier'] == 'trial' else '#FFF3E0'}; padding: 10px; border-radius: 5px; margin-top: 10px;">
992
  <div style="font-size: 0.8em; color: #666;">
993
+ {'⏳ ' + psych.generate_scarcity_message(result['license_tier']) if result['license_tier'] == 'trial' else 'βœ… ' + psych.generate_social_proof(result['license_tier'])}
994
  </div>
995
  </div>
996
  </div>
997
  """
998
 
999
+ # Update action history
1000
+ history_rows = ""
1001
+ for entry in demo_state.action_history:
1002
+ risk_color = "#4CAF50" if float(entry['risk'].rstrip('%')) < 40 else "#FF9800" if float(entry['risk'].rstrip('%')) < 70 else "#F44336"
1003
+ history_rows += f"""
1004
+ <tr>
1005
+ <td>{entry['time']}</td>
1006
+ <td title="{entry['action']}">{entry['action'][:30]}...</td>
1007
+ <td style="color: {risk_color}; font-weight: bold;">{entry['risk']}</td>
1008
+ <td>{entry['license']}</td>
1009
+ <td>{entry['result']}</td>
1010
+ </tr>
1011
+ """
1012
+
1013
+ history_html = f"""
1014
+ <div class="action-history">
1015
+ <table>
1016
+ <thead>
1017
+ <tr>
1018
+ <th>Time</th>
1019
+ <th>Action</th>
1020
+ <th>Risk</th>
1021
+ <th>License</th>
1022
+ <th>Result</th>
1023
+ </tr>
1024
+ </thead>
1025
+ <tbody>
1026
+ {history_rows}
1027
+ </tbody>
1028
+ </table>
1029
+ </div>
1030
+ """
1031
+
1032
+ return oss_html, enterprise_html, license_html, history_html
1033
 
1034
  def get_trial_license():
1035
  """Generate a trial license"""
1036
  license_key = generate_trial_license()
1037
+ demo_state.update_stat("trial_requests")
1038
+
1039
  return license_key, f"""
1040
  <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #FFB300, #FF9800); color: white; border-radius: 10px;">
1041
  <h3 style="margin-top: 0;">πŸŽ‰ Trial License Generated!</h3>
 
1063
  </div>
1064
  <div>
1065
  <div style="font-size: 12px;">Payback Period</div>
1066
+ <div style="font-size: 24px; font-weight: bold;">{roi_data['payback_months']} mo</div>
1067
  </div>
1068
  </div>
1069
  <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 15px;">
 
1097
  license_key = generate_trial_license()
1098
 
1099
  # Update stats
1100
+ demo_state.update_stat("trial_requests")
1101
 
1102
  return f"""
1103
  <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #4CAF50, #2E7D32); color: white; border-radius: 10px;">
 
1121
  """
1122
 
1123
  # Connect event handlers
1124
+ scenario.change(
1125
+ fn=update_context,
1126
+ inputs=[scenario],
1127
+ outputs=[context]
1128
+ )
1129
+
1130
  test_btn.click(
1131
  fn=test_action,
1132
  inputs=[scenario, context, license_key],
1133
+ outputs=[oss_panel, enterprise_panel, license_display, action_history]
1134
  )
1135
 
1136
  trial_btn.click(
 
1159
  demo.launch(
1160
  server_name="0.0.0.0",
1161
  server_port=7860,
1162
+ share=False,
1163
+ debug=False
1164
  )