improve this code using all the compute resources you can and write the complete improved version with new features.Thank you Orion import os
import time
import pyautogui
import google.generativeai as genai
import cv2
import numpy as np
from ultralytics import YOLO
import logging
import threading
import random
import string
from dotenv import load_dotenv
from abc import ABC, abstractmethod
from typing import Dict, List, Any, Callable
import json
from concurrent.futures import ThreadPoolExecutor
from PIL import Image
import io
import re

# Load environment variables
load_dotenv()

# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# Google API key setup
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
if not GOOGLE_API_KEY:
    logger.error("GOOGLE_API_KEY environment variable is not set. Exiting.")
    exit(1)

# Configure the Generative AI model
genai.configure(api_key=GOOGLE_API_KEY)

# Initialize Gemini model
model = genai.GenerativeModel('gemini-1.5-flash')

ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg"}

def allowed_file(filename: str) -> bool:
    """Check if the filename has an allowed extension."""
    _, ext = os.path.splitext(filename)
    return ext.lstrip('.').lower() in ALLOWED_EXTENSIONS

class Agent(ABC):
    """Abstract base class for all agents."""
    def __init__(self, name: str, role: str, system_prompt: str):
        self.name = name
        self.role = role
        self.system_prompt = system_prompt
        self.chat = model.start_chat(history=[])
        self.knowledge_base: Dict[str, Any] = {}

    def send_message(self, message: str, image: Image.Image = None) -> str:
        logger.info(f"{self.name}: Sending message to Gemini: {message}")
        try:
            if image:
                response = self.chat.send_message([message, image])
            else:
                response = self.chat.send_message(message)
            logger.info(f"{self.name}: Received response from Gemini: {response.text}")
            return response.text
        except Exception as e:
            logger.error(f"{self.name}: Error sending message to Gemini: {e}")
            return f"Error: {str(e)}"


    @abstractmethod
    def think(self) -> None:
        """Abstract method for agent's thinking process."""
        pass

    def update_knowledge(self, key: str, value: Any) -> None:
        """Update the agent's knowledge base."""
        self.knowledge_base[key] = value

    def get_knowledge(self, key: str) -> Any:
        """Retrieve information from the knowledge base."""
        return self.knowledge_base.get(key)

    def share_knowledge(self, other_agent: 'Agent') -> None:
        """Share knowledge with another agent."""
        other_agent.knowledge_base.update(self.knowledge_base)

class GeneralActionExecutor:
    """Executes mouse and keyboard actions based on commands."""
    def __init__(self):
        self.action_map: Dict[str, Callable[..., None]] = {
            "click": self.click,
            "double_click": self.double_click,
            "right_click": self.right_click,
            "move": self.move,
            "type": self.type_keys,
            "scroll": self.scroll,
            # Add more actions as needed
        }

    def execute(self, action: str, **kwargs) -> str:
        """Execute a given action with provided keyword arguments."""
        logger.info(f"Executing action: {action} with args: {kwargs}")
        action_func = self.action_map.get(action.lower())
        if not action_func:
            logger.error(f"Action '{action}' is not supported.")
            return f"Action '{action}' is not supported."
        try:
            action_func(**kwargs)
            return f"Action '{action}' executed successfully."
        except Exception as e:
            logger.error(f"Error executing action '{action}': {e}")
            return f"Error executing action '{action}': {e}"

    def click(self, x: int = None, y: int = None, button: str = 'left') -> None:
        """Performs a mouse click."""
        pyautogui.click(x=x, y=y, button=button)

    def double_click(self, x: int = None, y: int = None, button: str = 'left') -> None:
        """Performs a mouse double-click."""
        pyautogui.doubleClick(x=x, y=y, button=button)

    def right_click(self, x: int = None, y: int = None) -> None:
        """Performs a right mouse click."""
        pyautogui.rightClick(x=x, y=y)

    def move(self, x: int, y: int, duration: float = 0.5) -> None:
        """Moves the mouse to a specific position."""
        pyautogui.moveTo(x, y, duration=duration)

    def type_keys(self, text: str, interval: float = 0.05) -> None:
        """Types the given text using the keyboard."""
        pyautogui.write(text, interval=interval)

    def scroll(self, clicks: int) -> None:
        """Scrolls the mouse."""
        pyautogui.scroll(clicks)

