optimize the script below:

import cv2
import numpy as np
import pyautogui
import pytesseract
import time
from PIL import Image

import pydirectinput

from random import randint,uniform

# Configuration (adjust these values)
BASE_ROI = (860, 440, 200, 200)    # Base region of interest (centered on 1920x1080 screen)
COLOR_TARGET = (222, 172, 88)      # Target color in BGR format
COLOR_TOLERANCE = 20               # Tolerance for color matching
SCREENSHOT_INTERVAL = 0.01         # Time between screenshots in seconds
MONITOR_DURATION = 20              # Duration to monitor detected region in seconds
MASK_CHANGE_THRESHOLD = 0.15       # Threshold for masked area change (15% change)
MIN_MASK_AREA = 50                # Minimum mask area to consider (in pixels)
DIGIT_ROI = (942, 515, 35, 45)  # Larger region for digit detection (center of screen)

# Configure pytesseract path if needed
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'  # Uncomment and modify if needed


def press(key,duration_lower,duration_upper):

	pydirectinput.keyDown(key)
	time.sleep(uniform(duration_lower,duration_upper))
	pydirectinput.keyUp(key)
	return 0

def capture_screen():
    """Capture the entire screen and convert to OpenCV format"""
    screenshot = pyautogui.screenshot()
    return cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)

def get_base_roi():
    """Get the base region of interest"""
    return BASE_ROI

def find_color_region(image, target_color, tolerance):
    """Find regions in the image that match the target color within tolerance"""
    hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    lower_bound = np.array([max(0, c-tolerance) for c in cv2.cvtColor(np.uint8([[target_color]]), cv2.COLOR_BGR2HSV)[0][0]])
    upper_bound = np.array([min(255, c+tolerance) for c in cv2.cvtColor(np.uint8([[target_color]]), cv2.COLOR_BGR2HSV)[0][0]])
    
    mask = cv2.inRange(hsv_image, lower_bound, upper_bound)
    return mask

def get_largest_contour(mask):
    """Find the largest contour in the mask"""
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if not contours:
        return None
    
    largest_contour = max(contours, key=cv2.contourArea)
    return largest_contour

def calculate_mask_area(mask):
    """Calculate the total area of significant masked regions"""
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    total_area = 0
    for contour in contours:
        area = cv2.contourArea(contour)
        if area > MIN_MASK_AREA:
            total_area += area
    
    return total_area

def detect_digit():
    """Detect digit in the center region of the screen"""
    # Capture the digit region
    digit_screenshot = pyautogui.screenshot(region=DIGIT_ROI)
    #digit_screenshot = Image.open("1750271613-digit_region-nodigit.png")

    digit_screenshot_BGR = cv2.cvtColor(np.array(digit_screenshot), cv2.COLOR_RGB2BGR)
    
    # OCR configuration for single digit
    custom_config = r'--oem 3 --psm 10 -c tessedit_char_whitelist=12345'

    border = preprocess_white_digit_with_steps(digit_screenshot_BGR)

    # Perform OCR
    digit = pytesseract.image_to_string(border, config=custom_config).strip()

    #cv2.imwrite(f"{int(time.time())}-digit_region_thresh-{digit}.png", border)

    return digit if digit.isdigit() else None

def preprocess_white_digit_with_steps(image, output_dir='debug_steps'):
    import os
    # Create output directory if it doesn't exist
    os.makedirs(output_dir, exist_ok=True)
    
    # Convert to grayscale if needed
    if len(image.shape) == 3:
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    else:
        gray = image
    #cv2.imwrite(f'{output_dir}/1_grayscale.png', gray)

    # Threshold with Otsu's method
    _, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    #cv2.imwrite(f'{output_dir}/4_threshold.png', thresh)
    
    # Invert for Tesseract
    inverted = cv2.bitwise_not(thresh)
    #cv2.imwrite(f'{output_dir}/5_inverted.png', inverted)

    # Resize
    height = 28
    aspect = inverted.shape[1] / inverted.shape[0]
    dim = (int(height * aspect), height)
    resized = cv2.resize(inverted, dim, interpolation=cv2.INTER_AREA)
    #cv2.imwrite(f'{output_dir}/6_resized.png', resized)

    # Optional: Clean up noise
    kernel = np.ones((2,2), np.uint8)
    cleaned = cv2.morphologyEx(resized, cv2.MORPH_CLOSE, kernel)
    #cv2.imwrite(f'{output_dir}/7_cleaned.png', cleaned)

    # Add white border
    border = cv2.copyMakeBorder(
        cleaned,
        5, 5, 5, 5,
        cv2.BORDER_CONSTANT,
        value=[255]
    )
    #cv2.imwrite(f'{output_dir}/8_final.png', border)

    return border

