File size: 9,007 Bytes
651b674
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""Local, read-only graph review server. Only the frontend and graph are exposed."""

from __future__ import annotations

import argparse
import hashlib
import json
import mimetypes
from contextlib import ExitStack
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from tempfile import TemporaryDirectory
from urllib.parse import parse_qs, unquote, urlsplit

from compact_fact_extraction.graph import build_graph, validate_graph


PROJECT_ROOT = Path(__file__).resolve().parents[2]
CASE_DATA = PROJECT_ROOT / "МТС MWS CompactFactExtraction" / "Данные кейса"


def make_handler(graph: dict, frontend: Path, retriever=None) -> type[BaseHTTPRequestHandler]:
    """Serve a validated snapshot without exposing other project files."""
    validate_graph(graph)
    root = frontend.resolve()
    if not (root / "index.html").is_file():
        raise ValueError(f"Frontend index.html not found in {root}")
    payload = json.dumps(graph, ensure_ascii=False, indent=2).encode("utf-8")
    etag = '"' + hashlib.sha256(payload).hexdigest() + '"'

    class Handler(BaseHTTPRequestHandler):
        server_version = "DomainGraph/1.0"

        def do_GET(self) -> None:
            self._respond(send_body=True)

        def do_HEAD(self) -> None:
            self._respond(send_body=False)

        def do_POST(self) -> None:
            self._send(
                HTTPStatus.METHOD_NOT_ALLOWED,
                b'{"error":"This viewer is read-only"}',
                "application/json; charset=utf-8",
                send_body=True,
                extra_headers={"Allow": "GET, HEAD"},
            )

        def _respond(self, *, send_body: bool) -> None:
            try:
                parsed = urlsplit(self.path)
                path = unquote(parsed.path, errors="strict")
            except (ValueError, UnicodeError):
                self.send_error(HTTPStatus.BAD_REQUEST)
                return
            if path == "/api/search":
                if retriever is None:
                    self._json(HTTPStatus.SERVICE_UNAVAILABLE, {"error": "Поисковый индекс не загружен."}, send_body)
                    return
                try:
                    params = parse_qs(parsed.query, keep_blank_values=True, max_num_fields=8, errors="strict")
                    if set(params) - {"q", "category", "limit", "mode"} or any(len(v) != 1 for v in params.values()):
                        raise ValueError("Неизвестные или повторяющиеся параметры поиска.")
                    query = params.get("q", [""])[0].strip()
                    if not query or len(query) > 500:
                        raise ValueError("Введите запрос длиной от 1 до 500 символов.")
                    limit = int(params.get("limit", ["8"])[0])
                    if not 1 <= limit <= 20:
                        raise ValueError("limit должен быть от 1 до 20.")
                    result = retriever.search(
                        query, category=params.get("category", [None])[0] or None,
                        limit=limit, mode=params.get("mode", ["graph"])[0],
                    )
                except (ValueError, UnicodeError) as exc:
                    self._json(HTTPStatus.BAD_REQUEST, {"error": str(exc)}, send_body)
                    return
                self._json(HTTPStatus.OK, result, send_body)
                return
            if path == "/api/graph":
                if self.headers.get("If-None-Match") == etag:
                    self._send(
                        HTTPStatus.NOT_MODIFIED, b"", "application/json",
                        send_body=False, extra_headers={"ETag": etag},
                    )
                else:
                    self._send(
                        HTTPStatus.OK, payload, "application/json; charset=utf-8",
                        send_body=send_body, extra_headers={"ETag": etag},
                    )
                return
            if path == "/healthz":
                health = json.dumps({"status": "ok", "graph_id": graph["graph_id"]})
                self._send(
                    HTTPStatus.OK, health.encode(), "application/json; charset=utf-8",
                    send_body=send_body,
                )
                return
            if path.startswith("/api/"):
                self.send_error(HTTPStatus.NOT_FOUND)
                return
            relative = "index.html" if path == "/" else path.lstrip("/")
            try:
                candidate = (root / relative).resolve()
                if not candidate.is_relative_to(root) or not candidate.is_file():
                    self.send_error(HTTPStatus.NOT_FOUND)
                    return
                # Directory listings and project files outside the frontend are never served.
                if any(part.startswith(".") for part in candidate.relative_to(root).parts):
                    self.send_error(HTTPStatus.NOT_FOUND)
                    return
                body = candidate.read_bytes()
            except (OSError, ValueError):
                self.send_error(HTTPStatus.NOT_FOUND)
                return
            mime = mimetypes.guess_type(candidate.name)[0] or "application/octet-stream"
            if mime.startswith("text/") or mime in {"application/javascript", "application/json"}:
                mime += "; charset=utf-8"
            self._send(HTTPStatus.OK, body, mime, send_body=send_body)

        def _json(self, status, value, send_body):
            body = json.dumps(value, ensure_ascii=False).encode("utf-8")
            self._send(status, body, "application/json; charset=utf-8", send_body=send_body)

        def _send(
            self, status: HTTPStatus, body: bytes, content_type: str,
            *, send_body: bool, extra_headers: dict[str, str] | None = None,
        ) -> 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")
            self.send_header("X-Content-Type-Options", "nosniff")
            self.send_header("Referrer-Policy", "no-referrer")
            for name, value in (extra_headers or {}).items():
                self.send_header(name, value)
            self.end_headers()
            if send_body:
                self.wfile.write(body)

    return Handler


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(description="Локальный просмотр графа каталога и схемы")
    parser.add_argument("--catalog", type=Path, default=CASE_DATA / "catalog.json")
    parser.add_argument("--schema", type=Path, default=CASE_DATA / "schema.md")
    parser.add_argument("--answers", type=Path, help="Дополнения организаторов; по умолчанию рядом со схемой")
    parser.add_argument("--graph", type=Path, help="Готовый JSON вместо новой сборки")
    parser.add_argument("--index", type=Path, help="Готовый SQLite-индекс той же версии; иначе временный индекс")
    parser.add_argument("--frontend", type=Path, default=PROJECT_ROOT / "frontend")
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=8765)
    args = parser.parse_args(argv)
    if not 0 <= args.port <= 65535:
        parser.error("--port must be between 0 and 65535")
    from compact_fact_extraction.graph.retrieval import DomainRetriever, build_index

    with ExitStack() as resources:
        try:
            graph = (
                json.loads(args.graph.read_text(encoding="utf-8"))
                if args.graph else build_graph(args.catalog, args.schema, args.answers)
            )
            index = args.index
            if index is None:
                directory = resources.enter_context(TemporaryDirectory(prefix="domain-graph-"))
                index = Path(directory) / "index.sqlite"
                build_index(graph, index)
            retriever = DomainRetriever(graph, index)
            handler = make_handler(graph, args.frontend, retriever)
            server = ThreadingHTTPServer((args.host, args.port), handler)
        except (OSError, ValueError) as exc:
            parser.exit(2, f"Cannot start graph viewer: {exc}\n")
        host, port = server.server_address[:2]
        print(f"Graph viewer: http://{host}:{port}", flush=True)
        print(f"Graph snapshot: {graph['graph_id']}", flush=True)
        print("Read-only graph and search. Stop with Ctrl+C. Restart to load edited sources.", flush=True)
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            pass
        finally:
            server.server_close()


if __name__ == "__main__":
    main()