IAMVC commited on
Commit
f5a68d8
·
verified ·
1 Parent(s): 3ecc73c

Upload src/api.py with huggingface_hub

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