def input_detected_digit(digit):
    """Input the detected digit using pyautogui"""
    if digit is not None:
        print(f"Inputting detected digit: {digit}")
        pyautogui.write(digit)
        time.sleep(0.1)  # Small delay after input

def monitor_color_region():
    """Monitor the color region over time"""
    print("Starting color monitoring...")
    base_roi = get_base_roi()
    print(f"Base ROI: {base_roi}")
    last_region = None
    next_moniter = False
    last_monitor_str = None
    next_moniter = None

    while True:

        print("Searching...")
        #screen = capture_screen()

        
       
        x, y, w, h = base_roi
        
        screen = pyautogui.screenshot(region=(base_roi))
        roi = cv2.cvtColor(np.array(screen), cv2.COLOR_RGB2BGR)


        # Process only the ROI
        mask = find_color_region(roi, COLOR_TARGET, COLOR_TOLERANCE)
        contour = get_largest_contour(mask)

        if contour is not None:
            rx, ry, rw, rh = cv2.boundingRect(contour)
            region_size = rw * rh

            if region_size < 15:
                print(f"Skipping small color region: {rw}x{rh} pixels")
                continue

            region = (rx + x, ry + y, rw, rh)

            if last_region is None or \
               abs(region[0] - last_region[0]) > 10 or \
               abs(region[1] - last_region[1]) > 10:

                print(f"Color region detected at: {region} (size: {rw}x{rh})")
                
                
                new_monitor_str = f"Monitoring region {region} for {MONITOR_DURATION} seconds..."
                if last_monitor_str != new_monitor_str:
                    print(new_monitor_str)
                last_monitor_str = new_monitor_str
                start_time = time.time()
                timestamp_start = int(time.time())
                
                # Capture and save initial frame
                initial_frame = pyautogui.screenshot(region=region)
                initial_frame = cv2.cvtColor(np.array(initial_frame), cv2.COLOR_RGB2BGR)
                #cv2.imwrite(f"{timestamp_start}-initial_region.png", initial_frame)
                
                initial_mask = find_color_region(initial_frame, COLOR_TARGET, COLOR_TOLERANCE)
                initial_mask_area = calculate_mask_area(initial_mask)
                
                print(f"Initial mask area: {initial_mask_area:.2f} pixels")

                # Capture and save the digit region
                digit_frame = pyautogui.screenshot(region=DIGIT_ROI)
                digit_frame = cv2.cvtColor(np.array(digit_frame), cv2.COLOR_RGB2BGR)
                
                # Attempt to detect and input digit
                print("Attempting to detect digit...")
                fails = 0
                while fails != 10:

                    digit = detect_digit()
                    if digit:
                        print(f"Detected digit: {digit}")
                        # input_detected_digit(digit)
                        #cv2.imwrite(f"{timestamp_start}-digit_region-{digit}.png", digit_frame)
                        break
                    else:
                        print("No digit detected")
                        #cv2.imwrite(f"{timestamp_start}-digit_region-nodigit.png", digit_frame)
                        fails += 1
                
                if digit == None: continue
                last_mask_area_str = None

                while time.time() - start_time < MONITOR_DURATION:
                    current_frame = pyautogui.screenshot(region=region)
                    current_frame = cv2.cvtColor(np.array(current_frame), cv2.COLOR_RGB2BGR)
                    
                    current_mask = find_color_region(current_frame, COLOR_TARGET, COLOR_TOLERANCE)
                    current_mask_area = calculate_mask_area(current_mask)
                    
                    if initial_mask_area > 0:
                        area_change = abs(current_mask_area - initial_mask_area) / initial_mask_area
                    else:
                        area_change = 1.0 if current_mask_area > 0 else 0.0
                    
                    mask_area_str = f"Current mask area: {current_mask_area:.2f}, Relative change: {area_change:.2%}"
                    if last_mask_area_str != mask_area_str:
                        print(mask_area_str)
                    last_mask_area_str = mask_area_str


                    if area_change > MASK_CHANGE_THRESHOLD:
                        print(f"Significant mask area change detected! Change: {area_change:.2%}")
                        
                        # Save the current frame of the monitored region
                        #cv2.imwrite(f"{timestamp_start}-mask_change.png", current_frame)
                        #time.sleep(uniform(0.02, 0.078)) # random sleep
                        press(digit,0.05,0.10)
                        print(f"PRESSING {digit}")

                            
                        print('Disabling monitor as significant mask area change detected')
                        next_monitor = True
                        last_region = None
                        break

                    time.sleep(SCREENSHOT_INTERVAL)

                last_region = region
                if next_monitor == True:
                    next_monitor = False
                    last_region = None
                    continue

        else:
            last_region = None

        time.sleep(SCREENSHOT_INTERVAL)

if __name__ == "__main__":
    monitor_color_region()