terraproof 0.0.0-stage → 0.4.1

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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +356 -2
  3. package/bin/terraproof.js +4 -0
  4. package/dist/router/apply.js +147 -0
  5. package/dist/router/classify.js +111 -0
  6. package/dist/router/explain.js +9 -0
  7. package/dist/router/index.js +272 -0
  8. package/dist/router/resolve.js +239 -0
  9. package/dist/router/score.js +60 -0
  10. package/dist/router/types.js +1 -0
  11. package/dist/router/validate.js +81 -0
  12. package/instructions/engineering.md +14 -0
  13. package/instructions/security.md +14 -0
  14. package/instructions/simplicity.md +13 -0
  15. package/package.json +65 -4
  16. package/routing/DOMAIN_ROUTING.md +161 -0
  17. package/routing/ROUTER_DESIGN.md +173 -0
  18. package/routing/SKILL_MANIFEST.md +86 -0
  19. package/routing/checks.json +121 -0
  20. package/routing/collections.json +47 -0
  21. package/routing/registry.json +2211 -0
  22. package/routing/rules.json +64 -0
  23. package/skills/accuracy-assessment/SKILL.md +213 -0
  24. package/skills/accuracy-assessment/UPSTREAM.md +7 -0
  25. package/skills/accuracy-assessment/references/stratified-estimator.md +127 -0
  26. package/skills/accuracy-assessment/skill.json +103 -0
  27. package/skills/brainstorming/SKILL.md +250 -0
  28. package/skills/brainstorming/UPSTREAM.md +29 -0
  29. package/skills/brainstorming/scripts/frame-template.html +213 -0
  30. package/skills/brainstorming/scripts/helper.js +167 -0
  31. package/skills/brainstorming/scripts/server.cjs +723 -0
  32. package/skills/brainstorming/scripts/start-server.sh +209 -0
  33. package/skills/brainstorming/scripts/stop-server.sh +120 -0
  34. package/skills/brainstorming/skill.json +73 -0
  35. package/skills/brainstorming/spec-document-reviewer-prompt.md +49 -0
  36. package/skills/brainstorming/visual-companion.md +299 -0
  37. package/skills/crs-and-units/SKILL.md +200 -0
  38. package/skills/crs-and-units/UPSTREAM.md +7 -0
  39. package/skills/crs-and-units/skill.json +74 -0
  40. package/skills/design-postgis-tables/SKILL.md +494 -0
  41. package/skills/design-postgis-tables/UPSTREAM.md +21 -0
  42. package/skills/design-postgis-tables/skill.json +90 -0
  43. package/skills/gdal/SKILL.md +125 -0
  44. package/skills/gdal/UPSTREAM.md +22 -0
  45. package/skills/gdal/references/gdal-recipes.md +103 -0
  46. package/skills/gdal/skill.json +66 -0
  47. package/skills/geomaster/README.md +105 -0
  48. package/skills/geomaster/SKILL.md +366 -0
  49. package/skills/geomaster/UPSTREAM.md +21 -0
  50. package/skills/geomaster/references/advanced-gis.md +376 -0
  51. package/skills/geomaster/references/big-data.md +363 -0
  52. package/skills/geomaster/references/code-examples.md +531 -0
  53. package/skills/geomaster/references/coordinate-systems.md +364 -0
  54. package/skills/geomaster/references/core-libraries.md +273 -0
  55. package/skills/geomaster/references/data-sources.md +330 -0
  56. package/skills/geomaster/references/gis-software.md +369 -0
  57. package/skills/geomaster/references/industry-applications.md +420 -0
  58. package/skills/geomaster/references/machine-learning.md +462 -0
  59. package/skills/geomaster/references/programming-languages.md +456 -0
  60. package/skills/geomaster/references/remote-sensing.md +370 -0
  61. package/skills/geomaster/references/scientific-domains.md +416 -0
  62. package/skills/geomaster/references/specialized-topics.md +428 -0
  63. package/skills/geomaster/references/troubleshooting.md +439 -0
  64. package/skills/geomaster/skill.json +157 -0
  65. package/skills/geopandas/SKILL.md +250 -0
  66. package/skills/geopandas/UPSTREAM.md +22 -0
  67. package/skills/geopandas/references/crs-management.md +231 -0
  68. package/skills/geopandas/references/data-io.md +323 -0
  69. package/skills/geopandas/references/data-structures.md +207 -0
  70. package/skills/geopandas/references/geometric-operations.md +262 -0
  71. package/skills/geopandas/references/spatial-analysis.md +294 -0
  72. package/skills/geopandas/references/visualization.md +230 -0
  73. package/skills/geopandas/scripts/_common.py +605 -0
  74. package/skills/geopandas/scripts/crs_reprojection_plan.py +210 -0
  75. package/skills/geopandas/scripts/export_plan.py +305 -0
  76. package/skills/geopandas/scripts/geometry_validity_report.py +227 -0
  77. package/skills/geopandas/scripts/sensitive_coordinates_checklist.py +230 -0
  78. package/skills/geopandas/scripts/spatial_join_audit.py +368 -0
  79. package/skills/geopandas/scripts/vector_inventory.py +140 -0
  80. package/skills/geopandas/skill.json +116 -0
  81. package/skills/geoparquet-validation/SKILL.md +125 -0
  82. package/skills/geoparquet-validation/UPSTREAM.md +24 -0
  83. package/skills/geoparquet-validation/references/distribution-best-practices.md +118 -0
  84. package/skills/geoparquet-validation/references/gpio-commands.md +264 -0
  85. package/skills/geoparquet-validation/references/tool-comparison.md +155 -0
  86. package/skills/geoparquet-validation/skill.json +71 -0
  87. package/skills/geospatial-data-discovery/SKILL.md +49 -0
  88. package/skills/geospatial-data-discovery/UPSTREAM.md +15 -0
  89. package/skills/geospatial-data-discovery/skill.json +51 -0
  90. package/skills/geospatial-frontend/SKILL.md +86 -0
  91. package/skills/geospatial-frontend/UPSTREAM.md +23 -0
  92. package/skills/geospatial-frontend/references/design-system.md +283 -0
  93. package/skills/geospatial-frontend/references/user-preferences.md +96 -0
  94. package/skills/geospatial-frontend/skill.json +87 -0
  95. package/skills/geozarr/SKILL.md +244 -0
  96. package/skills/geozarr/UPSTREAM.md +21 -0
  97. package/skills/geozarr/skill.json +97 -0
  98. package/skills/networkx/SKILL.md +440 -0
  99. package/skills/networkx/UPSTREAM.md +22 -0
  100. package/skills/networkx/references/algorithms.md +384 -0
  101. package/skills/networkx/references/generators.md +385 -0
  102. package/skills/networkx/references/graph-basics.md +284 -0
  103. package/skills/networkx/references/io.md +457 -0
  104. package/skills/networkx/references/visualization.md +531 -0
  105. package/skills/networkx/skill.json +93 -0
  106. package/skills/raster-processing/SKILL.md +222 -0
  107. package/skills/raster-processing/UPSTREAM.md +7 -0
  108. package/skills/raster-processing/skill.json +81 -0
  109. package/skills/sar-basics/SKILL.md +202 -0
  110. package/skills/sar-basics/UPSTREAM.md +7 -0
  111. package/skills/sar-basics/references/calibration-lut.md +98 -0
  112. package/skills/sar-basics/skill.json +97 -0
  113. package/skills/satellite-preprocessing/SKILL.md +241 -0
  114. package/skills/satellite-preprocessing/UPSTREAM.md +7 -0
  115. package/skills/satellite-preprocessing/skill.json +84 -0
  116. package/skills/scientific-visualization/SKILL.md +285 -0
  117. package/skills/scientific-visualization/UPSTREAM.md +25 -0
  118. package/skills/scientific-visualization/assets/color_palettes.py +263 -0
  119. package/skills/scientific-visualization/assets/nature.mplstyle +68 -0
  120. package/skills/scientific-visualization/assets/presentation.mplstyle +68 -0
  121. package/skills/scientific-visualization/assets/publication.mplstyle +77 -0
  122. package/skills/scientific-visualization/assets/publisher_profiles.json +269 -0
  123. package/skills/scientific-visualization/references/color_palettes.md +227 -0
  124. package/skills/scientific-visualization/references/journal_requirements.md +169 -0
  125. package/skills/scientific-visualization/references/matplotlib_examples.md +336 -0
  126. package/skills/scientific-visualization/references/publication_guidelines.md +196 -0
  127. package/skills/scientific-visualization/references/sources.md +76 -0
  128. package/skills/scientific-visualization/scripts/_common.py +136 -0
  129. package/skills/scientific-visualization/scripts/export_plan.py +493 -0
  130. package/skills/scientific-visualization/scripts/figure_export.py +642 -0
  131. package/skills/scientific-visualization/scripts/image_metadata.py +731 -0
  132. package/skills/scientific-visualization/scripts/palette_audit.py +327 -0
  133. package/skills/scientific-visualization/scripts/style_presets.py +501 -0
  134. package/skills/scientific-visualization/scripts/style_preview.py +232 -0
  135. package/skills/scientific-visualization/skill.json +95 -0
  136. package/skills/spectral-indices/SKILL.md +235 -0
  137. package/skills/spectral-indices/UPSTREAM.md +7 -0
  138. package/skills/spectral-indices/skill.json +88 -0
  139. package/skills/stac-and-cloud-access/SKILL.md +209 -0
  140. package/skills/stac-and-cloud-access/UPSTREAM.md +7 -0
  141. package/skills/stac-and-cloud-access/references/run-manifest.md +94 -0
  142. package/skills/stac-and-cloud-access/skill.json +98 -0
  143. package/skills/statistical-analysis/SKILL.md +446 -0
  144. package/skills/statistical-analysis/UPSTREAM.md +24 -0
  145. package/skills/statistical-analysis/references/assumptions_and_diagnostics.md +379 -0
  146. package/skills/statistical-analysis/references/bayesian_statistics.md +686 -0
  147. package/skills/statistical-analysis/references/effect_sizes_and_power.md +649 -0
  148. package/skills/statistical-analysis/references/reporting_standards.md +482 -0
  149. package/skills/statistical-analysis/references/test_selection_guide.md +129 -0
  150. package/skills/statistical-analysis/scripts/assumption_checks.py +652 -0
  151. package/skills/statistical-analysis/skill.json +127 -0
  152. package/skills/systematic-debugging/SKILL.md +283 -0
  153. package/skills/systematic-debugging/UPSTREAM.md +28 -0
  154. package/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
  155. package/skills/systematic-debugging/condition-based-waiting.md +115 -0
  156. package/skills/systematic-debugging/defense-in-depth.md +122 -0
  157. package/skills/systematic-debugging/find-polluter.sh +72 -0
  158. package/skills/systematic-debugging/root-cause-tracing.md +169 -0
  159. package/skills/systematic-debugging/skill.json +88 -0
  160. package/skills/time-series-and-change/SKILL.md +217 -0
  161. package/skills/time-series-and-change/UPSTREAM.md +7 -0
  162. package/skills/time-series-and-change/references/change-methods.md +42 -0
  163. package/skills/time-series-and-change/skill.json +116 -0
  164. package/skills/vector-quality/SKILL.md +204 -0
  165. package/skills/vector-quality/UPSTREAM.md +7 -0
  166. package/skills/vector-quality/skill.json +82 -0
  167. package/skills/verification/SKILL.md +120 -0
  168. package/skills/verification/UPSTREAM.md +31 -0
  169. package/skills/verification/skill.json +67 -0
  170. package/skills/writing-plans/SKILL.md +171 -0
  171. package/skills/writing-plans/UPSTREAM.md +23 -0
  172. package/skills/writing-plans/plan-document-reviewer-prompt.md +49 -0
  173. package/skills/writing-plans/skill.json +80 -0
  174. package/sources/SOURCES.md +374 -0
  175. package/third_party/isaaccorley-geospatial-skills/LICENSE +176 -0
  176. package/third_party/isaaccorley-geospatial-skills/NOTICE.md +17 -0
  177. package/third_party/kdense-scientific-agent-skills/LICENSE +21 -0
  178. package/third_party/kdense-scientific-agent-skills/NOTICE.md +19 -0
  179. package/third_party/superpowers/LICENSE +21 -0
  180. package/third_party/superpowers/NOTICE.md +17 -0
  181. package/third_party/timescale-pg-aiguide/LICENSE +176 -0
  182. package/third_party/timescale-pg-aiguide/NOTICE.md +14 -0
