# COMPLETE FIXED hf_demo.py with all syntax errors resolved # ARF 3.3.9 DEMO WITH FIXED HTML RENDERING AND SYNTAX ERRORS 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 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 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 ============== 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 correctly shows REAL OSS when installed""" print("\nšŸ” INITIATING UNIFIED ARF DETECTION...") # Try REAL ARF OSS 3.3.9 first try: print("šŸ” Attempting import: agentic_reliability_framework") import agentic_reliability_framework as 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 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"{'='*80}\n") # ============== INITIALIZE ENGINES ============== arf_engine = EnhancedARFEngine() psychology_engine = EnhancedPsychologyEngine() # ============== ENHANCED CSS ============== ENHANCED_CSS = """ .arf-real-badge { background: linear-gradient(135deg, #4CAF50, #2E7D32, #1B5E20, #0D47A1); color: white; padding: 10px 22px; border-radius: 25px; font-size: 16px; 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; } .arf-sim-badge { background: linear-gradient(135deg, #FF9800, #F57C00, #E65100, #BF360C); color: white; padding: 10px 22px; border-radius: 25px; font-size: 16px; 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); } @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); } } .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); } .gate-passed { background: linear-gradient(135deg, #4CAF50, #2E7D32); } .gate-failed { background: linear-gradient(135deg, #F44336, #D32F2F); } .gate-pending { background: linear-gradient(135deg, #9E9E9E, #616161); } .gate-container { display: flex; align-items: center; justify-content: center; gap: 10px; margin: 20px 0; flex-wrap: wrap; } .gate-line { width: 40px; height: 4px; background: linear-gradient(90deg, #E0E0E0, #BDBDBD); border-radius: 2px; } .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; background: #FFFFFF; box-shadow: 0 8px 30px rgba(0,0,0,0.08); } .mathematical-card:hover { transform: translateY(-5px); box-shadow: 0 15px 40px rgba(0,0,0,0.15); } .license-oss { border-top-color: #1E88E5; background: linear-gradient(145deg, #E3F2FD, #FFFFFF); } .license-trial { border-top-color: #FFB300; background: linear-gradient(145deg, #FFF8E1, #FFFFFF); } @media (max-width: 768px) { .gradio-container { padding: 10px !important; } .arf-real-badge, .arf-sim-badge { padding: 6px 14px; font-size: 12px; } .mathematical-gate { width: 50px; height: 50px; font-size: 18px; } .gate-line { width: 20px; } .mathematical-card { padding: 15px; margin: 10px 0; } } @media (max-width: 480px) { .gradio-container { padding: 5px !important; } .arf-real-badge, .arf-sim-badge { padding: 4px 10px; font-size: 11px; } .mathematical-gate { width: 40px; height: 40px; font-size: 16px; } } """ # ============== HELPER FUNCTIONS ============== def generate_mathematical_trial_license() -> str: """Generate mathematically structured trial license""" segments = [] for _ in range(4): 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: return f'{emoji} {risk_text} ({category})
{confidence:.0%} conf' 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 return f"""
95% CI: {lower_pct:.0f}% - {upper_pct:.0f}% | Score: {score_pct:.0f}%
""" # ============== DEMO STATE ============== class EnhancedDemoState: """Demo state with mathematical tracking""" def __init__(self, arf_status: Dict[str, Any]): self.arf_status = arf_status self.stats = { 'actions_tested': 0, 'start_time': time.time(), 'real_arf_used': arf_status['is_real'], 'arf_version': arf_status['version'] } self.action_history = [] self.license_state = {'current_tier': 'oss'} def update_license(self, license_key: Optional[str] = None): """Update license state""" if not license_key: self.license_state = {'current_tier': 'oss'} return license_upper = license_key.upper() if 'ARF-TRIAL' in license_upper: self.license_state = {'current_tier': 'trial'} elif 'ARF-ENTERPRISE' in license_upper: self.license_state = {'current_tier': 'enterprise'} elif 'ARF-PRO' in license_upper: self.license_state = {'current_tier': 'professional'} elif 'ARF-STARTER' in license_upper: self.license_state = {'current_tier': 'starter'} else: self.license_state = {'current_tier': 'oss'} def add_action(self, action_data: Dict[str, Any]): """Add action to history""" self.action_history.insert(0, action_data) if len(self.action_history) > 10: self.action_history = self.action_history[:10] self.stats['actions_tested'] += 1 # Initialize demo state demo_state = EnhancedDemoState(ARF_UNIFIED_STATUS) # ============== GRADIO INTERFACE ============== def create_enhanced_demo(): """Create enhanced demo with fixed HTML rendering bugs""" # Get unified status arf_display = ARF_UNIFIED_STATUS['display_text'] arf_badge_class = ARF_UNIFIED_STATUS['badge_class'] with gr.Blocks( title=f"ARF {ARF_UNIFIED_STATUS['version']} - Mathematical Sophistication", theme=gr.themes.Soft(primary_hue="blue", secondary_hue="orange"), css=ENHANCED_CSS ) as demo: # ===== HEADER ===== gr.HTML(f"""

šŸ¤– ARF {ARF_UNIFIED_STATUS['version']}

Agentic Reliability Framework

PhD-Level Mathematical Sophistication • Prospect Theory Optimization

{arf_display} šŸ¤— Hugging Face Spaces License-Gated Execution Authority

Mathematical Foundation: Bayesian Inference • Prospect Theory • Confidence Intervals
Business Model: License-Gated Execution Authority • Market: Enterprise AI Infrastructure • Investor-Ready: PhD-Level Mathematical Sophistication

""") # ===== METRICS ===== with gr.Row(): metrics = [ ("92%", "Incident Prevention", "Bayesian confidence: 95%", "#4CAF50", "šŸ“Š"), ("$3.9M", "Avg. Breach Cost", "Preventable with mechanical gates", "#2196F3", "šŸ’°"), ("3.2 mo", "Payback Period", "Mathematical ROI calculation", "#FF9800", "šŸ“ˆ"), ("1K+", "Active Developers", "Social proof optimization", "#9C27B0", "šŸ‘Øā€šŸ’»") ] for value, title, subtitle, color, icon in metrics: with gr.Column(scale=1, min_width=200): gr.HTML(f"""
{icon} {value}
{title}
{subtitle}
""") # ===== SECTION HEADER ===== gr.HTML("""

🧮 Mathematical Execution Authority Demo

Test how Bayesian risk assessment and mechanical gates prevent unsafe AI actions

""") # ===== CONTROL PANEL ===== with gr.Row(): with gr.Column(scale=2): scenario = gr.Dropdown( label="šŸ¢ Select Enterprise Scenario", choices=[ "DROP DATABASE production", "DELETE FROM users WHERE status='active'", "GRANT admin TO new_intern", "SHUTDOWN production cluster", "UPDATE financial_records SET balance=0", "DEPLOY untested_model production" ], value="DROP DATABASE production", interactive=True ) context = gr.Textbox( label="šŸ“‹ Mathematical Context Analysis", value="Environment: production, User: junior_dev, Time: 2AM, Backup: 24h old, Compliance: PCI-DSS", interactive=False ) license_key = gr.Textbox( label="šŸ” License Key (Mechanical Gate)", placeholder="Enter ARF-TRIAL-XXXX for 14-day trial or ARF-ENTERPRISE-XXXX", value="" ) with gr.Row(): test_btn = gr.Button("⚔ Test Mathematical Assessment", variant="primary", scale=2) trial_btn = gr.Button("šŸŽ Generate Mathematical Trial", variant="secondary", scale=1) # ===== LICENSE DISPLAY ===== with gr.Column(scale=1): license_display = gr.HTML(f"""

OSS Edition Advisory Only

āš ļø No Mechanical Enforcement
Bayesian risk assessment only

Execution Level: ADVISORY_ONLY
Risk Prevention: 0%
Confidence Threshold: None
ARF Status: {arf_display}
""") # ===== RESULTS PANELS ===== with gr.Row(): with gr.Column(scale=1): oss_results = gr.HTML("""

OSS Bayesian Assessment Advisory

--
Risk Score (Bayesian)
🚨 Mathematical Risk Analysis:
• $3.9M expected financial exposure
• 0% mechanical prevention rate
• No confidence intervals for execution
šŸ“‹ Bayesian Recommendation:
Awaiting mathematical assessment...
""") with gr.Column(scale=1): enterprise_results = gr.HTML(f"""

Trial Edition Mechanical

