"""
ARF 3.3.9 - Enterprise Demo with Enhanced Psychology & Mathematics
FIXED: Shows "REAL ARF OSS 3.3.9" when real ARF is installed
ADDED: PhD-level mathematical sophistication with Bayesian confidence
ADDED: Prospect Theory psychological optimization
"""
import gradio as gr
import time
import random
import json
import uuid
import subprocess
import sys
import importlib
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple, Any, Union
import numpy as np
import pandas as pd
# Import enhanced engines
try:
from utils.arf_engine_enhanced import EnhancedARFEngine, BayesianRiskAssessment, RiskCategory
from utils.psychology_layer_enhanced import EnhancedPsychologyEngine
ARF_ENGINE_ENHANCED = True
print("ā
Enhanced ARF Engine loaded successfully")
except ImportError as e:
print(f"ā ļø Enhanced engines not available: {e}")
print("š Creating fallback engines...")
ARF_ENGINE_ENHANCED = False
# Fallback classes (simplified versions)
class EnhancedARFEngine:
def __init__(self):
self.arf_status = "SIMULATION"
def assess_action(self, action, context, license_key):
return {
"risk_assessment": {"score": 0.5, "confidence": 0.8},
"recommendation": "Simulated assessment",
"arf_status": "SIMULATION"
}
class EnhancedPsychologyEngine:
def generate_comprehensive_insights(self, *args, **kwargs):
return {"psychological_summary": "Basic psychological framing"}
# ============== UNIFIED ARF DETECTION (FIXED) ==============
print("=" * 80)
print("š ARF 3.3.9 ENHANCED DEMO INITIALIZATION")
print("š UNIFIED DETECTION: Single Source of Truth")
print("=" * 80)
def detect_unified_arf() -> Dict[str, Any]:
"""
Unified ARF detection that FIXES the "SIMULATED" display bug
Returns a single source of truth for the entire demo
"""
print("\nš INITIATING UNIFIED ARF DETECTION...")
# Try REAL ARF OSS 3.3.9 first (from requirements.txt)
try:
print("š Attempting import: agentic_reliability_framework")
import agentic_reliability_framework as arf
# Verify this is real ARF
version = getattr(arf, '__version__', '3.3.9')
print(f"ā
REAL ARF OSS {version} DETECTED")
return {
'status': 'REAL_OSS',
'is_real': True,
'version': version,
'source': 'agentic_reliability_framework',
'display_text': f'ā
REAL OSS {version}',
'badge_class': 'arf-real-badge',
'badge_css': 'arf-real',
'unified_truth': True,
'enterprise_ready': True
}
except ImportError:
print("ā ļø agentic_reliability_framework not directly importable")
# Try pip installation check
try:
print("š Checking pip installation...")
result = subprocess.run(
[sys.executable, "-m", "pip", "show", "agentic-reliability-framework"],
capture_output=True,
text=True,
timeout=5
)
if result.returncode == 0:
version = "3.3.9"
for line in result.stdout.split('\n'):
if line.startswith('Version:'):
version = line.split(':')[1].strip()
print(f"ā
ARF {version} installed via pip")
return {
'status': 'PIP_INSTALLED',
'is_real': True,
'version': version,
'source': 'pip_installation',
'display_text': f'ā
REAL OSS {version} (pip)',
'badge_class': 'arf-real-badge',
'badge_css': 'arf-real',
'unified_truth': True,
'enterprise_ready': True
}
except Exception as e:
print(f"ā ļø Pip check failed: {e}")
# Fallback to enhanced simulation
print("ā ļø Using enhanced enterprise simulation")
return {
'status': 'ENHANCED_SIMULATION',
'is_real': False,
'version': '3.3.9',
'source': 'enhanced_simulation',
'display_text': 'ā ļø ENTERPRISE SIMULATION 3.3.9',
'badge_class': 'arf-sim-badge',
'badge_css': 'arf-sim',
'unified_truth': True,
'enterprise_ready': True
}
# Get unified ARF status (SINGLE SOURCE OF TRUTH)
ARF_UNIFIED_STATUS = detect_unified_arf()
print(f"\n{'='*80}")
print("š UNIFIED ARF STATUS CONFIRMED:")
print(f" Display: {ARF_UNIFIED_STATUS['display_text']}")
print(f" Real ARF: {'ā
YES' if ARF_UNIFIED_STATUS['is_real'] else 'ā ļø SIMULATION'}")
print(f" Version: {ARF_UNIFIED_STATUS['version']}")
print(f" Source: {ARF_UNIFIED_STATUS['source']}")
print(f" Unified Truth: {'ā
ACTIVE' if ARF_UNIFIED_STATUS.get('unified_truth', False) else 'ā INACTIVE'}")
print(f"{'='*80}\n")
# ============== INITIALIZE ENHANCED ENGINES ==============
arf_engine = EnhancedARFEngine()
psychology_engine = EnhancedPsychologyEngine()
# Set ARF status in engine
arf_engine.set_arf_status(ARF_UNIFIED_STATUS['status'])
# ============== ENHANCED DEMO STATE ==============
class EnhancedDemoState:
"""Enhanced demo state with mathematical tracking"""
def __init__(self, arf_status: Dict[str, Any]):
# Bind to unified ARF status
self.arf_status = arf_status
# Mathematical statistics
self.stats = {
'actions_tested': 0,
'risks_prevented': 0,
'high_risk_blocked': 0,
'license_validations': 0,
'mechanical_gates_triggered': 0,
'total_processing_time_ms': 0,
'average_confidence': 0.0,
'average_risk': 0.0,
'start_time': time.time(),
'real_arf_used': arf_status['is_real'],
'arf_version': arf_status['version'],
'display_text': arf_status['display_text']
}
self.action_history = []
self.license_state = {
'current_tier': 'oss',
'current_license': None,
'execution_level': 'ADVISORY_ONLY'
}
def update_license(self, license_key: Optional[str] = None):
"""Update license state with enhanced validation"""
if not license_key:
self.license_state = {
'current_tier': 'oss',
'current_license': None,
'execution_level': 'ADVISORY_ONLY'
}
return
license_upper = license_key.upper()
if 'ARF-TRIAL' in license_upper:
self.license_state = {
'current_tier': 'trial',
'current_license': license_key,
'execution_level': 'OPERATOR_REVIEW',
'trial_expiry': time.time() + (14 * 24 * 3600),
'days_remaining': 14
}
self.stats['trial_licenses'] = self.stats.get('trial_licenses', 0) + 1
elif 'ARF-ENTERPRISE' in license_upper:
self.license_state = {
'current_tier': 'enterprise',
'current_license': license_key,
'execution_level': 'AUTONOMOUS_HIGH'
}
self.stats['enterprise_upgrades'] = self.stats.get('enterprise_upgrades', 0) + 1
elif 'ARF-PRO' in license_upper:
self.license_state = {
'current_tier': 'professional',
'current_license': license_key,
'execution_level': 'AUTONOMOUS_LOW'
}
elif 'ARF-STARTER' in license_upper:
self.license_state = {
'current_tier': 'starter',
'current_license': license_key,
'execution_level': 'SUPERVISED'
}
else:
self.license_state = {
'current_tier': 'oss',
'current_license': license_key,
'execution_level': 'ADVISORY_ONLY'
}
def add_action(self, action_data: Dict[str, Any]):
"""Add action with mathematical tracking"""
self.action_history.insert(0, action_data)
if len(self.action_history) > 10:
self.action_history = self.action_history[:10]
# Update statistics with mathematical precision
self.stats['actions_tested'] += 1
if action_data.get('risk_score', 0) > 0.7:
self.stats['high_risk_blocked'] += 1
if action_data.get('gate_decision') == 'BLOCKED':
self.stats['risks_prevented'] += 1
if action_data.get('license_tier') != 'oss':
self.stats['license_validations'] += 1
if action_data.get('total_gates', 0) > 0:
self.stats['mechanical_gates_triggered'] += 1
# Update rolling averages
n = self.stats['actions_tested']
old_avg_risk = self.stats.get('average_risk', 0)
old_avg_conf = self.stats.get('average_confidence', 0)
new_risk = action_data.get('risk_score', 0.5)
new_conf = action_data.get('confidence', 0.8)
self.stats['average_risk'] = old_avg_risk + (new_risk - old_avg_risk) / n
self.stats['average_confidence'] = old_avg_conf + (new_conf - old_avg_conf) / n
# Add processing time
self.stats['total_processing_time_ms'] = self.stats.get('total_processing_time_ms', 0) + \
action_data.get('processing_time_ms', 0)
def get_enhanced_stats(self) -> Dict[str, Any]:
"""Get enhanced statistics with mathematical insights"""
elapsed_hours = (time.time() - self.stats['start_time']) / 3600
# Calculate prevention rate
prevention_rate = 0.0
if self.stats['actions_tested'] > 0:
prevention_rate = self.stats['risks_prevented'] / self.stats['actions_tested']
# Calculate gate effectiveness
gate_effectiveness = 0.0
if self.stats['mechanical_gates_triggered'] > 0:
gate_effectiveness = self.stats['risks_prevented'] / self.stats['mechanical_gates_triggered']
# Calculate average processing time
avg_processing_time = 0.0
if self.stats['actions_tested'] > 0:
avg_processing_time = self.stats['total_processing_time_ms'] / self.stats['actions_tested']
return {
**self.stats,
'actions_per_hour': round(self.stats['actions_tested'] / max(elapsed_hours, 0.1), 1),
'prevention_rate': round(prevention_rate * 100, 1),
'gate_effectiveness': round(gate_effectiveness * 100, 1),
'average_risk_percentage': round(self.stats['average_risk'] * 100, 1),
'average_confidence_percentage': round(self.stats['average_confidence'] * 100, 1),
'average_processing_time_ms': round(avg_processing_time, 1),
'demo_duration_hours': round(elapsed_hours, 2),
'reliability_score': min(99.99, 95 + (prevention_rate * 5)),
'current_license_tier': self.license_state['current_tier'].upper(),
'current_execution_level': self.license_state['execution_level']
}
# Initialize demo state
demo_state = EnhancedDemoState(ARF_UNIFIED_STATUS)
# ============== ENHANCED CSS WITH PSYCHOLOGICAL COLORS ==============
ENHANCED_CSS = """
:root {
/* Mathematical Color Psychology */
--mathematical-blue: #2196F3;
--mathematical-green: #4CAF50;
--mathematical-orange: #FF9800;
--mathematical-red: #F44336;
--mathematical-purple: #9C27B0;
/* Prospect Theory Colors */
--prospect-gain: linear-gradient(135deg, #4CAF50, #2E7D32);
--prospect-loss: linear-gradient(135deg, #F44336, #D32F2F);
/* Bayesian Confidence Colors */
--confidence-high: rgba(76, 175, 80, 0.9);
--confidence-medium: rgba(255, 152, 0, 0.9);
--confidence-low: rgba(244, 67, 54, 0.9);
/* License Tier Colors */
--oss-color: #1E88E5;
--trial-color: #FFB300;
--starter-color: #FF9800;
--professional-color: #FF6F00;
--enterprise-color: #D84315;
}
/* Mathematical Badges */
.arf-real-badge {
background: linear-gradient(135deg,
#4CAF50 0%, /* Success green - trust */
#2E7D32 25%, /* Deep green - stability */
#1B5E20 50%, /* Forest green - growth */
#0D47A1 100% /* Mathematical blue - precision */
);
color: white;
padding: 8px 18px;
border-radius: 25px;
font-size: 14px;
font-weight: bold;
display: inline-flex;
align-items: center;
gap: 10px;
margin: 5px;
box-shadow: 0 6px 20px rgba(76, 175, 80, 0.4);
border: 3px solid rgba(255, 255, 255, 0.4);
animation: pulse-mathematical 2.5s infinite;
position: relative;
overflow: hidden;
}
.arf-real-badge::before {
content: "ā
";
font-size: 18px;
filter: drop-shadow(0 3px 5px rgba(0,0,0,0.3));
z-index: 2;
}
.arf-real-badge::after {
content: '';
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background: linear-gradient(
45deg,
transparent 30%,
rgba(255, 255, 255, 0.1) 50%,
transparent 70%
);
animation: shine 3s infinite;
}
.arf-sim-badge {
background: linear-gradient(135deg,
#FF9800 0%, /* Warning orange - attention */
#F57C00 25%, /* Deep orange - caution */
#E65100 50%, /* Dark orange - urgency */
#BF360C 100% /* Mathematical warning - precision */
);
color: white;
padding: 8px 18px;
border-radius: 25px;
font-size: 14px;
font-weight: bold;
display: inline-flex;
align-items: center;
gap: 10px;
margin: 5px;
box-shadow: 0 6px 20px rgba(255, 152, 0, 0.4);
border: 3px solid rgba(255, 255, 255, 0.4);
}
.arf-sim-badge::before {
content: "ā ļø";
font-size: 18px;
filter: drop-shadow(0 3px 5px rgba(0,0,0,0.3));
}
@keyframes pulse-mathematical {
0% {
box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.7),
0 6px 20px rgba(76, 175, 80, 0.4);
}
70% {
box-shadow: 0 0 0 15px rgba(76, 175, 80, 0),
0 6px 20px rgba(76, 175, 80, 0.4);
}
100% {
box-shadow: 0 0 0 0 rgba(76, 175, 80, 0),
0 6px 20px rgba(76, 175, 80, 0.4);
}
}
@keyframes shine {
0% { transform: translateX(-100%) translateY(-100%) rotate(45deg); }
100% { transform: translateX(100%) translateY(100%) rotate(45deg); }
}
/* Bayesian Confidence Visualizations */
.confidence-interval {
height: 30px;
background: linear-gradient(90deg,
var(--confidence-low) 0%,
var(--confidence-medium) 50%,
var(--confidence-high) 100%
);
border-radius: 15px;
margin: 15px 0;
position: relative;
overflow: hidden;
}
.confidence-interval::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: repeating-linear-gradient(
90deg,
transparent,
transparent 5px,
rgba(255, 255, 255, 0.1) 5px,
rgba(255, 255, 255, 0.1) 10px
);
}
.interval-marker {
position: absolute;
top: 0;
height: 100%;
width: 4px;
background: white;
transform: translateX(-50%);
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
/* Mathematical Gate Visualization */
.mathematical-gate {
width: 70px;
height: 70px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
color: white;
font-size: 24px;
position: relative;
box-shadow: 0 8px 25px rgba(0,0,0,0.3);
z-index: 2;
transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}
.mathematical-gate:hover {
transform: scale(1.1) rotate(5deg);
box-shadow: 0 12px 35px rgba(0,0,0,0.4);
}
.gate-passed {
background: linear-gradient(135deg, #4CAF50, #2E7D32);
animation: gate-success-mathematical 0.7s ease-out;
}
.gate-failed {
background: linear-gradient(135deg, #F44336, #D32F2F);
animation: gate-fail-mathematical 0.7s ease-out;
}
.gate-pending {
background: linear-gradient(135deg, #9E9E9E, #616161);
}
@keyframes gate-success-mathematical {
0% {
transform: scale(0.5) rotate(-180deg);
opacity: 0;
}
60% {
transform: scale(1.2) rotate(10deg);
}
80% {
transform: scale(0.95) rotate(-5deg);
}
100% {
transform: scale(1) rotate(0deg);
opacity: 1;
}
}
@keyframes gate-fail-mathematical {
0% { transform: scale(1) rotate(0deg); }
25% { transform: scale(1.1) rotate(-5deg); }
50% { transform: scale(0.9) rotate(5deg); }
75% { transform: scale(1.05) rotate(-3deg); }
100% { transform: scale(1) rotate(0deg); }
}
/* Prospect Theory Risk Visualization */
.prospect-risk-meter {
height: 35px;
background: linear-gradient(90deg,
#4CAF50 0%, /* Gains domain */
#FFC107 50%, /* Reference point */
#F44336 100% /* Losses domain (amplified) */
);
border-radius: 17.5px;
margin: 20px 0;
position: relative;
overflow: hidden;
box-shadow: inset 0 2px 10px rgba(0,0,0,0.2);
}
.prospect-risk-marker {
position: absolute;
top: -5px;
height: 45px;
width: 8px;
background: white;
border-radius: 4px;
transform: translateX(-50%);
box-shadow: 0 0 15px rgba(0,0,0,0.7);
transition: left 1s cubic-bezier(0.34, 1.56, 0.64, 1);
z-index: 3;
}
/* Mathematical License Cards */
.mathematical-card {
border-radius: 15px;
padding: 25px;
margin: 15px 0;
transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
border-top: 6px solid;
position: relative;
overflow: hidden;
}
.mathematical-card::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: linear-gradient(90deg,
rgba(255,255,255,0) 0%,
rgba(255,255,255,0.8) 50%,
rgba(255,255,255,0) 100%
);
}
.mathematical-card:hover {
transform: translateY(-5px);
box-shadow: 0 15px 40px rgba(0,0,0,0.15);
}
.license-oss {
border-top-color: var(--oss-color);
background: linear-gradient(145deg, #E3F2FD, #FFFFFF);
}
.license-trial {
border-top-color: var(--trial-color);
background: linear-gradient(145deg, #FFF8E1, #FFFFFF);
}
.license-starter {
border-top-color: var(--starter-color);
background: linear-gradient(145deg, #FFF3E0, #FFFFFF);
}
.license-professional {
border-top-color: var(--professional-color);
background: linear-gradient(145deg, #FFEBEE, #FFFFFF);
}
.license-enterprise {
border-top-color: var(--enterprise-color);
background: linear-gradient(145deg, #FBE9E7, #FFFFFF);
}
/* Mathematical ROI Calculator */
.mathematical-roi {
background: linear-gradient(135deg,
#667eea 0%,
#764ba2 25%,
#2196F3 50%,
#00BCD4 100%
);
color: white;
padding: 30px;
border-radius: 20px;
margin: 30px 0;
box-shadow: 0 12px 40px rgba(102, 126, 234, 0.4);
position: relative;
overflow: hidden;
}
.mathematical-roi::before {
content: 'Ī£';
position: absolute;
top: 20px;
right: 20px;
font-size: 120px;
opacity: 0.1;
font-weight: bold;
font-family: 'Times New Roman', serif;
}
/* Responsive Design */
@media (max-width: 768px) {
.arf-real-badge, .arf-sim-badge {
padding: 6px 14px;
font-size: 12px;
}
.mathematical-gate {
width: 60px;
height: 60px;
font-size: 20px;
}
.mathematical-card {
padding: 20px;
}
}
"""
# ============== HELPER FUNCTIONS ==============
def generate_mathematical_trial_license() -> str:
"""Generate mathematically structured trial license"""
segments = []
for _ in range(4):
# Generate segment with mathematical pattern
segment = ''.join(random.choices('0123456789ABCDEF', k=4))
segments.append(segment)
return f"ARF-TRIAL-{segments[0]}-{segments[1]}-{segments[2]}-{segments[3]}"
def format_mathematical_risk(risk_score: float, confidence: float = None) -> str:
"""Format risk with mathematical precision"""
if risk_score > 0.8:
color = "#F44336"
emoji = "šØ"
category = "CRITICAL"
elif risk_score > 0.6:
color = "#FF9800"
emoji = "ā ļø"
category = "HIGH"
elif risk_score > 0.4:
color = "#FFC107"
emoji = "š¶"
category = "MEDIUM"
else:
color = "#4CAF50"
emoji = "ā
"
category = "LOW"
risk_text = f"{risk_score:.1%}"
if confidence:
confidence_text = f"{confidence:.0%} conf"
return f'{emoji} {risk_text} ({category})
{confidence_text}'
else:
return f'{emoji} {risk_text} ({category})'
def create_confidence_interval_html(lower: float, upper: float, score: float) -> str:
"""Create HTML visualization of confidence interval"""
lower_pct = lower * 100
upper_pct = upper * 100
score_pct = score * 100
width = upper_pct - lower_pct
left_pos = lower_pct
return f"""
ā ļø No Mechanical Enforcement
Bayesian risk assessment only
| Time | Action | Risk | Confidence | License | Gates | Decision | ARF |
|---|---|---|---|---|---|---|---|
| No mathematical assessments yet. Test an action to see Bayesian analysis in action. | |||||||
{'ā ļø 14-Day Mathematical Trial
Bayesian analysis + mechanical gates' if current_tier == 'trial' else 'ā
Enterprise License
PhD-level mathematical sophistication' if current_tier != 'oss' else 'ā ļø OSS Edition
Bayesian advisory only'}
| Time | Action | Risk | Confidence | License | Gates | Decision | ARF |
|---|
Copy this key and paste it into the License Key field above.
Please enter a valid enterprise email address to receive your mathematical trial license.
Your 14-day mathematical trial license has been sent to: