Spaces:
Running
Running
Download modules/monitor/shared_browser.py from Arrechenash/stocks: direct link, hf CLI and curl.
- Browser
- Download file 2 kB
-
https://huggingface.co/spaces/Arrechenash/stocks/resolve/main/modules/monitor/shared_browser.py
- Command line
-
hf download hf://spaces/Arrechenash/stocks/modules/monitor/shared_browser.py
-
curl -L -o shared_browser.py https://huggingface.co/spaces/Arrechenash/stocks/resolve/main/modules/monitor/shared_browser.py
2 kB
| """Single shared headless Chromium instance for all experimental site | |
| scrapers (momo_scraper.py, titan_scraper.py). Each scraper previously | |
| launched its own browser process just to hold one page open -- that's two | |
| full Chromium processes for two WebSocket connections. One shared browser | |
| process with a separate BrowserContext per scraper (so cookies/UA stay | |
| isolated) cuts that in half. | |
| """ | |
| import asyncio | |
| from playwright.async_api import Browser, Playwright, async_playwright | |
| _playwright: Playwright | None = None | |
| _browser: Browser | None = None | |
| _lock = asyncio.Lock() | |
| async def get_browser() -> Browser: | |
| global _playwright, _browser | |
| async with _lock: | |
| if _browser is None: | |
| _playwright = await async_playwright().start() | |
| _browser = await _playwright.chromium.launch( | |
| headless=True, | |
| args=[ | |
| "--disable-blink-features=AutomationControlled", | |
| # Trims Chromium overhead we don't need for a headless | |
| # tab that only exists to keep one WebSocket open -- | |
| # no GPU/compositor, no background services, no | |
| # first-run/updater/telemetry work competing for CPU. | |
| "--disable-gpu", | |
| "--disable-dev-shm-usage", | |
| "--disable-extensions", | |
| "--disable-background-networking", | |
| "--disable-sync", | |
| "--disable-translate", | |
| "--disable-default-apps", | |
| "--metrics-recording-only", | |
| "--mute-audio", | |
| "--no-first-run", | |
| ], | |
| ) | |
| return _browser | |
| async def shutdown() -> None: | |
| global _playwright, _browser | |
| async with _lock: | |
| if _browser is not None: | |
| await _browser.close() | |
| _browser = None | |
| if _playwright is not None: | |
| await _playwright.stop() | |
| _playwright = None | |