--
Risk Score (Bayesian)
Mathematical Gates:
1
2
3
šŸ›”ļø Mechanical Enforcement:
Awaiting mathematical assessment...
""") # ===== EVENT HANDLERS ===== def update_context(scenario_name): """Update context with mathematical analysis""" scenarios = { "DROP DATABASE production": "Environment: production, User: junior_dev, Time: 2AM, Backup: 24h old, Compliance: PCI-DSS, Risk Multiplier: 1.5x", "DELETE FROM users WHERE status='active'": "Environment: production, User: admin, Records: 50,000, Backup: none, Business Hours: Yes, Risk Multiplier: 1.3x", "GRANT admin TO new_intern": "Environment: production, User: team_lead, New User: intern, MFA: false, Approval: Pending, Risk Multiplier: 1.2x", "SHUTDOWN production cluster": "Environment: production, User: devops, Nodes: 50, Redundancy: none, Business Impact: Critical, Risk Multiplier: 1.8x", "UPDATE financial_records SET balance=0": "Environment: production, User: finance_bot, Table: financial_records, Audit Trail: Incomplete, Risk Multiplier: 1.4x", "DEPLOY untested_model production": "Environment: production, User: ml_engineer, Model: untested, Tests: none, Rollback: difficult, Risk Multiplier: 1.6x" } return scenarios.get(scenario_name, "Environment: production, Risk Multiplier: 1.0x") def test_mathematical_assessment(scenario_name, context_text, license_text): """Test action with mathematical sophistication""" start_time = time.time() # Update license demo_state.update_license(license_text) # Parse context context = {} multipliers = {} for item in context_text.split(','): if ':' in item: key, value = item.split(':', 1) key = key.strip().lower() value = value.strip() context[key] = value # Extract multipliers if 'multiplier' in key: try: multipliers[key] = float(value.replace('x', '')) except: pass # Simulate enhanced assessment action_lower = scenario_name.lower() # Base risk calculation base_risk = 0.3 if 'drop database' in action_lower: base_risk = 0.85 risk_factors = ["Irreversible data destruction", "Service outage", "High financial impact"] elif 'delete' in action_lower: base_risk = 0.65 risk_factors = ["Data loss", "Write operation", "Recovery complexity"] elif 'grant' in action_lower and 'admin' in action_lower: base_risk = 0.55 risk_factors = ["Privilege escalation", "Security risk", "Access control"] elif 'shutdown' in action_lower: base_risk = 0.9 risk_factors = ["Service disruption", "Revenue impact", "Recovery time"] elif 'update' in action_lower and 'financial' in action_lower: base_risk = 0.75 risk_factors = ["Financial data", "Audit impact", "Compliance risk"] elif 'deploy' in action_lower and 'untested' in action_lower: base_risk = 0.7 risk_factors = ["Untested model", "Production risk", "Rollback difficulty"] else: base_risk = 0.45 risk_factors = ["Standard operation", "Moderate risk"] # Apply context multipliers risk_multiplier = 1.0 if context.get('environment') == 'production': risk_multiplier *= 1.5 if 'junior' in context.get('user', '').lower() or 'intern' in context.get('user', '').lower(): risk_multiplier *= 1.3 if context.get('backup') in ['none', 'none available', 'old']: risk_multiplier *= 1.6 if '2am' in context.get('time', '').lower() or 'night' in context.get('time', '').lower(): risk_multiplier *= 1.4 if 'pci' in context.get('compliance', '').lower() or 'hipaa' in context.get('compliance', '').lower(): risk_multiplier *= 1.3 # Apply any explicit multipliers for mult_key, mult_value in multipliers.items(): risk_multiplier *= mult_value final_risk = base_risk * risk_multiplier final_risk = min(0.99, max(0.1, final_risk)) # Calculate confidence confidence = 0.8 + (random.random() * 0.15) # Confidence interval ci_lower = max(0.1, final_risk - (0.2 * (1 - confidence))) ci_upper = min(1.0, final_risk + (0.2 * (1 - confidence))) # Risk category if final_risk > 0.8: risk_category = "CRITICAL" elif final_risk > 0.6: risk_category = "HIGH" elif final_risk > 0.4: risk_category = "MEDIUM" else: risk_category = "LOW" # Mechanical gates simulation gates_passed = 0 total_gates = 3 license_tier = demo_state.license_state['current_tier'] # Gate 1: Risk Assessment if final_risk < 0.8: gates_passed += 1 # Gate 2: License Validation if license_tier != 'oss': gates_passed += 1 # Gate 3: Context Check if 'production' not in context.get('environment', '').lower() or final_risk < 0.7: gates_passed += 1 # Additional gates for higher tiers if license_tier == 'professional': total_gates = 5 if final_risk < 0.6: gates_passed += 1 if 'backup' not in context or context.get('backup') not in ['none', 'none available']: gates_passed += 1 if license_tier == 'enterprise': total_gates = 7 if final_risk < 0.5: gates_passed += 1 if context.get('compliance') in ['pci-dss', 'hipaa', 'gdpr']: gates_passed += 1 if 'approval' in context.get('user', '').lower() or 'senior' in context.get('user', '').lower(): gates_passed += 1 # Gate decision if gates_passed == total_gates: gate_decision = "AUTONOMOUS" gate_reason = "All mathematical gates passed" elif gates_passed >= total_gates * 0.7: gate_decision = "SUPERVISED" gate_reason = "Most gates passed, requires monitoring" elif gates_passed >= total_gates * 0.5: gate_decision = "HUMAN_APPROVAL" gate_reason = "Requires human review and approval" else: gate_decision = "BLOCKED" gate_reason = "Failed critical mathematical gates" # Create action data action_data = { 'time': datetime.now().strftime("%H:%M:%S"), 'action': scenario_name[:40] + "..." if len(scenario_name) > 40 else scenario_name, 'risk_score': final_risk, 'confidence': confidence, 'risk_category': risk_category, 'license_tier': license_tier.upper(), 'gates_passed': gates_passed, 'total_gates': total_gates, 'gate_decision': gate_decision, 'processing_time_ms': round((time.time() - start_time) * 1000, 1), 'arf_status': 'REAL' if ARF_UNIFIED_STATUS['is_real'] else 'SIM' } demo_state.add_action(action_data) # Format outputs risk_formatted = format_mathematical_risk(final_risk, confidence) confidence_interval_html = create_confidence_interval_html(ci_lower, ci_upper, final_risk) # OSS recommendation if final_risk > 0.8: oss_rec = "🚨 CRITICAL RISK: Would be mathematically blocked by mechanical gates. Enterprise license required for protection." elif final_risk > 0.6: oss_rec = "āš ļø HIGH RISK: Requires Bayesian analysis and human review. Mechanical gates automate this mathematically." elif final_risk > 0.4: oss_rec = "šŸ”¶ MODERATE RISK: Bayesian confidence suggests review. Mathematical gates provide probabilistic safety." else: oss_rec = "āœ… LOW RISK: Bayesian analysis indicates safety. Mathematical gates add confidence intervals." # Enterprise enforcement if gate_decision == "BLOCKED": enforcement = f"āŒ MATHEMATICALLY BLOCKED: {gate_reason}. Risk factors: {', '.join(risk_factors[:2])}" elif gate_decision == "HUMAN_APPROVAL": enforcement = f"šŸ”„ MATHEMATICAL REVIEW: {gate_reason}. Bayesian confidence: {confidence:.0%}" elif gate_decision == "SUPERVISED": enforcement = f"šŸ‘ļø MATHEMATICAL SUPERVISION: {gate_reason}. Gates passed: {gates_passed}/{total_gates}" else: enforcement = f"āœ… MATHEMATICAL APPROVAL: {gate_reason}. Confidence interval: {ci_lower:.0%}-{ci_upper:.0%}" # Gate visualization gates_visualization = "" for i in range(total_gates): gate_class = "gate-passed" if i < gates_passed else "gate-failed" gates_visualization += f'
{i+1}
' if i < total_gates - 1: gates_visualization += '
' gates_html = f"""
Mathematical Gates: {gates_passed}/{total_gates} passed ({(gates_passed/total_gates)*100:.0f}%)
{gates_visualization}
""" # Tier info tier_data = { 'oss': {'color': '#1E88E5', 'bg': '#E3F2FD', 'name': 'OSS Edition'}, 'trial': {'color': '#FFB300', 'bg': '#FFF8E1', 'name': 'Trial Edition'}, 'starter': {'color': '#FF9800', 'bg': '#FFF3E0', 'name': 'Starter Edition'}, 'professional': {'color': '#FF6F00', 'bg': '#FFEBEE', 'name': 'Professional Edition'}, 'enterprise': {'color': '#D84315', 'bg': '#FBE9E7', 'name': 'Enterprise Edition'} } current_tier = license_tier tier_info = tier_data.get(current_tier, tier_data['oss']) # Update panels oss_html = f"""

