This repository has been archived by the owner on Jan 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
64 lines (48 loc) · 1.64 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from urllib.parse import urlparse
from pyppeteer import launch
import colorgram
from pathlib import Path
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def start(request: Request):
return templates.TemplateResponse("template.html", {
"request": request,
})
@app.post("/", response_class=HTMLResponse)
async def extract(request: Request):
form = await request.form()
if "url" not in form or form["url"] == "":
return templates.TemplateResponse("template.html", {
"request": request,
"url": "",
"error": "Please fill in an url",
})
url = form["url"]
if not url.startswith("http"):
url = "https://" + url
domain = urlparse(url).netloc
path = Path("screenshots") / Path(f'{domain}.png')
if not Path(path).exists():
await write_screenshot(url, path)
colors = colorgram.extract(path, 6)
Path(path).unlink(missing_ok=True)
return templates.TemplateResponse("template.html", {
"request": request,
"url": url.replace("https://", "").replace("http://", ""),
"colors": colors,
})
async def write_screenshot(url, path):
browser = await launch()
page = await browser.newPage()
await page.goto(url)
await page.screenshot({
"path": path,
"fullPage": True,
})
await browser.close()