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 |
+
import aiohttp
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
import torch
|
| 5 |
+
import faiss
|
| 6 |
+
import numpy as np
|
| 7 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 8 |
+
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 os
|
| 13 |
+
import speech_recognition as sr
|
| 14 |
+
import pyttsx3
|
| 15 |
+
from deep_translator import GoogleTranslator
|
| 16 |
+
|
| 17 |
+
# Codette's legacy modules (secured)
|
| 18 |
+
from components.adaptive_learning import AdaptiveLearningEnvironment
|
| 19 |
+
from components.real_time_data import RealTimeDataIntegrator
|
| 20 |
+
from components.sentiment_analysis import EnhancedSentimentAnalyzer
|
| 21 |
+
from components.self_improving_ai import SelfImprovingAI
|
| 22 |
+
from components.multi_agent import MultiAgentSystem
|
| 23 |
+
|
| 24 |
+
# Codriao's enhanced modules
|
| 25 |
+
from codriao_tb_module import CodriaoHealthModule
|
| 26 |
+
from secure_memory import SecureMemorySession
|
| 27 |
+
from ethical_filter import EthicalFilter
|
| 28 |
+
from results_store import save_result
|
| 29 |
+
|
| 30 |
+
# Utilities
|
| 31 |
+
from utils.database import Database
|
| 32 |
+
from utils.logger import logger
|
| 33 |
+
|
| 34 |
+
class CodriaoCore:
|
| 35 |
+
def __init__(self, config_path: str = "config.json"):
|
| 36 |
+
self.config = self._load_config(config_path)
|
| 37 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.config["model_name"])
|
| 38 |
+
self.model = AutoModelForCausalLM.from_pretrained(self.config["model_name"])
|
| 39 |
+
self.models = self._initialize_models()
|
| 40 |
+
self.context_memory = self._initialize_vector_memory()
|
| 41 |
+
self._encryption_key = self.config["security_settings"]["encryption_key"].encode()
|
| 42 |
+
self.jwt_secret = self.config["security_settings"]["jwt_secret"]
|
| 43 |
+
self.http_session = aiohttp.ClientSession()
|
| 44 |
+
self.database = Database()
|
| 45 |
+
|
| 46 |
+
# Cognitive & ethical subsystems
|
| 47 |
+
self.sentiment_analyzer = EnhancedSentimentAnalyzer()
|
| 48 |
+
self.self_improving_ai = SelfImprovingAI()
|
| 49 |
+
self.adaptive_learning = AdaptiveLearningEnvironment()
|
| 50 |
+
self.data_fetcher = RealTimeDataIntegrator()
|
| 51 |
+
self.multi_agent_system = MultiAgentSystem()
|
| 52 |
+
self.ethical_filter = EthicalFilter()
|
| 53 |
+
self.secure_memory = SecureMemorySession(self._encryption_key)
|
| 54 |
+
self.speech_engine = pyttsx3.init()
|
| 55 |
+
self.health_module = CodriaoHealthModule(ai_core=self)
|
| 56 |
+
|
| 57 |
+
def _load_config(self, config_path: str) -> dict:
|
| 58 |
+
with open(config_path, 'r') as file:
|
| 59 |
+
return json.load(file)
|
| 60 |
+
|
| 61 |
+
def _initialize_models(self):
|
| 62 |
+
return {
|
| 63 |
+
"base_model": self.model,
|
| 64 |
+
"tokenizer": self.tokenizer
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
def _initialize_vector_memory(self):
|
| 68 |
+
return faiss.IndexFlatL2(768)
|
| 69 |
+
|
| 70 |
+
async def generate_response(self, query: str, user_id: int) -> Dict[str, Any]:
|
| 71 |
+
try:
|
| 72 |
+
# Ethical Safety
|
| 73 |
+
check = self.ethical_filter.analyze_query(query)
|
| 74 |
+
if check["status"] == "blocked":
|
| 75 |
+
return {"error": check["reason"]}
|
| 76 |
+
if check["status"] == "flagged":
|
| 77 |
+
logger.warning(check["warning"])
|
| 78 |
+
|
| 79 |
+
# Optional: Trigger TB diagnostics by user request
|
| 80 |
+
if any(trigger in query.lower() for trigger in ["tb check", "run tb diagnostics", "tb test"]):
|
| 81 |
+
result = await self.run_tb_diagnostics("tb_image.jpg", "tb_cough.wav", user_id)
|
| 82 |
+
return result
|
| 83 |
+
|
| 84 |
+
vectorized_query = self._vectorize_query(query)
|
| 85 |
+
self.secure_memory.encrypt_vector(user_id, vectorized_query)
|
| 86 |
+
|
| 87 |
+
model_response = await self._generate_local_model_response(query)
|
| 88 |
+
agent_response = self.multi_agent_system.delegate_task(query)
|
| 89 |
+
sentiment = self.sentiment_analyzer.detailed_analysis(query)
|
| 90 |
+
self_reflection = self.self_improving_ai.evaluate_response(query, model_response)
|
| 91 |
+
real_time = self.data_fetcher.fetch_latest_data()
|
| 92 |
+
final_response = f"{model_response}\n\n{agent_response}\n\n{self_reflection}"
|
| 93 |
+
|
| 94 |
+
self.database.log_interaction(user_id, query, final_response)
|
| 95 |
+
self._speak_response(final_response)
|
| 96 |
+
|
| 97 |
+
return {
|
| 98 |
+
"response": final_response,
|
| 99 |
+
"sentiment": sentiment,
|
| 100 |
+
"real_time_data": real_time,
|
| 101 |
+
"security_level": self._evaluate_risk(final_response),
|
| 102 |
+
"token_optimized": True
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
except Exception as e:
|
| 106 |
+
logger.error(f"Response generation failed: {e}")
|
| 107 |
+
return {"error": "Codriao encountered a critical reasoning issue."}
|
| 108 |
+
|
| 109 |
+
async def run_tb_diagnostics(self, image_path: str, audio_path: str, user_id: int, language="en") -> Dict[str, Any]:
|
| 110 |
+
result = await self.health_module.evaluate_tb_risk(image_path, audio_path, user_id)
|
| 111 |
+
result_filename = save_result(result)
|
| 112 |
+
result["shareable_link"] = f"https://huggingface.co/spaces/Raiff1982/codriao/blob/main/results/{result_filename}"
|
| 113 |
+
|
| 114 |
+
# Auto-escalation for HIGH risk
|
| 115 |
+
if result["tb_risk"] == "HIGH":
|
| 116 |
+
result["next_steps"] = "Γ’ΒΒ Γ―ΒΈΒ Immediate follow-up required. Please visit a healthcare provider."
|
| 117 |
+
elif result["tb_risk"] == "MEDIUM":
|
| 118 |
+
result["next_steps"] = "Γ°ΒΒΒ Consider additional testing for confirmation."
|
| 119 |
+
|
| 120 |
+
# Multi-language support
|
| 121 |
+
if language != "en":
|
| 122 |
+
translated_result = GoogleTranslator(source="auto", target=language).translate(json.dumps(result))
|
| 123 |
+
return json.loads(translated_result)
|
| 124 |
+
|
| 125 |
+
return result
|
| 126 |
+
|
| 127 |
+
def _evaluate_risk(self, response: str) -> str:
|
| 128 |
+
if "critical" in response.lower():
|
| 129 |
+
return "HIGH"
|
| 130 |
+
elif "concern" in response.lower():
|
| 131 |
+
return "MEDIUM"
|
| 132 |
+
else:
|
| 133 |
+
return "LOW"
|
| 134 |
+
|
| 135 |
+
def _speak_response(self, response: str):
|
| 136 |
+
if self.config["speech_settings"]["emotion_adaptive"]:
|
| 137 |
+
try:
|
| 138 |
+
self.speech_engine.say(response)
|
| 139 |
+
self.speech_engine.runAndWait()
|
| 140 |
+
except:
|
| 141 |
+
pass # Ignore if running in a non-audio environment
|
| 142 |
+
|
| 143 |
+
def generate_jwt(self, user_id: int):
|
| 144 |
+
payload = {
|
| 145 |
+
"user_id": user_id,
|
| 146 |
+
"exp": datetime.utcnow() + timedelta(hours=1)
|
| 147 |
+
}
|
| 148 |
+
return encode(payload, self.jwt_secret, algorithm="HS256")
|
| 149 |
+
|
| 150 |
+
def verify_jwt(self, token: str):
|
| 151 |
+
try:
|
| 152 |
+
return decode(token, self.jwt_secret, algorithms=["HS256"])
|
| 153 |
+
except ExpiredSignatureError:
|
| 154 |
+
return None
|