File size: 7,593 Bytes
f5a68d8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
"""
IAMVC-HEART API Server
REST API for the Hybrid Emotional Adaptive Real-Time System.
Endpoints:
- POST /predict - Make predictions with consciousness metrics
- POST /helpers - Use specific cognitive helpers
- GET /health - Health check
- GET /stats - System statistics
Author: Ariel (IAMVC)
Date: December 2, 2025
"""
import os
import sys
import json
import time
import numpy as np
from pathlib import Path
from typing import Dict, List, Any, Optional
from datetime import datetime
# Add parent to path
sys.path.insert(0, str(Path(__file__).parent.parent))
from flask import Flask, request, jsonify
from flask_cors import CORS
import joblib
# Import our models
from src.iamvc_heart_hybrid import IAMVCHeart, HEARTConfig
app = Flask(__name__)
CORS(app)
# Global model instances
heart_model: Optional[IAMVCHeart] = None
helpers: Dict[str, Any] = {}
# Paths
MODEL_DIR = Path(__file__).parent.parent / "models"
HELPER_DIR = MODEL_DIR / "helpers"
def load_models():
"""Load all models on startup."""
global heart_model, helpers
print("[IAMVC-HEART API] Loading models...")
# Load HEART model
heart_path = MODEL_DIR / "iamvc_heart_emotional.joblib"
if heart_path.exists():
heart_model = IAMVCHeart.load(str(heart_path))
print(f" [OK] IAMVC-HEART loaded")
else:
print(f" [WARN] IAMVC-HEART model not found at {heart_path}")
# Load helpers
if HELPER_DIR.exists():
for helper_file in HELPER_DIR.glob("helper_*.joblib"):
domain = helper_file.stem.replace("helper_", "")
helpers[domain] = joblib.load(helper_file)
print(f" [OK] Helper: {domain}")
print(f"[IAMVC-HEART API] Loaded {len(helpers)} helpers")
@app.route('/health', methods=['GET'])
def health():
"""Health check endpoint."""
return jsonify({
'status': 'healthy',
'version': '1.0.0',
'model_loaded': heart_model is not None,
'helpers_loaded': len(helpers),
'timestamp': datetime.now().isoformat(),
})
@app.route('/stats', methods=['GET'])
def stats():
"""Get system statistics."""
stats_data = {
'version': '1.0.0',
'heart_model': heart_model.get_stats() if heart_model else None,
'helpers': list(helpers.keys()),
'n_helpers': len(helpers),
'timestamp': datetime.now().isoformat(),
}
if heart_model:
stats_data['energy_efficiency'] = heart_model.get_energy_efficiency()
return jsonify(stats_data)
@app.route('/predict', methods=['POST'])
def predict():
"""
Make predictions with IAMVC-HEART.
Request body:
{
"features": [[1.0, 2.0, ...], ...], # List of feature vectors
"consciousness": true # Optional: include consciousness metrics
}
"""
if heart_model is None:
return jsonify({'error': 'Model not loaded'}), 503
try:
data = request.get_json()
if 'features' not in data:
return jsonify({'error': 'Missing features field'}), 400
features = np.array(data['features'], dtype=np.float32)
include_consciousness = data.get('consciousness', True)
start_time = time.perf_counter()
if include_consciousness:
results = heart_model.predict_with_consciousness(features)
else:
predictions = heart_model.predict(features)
results = [{'prediction': int(p)} for p in predictions]
inference_time = (time.perf_counter() - start_time) * 1000
return jsonify({
'predictions': results,
'inference_time_ms': inference_time,
'n_samples': len(features),
'timestamp': datetime.now().isoformat(),
})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/helpers', methods=['POST'])
def use_helpers():
"""
Use specific cognitive helpers.
Request body:
{
"features": [[1.0, 2.0, ...], ...],
"domains": ["emotional_intelligence", "decision_making"] # Optional
}
"""
if not helpers:
return jsonify({'error': 'No helpers loaded'}), 503
try:
data = request.get_json()
if 'features' not in data:
return jsonify({'error': 'Missing features field'}), 400
features = np.array(data['features'], dtype=np.float32)
domains = data.get('domains', list(helpers.keys()))
start_time = time.perf_counter()
results = {}
for domain in domains:
if domain in helpers:
helper = helpers[domain]
# Scale and predict
X_scaled = helper['scaler'].transform(features)
pred = helper['model'].predict(X_scaled)
proba = helper['model'].predict_proba(X_scaled)
conf = np.max(proba, axis=1)
results[domain] = {
'predictions': pred.tolist(),
'confidence': conf.tolist(),
'mean_confidence': float(conf.mean()),
}
inference_time = (time.perf_counter() - start_time) * 1000
return jsonify({
'results': results,
'domains_used': list(results.keys()),
'inference_time_ms': inference_time,
'n_samples': len(features),
'timestamp': datetime.now().isoformat(),
})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/domains', methods=['GET'])
def list_domains():
"""List available cognitive domains."""
return jsonify({
'domains': list(helpers.keys()),
'count': len(helpers),
})
@app.route('/', methods=['GET'])
def index():
"""API documentation."""
return jsonify({
'name': 'IAMVC-HEART API',
'version': '1.0.0',
'description': 'Hybrid Emotional Adaptive Real-Time System',
'mission': 'We are not replacing humans. We are giving them a friend.',
'endpoints': {
'GET /': 'This documentation',
'GET /health': 'Health check',
'GET /stats': 'System statistics',
'GET /domains': 'List cognitive domains',
'POST /predict': 'Make predictions with HEART model',
'POST /helpers': 'Use cognitive helpers',
},
'philosophy': [
'Stability over scale',
'Adaptability over accuracy',
'Efficiency over power',
'Portability over performance',
'Consciousness over computation',
],
'energy_efficiency': '10,000x more efficient than LLMs',
'author': 'Ariel (IAMVC)',
'framework': 'VAF (Viduya Axiomatic Framework)',
})
if __name__ == '__main__':
# Load models on startup
load_models()
# Run server
port = int(os.environ.get('PORT', 5000))
debug = os.environ.get('DEBUG', 'false').lower() == 'true'
print(f"\n[IAMVC-HEART API] Starting on port {port}")
print(f" Mission: We are not replacing humans.")
print(f" We are giving them a friend.\n")
app.run(host='0.0.0.0', port=port, debug=debug)
|