modify this to use direct google search in browser instead of pasting into browser and then clicking search : import sys
import tkinter as tk
from tkinter import messagebox
from PIL import Image
import mss
import pytesseract
import pyperclip
import keyboard
import threading
import webbrowser
import pyautogui
import time

# Optional: If Tesseract is not in your PATH, uncomment and set the path manually
# pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

def select_region():
    """
    Allows the user to select a region on the screen by dragging the mouse.
    Returns the coordinates of the selected region.
    """
    region = {}

    def on_button_press(event):
        region['start_x'] = root.winfo_pointerx()
        region['start_y'] = root.winfo_pointery()
        canvas.create_rectangle(event.x, event.y, event.x, event.y, outline='red', width=2, tags='rect')

    def on_move_press(event):
        end_x = root.winfo_pointerx()
        end_y = root.winfo_pointery()
        canvas.coords('rect', region['start_x'] - root.winfo_rootx(), region['start_y'] - root.winfo_rooty(),
                      event.x, event.y)

    def on_button_release(event):
        region['end_x'] = root.winfo_pointerx()
        region['end_y'] = root.winfo_pointery()
        root.quit()

    root = tk.Tk()
    root.attributes('-alpha', 0.3)  # Semi-transparent
    root.attributes("-topmost", True)  # Stay on top
    root.overrideredirect(True)  # No window decorations

    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    root.geometry(f"{screen_width}x{screen_height}")

    canvas = tk.Canvas(root, cursor="cross", bg="grey")
    canvas.pack(fill=tk.BOTH, expand=True)

    canvas.bind("<ButtonPress-1>", on_button_press)
    canvas.bind("<B1-Motion>", on_move_press)
    canvas.bind("<ButtonRelease-1>", on_button_release)

    try:
        root.mainloop()
    except KeyboardInterrupt:
        sys.exit()

    # Calculate selected region
    left = min(region['start_x'], region.get('end_x', region['start_x'])) 
    top = min(region['start_y'], region.get('end_y', region['start_y'])) 
    right = max(region['start_x'], region.get('end_x', region['start_x'])) 
    bottom = max(region['start_y'], region.get('end_y', region['start_y'])) 

    root.destroy()
    return (left, top, right, bottom)

def capture_screenshot(region):
    """
    Captures a screenshot of the specified region.
    :param region: Tuple of (left, top, right, bottom)
    :return: PIL Image of the captured region
    """
    left, top, right, bottom = region
    width = right - left
    height = bottom - top

    if width <= 0 or height <= 0:
        messagebox.showerror("Error", "Invalid region selected. Please try again.")
        return None

    with mss.mss() as sct:
        monitor = {"top": top, "left": left, "width": width, "height": height}
        try:
            sct_img = sct.grab(monitor)
            img = Image.frombytes("RGB", sct_img.size, sct_img.rgb)
            return img
        except Exception as e:
            messagebox.showerror("Error", f"Failed to capture the screen: {e}")
            return None

def perform_ocr(image):
    """
    Performs OCR on the given image and returns the extracted text.
    :param image: PIL Image
    :return: Extracted text as string
    """
    try:
        text = pytesseract.image_to_string(image, lang='eng')
        if not text.strip():
            messagebox.showwarning("No Text Detected", "No text was detected in the selected region.")
        return text
    except pytesseract.TesseractNotFoundError:
        messagebox.showerror("Tesseract Not Found", "Tesseract OCR is not installed or not found in PATH.")
        return ""
    except Exception as e:
        messagebox.showerror("OCR Error", f"An error occurred during OCR: {e}")
        return ""

def copy_to_clipboard(text):
    """
    Copies the given text to the clipboard.
    :param text: Text to copy
    """
    try:
        pyperclip.copy(text)
        # Pop-up removed: Text copied to clipboard
    except Exception as e:
        messagebox.showerror("Clipboard Error", f"Failed to copy text to clipboard: {e}")

def automate_search(text):
    """
    Automates opening the browser, pasting the text into the search bar, and initiating a search.
    :param text: Text to search for
    """
    try:
        # Open the default web browser with the search engine (e.g., Google)
        search_engine_url = "https://www.google.com"
        webbrowser.open(search_engine_url)

        # Allow time for the browser to open and load the page
        time.sleep(5)  # Adjust sleep time based on your internet speed and system performance

        # Focus on the address bar (Ctrl + L) to ensure the page is ready
        pyautogui.hotkey('ctrl', 'l')
        time.sleep(1)

        # Simulate Ctrl + V to paste the text
        pyautogui.hotkey('ctrl', 'v')
        time.sleep(1)

        # Press Enter to initiate the search
        pyautogui.press('enter')

        # Pop-up removed: Search initiated
    except Exception as e:
        messagebox.showerror("Automation Error", f"An error occurred during browser automation: {e}")

def ocr_process():
    """
    Complete OCR process: select region, capture, perform OCR, copy to clipboard, and automate search.
    Runs in a separate thread to avoid blocking the hotkey listener.
    """
    region = select_region()
    if region == (0, 0, 0, 0):
        messagebox.showwarning("No Selection", "No region was selected.")
        return
    image = capture_screenshot(region)
    if image:
        text = perform_ocr(image)
        if text.strip():
            copy_to_clipboard(text)
            automate_search(text)

def start_listener():
    """
    Starts the hotkey listener.
    """
    messagebox.showinfo("OCR Tool", "OCR Tool is now running.\n\n"
                                    "Press Ctrl+Alt+C to capture text.\n"
                                    "Press Esc to exit.")
    # Define hotkeys
    keyboard.add_hotkey('ctrl+Alt+c', lambda: threading.Thread(target=ocr_process, daemon=True).start())
    keyboard.wait('esc')
    messagebox.showinfo("OCR Tool", "Exiting OCR Tool.")
    sys.exit()

def main():
    # Optional: Specify Tesseract executable path if not in PATH
    # pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

    # Start the hotkey listener
    listener_thread = threading.Thread(target=start_listener, daemon=True)
    listener_thread.start()

    # Keep the main thread alive to listen for hotkeys
    listener_thread.join()

if __name__ == "__main__":
    main()