"""Random Emotion Service - Background service for random-influenced emotion updates""" import os import sys import time import logging import random import threading from collections import deque # Add parent directory to path for imports sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from config import MODEL_CONFIG class QuantumEmotionService: """Background service that generates random numbers and applies them to emotions""" def __init__(self, emotional_agent, config=None): self.config = config or MODEL_CONFIG or {} self.emotional_agent = emotional_agent self.running = False self.thread = None self.random_numbers = deque(maxlen=6) # Store last 6 numbers self.last_update_time = time.time() self.update_interval = 10.0 # Update emotions every 10 seconds self.generation_interval = 1.0 # Generate number once per second logging.info("[RandomEmotionService] Initialized - will generate random numbers once per second") def _generate_random_number(self): """Generate a single random number""" return random.random() def _apply_random_emotions(self): """Apply the collected 6 random numbers to influence emotion state""" if len(self.random_numbers) < 6: logging.debug(f"[RandomEmotionService] Not enough numbers yet ({len(self.random_numbers)}/6)") return # Convert deque to list numbers = list(self.random_numbers) # Map 6 numbers to 5 emotions + overall variation # numbers[0] -> joy # numbers[1] -> sadness # numbers[2] -> anger # numbers[3] -> fear # numbers[4] -> curiosity # numbers[5] -> overall variation factor emotions = ["joy", "sadness", "anger", "fear", "curiosity"] current_state = self.emotional_agent.get_state() # Apply random influence (subtle changes, -0.05 to +0.05 range) for i, emotion in enumerate(emotions): if i < len(numbers) and numbers[i] is not None: # Convert 0-1 to -0.05 to +0.05 influence influence = (numbers[i] - 0.5) * 0.1 # Scale to ±0.05 # Apply with overall variation factor if len(numbers) > 5 and numbers[5] is not None: variation = (numbers[5] - 0.5) * 0.02 # Additional ±0.01 variation influence += variation # Update emotion new_value = current_state[emotion] + influence current_state[emotion] = max(0.05, min(1.0, new_value)) # Soft normalization to keep emotions balanced (only if they get too extreme) total = sum(current_state.values()) if total > 1.5 or total < 0.5: # Only normalize if emotions are way out of balance for emotion in emotions: current_state[emotion] = current_state[emotion] / total if total > 0 else 0.2 else: # Just ensure no emotion goes below minimum threshold for emotion in emotions: if current_state[emotion] < 0.05: current_state[emotion] = 0.05 # Update the emotional agent's state self.emotional_agent.emotional_state = current_state # Save to JSON after random update self.emotional_agent._save_to_json() logging.info(f"[RandomEmotionService] Applied random influence: {current_state}") def _service_loop(self): """Main service loop - generates random numbers once per second, updates emotions every 10 seconds""" logging.info("[RandomEmotionService] Service started") while self.running: try: # Generate random number (once per second) random_num = self._generate_random_number() self.random_numbers.append(random_num) logging.debug(f"[RandomEmotionService] Generated random number: {random_num:.4f}") # Check if it's time to update emotions (every 10 seconds) current_time = time.time() if current_time - self.last_update_time >= self.update_interval: if len(self.random_numbers) >= 6: self._apply_random_emotions() self.last_update_time = current_time logging.info(f"[RandomEmotionService] Updated emotions with {len(self.random_numbers)} random numbers") # Wait 1 second before next generation time.sleep(self.generation_interval) except Exception as e: logging.error(f"[RandomEmotionService] Error in service loop: {e}") time.sleep(self.generation_interval) # Wait before retrying def start(self): """Start the background service""" if self.running: logging.warning("[RandomEmotionService] Already running") return False self.running = True self.thread = threading.Thread(target=self._service_loop, daemon=True) self.thread.start() logging.info("[RandomEmotionService] Background service started") return True def stop(self): """Stop the background service""" if not self.running: return self.running = False if self.thread: self.thread.join(timeout=2.0) logging.info("[RandomEmotionService] Background service stopped") def is_running(self): """Check if service is running""" return self.running