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 ADDED
@@ -0,0 +1,3 @@
1
+ """Experimental MCP server for driving CODE V over its COM API."""
2
+
3
+ __version__ = "0.1.0"
codev_mcp/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from codev_mcp.server import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
codev_mcp/analyses.py ADDED
@@ -0,0 +1,277 @@
1
+ """Typed image-quality analyses built on CODE V's macro functions.
2
+
3
+ Each returns numbers, not listing text. CODE V signals a failed calculation
4
+ with a negative return value rather than an error, so every row is checked
5
+ and a failed row makes the whole envelope ``ok: false``.
6
+
7
+ Signatures follow the CODE V API Reference Guide (MTF_1FLD, RMS_1FLD) and the
8
+ Macro-PLUS Reference Manual (RMSSPOT).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from typing import Any
15
+
16
+ from codev_mcp.engine import CodeVEngine, Ops
17
+
18
+ # CVMTFTypeEnum, CVMTFWaveEnum, CVRMSFocusModeEnum (values from the type library)
19
+ MTF_DIF, MTF_GEO = 0, 1
20
+ MTF_SIW, MTF_SQW = 0, 1
21
+ FOCUS_NOM, FOCUS_BES = 0, 1
22
+
23
+
24
+ def _fields(cv: Any, fields: list[int] | None) -> list[int]:
25
+ n = int(cv.FieldCount)
26
+ if not fields:
27
+ return list(range(1, n + 1))
28
+ bad = [f for f in fields if not 1 <= f <= n]
29
+ if bad:
30
+ raise ValueError(f"Field numbers {bad} are outside 1..{n}.")
31
+ return list(fields)
32
+
33
+
34
+ def _check(cv: Any, zoom: int, wavelength: int | None = None) -> None:
35
+ if not 1 <= zoom <= int(cv.ZoomCount):
36
+ raise ValueError(f"Zoom {zoom} is outside 1..{int(cv.ZoomCount)}.")
37
+ if wavelength is not None and not 0 <= wavelength <= int(cv.WavelengthCount):
38
+ raise ValueError(f"Wavelength {wavelength} is outside 0..{int(cv.WavelengthCount)}.")
39
+
40
+
41
+ def _finish(rows: list[dict], **extra: Any) -> dict:
42
+ result: dict[str, Any] = {**extra, "results": rows}
43
+ failed = [r for r in rows if "error" in r]
44
+ if failed:
45
+ result["ok"] = False
46
+ result["failed_rows"] = len(failed)
47
+ return result
48
+
49
+
50
+ def rms_spot(engine: CodeVEngine, zoom: int, fields: list[int] | None) -> dict:
51
+ def fn(cv: Any) -> dict:
52
+ _check(cv, zoom)
53
+ rows = []
54
+ for f in _fields(cv, fields):
55
+ value = float(cv.EvaluateExpression(f"RMSSPOT({zoom},{f},1,0.01)"))
56
+ row: dict[str, Any] = {"field": f}
57
+ if value < 0:
58
+ row["error"] = (
59
+ "ray trace failure or no rays through the system"
60
+ if value > -1.5
61
+ else "ray grid not fully clipped: apertures and vignetting disagree"
62
+ )
63
+ else:
64
+ row["rms_spot_diameter"] = value
65
+ rows.append(row)
66
+ return _finish(rows, zoom=zoom, units="lens units", note="Polychromatic, nominal focus.")
67
+
68
+ return engine.with_cv(fn)
69
+
70
+
71
+ def wavefront_error(
72
+ engine: CodeVEngine,
73
+ zoom: int,
74
+ wavelength: int,
75
+ nrd: int,
76
+ best_focus: bool,
77
+ fields: list[int] | None,
78
+ ) -> dict:
79
+ def fn(ops: Ops) -> dict:
80
+ cv = ops.cv
81
+ _check(cv, zoom, wavelength)
82
+ mode = FOCUS_BES if best_focus else FOCUS_NOM
83
+ # CODE V's PSF functions do not support true afocal mode (AFC Y), and
84
+ # their error arrives too late to be kept out of the envelope reliably.
85
+ afocal = float(cv.EvaluateExpression("(AFC)")) == 1.0
86
+ rows = []
87
+ for f in _fields(cv, fields):
88
+ res = cv.RMS_1FLD(zoom, f, wavelength, nrd, mode)
89
+ row: dict[str, Any] = {"field": f}
90
+ if float(res("Result")) < 0:
91
+ row["error"] = "calculation failed (input error or too few rays)"
92
+ else:
93
+ out = res("Output")
94
+ rms = float(out[0])
95
+ row.update(rms_waves=rms, focus_shift=float(out[1]), wavelength_nm=float(out[5]))
96
+ # CODE V's value is exactly the Marechal formula exp(-(2 pi W)^2),
97
+ # which collapses to ~0 well before the image does (6e-13 at
98
+ # 0.84 waves, where the PSF peak is really 0.028).
99
+ row["strehl_marechal"] = float(out[4]) if rms <= MARECHAL_LIMIT else None
100
+ if not best_focus and afocal:
101
+ row["strehl_psf"] = None
102
+ row["strehl_psf_note"] = "PSF not supported by CODE V for afocal systems"
103
+ elif not best_focus:
104
+ value, errors, _ = ops.soft(lambda: _psf_strehl(cv, zoom, f, wavelength))
105
+ row["strehl_psf"] = value
106
+ if value is None:
107
+ row["strehl_psf_note"] = "PSF not available" + (f": {errors[0]}" if errors else "")
108
+ rows.append(row)
109
+ return _finish(
110
+ rows,
111
+ zoom=zoom,
112
+ wavelength="polychromatic" if wavelength == 0 else wavelength,
113
+ focus="best per field" if best_focus else "nominal",
114
+ note="Tilt removed. focus_shift is 0 at nominal focus. strehl_marechal is "
115
+ f"exp(-(2 pi W)^2), given only up to {MARECHAL_LIMIT} waves RMS, where that "
116
+ "approximation holds. strehl_psf is the peak of the computed PSF relative to "
117
+ "a perfect lens, valid at any aberration level; it is computed at nominal "
118
+ "focus only.",
119
+ )
120
+
121
+ return engine.with_ops(fn)
122
+
123
+
124
+ MARECHAL_LIMIT = 0.15 # waves RMS; Strehl about 0.4
125
+
126
+
127
+ ANGLE_UNITS = {"RAD": "radian", "MR": "milliradian", "DEG": "degree", "MIN": "arcminute", "SEC": "arcsecond"}
128
+
129
+
130
+ def _psf_strehl(cv: Any, zoom: int, field: int, wavelength: int) -> float | None:
131
+ """Strehl ratio from the PSF (PSF_1FLD output 8), or None if it fails.
132
+
133
+ Arguments follow the CODE V API guide: nominal focus, 128 grid, defaults
134
+ elsewhere, normalised intensity.
135
+ """
136
+ try:
137
+ res = cv.PSF_1FLD(zoom, field, wavelength, 1, 128, 0, 0, 0.0, 0, 1.0, 0, -1, 0.0)
138
+ except Exception:
139
+ return None
140
+ if float(res("Result")) < 0:
141
+ return None
142
+ value = float(res("Output")[7])
143
+ return value if 0.0 <= value <= 1.0 else None
144
+
145
+
146
+ def mtf(
147
+ engine: CodeVEngine,
148
+ frequencies: list[float],
149
+ zoom: int,
150
+ fields: list[int] | None,
151
+ diffraction: bool,
152
+ nrd: int,
153
+ ) -> dict:
154
+ def fn(cv: Any) -> dict:
155
+ _check(cv, zoom)
156
+ if not frequencies:
157
+ raise ValueError("Give at least one spatial frequency.")
158
+ afocal = float(cv.EvaluateExpression("(AFC)")) == 1.0
159
+ unit = ANGLE_UNITS.get(str(cv.EvaluateExpression("(ADM)")).strip().upper(), "angular unit")
160
+ kind = MTF_DIF if diffraction else MTF_GEO
161
+ rows = []
162
+ for f in _fields(cv, fields):
163
+ for freq in frequencies:
164
+ row: dict[str, Any] = {"field": f, "frequency": float(freq)}
165
+ for azimuth in (0.0, 90.0):
166
+ res = cv.MTF_1FLD(zoom, f, float(freq), azimuth, nrd, kind, MTF_SIW, 0)
167
+ key = f"azimuth_{int(azimuth)}"
168
+ if float(res("Result")) < 0:
169
+ row["error"] = f"calculation failed at azimuth {int(azimuth)}" + (
170
+ f" (afocal: {freq} cycles per {unit} may be beyond the cutoff)" if afocal else "")
171
+ break
172
+ out = res("Output")
173
+ row[key] = {"modulation": float(out[0]), "diffraction_limit": float(out[3])}
174
+ rows.append(row)
175
+ return _finish(
176
+ rows,
177
+ zoom=zoom,
178
+ type="diffraction" if diffraction else "geometrical",
179
+ frequency_units=f"cycles per {unit} (afocal system)" if afocal else "cycles/mm at the image",
180
+ note="Polychromatic, sine-wave object, nominal focus. Azimuth is the "
181
+ "orientation of the spatial frequency at the image, in degrees. For fields "
182
+ "along Y, azimuth 0 is radial (R) and 90 is tangential (T), matching CODE V's "
183
+ "MTF chart.",
184
+ )
185
+
186
+ return engine.with_cv(fn)
187
+
188
+
189
+ # -- field curves and distortion (FIE) -------------------------------------------
190
+
191
+ _FIE_ROW = re.compile(r"^\s*(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+"
192
+ r"(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s*$")
193
+
194
+
195
+ def _parse_fie(text: str) -> dict[int, dict]:
196
+ """Parse FIE's listing into {zoom position: table}.
197
+
198
+ Columns per row: relative field, angle (deg) or object height, X-focus and
199
+ Y-focus at the image surface, the same two displaced by the axial
200
+ defocus, and distortion in per cent.
201
+ """
202
+ tables: dict[int, dict] = {}
203
+ current: dict | None = None
204
+ for line in text.splitlines():
205
+ if m := re.match(r"\s*POSITION\s+(\d+)", line):
206
+ current = {"rows": [], "field_column": None, "wavelength_nm": None, "units": None}
207
+ tables[int(m.group(1))] = current
208
+ if current is None:
209
+ continue
210
+ if m := re.search(r"WAVELENGTH\s+([\d.]+)\s*NM", line):
211
+ current["wavelength_nm"] = float(m.group(1))
212
+ if "RELATIVE" in line and "FOCUS" in line:
213
+ current["field_column"] = "object_height" if "OBJ" in line else "angle_deg"
214
+ if m := re.search(r"Units of focus are\s+(\w+)", line):
215
+ current["units"] = m.group(1).lower()
216
+ if m := _FIE_ROW.match(line):
217
+ rel, fld, x, y, _xd, _yd, dist = (float(v) for v in m.groups())
218
+ current["rows"].append({"relative_field": rel, "field": fld, "x_focus": x, "y_focus": y,
219
+ "distortion_percent": dist})
220
+ return tables
221
+
222
+
223
+ def field_aberrations(engine: CodeVEngine, zoom: int) -> dict:
224
+ def fn(ops: Ops) -> dict:
225
+ _check(ops.cv, zoom)
226
+ r = ops.cmd("FIE; PLO NO; GO")
227
+ text = r["output"]
228
+ if "Field values will not be calculated" in text:
229
+ return {"ok": False, "not_applicable": True,
230
+ "error_detail": "The lens defines only an on-axis field, so there are no field curves or "
231
+ "distortion to report. Add off-axis fields to evaluate them."}
232
+ if "non-rotationally symmetric" in text or "ROTATIONALLY SYMMETRIC FIELD ABERRATIONS" not in text:
233
+ # CODE V's own advice for such systems: FIE is "probably inadequate";
234
+ # its distortion figures are measured from an axis the light does not follow.
235
+ return {"ok": False, "not_applicable": True,
236
+ "error_detail": "The lens is not rotationally symmetric (decentered or tilted), so field curves "
237
+ "and distortion measured from the axis are not meaningful. Use CODE V's Field Map option "
238
+ "instead, e.g. run_command('FMA; GO'), or plot the spot diagram."}
239
+ tables = _parse_fie(text)
240
+ table = tables.get(zoom)
241
+ if not table or not table["rows"]:
242
+ return {"ok": False, "error_detail": f"No field-curve table found for zoom position {zoom}.",
243
+ "listing_start": text[:1500]}
244
+ axis = table["rows"][0]
245
+ rows = []
246
+ for row in table["rows"]:
247
+ rows.append({
248
+ "relative_field": row["relative_field"],
249
+ table["field_column"]: row["field"],
250
+ "distortion_percent": row["distortion_percent"],
251
+ # Focus positions relative to the image surface.
252
+ "sagittal_focus": row["x_focus"],
253
+ "tangential_focus": row["y_focus"],
254
+ # Relative to the on-axis focus: the field curves proper,
255
+ # independent of where the image surface is placed.
256
+ "sagittal_field_curve": row["x_focus"] - axis["x_focus"],
257
+ "tangential_field_curve": row["y_focus"] - axis["y_focus"],
258
+ "astigmatism": row["y_focus"] - row["x_focus"],
259
+ })
260
+ worst = max(rows, key=lambda x: abs(x["distortion_percent"]))
261
+ return {
262
+ "zoom": zoom,
263
+ "wavelength_nm": table["wavelength_nm"],
264
+ "focus_units": table["units"],
265
+ "field_column": table["field_column"],
266
+ "rows": rows,
267
+ "max_distortion": {"percent": worst["distortion_percent"], "relative_field": worst["relative_field"]},
268
+ "sign_convention": "Focus values are distances along the axis from the image surface to the "
269
+ "focus. Negative means the focus lies in front of the image surface, on the lens side; "
270
+ "positive means beyond it. Field curves are the same values measured from the on-axis "
271
+ "focus. astigmatism = tangential - sagittal. Positive distortion is pincushion, "
272
+ "negative is barrel.",
273
+ "note": "From CODE V's FIE option at the reference wavelength, in steps of 10% of the "
274
+ "maximum field (the first field is taken as the axis and the last as the maximum).",
275
+ }
276
+
277
+ return engine.with_ops(fn)
@@ -0,0 +1,369 @@
1
+ """Build the local reference database from your own CODE V install.
2
+
3
+ codev-mcp-build-data # or: python -m codev_mcp.build_data
4
+
5
+ or, from inside Claude, the ``build_reference_data`` tool, which runs the same
6
+ build in a background thread (:data:`background`).
7
+
8
+ Indexes the HTML help for full-text search and loads the glass catalogs into
9
+ one SQLite file. Nothing vendor-derived ships with this package; the database
10
+ is written under ~/codev-mcp (see paths.py) and stays on your machine. No CODE V session
11
+ is started and no licence is used.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import math
19
+ import re
20
+ import sqlite3
21
+ import sys
22
+ import threading
23
+ import time
24
+ import xml.etree.ElementTree as ET
25
+ from html.parser import HTMLParser
26
+ from pathlib import Path
27
+
28
+ from codev_mcp.reference import SCHEMA_VERSION, build_path, find_install_dir
29
+
30
+ # Fraunhofer lines, micrometres
31
+ LAMBDA_D, LAMBDA_F, LAMBDA_C = 0.5875618, 0.4861327, 0.6562725
32
+
33
+ _BLOCK_TAGS = {"p", "div", "tr", "li", "h1", "h2", "h3", "h4", "h5", "h6", "br", "table", "pre"}
34
+ _SKIP_TAGS = {"script", "style", "noscript"}
35
+
36
+
37
+ class _PageText(HTMLParser):
38
+ """Pull the title and the text of ``<div id="page_content">`` from a help page."""
39
+
40
+ def __init__(self) -> None:
41
+ super().__init__(convert_charrefs=True)
42
+ self.title = ""
43
+ self.parts: list[str] = []
44
+ self._in_title = False
45
+ self._depth = 0 # >0 while inside page_content
46
+ self._skip = 0
47
+
48
+ def handle_starttag(self, tag, attrs):
49
+ if tag == "title":
50
+ self._in_title = True
51
+ if tag in _SKIP_TAGS:
52
+ self._skip += 1
53
+ if self._depth:
54
+ if tag == "div":
55
+ self._depth += 1
56
+ if tag in _BLOCK_TAGS:
57
+ self.parts.append("\n")
58
+ elif tag == "td":
59
+ self.parts.append(" ")
60
+ elif tag == "div" and dict(attrs).get("id") == "page_content":
61
+ self._depth = 1
62
+
63
+ def handle_endtag(self, tag):
64
+ if tag == "title":
65
+ self._in_title = False
66
+ if tag in _SKIP_TAGS and self._skip:
67
+ self._skip -= 1
68
+ if self._depth and tag == "div":
69
+ self._depth -= 1
70
+
71
+ def handle_data(self, data):
72
+ if self._in_title:
73
+ self.title += data
74
+ elif self._depth and not self._skip:
75
+ self.parts.append(data)
76
+
77
+ def text(self) -> str:
78
+ text = "".join(self.parts).replace("\xa0", " ")
79
+ text = re.sub(r"[ \t]+", " ", text)
80
+ return re.sub(r"\s*\n\s*", "\n", text).strip()
81
+
82
+
83
+ def build_manual(con: sqlite3.Connection, help_dir: Path) -> dict:
84
+ con.executescript(
85
+ """
86
+ DROP TABLE IF EXISTS pages;
87
+ DROP TABLE IF EXISTS pages_fts;
88
+ CREATE TABLE pages (id INTEGER PRIMARY KEY, section TEXT, path TEXT, title TEXT, body TEXT);
89
+ CREATE VIRTUAL TABLE pages_fts USING fts5(
90
+ title, body, content='pages', content_rowid='id', tokenize='porter unicode61'
91
+ );
92
+ """
93
+ )
94
+ count = skipped = 0
95
+ for section_dir in sorted(p for p in help_dir.iterdir() if p.is_dir()):
96
+ for page in sorted(section_dir.glob("*.html")):
97
+ parser = _PageText()
98
+ try:
99
+ parser.feed(page.read_text(encoding="utf-8", errors="replace"))
100
+ except Exception:
101
+ skipped += 1
102
+ continue
103
+ body = parser.text()
104
+ if len(body) < 40: # navigation stubs and empty pages
105
+ skipped += 1
106
+ continue
107
+ con.execute(
108
+ "INSERT INTO pages (section, path, title, body) VALUES (?, ?, ?, ?)",
109
+ (section_dir.name, f"{section_dir.name}/{page.name}", parser.title.strip(), body),
110
+ )
111
+ count += 1
112
+ con.execute("INSERT INTO pages_fts (rowid, title, body) SELECT id, title, body FROM pages")
113
+ return {"pages": count, "skipped": skipped}
114
+
115
+
116
+ # -- glass ------------------------------------------------------------------
117
+
118
+
119
+ def _index(equation: str, c: list[float], lam: float) -> float | None:
120
+ """Refractive index at ``lam`` micrometres, for the equation forms we know."""
121
+ try:
122
+ l2 = lam * lam
123
+ if "Sellmeier" in equation and "Standard" not in equation:
124
+ # n^2 - 1 = sum K_i l^2 / (l^2 - L_i), coefficients stored K1, L1, K2, L2, ...
125
+ n2 = 1.0 + sum(c[i] * l2 / (l2 - c[i + 1]) for i in range(0, len(c) - 1, 2))
126
+ elif "Laurent" in equation:
127
+ # n^2 = A0 + A1 l^2 + A2 l^-2 + A3 l^-4 + A4 l^-6 + ...
128
+ n2 = c[0] + c[1] * l2 + sum(c[i] * l2 ** -(i - 1) for i in range(2, len(c)))
129
+ else:
130
+ return None
131
+ return math.sqrt(n2) if n2 > 1.0 else None
132
+ except (ZeroDivisionError, IndexError, ValueError, OverflowError):
133
+ return None
134
+
135
+
136
+ def _from_code(code: str) -> tuple[float | None, float | None]:
137
+ """nd and Vd from a six-digit glass code such as 517642."""
138
+ digits = re.sub(r"\D", "", code or "")
139
+ if len(digits) != 6:
140
+ return None, None
141
+ return 1.0 + int(digits[:3]) / 1000.0, int(digits[3:]) / 10.0
142
+
143
+
144
+ def _num(text: str | None) -> float | None:
145
+ try:
146
+ return float(text) if text not in (None, "") else None
147
+ except ValueError:
148
+ return None
149
+
150
+
151
+ def _cte_factor(text: str | None) -> float | None:
152
+ """Catalogs write the CTE factor as ``10e-6`` meaning 10^-6, not 1e-5."""
153
+ m = re.fullmatch(r"\s*10[eE]-(\d+)\s*", text or "")
154
+ return 10.0 ** -int(m.group(1)) if m else _num(text)
155
+
156
+
157
+ def build_glass(con: sqlite3.Connection, glass_dir: Path) -> dict:
158
+ con.executescript(
159
+ """
160
+ DROP TABLE IF EXISTS glasses;
161
+ CREATE TABLE glasses (
162
+ catalog TEXT, name TEXT, glass_code TEXT, nd REAL, vd REAL, index_source TEXT,
163
+ equation TEXT, coefficients TEXT, wl_low_nm REAL, wl_high_nm REAL,
164
+ availability_code TEXT, replacement TEXT, cte REAL, cte_range TEXT,
165
+ properties TEXT
166
+ );
167
+ CREATE INDEX glasses_name ON glasses (name COLLATE NOCASE);
168
+ CREATE INDEX glasses_nd ON glasses (nd);
169
+ """
170
+ )
171
+ stats = {"catalogs": 0, "glasses": 0, "index_computed": 0, "index_from_code": 0, "index_unknown": 0}
172
+ for path in sorted(glass_dir.glob("*.xml")):
173
+ root = ET.parse(path).getroot()
174
+ catalog = root.findtext("Name") or path.stem
175
+ stats["catalogs"] += 1
176
+ for g in root.iter("Glass"):
177
+ equation = g.findtext("EquationType") or ""
178
+ coeffs = [float(x.text) for x in g.iter("Coefficient") if x.text]
179
+ code = g.findtext("NumericName") or ""
180
+ code_nd, code_vd = _from_code(code)
181
+
182
+ nd = vd = None
183
+ source = "unknown"
184
+ n_d, n_f, n_c = (_index(equation, coeffs, lam) for lam in (LAMBDA_D, LAMBDA_F, LAMBDA_C))
185
+ if n_d and n_f and n_c and n_f != n_c:
186
+ calc_vd = (n_d - 1.0) / (n_f - n_c)
187
+ # Trust the computed value only where it agrees with the catalog's
188
+ # own glass code; otherwise the equation form was not what we assumed.
189
+ if code_nd is None or (abs(n_d - code_nd) < 0.0015 and abs(calc_vd - code_vd) < 0.2):
190
+ nd, vd, source = n_d, calc_vd, "computed" if code_nd is not None else "computed, unchecked"
191
+ if nd is None and code_nd is not None:
192
+ nd, vd, source = code_nd, code_vd, "glass code"
193
+ key = "index_computed" if source.startswith("computed") else (
194
+ "index_from_code" if source == "glass code" else "index_unknown"
195
+ )
196
+ stats[key] += 1
197
+
198
+ cte = g.find("LowCTE")
199
+ if cte is None:
200
+ cte = g.find("HighCTE")
201
+ cte_value = cte_range = None
202
+ if cte is not None:
203
+ value, factor = _num(cte.findtext("Value")), _cte_factor(cte.findtext("ExpansionCoeffFactor"))
204
+ if value is not None and factor is not None:
205
+ cte_value = value * factor
206
+ cte_range = f"{cte.findtext('LowerTemperatureLimit')} to {cte.findtext('UpperTemperatureLimit')} C"
207
+ props = {
208
+ p.findtext("Name"): _num(p.findtext("Value"))
209
+ for p in g.iter("Property")
210
+ if _num(p.findtext("Value")) # catalogs store 0 for "not given"
211
+ }
212
+ con.execute(
213
+ "INSERT INTO glasses VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
214
+ (
215
+ catalog, g.findtext("GlassName"), code, nd, vd, source, equation,
216
+ json.dumps(coeffs), _num(g.findtext("LowWavelength")), _num(g.findtext("HighWavelength")),
217
+ g.findtext("Availability"), g.findtext("ReplacementGlass"), cte_value, cte_range,
218
+ json.dumps(props),
219
+ ),
220
+ )
221
+ stats["glasses"] += 1
222
+ return stats
223
+
224
+
225
+ def build_availability(con: sqlite3.Connection) -> dict:
226
+ """Read the glass availability-code table from the indexed manual page.
227
+
228
+ Kept out of the source so no vendor text is committed; it comes from the
229
+ user's own help files like everything else here.
230
+ """
231
+ con.executescript(
232
+ "DROP TABLE IF EXISTS availability;"
233
+ "CREATE TABLE availability (code TEXT PRIMARY KEY, meaning TEXT);"
234
+ )
235
+ if not con.execute("SELECT 1 FROM sqlite_master WHERE name = 'pages'").fetchone():
236
+ return {"codes": 0, "note": "manual not indexed"}
237
+ row = con.execute(
238
+ "SELECT body FROM pages WHERE title LIKE '%Availability Codes%' ORDER BY length(body) LIMIT 1"
239
+ ).fetchone()
240
+ if not row:
241
+ return {"codes": 0, "note": "availability page not found"}
242
+ lines = [s.strip() for s in row[0].splitlines() if s.strip()]
243
+ try:
244
+ start = lines.index("Definition") + 1
245
+ except ValueError:
246
+ return {"codes": 0, "note": "availability table not recognised"}
247
+ pairs = []
248
+ for code, meaning in zip(lines[start::2], lines[start + 1 :: 2]):
249
+ if not code.isdigit():
250
+ break
251
+ pairs.append((code, meaning))
252
+ con.executemany("INSERT OR REPLACE INTO availability VALUES (?, ?)", pairs)
253
+ return {"codes": len(pairs)}
254
+
255
+
256
+ def build(install_dir: Path, out: Path, on_phase=None) -> dict:
257
+ """Build the database at ``out``; ``on_phase(name)`` is told as each part starts."""
258
+ phase = on_phase or (lambda name: None)
259
+ out.parent.mkdir(parents=True, exist_ok=True)
260
+ tmp = out.with_suffix(".tmp")
261
+ tmp.unlink(missing_ok=True)
262
+ con = sqlite3.connect(tmp)
263
+ report: dict = {"install_dir": str(install_dir), "database": str(out)}
264
+ try:
265
+ con.execute("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)")
266
+ help_dir, glass_dir = install_dir / "help", install_dir / "glass"
267
+ phase("manual")
268
+ report["manual"] = build_manual(con, help_dir) if help_dir.is_dir() else "help folder not found; skipped"
269
+ phase("glass")
270
+ report["glass"] = build_glass(con, glass_dir) if glass_dir.is_dir() else "glass folder not found; skipped"
271
+ phase("availability")
272
+ report["availability"] = build_availability(con)
273
+ meta = {
274
+ "schema": str(SCHEMA_VERSION),
275
+ "install_dir": str(install_dir),
276
+ "built": time.strftime("%Y-%m-%d %H:%M:%S"),
277
+ "report": json.dumps(report),
278
+ }
279
+ con.executemany("INSERT INTO meta VALUES (?, ?)", meta.items())
280
+ con.commit()
281
+ finally:
282
+ con.close()
283
+ _replace(tmp, out)
284
+ return report
285
+
286
+
287
+ def _replace(tmp: Path, out: Path, tries: int = 20) -> None:
288
+ """Move the new database into place; a reader holding it open on Windows makes this fail briefly."""
289
+ for i in range(tries):
290
+ try:
291
+ tmp.replace(out)
292
+ return
293
+ except PermissionError:
294
+ if i == tries - 1:
295
+ raise
296
+ time.sleep(0.25)
297
+
298
+
299
+ class BackgroundBuild:
300
+ """One build at a time in a background thread, for the ``build_reference_data`` tool.
301
+
302
+ The build reads only the user's own help and glass files: no CODE V session,
303
+ no licence seat. It takes a few minutes, so the tool starts it and returns,
304
+ and later calls (or ``reference_status``) report its progress.
305
+ """
306
+
307
+ def __init__(self) -> None:
308
+ self._lock = threading.Lock()
309
+ self._thread: threading.Thread | None = None
310
+ self._state: dict = {"state": "not started"}
311
+ self._t0 = 0.0
312
+
313
+ @property
314
+ def running(self) -> bool:
315
+ return self._thread is not None and self._thread.is_alive()
316
+
317
+ def start(self, install_dir: Path, out: Path) -> dict:
318
+ with self._lock:
319
+ if self.running:
320
+ return {**self.status(), "started": False, "note": "A build is already running."}
321
+ self._t0 = time.monotonic()
322
+ self._state = {"state": "running", "phase": "starting", "install_dir": str(install_dir),
323
+ "database": str(out), "started_at": time.strftime("%Y-%m-%d %H:%M:%S")}
324
+ self._thread = threading.Thread(target=self._run, args=(install_dir, out),
325
+ name="codev-mcp-reference-build", daemon=True)
326
+ self._thread.start()
327
+ return {**self.status(), "started": True}
328
+
329
+ def _run(self, install_dir: Path, out: Path) -> None:
330
+ def on_phase(name: str) -> None:
331
+ self._state["phase"] = name
332
+
333
+ try:
334
+ report = build(install_dir, out, on_phase)
335
+ self._state = {**self._state, "state": "done", "report": report}
336
+ except Exception as exc: # reported to the caller, never raised in the thread
337
+ self._state = {**self._state, "state": "failed", "error": f"{type(exc).__name__}: {exc}"}
338
+ self._state.pop("phase", None)
339
+ self._state["seconds"] = round(time.monotonic() - self._t0, 1)
340
+
341
+ def status(self) -> dict:
342
+ out = dict(self._state)
343
+ if out["state"] == "running":
344
+ out["seconds"] = round(time.monotonic() - self._t0, 1)
345
+ return out
346
+
347
+ def wait(self, seconds: float) -> None:
348
+ thread = self._thread
349
+ if thread is not None and seconds > 0:
350
+ thread.join(seconds)
351
+
352
+
353
+ background = BackgroundBuild()
354
+
355
+
356
+ def main() -> int:
357
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
358
+ ap.add_argument("--codev-dir", help="CODE V install folder (default: found from the COM registration)")
359
+ args = ap.parse_args()
360
+ install = Path(args.codev_dir) if args.codev_dir else find_install_dir()
361
+ if not install or not install.is_dir():
362
+ print("Could not find the CODE V install folder. Pass --codev-dir or set CODEV_DIR.", file=sys.stderr)
363
+ return 1
364
+ print(json.dumps(build(install, build_path()), indent=2))
365
+ return 0
366
+
367
+
368
+ if __name__ == "__main__":
369
+ raise SystemExit(main())