grapheye 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. grapheye-0.1.0/LICENSE +21 -0
  2. grapheye-0.1.0/PKG-INFO +181 -0
  3. grapheye-0.1.0/README.md +151 -0
  4. grapheye-0.1.0/grapheye/__init__.py +16 -0
  5. grapheye-0.1.0/grapheye/__main__.py +3 -0
  6. grapheye-0.1.0/grapheye/app.py +143 -0
  7. grapheye-0.1.0/grapheye/cli.py +226 -0
  8. grapheye-0.1.0/grapheye/demo.py +60 -0
  9. grapheye-0.1.0/grapheye/events.py +234 -0
  10. grapheye-0.1.0/grapheye/export.py +171 -0
  11. grapheye-0.1.0/grapheye/history.py +339 -0
  12. grapheye-0.1.0/grapheye/importing.py +42 -0
  13. grapheye-0.1.0/grapheye/models.py +207 -0
  14. grapheye-0.1.0/grapheye/notebook.py +556 -0
  15. grapheye-0.1.0/grapheye/routes.py +196 -0
  16. grapheye-0.1.0/grapheye/serialization.py +118 -0
  17. grapheye-0.1.0/grapheye/static/api.js +96 -0
  18. grapheye-0.1.0/grapheye/static/app.js +689 -0
  19. grapheye-0.1.0/grapheye/static/controller.js +3790 -0
  20. grapheye-0.1.0/grapheye/static/dom.js +145 -0
  21. grapheye-0.1.0/grapheye/static/exportclient.js +111 -0
  22. grapheye-0.1.0/grapheye/static/favicon.svg +19 -0
  23. grapheye-0.1.0/grapheye/static/graph2d.js +992 -0
  24. grapheye-0.1.0/grapheye/static/graph3d.js +1237 -0
  25. grapheye-0.1.0/grapheye/static/hyperblob.js +333 -0
  26. grapheye-0.1.0/grapheye/static/importclient.js +40 -0
  27. grapheye-0.1.0/grapheye/static/index.html +480 -0
  28. grapheye-0.1.0/grapheye/static/layouts.js +298 -0
  29. grapheye-0.1.0/grapheye/static/logo_dark.svg +71 -0
  30. grapheye-0.1.0/grapheye/static/logo_light.svg +71 -0
  31. grapheye-0.1.0/grapheye/static/physics.js +190 -0
  32. grapheye-0.1.0/grapheye/static/settingsui.js +82 -0
  33. grapheye-0.1.0/grapheye/static/state.js +259 -0
  34. grapheye-0.1.0/grapheye/static/style.css +2248 -0
  35. grapheye-0.1.0/grapheye/static/theme.js +188 -0
  36. grapheye-0.1.0/grapheye/static/ui.js +374 -0
  37. grapheye-0.1.0/grapheye/static/utils.js +238 -0
  38. grapheye-0.1.0/grapheye/static/vendor/3d-force-graph.min.js +5 -0
  39. grapheye-0.1.0/grapheye/static/vendor/NOTICE.md +61 -0
  40. grapheye-0.1.0/grapheye/static/vendor/d3/d3-dispatch.min.js +2 -0
  41. grapheye-0.1.0/grapheye/static/vendor/d3/d3-force.min.js +2 -0
  42. grapheye-0.1.0/grapheye/static/vendor/d3/d3-quadtree.min.js +2 -0
  43. grapheye-0.1.0/grapheye/static/vendor/d3/d3-timer.min.js +2 -0
  44. grapheye-0.1.0/grapheye/static/vendor/force-graph.min.js +5 -0
  45. grapheye-0.1.0/grapheye/static/vendor/three-spritetext.min.js +2 -0
  46. grapheye-0.1.0/grapheye/static/vendor/three.min.js +7 -0
  47. grapheye-0.1.0/grapheye/static/viewcommon.js +741 -0
  48. grapheye-0.1.0/grapheye/store.py +1403 -0
  49. grapheye-0.1.0/grapheye/validation.py +209 -0
  50. grapheye-0.1.0/grapheye/version.py +3 -0
  51. grapheye-0.1.0/grapheye.egg-info/PKG-INFO +181 -0
  52. grapheye-0.1.0/grapheye.egg-info/SOURCES.txt +70 -0
  53. grapheye-0.1.0/grapheye.egg-info/dependency_links.txt +1 -0
  54. grapheye-0.1.0/grapheye.egg-info/entry_points.txt +2 -0
  55. grapheye-0.1.0/grapheye.egg-info/requires.txt +8 -0
  56. grapheye-0.1.0/grapheye.egg-info/top_level.txt +1 -0
  57. grapheye-0.1.0/pyproject.toml +77 -0
  58. grapheye-0.1.0/setup.cfg +4 -0
  59. grapheye-0.1.0/tests/test_api.py +476 -0
  60. grapheye-0.1.0/tests/test_cli.py +183 -0
  61. grapheye-0.1.0/tests/test_convert.py +112 -0
  62. grapheye-0.1.0/tests/test_demo.py +24 -0
  63. grapheye-0.1.0/tests/test_events.py +205 -0
  64. grapheye-0.1.0/tests/test_graphstore.py +685 -0
  65. grapheye-0.1.0/tests/test_history.py +148 -0
  66. grapheye-0.1.0/tests/test_import.py +132 -0
  67. grapheye-0.1.0/tests/test_layout.py +304 -0
  68. grapheye-0.1.0/tests/test_multigraph.py +208 -0
  69. grapheye-0.1.0/tests/test_notebook.py +195 -0
  70. grapheye-0.1.0/tests/test_review_fixes.py +143 -0
  71. grapheye-0.1.0/tests/test_server.py +55 -0
  72. grapheye-0.1.0/tests/test_ui.py +3793 -0
