|
| 1 | +from beam import Output, endpoint, Image, env |
| 2 | +import asyncio |
| 3 | + |
| 4 | +if env.is_remote(): |
| 5 | + from playwright.async_api import async_playwright |
| 6 | + |
| 7 | +image = ( |
| 8 | + Image(python_version="python3.11") |
| 9 | + .add_python_packages( |
| 10 | + [ |
| 11 | + "playwright", |
| 12 | + ] |
| 13 | + ) |
| 14 | + .add_commands(["playwright install chromium", "playwright install-deps chromium"]) |
| 15 | +) |
| 16 | + |
| 17 | + |
| 18 | +@endpoint(name="headless-browser", cpu=2, memory="16Gi", image=image) |
| 19 | +async def browser(url: str = "https://example.com"): |
| 20 | + print(f"Navigating to: {url}") |
| 21 | + output_path = "/tmp/screenshot.png" |
| 22 | + |
| 23 | + async with async_playwright() as playwright: |
| 24 | + browser = await playwright.chromium.launch( |
| 25 | + headless=True, |
| 26 | + args=["--no-sandbox", "--disable-dev-shm-usage"], |
| 27 | + ) |
| 28 | + print("Browser launched successfully") |
| 29 | + |
| 30 | + try: |
| 31 | + page = await browser.new_page() |
| 32 | + await page.set_viewport_size({"width": 1920, "height": 1080}) |
| 33 | + |
| 34 | + await page.goto(url, wait_until="networkidle") |
| 35 | + print("Page loaded, waiting 2 seconds for any dynamic content...") |
| 36 | + |
| 37 | + await asyncio.sleep(2) |
| 38 | + |
| 39 | + await page.screenshot(path=output_path, full_page=True, type="png") |
| 40 | + print(f"Screenshot saved as: {output_path}") |
| 41 | + |
| 42 | + finally: |
| 43 | + await browser.close() |
| 44 | + |
| 45 | + output_file = Output(path=output_path) |
| 46 | + output_file.save() |
| 47 | + public_url = output_file.public_url(expires=400) |
| 48 | + |
| 49 | + return {"output_url": public_url} |
0 commit comments