Spaces:
Paused
Paused
Update app/lens_text_core.py
Browse files1223454 unmodified lines1011121314151616 unmodified lines3334353637383940413940414243444546474849505152535455565758596061626364656667424344454647486970717273744950517652535479808182838485868788899091925556575859606162636465666768697071727374757677787980818283848586
import os, time, asyncio, base64, re, threading, hashlib, logging, shutilimport 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 = 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", # Windows r"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 env
for cmd in ("google-chrome", "chromium-browser", "chromium", "chrome"): path = shutil.which(cmd) if path: return path
for path in _COMMON_CHROME_PATHS: if os.path.exists(path): return path
raise RuntimeError( "Chrome binary not found; set CHROME_BINARY env var or install Chrome/Chromium" )def _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 p
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_loc for flag in CHROME_EXTRA_ARGS:def _cleanup_profiles(): for p in _PROFILE_DIRS: try: opts.add_argument(flag) shutil.rmtree(p, ignore_errors=True) except Exception: pass service = 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: pass return drv
atexit.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