Spaces:
Runtime error
Runtime error
Update AICoreAGIX_with_TB.py
Browse files- AICoreAGIX_with_TB.py +43 -40
AICoreAGIX_with_TB.py
CHANGED
@@ -9,7 +9,6 @@ from typing import List, Dict, Any
|
|
9 |
from cryptography.fernet import Fernet
|
10 |
from jwt import encode, decode, ExpiredSignatureError
|
11 |
from datetime import datetime, timedelta
|
12 |
-
import speech_recognition as sr
|
13 |
import pyttsx3
|
14 |
import os
|
15 |
|
@@ -41,7 +40,7 @@ class AICoreAGIX:
|
|
41 |
self.federated_ai = FederatedAI()
|
42 |
|
43 |
# Secure memory setup
|
44 |
-
self._encryption_key =
|
45 |
secure_memory_module = load_secure_memory_module()
|
46 |
SecureMemorySession = secure_memory_module.SecureMemorySession
|
47 |
self.secure_memory_loader = SecureMemorySession(self._encryption_key)
|
@@ -51,6 +50,10 @@ class AICoreAGIX:
|
|
51 |
|
52 |
async def generate_response(self, query: str, user_id: int) -> Dict[str, Any]:
|
53 |
try:
|
|
|
|
|
|
|
|
|
54 |
result = self.ethical_filter.analyze_query(query)
|
55 |
if result["status"] == "blocked":
|
56 |
return {"error": result["reason"]}
|
@@ -59,33 +62,23 @@ class AICoreAGIX:
|
|
59 |
|
60 |
if any(phrase in query.lower() for phrase in ["tb check", "analyze my tb", "run tb diagnostics", "tb test"]):
|
61 |
result = await self.run_tb_diagnostics("tb_image.jpg", "tb_cough.wav", user_id)
|
62 |
-
return
|
63 |
-
"response": result["ethical_analysis"],
|
64 |
-
"explanation": result["explanation"],
|
65 |
-
"tb_risk": result["tb_risk"],
|
66 |
-
"image_analysis": result["image_analysis"],
|
67 |
-
"audio_analysis": result["audio_analysis"],
|
68 |
-
"system_health": result["system_health"]
|
69 |
-
}
|
70 |
|
71 |
vectorized_query = self._vectorize_query(query)
|
72 |
self.secure_memory_loader.encrypt_vector(user_id, vectorized_query)
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
final_response = (
|
82 |
-
f"{model_response}\n\n"
|
83 |
-
f"{agent_response}\n\n"
|
84 |
-
f"{self_reflection}\n\n"
|
85 |
-
f"Logic: {neural_reasoning}"
|
86 |
)
|
87 |
|
|
|
|
|
88 |
self.database.log_interaction(user_id, query, final_response)
|
|
|
89 |
self._speak_response(final_response)
|
90 |
|
91 |
return {
|
@@ -99,6 +92,11 @@ class AICoreAGIX:
|
|
99 |
logger.error(f"Response generation failed: {e}")
|
100 |
return {"error": "Processing failed - safety protocols engaged"}
|
101 |
|
|
|
|
|
|
|
|
|
|
|
102 |
async def run_tb_diagnostics(self, image_path: str, audio_path: str, user_id: int) -> Dict[str, Any]:
|
103 |
try:
|
104 |
result = await self.health_module.evaluate_tb_risk(image_path, audio_path, user_id)
|
@@ -106,27 +104,32 @@ class AICoreAGIX:
|
|
106 |
return result
|
107 |
except Exception as e:
|
108 |
logger.error(f"TB diagnostics failed: {e}")
|
109 |
-
return {
|
110 |
-
"tb_risk": "ERROR",
|
111 |
-
"error": str(e),
|
112 |
-
"image_analysis": {},
|
113 |
-
"audio_analysis": {},
|
114 |
-
"ethical_analysis": "Unable to complete TB diagnostic.",
|
115 |
-
"explanation": None,
|
116 |
-
"system_health": None
|
117 |
-
}
|
118 |
|
119 |
-
def
|
120 |
-
|
121 |
-
|
122 |
|
123 |
def _initialize_vector_memory(self):
|
124 |
return faiss.IndexFlatL2(768)
|
125 |
|
126 |
-
def
|
127 |
-
|
128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
|
130 |
def _speak_response(self, response: str):
|
131 |
-
|
132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
from cryptography.fernet import Fernet
|
10 |
from jwt import encode, decode, ExpiredSignatureError
|
11 |
from datetime import datetime, timedelta
|
|
|
12 |
import pyttsx3
|
13 |
import os
|
14 |
|
|
|
40 |
self.federated_ai = FederatedAI()
|
41 |
|
42 |
# Secure memory setup
|
43 |
+
self._encryption_key = Fernet.generate_key() # Rotated dynamically
|
44 |
secure_memory_module = load_secure_memory_module()
|
45 |
SecureMemorySession = secure_memory_module.SecureMemorySession
|
46 |
self.secure_memory_loader = SecureMemorySession(self._encryption_key)
|
|
|
50 |
|
51 |
async def generate_response(self, query: str, user_id: int) -> Dict[str, Any]:
|
52 |
try:
|
53 |
+
# Validate query
|
54 |
+
if not isinstance(query, str) or len(query.strip()) == 0:
|
55 |
+
raise ValueError("Invalid query input.")
|
56 |
+
|
57 |
result = self.ethical_filter.analyze_query(query)
|
58 |
if result["status"] == "blocked":
|
59 |
return {"error": result["reason"]}
|
|
|
62 |
|
63 |
if any(phrase in query.lower() for phrase in ["tb check", "analyze my tb", "run tb diagnostics", "tb test"]):
|
64 |
result = await self.run_tb_diagnostics("tb_image.jpg", "tb_cough.wav", user_id)
|
65 |
+
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
66 |
|
67 |
vectorized_query = self._vectorize_query(query)
|
68 |
self.secure_memory_loader.encrypt_vector(user_id, vectorized_query)
|
69 |
+
|
70 |
+
# Gather responses asynchronously
|
71 |
+
responses = await asyncio.gather(
|
72 |
+
self._generate_local_model_response(query),
|
73 |
+
self.multi_agent_system.delegate_task(query),
|
74 |
+
self.self_improving_ai.evaluate_response(query),
|
75 |
+
self.neural_symbolic_engine.integrate_reasoning(query)
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
)
|
77 |
|
78 |
+
final_response = "\n\n".join(responses)
|
79 |
+
|
80 |
self.database.log_interaction(user_id, query, final_response)
|
81 |
+
self._log_to_blockchain(user_id, query, final_response)
|
82 |
self._speak_response(final_response)
|
83 |
|
84 |
return {
|
|
|
92 |
logger.error(f"Response generation failed: {e}")
|
93 |
return {"error": "Processing failed - safety protocols engaged"}
|
94 |
|
95 |
+
async def _generate_local_model_response(self, query: str) -> str:
|
96 |
+
inputs = self.tokenizer(query, return_tensors="pt")
|
97 |
+
outputs = self.model.generate(**inputs)
|
98 |
+
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
99 |
+
|
100 |
async def run_tb_diagnostics(self, image_path: str, audio_path: str, user_id: int) -> Dict[str, Any]:
|
101 |
try:
|
102 |
result = await self.health_module.evaluate_tb_risk(image_path, audio_path, user_id)
|
|
|
104 |
return result
|
105 |
except Exception as e:
|
106 |
logger.error(f"TB diagnostics failed: {e}")
|
107 |
+
return {"tb_risk": "ERROR", "error": str(e)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
|
109 |
+
def _vectorize_query(self, query: str):
|
110 |
+
tokenized = self.tokenizer(query, return_tensors="pt")
|
111 |
+
return tokenized["input_ids"].detach().numpy()
|
112 |
|
113 |
def _initialize_vector_memory(self):
|
114 |
return faiss.IndexFlatL2(768)
|
115 |
|
116 |
+
def _log_to_blockchain(self, user_id: int, query: str, final_response: str):
|
117 |
+
retries = 3
|
118 |
+
for attempt in range(retries):
|
119 |
+
try:
|
120 |
+
# Replace with real blockchain logging function
|
121 |
+
logger.info(f"Logging interaction to blockchain: Attempt {attempt + 1}")
|
122 |
+
break
|
123 |
+
except Exception as e:
|
124 |
+
logger.warning(f"Blockchain logging failed: {e}")
|
125 |
+
continue
|
126 |
|
127 |
def _speak_response(self, response: str):
|
128 |
+
try:
|
129 |
+
self.speech_engine.say(response)
|
130 |
+
self.speech_engine.runAndWait()
|
131 |
+
except Exception as e:
|
132 |
+
logger.error(f"Speech synthesis failed: {e}")
|
133 |
+
|
134 |
+
async def shutdown(self):
|
135 |
+
await self.http_session.close()
|