|
|
"""
|
|
|
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
|
|
|
|
|
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent.parent))
|
|
|
|
|
|
from flask import Flask, request, jsonify
|
|
|
from flask_cors import CORS
|
|
|
import joblib
|
|
|
|
|
|
|
|
|
from src.iamvc_heart_hybrid import IAMVCHeart, HEARTConfig
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
CORS(app)
|
|
|
|
|
|
|
|
|
heart_model: Optional[IAMVCHeart] = None
|
|
|
helpers: Dict[str, Any] = {}
|
|
|
|
|
|
|
|
|
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...")
|
|
|
|
|
|
|
|
|
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}")
|
|
|
|
|
|
|
|
|
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]
|
|
|
|
|
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
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)
|
|
|
|