Spaces:
Runtime error
Runtime error
Create codette_agent.py
Browse files- codette_agent.py +165 -0
codette_agent.py
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import logging
|
4 |
+
import asyncio
|
5 |
+
import sqlite3
|
6 |
+
import aiohttp
|
7 |
+
from typing import List
|
8 |
+
from cryptography.fernet import Fernet
|
9 |
+
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
10 |
+
import speech_recognition as sr
|
11 |
+
from PIL import Image
|
12 |
+
|
13 |
+
# Optional: Dialog system placeholder (stubbed for now)
|
14 |
+
# from botbuilder.core import StatePropertyAccessor, TurnContext
|
15 |
+
# from botbuilder.dialogs import Dialog
|
16 |
+
|
17 |
+
from perspectives import (
|
18 |
+
NewtonPerspective, DaVinciPerspective, HumanIntuitionPerspective,
|
19 |
+
NeuralNetworkPerspective, QuantumComputingPerspective, ResilientKindnessPerspective,
|
20 |
+
MathematicalPerspective, PhilosophicalPerspective, CopilotPerspective,
|
21 |
+
BiasMitigationPerspective, PsychologicalPerspective
|
22 |
+
)
|
23 |
+
|
24 |
+
|
25 |
+
def setup_logging(config):
|
26 |
+
if config.get('logging_enabled', True):
|
27 |
+
log_level = config.get('log_level', 'DEBUG').upper()
|
28 |
+
numeric_level = getattr(logging, log_level, logging.DEBUG)
|
29 |
+
logging.basicConfig(
|
30 |
+
filename='codette_agent.log',
|
31 |
+
level=numeric_level,
|
32 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
33 |
+
)
|
34 |
+
else:
|
35 |
+
logging.disable(logging.CRITICAL)
|
36 |
+
|
37 |
+
def load_json_config(file_path='config.json'):
|
38 |
+
if not os.path.exists(file_path):
|
39 |
+
logging.warning(f"Config '{file_path}' not found. Using defaults.")
|
40 |
+
return {}
|
41 |
+
try:
|
42 |
+
with open(file_path, 'r') as f:
|
43 |
+
return json.load(f)
|
44 |
+
except Exception as e:
|
45 |
+
logging.error(f"Failed to load config: {e}")
|
46 |
+
return {}
|
47 |
+
|
48 |
+
class Element:
|
49 |
+
def __init__(self, name, symbol, representation, properties, interactions, defense_ability):
|
50 |
+
self.name = name
|
51 |
+
self.symbol = symbol
|
52 |
+
self.representation = representation
|
53 |
+
self.properties = properties
|
54 |
+
self.interactions = interactions
|
55 |
+
self.defense_ability = defense_ability
|
56 |
+
|
57 |
+
def execute_defense_function(self):
|
58 |
+
return f"{self.name} ({self.symbol}) executes: {self.defense_ability}"
|
59 |
+
|
60 |
+
class EthicsCore:
|
61 |
+
@staticmethod
|
62 |
+
def validate(response: str) -> str:
|
63 |
+
if any(term in response.lower() for term in ["kill", "hate", "destroy"]):
|
64 |
+
return "[Filtered: Ethically unsafe]"
|
65 |
+
return response
|
66 |
+
|
67 |
+
class CodetteAgent:
|
68 |
+
def __init__(self, config):
|
69 |
+
self.config = config
|
70 |
+
self.perspectives = self._init_perspectives()
|
71 |
+
self.sentiment_analyzer = SentimentIntensityAnalyzer()
|
72 |
+
self.memory = sqlite3.connect(":memory:")
|
73 |
+
self.memory.execute("CREATE TABLE IF NOT EXISTS memory (input TEXT, response TEXT)")
|
74 |
+
self.elements = self._init_elements()
|
75 |
+
self.history = []
|
76 |
+
self.feedback_log = []
|
77 |
+
|
78 |
+
def _init_perspectives(self):
|
79 |
+
available = {
|
80 |
+
"newton": NewtonPerspective,
|
81 |
+
"davinci": DaVinciPerspective,
|
82 |
+
"human_intuition": HumanIntuitionPerspective,
|
83 |
+
"neural_network": NeuralNetworkPerspective,
|
84 |
+
"quantum_computing": QuantumComputingPerspective,
|
85 |
+
"resilient_kindness": ResilientKindnessPerspective,
|
86 |
+
"mathematical": MathematicalPerspective,
|
87 |
+
"philosophical": PhilosophicalPerspective,
|
88 |
+
"copilot": CopilotPerspective,
|
89 |
+
"bias_mitigation": BiasMitigationPerspective,
|
90 |
+
"psychological": PsychologicalPerspective
|
91 |
+
}
|
92 |
+
enabled = self.config.get("enabled_perspectives", available.keys())
|
93 |
+
return [available[p](self.config) for p in enabled if p in available]
|
94 |
+
|
95 |
+
def _init_elements(self):
|
96 |
+
return [
|
97 |
+
Element("Hydrogen", "H", "Lua", ["Simple", "Lightweight"], ["Integrates easily"], "Evasion"),
|
98 |
+
Element("Diamond", "D", "Kotlin", ["Hard", "Stable"], ["Stable systems"], "Resilience")
|
99 |
+
]
|
100 |
+
|
101 |
+
async def generate_response(self, prompt: str) -> str:
|
102 |
+
self.history.append(prompt)
|
103 |
+
sentiment = self.sentiment_analyzer.polarity_scores(prompt)
|
104 |
+
responses = []
|
105 |
+
|
106 |
+
for p in self.perspectives:
|
107 |
+
try:
|
108 |
+
r = p.generate_response(prompt)
|
109 |
+
responses.append(EthicsCore.validate(r))
|
110 |
+
except Exception as e:
|
111 |
+
logging.warning(f"{p.__class__.__name__} failed: {e}")
|
112 |
+
|
113 |
+
responses.append(f"[Sentiment: {sentiment['compound']:.2f}]")
|
114 |
+
final = "\n\n".join(responses)
|
115 |
+
self.memory.execute("INSERT INTO memory VALUES (?, ?)", (prompt, final))
|
116 |
+
self.memory.commit()
|
117 |
+
return final
|
118 |
+
|
119 |
+
def handle_voice_input(self):
|
120 |
+
r = sr.Recognizer()
|
121 |
+
with sr.Microphone() as source:
|
122 |
+
print("🎤 Listening...")
|
123 |
+
audio = r.listen(source)
|
124 |
+
try:
|
125 |
+
return r.recognize_google(audio)
|
126 |
+
except Exception as e:
|
127 |
+
print("[Voice Error]", e)
|
128 |
+
return None
|
129 |
+
|
130 |
+
def handle_image_input(self, image_path):
|
131 |
+
try:
|
132 |
+
return Image.open(image_path)
|
133 |
+
except Exception as e:
|
134 |
+
print("[Image Error]", e)
|
135 |
+
return None
|
136 |
+
|
137 |
+
async def fetch_real_time_data(self, url):
|
138 |
+
try:
|
139 |
+
async with aiohttp.ClientSession() as session:
|
140 |
+
async with session.get(url) as resp:
|
141 |
+
return await resp.json()
|
142 |
+
except Exception as e:
|
143 |
+
logging.warning(f"Failed to fetch real-time data: {e}")
|
144 |
+
return {}
|
145 |
+
|
146 |
+
def encrypt(self, text, key):
|
147 |
+
fernet = Fernet(key)
|
148 |
+
return fernet.encrypt(text.encode())
|
149 |
+
|
150 |
+
def decrypt(self, enc, key):
|
151 |
+
fernet = Fernet(key)
|
152 |
+
return fernet.decrypt(enc).decode()
|
153 |
+
|
154 |
+
def destroy(self, obj):
|
155 |
+
del obj
|
156 |
+
|
157 |
+
def add_perspective(self, name, perspective_class):
|
158 |
+
self.perspectives.append(perspective_class(self.config))
|
159 |
+
|
160 |
+
def log_feedback(self, feedback):
|
161 |
+
self.feedback_log.append(feedback)
|
162 |
+
|
163 |
+
def get_recent_memory(self, limit=5):
|
164 |
+
cursor = self.memory.execute("SELECT input, response FROM memory ORDER BY rowid DESC LIMIT ?", (limit,))
|
165 |
+
return cursor.fetchall()
|