# COMPLETE FIXED hf_demo.py with Gradio 4.x for Hugging Face Spaces
# ARF 3.3.9 DEMO WITH PROPER HUGGING FACE SPACES COMPATIBILITY
import gradio as gr
import time
import random
import json
import uuid
import subprocess
import sys
import importlib
import os
import threading
import socket
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple, Any, Union
import numpy as np
# ============== FASTAPI INTEGRATION ==============
try:
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
import uvicorn
FASTAPI_AVAILABLE = True
print("✅ FastAPI available")
except ImportError as e:
print(f"⚠️ FastAPI not available: {e}")
FASTAPI_AVAILABLE = False
# Create dummy classes if FastAPI not installed
class BaseModel:
def dict(self): return {}
class FastAPI: pass
class HTTPException(Exception): pass
class CORSMiddleware: pass
def Field(*args, **kwargs): return None
if FASTAPI_AVAILABLE:
# Create FastAPI app
api_app = FastAPI(title="ARF Mathematical Engine", version="3.3.9")
# Add CORS middleware
api_app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # In production, restrict to your Replit domain
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Define Pydantic models
class ActionEvaluationRequest(BaseModel):
proposed_action: str = Field(..., description="The command the AI wants to execute")
confidence_score: float = Field(..., ge=0.0, le=1.0, description="AI confidence score")
risk_level: str = Field(..., description="Risk level (LOW/MEDIUM/HIGH/CRITICAL)")
requires_human: bool = Field(..., description="Whether action requires human oversight")
rollback_feasible: bool = Field(..., description="Whether action can be rolled back")
description: Optional[str] = Field(None, description="Optional action description")
incident_id: Optional[int] = Field(None, description="Optional incident ID")
class GateEvaluationResponse(BaseModel):
gate: str
reason: str
passed: bool
threshold: Optional[float] = None
actual: Optional[float] = None
metadata: Optional[dict] = None
class ActionEvaluationResponse(BaseModel):
allowed: bool
required_level: str
gates_triggered: list[GateEvaluationResponse]
should_escalate: bool
escalation_reason: Optional[str] = None
class ConfigResponse(BaseModel):
confidenceThreshold: float
maxAutonomousRisk: str
riskScoreThresholds: dict
# Add API endpoints
@api_app.get("/api/v1/config", response_model=ConfigResponse)
async def get_config():
"""Get current ARF configuration"""
return {
"confidenceThreshold": 0.9,
"maxAutonomousRisk": "MEDIUM",
"riskScoreThresholds": {
"LOW": 0.7,
"MEDIUM": 0.5,
"HIGH": 0.3,
"CRITICAL": 0.1
}
}
@api_app.post("/api/v1/evaluate", response_model=ActionEvaluationResponse)
async def evaluate_action(request: ActionEvaluationRequest):
"""Evaluate an action using mathematical Bayesian assessment"""
try:
# Simulate gate evaluations
gates = []
# Confidence gate
confidence_passed = request.confidence_score >= 0.9
gates.append(GateEvaluationResponse(
gate="confidence_threshold",
reason=f"Confidence {request.confidence_score:.2f} meets threshold 0.9" if confidence_passed
else f"Confidence {request.confidence_score:.2f} below threshold 0.9",
passed=confidence_passed,
threshold=0.9,
actual=request.confidence_score
))
# Risk gate
risk_passed = request.risk_level in ["LOW", "MEDIUM"]
gates.append(GateEvaluationResponse(
gate="risk_assessment",
reason=f"Risk level {request.risk_level} within autonomous range" if risk_passed
else f"Risk level {request.risk_level} exceeds autonomous threshold",
passed=risk_passed,
metadata={"maxAutonomousRisk": "MEDIUM", "actionRisk": request.risk_level}
))
# Rollback gate
destructive_keywords = ['delete', 'drop', 'terminate', 'remove', 'destroy']
is_destructive = any(keyword in request.proposed_action.lower() for keyword in destructive_keywords)
rollback_passed = not is_destructive or request.rollback_feasible
gates.append(GateEvaluationResponse(
gate="rollback_feasibility",
reason="Non-destructive operation" if not is_destructive
else "Has rollback plan" if request.rollback_feasible
else "Destructive operation lacks rollback plan",
passed=rollback_passed,
metadata={"isDestructive": is_destructive, "requiresRollback": is_destructive}
))
# Human review gate
human_passed = not request.requires_human
gates.append(GateEvaluationResponse(
gate="human_review",
reason="Human review not required" if human_passed else "Human review required by policy",
passed=human_passed,
metadata={"policyRequiresHuman": request.requires_human}
))
# License gate (always passes in this simulation)
gates.append(GateEvaluationResponse(
gate="license_check",
reason="No license violations detected",
passed=True,
metadata={"licenseSensitive": False}
))
all_passed = all(g.passed for g in gates)
# Determine required level
if all_passed:
if request.risk_level == "LOW":
required_level = "AUTONOMOUS_LOW"
elif request.risk_level == "MEDIUM":
required_level = "AUTONOMOUS_HIGH"
else:
required_level = "SUPERVISED"
else:
required_level = "OPERATOR_REVIEW"
return ActionEvaluationResponse(
allowed=all_passed,
required_level=required_level,
gates_triggered=gates,
should_escalate=not all_passed,
escalation_reason=None if all_passed else "Failed critical gates"
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@api_app.post("/api/v1/process")
async def process_action(request: ActionEvaluationRequest):
"""Process action through full ARF pipeline"""
evaluation = await evaluate_action(request)
# Determine final status based on evaluation
if evaluation.allowed and not evaluation.should_escalate:
final_status = "executed"
elif evaluation.should_escalate:
final_status = "needs_approval"
else:
final_status = "blocked"
return {
"action": request.dict(),
"evaluation": evaluation.dict(),
"finalStatus": final_status
}
@api_app.post("/api/v1/simulate")
async def simulate_action(request: ActionEvaluationRequest, config: dict = None):
"""Simulate action with temporary configuration"""
evaluation = await evaluate_action(request)
return evaluation
def run_fastapi():
"""Run FastAPI server in background thread"""
uvicorn.run(api_app, host="0.0.0.0", port=8000, log_level="warning")
# ============== HUGGING FACE SPACES DETECTION ==============
def is_huggingface_spaces():
"""Detect if running in Hugging Face Spaces environment"""
return os.environ.get('SPACE_ID') is not None or \
os.environ.get('HF_SPACE') is not None or \
os.environ.get('SYSTEM') == 'spaces' or \
os.path.exists('/.dockerenv') and 'space' in os.environ.get('HOSTNAME', '')
# Set environment variables for Hugging Face Spaces
if is_huggingface_spaces():
os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'
os.environ['GRADIO_SERVER_NAME'] = '0.0.0.0'
os.environ['GRADIO_SERVER_PORT'] = '7860'
# 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"""
Test how Bayesian risk assessment and mechanical gates prevent unsafe AI actions
⚠️ No Mechanical Enforcement
Bayesian risk assessment only
{'⚠️ 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 |
|---|