File size: 2,361 Bytes
bd0f095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Standalone server for the PR diff prototype and its public GitHub snapshot."""

from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse
import os

ROOT = Path(__file__).resolve().parent
ASSETS = {
    "/": ("patch_view.html", "text/html; charset=utf-8", None),
    "/patch-view": ("patch_view.html", "text/html; charset=utf-8", None),
    "/patch-view/script.js": ("patch_view.js", "text/javascript; charset=utf-8", None),
    "/patch-view/data": ("data/pr.diff", "text/plain; charset=utf-8", None),
    "/patch-view/comments": (
        "data/comments.json.gz",
        "application/json; charset=utf-8",
        "gzip",
    ),
}


class Handler(BaseHTTPRequestHandler):
    def do_GET(self):  # noqa: N802
        parsed = urlparse(self.path)
        if parsed.path == "/health":
            self.reply(200, "text/plain", b"ok")
            return
        asset = ASSETS.get(parsed.path)
        if asset is None:
            self.reply(404, "text/plain", b"Not found")
            return
        if parsed.path in {"/patch-view/data", "/patch-view/comments"}:
            params = parse_qs(parsed.query)
            if (
                params.get("pr", ["43451"])[0] != "43451"
                or params.get("repository", ["huggingface/transformers"])[0]
                != "huggingface/transformers"
            ):
                self.reply(
                    400,
                    "text/plain",
                    b"This prototype contains the saved huggingface/transformers PR #43451 snapshot.",
                )
                return
        name, content_type, encoding = asset
        self.reply(200, content_type, (ROOT / name).read_bytes(), encoding)

    def reply(self, status, content_type, body, encoding=None):
        self.send_response(status)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-cache")
        if encoding:
            self.send_header("Content-Encoding", encoding)
        self.end_headers()
        self.wfile.write(body)


if __name__ == "__main__":
    port = int(os.environ.get("PORT", "7860"))
    print(f"Serving prototype on :{port}", flush=True)
    ThreadingHTTPServer(("0.0.0.0", port), Handler).serve_forever()