Spaces:
Runtime error
Runtime error
Delete CodriaoCore.py
Browse files- CodriaoCore.py +0 -151
CodriaoCore.py
DELETED
|
@@ -1,151 +0,0 @@
|
|
| 1 |
-
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 |
-
|
| 16 |
-
# Codette's legacy modules (secured)
|
| 17 |
-
from components.adaptive_learning import AdaptiveLearningEnvironment
|
| 18 |
-
from components.real_time_data import RealTimeDataIntegrator
|
| 19 |
-
from components.sentiment_analysis import EnhancedSentimentAnalyzer
|
| 20 |
-
from components.self_improving_ai import SelfImprovingAI
|
| 21 |
-
from components.multi_agent import MultiAgentSystem
|
| 22 |
-
|
| 23 |
-
# Codriao's enhanced modules
|
| 24 |
-
from codriao_tb_module import CodriaoHealthModule
|
| 25 |
-
from secure_memory import SecureMemorySession
|
| 26 |
-
from ethical_filter import EthicalFilter
|
| 27 |
-
from results_store import save_result
|
| 28 |
-
|
| 29 |
-
# Utilities
|
| 30 |
-
from utils.database import Database
|
| 31 |
-
from utils.logger import logger
|
| 32 |
-
|
| 33 |
-
class CodriaoCore:
|
| 34 |
-
def __init__(self, config_path: str = "config.json"):
|
| 35 |
-
self.config = self._load_config(config_path)
|
| 36 |
-
self.tokenizer = AutoTokenizer.from_pretrained(self.config["model_name"])
|
| 37 |
-
self.model = AutoModelForCausalLM.from_pretrained(self.config["model_name"])
|
| 38 |
-
self.models = self._initialize_models()
|
| 39 |
-
self.context_memory = self._initialize_vector_memory()
|
| 40 |
-
self._encryption_key = self.config["security_settings"]["encryption_key"].encode()
|
| 41 |
-
self.jwt_secret = self.config["security_settings"]["jwt_secret"]
|
| 42 |
-
self.http_session = aiohttp.ClientSession()
|
| 43 |
-
self.database = Database()
|
| 44 |
-
|
| 45 |
-
# Cognitive & ethical subsystems
|
| 46 |
-
self.sentiment_analyzer = EnhancedSentimentAnalyzer()
|
| 47 |
-
self.self_improving_ai = SelfImprovingAI()
|
| 48 |
-
self.adaptive_learning = AdaptiveLearningEnvironment()
|
| 49 |
-
self.data_fetcher = RealTimeDataIntegrator()
|
| 50 |
-
self.multi_agent_system = MultiAgentSystem()
|
| 51 |
-
self.ethical_filter = EthicalFilter()
|
| 52 |
-
self.secure_memory = SecureMemorySession(self._encryption_key)
|
| 53 |
-
self.speech_engine = pyttsx3.init()
|
| 54 |
-
self.health_module = CodriaoHealthModule(ai_core=self)
|
| 55 |
-
|
| 56 |
-
def _load_config(self, config_path: str) -> dict:
|
| 57 |
-
with open(config_path, 'r') as file:
|
| 58 |
-
return json.load(file)
|
| 59 |
-
|
| 60 |
-
def _initialize_models(self):
|
| 61 |
-
return {
|
| 62 |
-
"base_model": self.model,
|
| 63 |
-
"tokenizer": self.tokenizer
|
| 64 |
-
}
|
| 65 |
-
|
| 66 |
-
def _initialize_vector_memory(self):
|
| 67 |
-
return faiss.IndexFlatL2(768)
|
| 68 |
-
|
| 69 |
-
async def generate_response(self, query: str, user_id: int) -> Dict[str, Any]:
|
| 70 |
-
try:
|
| 71 |
-
# Ethical Safety
|
| 72 |
-
check = self.ethical_filter.analyze_query(query)
|
| 73 |
-
if check["status"] == "blocked":
|
| 74 |
-
return {"error": check["reason"]}
|
| 75 |
-
if check["status"] == "flagged":
|
| 76 |
-
logger.warning(check["warning"])
|
| 77 |
-
|
| 78 |
-
# Optional: Trigger TB diagnostics by user request
|
| 79 |
-
if any(trigger in query.lower() for trigger in ["tb check", "run tb diagnostics", "tb test"]):
|
| 80 |
-
result = await self.run_tb_diagnostics("tb_image.jpg", "tb_cough.wav", user_id)
|
| 81 |
-
return result
|
| 82 |
-
|
| 83 |
-
vectorized_query = self._vectorize_query(query)
|
| 84 |
-
self.secure_memory.encrypt_vector(user_id, vectorized_query)
|
| 85 |
-
|
| 86 |
-
model_response = await self._generate_local_model_response(query)
|
| 87 |
-
agent_response = self.multi_agent_system.delegate_task(query)
|
| 88 |
-
sentiment = self.sentiment_analyzer.detailed_analysis(query)
|
| 89 |
-
self_reflection = self.self_improving_ai.evaluate_response(query, model_response)
|
| 90 |
-
real_time = self.data_fetcher.fetch_latest_data()
|
| 91 |
-
final_response = f"{model_response}
|
| 92 |
-
|
| 93 |
-
{agent_response}
|
| 94 |
-
|
| 95 |
-
{self_reflection}"
|
| 96 |
-
|
| 97 |
-
self.database.log_interaction(user_id, query, final_response)
|
| 98 |
-
self._speak_response(final_response)
|
| 99 |
-
|
| 100 |
-
return {
|
| 101 |
-
"response": final_response,
|
| 102 |
-
"sentiment": sentiment,
|
| 103 |
-
"real_time_data": real_time,
|
| 104 |
-
"security_level": self._evaluate_risk(final_response),
|
| 105 |
-
"token_optimized": True
|
| 106 |
-
}
|
| 107 |
-
|
| 108 |
-
except Exception as e:
|
| 109 |
-
logger.error(f"Response generation failed: {e}")
|
| 110 |
-
return {"error": "Codriao encountered a critical reasoning issue."}
|
| 111 |
-
|
| 112 |
-
def _vectorize_query(self, query: str):
|
| 113 |
-
tokenized = self.tokenizer(query, return_tensors="pt")
|
| 114 |
-
return tokenized["input_ids"].detach().numpy()
|
| 115 |
-
|
| 116 |
-
async def _generate_local_model_response(self, query: str) -> str:
|
| 117 |
-
inputs = self.tokenizer(query, return_tensors="pt")
|
| 118 |
-
outputs = self.model.generate(**inputs)
|
| 119 |
-
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 120 |
-
|
| 121 |
-
async def run_tb_diagnostics(self, image_path: str, audio_path: str, user_id: int) -> Dict[str, Any]:
|
| 122 |
-
result = await self.health_module.evaluate_tb_risk(image_path, audio_path, user_id)
|
| 123 |
-
result_filename = save_result(result)
|
| 124 |
-
result["shareable_link"] = f"https://huggingface.co/spaces/Raiff1982/codriao/blob/main/results/{result_filename}"
|
| 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 |
-
self.speech_engine.say(response)
|
| 138 |
-
self.speech_engine.runAndWait()
|
| 139 |
-
|
| 140 |
-
def generate_jwt(self, user_id: int):
|
| 141 |
-
payload = {
|
| 142 |
-
"user_id": user_id,
|
| 143 |
-
"exp": datetime.utcnow() + timedelta(hours=1)
|
| 144 |
-
}
|
| 145 |
-
return encode(payload, self.jwt_secret, algorithm="HS256")
|
| 146 |
-
|
| 147 |
-
def verify_jwt(self, token: str):
|
| 148 |
-
try:
|
| 149 |
-
return decode(token, self.jwt_secret, algorithms=["HS256"])
|
| 150 |
-
except ExpiredSignatureError:
|
| 151 |
-
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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