Spaces:
Sleeping
Sleeping
Update codette_new.py
Browse files- codette_new.py +357 -327
codette_new.py
CHANGED
|
@@ -1,327 +1,357 @@
|
|
| 1 |
-
|
| 2 |
-
import nltk
|
| 3 |
-
import numpy as np
|
| 4 |
-
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 5 |
-
from typing import List, Dict, Any, Optional
|
| 6 |
-
from nltk.tokenize import word_tokenize
|
| 7 |
-
import os
|
| 8 |
-
import json
|
| 9 |
-
from datetime import datetime
|
| 10 |
-
|
| 11 |
-
logger = logging.getLogger(__name__)
|
| 12 |
-
|
| 13 |
-
# Download required NLTK data with error handling
|
| 14 |
-
try:
|
| 15 |
-
nltk.download('punkt', quiet=True)
|
| 16 |
-
nltk.download('averaged_perceptron_tagger', quiet=True)
|
| 17 |
-
nltk.download('wordnet', quiet=True)
|
| 18 |
-
except Exception as e:
|
| 19 |
-
logger.warning(f"NLTK download failed (this is non-critical): {e}")
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
#
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
self.
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
self.
|
| 43 |
-
self.
|
| 44 |
-
self.
|
| 45 |
-
self.
|
| 46 |
-
self.
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
"
|
| 73 |
-
"
|
| 74 |
-
"
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
"
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
if
|
| 166 |
-
return
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
return
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
return
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
"
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
"
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
"
|
| 264 |
-
"
|
| 265 |
-
"
|
| 266 |
-
"
|
| 267 |
-
}
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import nltk
|
| 3 |
+
import numpy as np
|
| 4 |
+
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 5 |
+
from typing import List, Dict, Any, Optional
|
| 6 |
+
from nltk.tokenize import word_tokenize
|
| 7 |
+
import os
|
| 8 |
+
import json
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
# Download required NLTK data with error handling
|
| 14 |
+
try:
|
| 15 |
+
nltk.download('punkt', quiet=True)
|
| 16 |
+
nltk.download('averaged_perceptron_tagger', quiet=True)
|
| 17 |
+
nltk.download('wordnet', quiet=True)
|
| 18 |
+
except Exception as e:
|
| 19 |
+
logger.warning(f"NLTK download failed (this is non-critical): {e}")
|
| 20 |
+
|
| 21 |
+
# Import natural response enhancer (optional - graceful degradation if not available)
|
| 22 |
+
try:
|
| 23 |
+
from src.components.natural_response_enhancer import get_natural_enhancer
|
| 24 |
+
NATURAL_ENHANCER_AVAILABLE = True
|
| 25 |
+
except ImportError:
|
| 26 |
+
try:
|
| 27 |
+
# Try alternative import path
|
| 28 |
+
from natural_response_enhancer import get_natural_enhancer
|
| 29 |
+
NATURAL_ENHANCER_AVAILABLE = True
|
| 30 |
+
except ImportError:
|
| 31 |
+
NATURAL_ENHANCER_AVAILABLE = False
|
| 32 |
+
logger.debug("Natural response enhancer not available")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class Codette:
|
| 36 |
+
def __init__(self, user_name="User"):
|
| 37 |
+
self.user_name = user_name
|
| 38 |
+
self.memory = []
|
| 39 |
+
self.analyzer = SentimentIntensityAnalyzer()
|
| 40 |
+
np.seterr(divide='ignore', invalid='ignore')
|
| 41 |
+
# audit_log may rely on logging; ensure method exists before call
|
| 42 |
+
self.context_memory = []
|
| 43 |
+
self.daw_knowledge = self._initialize_daw_knowledge()
|
| 44 |
+
self.recent_responses = []
|
| 45 |
+
self.max_recent_responses = 20
|
| 46 |
+
self.personality_modes = {
|
| 47 |
+
'technical_expert': 'precise_technical_professional',
|
| 48 |
+
'creative_mentor': 'inspirational_metaphorical_encouraging',
|
| 49 |
+
'practical_guide': 'direct_actionable_efficient',
|
| 50 |
+
'analytical_teacher': 'detailed_explanatory_educational',
|
| 51 |
+
'innovative_explorer': 'experimental_cutting_edge_forward_thinking'
|
| 52 |
+
}
|
| 53 |
+
self.current_personality = 'technical_expert'
|
| 54 |
+
self.conversation_topics = []
|
| 55 |
+
self.max_conversation_topics = 10
|
| 56 |
+
self.has_music_knowledge_table = False
|
| 57 |
+
self.has_music_knowledge_backup_table = False
|
| 58 |
+
self.has_chat_history_table = False
|
| 59 |
+
self.music_knowledge_table = 'music_knowledge'
|
| 60 |
+
self.supabase_client = self._initialize_supabase()
|
| 61 |
+
# Initialize natural response enhancer if available
|
| 62 |
+
self.natural_enhancer = get_natural_enhancer() if NATURAL_ENHANCER_AVAILABLE else None
|
| 63 |
+
# Log after initialization
|
| 64 |
+
try:
|
| 65 |
+
self.audit_log("Codette initialized with FULL ML CAPABILITIES (no placeholders)", system=True)
|
| 66 |
+
except Exception:
|
| 67 |
+
logger.info("Codette initialized (audit log not available yet)")
|
| 68 |
+
|
| 69 |
+
def _initialize_daw_knowledge(self) -> Dict[str, Any]:
|
| 70 |
+
return {
|
| 71 |
+
"frequency_ranges": {
|
| 72 |
+
"sub_bass": (20, 60),
|
| 73 |
+
"bass": (60, 250),
|
| 74 |
+
"low_mid": (250, 500),
|
| 75 |
+
"mid": (500, 2000),
|
| 76 |
+
"high_mid": (2000, 4000),
|
| 77 |
+
"presence": (4000, 6000),
|
| 78 |
+
"brilliance": (6000, 20000)
|
| 79 |
+
},
|
| 80 |
+
"mixing_principles": {
|
| 81 |
+
"gain_staging": "Set master fader to -6dB headroom before mixing. Individual tracks should peak around -12dB to -6dB.",
|
| 82 |
+
"eq_fundamentals": "Cut before boost. Use high-pass filters to remove unnecessary low-end. EQ to fit tracks in the frequency spectrum, not in isolation.",
|
| 83 |
+
"compression_strategy": "Start with 4:1 ratio, adjust attack/release based on transient content. Use parallel compression for drums.",
|
| 84 |
+
"panning_technique": "Pan rhythmic elements for width, keep bass and kick centered. Use mid-side processing for stereo field control."
|
| 85 |
+
},
|
| 86 |
+
"problem_detection": {
|
| 87 |
+
"muddy_mix": "Excessive energy in 200-500Hz range. Solution: High-pass filters on non-bass elements, surgical EQ cuts.",
|
| 88 |
+
"harsh_highs": "Peak around 3-5kHz causing fatigue. Solution: Gentle EQ reduction, de-esser on vocals.",
|
| 89 |
+
"weak_low_end": "Insufficient bass presence. Solution: Check phase relationships, ensure bass/kick complement each other.",
|
| 90 |
+
"lack_of_depth": "Everything sounds flat. Solution: Use reverb/delay strategically, automate wet/dry mix."
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
def respond(self, prompt: str) -> str:
|
| 95 |
+
sentiment = self.analyze_sentiment(prompt)
|
| 96 |
+
key_concepts = self.extract_key_concepts(prompt)
|
| 97 |
+
|
| 98 |
+
self.memory.append({
|
| 99 |
+
"prompt": prompt,
|
| 100 |
+
"sentiment": sentiment,
|
| 101 |
+
"concepts": key_concepts,
|
| 102 |
+
"timestamp": datetime.now().isoformat()
|
| 103 |
+
})
|
| 104 |
+
|
| 105 |
+
is_daw_query = self._is_daw_query_ml(prompt, key_concepts)
|
| 106 |
+
responses: List[str] = []
|
| 107 |
+
|
| 108 |
+
if is_daw_query:
|
| 109 |
+
daw_response = self._generate_daw_specific_response_ml(prompt, key_concepts, sentiment)
|
| 110 |
+
responses.append(f"{daw_response}") # Removed [DAW Expert] prefix
|
| 111 |
+
|
| 112 |
+
technical_insight = self._generate_technical_insight_ml(key_concepts, sentiment)
|
| 113 |
+
responses.append(f"{technical_insight}") # Removed [Technical] prefix
|
| 114 |
+
else:
|
| 115 |
+
neural_insight = self._generate_neural_insight_ml(key_concepts, sentiment)
|
| 116 |
+
responses.append(f"{neural_insight}") # Removed [Neural] prefix
|
| 117 |
+
|
| 118 |
+
logical_response = self._generate_logical_response_ml(key_concepts, sentiment)
|
| 119 |
+
responses.append(f"{logical_response}") # Removed [Logical] prefix
|
| 120 |
+
|
| 121 |
+
creative_response = self._generate_creative_response_ml(key_concepts, sentiment)
|
| 122 |
+
responses.append(f"{creative_response}") # Removed [Creative] prefix
|
| 123 |
+
|
| 124 |
+
try:
|
| 125 |
+
full_response = "\n\n".join(responses)
|
| 126 |
+
self.save_conversation_to_db(prompt, full_response)
|
| 127 |
+
except Exception as e:
|
| 128 |
+
logger.warning(f"Could not save conversation to DB: {e}")
|
| 129 |
+
|
| 130 |
+
self.context_memory.append({
|
| 131 |
+
'input': prompt,
|
| 132 |
+
'concepts': key_concepts,
|
| 133 |
+
'sentiment': sentiment.get('compound', 0) if isinstance(sentiment, dict) else 0,
|
| 134 |
+
'is_daw': is_daw_query
|
| 135 |
+
})
|
| 136 |
+
|
| 137 |
+
# Apply natural enhancement to remove any unnatural markers and improve flow
|
| 138 |
+
final_response = "\n\n".join(responses)
|
| 139 |
+
|
| 140 |
+
if self.natural_enhancer:
|
| 141 |
+
try:
|
| 142 |
+
final_response = self.natural_enhancer.enhance_response(
|
| 143 |
+
final_response,
|
| 144 |
+
confidence=0.85,
|
| 145 |
+
context={'domain': 'music' if is_daw_query else 'general'}
|
| 146 |
+
)
|
| 147 |
+
except Exception as e:
|
| 148 |
+
logger.debug(f"Natural enhancement failed (using original): {e}")
|
| 149 |
+
# Fall back to original if enhancement fails
|
| 150 |
+
|
| 151 |
+
return final_response
|
| 152 |
+
|
| 153 |
+
def _is_daw_query_ml(self, prompt: str, concepts: List[str]) -> bool:
|
| 154 |
+
daw_semantic_indicators = {
|
| 155 |
+
'audio_production', 'mixing', 'mastering', 'recording',
|
| 156 |
+
'eq', 'compression', 'reverb', 'delay', 'frequency',
|
| 157 |
+
'gain', 'volume', 'pan', 'stereo', 'track', 'plugin'
|
| 158 |
+
}
|
| 159 |
+
prompt_lower = prompt.lower()
|
| 160 |
+
concept_set = set(concepts)
|
| 161 |
+
return bool(daw_semantic_indicators & concept_set) or any(indicator in prompt_lower for indicator in ['mix', 'eq', 'compress', 'audio', 'track'])
|
| 162 |
+
|
| 163 |
+
def _generate_daw_specific_response_ml(self, prompt: str, concepts: List[str], sentiment: Dict) -> str:
|
| 164 |
+
prompt_lower = prompt.lower()
|
| 165 |
+
if any(term in prompt_lower for term in ['gain', 'level', 'volume', 'loud']):
|
| 166 |
+
return self.daw_knowledge['mixing_principles']['gain_staging']
|
| 167 |
+
elif any(term in prompt_lower for term in ['eq', 'frequency', 'boost', 'cut']):
|
| 168 |
+
return self.daw_knowledge['mixing_principles']['eq_fundamentals']
|
| 169 |
+
elif any(term in prompt_lower for term in ['compress', 'ratio', 'attack', 'release']):
|
| 170 |
+
return self.daw_knowledge['mixing_principles']['compression_strategy']
|
| 171 |
+
elif any(term in prompt_lower for term in ['pan', 'stereo', 'width']):
|
| 172 |
+
return self.daw_knowledge['mixing_principles']['panning_technique']
|
| 173 |
+
elif any(term in prompt_lower for term in ['muddy', 'unclear', 'boomy']):
|
| 174 |
+
return self.daw_knowledge['problem_detection']['muddy_mix']
|
| 175 |
+
elif any(term in prompt_lower for term in ['harsh', 'bright', 'sibilant']):
|
| 176 |
+
return self.daw_knowledge['problem_detection']['harsh_highs']
|
| 177 |
+
elif any(term in prompt_lower for term in ['thin', 'weak bass', 'no low end']):
|
| 178 |
+
return self.daw_knowledge['problem_detection']['weak_low_end']
|
| 179 |
+
elif any(term in prompt_lower for term in ['flat', 'depth', 'dimension']):
|
| 180 |
+
return self.daw_knowledge['problem_detection']['lack_of_depth']
|
| 181 |
+
else:
|
| 182 |
+
if isinstance(sentiment, dict) and sentiment.get('compound', 0) < 0:
|
| 183 |
+
return "Identify the specific issue: frequency buildup, dynamic imbalance, or routing problem. Isolate and address systematically."
|
| 184 |
+
else:
|
| 185 |
+
return "Continue with gain staging, then EQ for balance, compression for control, and spatial effects for depth. Follow signal flow logically."
|
| 186 |
+
|
| 187 |
+
def _generate_neural_insight_ml(self, concepts: List[str], sentiment: Dict) -> str:
|
| 188 |
+
if not concepts:
|
| 189 |
+
return "Neural analysis suggests exploring the pattern relationships within this context."
|
| 190 |
+
primary_concept = concepts[0] if concepts else "concept"
|
| 191 |
+
sentiment_polarity = "positive" if (isinstance(sentiment, dict) and sentiment.get('compound', 0) > 0) else "neutral" if (isinstance(sentiment, dict) and sentiment.get('compound', 0) == 0) else "analytical"
|
| 192 |
+
return f"Pattern recognition analysis of '{primary_concept}' reveals {sentiment_polarity} associations across multiple domains. Neural networks suggest systematic exploration through interconnected relationships."
|
| 193 |
+
|
| 194 |
+
def _generate_logical_response_ml(self, concepts: List[str], sentiment: Dict) -> str:
|
| 195 |
+
if not concepts:
|
| 196 |
+
return "Logical analysis requires structured evaluation of cause-effect relationships."
|
| 197 |
+
primary_concept = concepts[0]
|
| 198 |
+
return f"Structured analysis shows that '{primary_concept}' follows deterministic principles. Cause-effect mapping suggests systematic approach yields optimal outcomes."
|
| 199 |
+
|
| 200 |
+
def _generate_creative_response_ml(self, concepts: List[str], sentiment: Dict) -> str:
|
| 201 |
+
if not concepts:
|
| 202 |
+
return "Creative synthesis reveals novel connections emerging from conceptual intersections."
|
| 203 |
+
primary_concept = concepts[0]
|
| 204 |
+
return f"Creative synthesis transforms '{primary_concept}' through multi-dimensional perspective shifts. Emergent patterns suggest innovative approaches through systematic exploration."
|
| 205 |
+
|
| 206 |
+
def _generate_technical_insight_ml(self, concepts: List[str], sentiment: Dict) -> str:
|
| 207 |
+
if not concepts:
|
| 208 |
+
return "Technical analysis requires precise parameter identification and systematic adjustment."
|
| 209 |
+
primary_concept = concepts[0]
|
| 210 |
+
return f"Technical analysis of '{primary_concept}' indicates specific parameter optimization opportunities. Systematic calibration yields measurable improvements."
|
| 211 |
+
|
| 212 |
+
def analyze_sentiment(self, text: str) -> Dict[str, float]:
|
| 213 |
+
score = self.analyzer.polarity_scores(text)
|
| 214 |
+
try:
|
| 215 |
+
self.audit_log(f"Sentiment analysis: {score}")
|
| 216 |
+
except Exception:
|
| 217 |
+
logger.debug("audit_log unavailable during sentiment analysis")
|
| 218 |
+
return score
|
| 219 |
+
|
| 220 |
+
def extract_key_concepts(self, text: str) -> List[str]:
|
| 221 |
+
try:
|
| 222 |
+
tokens = word_tokenize(text.lower())
|
| 223 |
+
concepts = [token for token in tokens if len(token) > 2 and token.isalpha()]
|
| 224 |
+
return list(dict.fromkeys(concepts))[:5]
|
| 225 |
+
except Exception as e:
|
| 226 |
+
logger.warning(f"Could not extract concepts: {e}")
|
| 227 |
+
return [w for w in text.lower().split() if len(w) > 2][:5]
|
| 228 |
+
|
| 229 |
+
def audit_log(self, message: str, system: bool = False) -> None:
|
| 230 |
+
source = "SYSTEM" if system else self.user_name
|
| 231 |
+
logger.info(f"{source}: {message}")
|
| 232 |
+
|
| 233 |
+
def _initialize_supabase(self):
|
| 234 |
+
try:
|
| 235 |
+
from supabase import create_client, Client
|
| 236 |
+
supabase_url = (
|
| 237 |
+
os.environ.get('VITE_SUPABASE_URL') or
|
| 238 |
+
os.environ.get('SUPABASE_URL') or
|
| 239 |
+
os.environ.get('NEXT_PUBLIC_SUPABASE_URL')
|
| 240 |
+
)
|
| 241 |
+
supabase_key = (
|
| 242 |
+
os.environ.get('VITE_SUPABASE_ANON_KEY') or
|
| 243 |
+
os.environ.get('SUPABASE_KEY') or
|
| 244 |
+
os.environ.get('SUPABASE_SERVICE_ROLE_KEY') or
|
| 245 |
+
os.environ.get('NEXT_PUBLIC_SUPABASE_ANON_KEY')
|
| 246 |
+
)
|
| 247 |
+
if supabase_url and supabase_key:
|
| 248 |
+
client = create_client(supabase_url, supabase_key)
|
| 249 |
+
logger.info("✅ Supabase client initialized")
|
| 250 |
+
return client
|
| 251 |
+
else:
|
| 252 |
+
logger.warning("⚠️ Supabase credentials not found in environment")
|
| 253 |
+
return None
|
| 254 |
+
except Exception as e:
|
| 255 |
+
logger.warning(f"⚠️ Could not initialize Supabase: {e}")
|
| 256 |
+
return None
|
| 257 |
+
|
| 258 |
+
def save_conversation_to_db(self, user_message: str, codette_response: str) -> None:
|
| 259 |
+
if not self.supabase_client:
|
| 260 |
+
return
|
| 261 |
+
try:
|
| 262 |
+
data = {
|
| 263 |
+
"user_message": user_message,
|
| 264 |
+
"codette_response": codette_response,
|
| 265 |
+
"timestamp": datetime.now().isoformat(),
|
| 266 |
+
"user_name": self.user_name
|
| 267 |
+
}
|
| 268 |
+
self.supabase_client.table('chat_history').insert(data).execute()
|
| 269 |
+
logger.debug("Conversation saved to Supabase")
|
| 270 |
+
except Exception as e:
|
| 271 |
+
logger.debug(f"Could not save conversation: {e}")
|
| 272 |
+
|
| 273 |
+
async def generate_response(self, query: str, user_id: int = 0, daw_context: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
| 274 |
+
try:
|
| 275 |
+
response_text = self.respond(query)
|
| 276 |
+
sentiment = self.analyze_sentiment(query)
|
| 277 |
+
result = {
|
| 278 |
+
"response": response_text,
|
| 279 |
+
"sentiment": sentiment,
|
| 280 |
+
"confidence": 0.85,
|
| 281 |
+
"timestamp": datetime.now().isoformat(),
|
| 282 |
+
"source": "codette_new",
|
| 283 |
+
"ml_enhanced": True,
|
| 284 |
+
"security_filtered": True,
|
| 285 |
+
"health_status": "healthy"
|
| 286 |
+
}
|
| 287 |
+
if daw_context:
|
| 288 |
+
result["daw_context"] = daw_context
|
| 289 |
+
return result
|
| 290 |
+
except Exception as e:
|
| 291 |
+
logger.error(f"Response generation failed: {e}")
|
| 292 |
+
return {
|
| 293 |
+
"error": str(e),
|
| 294 |
+
"response": "I encountered an issue. Could you rephrase your question?",
|
| 295 |
+
"fallback": True,
|
| 296 |
+
"timestamp": datetime.now().isoformat()
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
def generate_mixing_suggestions(self, track_type: str, track_info: dict) -> List[str]:
|
| 300 |
+
suggestions = []
|
| 301 |
+
peak_level = track_info.get('peak_level', 0)
|
| 302 |
+
if peak_level > -3:
|
| 303 |
+
suggestions.append("Reduce level to prevent clipping (aim for -6dB peak)")
|
| 304 |
+
elif peak_level < -20:
|
| 305 |
+
suggestions.append("Increase level - track is very quiet (aim for -12dB to -6dB)")
|
| 306 |
+
if track_type == 'audio':
|
| 307 |
+
suggestions.append("Apply high-pass filter at 80-100Hz to remove rumble")
|
| 308 |
+
suggestions.append("Check for phase issues if recording in stereo")
|
| 309 |
+
suggestions.append("Use compression to control dynamics (4:1 ratio, 10ms attack)")
|
| 310 |
+
elif track_type == 'instrument':
|
| 311 |
+
suggestions.append("Add gentle compression for consistency (3:1 ratio)")
|
| 312 |
+
suggestions.append("EQ to fit in frequency spectrum - boost presence around 3-5kHz")
|
| 313 |
+
suggestions.append("Consider reverb send for spatial depth")
|
| 314 |
+
elif track_type == 'midi':
|
| 315 |
+
suggestions.append("Adjust velocity curves for natural dynamics")
|
| 316 |
+
suggestions.append("Layer with EQ and compression for polish")
|
| 317 |
+
if track_info.get('muted'):
|
| 318 |
+
suggestions.append("⚠️ Track is muted - unmute to hear in mix")
|
| 319 |
+
if track_info.get('soloed'):
|
| 320 |
+
suggestions.append("ℹ️ Track is soloed - unsolo to hear full mix context")
|
| 321 |
+
return suggestions[:4]
|
| 322 |
+
|
| 323 |
+
def analyze_daw_context(self, daw_context: dict) -> Dict[str, Any]:
|
| 324 |
+
tracks = daw_context.get('tracks', []) if isinstance(daw_context, dict) else []
|
| 325 |
+
analysis = {
|
| 326 |
+
'track_count': len(tracks),
|
| 327 |
+
'recommendations': [],
|
| 328 |
+
'potential_issues': [],
|
| 329 |
+
'session_health': 'good'
|
| 330 |
+
}
|
| 331 |
+
if analysis['track_count'] > 64:
|
| 332 |
+
analysis['potential_issues'].append("High track count (>64) may impact CPU performance")
|
| 333 |
+
analysis['session_health'] = 'warning'
|
| 334 |
+
if analysis['track_count'] > 100:
|
| 335 |
+
analysis['potential_issues'].append("Very high track count (>100) - consider bouncing to audio")
|
| 336 |
+
analysis['session_health'] = 'critical'
|
| 337 |
+
muted_count = len([t for t in tracks if t.get('muted', False)])
|
| 338 |
+
if muted_count > len(tracks) * 0.3 and len(tracks) > 0:
|
| 339 |
+
analysis['potential_issues'].append(f"{muted_count} muted tracks - consider archiving unused content")
|
| 340 |
+
analysis['recommendations'].append("Use color coding for track organization")
|
| 341 |
+
analysis['recommendations'].append("Create buses for grouped processing (drums, vocals, etc)")
|
| 342 |
+
analysis['recommendations'].append("Leave 6dB headroom on master for mastering")
|
| 343 |
+
bpm = daw_context.get('bpm', 120) if isinstance(daw_context, dict) else 120
|
| 344 |
+
if bpm:
|
| 345 |
+
analysis['recommendations'].append(f"Current BPM: {bpm} - sync delay times to tempo for musical results")
|
| 346 |
+
return analysis
|
| 347 |
+
|
| 348 |
+
def get_personality_prefix(self) -> str:
|
| 349 |
+
prefixes = {
|
| 350 |
+
'technical_expert': '[Technical Expert]',
|
| 351 |
+
'creative_mentor': '[Creative Mentor]',
|
| 352 |
+
'practical_guide': '[Practical Guide]',
|
| 353 |
+
'analytical_teacher': '[Analytical Teacher]',
|
| 354 |
+
'innovative_explorer': '[Innovation Explorer]'
|
| 355 |
+
}
|
| 356 |
+
return prefixes.get(self.current_personality, '[Expert]')
|
| 357 |
+
|