import sys
import os
import time
import random
from pathlib import Path

try:
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException, NoSuchElementException
    import psutil
    import pyperclip
except ImportError as e:
    print("Run: pip install selenium psutil pyperclip")
    sys.exit(1)

def kill_chromedriver():
    try:
        for proc in psutil.process_iter(['name', 'pid']):
            if proc.info['name'] and proc.info['name'].lower() in ['chromedriver.exe', 'chrome.exe']:
                try:
                    parent = psutil.Process(proc.info['pid'])
                    for child in parent.children(recursive=True):
                        child.kill()
                    parent.kill()
                except psutil.NoSuchProcess:
                    pass
        time.sleep(1)
    except:
        pass

def extract_text_with_google_lens(image_path, headless=False, timeout=30):
    if not os.path.exists(image_path):
        image_path = r'C:/img.jpg'
        if not os.path.exists(image_path):
            return "Error: Image file not found"

    options = webdriver.ChromeOptions()
    if headless:
        options.add_argument('--headless')
        options.add_argument('--disable-gpu')
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('--window-size=1920,1080')
    options.add_argument('--disable-logging')
    options.add_argument('--log-level=3')
    options.add_argument('--silent')
    options.add_experimental_option("excludeSwitches", ["enable-logging", "enable-automation"])

    driver = None
    try:
        driver = webdriver.Chrome(options=options)
        driver.get('https://www.google.com/?olud')
        time.sleep(random.uniform(1, 3))

        driver.execute_script("window.scrollTo(0, 200);")
        time.sleep(random.uniform(0.5, 1.5))
        driver.execute_script("window.scrollTo(0, 0);")
        time.sleep(random.uniform(0.5, 1.5))

        upload_button = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '//input[@type="file"]'))
        )
        time.sleep(random.uniform(0.5, 1.5))
        upload_button.send_keys(image_path)

        print("\n⚠️ Est-ce qu’un CAPTCHA est apparu ? (oui/non) :", end=" ")
        reponse = input().strip().lower()
        if reponse == "oui":
            print("⏳ En attente de résolution du CAPTCHA... Appuie sur Entrée quand tu as terminé.")
            input()

        WebDriverWait(driver, timeout).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, 'div[data-test-id="lens-results"], div[class*="results"], div[id*="results"], div[class*="container"]'))
        )

        try:
            select_text_btn = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, '//span[contains(text(), "Sélectionner le texte")]'))
            )
            select_text_btn.click()
            time.sleep(random.uniform(1, 2))
        except:
            driver.save_screenshot('no_select_button.png')
            return "Error: 'Sélectionner le texte' introuvable"

        try:
            copy_btn = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, '//span[contains(text(), "Copier")]'))
            )
            copy_btn.click()
            time.sleep(random.uniform(0.5, 1.5))
        except:
            driver.save_screenshot('copy_error.png')
            return "Error: 'Copier' introuvable"

        extracted_text = pyperclip.paste().strip()
        if not extracted_text:
            extracted_text = "No text detected or copied"
        return extracted_text

    except Exception as e:
        if driver:
            driver.save_screenshot('error_debug.png')
        return f"Error: {str(e)}"

    finally:
        if driver:
            try:
                driver.quit()
                time.sleep(1)
                kill_chromedriver()
            except:
                kill_chromedriver()

if __name__ == "__main__":
    image_path = r'C:/img.jpg'
    extracted_text = extract_text_with_google_lens(image_path, headless=False, timeout=30)
    print("\nExtracted Text from Google Lens OCR:")
    print(extracted_text)
rendre ce script undetectable par google sans utiliser undetected chrome driver