gemsmap 0.3.0__py3-none-any.whl

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.
gemsmap/cli.py ADDED
@@ -0,0 +1,172 @@
1
+ """The `gemsmap` command.
2
+
3
+ gemsmap start GEMsMAP and open it in the browser (http://127.0.0.1:8765)
4
+ gemsmap --port 8766 another port (the Map Builder's autosave belongs to the address, so keep one port)
5
+ gemsmap --no-browser start without opening the browser
6
+ gemsmap diagnose versions, solvers and folders, to paste into a bug report
7
+ gemsmap bigg-data install the BiGG tables once (~19 MB download; --from <folder> for local files)
8
+ gemsmap --version
9
+
10
+ Output is plain ASCII so that it prints in every console.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import os
17
+ import platform
18
+ import socket
19
+ import sys
20
+ import threading
21
+ import time
22
+ import urllib.request
23
+ import webbrowser
24
+ from pathlib import Path
25
+ from typing import Optional
26
+
27
+ from . import __version__
28
+
29
+ DEFAULT_PORT = int(os.environ.get("GEMSMAP_PORT", 8765))
30
+
31
+
32
+ def _get(url: str, timeout: float = 1.5) -> Optional[tuple[str, bytes]]:
33
+ try:
34
+ with urllib.request.urlopen(url, timeout=timeout) as res:
35
+ return res.headers.get("content-type", ""), res.read(65536)
36
+ except Exception:
37
+ return None
38
+
39
+
40
+ def _probe(base: str) -> Optional[str]:
41
+ """What answers at this address: 'gemsmap' (API and interface), 'backend' (API only), or None."""
42
+ health = _get(base + "/api/health")
43
+ if not health:
44
+ return None
45
+ try:
46
+ if json.loads(health[1]).get("status") != "ok":
47
+ return None
48
+ except ValueError:
49
+ return None
50
+ page = _get(base + "/")
51
+ return "gemsmap" if page and page[0].startswith("text/html") else "backend"
52
+
53
+
54
+ def _port_free(host: str, port: int) -> bool:
55
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
56
+ try:
57
+ s.bind((host, port))
58
+ return True
59
+ except OSError:
60
+ return False
61
+
62
+
63
+ def _open_when_ready(base: str) -> None:
64
+ for _ in range(240): # up to a minute: the first start imports COBRApy
65
+ if _get(base + "/api/health", timeout=0.5):
66
+ webbrowser.open(base)
67
+ return
68
+ time.sleep(0.25)
69
+
70
+
71
+ def run(host: str, port: int, open_browser: bool) -> int:
72
+ base = f"http://{'127.0.0.1' if host in ('0.0.0.0', '') else host}:{port}"
73
+ found = _probe(base)
74
+ if found == "gemsmap":
75
+ print(f"GEMsMAP is already running at {base}")
76
+ if open_browser:
77
+ webbrowser.open(base)
78
+ return 0
79
+ if found == "backend":
80
+ print(f"Port {port} is used by a GEMsMAP backend without the interface (a development backend?).\n"
81
+ f"Stop it, or start on another port: gemsmap --port {port + 1}")
82
+ return 1
83
+ if not _port_free(host, port):
84
+ print(f"Port {port} is in use by another program. Start on another port: gemsmap --port {port + 1}")
85
+ return 1
86
+
87
+ print(f"Starting GEMsMAP {__version__} ...", flush=True)
88
+ import uvicorn
89
+
90
+ from .server import app, has_web
91
+ if not has_web():
92
+ print("Note: the web interface is not part of this installation (development checkout?). "
93
+ "Only the API runs; use `npm run dev` for the interface.")
94
+ if open_browser and has_web():
95
+ threading.Thread(target=_open_when_ready, args=(base,), daemon=True).start()
96
+ print(f"GEMsMAP {__version__} is running at {base}\n"
97
+ "Keep this window open while you use it. Press Ctrl+C to stop.", flush=True)
98
+ uvicorn.run(app, host=host, port=port, log_level="warning")
99
+ return 0
100
+
101
+
102
+ def diagnose() -> str:
103
+ """Everything a bug report needs, one fact per line."""
104
+ lines = [f"GEMsMAP {__version__}",
105
+ f"Python {platform.python_version()} ({platform.python_implementation()}) at {sys.executable}",
106
+ f"System {platform.platform()} ({platform.machine()})"]
107
+ try:
108
+ import cobra
109
+ import optlang
110
+ solvers = sorted(k for k, v in optlang.available_solvers.items() if v)
111
+ default = str(cobra.Configuration().solver.__name__).split(".")[-1].replace("_interface", "").upper()
112
+ lines.append(f"COBRApy {cobra.__version__}, optlang {optlang.__version__}, solvers: {', '.join(solvers) or 'none'} (default {default})")
113
+ except Exception as e: # a broken scientific stack is exactly what this command must report
114
+ lines.append(f"COBRApy: not importable ({type(e).__name__}: {e})")
115
+ try:
116
+ import fastapi
117
+ import uvicorn
118
+ lines.append(f"FastAPI {fastapi.__version__}, uvicorn {uvicorn.__version__}")
119
+ except Exception as e:
120
+ lines.append(f"FastAPI/uvicorn: not importable ({type(e).__name__}: {e})")
121
+ web = Path(__file__).with_name("web") / "index.html"
122
+ lines.append(f"Web interface: {'included' if web.is_file() else 'not included (development checkout)'}")
123
+ try:
124
+ from cobragui import registry
125
+ from cobragui.services import bigg_service
126
+ lines.append(f"Data folder: {registry.cache_dir().parent}")
127
+ st = bigg_service.status()
128
+ lines.append(f"BiGG tables: installed {st.get('installed', '')}, {st.get('metabolites')} metabolites, {st.get('reactions')} reactions"
129
+ if st.get("available") else "BiGG tables: not installed (optional; run: gemsmap bigg-data)")
130
+ except Exception as e:
131
+ lines.append(f"Data folder: unknown ({type(e).__name__}: {e})")
132
+ return "\n".join(lines)
133
+
134
+
135
+ def bigg_data(folder: Optional[Path]) -> int:
136
+ from cobragui.services import bigg_service
137
+ try:
138
+ st = bigg_service.install_from(folder, log=lambda m: print(m.replace("…", "..."), flush=True))
139
+ except (bigg_service.BiggDataError, OSError) as e:
140
+ print(f"BiGG data not installed: {e}")
141
+ return 1
142
+ print(f"BiGG data installed in {bigg_service.data_dir()}: {st['metabolites']} universal metabolites, {st['reactions']} reactions.\n"
143
+ "A running GEMsMAP uses them from its next search.")
144
+ return 0
145
+
146
+
147
+ def main(argv: Optional[list[str]] = None) -> int:
148
+ # Windows pipes use the legacy code page (cp1252, cp949...): a folder name it cannot encode must not crash us
149
+ for stream in (sys.stdout, sys.stderr):
150
+ try:
151
+ stream.reconfigure(errors="backslashreplace")
152
+ except (AttributeError, ValueError):
153
+ pass
154
+ ap = argparse.ArgumentParser(prog="gemsmap", description="GEMsMAP: integrating constraint-based modeling, metabolic visualization and identity-aware pathway templates.")
155
+ ap.add_argument("--version", action="version", version=f"GEMsMAP {__version__}")
156
+ ap.add_argument("--host", default="127.0.0.1", help="address to listen on (default 127.0.0.1: this computer only)")
157
+ ap.add_argument("--port", type=int, default=DEFAULT_PORT, help=f"port (default {DEFAULT_PORT})")
158
+ ap.add_argument("--no-browser", action="store_true", help="do not open the browser")
159
+ sub = ap.add_subparsers(dest="command", metavar="command")
160
+ sub.add_parser("diagnose", help="print versions, solvers and folders for a bug report")
161
+ bd = sub.add_parser("bigg-data", help="install the BiGG universal tables once (optional, ~19 MB)")
162
+ bd.add_argument("--from", dest="folder", type=Path, help="folder with BiGG metabolite and reaction JSON files you downloaded")
163
+ a = ap.parse_args(argv)
164
+ if a.command == "diagnose":
165
+ print(diagnose())
166
+ return 0
167
+ if a.command == "bigg-data":
168
+ return bigg_data(a.folder)
169
+ try:
170
+ return run(a.host, a.port, not a.no_browser)
171
+ except KeyboardInterrupt:
172
+ return 0
gemsmap/server.py ADDED
@@ -0,0 +1,32 @@
1
+ """The GEMsMAP application: the COBRAGUI API (/api) and the built web interface (/) on one address.
2
+
3
+ The interface is the Vite build (`npm run build` → dist/), copied into gemsmap/web/ when the package is built
4
+ (tools/release/build.py). In a development checkout there is no web/ folder: Vite serves the interface and proxies
5
+ /api to this backend.
6
+ """
7
+ from pathlib import Path
8
+
9
+ from fastapi.staticfiles import StaticFiles
10
+
11
+ from cobragui.main import app
12
+
13
+ WEB = Path(__file__).with_name("web")
14
+
15
+
16
+ class _WebFiles(StaticFiles):
17
+ """Static files; the HTML entry point is never cached, so an upgrade never loads stale asset names."""
18
+
19
+ async def get_response(self, path, scope):
20
+ response = await super().get_response(path, scope)
21
+ if response.headers.get("content-type", "").startswith("text/html"):
22
+ response.headers["Cache-Control"] = "no-cache"
23
+ return response
24
+
25
+
26
+ def has_web() -> bool:
27
+ return (WEB / "index.html").is_file()
28
+
29
+
30
+ if has_web():
31
+ # mounted after the API routes, so /api/... is always matched first
32
+ app.mount("/", _WebFiles(directory=WEB, html=True), name="web")