Spaces:
Paused
Paused
Update app/lens_text_core.py
Browse files123454 unmodified lines10111213141516 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495import os, time, asyncio, base64, re, threading, hashlib, logging, shutilfrom io import BytesIOfrom typing import Any, Dict, List, Unionfrom urllib.parse import urlparse4 unmodified linesfrom selenium import webdriverfrom selenium.webdriver.chrome.options import Options as ChromeOptionsfrom selenium.webdriver.chrome.service import Service as ChromeServicefrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC16 unmodified lines"--window-size=1920,1080 --headless=new",).split()_CACHE_TTL = 300_IDLE_TIMEOUT = int(os.getenv("CHROME_IDLE_SECONDS", "60"))_BROWSER_TTL = 900_COMMON_CHROME_PATHS = [# Linux"/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser","/snap/bin/chromium","/opt/google/chrome/google-chrome",# macOS"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium",# Windowsr"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",r"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",]def _find_chrome_binary() -> str:if (env := os.getenv("CHROME_BINARY")):return envfor cmd in ("google-chrome", "chromium-browser", "chromium", "chrome"):path = shutil.which(cmd)if path:return pathfor path in _COMMON_CHROME_PATHS:if os.path.exists(path):return pathraise RuntimeError("Chrome binary not found; set CHROME_BINARY env var or install Chrome/Chromium")def _build_chrome(cookie_dict: Dict[str, str] | None = None):bin_loc = _find_chrome_binary()drv_path = os.getenv("CHROMEDRIVER", "/usr/bin/chromedriver")opts = ChromeOptions()opts.binary_location = bin_locfor flag in CHROME_EXTRA_ARGS:try:opts.add_argument(flag)except Exception:passservice = ChromeService(executable_path=drv_path)drv = webdriver.Chrome(service=service, options=opts)drv.execute_cdp_cmd("Network.enable", {})if cookie_dict:for name, val in cookie_dict.items():try:drv.execute_cdp_cmd("Network.setCookie", {"name": name, "value": val,"domain": ".google.com", "path": "/", "secure": True})except Exception:passreturn drv_cached_cookie, _cached_cookie_ts, _cookie_lock = None, 0.0, threading.Lock()_global_driver, _driver_last_use, _driver_lock = None, 0.0, threading.Lock()123454 unmodified lines1011121314151616 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import os, time, asyncio, base64, re, threading, hashlib, logging, shutil, atexit, tempfile, uuidfrom io import BytesIOfrom typing import Any, Dict, List, Unionfrom urllib.parse import urlparse4 unmodified linesfrom selenium import webdriverfrom selenium.webdriver.chrome.options import Options as ChromeOptionsfrom selenium.webdriver.chrome.service import Service as ChromeServicefrom selenium.common.exceptions import SessionNotCreatedExceptionfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC16 unmodified lines"--window-size=1920,1080 --headless=new",).split()_PROFILE_DIRS = []_CACHE_TTL = 300_IDLE_TIMEOUT = int(os.getenv("CHROME_IDLE_SECONDS", "60"))_BROWSER_TTL = 900def _mk_profile_dir() -> str:base = os.getenv("CHROME_PROFILE_BASE", tempfile.gettempdir())p = os.path.join(base, f"chrome-profile-{os.getpid()}-{threading.get_ident()}-{uuid.uuid4().hex}")os.makedirs(p, exist_ok=True)_PROFILE_DIRS.append(p)return pdef _cleanup_profiles():for p in _PROFILE_DIRS:try:shutil.rmtree(p, ignore_errors=True)except Exception:passatexit.register(_cleanup_profiles)def _build_chrome() -> webdriver.Chrome:opts = ChromeOptions()extra = os.getenv("CHROME_EXTRA_ARGS","--disable-gpu --no-sandbox --disable-dev-shm-usage --window-size=1920,1080 --headless=new",).split()for a in extra:if a:opts.add_argument(a)profile_dir = _mk_profile_dir()opts.add_argument(f"--user-data-dir={profile_dir}")opts.add_argument("--profile-directory=Default")drv_path = os.getenv("CHROMEDRIVER")try:if drv_path and os.path.exists(drv_path):return webdriver.Chrome(service=ChromeService(executable_path=drv_path), options=opts)return webdriver.Chrome(options=opts)except SessionNotCreatedException as e:LOGGER.warning("SessionNotCreated: %s; retry with a fresh profile dir", e)profile_dir2 = _mk_profile_dir()opts.arguments = [a for a in opts.arguments if not a.startswith("--user-data-dir=")]opts.add_argument(f"--user-data-dir={profile_dir2}")return webdriver.Chrome(options=opts)_cached_cookie, _cached_cookie_ts, _cookie_lock = None, 0.0, threading.Lock()_global_driver, _driver_last_use, _driver_lock = None, 0.0, threading.Lock()
app/lens_text_core.py+42-51