OSS Bayesian Assessment Advisory

{risk_formatted}
Risk Score (Bayesian)
{confidence_interval_html}
🚨 Mathematical Risk Analysis:
• ${final_risk * 5000000:,.0f} expected financial exposure
• 0% mechanical prevention rate
• {ci_lower:.0%}-{ci_upper:.0%} confidence interval
šŸ“‹ Bayesian Recommendation:
{oss_rec}
""" enterprise_html = f"""

{tier_info['name']} Mechanical

{risk_formatted}
Risk Score (Bayesian)
{confidence_interval_html}
{gates_html}
šŸ›”ļø Mechanical Enforcement:
{enforcement}
""" license_html = f"""

{tier_info['name']} Active

{'āš ļø 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'}

Execution Level: {'AUTONOMOUS_HIGH' if current_tier == 'enterprise' else 'OPERATOR_REVIEW' if current_tier == 'trial' else 'ADVISORY_ONLY'}
Risk Prevention: {92 if current_tier == 'enterprise' else 85 if current_tier == 'professional' else 70 if current_tier == 'starter' else 50 if current_tier == 'trial' else 0}%
Confidence Threshold: {90 if current_tier == 'enterprise' else 80 if current_tier == 'professional' else 70 if current_tier == 'starter' else 60 if current_tier == 'trial' else 0}%
ARF Status: {arf_display}
""" # Build history rows history_rows_html = "" for entry in demo_state.action_history: risk_text = format_mathematical_risk(entry['risk_score']) confidence_text = f"{entry.get('confidence', 0.8):.0%}" gates_text = f"{entry['gates_passed']}/{entry['total_gates']}" gates_color = "#4CAF50" if entry['gates_passed'] == entry['total_gates'] else "#F44336" if entry['gates_passed'] == 0 else "#FF9800" arf_emoji = "āœ…" if entry['arf_status'] == 'REAL' else "āš ļø" decision_emoji = { "AUTONOMOUS": "āœ…", "SUPERVISED": "šŸ‘ļø", "HUMAN_APPROVAL": "šŸ”„", "BLOCKED": "āŒ" }.get(entry['gate_decision'], "⚔") history_rows_html += f''' {entry['time']} {entry['action'][:35]}... {risk_text} {confidence_text} {entry['license_tier']} {gates_text} {decision_emoji} {arf_emoji} ''' # Build history table if history_rows_html: history_table = f""" {history_rows_html}
Time Action Risk Confidence License Gates Decision ARF
""" else: history_table = """
No mathematical assessments yet. Test an action to see Bayesian analysis in action.
""" # Final history HTML history_html = f"""

šŸ“Š Mathematical Action History

{history_table}
""" return oss_html, enterprise_html, license_html, history_html def generate_trial(): """Generate mathematical trial license""" license_key = generate_mathematical_trial_license() return license_key, f"""

šŸŽ‰ Mathematical Trial License Generated!

{license_key}

Copy this key and paste it into the License Key field above.

ā³ 14-day mathematical trial
🧮 Bayesian analysis with confidence intervals
šŸ›”ļø Mechanical gates with mathematical weights
""" # Connect handlers scenario.change( fn=update_context, inputs=[scenario], outputs=[context] ) test_btn.click( fn=test_mathematical_assessment, inputs=[scenario, context, license_key], outputs=[oss_results, enterprise_results, license_display] ) trial_btn.click( fn=generate_trial, inputs=[], outputs=[license_key] ) return demo # ============== MAIN EXECUTION ============== if __name__ == "__main__": print("\n" + "="*80) print("šŸš€ LAUNCHING FIXED ARF 3.3.9 DEMO") print("šŸ“Š ARF Status:", ARF_UNIFIED_STATUS['display_text']) print("="*80) demo = create_enhanced_demo() demo.launch( server_name="0.0.0.0", server_port=7860, share=False, debug=False )