grapheye-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GraphEye contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.4
2
+ Name: grapheye
3
+ Version: 0.1.0
4
+ Summary: Interactive networkx graph visualization in the browser: physics, editing, 2D/3D
5
+ Author: GraphEye contributors
6
+ License-Expression: MIT
7
+ Keywords: networkx,graph,visualization,fastapi,webgl,3d
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Framework :: FastAPI
18
+ Classifier: Topic :: Scientific/Engineering :: Visualization
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: fastapi>=0.110
23
+ Requires-Dist: uvicorn>=0.29
24
+ Requires-Dist: networkx>=3.0
25
+ Requires-Dist: numpy>=1.24
26
+ Requires-Dist: scipy>=1.10
27
+ Provides-Extra: image
28
+ Requires-Dist: playwright>=1.40; extra == "image"
29
+ Dynamic: license-file
30
+
31
+ # GraphEye
32
+
33
+ <p align="center"><img src="grapheye/static/logo_light.svg" alt="Logo" width="200"></p>
34
+
35
+ Interactive [networkx](https://networkx.org) graph visualization in the browser: physics, mouse editing, 2D/3D modes.
36
+
37
+ The passed `networkx` graph remains the single source of truth: edits from the browser mutate the object directly, while code changes are picked up by the window automatically.
38
+
39
+ - Rendering: WebGL ([3d-force-graph](https://github.com/vasturiano/3d-force-graph) / force-graph 2D), d3-force engine
40
+ - Server: FastAPI + uvicorn
41
+ - Modes: 2D / 3D, physics simulation, mouse-based graph editing
42
+ - Fully offline: JS libraries are vendored in `grapheye/static/vendor/`
43
+
44
+ ## Contents
45
+
46
+ - [Description](#description)
47
+ - [Demo](#demo)
48
+ - [Graph types](#graph-types)
49
+ - [Layouts](#layouts)
50
+ - [Reactivity](#reactivity)
51
+ - [Installation](#installation)
52
+ - [Quick start](#quick-start)
53
+ - [Documentation](#documentation)
54
+ - [License](#license)
55
+
56
+ ## Description
57
+
58
+ GraphEye is a browser-based editor and viewer for networkx graphs:
59
+
60
+ - viewing and editing: nodes, edges, hyperedges, attributes, groups;
61
+ - directed / undirected graphs, multigraphs, hypergraphs (including nested ones);
62
+ - networkx layouts (spring, circular, kamada-kawai, spectral, shell, spiral, planar, and more) + local layouts (circle, grid, hierarchy, by group, sphere);
63
+ - two-way sync between code and window: SSE + graph revision check;
64
+ - undo / redo, export (GraphML, GEXF, GML, JSON, CSV, PNG), import;
65
+ - run as a CLI server or directly from Jupyter (`show`, `show_image`).
66
+
67
+ ## Demo
68
+
69
+ ### Graph types
70
+
71
+ Undirected / directed, graph / multigraph:
72
+
73
+ ![Graph types: plain, directed, multigraph](assets/graph-types.png)
74
+
75
+ See example: [`demo/directed-multigraph.ipynb`](demo/directed-multigraph.ipynb).
76
+
77
+ Graph / hypergraph / nested hypergraph:
78
+
79
+ ![Hypergraphs: plain view, hypergraph, nested hypergraph](assets/hypergraphs.png)
80
+
81
+ See example: [`demo/hypergraphs.ipynb`](demo/hypergraphs.ipynb).
82
+
83
+ A hyperedge is a node with `hyperedge=True`; links to members are plain edges from the hub. A member can itself be another hyper-hub — that is how nested hypergraphs are built. In the "Hypergraph" view areas are drawn as blob / polygon; in the "Graph" view hubs look like diamonds with links.
84
+
85
+ ### Layouts
86
+
87
+ ![Layouts: spring, kamada-kawai](assets/layouts/spring_kamada-kawai.png)
88
+
89
+ ![Layouts: circle, hierarchy](assets/layouts/circle_hierarchy.png)
90
+
91
+ ![Layouts: spectral, shells](assets/layouts/spectral_shells.png)
92
+
93
+ Full gallery: [`demo/layouts.ipynb`](demo/layouts.ipynb) (circle, grid, hierarchy, by group, sphere, spiral, spring, kamada-kawai, spectral, shells, planar).
94
+
95
+ A layout is computed via networkx and written into node `x`/`y`/`z` attributes — i.e. stored in the graph itself. Hyperedge hubs are excluded from the computation: they get the centroid of their members.
96
+
97
+ ### Reactivity
98
+
99
+ Edits from the window apply instantly. Code changes (`G.add_edge(...)` in a neighboring cell) are noticed by the server itself: while the editor is open, the graph revision is re-checked every 3 s and broadcast to SSE subscribers, and in Jupyter `show()` additionally installs a `post_run_cell` hook — changes appear right after cell execution.
100
+
101
+ <video src="assets/reactivity.mp4" controls width="100%"></video>
102
+
103
+ See example: [`demo/reactivity.ipynb`](demo/reactivity.ipynb).
104
+
105
+ ## Installation
106
+
107
+ Requires Python ≥ 3.10.
108
+
109
+ ```bash
110
+ pip install grapheye
111
+ ```
112
+
113
+ For static PNGs in notebooks (via Playwright):
114
+
115
+ ```bash
116
+ pip install "grapheye[image]"
117
+ python -m playwright install chromium
118
+ ```
119
+
120
+ From source:
121
+
122
+ ```bash
123
+ pip install -e .
124
+ ```
125
+
126
+ Dependencies: `fastapi>=0.110`, `uvicorn>=0.29`, `networkx>=3.0`, `numpy>=1.24`, `scipy>=1.10`.
127
+
128
+ ## Quick start
129
+
130
+ CLI — empty graph:
131
+
132
+ ```bash
133
+ grapheye
134
+ # open http://127.0.0.1:8000
135
+ ```
136
+
137
+ CLI — your own graph from a file:
138
+
139
+ ```bash
140
+ grapheye --graph graph.graphml # .graphml / .gexf / .gml / .gpickle / .pkl
141
+ ```
142
+
143
+ Python — embed into your app:
144
+
145
+ ```python
146
+ import networkx as nx
147
+ import uvicorn
148
+ from grapheye import create_app
149
+
150
+ G = nx.Graph()
151
+ G.add_node("alice", label="Alice", group="person")
152
+ G.add_node("bob", label="Bob", group="person")
153
+ G.add_edge("alice", "bob", weight=3)
154
+
155
+ uvicorn.run(create_app(G), host="127.0.0.1", port=8000)
156
+ # browser edits mutate G
157
+ ```
158
+
159
+ Jupyter — graph right in a cell:
160
+
161
+ ```python
162
+ from grapheye import show
163
+ import networkx as nx
164
+
165
+ G = nx.karate_club_graph()
166
+ show(G) # iframe with the editor; stop with: server.should_exit = True
167
+ ```
168
+
169
+ ## Documentation
170
+
171
+ - [`docs/api.md`](docs/api.md) — Python API (`create_app`, `GraphStore`, `show`/`show_image`/`start_server`), payload format, REST API, CLI, synchronization model, undo/redo, limitations.
172
+ - [`docs/editing.md`](docs/editing.md) — working in the browser: editing, hotkeys, sidebar (Inspector / Graph / Settings / Help), view and physics settings, hypergraphs, code sync.
173
+ - Examples:
174
+ - [`demo/directed-multigraph.ipynb`](demo/directed-multigraph.ipynb) — directed graphs and multigraphs.
175
+ - [`demo/hypergraphs.ipynb`](demo/hypergraphs.ipynb) — hypergraphs and nesting.
176
+ - [`demo/layouts.ipynb`](demo/layouts.ipynb) — layout gallery.
177
+ - [`demo/reactivity.ipynb`](demo/reactivity.ipynb) — "code ↔ window" reactivity.
178
+
179
+ ## License
180
+
181
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,151 @@
1
+ # GraphEye
2
+
3
+ <p align="center"><img src="grapheye/static/logo_light.svg" alt="Logo" width="200"></p>
4
+
5
+ Interactive [networkx](https://networkx.org) graph visualization in the browser: physics, mouse editing, 2D/3D modes.
6
+
7
+ The passed `networkx` graph remains the single source of truth: edits from the browser mutate the object directly, while code changes are picked up by the window automatically.
8
+
9
+ - Rendering: WebGL ([3d-force-graph](https://github.com/vasturiano/3d-force-graph) / force-graph 2D), d3-force engine
10
+ - Server: FastAPI + uvicorn
11
+ - Modes: 2D / 3D, physics simulation, mouse-based graph editing
12
+ - Fully offline: JS libraries are vendored in `grapheye/static/vendor/`
13
+
14
+ ## Contents
15
+
16
+ - [Description](#description)
17
+ - [Demo](#demo)
18
+ - [Graph types](#graph-types)
19
+ - [Layouts](#layouts)
20
+ - [Reactivity](#reactivity)
21
+ - [Installation](#installation)
22
+ - [Quick start](#quick-start)
23
+ - [Documentation](#documentation)
24
+ - [License](#license)
25
+
26
+ ## Description
27
+
28
+ GraphEye is a browser-based editor and viewer for networkx graphs:
29
+
30
+ - viewing and editing: nodes, edges, hyperedges, attributes, groups;
31
+ - directed / undirected graphs, multigraphs, hypergraphs (including nested ones);
32
+ - networkx layouts (spring, circular, kamada-kawai, spectral, shell, spiral, planar, and more) + local layouts (circle, grid, hierarchy, by group, sphere);
33
+ - two-way sync between code and window: SSE + graph revision check;
34
+ - undo / redo, export (GraphML, GEXF, GML, JSON, CSV, PNG), import;
35
+ - run as a CLI server or directly from Jupyter (`show`, `show_image`).
36
+
37
+ ## Demo
38
+
39
+ ### Graph types
40
+
41
+ Undirected / directed, graph / multigraph:
42
+
43
+ ![Graph types: plain, directed, multigraph](assets/graph-types.png)
44
+
45
+ See example: [`demo/directed-multigraph.ipynb`](demo/directed-multigraph.ipynb).
46
+
47
+ Graph / hypergraph / nested hypergraph:
48
+
49
+ ![Hypergraphs: plain view, hypergraph, nested hypergraph](assets/hypergraphs.png)
50
+
51
+ See example: [`demo/hypergraphs.ipynb`](demo/hypergraphs.ipynb).
52
+
53
+ A hyperedge is a node with `hyperedge=True`; links to members are plain edges from the hub. A member can itself be another hyper-hub — that is how nested hypergraphs are built. In the "Hypergraph" view areas are drawn as blob / polygon; in the "Graph" view hubs look like diamonds with links.
54
+
55
+ ### Layouts
56
+
57
+ ![Layouts: spring, kamada-kawai](assets/layouts/spring_kamada-kawai.png)
58
+
59
+ ![Layouts: circle, hierarchy](assets/layouts/circle_hierarchy.png)
60
+
61
+ ![Layouts: spectral, shells](assets/layouts/spectral_shells.png)
62
+
63
+ Full gallery: [`demo/layouts.ipynb`](demo/layouts.ipynb) (circle, grid, hierarchy, by group, sphere, spiral, spring, kamada-kawai, spectral, shells, planar).
64
+
65
+ A layout is computed via networkx and written into node `x`/`y`/`z` attributes — i.e. stored in the graph itself. Hyperedge hubs are excluded from the computation: they get the centroid of their members.
66
+
67
+ ### Reactivity
68
+
69
+ Edits from the window apply instantly. Code changes (`G.add_edge(...)` in a neighboring cell) are noticed by the server itself: while the editor is open, the graph revision is re-checked every 3 s and broadcast to SSE subscribers, and in Jupyter `show()` additionally installs a `post_run_cell` hook — changes appear right after cell execution.
70
+
71
+ <video src="assets/reactivity.mp4" controls width="100%"></video>
72
+
73
+ See example: [`demo/reactivity.ipynb`](demo/reactivity.ipynb).
74
+
75
+ ## Installation
76
+
77
+ Requires Python ≥ 3.10.
78
+
79
+ ```bash
80
+ pip install grapheye
81
+ ```
82
+
83
+ For static PNGs in notebooks (via Playwright):
84
+
85
+ ```bash
86
+ pip install "grapheye[image]"
87
+ python -m playwright install chromium
88
+ ```
89
+
90
+ From source:
91
+
92
+ ```bash
93
+ pip install -e .
94
+ ```
95
+
96
+ Dependencies: `fastapi>=0.110`, `uvicorn>=0.29`, `networkx>=3.0`, `numpy>=1.24`, `scipy>=1.10`.
97
+
98
+ ## Quick start
99
+
100
+ CLI — empty graph:
101
+
102
+ ```bash
103
+ grapheye
104
+ # open http://127.0.0.1:8000
105
+ ```
106
+
107
+ CLI — your own graph from a file:
108
+
109
+ ```bash
110
+ grapheye --graph graph.graphml # .graphml / .gexf / .gml / .gpickle / .pkl
111
+ ```
112
+
113
+ Python — embed into your app:
114
+
115
+ ```python
116
+ import networkx as nx
117
+ import uvicorn
118
+ from grapheye import create_app
119
+
120
+ G = nx.Graph()
121
+ G.add_node("alice", label="Alice", group="person")
122
+ G.add_node("bob", label="Bob", group="person")
123
+ G.add_edge("alice", "bob", weight=3)
124
+
125
+ uvicorn.run(create_app(G), host="127.0.0.1", port=8000)
126
+ # browser edits mutate G
127
+ ```
128
+
129
+ Jupyter — graph right in a cell:
130
+
131
+ ```python
132
+ from grapheye import show
133
+ import networkx as nx
134
+
135
+ G = nx.karate_club_graph()
136
+ show(G) # iframe with the editor; stop with: server.should_exit = True
137
+ ```
138
+
139
+ ## Documentation
140
+
141
+ - [`docs/api.md`](docs/api.md) — Python API (`create_app`, `GraphStore`, `show`/`show_image`/`start_server`), payload format, REST API, CLI, synchronization model, undo/redo, limitations.
142
+ - [`docs/editing.md`](docs/editing.md) — working in the browser: editing, hotkeys, sidebar (Inspector / Graph / Settings / Help), view and physics settings, hypergraphs, code sync.
143
+ - Examples:
144
+ - [`demo/directed-multigraph.ipynb`](demo/directed-multigraph.ipynb) — directed graphs and multigraphs.
145
+ - [`demo/hypergraphs.ipynb`](demo/hypergraphs.ipynb) — hypergraphs and nesting.
146
+ - [`demo/layouts.ipynb`](demo/layouts.ipynb) — layout gallery.
147
+ - [`demo/reactivity.ipynb`](demo/reactivity.ipynb) — "code ↔ window" reactivity.
148
+
149
+ ## License
150
+
151
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,16 @@
1
+ from .app import GraphStore, create_app
2
+ from .demo import demo_graph, demo_hypergraph
3
+ from .notebook import show, show_image, start_server, stop_server
4
+ from .version import __version__
5
+
6
+ __all__ = [
7
+ "GraphStore",
8
+ "create_app",
9
+ "demo_graph",
10
+ "demo_hypergraph",
11
+ "show",
12
+ "show_image",
13
+ "start_server",
14
+ "stop_server",
15
+ "__version__",
16
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,143 @@
1
+ """GraphEye FastAPI application."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import secrets
7
+ from collections.abc import AsyncIterator
8
+ from contextlib import asynccontextmanager
9
+ from importlib import resources
10
+ from pathlib import Path
11
+
12
+ import networkx as nx
13
+ from fastapi import FastAPI, Request
14
+ from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
15
+ from fastapi.staticfiles import StaticFiles
16
+ from starlette.middleware.gzip import GZipMiddleware
17
+
18
+ from .events import RevisionHub
19
+ from .routes import create_router
20
+ from .store import GraphStore
21
+ from .version import __version__
22
+
23
+ # Resolve the static directory: works both for a regular install and from source.
24
+ # resources.files() does not yield a real path inside a zip package, so fall back to Path(__file__).
25
+ try:
26
+ _res_static = resources.files("grapheye") / "static"
27
+ _res_path = os.fspath(_res_static) if hasattr(_res_static, "__fspath__") else str(_res_static)
28
+ STATIC_DIR = _res_path if os.path.isdir(_res_path) else str(Path(__file__).parent / "static")
29
+ except Exception:
30
+ STATIC_DIR = str(Path(__file__).parent / "static")
31
+
32
+ TOKEN_COOKIE = "grapheye_token"
33
+
34
+
35
+ def _token_from_request(request: Request) -> str | None:
36
+ header = request.headers.get("x-grapheye-token")
37
+ if header:
38
+ return header
39
+ authorization = request.headers.get("authorization", "")
40
+ if authorization.lower().startswith("bearer "):
41
+ return authorization[7:].strip()
42
+ cookie = request.cookies.get(TOKEN_COOKIE)
43
+ if cookie:
44
+ return cookie
45
+ return request.query_params.get("token")
46
+
47
+
48
+ def _valid_token(supplied: str | None, expected: str) -> bool:
49
+ return bool(supplied) and secrets.compare_digest(str(supplied), expected)
50
+
51
+
52
+ def create_app(
53
+ graph: nx.Graph | None = None,
54
+ *,
55
+ history_limit: int = 100,
56
+ token: str | None = None,
57
+ title: str = "GraphEye",
58
+ ) -> FastAPI:
59
+ """Create a FastAPI application on top of the given networkx graph.
60
+
61
+ The graph is not copied: all edits from the browser mutate it directly.
62
+ token is an optional shared secret for /api/*; opening
63
+ ``/?token=...`` stores it in an HttpOnly cookie.
64
+ """
65
+ store = GraphStore(graph, history_limit=history_limit)
66
+ hub = RevisionHub(store)
67
+
68
+ @asynccontextmanager
69
+ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
70
+ yield
71
+ # Close SSE streams so Ctrl+C does not wait for open browser tabs.
72
+ hub.shutdown()
73
+
74
+ # FastAPI >= 0.165 включает native OpenTelemetry-телеметрию, которая
75
+ # падает при несовпадении версий opentelemetry (get_logger signature).
76
+ # Библиотеке она не нужна — отключаем, с fallback для старых FastAPI.
77
+ try:
78
+ app = FastAPI(
79
+ title=title,
80
+ version=__version__,
81
+ lifespan=lifespan,
82
+ telemetry={"tracing": False, "metrics": False, "logs": False, "operation_spans": False},
83
+ )
84
+ except TypeError:
85
+ app = FastAPI(title=title, version=__version__, lifespan=lifespan)
86
+ app.state.store = store
87
+ app.state.hub = hub
88
+ app.state.graph = store.graph
89
+ app.state.token = token
90
+ app.include_router(create_router(store, hub, app))
91
+
92
+ if token:
93
+ expected = str(token)
94
+
95
+ @app.middleware("http")
96
+ async def auth_middleware(request: Request, call_next):
97
+ path = request.url.path
98
+ if path == "/" and "token" in request.query_params:
99
+ supplied = request.query_params.get("token")
100
+ if not _valid_token(supplied, expected):
101
+ return JSONResponse({"detail": "Invalid token"}, status_code=401)
102
+ response = RedirectResponse(url="/", status_code=303)
103
+ response.set_cookie(
104
+ TOKEN_COOKIE,
105
+ expected,
106
+ httponly=True,
107
+ samesite="lax",
108
+ secure=request.url.scheme == "https",
109
+ )
110
+ return response
111
+ if path.startswith("/api/"):
112
+ if not _valid_token(_token_from_request(request), expected):
113
+ return JSONResponse({"detail": "GraphEye token required"}, status_code=401)
114
+ return await call_next(request)
115
+
116
+ app.add_middleware(GZipMiddleware, minimum_size=1024)
117
+
118
+ @app.middleware("http")
119
+ async def static_cache_middleware(request: Request, call_next):
120
+ response = await call_next(request)
121
+ path = request.url.path
122
+ if path.startswith("/static/vendor/"):
123
+ response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
124
+ elif path.startswith("/static/"):
125
+ response.headers.setdefault("Cache-Control", "no-cache")
126
+ return response
127
+
128
+ static_dir = str(STATIC_DIR)
129
+ app.mount("/static", StaticFiles(directory=static_dir), name="static")
130
+
131
+ @app.get("/health", include_in_schema=False)
132
+ def health() -> dict:
133
+ return {"status": "ok"}
134
+
135
+ @app.get("/", include_in_schema=False)
136
+ def index() -> FileResponse:
137
+ return FileResponse(os.path.join(static_dir, "index.html"))
138
+
139
+ @app.get("/favicon.ico", include_in_schema=False)
140
+ def favicon() -> FileResponse:
141
+ return FileResponse(os.path.join(static_dir, "favicon.svg"), media_type="image/svg+xml")
142
+
143
+ return app