File size: 2,747 Bytes
33e958f
136ae30
df87638
 
136ae30
b5bf16b
 
 
 
 
 
136ae30
7eecb79
136ae30
b5bf16b
 
 
 
 
 
 
 
 
33e958f
df87638
 
 
33e958f
7eecb79
df87638
 
33e958f
1fab9b0
df87638
 
 
33e958f
df87638
 
 
1fab9b0
df87638
 
 
33e958f
7eecb79
 
 
33e958f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5bf16b
 
 
136ae30
b5bf16b
 
 
33e958f
 
b5bf16b
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from typing import Literal
import httpx
import nbformat
from nbformat import NotebookNode, ValidationError
from nbconvert import HTMLExporter
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.responses import FileResponse, JSONResponse, HTMLResponse
from starlette.requests import Request
from starlette.routing import Route

client = httpx.AsyncClient()
html_exporter = HTMLExporter(template_name="lab")


async def homepage(_):
    return FileResponse("static/index.html")


async def healthz(_):
    return JSONResponse({"success": True})


def convert(s: str, theme: Literal["light", "dark"], debug_info: str) -> str:
    # Capture potential validation error:
    try:
        notebook_node: NotebookNode = nbformat.reads(
            s,
            as_version=nbformat.current_nbformat,
        )
    except nbformat.reader.NotJSONError:
        print(400, f"Notebook is not JSON. {debug_info}")
        raise HTTPException(400, f"Notebook is not JSON.")
    except ValidationError as e:
        print(
            400,
            f"Notebook is invalid according to nbformat: {e}. {debug_info}",
        )
        raise HTTPException(
            400,
            f"Notebook is invalid according to nbformat: {e}.",
        )

    print(f"Input: nbformat v{notebook_node.nbformat}.{notebook_node.nbformat_minor}")
    html_exporter.theme = theme
    body, _ = html_exporter.from_notebook_node(notebook_node)
    # TODO(customize or simplify template?)
    # TODO(also check source code for jupyter/nbviewer)
    return body


async def convert_from_url(req: Request):
    url = req.query_params.get("url")
    theme = "dark" if req.query_params.get("theme") == "dark" else "light"

    if not url:
        raise HTTPException(400, "Param url is missing")
    print("\n===", url)
    r = await client.get(
        url,
        follow_redirects=True,
        # httpx no follow redirect by default
    )
    if r.status_code != 200:
        raise HTTPException(
            400, f"Got an error {r.status_code} when fetching remote file"
        )

    return HTMLResponse(content=convert(r.text, theme=theme, debug_info=f"url={url}"))


async def convert_from_upload(req: Request):
    theme = "dark" if req.query_params.get("theme") == "dark" else "light"

    s = (await req.body()).decode("utf-8")
    return HTMLResponse(
        content=convert(
            s, theme=theme, debug_info=f"upload_from={req.headers.get('user-agent')}"
        )
    )


app = Starlette(
    debug=False,
    routes=[
        Route("/", homepage),
        Route("/healthz", healthz),
        Route("/convert", convert_from_url),
        Route("/upload", convert_from_upload, methods=["POST"]),
    ],
)