@@ -0,0 +1,731 @@
1
+ #!/usr/bin/env python3
2
+ """Inspect figure/image metadata and screen it against explicit constraints.
3
+
4
+ The tool is network-free. Pillow is loaded only for raster inputs and pypdf is
5
+ loaded only for PDF inputs. A successful screen is not a journal-compliance
6
+ claim.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import math
13
+ import re
14
+ import sys
15
+ import warnings
16
+ import xml.etree.ElementTree as ET
17
+ from pathlib import Path
18
+ from typing import Any, Iterable
19
+
20
+ from _common import (
21
+ MAX_INPUT_BYTES,
22
+ CliError,
23
+ checked_input_file,
24
+ emit_json,
25
+ positive_float,
26
+ positive_int,
27
+ )
28
+
29
+ SCHEMA_VERSION = "1.0"
30
+ DEFAULT_MAX_PIXELS = 100_000_000
31
+ MAX_XML_ELEMENTS = 100_000
32
+ MAX_SVG_BYTES = 20 * 1024 * 1024
33
+ FORMAT_ALIASES = {
34
+ "jpg": "JPEG",
35
+ "jpeg": "JPEG",
36
+ "tif": "TIFF",
37
+ "tiff": "TIFF",
38
+ "svg": "SVG",
39
+ "pdf": "PDF",
40
+ "eps": "EPS",
41
+ "ps": "PS",
42
+ "png": "PNG",
43
+ "webp": "WEBP",
44
+ }
45
+ VECTOR_SUFFIXES = {".svg", ".pdf", ".eps", ".ps"}
46
+ LENGTH_RE = re.compile(
47
+ r"^\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)"
48
+ r"\s*(px|pt|pc|in|cm|mm)?\s*$"
49
+ )
50
+
51
+
52
+ def _finite_number(value: Any) -> float | None:
53
+ """Convert a scalar or rational-like value to a finite float."""
54
+ try:
55
+ number = float(value)
56
+ except (TypeError, ValueError, OverflowError):
57
+ return None
58
+ return number if math.isfinite(number) else None
59
+
60
+
61
+ def _dpi_pair(value: Any) -> tuple[float | None, float | None]:
62
+ """Normalize common Pillow DPI metadata representations."""
63
+ if isinstance(value, (tuple, list)) and len(value) >= 2:
64
+ return _finite_number(value[0]), _finite_number(value[1])
65
+ scalar = _finite_number(value)
66
+ return scalar, scalar
67
+
68
+
69
+ def _length_to_inches(value: str | None) -> tuple[float | None, str | None]:
70
+ """Parse an SVG/CSS absolute length using the CSS 96 px/in convention."""
71
+ if value is None:
72
+ return None, None
73
+ match = LENGTH_RE.match(value)
74
+ if not match:
75
+ return None, None
76
+ number = float(match.group(1))
77
+ unit = (match.group(2) or "px").lower()
78
+ factors = {
79
+ "px": 1.0 / 96.0,
80
+ "pt": 1.0 / 72.0,
81
+ "pc": 1.0 / 6.0,
82
+ "in": 1.0,
83
+ "cm": 1.0 / 2.54,
84
+ "mm": 1.0 / 25.4,
85
+ }
86
+ return number * factors[unit], unit
87
+
88
+
89
+ def _base_metadata(path: Path) -> dict[str, Any]:
90
+ info = path.stat()
91
+ return {
92
+ "path": str(path),
93
+ "name": path.name,
94
+ "suffix": path.suffix.lower(),
95
+ "size_bytes": info.st_size,
96
+ }
97
+
98
+
99
+ def inspect_raster(path: Path, *, max_pixels: int) -> dict[str, Any]:
100
+ """Inspect a raster image with Pillow without decoding all pixel data."""
101
+ try:
102
+ from PIL import Image
103
+ except ImportError as exc:
104
+ raise CliError(
105
+ "Pillow is required for raster metadata; "
106
+ "run with --with 'pillow==12.3.0'"
107
+ ) from exc
108
+
109
+ previous_limit = Image.MAX_IMAGE_PIXELS
110
+ Image.MAX_IMAGE_PIXELS = max_pixels
111
+ try:
112
+ with warnings.catch_warnings():
113
+ warnings.simplefilter("error", Image.DecompressionBombWarning)
114
+ with Image.open(path) as image:
115
+ width, height = image.size
116
+ if width * height > max_pixels:
117
+ raise CliError(
118
+ f"image has {width * height} pixels; "
119
+ f"limit is {max_pixels}"
120
+ )
121
+ dpi_x, dpi_y = _dpi_pair(image.info.get("dpi"))
122
+ icc = image.info.get("icc_profile")
123
+ metadata = {
124
+ "format": (image.format or path.suffix.lstrip(".")).upper(),
125
+ "kind": "raster",
126
+ "width_px": int(width),
127
+ "height_px": int(height),
128
+ "pixel_count": int(width * height),
129
+ "mode": image.mode,
130
+ "bands": list(image.getbands()),
131
+ "has_alpha": "A" in image.getbands()
132
+ or "transparency" in image.info,
133
+ "frames": int(getattr(image, "n_frames", 1)),
134
+ "dpi_x": dpi_x,
135
+ "dpi_y": dpi_y,
136
+ "width_mm_from_metadata": (
137
+ width / dpi_x * 25.4 if dpi_x and dpi_x > 0 else None
138
+ ),
139
+ "height_mm_from_metadata": (
140
+ height / dpi_y * 25.4 if dpi_y and dpi_y > 0 else None
141
+ ),
142
+ "icc_profile_present": bool(icc),
143
+ "icc_profile_bytes": len(icc) if isinstance(icc, bytes) else 0,
144
+ "compression": image.info.get("compression"),
145
+ "exif_present": bool(image.info.get("exif")),
146
+ }
147
+ image.verify()
148
+ return metadata
149
+ except Image.DecompressionBombWarning as exc:
150
+ raise CliError(f"image exceeds safe pixel limits: {exc}") from exc
151
+ except Image.DecompressionBombError as exc:
152
+ raise CliError(f"image exceeds safe pixel limits: {exc}") from exc
153
+ except OSError as exc:
154
+ raise CliError(f"Pillow could not inspect {path}: {exc}") from exc
155
+ finally:
156
+ Image.MAX_IMAGE_PIXELS = previous_limit
157
+
158
+
159
+ def inspect_svg(path: Path) -> dict[str, Any]:
160
+ """Inspect SVG dimensions and resource types with bounded XML parsing."""
161
+ if path.stat().st_size > MAX_SVG_BYTES:
162
+ raise CliError(
163
+ f"SVG is {path.stat().st_size} bytes; limit is {MAX_SVG_BYTES} bytes"
164
+ )
165
+ try:
166
+ payload = path.read_bytes()
167
+ if re.search(br"<!ENTITY\b", payload, flags=re.IGNORECASE) or re.search(
168
+ br"<!DOCTYPE[^>]*\[", payload, flags=re.IGNORECASE | re.DOTALL
169
+ ):
170
+ raise CliError("SVG internal DTD/entity declarations are not allowed")
171
+ root = ET.fromstring(payload)
172
+ except (ET.ParseError, OSError) as exc:
173
+ raise CliError(f"invalid SVG/XML input: {exc}") from exc
174
+
175
+ width_raw = root.get("width")
176
+ height_raw = root.get("height")
177
+ width_in, width_unit = _length_to_inches(width_raw)
178
+ height_in, height_unit = _length_to_inches(height_raw)
179
+ viewbox_raw = root.get("viewBox")
180
+ viewbox: list[float] | None = None
181
+ if viewbox_raw:
182
+ try:
183
+ values = [float(item) for item in re.split(r"[\s,]+", viewbox_raw.strip())]
184
+ except ValueError:
185
+ values = []
186
+ if len(values) == 4 and all(math.isfinite(item) for item in values):
187
+ viewbox = values
188
+
189
+ element_count = 0
190
+ text_count = 0
191
+ image_count = 0
192
+ external_images = 0
193
+ for element in root.iter():
194
+ element_count += 1
195
+ if element_count > MAX_XML_ELEMENTS:
196
+ raise CliError(
197
+ f"SVG has more than {MAX_XML_ELEMENTS} elements; refusing input"
198
+ )
199
+ local_name = element.tag.rsplit("}", 1)[-1].lower()
200
+ if local_name == "text":
201
+ text_count += 1
202
+ elif local_name == "image":
203
+ image_count += 1
204
+ href = (
205
+ element.get("href")
206
+ or element.get("{http://www.w3.org/1999/xlink}href")
207
+ or ""
208
+ )
209
+ if href and not href.startswith("data:"):
210
+ external_images += 1
211
+
212
+ return {
213
+ "format": "SVG",
214
+ "kind": "vector",
215
+ "width_raw": width_raw,
216
+ "height_raw": height_raw,
217
+ "width_unit": width_unit,
218
+ "height_unit": height_unit,
219
+ "width_mm": width_in * 25.4 if width_in is not None else None,
220
+ "height_mm": height_in * 25.4 if height_in is not None else None,
221
+ "viewbox": viewbox,
222
+ "dpi_x": None,
223
+ "dpi_y": None,
224
+ "mode": None,
225
+ "element_count": element_count,
226
+ "text_element_count": text_count,
227
+ "image_element_count": image_count,
228
+ "external_image_count": external_images,
229
+ "note": (
230
+ "SVG is resolution-independent except for embedded raster images; "
231
+ "external image resources were counted but not fetched."
232
+ ),
233
+ }
234
+
235
+
236
+ def _pdf_font_report(page: Any) -> dict[str, Any]:
237
+ """Return a conservative first-page PDF font resource report."""
238
+ try:
239
+ resources = page.get("/Resources")
240
+ resources = resources.get_object() if resources else None
241
+ fonts = resources.get("/Font") if resources else None
242
+ fonts = fonts.get_object() if fonts else None
243
+ except Exception:
244
+ fonts = None
245
+ if not fonts:
246
+ return {
247
+ "resource_count": 0,
248
+ "embedded_count": 0,
249
+ "unembedded_count": 0,
250
+ "unknown_count": 0,
251
+ "all_embedded": None,
252
+ "fonts": [],
253
+ }
254
+
255
+ def embedded_status(font: Any) -> bool | None:
256
+ try:
257
+ subtype = str(font.get("/Subtype", ""))
258
+ if subtype == "/Type3":
259
+ # Type 3 glyph programs live in the PDF CharProcs dictionary.
260
+ return True
261
+ candidates = [font]
262
+ descendants = font.get("/DescendantFonts")
263
+ if descendants:
264
+ candidates.extend(
265
+ reference.get_object() for reference in descendants
266
+ )
267
+ saw_descriptor = False
268
+ for candidate in candidates:
269
+ descriptor = candidate.get("/FontDescriptor")
270
+ descriptor = descriptor.get_object() if descriptor else None
271
+ if descriptor:
272
+ saw_descriptor = True
273
+ if any(
274
+ descriptor.get(key)
275
+ for key in ("/FontFile", "/FontFile2", "/FontFile3")
276
+ ):
277
+ return True
278
+ return False if saw_descriptor else None
279
+ except Exception:
280
+ return None
281
+
282
+ records: list[dict[str, Any]] = []
283
+ for resource_name, reference in fonts.items():
284
+ try:
285
+ font = reference.get_object()
286
+ embedded = embedded_status(font)
287
+ records.append(
288
+ {
289
+ "resource": str(resource_name),
290
+ "base_font": str(font.get("/BaseFont", "")),
291
+ "subtype": str(font.get("/Subtype", "")),
292
+ "embedded": embedded,
293
+ }
294
+ )
295
+ except Exception:
296
+ records.append(
297
+ {
298
+ "resource": str(resource_name),
299
+ "base_font": "",
300
+ "subtype": "",
301
+ "embedded": None,
302
+ }
303
+ )
304
+ definite = [item["embedded"] for item in records if item["embedded"] is not None]
305
+ unknown_count = sum(item["embedded"] is None for item in records)
306
+ return {
307
+ "resource_count": len(records),
308
+ "embedded_count": sum(item is True for item in definite),
309
+ "unembedded_count": sum(item is False for item in definite),
310
+ "unknown_count": unknown_count,
311
+ "all_embedded": (
312
+ None
313
+ if not definite or unknown_count
314
+ else all(item is True for item in definite)
315
+ ),
316
+ "fonts": records,
317
+ "scope": "first page resource dictionary only",
318
+ }
319
+
320
+
321
+ def inspect_pdf(path: Path) -> dict[str, Any]:
322
+ """Inspect PDF page dimensions and first-page font resources with pypdf."""
323
+ try:
324
+ from pypdf import PdfReader
325
+ except ImportError as exc:
326
+ raise CliError(
327
+ "pypdf is required for PDF metadata; "
328
+ "run with --with 'pypdf==6.14.2'"
329
+ ) from exc
330
+ try:
331
+ reader = PdfReader(path, strict=False)
332
+ if reader.is_encrypted:
333
+ try:
334
+ unlocked = reader.decrypt("")
335
+ except Exception:
336
+ unlocked = 0
337
+ if not unlocked:
338
+ return {
339
+ "format": "PDF",
340
+ "kind": "vector-container",
341
+ "encrypted": True,
342
+ "page_count": None,
343
+ "width_mm": None,
344
+ "height_mm": None,
345
+ "dpi_x": None,
346
+ "dpi_y": None,
347
+ "mode": None,
348
+ "font_resources": None,
349
+ "note": "Encrypted PDF could not be inspected without a password.",
350
+ }
351
+ page_count = len(reader.pages)
352
+ if page_count < 1:
353
+ raise CliError("PDF has no pages")
354
+ page = reader.pages[0]
355
+ width_pt = float(page.mediabox.width)
356
+ height_pt = float(page.mediabox.height)
357
+ return {
358
+ "format": "PDF",
359
+ "kind": "vector-container",
360
+ "encrypted": bool(reader.is_encrypted),
361
+ "page_count": page_count,
362
+ "first_page_width_pt": width_pt,
363
+ "first_page_height_pt": height_pt,
364
+ "width_mm": width_pt / 72.0 * 25.4,
365
+ "height_mm": height_pt / 72.0 * 25.4,
366
+ "dpi_x": None,
367
+ "dpi_y": None,
368
+ "mode": None,
369
+ "font_resources": _pdf_font_report(page),
370
+ "note": (
371
+ "PDF page size and font resources do not establish the "
372
+ "resolution of embedded raster images."
373
+ ),
374
+ }
375
+ except CliError:
376
+ raise
377
+ except Exception as exc:
378
+ raise CliError(f"pypdf could not inspect {path}: {exc}") from exc
379
+
380
+
381
+ def inspect_eps(path: Path) -> dict[str, Any]:
382
+ """Inspect an EPS/PS bounding box without invoking PostScript."""
383
+ size = path.stat().st_size
384
+ with path.open("rb") as handle:
385
+ prefix = handle.read(min(size, 128 * 1024))
386
+ suffix = b""
387
+ if size > len(prefix):
388
+ handle.seek(max(0, size - 128 * 1024))
389
+ suffix = handle.read(128 * 1024)
390
+ text = (prefix + b"\n" + suffix).decode("latin-1", errors="replace")
391
+ matches = re.findall(
392
+ r"^%%(?:HiRes)?BoundingBox:\s+"
393
+ r"([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s+"
394
+ r"([+-]?\d+(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?)\s*$",
395
+ text,
396
+ flags=re.MULTILINE,
397
+ )
398
+ bbox = [float(value) for value in matches[-1]] if matches else None
399
+ width_pt = bbox[2] - bbox[0] if bbox else None
400
+ height_pt = bbox[3] - bbox[1] if bbox else None
401
+ return {
402
+ "format": "EPS" if path.suffix.lower() == ".eps" else "PS",
403
+ "kind": "vector-container",
404
+ "bounding_box_pt": bbox,
405
+ "width_mm": width_pt / 72.0 * 25.4 if width_pt is not None else None,
406
+ "height_mm": (
407
+ height_pt / 72.0 * 25.4 if height_pt is not None else None
408
+ ),
409
+ "dpi_x": None,
410
+ "dpi_y": None,
411
+ "mode": None,
412
+ "note": "PostScript was not executed; only DSC bounding-box text was read.",
413
+ }
414
+
415
+
416
+ def inspect_file(
417
+ value: str | Path,
418
+ *,
419
+ max_bytes: int = MAX_INPUT_BYTES,
420
+ max_pixels: int = DEFAULT_MAX_PIXELS,
421
+ ) -> dict[str, Any]:
422
+ """Inspect a supported local figure/image and return structured metadata."""
423
+ path = checked_input_file(value, max_bytes=max_bytes)
424
+ suffix = path.suffix.lower()
425
+ if suffix == ".svg":
426
+ metadata = inspect_svg(path)
427
+ elif suffix == ".pdf":
428
+ metadata = inspect_pdf(path)
429
+ elif suffix in {".eps", ".ps"}:
430
+ metadata = inspect_eps(path)
431
+ else:
432
+ metadata = inspect_raster(path, max_pixels=max_pixels)
433
+ return {
434
+ "schema_version": SCHEMA_VERSION,
435
+ "input": _base_metadata(path),
436
+ "metadata": metadata,
437
+ }
438
+
439
+
440
+ def _normalize_formats(values: Iterable[str]) -> list[str]:
441
+ normalized: list[str] = []
442
+ for value in values:
443
+ for item in value.split(","):
444
+ name = item.strip().lower().lstrip(".")
445
+ if not name:
446
+ continue
447
+ normalized.append(FORMAT_ALIASES.get(name, name.upper()))
448
+ return sorted(set(normalized))
449
+
450
+
451
+ def _check(
452
+ name: str,
453
+ status: str,
454
+ *,
455
+ actual: Any,
456
+ expected: Any,
457
+ detail: str,
458
+ ) -> dict[str, Any]:
459
+ return {
460
+ "name": name,
461
+ "status": status,
462
+ "actual": actual,
463
+ "expected": expected,
464
+ "detail": detail,
465
+ }
466
+
467
+
468
+ def screen_metadata(
469
+ report: dict[str, Any],
470
+ *,
471
+ expected_formats: Iterable[str] = (),
472
+ expected_modes: Iterable[str] = (),
473
+ min_dpi: float | None = None,
474
+ max_dpi: float | None = None,
475
+ min_width_px: int | None = None,
476
+ max_width_px: int | None = None,
477
+ min_height_px: int | None = None,
478
+ max_height_px: int | None = None,
479
+ max_file_bytes: int | None = None,
480
+ target_width_mm: float | None = None,
481
+ alpha_policy: str | None = None,
482
+ ) -> dict[str, Any]:
483
+ """Apply only caller-supplied constraints to an inspection report."""
484
+ metadata = report["metadata"]
485
+ checks: list[dict[str, Any]] = []
486
+
487
+ formats = _normalize_formats(expected_formats)
488
+ if formats:
489
+ actual = str(metadata.get("format", "")).upper()
490
+ checks.append(
491
+ _check(
492
+ "format",
493
+ "pass" if actual in formats else "fail",
494
+ actual=actual,
495
+ expected=formats,
496
+ detail="File format is compared with the explicit allow-list.",
497
+ )
498
+ )
499
+
500
+ modes = sorted(
501
+ {
502
+ item.strip().upper()
503
+ for value in expected_modes
504
+ for item in value.split(",")
505
+ if item.strip()
506
+ }
507
+ )
508
+ if modes:
509
+ actual_mode = metadata.get("mode")
510
+ status = (
511
+ "unknown"
512
+ if actual_mode is None
513
+ else ("pass" if str(actual_mode).upper() in modes else "fail")
514
+ )
515
+ checks.append(
516
+ _check(
517
+ "mode",
518
+ status,
519
+ actual=actual_mode,
520
+ expected=modes,
521
+ detail="Vector containers generally do not expose one image mode.",
522
+ )
523
+ )
524
+
525
+ width_px = metadata.get("width_px")
526
+ height_px = metadata.get("height_px")
527
+ for name, actual, minimum, maximum in (
528
+ ("width_px", width_px, min_width_px, max_width_px),
529
+ ("height_px", height_px, min_height_px, max_height_px),
530
+ ):
531
+ if minimum is None and maximum is None:
532
+ continue
533
+ if actual is None:
534
+ status = "unknown"
535
+ elif minimum is not None and actual < minimum:
536
+ status = "fail"
537
+ elif maximum is not None and actual > maximum:
538
+ status = "fail"
539
+ else:
540
+ status = "pass"
541
+ checks.append(
542
+ _check(
543
+ name,
544
+ status,
545
+ actual=actual,
546
+ expected={"min": minimum, "max": maximum},
547
+ detail="Pixel dimensions are available for raster inputs.",
548
+ )
549
+ )
550
+
551
+ dpi_x = metadata.get("dpi_x")
552
+ dpi_y = metadata.get("dpi_y")
553
+ effective_dpi = None
554
+ if target_width_mm is not None and width_px is not None:
555
+ effective_dpi = width_px / (target_width_mm / 25.4)
556
+ actual_dpi = effective_dpi
557
+ dpi_basis = "effective at target width"
558
+ if actual_dpi is None and dpi_x and dpi_y:
559
+ actual_dpi = min(float(dpi_x), float(dpi_y))
560
+ dpi_basis = "embedded metadata"
561
+ if min_dpi is not None or max_dpi is not None:
562
+ if actual_dpi is None:
563
+ status = "unknown"
564
+ elif (
565
+ min_dpi is not None
566
+ and actual_dpi < min_dpi
567
+ and not math.isclose(actual_dpi, min_dpi, rel_tol=1e-12, abs_tol=1e-9)
568
+ ):
569
+ status = "fail"
570
+ elif (
571
+ max_dpi is not None
572
+ and actual_dpi > max_dpi
573
+ and not math.isclose(actual_dpi, max_dpi, rel_tol=1e-12, abs_tol=1e-9)
574
+ ):
575
+ status = "fail"
576
+ else:
577
+ status = "pass"
578
+ checks.append(
579
+ _check(
580
+ "dpi",
581
+ status,
582
+ actual=actual_dpi,
583
+ expected={"min": min_dpi, "max": max_dpi},
584
+ detail=(
585
+ f"DPI basis: {dpi_basis}. Metadata DPI is not a quality "
586
+ "measure; effective DPI depends on final physical size."
587
+ ),
588
+ )
589
+ )
590
+
591
+ if max_file_bytes is not None:
592
+ actual_bytes = report["input"]["size_bytes"]
593
+ checks.append(
594
+ _check(
595
+ "file_size",
596
+ "pass" if actual_bytes <= max_file_bytes else "fail",
597
+ actual=actual_bytes,
598
+ expected={"max": max_file_bytes},
599
+ detail="File size is measured from the local input.",
600
+ )
601
+ )
602
+
603
+ if alpha_policy is not None:
604
+ if alpha_policy not in {"allow", "forbid", "require"}:
605
+ raise CliError("alpha_policy must be allow, forbid, or require")
606
+ has_alpha = metadata.get("has_alpha")
607
+ if has_alpha is None:
608
+ alpha_status = "unknown"
609
+ elif alpha_policy == "allow":
610
+ alpha_status = "pass"
611
+ elif alpha_policy == "forbid":
612
+ alpha_status = "pass" if not has_alpha else "fail"
613
+ else:
614
+ alpha_status = "pass" if has_alpha else "fail"
615
+ checks.append(
616
+ _check(
617
+ "alpha",
618
+ alpha_status,
619
+ actual=has_alpha,
620
+ expected=alpha_policy,
621
+ detail=(
622
+ "Alpha is detected for raster modes/transparency metadata. "
623
+ "Vector transparency requires rendered-content inspection."
624
+ ),
625
+ )
626
+ )
627
+
628
+ counts = {
629
+ status: sum(item["status"] == status for item in checks)
630
+ for status in ("pass", "fail", "warning", "unknown")
631
+ }
632
+ screened = dict(report)
633
+ screened["checks"] = checks
634
+ screened["screening_summary"] = counts
635
+ screened["notice"] = (
636
+ "This deterministic metadata screen checks only the supplied constraints. "
637
+ "It does not verify visual quality, scientific integrity, accessibility, "
638
+ "embedded-raster resolution in vector files, or journal compliance."
639
+ )
640
+ return screened
641
+
642
+
643
+ def build_parser() -> argparse.ArgumentParser:
644
+ parser = argparse.ArgumentParser(
645
+ description=(
646
+ "Inspect local raster, SVG, PDF, EPS, or PS metadata and optionally "
647
+ "screen it against explicit constraints. No network access is used."
648
+ )
649
+ )
650
+ parser.add_argument("input", help="local figure/image file (symlinks rejected)")
651
+ parser.add_argument(
652
+ "--format",
653
+ dest="formats",
654
+ action="append",
655
+ default=[],
656
+ help="allowed format; repeat or use comma-separated values",
657
+ )
658
+ parser.add_argument(
659
+ "--mode",
660
+ dest="modes",
661
+ action="append",
662
+ default=[],
663
+ help="allowed raster mode (for example RGB,L); repeat as needed",
664
+ )
665
+ parser.add_argument("--min-dpi", type=positive_float)
666
+ parser.add_argument("--max-dpi", type=positive_float)
667
+ parser.add_argument(
668
+ "--target-width-mm",
669
+ type=positive_float,
670
+ help="calculate effective raster DPI at this final width",
671
+ )
672
+ parser.add_argument("--min-width-px", type=positive_int)
673
+ parser.add_argument("--max-width-px", type=positive_int)
674
+ parser.add_argument("--min-height-px", type=positive_int)
675
+ parser.add_argument("--max-height-px", type=positive_int)
676
+ parser.add_argument("--max-file-bytes", type=positive_int)
677
+ parser.add_argument(
678
+ "--alpha-policy",
679
+ choices=("allow", "forbid", "require"),
680
+ help="optional raster alpha/transparency screen",
681
+ )
682
+ parser.add_argument(
683
+ "--max-input-bytes",
684
+ type=positive_int,
685
+ default=MAX_INPUT_BYTES,
686
+ help=f"input byte limit (default: {MAX_INPUT_BYTES})",
687
+ )
688
+ parser.add_argument(
689
+ "--max-pixels",
690
+ type=positive_int,
691
+ default=DEFAULT_MAX_PIXELS,
692
+ help=f"raster pixel limit (default: {DEFAULT_MAX_PIXELS})",
693
+ )
694
+ parser.add_argument("--output", help="optional JSON report path")
695
+ parser.add_argument(
696
+ "--force", action="store_true", help="overwrite an existing JSON report"
697
+ )
698
+ return parser
699
+
700
+
701
+ def main(argv: list[str] | None = None) -> int:
702
+ parser = build_parser()
703
+ try:
704
+ args = parser.parse_args(argv)
705
+ report = inspect_file(
706
+ args.input,
707
+ max_bytes=args.max_input_bytes,
708
+ max_pixels=args.max_pixels,
709
+ )
710
+ report = screen_metadata(
711
+ report,
712
+ expected_formats=args.formats,
713
+ expected_modes=args.modes,
714
+ min_dpi=args.min_dpi,
715
+ max_dpi=args.max_dpi,
716
+ min_width_px=args.min_width_px,
717
+ max_width_px=args.max_width_px,
718
+ min_height_px=args.min_height_px,
719
+ max_height_px=args.max_height_px,
720
+ max_file_bytes=args.max_file_bytes,
721
+ target_width_mm=args.target_width_mm,
722
+ alpha_policy=args.alpha_policy,
723
+ )
724
+ emit_json(report, output=args.output, force=args.force)
725
+ return 1 if report["screening_summary"]["fail"] else 0
726
+ except CliError as exc:
727
+ parser.exit(2, f"error: {exc}\n")
728
+
729
+
730
+ if __name__ == "__main__":
731
+ sys.exit(main())