codev-mcp 0.1.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.
- codev_mcp/__init__.py +3 -0
- codev_mcp/__main__.py +4 -0
- codev_mcp/analyses.py +277 -0
- codev_mcp/build_data.py +369 -0
- codev_mcp/doctor.py +308 -0
- codev_mcp/edits.py +410 -0
- codev_mcp/engine.py +693 -0
- codev_mcp/montecarlo.py +278 -0
- codev_mcp/optimize.py +279 -0
- codev_mcp/paths.py +35 -0
- codev_mcp/plots.py +142 -0
- codev_mcp/procs.py +73 -0
- codev_mcp/reference.py +315 -0
- codev_mcp/server.py +966 -0
- codev_mcp/settings.py +100 -0
- codev_mcp/snapshots.py +199 -0
- codev_mcp/sysdata.py +262 -0
- codev_mcp/toldata.py +339 -0
- codev_mcp/tolerance.py +363 -0
- codev_mcp-0.1.0.dist-info/METADATA +371 -0
- codev_mcp-0.1.0.dist-info/RECORD +25 -0
- codev_mcp-0.1.0.dist-info/WHEEL +4 -0
- codev_mcp-0.1.0.dist-info/entry_points.txt +4 -0
- codev_mcp-0.1.0.dist-info/licenses/LICENSE +202 -0
- codev_mcp-0.1.0.dist-info/licenses/NOTICE +12 -0
codev_mcp/plots.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Render CODE V plots to PNG so an agent can look at them.
|
|
2
|
+
|
|
3
|
+
CODE V has two kinds of graphics, and they leave a background session in
|
|
4
|
+
different ways:
|
|
5
|
+
|
|
6
|
+
- Legacy vector plots (VIE, RIM, FIE, SPO) are sent to a .plt file with
|
|
7
|
+
``GRA file`` and converted with ``GCV PNG file``.
|
|
8
|
+
- Charts (MTF, PSF) are exported directly with ``WGF PNG file w h``; PSF
|
|
9
|
+
writes one image per field (``name_F1.png``, ...).
|
|
10
|
+
|
|
11
|
+
Without either, background plots are written to a temporary file and deleted
|
|
12
|
+
as soon as the plot event returns. Full-size images are kept on disk; the
|
|
13
|
+
copy returned to the agent is scaled down so it is cheap to look at.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import io
|
|
19
|
+
import os
|
|
20
|
+
import time
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from codev_mcp.engine import CodeVEngine, Ops
|
|
25
|
+
|
|
26
|
+
# kind -> (route, option command, what it shows)
|
|
27
|
+
KINDS: dict[str, tuple[str, str, str]] = {
|
|
28
|
+
"layout": ("legacy", "VIE", "2D lens drawing with ray bundles"),
|
|
29
|
+
"ray_fan": ("legacy", "RIM", "transverse ray aberration fans per field and wavelength"),
|
|
30
|
+
"field_curves": ("legacy", "FIE", "astigmatic field curves, distortion and lateral colour"),
|
|
31
|
+
"spot": ("legacy", "SPO", "spot diagrams per field"),
|
|
32
|
+
"mtf": ("chart", "MTF", "MTF versus spatial frequency per field"),
|
|
33
|
+
"psf": ("chart", "PSF", "point spread function, one image per field"),
|
|
34
|
+
}
|
|
35
|
+
KEEP_FILES = 60
|
|
36
|
+
MAX_GRA_PATH = 78 # CODE V cut "...-layout.plt" to "...-layout.p" at about 80 characters
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _dir(engine: CodeVEngine) -> Path:
|
|
40
|
+
d = Path(engine.start_dir) / "plots"
|
|
41
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
return d
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _prune(folder: Path) -> None:
|
|
46
|
+
files = sorted(folder.glob("*.png"), key=lambda p: p.stat().st_mtime)
|
|
47
|
+
for f in files[:-KEEP_FILES]:
|
|
48
|
+
f.unlink(missing_ok=True)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _wait_for(path: Path, timeout_s: float = 20.0) -> bool:
|
|
52
|
+
"""Wait until ``path`` exists and its size has stopped changing."""
|
|
53
|
+
deadline, last = time.time() + timeout_s, -1
|
|
54
|
+
while time.time() < deadline:
|
|
55
|
+
size = path.stat().st_size if path.is_file() else -1
|
|
56
|
+
if size > 0 and size == last:
|
|
57
|
+
return True
|
|
58
|
+
last = size
|
|
59
|
+
time.sleep(0.3)
|
|
60
|
+
return path.is_file()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _shrink(path: Path, max_pixels: int) -> tuple[bytes, list[int], list[int]]:
|
|
64
|
+
from PIL import Image as PILImage
|
|
65
|
+
|
|
66
|
+
with PILImage.open(path) as im:
|
|
67
|
+
full = list(im.size)
|
|
68
|
+
im = im.convert("RGB")
|
|
69
|
+
im.thumbnail((max_pixels, max_pixels))
|
|
70
|
+
buf = io.BytesIO()
|
|
71
|
+
im.save(buf, format="PNG", optimize=True)
|
|
72
|
+
return buf.getvalue(), full, list(im.size)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def render(engine: CodeVEngine, kind: str, settings: str | None, max_pixels: int) -> dict:
|
|
76
|
+
"""Render one plot. Returns the envelope plus ``images``: [(png bytes, info)]."""
|
|
77
|
+
if kind not in KINDS:
|
|
78
|
+
return {"ok": False, "error_detail": f"kind must be one of {sorted(KINDS)}."}
|
|
79
|
+
route, option, _ = KINDS[kind]
|
|
80
|
+
max_pixels = max(400, min(int(max_pixels), 3000))
|
|
81
|
+
extra = f"; {settings.strip().strip(';')}" if settings and settings.strip() else ""
|
|
82
|
+
folder = _dir(engine)
|
|
83
|
+
stem = f"{time.strftime('%m%d%H%M%S')}{int(time.time() * 1000) % 1000:03d}-{kind}"
|
|
84
|
+
# CODE V truncates GRA file names beyond about 80 characters, so pass
|
|
85
|
+
# short paths relative to its starting directory, not absolute ones. An
|
|
86
|
+
# attached window has its own working folder, so there the path must be
|
|
87
|
+
# absolute, and it has to fit.
|
|
88
|
+
if engine.mode == "attached":
|
|
89
|
+
rel = str(folder / stem)
|
|
90
|
+
if len(rel) + 4 > MAX_GRA_PATH:
|
|
91
|
+
return {"ok": False, "error_detail": f"The plot folder path is too long for CODE V while attached to a "
|
|
92
|
+
f"window ({len(rel) + 4} characters; CODE V truncates beyond {MAX_GRA_PATH}). Set "
|
|
93
|
+
"CODEV_START_DIR to a shorter folder, or detach to plot from a background session."}
|
|
94
|
+
else:
|
|
95
|
+
rel = os.path.join("plots", stem)
|
|
96
|
+
|
|
97
|
+
def fn(ops: Ops) -> dict:
|
|
98
|
+
errors: list[str] = []
|
|
99
|
+
if route == "legacy":
|
|
100
|
+
plt = folder / f"{stem}.plt"
|
|
101
|
+
r = ops.cmd(f'GRA "{rel}.plt"')
|
|
102
|
+
errors += r["errors"]
|
|
103
|
+
try:
|
|
104
|
+
r = ops.cmd(f"{option}{extra}; GO")
|
|
105
|
+
errors += r["errors"]
|
|
106
|
+
finally:
|
|
107
|
+
ops.cmd("GRA T") # always send graphics back to the default
|
|
108
|
+
if plt.is_file() and plt.stat().st_size > 0:
|
|
109
|
+
errors += ops.cmd(f'GCV PNG "{rel}.plt"')["errors"]
|
|
110
|
+
# GCV returns before the PNG is written (about 2 s for a layout).
|
|
111
|
+
_wait_for(folder / f"{stem}.png")
|
|
112
|
+
plt.unlink(missing_ok=True)
|
|
113
|
+
else:
|
|
114
|
+
r = ops.cmd(f'WGF PNG "{rel}.png" 1600 1200')
|
|
115
|
+
errors += r["errors"]
|
|
116
|
+
try:
|
|
117
|
+
r = ops.cmd(f"{option}{extra}; GO")
|
|
118
|
+
errors += r["errors"]
|
|
119
|
+
finally:
|
|
120
|
+
ops.cmd("WGF NO")
|
|
121
|
+
produced = sorted(folder.glob(f"{stem}*.png"))
|
|
122
|
+
if not produced:
|
|
123
|
+
return {"ok": False, "kind": kind, "error_detail": "CODE V produced no image.",
|
|
124
|
+
"codev_errors": errors}
|
|
125
|
+
return {"kind": kind, "files": [str(p) for p in produced]}
|
|
126
|
+
|
|
127
|
+
result = engine.with_ops(fn)
|
|
128
|
+
images: list[tuple[bytes, dict]] = []
|
|
129
|
+
for f in result.get("files", []):
|
|
130
|
+
p = Path(f)
|
|
131
|
+
data, full, shown = _shrink(p, max_pixels)
|
|
132
|
+
info = {"file": str(p), "full_size": full, "returned_size": shown}
|
|
133
|
+
if p.stem.rsplit("_", 1)[-1].startswith("F") and p.stem.rsplit("_", 1)[-1][1:].isdigit():
|
|
134
|
+
info["field"] = int(p.stem.rsplit("_", 1)[-1][1:])
|
|
135
|
+
images.append((data, info))
|
|
136
|
+
_prune(folder)
|
|
137
|
+
result["images"] = images
|
|
138
|
+
return result
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def describe_kinds() -> dict[str, Any]:
|
|
142
|
+
return {k: v[2] for k, v in KINDS.items()}
|
codev_mcp/procs.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Minimal Windows process listing, used to clean up after a failed CODE V start.
|
|
2
|
+
|
|
3
|
+
When anything between creating the CODE V COM object and a healthy session
|
|
4
|
+
fails (an invalid starting directory, a licence error), the COM server
|
|
5
|
+
(``cvgui.exe -Embedding``) and its ``codevm.exe`` can stay running and hold a
|
|
6
|
+
licence seat. Releasing the COM reference does not reliably end them when an
|
|
7
|
+
event sink is attached, so the engine notes which ``cvgui.exe`` processes
|
|
8
|
+
existed before the start and ends the new ones if the start fails.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import ctypes
|
|
14
|
+
import ctypes.wintypes as wt
|
|
15
|
+
|
|
16
|
+
TH32CS_SNAPPROCESS = 0x00000002
|
|
17
|
+
PROCESS_TERMINATE = 0x0001
|
|
18
|
+
INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class _Entry(ctypes.Structure):
|
|
22
|
+
_fields_ = [
|
|
23
|
+
("dwSize", wt.DWORD),
|
|
24
|
+
("cntUsage", wt.DWORD),
|
|
25
|
+
("th32ProcessID", wt.DWORD),
|
|
26
|
+
("th32DefaultHeapID", ctypes.c_size_t),
|
|
27
|
+
("th32ModuleID", wt.DWORD),
|
|
28
|
+
("cntThreads", wt.DWORD),
|
|
29
|
+
("th32ParentProcessID", wt.DWORD),
|
|
30
|
+
("pcPriClassBase", ctypes.c_long),
|
|
31
|
+
("dwFlags", wt.DWORD),
|
|
32
|
+
("szExeFile", ctypes.c_wchar * 260),
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def processes() -> list[tuple[int, int, str]]:
|
|
37
|
+
"""(pid, parent pid, lower-case exe name) for every process."""
|
|
38
|
+
k32 = ctypes.windll.kernel32
|
|
39
|
+
snap = k32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
|
|
40
|
+
if snap == INVALID_HANDLE_VALUE:
|
|
41
|
+
return []
|
|
42
|
+
out = []
|
|
43
|
+
try:
|
|
44
|
+
entry = _Entry()
|
|
45
|
+
entry.dwSize = ctypes.sizeof(_Entry)
|
|
46
|
+
ok = k32.Process32FirstW(snap, ctypes.byref(entry))
|
|
47
|
+
while ok:
|
|
48
|
+
out.append((entry.th32ProcessID, entry.th32ParentProcessID, entry.szExeFile.lower()))
|
|
49
|
+
ok = k32.Process32NextW(snap, ctypes.byref(entry))
|
|
50
|
+
finally:
|
|
51
|
+
k32.CloseHandle(snap)
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def pids(name: str) -> set[int]:
|
|
56
|
+
name = name.lower()
|
|
57
|
+
return {pid for pid, _, exe in processes() if exe == name}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def terminate_tree(pid: int) -> list[int]:
|
|
61
|
+
"""End ``pid`` and its direct children; return the pids ended."""
|
|
62
|
+
k32 = ctypes.windll.kernel32
|
|
63
|
+
targets = [child for child, parent, _ in processes() if parent == pid] + [pid]
|
|
64
|
+
ended = []
|
|
65
|
+
for target in targets:
|
|
66
|
+
handle = k32.OpenProcess(PROCESS_TERMINATE, False, target)
|
|
67
|
+
if handle:
|
|
68
|
+
try:
|
|
69
|
+
if k32.TerminateProcess(handle, 1):
|
|
70
|
+
ended.append(target)
|
|
71
|
+
finally:
|
|
72
|
+
k32.CloseHandle(handle)
|
|
73
|
+
return ended
|
codev_mcp/reference.py
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
"""Query the local reference database: manual search and glass lookup.
|
|
2
|
+
|
|
3
|
+
Engine-free and licence-free. The database is built by ``codev-mcp-build-data``
|
|
4
|
+
from the user's own CODE V install; until then every function returns a typed
|
|
5
|
+
"unavailable" result and the rest of the server keeps working.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import functools
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import sqlite3
|
|
14
|
+
import threading
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from codev_mcp import settings
|
|
19
|
+
from codev_mcp.paths import LEGACY_DATA_DIR, data_dir
|
|
20
|
+
|
|
21
|
+
SCHEMA_VERSION = 1
|
|
22
|
+
BUILD_HINT = ("Build it from your CODE V install with the `build_reference_data` tool "
|
|
23
|
+
"(or `codev-mcp-build-data` in a terminal); it takes a few minutes and no licence.")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build_path() -> Path:
|
|
27
|
+
"""Where codev-mcp-build-data writes the database."""
|
|
28
|
+
return data_dir() / "reference.db"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def db_path() -> Path:
|
|
32
|
+
"""The database to read: the current location, else one built before the move."""
|
|
33
|
+
current = build_path()
|
|
34
|
+
legacy = LEGACY_DATA_DIR / "reference.db"
|
|
35
|
+
if not current.is_file() and not settings.env("CODEV_MCP_DATA") and legacy.is_file():
|
|
36
|
+
return legacy
|
|
37
|
+
return current
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def find_install_dir(progid: str | None = None) -> Path | None:
|
|
41
|
+
"""Locate CODE V from CODEV_DIR, else from where the COM server is registered."""
|
|
42
|
+
configured = settings.codev_dir()
|
|
43
|
+
if configured:
|
|
44
|
+
return configured
|
|
45
|
+
try:
|
|
46
|
+
import winreg
|
|
47
|
+
except ImportError:
|
|
48
|
+
return None
|
|
49
|
+
progid = progid or settings.progid()
|
|
50
|
+
views = (winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY)
|
|
51
|
+
hives = (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE) # per-user wins, as in COM
|
|
52
|
+
|
|
53
|
+
def read(hive, sub, view):
|
|
54
|
+
try:
|
|
55
|
+
with winreg.OpenKey(hive, sub, 0, winreg.KEY_READ | view) as key:
|
|
56
|
+
return winreg.QueryValue(key, None)
|
|
57
|
+
except OSError:
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
clsid = next(
|
|
61
|
+
(v for h in hives for w in views if (v := read(h, rf"Software\Classes\{progid}\CLSID", w))), None
|
|
62
|
+
)
|
|
63
|
+
if not clsid:
|
|
64
|
+
return None
|
|
65
|
+
for hive in hives:
|
|
66
|
+
for view in views:
|
|
67
|
+
exe = read(hive, rf"Software\Classes\CLSID\{clsid}\LocalServer32", view)
|
|
68
|
+
if exe:
|
|
69
|
+
folder = Path(exe.strip().strip('"').split('"')[0]).parent
|
|
70
|
+
if folder.is_dir():
|
|
71
|
+
return folder
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
_opened = threading.local()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _connect() -> sqlite3.Connection | None:
|
|
79
|
+
"""A read-only connection, closed when the public function that opened it returns.
|
|
80
|
+
|
|
81
|
+
``with con:`` only ends a transaction; it does not close. An open
|
|
82
|
+
connection on Windows stops a rebuild from replacing the file, so every
|
|
83
|
+
public function that connects is wrapped in :func:`_closes_connections`.
|
|
84
|
+
"""
|
|
85
|
+
path = db_path()
|
|
86
|
+
if not path.is_file():
|
|
87
|
+
return None
|
|
88
|
+
con = sqlite3.connect(f"file:{path.as_posix()}?mode=ro", uri=True)
|
|
89
|
+
con.row_factory = sqlite3.Row
|
|
90
|
+
opened = getattr(_opened, "cons", None)
|
|
91
|
+
if opened is not None:
|
|
92
|
+
opened.append(con)
|
|
93
|
+
return con
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _closes_connections(fn):
|
|
97
|
+
@functools.wraps(fn)
|
|
98
|
+
def wrapper(*args, **kwargs):
|
|
99
|
+
outer = getattr(_opened, "cons", None)
|
|
100
|
+
_opened.cons = []
|
|
101
|
+
try:
|
|
102
|
+
return fn(*args, **kwargs)
|
|
103
|
+
finally:
|
|
104
|
+
for con in _opened.cons:
|
|
105
|
+
con.close()
|
|
106
|
+
_opened.cons = outer
|
|
107
|
+
return wrapper
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _unavailable(what: str) -> dict:
|
|
111
|
+
return {"ok": False, "unavailable": True, "error": f"The {what} reference data is not built. {BUILD_HINT}"}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _has_table(con: sqlite3.Connection, name: str) -> bool:
|
|
115
|
+
return bool(con.execute("SELECT 1 FROM sqlite_master WHERE name = ?", (name,)).fetchone())
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@_closes_connections
|
|
119
|
+
def status() -> dict:
|
|
120
|
+
con = _connect()
|
|
121
|
+
if con is None:
|
|
122
|
+
return {"ok": True, "built": False, "database": str(db_path()), "hint": BUILD_HINT}
|
|
123
|
+
with con:
|
|
124
|
+
meta = dict(con.execute("SELECT key, value FROM meta").fetchall())
|
|
125
|
+
out: dict[str, Any] = {
|
|
126
|
+
"ok": True,
|
|
127
|
+
"built": True,
|
|
128
|
+
"database": str(db_path()),
|
|
129
|
+
"built_at": meta.get("built"),
|
|
130
|
+
"install_dir": meta.get("install_dir"),
|
|
131
|
+
}
|
|
132
|
+
if _has_table(con, "pages"):
|
|
133
|
+
out["manual_pages"] = con.execute("SELECT count(*) FROM pages").fetchone()[0]
|
|
134
|
+
out["manual_sections"] = [r[0] for r in con.execute("SELECT DISTINCT section FROM pages ORDER BY 1")]
|
|
135
|
+
if _has_table(con, "glasses"):
|
|
136
|
+
out["glasses"] = con.execute("SELECT count(*) FROM glasses").fetchone()[0]
|
|
137
|
+
out["glass_catalogs"] = [r[0] for r in con.execute("SELECT DISTINCT catalog FROM glasses ORDER BY 1")]
|
|
138
|
+
return out
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# -- manual -------------------------------------------------------------------
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _fts_query(query: str, joiner: str) -> str:
|
|
145
|
+
terms = re.findall(r"[A-Za-z0-9_]+", query)
|
|
146
|
+
return joiner.join(f'"{t}"' for t in terms)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@_closes_connections
|
|
150
|
+
def search_manual(query: str, section: str | None = None, limit: int = 8) -> dict:
|
|
151
|
+
con = _connect()
|
|
152
|
+
if con is None or not _has_table(con, "pages"):
|
|
153
|
+
return _unavailable("manual")
|
|
154
|
+
if not re.search(r"[A-Za-z0-9]", query or ""):
|
|
155
|
+
return {"ok": False, "error": "Give at least one word to search for."}
|
|
156
|
+
limit = max(1, min(int(limit), 25))
|
|
157
|
+
sql = """
|
|
158
|
+
SELECT p.id, p.section, p.title, length(p.body) AS chars,
|
|
159
|
+
snippet(pages_fts, 1, '[', ']', ' ... ', 24) AS snippet
|
|
160
|
+
FROM pages_fts JOIN pages p ON p.id = pages_fts.rowid
|
|
161
|
+
WHERE pages_fts MATCH ? {section}
|
|
162
|
+
ORDER BY bm25(pages_fts, 8.0, 1.0) LIMIT ?
|
|
163
|
+
""".format(section="AND p.section = ?" if section else "")
|
|
164
|
+
with con:
|
|
165
|
+
matched = "all words"
|
|
166
|
+
for joiner, label in ((" AND ", "all words"), (" OR ", "any word")):
|
|
167
|
+
args: list[Any] = [_fts_query(query, joiner)]
|
|
168
|
+
if section:
|
|
169
|
+
args.append(section)
|
|
170
|
+
rows = con.execute(sql, [*args, limit]).fetchall()
|
|
171
|
+
matched = label
|
|
172
|
+
if rows:
|
|
173
|
+
break
|
|
174
|
+
return {
|
|
175
|
+
"ok": True,
|
|
176
|
+
"query": query,
|
|
177
|
+
"matched": matched,
|
|
178
|
+
"results": [
|
|
179
|
+
{"page_id": r["id"], "section": r["section"], "title": r["title"],
|
|
180
|
+
"chars": r["chars"], "snippet": r["snippet"].replace("\n", " ")}
|
|
181
|
+
for r in rows
|
|
182
|
+
],
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@_closes_connections
|
|
187
|
+
def read_manual_page(page_id: int, offset: int = 0, max_chars: int = 6000) -> dict:
|
|
188
|
+
con = _connect()
|
|
189
|
+
if con is None or not _has_table(con, "pages"):
|
|
190
|
+
return _unavailable("manual")
|
|
191
|
+
with con:
|
|
192
|
+
row = con.execute("SELECT * FROM pages WHERE id = ?", (page_id,)).fetchone()
|
|
193
|
+
if row is None:
|
|
194
|
+
return {"ok": False, "error": f"No manual page with id {page_id}."}
|
|
195
|
+
offset = max(0, int(offset))
|
|
196
|
+
max_chars = max(200, min(int(max_chars), 20000))
|
|
197
|
+
body = row["body"]
|
|
198
|
+
chunk = body[offset : offset + max_chars]
|
|
199
|
+
out = {
|
|
200
|
+
"ok": True, "page_id": page_id, "section": row["section"], "title": row["title"],
|
|
201
|
+
"path": row["path"], "total_chars": len(body), "offset": offset, "text": chunk,
|
|
202
|
+
}
|
|
203
|
+
if offset + len(chunk) < len(body):
|
|
204
|
+
out["next_offset"] = offset + len(chunk)
|
|
205
|
+
return out
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
# -- glass --------------------------------------------------------------------
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _availability(con: sqlite3.Connection) -> dict[str, str]:
|
|
212
|
+
if not _has_table(con, "availability"):
|
|
213
|
+
return {}
|
|
214
|
+
return dict(con.execute("SELECT code, meaning FROM availability").fetchall())
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _glass_row(row: sqlite3.Row, full: bool, avail: dict[str, str]) -> dict:
|
|
218
|
+
out: dict[str, Any] = {
|
|
219
|
+
"catalog": row["catalog"],
|
|
220
|
+
"name": row["name"],
|
|
221
|
+
"glass_code": row["glass_code"],
|
|
222
|
+
"nd": None if row["nd"] is None else round(row["nd"], 6),
|
|
223
|
+
"vd": None if row["vd"] is None else round(row["vd"], 3),
|
|
224
|
+
"index_source": row["index_source"],
|
|
225
|
+
"availability_code": row["availability_code"],
|
|
226
|
+
}
|
|
227
|
+
if row["availability_code"] in avail:
|
|
228
|
+
out["availability"] = avail[row["availability_code"]]
|
|
229
|
+
if row["replacement"]:
|
|
230
|
+
out["replacement"] = row["replacement"]
|
|
231
|
+
if full:
|
|
232
|
+
out.update(
|
|
233
|
+
wavelength_range_nm=[row["wl_low_nm"], row["wl_high_nm"]],
|
|
234
|
+
cte_ppm_per_K=None if row["cte"] is None else round(row["cte"] * 1e6, 3),
|
|
235
|
+
cte_range=row["cte_range"],
|
|
236
|
+
dispersion_equation=row["equation"],
|
|
237
|
+
dispersion_coefficients=json.loads(row["coefficients"]),
|
|
238
|
+
properties=json.loads(row["properties"]),
|
|
239
|
+
)
|
|
240
|
+
return out
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
@_closes_connections
|
|
244
|
+
def lookup_glass(name: str, catalog: str | None = None) -> dict:
|
|
245
|
+
con = _connect()
|
|
246
|
+
if con is None or not _has_table(con, "glasses"):
|
|
247
|
+
return _unavailable("glass")
|
|
248
|
+
# Accept CODE V's NAME_CATALOG form as well as a bare name.
|
|
249
|
+
wanted = (name or "").strip()
|
|
250
|
+
if not catalog and "_" in wanted:
|
|
251
|
+
head, _, tail = wanted.rpartition("_")
|
|
252
|
+
with con:
|
|
253
|
+
if con.execute("SELECT 1 FROM glasses WHERE catalog = ? COLLATE NOCASE", (tail,)).fetchone():
|
|
254
|
+
wanted, catalog = head, tail
|
|
255
|
+
sql, args = "SELECT * FROM glasses WHERE name = ? COLLATE NOCASE", [wanted]
|
|
256
|
+
if catalog:
|
|
257
|
+
sql += " AND catalog = ? COLLATE NOCASE"
|
|
258
|
+
args.append(catalog)
|
|
259
|
+
# Names differ in punctuation between vendors and CODE V (N-BK7 vs NBK7).
|
|
260
|
+
squeezed = re.sub(r"[^A-Za-z0-9]", "", wanted)
|
|
261
|
+
with con:
|
|
262
|
+
rows = con.execute(sql + " ORDER BY catalog", args).fetchall()
|
|
263
|
+
if not rows and squeezed != wanted:
|
|
264
|
+
args[0] = squeezed
|
|
265
|
+
rows = con.execute(sql + " ORDER BY catalog", args).fetchall()
|
|
266
|
+
avail = _availability(con)
|
|
267
|
+
if rows:
|
|
268
|
+
return {"ok": True, "matches": [_glass_row(r, full=True, avail=avail) for r in rows]}
|
|
269
|
+
near = con.execute(
|
|
270
|
+
"SELECT * FROM glasses WHERE replace(replace(name, '-', ''), ' ', '') LIKE ? ORDER BY length(name) LIMIT 10",
|
|
271
|
+
(f"%{squeezed}%",),
|
|
272
|
+
).fetchall()
|
|
273
|
+
return {
|
|
274
|
+
"ok": False,
|
|
275
|
+
"error": f"No glass named {name!r}" + (f" in {catalog}" if catalog else "") + ".",
|
|
276
|
+
"similar": [_glass_row(r, full=False, avail=avail) for r in near],
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
@_closes_connections
|
|
281
|
+
def search_glass(
|
|
282
|
+
nd: float, vd: float, nd_tolerance: float, vd_tolerance: float,
|
|
283
|
+
catalogs: list[str] | None, limit: int, include_discontinued: bool = False,
|
|
284
|
+
) -> dict:
|
|
285
|
+
con = _connect()
|
|
286
|
+
if con is None or not _has_table(con, "glasses"):
|
|
287
|
+
return _unavailable("glass")
|
|
288
|
+
limit = max(1, min(int(limit), 50))
|
|
289
|
+
sql = "SELECT * FROM glasses WHERE nd BETWEEN ? AND ? AND vd BETWEEN ? AND ?"
|
|
290
|
+
args: list[Any] = [nd - nd_tolerance, nd + nd_tolerance, vd - vd_tolerance, vd + vd_tolerance]
|
|
291
|
+
if catalogs:
|
|
292
|
+
sql += f" AND upper(catalog) IN ({','.join('?' * len(catalogs))})"
|
|
293
|
+
args += [c.upper() for c in catalogs]
|
|
294
|
+
if nd_tolerance <= 0 or vd_tolerance <= 0:
|
|
295
|
+
return {"ok": False, "error": "Tolerances must be positive."}
|
|
296
|
+
with con:
|
|
297
|
+
rows = con.execute(sql, args).fetchall()
|
|
298
|
+
avail = _availability(con)
|
|
299
|
+
skipped = 0
|
|
300
|
+
if not include_discontinued and avail:
|
|
301
|
+
kept = [r for r in rows if "discontinued" not in avail.get(r["availability_code"], "").lower()]
|
|
302
|
+
skipped, rows = len(rows) - len(kept), kept
|
|
303
|
+
|
|
304
|
+
# Rank by distance in the glass map, each axis scaled by its tolerance.
|
|
305
|
+
def distance(r: sqlite3.Row) -> float:
|
|
306
|
+
return ((r["nd"] - nd) / nd_tolerance) ** 2 + ((r["vd"] - vd) / vd_tolerance) ** 2
|
|
307
|
+
|
|
308
|
+
rows.sort(key=distance)
|
|
309
|
+
return {
|
|
310
|
+
"ok": True,
|
|
311
|
+
"target": {"nd": nd, "vd": vd},
|
|
312
|
+
"found": len(rows),
|
|
313
|
+
"discontinued_skipped": skipped,
|
|
314
|
+
"results": [_glass_row(r, full=False, avail=avail) for r in rows[:limit]],
|
|
315
|
+
}
|