flyingff2083/parallel_self
0
1/**2 * Emotion Detection Client3 * Integrates with your existing emotion.py (DeepFace + OpenCV)4 * 5 * This is a mock implementation. For real emotion data:6 * - Option 1: Modify your emotion.py to send data via HTTP POST7 * - Option 2: Create a WebSocket bridge between Python and JavaScript8 * - Option 3: Use a JavaScript-based emotion detection library9 */10 11class EmotionClient {12 constructor(sessionId) {13 this.sessionId = sessionId;14 this.isRunning = false;15 this.updateInterval = null;16 this.mockMode = true; // Set to false when real emotion API is available17 }18 19 start() {20 if (this.isRunning) return;21 22 log('Starting emotion detection...');23 this.isRunning = true;24 25 // Update emotion status indicator26 this.updateStatusIndicator('active');27 28 if (this.mockMode) {29 // Mock emotion data for testing30 this.startMockEmotionDetection();31 } else {32 // Real emotion detection would go here33 this.startRealEmotionDetection();34 }35 }36 37 stop() {38 if (!this.isRunning) return;39 40 log('Stopping emotion detection...');41 this.isRunning = false;42 43 if (this.updateInterval) {44 clearInterval(this.updateInterval);45 this.updateInterval = null;46 }47 48 this.updateStatusIndicator('inactive');49 }50 51 updateStatusIndicator(status) {52 const indicator = document.getElementById('emotion-status');53 const indicatorElement = indicator.parentElement;54 55 if (status === 'active') {56 indicator.textContent = 'Monitoring ✓';57 indicatorElement.classList.remove('inactive');58 indicatorElement.classList.add('active');59 } else {60 indicator.textContent = 'Not Connected';61 indicatorElement.classList.remove('active');62 indicatorElement.classList.add('inactive');63 }64 }65 66 startMockEmotionDetection() {67 // Generate mock emotion data for testing68 this.updateInterval = setInterval(() => {69 const emotionData = this.generateMockEmotion();70 this.sendEmotionData(emotionData);71 }, CONFIG.EMOTION_UPDATE_INTERVAL);72 }73 74 generateMockEmotion() {75 // Generate realistic-looking mock emotions76 const baseEmotion = Math.random();77 78 let emotions;79 if (baseEmotion < 0.6) {80 // Mostly neutral/happy81 emotions = {82 happy: 0.3 + Math.random() * 0.4,83 neutral: 0.3 + Math.random() * 0.3,84 sad: Math.random() * 0.1,85 angry: Math.random() * 0.1,86 fear: Math.random() * 0.187 };88 } else if (baseEmotion < 0.85) {89 // More stressed emotions90 emotions = {91 happy: Math.random() * 0.2,92 neutral: 0.2 + Math.random() * 0.3,93 sad: 0.1 + Math.random() * 0.3,94 angry: 0.1 + Math.random() * 0.2,95 fear: 0.1 + Math.random() * 0.296 };97 } else {98 // High stress (rare)99 emotions = {100 happy: Math.random() * 0.1,101 neutral: Math.random() * 0.2,102 sad: 0.2 + Math.random() * 0.3,103 angry: 0.2 + Math.random() * 0.3,104 fear: 0.2 + Math.random() * 0.3105 };106 }107 108 // Normalize to sum to 1109 const sum = Object.values(emotions).reduce((a, b) => a + b, 0);110 Object.keys(emotions).forEach(key => {111 emotions[key] /= sum;112 });113 114 return {115 timestamp: Date.now(),116 emotions117 };118 }119 120 async sendEmotionData(emotionData) {121 if (!this.isRunning) return;122 123 try {124 const response = await fetch(`${CONFIG.API_URL}/session/${this.sessionId}/emotion`, {125 method: 'POST',126 headers: {127 'Content-Type': 'application/json'128 },129 body: JSON.stringify(emotionData)130 });131 132 const result = await response.json();133 134 if (result.intervention) {135 log('Intervention triggered by emotion threshold');136 this.stop();137 138 // Notify main app139 if (window.protocolManager) {140 window.protocolManager.handleIntervention('Emotion threshold exceeded');141 }142 }143 144 } catch (err) {145 error('Failed to send emotion data:', err);146 }147 }148 149 /**150 * Integration with your existing emotion.py151 * 152 * To use real emotion detection:153 * 1. Modify your emotion.py to include:154 * 155 * import requests156 * import json157 * 158 * # In your detection loop:159 * emotion_data = {160 * 'timestamp': int(time.time() * 1000),161 * 'emotions': {162 * 'happy': result[0]['emotion']['happy'] / 100,163 * 'sad': result[0]['emotion']['sad'] / 100,164 * 'angry': result[0]['emotion']['angry'] / 100,165 * 'fear': result[0]['emotion']['fear'] / 100,166 * 'neutral': result[0]['emotion']['neutral'] / 100167 * }168 * }169 * 170 * # Send to backend171 * session_id = sys.argv[1] # Pass session ID as argument172 * requests.post(173 * f'http://localhost:3000/api/session/{session_id}/emotion',174 * json=emotion_data175 * )176 * 177 * 2. Start emotion.py with session ID:178 * python emotion.py <session_id>179 * 180 * 3. Set mockMode = false in this class181 */182 startRealEmotionDetection() {183 // This would integrate with your actual emotion detection184 // For now, show instructions185 console.info(`186To use real emotion detection:1871. Modify emotion.py to send data to: ${CONFIG.API_URL}/session/${this.sessionId}/emotion1882. Start emotion.py with: python emotion.py ${this.sessionId}1893. Set mockMode = false in emotion-client.js190 `);191 }192}193 194// Make available globally195window.EmotionClient = EmotionClient;196 