class MasterAgent(Agent):
    """Master agent that manages tasks, takes screenshots, and executes actions."""
    def __init__(self):
        super().__init__(
            name="Master",
            role="Control, delegate, and execute actions",
            system_prompt="You are the master agent. Your role is to analyze tasks, execute actions, and manage operations."
        )
        self.action_executor = GeneralActionExecutor()
        self.screenshot_thread: threading.Thread = None
        self.screenshot_counter: int = 0
        self.task_queue: List[str] = []
        self.executor = ThreadPoolExecutor(max_workers=5)
        self.screenshot_interval: int = 60  # Screenshot interval in seconds
        self.yolo_models: Dict[str, YOLO] = {}
        self.running = True

    def delegate_task(self, task_description: str) -> str:
        """Delegate a task based on its description."""
        logger.info(f"{self.name}: Received task: {task_description}")
        self.task_queue.append(task_description)
        return "Task added to queue for processing."

    def think(self) -> None:
        """Process the task queue and execute tasks."""
        logger.info(f"{self.name}: Thinking...")
        self.process_task_queue()
        # Potentially add more thinking processes here

    def process_task_queue(self) -> None:
        """Process tasks in the queue using a thread pool."""
        logger.info(f"{self.name}: Processing task queue. Current queue size: {len(self.task_queue)}")
        while self.task_queue:
            task = self.task_queue.pop(0)
            logger.info(f"{self.name}: Processing task: {task}")
            self.executor.submit(self.process_task, task)

    def process_task(self, task: str) -> None:
        """Process an individual task."""
        logger.info(f"{self.name}: Starting task processing: {task}")
        if task.startswith("action:"):
            action_command = task[len("action:"):].strip()
            response = self.execute_action_command(action_command)
            logger.info(f"{self.name}: Action response: {response}")
        elif task.startswith("screenshot_analysis:"):
            analysis = task[len("screenshot_analysis:"):].strip()
            self.handle_screenshot_analysis(analysis)
        else:
            response = self.send_message(f"Analyze this task and suggest actions: {task}")
            logger.info(f"{self.name}: Task analysis: {response}")
            self.parse_and_enqueue_actions(response)

    def execute_action_command(self, command: str) -> str:
        """Parse and execute an action command."""
        try:
            if ':' not in command:
                return "Invalid action command format."
            action_type, params = command.split(':', 1)
            param_dict = dict(re.findall(r'(\w+)=([\w\.]+)', params))

            # Convert parameter values to appropriate types
            for key, value in param_dict.items():
                if value.isdigit():
                    param_dict[key] = int(value)
                else:
                    try:
                        param_dict[key] = float(value)
                    except ValueError:
                        pass  # Keep as string
            logger.info(f"{self.name}: Executing action '{action_type}' with params {param_dict}")
            return self.action_executor.execute(action_type, **param_dict)
        except Exception as e:
            logger.error(f"{self.name}: Error parsing action command '{command}': {e}")
            return f"Error parsing action command: {e}"

    def parse_and_enqueue_actions(self, analysis: str) -> None:
        """Parse the analysis from the model and enqueue actionable tasks."""
        lines = analysis.split('\n')
        for line in lines:
            if line.lower().startswith("execute action:"):
                action_command = line[len("execute action:"):].strip()
                self.task_queue.append(f"action:{action_command}")

    def handle_screenshot_analysis(self, analysis: str) -> None:
        """Handle the results of a screenshot analysis."""
        logger.info(f"{self.name}: Handling screenshot analysis: {analysis}")
        self.task_queue.append(f"screenshot_analysis:{analysis}")

    def start_screenshot_thread(self) -> None:
        """Start a background thread to take periodic screenshots."""
        logger.info(f"{self.name}: Starting screenshot thread")
        self.screenshot_thread = threading.Thread(target=self.take_screenshots, daemon=True)
        self.screenshot_thread.start()

    def take_screenshots(self) -> None:
        """Continuously take screenshots at specified intervals."""
        logger.info(f"{self.name}: Screenshot thread started")
        while self.running:
            try:
                logger.info(f"{self.name}: Taking screenshot")
                screenshot = pyautogui.screenshot()
                filename = f"screenshot_{self.screenshot_counter}.png"
                screenshot.save(filename)
                self.screenshot_counter += 1
                logger.info(f"{self.name}: Screenshot saved as {filename}")
                self.analyze_screenshot(filename)
                time.sleep(self.screenshot_interval)
            except Exception as e:
                logger.error(f"{self.name}: Error taking screenshot: {e}")
                time.sleep(5)

    def analyze_screenshot(self, image_path: str) -> None:
        """Analyze a screenshot using Gemini and enqueue analysis results."""
        logger.info(f"{self.name}: Analyzing screenshot: {image_path}")
        try:
            with Image.open(image_path) as img:
                analysis = self.send_message("Analyze this screenshot and describe its contents:", img)
            logger.info(f"{self.name}: Screenshot analysis: {analysis}")
            self.update_knowledge(f"screenshot_analysis_{image_path}", analysis)
            self.task_queue.append(f"screenshot_analysis:{analysis}")
        except Exception as e:
            logger.error(f"{self.name}: Error analyzing screenshot: {e}")
            self.task_queue.append(f"Handle failed screenshot analysis: {image_path}")

    def stop(self) -> None:
        """Stop the agent's operations gracefully."""
        logger.info(f"{self.name}: Stopping agent.")
        self.running = False
        if self.screenshot_thread and self.screenshot_thread.is_alive():
            self.screenshot_thread.join(timeout=5)
        self.executor.shutdown(wait=True)
        logger.info(f"{self.name}: Agent stopped.")

class AgentCoordinator:
    """Coordinator that manages one or multiple MasterAgents."""
    def __init__(self):
        self.master_agents: List[MasterAgent] = [MasterAgent()]
        self.executor = ThreadPoolExecutor(max_workers=5)

    def run(self) -> None:
        """Run the coordinator to manage agents."""
        try:
            for master in self.master_agents:
                master.start_screenshot_thread()

            while True:
                for master in self.master_agents:
                    master.think()
                time.sleep(10)  # Adjust the sleep duration as needed
        except KeyboardInterrupt:
            logger.info("Coordinator received KeyboardInterrupt. Shutting down.")
        except Exception as e:
            logger.error(f"Coordinator encountered an error: {e}")
        finally:
            self.cleanup()

    def cleanup(self) -> None:
        """Clean up all master agents."""
        for master in self.master_agents:
            master.stop()
        self.executor.shutdown(wait=True)
        logger.info("Coordinator cleanup completed.")

def main() -> None:
    """Main entry point for the agent system."""
    coordinator = AgentCoordinator()
    coordinator.run()

if __name__ == "__main__":
    main()