# main.py import os import gradio as gr import spaces from fastapi import FastAPI from fastapi.responses import JSONResponse from playwright.async_api import async_playwright from turnstile import solve_turnstile app = FastAPI() DOMAIN = os.getenv("DOMAIN", "https://fourstore-cloudflare.hf.space") TIMEOUT = int(os.getenv("timeOut", 60000)) BROWSER_LIMIT = int(os.getenv("browserLimit", 20)) _state = {"browser_limit": BROWSER_LIMIT} @spaces.GPU def _noop(): pass @app.get("/api") async def api_root(): return { "message": "Server is running!", "domain": DOMAIN, "endpoint": f"{DOMAIN}/gradio/turnstile", "status": { "browserLimit": _state["browser_limit"], "timeOut": TIMEOUT, }, } @app.post("/turnstile") async def turnstile_route(body: dict): domain = body.get("domain") site_key = body.get("siteKey") proxy = body.get("proxy") if not domain or not site_key: return JSONResponse({"message": "Missing domain or siteKey"}, status_code=400) if _state["browser_limit"] <= 0: return JSONResponse({"message": "Too Many Requests"}, status_code=429) _state["browser_limit"] -= 1 pw = browser = None try: pw = await async_playwright().start() launch_args = { "headless": True, "args": ["--no-sandbox", "--disable-dev-shm-usage"], } if proxy and proxy.get("hostname"): launch_args["proxy"] = { "server": f"http://{proxy['hostname']}:{proxy['port']}" } browser = await pw.chromium.launch(**launch_args) context = await browser.new_context() page = await context.new_page() async def block(route): if route.request.resource_type in ("image", "stylesheet", "font", "media"): await route.abort() else: await route.continue_() await page.route("**/*", block) await page.goto("about:blank") token = await solve_turnstile(domain, site_key, page, proxy) return {"code": 200, "token": token} except Exception as e: return JSONResponse({"code": 500, "message": str(e)}, status_code=500) finally: if browser: try: await browser.close() except Exception: pass if pw: try: await pw.stop() except Exception: pass _state["browser_limit"] += 1 with gr.Blocks() as demo: gr.Markdown("Turnstile Service. API endpoint: /gradio/turnstile") app = gr.mount_gradio_app(app, demo, path="/gradio")