Update app.py
Browse files
app.py
CHANGED
|
@@ -16,6 +16,9 @@ from botbuilder.schema import Activity, ActivityTypes
|
|
| 16 |
from bot import MyBot
|
| 17 |
from config import DefaultConfig
|
| 18 |
from ai_core import AICore
|
|
|
|
|
|
|
|
|
|
| 19 |
import numpy as np
|
| 20 |
import logging
|
| 21 |
from typing import Dict, Any, Tuple
|
|
@@ -26,42 +29,85 @@ logger = logging.getLogger(__name__)
|
|
| 26 |
|
| 27 |
CONFIG = DefaultConfig()
|
| 28 |
|
| 29 |
-
# Initialize AI Core
|
| 30 |
ai_core = AICore()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
# Bot Framework Setup
|
| 33 |
SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
|
| 34 |
ADAPTER = BotFrameworkAdapter(SETTINGS)
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
class CodetteGradioApp:
|
| 37 |
def __init__(self, ai_core: AICore):
|
| 38 |
self.ai_core = ai_core
|
| 39 |
self.chat_history = []
|
| 40 |
|
| 41 |
-
def process_message(self, message: str, history: list) -> Tuple[str, list]:
|
| 42 |
-
"""Process a message and update chat history"""
|
| 43 |
try:
|
| 44 |
-
# Generate response
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
return "", history
|
| 54 |
-
|
| 55 |
except Exception as e:
|
| 56 |
logger.error(f"Error processing message: {e}")
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
def analyze_text(self, text: str)
|
| 60 |
"""Perform comprehensive text analysis"""
|
| 61 |
try:
|
| 62 |
# Get sentiment
|
| 63 |
sentiment = self.ai_core.analyze_sentiment(text)
|
| 64 |
-
|
| 65 |
# Get embeddings
|
| 66 |
embeddings = self.ai_core.get_embeddings(text)
|
| 67 |
if embeddings:
|
|
@@ -69,25 +115,23 @@ class CodetteGradioApp:
|
|
| 69 |
embedding_viz = self._visualize_embeddings(embeddings)
|
| 70 |
else:
|
| 71 |
embedding_viz = None
|
| 72 |
-
|
| 73 |
# Generate creative expansion
|
| 74 |
expansion = self.ai_core.generate_text(
|
| 75 |
f"Creative expansion of the concept: {text}",
|
| 76 |
max_length=150
|
| 77 |
)
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
}
|
| 84 |
except Exception as e:
|
| 85 |
logger.error(f"Error in text analysis: {e}")
|
| 86 |
-
return
|
| 87 |
-
"
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
|
| 92 |
def _visualize_embeddings(self, embeddings: list) -> np.ndarray:
|
| 93 |
"""Create a simple 2D visualization of embeddings"""
|
|
@@ -127,7 +171,7 @@ async def messages(req: Request) -> Response:
|
|
| 127 |
|
| 128 |
# Create Gradio interface
|
| 129 |
def create_gradio_interface():
|
| 130 |
-
with gr.Blocks(title="Codette AI Assistant", theme="
|
| 131 |
gr.Markdown("""
|
| 132 |
# 🤖 Codette AI Assistant
|
| 133 |
A sophisticated AI assistant powered by Hugging Face models.
|
|
@@ -145,23 +189,22 @@ def create_gradio_interface():
|
|
| 145 |
chatbot = gr.Chatbot(
|
| 146 |
[],
|
| 147 |
elem_id="chatbot",
|
| 148 |
-
height=400
|
|
|
|
| 149 |
)
|
| 150 |
-
|
| 151 |
with gr.Row():
|
| 152 |
txt = gr.Textbox(
|
| 153 |
show_label=False,
|
| 154 |
placeholder="Type your message here...",
|
| 155 |
container=False
|
| 156 |
)
|
| 157 |
-
|
| 158 |
-
|
| 159 |
txt.submit(
|
| 160 |
gradio_app.process_message,
|
| 161 |
-
[txt, chatbot],
|
| 162 |
[txt, chatbot]
|
| 163 |
)
|
| 164 |
-
|
| 165 |
clear = gr.Button("Clear")
|
| 166 |
clear.click(lambda: [], None, chatbot)
|
| 167 |
|
|
|
|
| 16 |
from bot import MyBot
|
| 17 |
from config import DefaultConfig
|
| 18 |
from ai_core import AICore
|
| 19 |
+
from aegis_integration import AegisBridge
|
| 20 |
+
from aegis_integration.config import AEGIS_CONFIG
|
| 21 |
+
from aegis_integration.routes import register_aegis_endpoints
|
| 22 |
import numpy as np
|
| 23 |
import logging
|
| 24 |
from typing import Dict, Any, Tuple
|
|
|
|
| 29 |
|
| 30 |
CONFIG = DefaultConfig()
|
| 31 |
|
| 32 |
+
# Initialize AI Core and AEGIS
|
| 33 |
ai_core = AICore()
|
| 34 |
+
aegis_bridge = AegisBridge(ai_core, AEGIS_CONFIG)
|
| 35 |
+
ai_core.set_aegis_bridge(aegis_bridge)
|
| 36 |
+
|
| 37 |
+
# Force fallback to gpt2 for text generation
|
| 38 |
+
ai_core.model_id = 'gpt2'
|
| 39 |
|
| 40 |
# Bot Framework Setup
|
| 41 |
SETTINGS = BotFrameworkAdapterSettings(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
|
| 42 |
ADAPTER = BotFrameworkAdapter(SETTINGS)
|
| 43 |
|
| 44 |
+
# Create Gradio interface with AEGIS integration
|
| 45 |
+
app = gr.Interface(
|
| 46 |
+
fn=lambda x: ai_core.generate_text(x),
|
| 47 |
+
inputs="text",
|
| 48 |
+
outputs=[
|
| 49 |
+
gr.Textbox(label="Response"),
|
| 50 |
+
gr.JSON(label="AEGIS Analysis", visible=True)
|
| 51 |
+
],
|
| 52 |
+
title="Codette with AEGIS",
|
| 53 |
+
description="An ethical AI assistant enhanced with AEGIS analysis"
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
class CodetteGradioApp:
|
| 57 |
def __init__(self, ai_core: AICore):
|
| 58 |
self.ai_core = ai_core
|
| 59 |
self.chat_history = []
|
| 60 |
|
| 61 |
+
def process_message(self, message: str, history: list, cocoon_mode: bool = False) -> Tuple[str, list]:
|
| 62 |
+
"""Process a message and update chat history, with optional cocoon-powered creativity"""
|
| 63 |
try:
|
| 64 |
+
# Generate response (cocoon-powered if enabled)
|
| 65 |
+
if cocoon_mode:
|
| 66 |
+
# Ensure cocoons are loaded
|
| 67 |
+
if not hasattr(self.ai_core, 'cocoon_data') or not self.ai_core.cocoon_data:
|
| 68 |
+
self.ai_core.load_cocoon_data()
|
| 69 |
+
response = self.ai_core.remix_and_randomize_response(message, cocoon_mode=True)
|
| 70 |
+
else:
|
| 71 |
+
response = self.ai_core.generate_text(message)
|
| 72 |
+
try:
|
| 73 |
+
# Analyze sentiment
|
| 74 |
+
sentiment = self.ai_core.analyze_sentiment(message)
|
| 75 |
+
label = sentiment.get('label', '').upper()
|
| 76 |
+
score = sentiment.get('score', 0.0)
|
| 77 |
+
# Use transformers to generate a unique, sentiment-aware reply
|
| 78 |
+
if label == 'POS':
|
| 79 |
+
prompt = f"The user said something positive: '{message}'. Respond in a cheerful, encouraging, and unique way."
|
| 80 |
+
elif label == 'NEG':
|
| 81 |
+
prompt = f"The user said something negative: '{message}'. Respond with empathy, support, and a unique comforting message."
|
| 82 |
+
elif label == 'NEU':
|
| 83 |
+
prompt = f"The user said something neutral: '{message}'. Respond in a thoughtful, neutral, and unique way."
|
| 84 |
+
else:
|
| 85 |
+
prompt = f"The user's sentiment is unclear: '{message}'. Respond in a curious, open-minded, and unique way."
|
| 86 |
+
char_response = self.ai_core.generate_text(prompt, max_length=60)
|
| 87 |
+
sentiment_info = f"\n[Sentiment: {label} ({score:.2f})] {char_response}"
|
| 88 |
+
except Exception as sent_e:
|
| 89 |
+
logger.error(f"Sentiment analysis error: {sent_e}")
|
| 90 |
+
sentiment_info = "\n[Sentiment: error (0.00)] 🤖 Sorry, I couldn't analyze the sentiment."
|
| 91 |
+
# Update history in Gradio 'messages' format
|
| 92 |
+
history = history + [
|
| 93 |
+
{"role": "user", "content": message},
|
| 94 |
+
{"role": "assistant", "content": response + sentiment_info}
|
| 95 |
+
]
|
| 96 |
return "", history
|
|
|
|
| 97 |
except Exception as e:
|
| 98 |
logger.error(f"Error processing message: {e}")
|
| 99 |
+
# Add error as assistant message
|
| 100 |
+
history = history + [
|
| 101 |
+
{"role": "user", "content": message},
|
| 102 |
+
{"role": "assistant", "content": f"Error: {str(e)}"}
|
| 103 |
+
]
|
| 104 |
+
return "", history
|
| 105 |
|
| 106 |
+
def analyze_text(self, text: str):
|
| 107 |
"""Perform comprehensive text analysis"""
|
| 108 |
try:
|
| 109 |
# Get sentiment
|
| 110 |
sentiment = self.ai_core.analyze_sentiment(text)
|
|
|
|
| 111 |
# Get embeddings
|
| 112 |
embeddings = self.ai_core.get_embeddings(text)
|
| 113 |
if embeddings:
|
|
|
|
| 115 |
embedding_viz = self._visualize_embeddings(embeddings)
|
| 116 |
else:
|
| 117 |
embedding_viz = None
|
|
|
|
| 118 |
# Generate creative expansion
|
| 119 |
expansion = self.ai_core.generate_text(
|
| 120 |
f"Creative expansion of the concept: {text}",
|
| 121 |
max_length=150
|
| 122 |
)
|
| 123 |
+
return (
|
| 124 |
+
f"Sentiment: {sentiment['label']} (confidence: {sentiment['score']:.2f})",
|
| 125 |
+
embedding_viz,
|
| 126 |
+
expansion
|
| 127 |
+
)
|
|
|
|
| 128 |
except Exception as e:
|
| 129 |
logger.error(f"Error in text analysis: {e}")
|
| 130 |
+
return (
|
| 131 |
+
"Error analyzing sentiment",
|
| 132 |
+
None,
|
| 133 |
+
str(e)
|
| 134 |
+
)
|
| 135 |
|
| 136 |
def _visualize_embeddings(self, embeddings: list) -> np.ndarray:
|
| 137 |
"""Create a simple 2D visualization of embeddings"""
|
|
|
|
| 171 |
|
| 172 |
# Create Gradio interface
|
| 173 |
def create_gradio_interface():
|
| 174 |
+
with gr.Blocks(title="Codette AI Assistant", theme="default") as interface:
|
| 175 |
gr.Markdown("""
|
| 176 |
# 🤖 Codette AI Assistant
|
| 177 |
A sophisticated AI assistant powered by Hugging Face models.
|
|
|
|
| 189 |
chatbot = gr.Chatbot(
|
| 190 |
[],
|
| 191 |
elem_id="chatbot",
|
| 192 |
+
height=400,
|
| 193 |
+
type="messages"
|
| 194 |
)
|
|
|
|
| 195 |
with gr.Row():
|
| 196 |
txt = gr.Textbox(
|
| 197 |
show_label=False,
|
| 198 |
placeholder="Type your message here...",
|
| 199 |
container=False
|
| 200 |
)
|
| 201 |
+
with gr.Row():
|
| 202 |
+
cocoon_toggle = gr.Checkbox(label="Enable Cocoon-Powered Creativity", value=False)
|
| 203 |
txt.submit(
|
| 204 |
gradio_app.process_message,
|
| 205 |
+
[txt, chatbot, cocoon_toggle],
|
| 206 |
[txt, chatbot]
|
| 207 |
)
|
|
|
|
| 208 |
clear = gr.Button("Clear")
|
| 209 |
clear.click(lambda: [], None, chatbot)
|
| 210 |
|