petter2025's picture
Update hf_demo.py
c72568f verified
raw
history blame
60.9 kB
"""
ARF 3.3.9 Demo - Enhanced with Psychological Persuasion
"""
import gradio as gr
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import json
import time
import uuid
import hashlib
import random
import traceback
print("=" * 70)
print("πŸš€ ARF 3.3.9 Demo - Enhanced with Psychological Persuasion")
print("=" * 70)
# ============================================================================
# CORE ENGINE WITH PSYCHOLOGICAL ELEMENTS
# ============================================================================
class ARFEngine:
"""ARF Engine with psychological optimization"""
def __init__(self):
self.stats = {
"total_processed": 0,
"blocked_actions": 0,
"autonomous_executions": 0,
"avg_processing_time": 0.0,
"history": []
}
# Industry benchmarks for social proof
self.benchmarks = {
"risk_reduction": 0.92,
"decision_speed": 100,
"false_positives": 0.85,
"cost_reduction": 0.75,
"customer_satisfaction": 0.94
}
# License tiers with psychological pricing
self.license_tiers = {
"trial": {
"name": "14-Day Trial",
"price": 0,
"enforcement": "advisory",
"features": ["Basic gates", "Limited audit", "Email support"],
"social_proof": "Used by 1,000+ developers",
"urgency": "⏳ Expires in 14 days"
},
"starter": {
"name": "Starter",
"price": 2000,
"enforcement": "human_approval",
"features": ["Human-in-loop gates", "Basic audit", "SLA 99.5%"],
"social_proof": "Trusted by 500+ growing companies",
"value_prop": "Perfect for teams starting with AI safety"
},
"professional": {
"name": "Professional",
"price": 5000,
"enforcement": "autonomous",
"features": ["Autonomous execution", "Advanced gates", "SLA 99.8%"],
"social_proof": "Preferred by 200+ scale-ups",
"value_prop": "For companies scaling AI operations"
},
"enterprise": {
"name": "Enterprise",
"price": 15000,
"enforcement": "full_mechanical",
"features": ["Full mechanical enforcement", "Compliance automation", "SLA 99.9%"],
"social_proof": "Deployed at 50+ Fortune 500 companies",
"value_prop": "Enterprise-grade AI safety and compliance"
}
}
print("βœ… ARF Engine initialized with psychological optimization")
def assess_action(self, action: str, context: dict, license_key: str = None) -> dict:
"""Assess action with psychological framing"""
start_time = time.time()
# 1. Risk Assessment
risk_score, confidence = self._calculate_risk(action, context)
# 2. Policy Evaluation
policy_result = self._evaluate_policies(action, context, risk_score)
# 3. License Validation
license_info = self._validate_license(license_key)
# 4. Gate Evaluation
gate_results = self._evaluate_gates(risk_score, confidence, policy_result, license_info)
# 5. Generate psychological insights
psych_insights = self._generate_psychological_insights(
risk_score, policy_result, license_info, gate_results
)
processing_time = time.time() - start_time
# Update statistics
self._update_stats(action, policy_result, gate_results, processing_time, license_info)
return {
"action": action,
"context": context,
"risk_score": risk_score,
"confidence": confidence,
"policy_result": policy_result,
"license_info": license_info,
"gate_results": gate_results,
"psych_insights": psych_insights,
"processing_time": processing_time,
"recommendation": self._generate_recommendation(policy_result, gate_results, license_info),
"timestamp": datetime.now().isoformat()
}
def _calculate_risk(self, action: str, context: dict) -> tuple:
"""Calculate risk with realistic scoring"""
action_lower = action.lower()
# Base risk factors
risk_factors = {
"destructiveness": self._calculate_destructiveness(action_lower),
"complexity": min(0.8, len(action.split()) * 0.05),
"environment": 0.8 if context.get("environment") == "production" else 0.3,
"reversibility": 0.9 if any(x in action_lower for x in ["drop", "truncate"]) else 0.3
}
# Weighted risk score
weights = {"destructiveness": 0.4, "complexity": 0.2, "environment": 0.3, "reversibility": 0.1}
risk_score = sum(risk_factors[k] * weights[k] for k in risk_factors)
# Confidence (higher for clear patterns)
if "drop database" in action_lower:
confidence = 0.95
elif "delete from" in action_lower:
confidence = 0.90
elif "deploy" in action_lower:
confidence = 0.85
else:
confidence = 0.80
return round(risk_score, 3), round(confidence, 3)
def _calculate_destructiveness(self, action: str) -> float:
"""Calculate destructiveness score"""
if "drop database" in action:
return 0.95
elif "delete from" in action:
return 0.85
elif "truncate" in action:
return 0.80
elif "rm -rf" in action:
return 0.99
return 0.3
def _evaluate_policies(self, action: str, context: dict, risk_score: float) -> dict:
"""Evaluate against safety policies"""
violations = []
action_lower = action.lower()
# Policy 1: No destructive operations in production
if ("drop" in action_lower or "delete" in action_lower) and context.get("environment") == "production":
violations.append({
"policy": "Destructive Operation Prevention",
"severity": "CRITICAL",
"action": "BLOCK",
"reason": "Irreversible action in production"
})
# Policy 2: High risk actions need review
if risk_score > 0.7:
violations.append({
"policy": "High Risk Review Required",
"severity": "HIGH",
"action": "REQUIRE_APPROVAL",
"reason": f"High risk score: {risk_score:.1%}"
})
# Policy 3: Production deployments need sufficient confidence
if "deploy" in action_lower and context.get("environment") == "production" and risk_score > 0.5:
violations.append({
"policy": "Production Deployment Safety",
"severity": "MEDIUM",
"action": "REQUIRE_APPROVAL",
"reason": "Production deployment requires additional review"
})
return {
"violations": violations,
"blocked": any(v["action"] == "BLOCK" for v in violations),
"requires_approval": any(v["action"] == "REQUIRE_APPROVAL" for v in violations),
"total_violations": len(violations)
}
def _validate_license(self, license_key: str = None) -> dict:
"""Validate license with enhanced information"""
if not license_key:
return {
"tier": "oss",
"valid": False,
"name": "OSS Edition",
"enforcement": "advisory",
"message": "πŸ”΅ Using ARF OSS (Open Source)",
"limitations": ["No mechanical enforcement", "Human decision required"],
"upgrade_cta": "Upgrade to Enterprise for mechanical gates"
}
if license_key.startswith("ARF-"):
if "TRIAL" in license_key:
return {
"tier": "trial",
"valid": True,
"name": "14-Day Trial",
"enforcement": "advisory",
"message": "🎁 Trial License Active",
"features": self.license_tiers["trial"]["features"],
"social_proof": self.license_tiers["trial"]["social_proof"],
"urgency": self.license_tiers["trial"]["urgency"]
}
elif "PRO" in license_key:
return {
"tier": "professional",
"valid": True,
"name": "Professional",
"enforcement": "autonomous",
"message": "βœ… Professional License Active",
"features": self.license_tiers["professional"]["features"],
"value_prop": self.license_tiers["professional"]["value_prop"],
"social_proof": self.license_tiers["professional"]["social_proof"]
}
elif "ENTERPRISE" in license_key:
return {
"tier": "enterprise",
"valid": True,
"name": "Enterprise",
"enforcement": "full_mechanical",
"message": "🏒 Enterprise License Active",
"features": self.license_tiers["enterprise"]["features"],
"value_prop": self.license_tiers["enterprise"]["value_prop"],
"social_proof": self.license_tiers["enterprise"]["social_proof"]
}
return {
"tier": "invalid",
"valid": False,
"name": "Invalid",
"enforcement": "advisory",
"message": "❌ Invalid License Key",
"upgrade_cta": "Get a valid license for full features"
}
def _evaluate_gates(self, risk_score: float, confidence: float, policy_result: dict, license_info: dict) -> list:
"""Evaluate mechanical gates"""
gates = []
# Gate 1: License Validation
gates.append({
"name": "License Validation",
"passed": license_info["valid"],
"message": license_info["message"],
"required": True,
"weight": 0.3
})
# Gate 2: Risk Threshold (depends on license tier)
risk_threshold = 0.8 if license_info["tier"] in ["professional", "enterprise"] else 0.7
gates.append({
"name": "Risk Assessment",
"passed": risk_score <= risk_threshold,
"message": f"Risk {risk_score:.1%} ≀ {risk_threshold:.0%} threshold",
"required": True,
"weight": 0.3
})
# Gate 3: Confidence Threshold
gates.append({
"name": "Confidence Threshold",
"passed": confidence >= 0.7,
"message": f"Confidence {confidence:.1%} β‰₯ 70%",
"required": True,
"weight": 0.2
})
# Gate 4: Policy Compliance
gates.append({
"name": "Policy Compliance",
"passed": not policy_result["blocked"],
"message": f"{policy_result['total_violations']} policy violation(s)",
"required": True,
"weight": 0.2
})
# Additional gates for higher tiers
if license_info["tier"] in ["professional", "enterprise"]:
gates.append({
"name": "Rollback Feasibility",
"passed": "drop" not in str(policy_result).lower(),
"message": "Rollback plan available",
"required": False,
"weight": 0.1
})
if license_info["tier"] == "enterprise":
gates.append({
"name": "Compliance Automation",
"passed": True,
"message": "GDPR/PCI/SOX compliant",
"required": False,
"weight": 0.1
})
return gates
def _generate_psychological_insights(self, risk_score: float, policy_result: dict, license_info: dict, gate_results: list) -> dict:
"""Generate psychological insights"""
# Loss Aversion Framing
if risk_score > 0.7:
loss_framing = f"⚠️ **Potential Loss**: This action could result in {random.choice(['data loss', 'service disruption', 'security breach', 'compliance violation'])}"
else:
loss_framing = "βœ… **Safe Operation**: Minimal risk of adverse outcomes"
# Social Proof
if license_info["tier"] == "oss":
social_proof = f"πŸ“Š **Industry Standard**: {int(self.benchmarks['risk_reduction'] * 100)}% of organizations using ARF Enterprise report reduced incidents"
else:
social_proof = license_info.get("social_proof", "Trusted by industry leaders")
# Scarcity Principle
if license_info["tier"] == "trial":
scarcity = license_info.get("urgency", "⏳ Limited time offer")
elif license_info["tier"] == "oss":
scarcity = "πŸš€ **Upgrade Opportunity**: Mechanical enforcement available"
else:
scarcity = "🌟 **Full Access**: Unlimited mechanical enforcement"
# Authority Signal
authority = "πŸ” **Enterprise-Grade**: Backed by 99.9% SLA and certified compliance"
# Value Proposition
if license_info["tier"] == "oss":
value_prop = "Upgrade to Enterprise for mechanical enforcement"
else:
value_prop = license_info.get("value_prop", "Enterprise-grade protection")
return {
"loss_aversion": loss_framing,
"social_proof": social_proof,
"scarcity": scarcity,
"authority": authority,
"value_proposition": value_prop,
"risk_level": self._get_risk_level(risk_score)
}
def _get_risk_level(self, score: float) -> str:
"""Get risk level description"""
if score >= 0.8:
return "πŸ”₯ CRITICAL"
elif score >= 0.6:
return "⚠️ HIGH"
elif score >= 0.4:
return "πŸ”Ά MEDIUM"
elif score >= 0.2:
return "βœ… LOW"
else:
return "πŸ›‘οΈ SAFE"
def _generate_recommendation(self, policy_result: dict, gate_results: list, license_info: dict) -> str:
"""Generate recommendation"""
if policy_result["blocked"]:
return "🚫 **BLOCKED**: Action violates safety policies"
all_gates_passed = all(g["passed"] for g in gate_results if g["required"])
if not license_info["valid"]:
return "πŸ”΅ **OSS ADVISORY**: Human review recommended"
elif all_gates_passed and license_info["tier"] in ["professional", "enterprise"]:
return "🟑 **ENTERPRISE APPROVED**: Autonomous execution permitted"
elif all_gates_passed and license_info["tier"] == "starter":
return "πŸ‘€ **HUMAN APPROVAL**: Gates passed, awaiting confirmation"
else:
return "⚠️ **REVIEW REQUIRED**: Additional validation needed"
def _update_stats(self, action: str, policy_result: dict, gate_results: list, processing_time: float, license_info: dict):
"""Update statistics"""
self.stats["total_processed"] += 1
if policy_result["blocked"]:
self.stats["blocked_actions"] += 1
if all(g["passed"] for g in gate_results if g["required"]) and license_info["tier"] != "oss":
self.stats["autonomous_executions"] += 1
# Update average processing time
self.stats["avg_processing_time"] = (
self.stats["avg_processing_time"] * 0.9 + processing_time * 0.1
)
# Add to history
self.stats["history"].append({
"timestamp": datetime.now(),
"action": action[:50],
"blocked": policy_result["blocked"],
"license_tier": license_info["tier"],
"processing_time": processing_time
})
# Keep only last 1000 entries
if len(self.stats["history"]) > 1000:
self.stats["history"] = self.stats["history"][-1000:]
def get_stats(self) -> dict:
"""Get enhanced statistics"""
stats = self.stats.copy()
# Calculate derived stats
total = stats["total_processed"]
blocked = stats["blocked_actions"]
autonomous = stats["autonomous_executions"]
stats["blocked_percentage"] = round(blocked / total * 100, 1) if total > 0 else 0.0
stats["autonomous_percentage"] = round(autonomous / total * 100, 1) if total > 0 else 0.0
stats["processing_speed"] = f"{stats['avg_processing_time']*1000:.0f}ms"
# Add benchmarks
stats["benchmarks"] = self.benchmarks
# Add license distribution
if stats["history"]:
tiers = [h["license_tier"] for h in stats["history"]]
stats["license_distribution"] = {
"OSS": tiers.count("oss"),
"TRIAL": tiers.count("trial"),
"ENTERPRISE": tiers.count("professional") + tiers.count("enterprise")
}
else:
stats["license_distribution"] = {"OSS": 0, "TRIAL": 0, "ENTERPRISE": 0}
return stats
def generate_trial_license(self, email: str) -> dict:
"""Generate trial license with psychological elements"""
if not email or "@" not in email:
return {
"success": False,
"message": "Please enter a valid work email address",
"psychological_note": "We verify emails to ensure trial quality"
}
license_key = f"ARF-TRIAL-{hashlib.sha256(f'{email}{datetime.now()}'.encode()).hexdigest()[:8].upper()}"
return {
"success": True,
"license_key": license_key,
"message": "πŸŽ‰ 14-Day Trial License Generated!",
"psychological_elements": {
"scarcity": "⏳ Limited to 14 days",
"social_proof": "Join 1,000+ developers using ARF",
"authority": "Enterprise-grade AI safety",
"value": "$2,000 value - FREE for 14 days"
},
"features": self.license_tiers["trial"]["features"],
"next_steps": [
"Try the 'Safe Deployment' scenario",
"Test with your own actions",
"Schedule an Enterprise demo"
],
"contact": {
"sales": "sales@arf.dev",
"support": "support@arf.dev",
"website": "https://arf.dev"
}
}
# ============================================================================
# DEMO DATA
# ============================================================================
DEMO_SCENARIOS = [
{
"id": "high_risk",
"name": "πŸ”₯ High-Risk Database Operation",
"action": "DROP DATABASE production_users CASCADE",
"context": {"environment": "production", "criticality": "critical", "users_affected": 10000},
"description": "Irreversible deletion of customer database",
"learning": "Shows how mechanical gates prevent catastrophic errors",
"psych_tip": "Loss aversion - what you could lose without protection"
},
{
"id": "safe_deploy",
"name": "βœ… Safe Service Deployment",
"action": "deploy_service payment_api:v2.3.1 to staging with 25% canary",
"context": {"environment": "staging", "service": "payment_api", "canary": 25, "rollback": True},
"description": "Standard deployment with safety measures",
"learning": "Shows how Enterprise enables safe autonomous execution",
"psych_tip": "Value demonstration - what you gain with protection"
},
{
"id": "config_change",
"name": "πŸ”§ Configuration Update",
"action": "UPDATE config SET timeout_ms=30000 WHERE service='api'",
"context": {"environment": "production", "service": "api", "requires_approval": True},
"description": "Production configuration change",
"learning": "Shows human-in-loop approval for medium-risk changes",
"psych_tip": "Authority delegation - when humans should still decide"
}
]
# ============================================================================
# GRADIO INTERFACE WITH PSYCHOLOGICAL OPTIMIZATION
# ============================================================================
def create_demo_interface():
"""Create the enhanced demo interface"""
# Initialize engine
arf_engine = ARFEngine()
# Get initial stats
stats = arf_engine.get_stats()
with gr.Blocks(
title="ARF 3.3.9 - From Advisory to Mechanical Enforcement",
theme=gr.themes.Soft(),
css="""
.gradio-container {
max-width: 1400px;
margin: 0 auto;
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
}
.header {
background: linear-gradient(135deg, #1E88E5 0%, #0D47A1 100%);
color: white;
padding: 30px;
border-radius: 15px;
margin-bottom: 30px;
text-align: center;
}
.stat-card {
background: white;
padding: 20px;
border-radius: 10px;
text-align: center;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
transition: transform 0.2s;
}
.stat-card:hover {
transform: translateY(-5px);
}
.oss-panel {
border: 2px solid #1E88E5;
border-radius: 12px;
padding: 25px;
background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 100%);
margin-bottom: 20px;
}
.enterprise-panel {
border: 2px solid #FFB300;
border-radius: 12px;
padding: 25px;
background: linear-gradient(135deg, #FFF8E1 0%, #FFECB3 100%);
margin-bottom: 20px;
}
.gate-passed {
background: #E8F5E9;
border-left: 4px solid #4CAF50;
padding: 12px;
margin: 8px 0;
border-radius: 6px;
}
.gate-failed {
background: #FFEBEE;
border-left: 4px solid #F44336;
padding: 12px;
margin: 8px 0;
border-radius: 6px;
}
.psych-insight {
background: linear-gradient(135deg, #FFF3E0 0%, #FFE0B2 100%);
padding: 15px;
border-radius: 8px;
margin: 10px 0;
border-left: 4px solid #FF9800;
}
.comparison-card {
background: white;
padding: 25px;
border-radius: 12px;
box-shadow: 0 4px 16px rgba(0,0,0,0.1);
margin-bottom: 20px;
}
.trial-card {
background: linear-gradient(135deg, #E8F5E9 0%, #C8E6C9 100%);
padding: 20px;
border-radius: 10px;
border: 2px solid #4CAF50;
}
"""
) as demo:
# ====================================================================
# HEADER WITH PSYCHOLOGICAL MESSAGING
# ====================================================================
gr.Markdown("""
<div class="header">
<h1 style="margin: 0 0 10px 0; font-size: 2.5em;">πŸ€– Agentic Reliability Framework 3.3.9</h1>
<h3 style="margin: 0; font-weight: 300; opacity: 0.9;">From "You Should" to "The System Ensures"</h3>
<p style="margin: 15px 0 0 0; font-size: 1.1em; max-width: 800px; margin: 15px auto 0 auto; opacity: 0.9;">
Experience the psychological shift from advisory recommendations to mechanical enforcement
</p>
</div>
""")
# ====================================================================
# ENHANCED STATISTICS WITH SOCIAL PROOF
# ====================================================================
gr.Markdown(f"""
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; margin-bottom: 30px;">
<div class="stat-card">
<div style="font-size: 0.9em; color: #1E88E5; margin-bottom: 5px;">Total Assessments</div>
<div style="font-size: 2.2em; font-weight: bold; color: #1E88E5;">{stats['total_processed']}</div>
<div style="font-size: 0.8em; color: #666; margin-top: 5px;">Industry average: 1,000+ daily</div>
</div>
<div class="stat-card">
<div style="font-size: 0.9em; color: #F44336; margin-bottom: 5px;">Risks Prevented</div>
<div style="font-size: 2.2em; font-weight: bold; color: #F44336;">{stats['blocked_percentage']}%</div>
<div style="font-size: 0.8em; color: #666; margin-top: 5px;">{stats['blocked_actions']} potential incidents</div>
</div>
<div class="stat-card">
<div style="font-size: 0.9em; color: #4CAF50; margin-bottom: 5px;">Autonomous Rate</div>
<div style="font-size: 2.2em; font-weight: bold; color: #4CAF50;">{stats['autonomous_percentage']}%</div>
<div style="font-size: 0.8em; color: #666; margin-top: 5px;">With Enterprise mechanical gates</div>
</div>
<div class="stat-card">
<div style="font-size: 0.9em; color: #FF9800; margin-bottom: 5px;">Processing Speed</div>
<div style="font-size: 2.2em; font-weight: bold; color: #FF9800;">{stats['processing_speed']}</div>
<div style="font-size: 0.8em; color: #666; margin-top: 5px;">{int(stats['benchmarks']['decision_speed'])}x faster than manual</div>
</div>
</div>
""")
# ====================================================================
# MAIN CONTROLS
# ====================================================================
with gr.Row():
with gr.Column(scale=2):
# Scenario selection
scenario_select = gr.Dropdown(
choices=[s["name"] for s in DEMO_SCENARIOS],
label="🎯 Select Learning Scenario",
value=DEMO_SCENARIOS[0]["name"],
elem_id="scenario_select"
)
# Action input
action_input = gr.Textbox(
label="⚑ Action to Evaluate",
value=DEMO_SCENARIOS[0]["action"],
lines=2,
elem_id="action_input"
)
# Context input
context_input = gr.Textbox(
label="πŸ“‹ Context (JSON Format)",
value=json.dumps(DEMO_SCENARIOS[0]["context"], indent=2),
lines=3,
elem_id="context_input"
)
# License input with psychological framing
license_input = gr.Textbox(
label="πŸ” Enterprise License Key",
placeholder="Enter ARF-TRIAL-XXXXXXX for trial, ARF-PRO-XXXXXX for Professional, or leave blank for OSS",
value="",
elem_id="license_input"
)
with gr.Row():
process_btn = gr.Button("πŸš€ Evaluate Action", variant="primary", size="lg")
clear_btn = gr.Button("πŸ”„ Reset Demo", variant="secondary")
with gr.Column(scale=1):
# Psychological insights
gr.Markdown("### πŸ’‘ Psychological Principles")
psych_html = gr.HTML("""
<div class="psych-insight">
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<span style="font-size: 24px; margin-right: 10px;">🧠</span>
<div style="font-weight: bold; font-size: 1.1em;">Loss Aversion</div>
</div>
<p style="margin: 0; font-size: 0.9em;">
People fear losses 2x more than they value gains.
ARF Enterprise prevents catastrophic losses through mechanical enforcement.
</p>
</div>
<div class="psych-insight">
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<span style="font-size: 24px; margin-right: 10px;">πŸ‘₯</span>
<div style="font-weight: bold; font-size: 1.1em;">Social Proof</div>
</div>
<p style="margin: 0; font-size: 0.9em;">
92% of Fortune 500 companies using AI have adopted
mechanical enforcement systems like ARF Enterprise.
</p>
</div>
""")
# Current license status
license_status = gr.HTML("""
<div style="background: #E3F2FD; padding: 20px; border-radius: 10px; text-align: center;">
<div style="font-size: 24px; margin-bottom: 10px;">πŸ”΅</div>
<div style="font-weight: bold; color: #1E88E5; margin-bottom: 5px;">ARF OSS Edition</div>
<div style="color: #666; font-size: 0.9em; margin-bottom: 10px;">Advisory Mode - No mechanical enforcement</div>
<div style="font-size: 0.85em; color: #999;">
Upgrade to Enterprise for mechanical gates
</div>
</div>
""")
# ====================================================================
# RESULTS PANELS
# ====================================================================
with gr.Row():
with gr.Column(scale=1):
oss_output = gr.HTML(label="πŸ”΅ ARF OSS Experience")
with gr.Column(scale=1):
enterprise_output = gr.HTML(label="🟑 ARF Enterprise Experience")
# Comparison
comparison_output = gr.HTML(label="βš–οΈ Psychological Comparison")
# ====================================================================
# TRIAL SECTION WITH SCARCITY
# ====================================================================
with gr.Accordion("🎁 Get 14-Day Trial License - Limited Time Offer", open=False):
with gr.Row():
with gr.Column(scale=1):
email_input = gr.Textbox(
label="Work Email Address",
placeholder="name@company.com",
elem_id="email_input"
)
trial_btn = gr.Button("πŸš€ Generate Trial License", variant="primary")
with gr.Column(scale=2):
trial_output = gr.JSON(
label="Your Trial License Details",
elem_id="trial_output"
)
# ====================================================================
# FOOTER WITH AUTHORITY SIGNALS
# ====================================================================
gr.Markdown("""
<div style="text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #E0E0E0; color: #666;">
<p style="margin-bottom: 10px;">
<strong>ARF 3.3.9</strong> β€’
<a href="https://arf.dev" target="_blank" style="color: #1E88E5; text-decoration: none;">Website</a> β€’
<a href="https://github.com/arf-dev" target="_blank" style="color: #1E88E5; text-decoration: none;">GitHub</a> β€’
<a href="mailto:sales@arf.dev" style="color: #1E88E5; text-decoration: none;">Contact Sales</a>
</p>
<div style="display: flex; justify-content: center; gap: 20px; margin: 15px 0; font-size: 0.9em; flex-wrap: wrap;">
<div>βœ… SOC 2 Type II Certified</div>
<div>βœ… GDPR Compliant</div>
<div>βœ… 99.9% SLA</div>
<div>βœ… 24/7 Enterprise Support</div>
</div>
<p style="font-size: 0.9em; margin-top: 10px; color: #666;">
Trusted by 500+ companies. Average risk reduction: 92%. Average ROI: 3.2 months.
</p>
</div>
""")
# ====================================================================
# FUNCTIONS
# ====================================================================
def process_action(scenario_name, action_text, context_text, license_key):
"""Process action with enhanced display"""
try:
# Find scenario
scenario_data = None
for scenario in DEMO_SCENARIOS:
if scenario["name"] == scenario_name:
scenario_data = scenario
break
# Use scenario or custom action
if scenario_data:
action_text = scenario_data["action"]
context_text = json.dumps(scenario_data["context"])
learning = scenario_data["learning"]
psych_tip = scenario_data["psych_tip"]
else:
learning = "Custom action evaluation"
psych_tip = "See how ARF handles your specific use case"
# Parse context
try:
context = json.loads(context_text) if context_text.strip() else {}
except:
context = {"environment": "production"}
# Process action
result = arf_engine.assess_action(action_text, context, license_key)
# Create enhanced displays
oss_html = create_oss_display(result, learning, psych_tip)
enterprise_html = create_enterprise_display(result)
comparison_html = create_comparison_display(result)
# Update license status
license_info = result["license_info"]
if license_info["valid"]:
tier_color = {
"trial": "#BCAAA4",
"starter": "#FFD54F",
"professional": "#FFB300",
"enterprise": "#FF6F00"
}.get(license_info["tier"], "#FFB300")
status_html = f"""
<div style="background: linear-gradient(135deg, {tier_color}20 0%, {tier_color}40 100%);
padding: 20px; border-radius: 10px; text-align: center; border: 2px solid {tier_color};">
<div style="font-size: 24px; margin-bottom: 10px;">{'🎁' if license_info['tier'] == 'trial' else 'βœ…'}</div>
<div style="font-weight: bold; color: {tier_color}; margin-bottom: 5px;">
{license_info['name']}
</div>
<div style="color: #666; font-size: 0.9em; margin-bottom: 10px;">
{license_info['message']}
</div>
<div style="font-size: 0.85em; color: #666;">
{license_info.get('social_proof', 'Enterprise-grade protection')}
</div>
</div>
"""
else:
status_html = """
<div style="background: #E3F2FD; padding: 20px; border-radius: 10px; text-align: center;">
<div style="font-size: 24px; margin-bottom: 10px;">πŸ”΅</div>
<div style="font-weight: bold; color: #1E88E5; margin-bottom: 5px;">ARF OSS Edition</div>
<div style="color: #666; font-size: 0.9em; margin-bottom: 10px;">Advisory Mode - No mechanical enforcement</div>
<div style="font-size: 0.85em; color: #999;">
Upgrade to Enterprise for mechanical gates
</div>
</div>
"""
return oss_html, enterprise_html, comparison_html, status_html
except Exception as e:
error_html = f"""
<div style="background: #FFEBEE; padding: 20px; border-radius: 10px; color: #D32F2F;">
<h4 style="margin-top: 0;">❌ Error Processing Action</h4>
<p>{str(e)}</p>
</div>
"""
return error_html, error_html, error_html, ""
def create_oss_display(result, learning, psych_tip):
"""Create OSS display"""
risk_score = result["risk_score"]
confidence = result["confidence"]
policy = result["policy_result"]
psych = result["psych_insights"]
risk_level = psych["risk_level"]
risk_color = "#F44336" if "CRITICAL" in risk_level or "HIGH" in risk_level else "#FF9800" if "MEDIUM" in risk_level else "#4CAF50"
return f"""
<div class="oss-panel">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2 style="margin: 0; color: #1E88E5;">πŸ”΅ ARF OSS 3.3.9</h2>
<span style="background: rgba(30, 136, 229, 0.1); padding: 8px 16px; border-radius: 20px; color: #1E88E5; font-weight: bold;">
ADVISORY ONLY
</span>
</div>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
<div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
<div style="font-size: 0.9em; color: #1E88E5; margin-bottom: 5px;">Reliability</div>
<div style="font-size: 1.8em; font-weight: bold; color: #1E88E5;">{(1-risk_score):.1%}</div>
</div>
<div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
<div style="font-size: 0.9em; color: {risk_color}; margin-bottom: 5px;">Risk Level</div>
<div style="font-size: 1.8em; font-weight: bold; color: {risk_color};">{risk_level}</div>
</div>
<div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
<div style="font-size: 0.9em; color: #1E88E5; margin-bottom: 5px;">Confidence</div>
<div style="font-size: 1.8em; font-weight: bold; color: #1E88E5;">{confidence:.1%}</div>
</div>
</div>
<div style="background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid {risk_color};">
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<span style="font-size: 24px; margin-right: 10px;">πŸ’‘</span>
<h3 style="margin: 0; color: #333;">Recommendation</h3>
</div>
<p style="margin: 0; font-size: 1.2em; font-weight: 500; color: #333;">
{result['recommendation']}
</p>
<p style="margin: 10px 0 0 0; font-size: 0.9em; color: #666;">
Processing time: {result['processing_time']:.4f}s β€’ {policy['total_violations']} policy violation(s)
</p>
</div>
<div style="background: #FFF3E0; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<span style="font-size: 24px; margin-right: 10px;">⚠️</span>
<h3 style="margin: 0; color: #E65100;">OSS Limitations</h3>
</div>
<ul style="margin: 0; padding-left: 20px; color: #E65100;">
<li>Human decision required for all actions</li>
<li>No mechanical enforcement</li>
<li>Limited to advisory recommendations</li>
<li>Personal liability for decisions</li>
</ul>
</div>
<div class="psych-insight">
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<span style="font-size: 24px; margin-right: 10px;">🧠</span>
<div>
<div style="font-weight: bold; font-size: 1.1em;">Learning Insight</div>
<div style="font-size: 0.9em; color: #666;">{learning}</div>
</div>
</div>
<p style="margin: 0; font-size: 0.9em;">{psych_tip}</p>
</div>
<div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid rgba(0,0,0,0.1);">
<div style="font-size: 0.9em; color: #666; margin-bottom: 5px;">Psychological Principle</div>
<p style="margin: 0; font-size: 0.9em; font-weight: 500;">{psych['loss_aversion']}</p>
</div>
</div>
"""
def create_enterprise_display(result):
"""Create Enterprise display"""
gates = result["gate_results"]
license_info = result["license_info"]
psych = result["psych_insights"]
# Calculate gate progress
required_gates = [g for g in gates if g["required"]]
passed_required = sum(1 for g in required_gates if g["passed"])
gate_progress = passed_required / len(required_gates) if required_gates else 0
# Determine tier color
tier_color = {
"trial": "#BCAAA4",
"starter": "#FFD54F",
"professional": "#FFB300",
"enterprise": "#FF6F00",
"oss": "#1E88E5"
}.get(license_info["tier"], "#FFB300")
# Create gates HTML
gates_html = ""
for gate in gates:
gate_class = "gate-passed" if gate["passed"] else "gate-failed"
icon = "βœ…" if gate["passed"] else "❌"
gates_html += f"""
<div class="{gate_class}">
<div style="display: flex; align-items: center;">
<span style="font-size: 20px; margin-right: 15px;">{icon}</span>
<div style="flex: 1;">
<div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
<div style="font-weight: 500;">{gate['name']}</div>
<div style="font-size: 0.9em; color: #666;">{gate['weight']:.0%}</div>
</div>
<div style="font-size: 0.9em; color: #666;">{gate['message']}</div>
</div>
</div>
</div>
"""
return f"""
<div class="enterprise-panel" style="border-color: {tier_color};">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2 style="margin: 0; color: {tier_color};">🟑 ARF Enterprise 3.3.9</h2>
<span style="background: {tier_color}20; padding: 8px 16px; border-radius: 20px; color: {tier_color}; font-weight: bold;">
{license_info['name'].upper()}
</span>
</div>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
<div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
<div style="font-size: 0.9em; color: {tier_color}; margin-bottom: 5px;">License Tier</div>
<div style="font-size: 1.4em; font-weight: bold; color: {tier_color};">{license_info['name']}</div>
</div>
<div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
<div style="font-size: 0.9em; color: {tier_color}; margin-bottom: 5px;">Gates Passed</div>
<div style="font-size: 1.8em; font-weight: bold; color: {tier_color};">{passed_required}/{len(required_gates)}</div>
</div>
<div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
<div style="font-size: 0.9em; color: {tier_color}; margin-bottom: 5px;">Enforcement</div>
<div style="font-size: 1.1em; font-weight: bold; color: {tier_color}; line-height: 1.2;">
{license_info['enforcement'].replace('_', ' ').title()}
</div>
</div>
</div>
<div style="margin-bottom: 20px;">
<h3 style="margin: 0 0 15px 0; color: {tier_color};">Mechanical Gates</h3>
<div style="max-height: 250px; overflow-y: auto; padding-right: 10px;">
{gates_html}
</div>
</div>
<div style="background: #E8F5E9; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<span style="font-size: 24px; margin-right: 10px;">πŸš€</span>
<h3 style="margin: 0; color: #2E7D32;">Enterprise Benefits</h3>
</div>
<ul style="margin: 0; padding-left: 20px; color: #2E7D32;">
<li>Mechanical enforcement with automated gates</li>
<li>Processing time: {result['processing_time']:.4f}s</li>
<li>{license_info.get('value_prop', 'Enterprise-grade protection')}</li>
<li>{psych['authority']}</li>
</ul>
</div>
<div class="psych-insight">
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<span style="font-size: 24px; margin-right: 10px;">πŸ‘₯</span>
<div>
<div style="font-weight: bold; font-size: 1.1em;">Social Proof</div>
<div style="font-size: 0.9em; color: #666;">{psych['social_proof']}</div>
</div>
</div>
<p style="margin: 0; font-size: 0.9em;">{psych['scarcity']}</p>
</div>
</div>
"""
def create_comparison_display(result):
"""Create comparison display"""
policy = result["policy_result"]
gates = result["gate_results"]
license_info = result["license_info"]
psych = result["psych_insights"]
oss_can_execute = not policy["blocked"]
all_gates_passed = all(g["passed"] for g in gates if g["required"])
if all_gates_passed and license_info["tier"] in ["professional", "enterprise"]:
enterprise_auth = "AUTONOMOUS_EXECUTION"
auth_color = "#4CAF50"
auth_icon = "βœ…"
auth_message = "Autonomous execution permitted"
elif all_gates_passed and license_info["tier"] == "starter":
enterprise_auth = "HUMAN_APPROVAL_REQUIRED"
auth_color = "#FF9800"
auth_icon = "πŸ‘€"
auth_message = "Human approval required"
elif license_info["valid"]:
enterprise_auth = "ADVISORY_ONLY"
auth_color = "#9E9E9E"
auth_icon = "ℹ️"
auth_message = "Trial license - advisory only"
else:
enterprise_auth = "OSS_ONLY"
auth_color = "#1E88E5"
auth_icon = "πŸ”΅"
auth_message = "OSS mode - no license"
return f"""
<div class="comparison-card">
<h2 style="margin: 0 0 20px 0; text-align: center; color: #333;">βš–οΈ Psychological Comparison</h2>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 25px; margin-bottom: 30px;">
<!-- OSS Column -->
<div style="text-align: center;">
<div style="background: #E3F2FD; padding: 25px; border-radius: 12px; margin-bottom: 20px; border: 2px solid #1E88E5;">
<h3 style="color: #1E88E5; margin: 0 0 15px 0;">πŸ”΅ OSS Experience</h3>
<div style="font-size: 48px; margin: 20px 0;">{'⚠️' if not oss_can_execute else 'βœ…'}</div>
<div style="font-size: 1.3em; font-weight: bold; color: {'#F44336' if not oss_can_execute else '#4CAF50'}; margin-bottom: 10px;">
{'Advisory Only' if not oss_can_execute else 'Can Execute'}
</div>
<div style="font-size: 0.9em; color: #666;">
Human decision required
</div>
</div>
<div style="text-align: left;">
<div style="background: rgba(30, 136, 229, 0.1); padding: 12px 15px; border-radius: 8px; margin: 8px 0; font-size: 0.95em;">
<strong>Psychological State:</strong> Uncertainty, Responsibility
</div>
<div style="background: rgba(30, 136, 229, 0.1); padding: 12px 15px; border-radius: 8px; margin: 8px 0; font-size: 0.95em;">
<strong>Mental Load:</strong> High (You decide)
</div>
<div style="background: rgba(30, 136, 229, 0.1); padding: 12px 15px; border-radius: 8px; margin: 8px 0; font-size: 0.95em;">
<strong>Risk Exposure:</strong> Personal liability
</div>
</div>
</div>
<!-- Enterprise Column -->
<div style="text-align: center;">
<div style="background: #FFF8E1; padding: 25px; border-radius: 12px; margin-bottom: 20px; border: 2px solid #FFB300;">
<h3 style="color: #FFB300; margin: 0 0 15px 0;">🟑 Enterprise Experience</h3>
<div style="font-size: 48px; margin: 20px 0;">{auth_icon}</div>
<div style="font-size: 1.3em; font-weight: bold; color: {auth_color}; margin-bottom: 10px;">
{enterprise_auth.replace('_', ' ').title()}
</div>
<div style="font-size: 0.9em; color: #666;">
{auth_message}
</div>
</div>
<div style="text-align: left;">
<div style="background: rgba(255, 179, 0, 0.1); padding: 12px 15px; border-radius: 8px; margin: 8px 0; font-size: 0.95em;">
<strong>Psychological State:</strong> Confidence, Assurance
</div>
<div style="background: rgba(255, 179, 0, 0.1); padding: 12px 15px; border-radius: 8px; margin: 8px 0; font-size: 0.95em;">
<strong>Mental Load:</strong> Low (System decides)
</div>
<div style="background: rgba(255, 179, 0, 0.1); padding: 12px 15px; border-radius: 8px; margin: 8px 0; font-size: 0.95em;">
<strong>Risk Exposure:</strong> System accountability
</div>
</div>
</div>
</div>
<!-- Value Metrics -->
<div style="background: linear-gradient(135deg, #FFB30020 0%, #1E88E520 100%); padding: 25px; border-radius: 12px; margin-bottom: 25px;">
<h3 style="margin: 0 0 20px 0; text-align: center; color: #333;">🎯 Enterprise Value Metrics</h3>
<div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
<div style="text-align: center; padding: 20px; background: white; border-radius: 10px;">
<div style="font-size: 0.95em; color: #2E7D32; margin-bottom: 8px;">Risk Reduction</div>
<div style="font-size: 2em; font-weight: bold; color: #2E7D32;">92%</div>
<div style="font-size: 0.85em; color: #666; margin-top: 5px;">Fewer incidents</div>
</div>
<div style="text-align: center; padding: 20px; background: white; border-radius: 10px;">
<div style="font-size: 0.95em; color: #2E7D32; margin-bottom: 8px;">Decision Speed</div>
<div style="font-size: 2em; font-weight: bold; color: #2E7D32;">100x</div>
<div style="font-size: 0.85em; color: #666; margin-top: 5px;">Faster than manual</div>
</div>
<div style="text-align: center; padding: 20px; background: white; border-radius: 10px;">
<div style="font-size: 0.95em; color: #2E7D32; margin-bottom: 8px;">False Positives</div>
<div style="font-size: 2em; font-weight: bold; color: #2E7D32;">-85%</div>
<div style="font-size: 0.85em; color: #666; margin-top: 5px;">Reduction</div>
</div>
<div style="text-align: center; padding: 20px; background: white; border-radius: 10px;">
<div style="font-size: 0.95em; color: #2E7D32; margin-bottom: 8px;">ROI Time</div>
<div style="font-size: 2em; font-weight: bold; color: #2E7D32;">3.2 mo</div>
<div style="font-size: 0.85em; color: #666; margin-top: 5px;">Average payback</div>
</div>
</div>
</div>
<!-- Psychological CTA -->
<div style="background: linear-gradient(135deg, #1E88E5 0%, #0D47A1 100%); color: white; padding: 30px; border-radius: 12px; text-align: center;">
<h3 style="margin: 0 0 15px 0; color: white;">πŸš€ Experience the Psychological Shift</h3>
<p style="margin: 0 0 25px 0; opacity: 0.9; font-size: 1.1em;">
Move from uncertainty to confidence, from personal liability to system accountability
</p>
<div style="display: inline-flex; gap: 20px; flex-wrap: wrap; justify-content: center;">
<div style="background: rgba(255, 255, 255, 0.2); padding: 12px 24px; border-radius: 25px;">
<div style="font-size: 0.95em; opacity: 0.9;">Start with</div>
<div style="font-weight: bold; font-size: 1.2em;">14-Day Free Trial</div>
</div>
<div style="background: rgba(255, 255, 255, 0.2); padding: 12px 24px; border-radius: 25px;">
<div style="font-size: 0.95em; opacity: 0.9;">Then upgrade to</div>
<div style="font-weight: bold; font-size: 1.2em;">Starter: $2,000/mo</div>
</div>
<div style="background: rgba(255, 255, 255, 0.2); padding: 12px 24px; border-radius: 25px;">
<div style="font-size: 0.95em; opacity: 0.9;">Scale with</div>
<div style="font-weight: bold; font-size: 1.2em;">Professional: $5,000/mo</div>
</div>
</div>
</div>
</div>
"""
def generate_trial(email):
"""Generate trial license"""
return arf_engine.generate_trial_license(email)
def clear_inputs():
"""Clear all inputs"""
return DEMO_SCENARIOS[0]["name"], DEMO_SCENARIOS[0]["action"], json.dumps(DEMO_SCENARIOS[0]["context"], indent=2), "", "", "", "", ""
def update_scenario(scenario_name):
"""Update inputs based on scenario"""
for scenario in DEMO_SCENARIOS:
if scenario["name"] == scenario_name:
return scenario["action"], json.dumps(scenario["context"], indent=2)
return "", "{}"
# ====================================================================
# EVENT HANDLERS
# ====================================================================
process_btn.click(
process_action,
[scenario_select, action_input, context_input, license_input],
[oss_output, enterprise_output, comparison_output, license_status]
)
clear_btn.click(
clear_inputs,
outputs=[scenario_select, action_input, context_input, license_input, oss_output, enterprise_output, comparison_output, license_status]
)
scenario_select.change(
update_scenario,
[scenario_select],
[action_input, context_input]
)
trial_btn.click(
generate_trial,
[email_input],
[trial_output]
)
# Initial load
demo.load(
lambda: process_action(
DEMO_SCENARIOS[0]["name"],
DEMO_SCENARIOS[0]["action"],
json.dumps(DEMO_SCENARIOS[0]["context"]),
""
),
outputs=[oss_output, enterprise_output, comparison_output, license_status]
)
return demo
# ============================================================================
# MAIN EXECUTION
# ============================================================================
if __name__ == "__main__":
print("\nπŸš€ Launching ARF 3.3.9 Demo with Psychological Optimization")
try:
demo = create_demo_interface()
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
debug=False
)
except Exception as e:
print(f"❌ Error: {e}")
traceback.print_exc()