Spaces:
Paused
Paused
Update app/main.py
Browse files- app/main.py +21 -11
app/main.py
CHANGED
|
@@ -1,22 +1,32 @@
|
|
| 1 |
from fastapi import FastAPI, Query
|
| 2 |
from fastapi.responses import JSONResponse
|
|
|
|
| 3 |
import base64
|
| 4 |
from playwright.async_api import async_playwright
|
| 5 |
-
import io
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
@app.get("/screenshot")
|
| 10 |
async def screenshot(url: str = Query(..., description="Web page URL to capture")):
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI, Query
|
| 2 |
from fastapi.responses import JSONResponse
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
import base64
|
| 5 |
from playwright.async_api import async_playwright
|
|
|
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
|
| 9 |
+
# Optional: Allow access from any frontend (useful for Hugging Face Gradio frontends)
|
| 10 |
+
app.add_middleware(
|
| 11 |
+
CORSMiddleware,
|
| 12 |
+
allow_origins=["*"],
|
| 13 |
+
allow_methods=["*"],
|
| 14 |
+
allow_headers=["*"],
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
@app.get("/screenshot")
|
| 18 |
async def screenshot(url: str = Query(..., description="Web page URL to capture")):
|
| 19 |
+
try:
|
| 20 |
+
async with async_playwright() as p:
|
| 21 |
+
browser = await p.chromium.launch()
|
| 22 |
+
page = await browser.new_page()
|
| 23 |
+
await page.goto(url, timeout=30000) # 30s timeout
|
| 24 |
+
buffer = await page.screenshot(full_page=True)
|
| 25 |
+
await browser.close()
|
| 26 |
|
| 27 |
+
b64_image = base64.b64encode(buffer).decode("utf-8")
|
| 28 |
+
data_url = f"data:image/png;base64,{b64_image}"
|
| 29 |
+
return JSONResponse(content={"image_base64": data_url})
|
| 30 |
|
| 31 |
+
except Exception as e:
|
| 32 |
+
return JSONResponse(status_code=500, content={"error": str(e)})
|