starbash 0.3.6__tar.gz → 0.3.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. {starbash-0.3.6 → starbash-0.3.8}/PKG-INFO +1 -1
  2. {starbash-0.3.6 → starbash-0.3.8}/pyproject.toml +2 -2
  3. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/analytics.py +1 -1
  4. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/doit.py +86 -7
  5. starbash-0.3.8/src/starbash/fits.py +135 -0
  6. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/processing.py +196 -23
  7. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/recipes/crop.py +90 -4
  8. starbash-0.3.8/src/starbash/recipes/osc.py +568 -0
  9. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/run_state.py +15 -2
  10. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/tool/context.py +24 -0
  11. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/tool/graxpert.py +47 -4
  12. starbash-0.3.8/src/starbash/tool/ranges.py +52 -0
  13. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/tool/rcastro.py +77 -12
  14. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/tool/siril.py +20 -1
  15. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/tool/starnet.py +9 -2
  16. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/pages/publish.py +46 -10
  17. starbash-0.3.6/src/starbash/fits.py +0 -59
  18. starbash-0.3.6/src/starbash/recipes/osc.py +0 -260
  19. {starbash-0.3.6 → starbash-0.3.8}/LICENSE +0 -0
  20. {starbash-0.3.6 → starbash-0.3.8}/README.md +0 -0
  21. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/__init__.py +0 -0
  22. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/aliases.py +0 -0
  23. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/app.py +0 -0
  24. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/assets/__init__.py +0 -0
  25. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/assets/check.png +0 -0
  26. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/assets/favicon.ico +0 -0
  27. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/assets/icon.png +0 -0
  28. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/assets/icon.svg +0 -0
  29. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/assets/starbash.desktop.in +0 -0
  30. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/check_version.py +0 -0
  31. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/commands/__init__.py +0 -0
  32. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/commands/gui.py +0 -0
  33. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/commands/info.py +0 -0
  34. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/commands/process.py +0 -0
  35. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/commands/publish.py +0 -0
  36. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/commands/repo.py +0 -0
  37. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/commands/select.py +0 -0
  38. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/commands/user.py +0 -0
  39. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/database.py +0 -0
  40. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/defaults/__init__.py +0 -0
  41. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/defaults/starbash.toml +0 -0
  42. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/doit_types.py +0 -0
  43. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/dwarf3.py +0 -0
  44. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/events.py +0 -0
  45. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/exception.py +0 -0
  46. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/filtering.py +0 -0
  47. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/interaction.py +0 -0
  48. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/linux.py +0 -0
  49. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/main.py +0 -0
  50. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/os.py +0 -0
  51. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/parameters.py +0 -0
  52. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/paths.py +0 -0
  53. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/preferences.py +0 -0
  54. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/processed_target.py +0 -0
  55. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/processing_like.py +0 -0
  56. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/publish/__init__.py +0 -0
  57. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/publish/credentials.py +0 -0
  58. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/publish/github.py +0 -0
  59. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/publish/github_publish.py +0 -0
  60. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/publish/github_service.py +0 -0
  61. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/recipes/README.md +0 -0
  62. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/recipes/__init__.py +0 -0
  63. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/recipes/report_registration.py +0 -0
  64. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/report.py +0 -0
  65. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/rich.py +0 -0
  66. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/safety.py +0 -0
  67. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/score.py +0 -0
  68. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/selection.py +0 -0
  69. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/sim_siril/__init__.py +0 -0
  70. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/sim_siril/connection.py +0 -0
  71. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/sim_siril/enums.py +0 -0
  72. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/sim_siril/utility.py +0 -0
  73. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/siril/import_registration.py +0 -0
  74. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/stage_utils.py +0 -0
  75. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/stages.py +0 -0
  76. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/__init__.py +0 -0
  77. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/repo/master.toml +0 -0
  78. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/repo/processed.toml +0 -0
  79. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/report/Gemfile +0 -0
  80. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/report/README.md.jinja +0 -0
  81. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/report/__init__.py +0 -0
  82. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/report/_config.yml +0 -0
  83. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/report/default.html +0 -0
  84. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/report/index.md.jinja +0 -0
  85. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/report/target.md.jinja +0 -0
  86. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/target/master.toml +0 -0
  87. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/target/processed/about.toml +0 -0
  88. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/target/processed/main.toml +0 -0
  89. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/target/processed/sessions.toml +0 -0
  90. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/templates/userconfig.toml +0 -0
  91. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/toml.py +0 -0
  92. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/tool/__init__.py +0 -0
  93. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/tool/base.py +0 -0
  94. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/tool/python.py +0 -0
  95. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/__init__.py +0 -0
  96. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/cli.py +0 -0
  97. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/cli_events.py +0 -0
  98. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/__init__.py +0 -0
  99. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/app.py +0 -0
  100. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/bridge.py +0 -0
  101. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/desktop.py +0 -0
  102. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/interaction.py +0 -0
  103. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/jobs.py +0 -0
  104. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/launcher.py +0 -0
  105. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/main_window.py +0 -0
  106. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/models.py +0 -0
  107. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/pages/__init__.py +0 -0
  108. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/pages/base.py +0 -0
  109. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/pages/dashboard.py +0 -0
  110. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/pages/masters.py +0 -0
  111. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/pages/processing.py +0 -0
  112. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/pages/repositories.py +0 -0
  113. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/pages/sessions.py +0 -0
  114. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/pages/settings.py +0 -0
  115. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/pages/targets.py +0 -0
  116. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/pages/wizard.py +0 -0
  117. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/services.py +0 -0
  118. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/theme.py +0 -0
  119. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/widgets/__init__.py +0 -0
  120. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/widgets/busy_indicator.py +0 -0
  121. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/widgets/file_links.py +0 -0
  122. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/widgets/github_login.py +0 -0
  123. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/widgets/hover_preview.py +0 -0
  124. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/widgets/image_viewer.py +0 -0
  125. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/widgets/log_view.py +0 -0
  126. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/widgets/master_picker.py +0 -0
  127. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/widgets/selection_panel.py +0 -0
  128. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/widgets/stat_card.py +0 -0
  129. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/widgets/tool_warning.py +0 -0
  130. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/ui/qt/workers.py +0 -0
  131. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/url.py +0 -0
  132. {starbash-0.3.6 → starbash-0.3.8}/src/starbash/windows.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: starbash
3
- Version: 0.3.6
3
+ Version: 0.3.8
4
4
  Summary: A tool for automating/standardizing/sharing astrophotography workflows.
5
5
  License-File: LICENSE
6
6
  Author: Kevin Hester
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "starbash"
3
- version = "0.3.6"
3
+ version = "0.3.8"
4
4
  description = "A tool for automating/standardizing/sharing astrophotography workflows."
5
5
  authors = ["Kevin Hester <kevinh@geeksville.com>"]
6
6
  readme = "README.md"
@@ -72,7 +72,7 @@ sb = "starbash.main:app" # std alias for convenience
72
72
 
73
73
  [tool.pytest.ini_options]
74
74
  markers = [
75
- "slow: marks tests as slow (deselect with '-m \"not slow\"')",
75
+ "slow: marks tests that take >10s in the default '-n auto' run (deselect with '-m \"not slow\"')",
76
76
  "integration: marks tests as integration tests requiring /test-data (deselect with '-m \"not integration\"')",
77
77
  "gui: marks tests that build real Qt widgets (offscreen; deselect with '-m \"not gui\"')",
78
78
  "gui_integration: marks the scripted gui_integration movie runs (needs ffmpeg + /test-data; deselect with '-m \"not gui_integration\"')",
@@ -72,7 +72,7 @@ def analytics_setup(allowed: bool = False, user_email: str | None = None) -> Non
72
72
  )
73
73
  sentry_sdk.init(
74
74
  dsn="https://e9496a4ea8b37a053203a2cbc10d64e6@o209837.ingest.us.sentry.io/4510264204132352",
75
- send_default_pii=True,
75
+ data_collection={},
76
76
  enable_logs=True,
77
77
  traces_sample_rate=1.0,
78
78
  disabled_integrations=[
@@ -6,7 +6,7 @@ import re
6
6
  import shutil
7
7
  from collections import OrderedDict
8
8
  from collections.abc import Callable
9
- from dataclasses import dataclass
9
+ from dataclasses import dataclass, field
10
10
  from pathlib import Path
11
11
  from typing import TYPE_CHECKING, Any
12
12
 
@@ -22,6 +22,7 @@ from starbash import InputDef, events
22
22
  from starbash.database import ImageRow
23
23
  from starbash.doit_types import TaskDict
24
24
  from starbash.exception import FilesystemUnavailableError, UserHandledError
25
+ from starbash.fits import FITS_VARIANT_SUFFIXES, resolve_fits_variant
25
26
  from starbash.os import symlink_or_copy
26
27
  from starbash.paths import get_user_cache_dir
27
28
  from starbash.tool.base import Tool
@@ -59,6 +60,7 @@ class FileInfo:
59
60
  image_rows: list[ImageRow] | None = None # List of individual files (if applicable)
60
61
  provenance: dict[str, int] | None = None # Generated basename -> source image ID
61
62
  sequence_provenance: dict[str, list[int]] | None = None # Sequence -> source IDs in order
63
+ producers: dict[str, str] = field(default_factory=dict) # output path -> producing task
62
64
  definition: InputDef | None = (
63
65
  None # The input (or output) definition that produced this FileInfo
64
66
  )
@@ -171,6 +173,49 @@ def cleanup_temporaries(stage: Any, context: dict[str, Any]) -> None:
171
173
  logging.warning(f"Failed to remove temporary {match_path}: {e}")
172
174
 
173
175
 
176
+ def _normalize_declared_outputs(task_dict: TaskDict) -> None:
177
+ """Rename on-disk FITS siblings to the declared output spelling.
178
+
179
+ Siril appends its *saved* extension (``.fit``/``.fits``) to an
180
+ extension-less ``-out`` path, so a recipe declaring ``master.fit`` gets
181
+ ``master.fits`` on machines whose preference is ``.fits``. Doit checks its
182
+ ``targets`` by exact path; a spelling mismatch makes every run look
183
+ out-of-date (or, for masters, makes ``add_image`` index a file that was
184
+ never created). After the tool runs, bring the on-disk file to the
185
+ declared spelling.
186
+ """
187
+ context = (task_dict.get("meta", {}) or {}).get("context", {})
188
+ output = context.get("output")
189
+ rows: list[ImageRow] = []
190
+ if isinstance(output, FileInfo):
191
+ rows = list(output.image_rows or [])
192
+ candidates = [Path(img["abspath"]) for img in rows if img.get("abspath")]
193
+ if output.full is not None and not rows:
194
+ candidates = [Path(output.full)]
195
+ else:
196
+ candidates = []
197
+ for declared in candidates:
198
+ if declared.suffix.lower() not in FITS_VARIANT_SUFFIXES or declared.exists():
199
+ continue
200
+ sibling = declared.with_suffix(".fits" if declared.suffix.lower() == ".fit" else ".fit")
201
+ if sibling.exists():
202
+ try:
203
+ sibling.rename(declared)
204
+ except OSError:
205
+ logging.warning(
206
+ "FITS sibling %s exists but could not be renamed to declared %s",
207
+ sibling,
208
+ declared,
209
+ )
210
+ else:
211
+ logging.debug("Renamed %s to declared output %s", sibling, declared)
212
+ if isinstance(output, FileInfo) and output.image_rows:
213
+ for img in output.image_rows:
214
+ resolved = resolve_fits_variant(img.get("abspath", ""))
215
+ if str(resolved) != img.get("abspath"):
216
+ img["abspath"] = str(resolved)
217
+
218
+
174
219
  def doit_post_process(task_dict: TaskDict) -> None:
175
220
  """Do after execution processing
176
221
 
@@ -197,9 +242,12 @@ def doit_post_process(task_dict: TaskDict) -> None:
197
242
 
198
243
  # The generated files might not have propagated all of the metadata (because we added it after FITS import)
199
244
  extra_metadata = context.get("metadata", {})
245
+ # Siril appends its *saved* extension (.fit/.fits) to an
246
+ # extension-less -out path, so the declared output may name a
247
+ # sibling of the file Siril actually wrote.
200
248
  sb.add_image(
201
249
  output.repo,
202
- output.full,
250
+ resolve_fits_variant(output.full),
203
251
  force=True,
204
252
  extra_metadata=extra_metadata,
205
253
  )
@@ -207,6 +255,33 @@ def doit_post_process(task_dict: TaskDict) -> None:
207
255
  add_action(task_dict, closure)
208
256
 
209
257
 
258
+ def _sequence_member_files(base_dir: Path, sequence_file: Path) -> list[Path]:
259
+ """The FITS files a Siril sequence names, in member order.
260
+
261
+ Members are ``<stem>_<index>.fit`` (or ``.fits``). A glob of ``<stem>*``
262
+ also matches a later stage that reused the stem: the broadband convert
263
+ wrote 4832 ``bkg_pp_light_s233_*.fits`` beside the 89 ``.fit`` members, and
264
+ rewrote the ``.seq`` to claim those 4832. The header is therefore not the
265
+ membership. One extension is the sequence; when both exist the smaller set
266
+ is the original and the larger one is the rewrite.
267
+ """
268
+ stem = sequence_file.stem
269
+ by_extension: dict[str, list[Path]] = {}
270
+ for extension in (".fit", ".fits"):
271
+ numbered = []
272
+ for path in base_dir.glob(f"{stem}*{extension}"):
273
+ match = re.fullmatch(rf"{re.escape(stem)}(\d+){extension}", path.name)
274
+ if match:
275
+ numbered.append((int(match.group(1)), path))
276
+ if numbered:
277
+ by_extension[extension] = [path for _, path in sorted(numbered)]
278
+ if not by_extension:
279
+ return []
280
+ if len(by_extension) == 1:
281
+ return next(iter(by_extension.values()))
282
+ return min(by_extension.values(), key=len)
283
+
284
+
210
285
  def merge_to(base_name: str, fi: FileInfo) -> None:
211
286
  """Merge all input files in fi into a single sequence named base_name.
212
287
 
@@ -232,12 +307,13 @@ def merge_to(base_name: str, fi: FileInfo) -> None:
232
307
  for short_path in fi.short_paths:
233
308
  path = Path(short_path)
234
309
 
235
- # If it's a .seq file, find all FITS files with that prefix
310
+ # If it's a .seq file, collect the members it declares. A prefix glob
311
+ # also matches frames a later stage wrote with the same stem.
236
312
  if path.suffix == ".seq":
237
- seq_prefix = path.stem
238
- pattern1 = str(base_dir / f"{seq_prefix}*.fit")
239
- pattern2 = str(base_dir / f"{seq_prefix}*.fits")
240
- matching_files = sorted(glob.glob(pattern1) + glob.glob(pattern2))
313
+ sequence_file = base_dir / path.name
314
+ matching_files = [
315
+ str(member) for member in _sequence_member_files(base_dir, sequence_file)
316
+ ]
241
317
  source_ids = (fi.sequence_provenance or {}).get(path.name)
242
318
  if source_ids is None and path.name.endswith("_.seq"):
243
319
  source_ids = (fi.sequence_provenance or {}).get(f"{path.stem}.seq")
@@ -376,6 +452,9 @@ class ToolAction(BaseAction):
376
452
  self.result = self.tool.run(
377
453
  self.commands, context=context, cwd=self.cwd, log_out=logfile, **self.parameters
378
454
  )
455
+ # Siril may have written a FITS sibling (.fits for a declared .fit);
456
+ # bring it to the declared spelling before doit checks its targets.
457
+ _normalize_declared_outputs(self.task.meta)
379
458
  except OSError as e:
380
459
  error = FilesystemUnavailableError(
381
460
  f"running {self.tool.name} for task '{self.task.name}'", e
@@ -0,0 +1,135 @@
1
+ """Helpers for reading FITS metadata."""
2
+
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ import numpy as np
7
+ from astropy.io import fits
8
+
9
+ __all__ = [
10
+ "canonical_fits_path",
11
+ "read_dimensions",
12
+ "read_fits_header",
13
+ "resolve_fits_variant",
14
+ "signal_scale",
15
+ ]
16
+
17
+ #: Siril appends its *saved* extension (``.fit`` or ``.fits``, per the user's
18
+ #: ``config.1.4.ini``) to an extension-less ``-out`` path. A recipe that names
19
+ #: ``master_bias_gain100.fit`` therefore gets ``...gain100.fits`` on a machine
20
+ #: whose preference is ``.fits`` -- and recording the declared path would point
21
+ #: doit and the DB at a file that was never created. We deliberately do *not*
22
+ #: pin this with ``setext``: it calls ``writeinitfile()``, persisting the
23
+ #: preference into Siril's shared user config, so parallel runs race on that
24
+ #: file (Windows CI: ``save`` failing with "already exists?"). Instead every
25
+ #: lookup treats the two spellings as the same file.
26
+ FITS_VARIANT_SUFFIXES = (".fit", ".fits")
27
+
28
+
29
+ def resolve_fits_variant(path: str | Path) -> Path:
30
+ """Return the on-disk spelling of a FITS path, trying ``.fit``/``.fits``.
31
+
32
+ Returns ``path`` itself when it exists (or has no FITS suffix); otherwise
33
+ returns the existing sibling with the other spelling, or ``path`` unchanged
34
+ when neither exists.
35
+ """
36
+ candidate = Path(path)
37
+ if candidate.exists() or candidate.suffix.lower() not in FITS_VARIANT_SUFFIXES:
38
+ return candidate
39
+ sibling = candidate.with_suffix(".fits" if candidate.suffix.lower() == ".fit" else ".fit")
40
+ return sibling if sibling.exists() else candidate
41
+
42
+
43
+ def canonical_fits_path(path: str | Path) -> str:
44
+ """Canonical key for comparing FITS paths: collapses ``.fit``/``.fits``.
45
+
46
+ Dict lookups keyed on ``abspath`` (producers, image_rows, doit
47
+ file_dep/target matching) must agree whether Siril wrote ``.fit`` or
48
+ ``.fits``. Non-FITS paths pass through unchanged.
49
+ """
50
+ text = str(path)
51
+ lower = text.lower()
52
+ for suffix in FITS_VARIANT_SUFFIXES:
53
+ if lower.endswith(suffix):
54
+ return text[: -len(suffix)] + ".fit"
55
+ return text
56
+
57
+
58
+ def _json_safe(value: Any) -> Any:
59
+ """Convert an astropy header value into a plain JSON-serializable Python value.
60
+
61
+ Commentary cards (COMMENT/HISTORY/blank keyword) come back as
62
+ ``_HeaderCommentaryCards`` (a list-like of strings) and other cards can be
63
+ ``bool``, numpy scalars etc. None of those serialize via ``json.dumps``.
64
+ """
65
+ # Commentary cards: list-like container of strings; join into one string
66
+ if isinstance(value, fits.header._HeaderCommentaryCards):
67
+ return "\n".join(value)
68
+ if isinstance(value, (list, tuple)):
69
+ return [_json_safe(v) for v in value]
70
+ if isinstance(value, bool): # must precede int check (bool is an int subclass)
71
+ return value
72
+ if isinstance(value, (int, float, str)) or value is None:
73
+ return value
74
+ # numpy scalars and anything else: fall back to str()
75
+ return str(value)
76
+
77
+
78
+ def read_fits_header(file_path: str | Path) -> dict[str, Any]:
79
+ """Read and return the primary FITS header from ``file_path``.
80
+
81
+ All values are converted to plain JSON-serializable Python types.
82
+ """
83
+ with fits.open(str(file_path), memmap=False) as hdul:
84
+ hdu0: Any = hdul[0]
85
+ return {key: _json_safe(value) for key, value in hdu0.header.items()}
86
+
87
+
88
+ def read_dimensions(file_path: str | Path) -> tuple[int, int]:
89
+ """Return the primary FITS image dimensions as ``(width, height)``.
90
+
91
+ Raises:
92
+ ValueError: If the primary header has missing or invalid dimensions.
93
+ """
94
+ header = read_fits_header(file_path)
95
+ try:
96
+ width = int(header["NAXIS1"])
97
+ height = int(header["NAXIS2"])
98
+ except (KeyError, TypeError, ValueError) as exc:
99
+ raise ValueError(
100
+ f"FITS image '{file_path}' is missing valid NAXIS1/NAXIS2 dimensions"
101
+ ) from exc
102
+
103
+ if width <= 0 or height <= 0:
104
+ raise ValueError(f"FITS image '{file_path}' has invalid dimensions: {width}x{height}")
105
+
106
+ return width, height
107
+
108
+
109
+ def signal_scale(file_path: str | Path, q: float = 99) -> float:
110
+ """Return ``1 / (Pq - median)`` for a palette channel, its bright reference.
111
+
112
+ The SHO/HOO palettes rescale each channel by this inverse span so that a
113
+ duo-stack OIII/Sii channel's nebulosity is not crushed by a star-pinned
114
+ global max: ``(x - median) * scale`` maps the channel's own Pq onto 1 while
115
+ leaving the sky (at/below the median) at zero. ``q`` is the percentile of
116
+ the reference (default 99), which lands above the nebula but below the few
117
+ saturated star cores (see doc/plans/duo-palette-orange.md).
118
+
119
+ Raises:
120
+ ValueError: If the image is not a finite float FITS, or has no signal
121
+ above its median (everything within [median, median]).
122
+ """
123
+ with fits.open(str(file_path), memmap=True) as hdul:
124
+ primary: Any = hdul[0]
125
+ data = primary.data
126
+ if data is None or data.dtype.kind != "f":
127
+ raise ValueError(f"Palette channel must be a floating-point FITS image: {file_path}")
128
+ if not np.isfinite(data).all():
129
+ raise ValueError(f"Palette channel contains non-finite pixels: {file_path}")
130
+ median = float(np.median(data))
131
+ reference = float(np.percentile(data, q))
132
+ span = reference - median
133
+ if span <= 0:
134
+ raise ValueError(f"Palette channel has no above-median signal: {file_path}")
135
+ return 1.0 / span
@@ -45,6 +45,7 @@ from starbash.exception import (
45
45
  raise_missing_repo,
46
46
  )
47
47
  from starbash.filtering import FallbackToImageException, filter_by_requires
48
+ from starbash.fits import canonical_fits_path
48
49
  from starbash.preferences import auto_reindex_enabled
49
50
  from starbash.processed_target import ProcessedTarget
50
51
  from starbash.processing_like import ProcessingLike
@@ -227,19 +228,20 @@ def masters_needed_by(
227
228
 
228
229
  Returns:
229
230
  The set of needed master output paths, normalised with
230
- :func:`os.path.realpath` so symlinked/relative spellings still match.
231
+ :func:`os.path.realpath` so symlinked/relative spellings still match,
232
+ then :func:`canonical_fits_path` so ``.fit``/``.fits`` spellings match.
231
233
  """
232
234
  needed: set[str] = set()
233
235
  for task in target_tasks:
234
236
  for dep in task.get("file_dep", None) or []:
235
- needed.add(os.path.realpath(str(dep)))
237
+ needed.add(canonical_fits_path(os.path.realpath(str(dep))))
236
238
 
237
239
  # Map every produced master path to the task that produces it, so the
238
240
  # closure below can follow a needed output back to its own inputs.
239
241
  producers: dict[str, TaskDict] = {}
240
242
  for task in master_tasks:
241
243
  for output in task.get("targets", None) or []:
242
- producers[os.path.realpath(str(output))] = task
244
+ producers[canonical_fits_path(os.path.realpath(str(output)))] = task
243
245
 
244
246
  frontier = list(needed)
245
247
  while frontier:
@@ -247,7 +249,7 @@ def masters_needed_by(
247
249
  if task is None:
248
250
  continue
249
251
  for dep in task.get("file_dep", None) or []:
250
- normalised = os.path.realpath(str(dep))
252
+ normalised = canonical_fits_path(os.path.realpath(str(dep)))
251
253
  if normalised not in needed:
252
254
  needed.add(normalised)
253
255
  frontier.append(normalised)
@@ -282,6 +284,7 @@ class Processing(ProcessingLike):
282
284
  self.results: list[ProcessingResult] = []
283
285
 
284
286
  self._stages_cache: list[StageDict] | None = None # Cache for stages property
287
+ self._built_tasks: list[TaskDict] = []
285
288
  #: What role selection decided for the current job (see doc/plans/stage-roles.md).
286
289
  self._stage_selection: StageSelection | None = None
287
290
  #: The target whose tasks are currently executing (for live log attribution).
@@ -825,6 +828,7 @@ class Processing(ProcessingLike):
825
828
  def _add_task(self, task: TaskDict) -> None:
826
829
  """Add a task to the doit task list."""
827
830
  self.doit.add_task(task)
831
+ self._built_tasks.append(task)
828
832
 
829
833
  def _run_jobs(self) -> None:
830
834
  # add a default task to run all the other tasks
@@ -861,7 +865,35 @@ class Processing(ProcessingLike):
861
865
 
862
866
  with ProcessedTarget(self, target) as pt:
863
867
  pt.config_valid = False # assume our config is not worth writing
868
+ tasks = self._build_target_tasks(pt)
869
+ self.doit.set_tasks(tasks)
870
+ # self.doit.run(
871
+ # [
872
+ # "info",
873
+ # "process_all", # "stack_m20", # seqextract_haoiii_m20_s35
874
+ # ]
875
+ # )
876
+ # self.doit.run(["dumpdb"])
877
+ pt.config_valid = True # our config is probably worth keeping
864
878
 
879
+ def _build_target_tasks(self, pt: ProcessedTarget) -> list[TaskDict]:
880
+ """Build a target's task graph, rebuilding it when a stage conflict appears.
881
+
882
+ Role selection happens *before* any task is created (so the branch of the
883
+ losing implementation never materialises), but a conflict over an output
884
+ *file* can only be seen once the tasks - and therefore the files they
885
+ claim - exist. When the first pass has to exclude a stage, consumers
886
+ built in that pass were already given outputs it will never produce:
887
+ ``crop`` multiplexes over every ``stack_.*`` output, so a stacking recipe
888
+ that loses a conflict still shows up as a ``crop`` task on a file nobody
889
+ will create. doit treats the missing file as "needs running", the task
890
+ runs and fails, and the rest of the target is abandoned. So re-select
891
+ with the exclusion just recorded and build again - that second pass is
892
+ exactly the graph a subsequent run would produce.
893
+
894
+ Every pass excludes at least one more stage, so this terminates.
895
+ """
896
+ for _ in range(len(self.stages) + 1):
865
897
  # Pick one implementation per stage 'role' *before* any task is created,
866
898
  # so the branch of the losing implementation never materialises and
867
899
  # downstream stages follow the winner. This is also what lets a recipe
@@ -877,6 +909,7 @@ class Processing(ProcessingLike):
877
909
  # Sort what survived: a consumer's 'after' may now name a role, or a
878
910
  # dropped role member (which redirects onto the winner).
879
911
  stages = sort_stages(selection.stages, resolve=selection.resolve)
912
+ self.doit.set_tasks([]) # a rebuild must not keep the previous pass's tasks
880
913
  self._stages_to_tasks(stages)
881
914
 
882
915
  # Every stage in the merged recipe catalog gets a candidate task, but
@@ -884,17 +917,15 @@ class Processing(ProcessingLike):
884
917
  # skips stages with insufficient inputs). Record the relevant ones so
885
918
  # the live run tree lists only what applies to *this* target.
886
919
  candidate_tasks = self.tasks
920
+ if self._exclude_conflicting_stages(pt, candidate_tasks):
921
+ continue # that pass still consumed the excluded stage; build again
922
+
887
923
  pt.set_run_stages(tasks_to_stages(candidate_tasks))
924
+ return self.preflight_tasks(candidate_tasks)
888
925
 
889
- self.doit.set_tasks(self.preflight_tasks(pt, candidate_tasks))
890
- # self.doit.run(
891
- # [
892
- # "info",
893
- # "process_all", # "stack_m20", # seqextract_haoiii_m20_s35
894
- # ]
895
- # )
896
- # self.doit.run(["dumpdb"])
897
- pt.config_valid = True # our config is probably worth keeping
926
+ raise RuntimeError( # pragma: no cover - each pass excludes at least one stage
927
+ "stage conflict resolution never converged"
928
+ )
898
929
 
899
930
  @property
900
931
  def stages(
@@ -1006,17 +1037,27 @@ class Processing(ProcessingLike):
1006
1037
  # the correct session specific files
1007
1038
  self.context.pop("input", None)
1008
1039
 
1009
- def _get_prior_tasks(self, stage: StageDict) -> TaskDict | list[TaskDict] | None:
1040
+ def _get_prior_tasks(
1041
+ self, stage: StageDict, input: InputDef | None = None
1042
+ ) -> TaskDict | list[TaskDict] | None:
1010
1043
  """Get the prior tasks for the given stage based on the 'after' input definition.
1011
1044
 
1012
1045
  Args:
1013
1046
  stage: The stage definition from TOML
1047
+ input: The input whose ``after`` to follow. A stage may consume several
1048
+ producers (the plate from ``stack_dual_duo``, the lights from
1049
+ ``light.*``); without this, every input follows the first ``after``
1050
+ and a later block is filtered against the wrong files.
1014
1051
  Returns:
1015
1052
  Note: this function will return a single TaskDict if the prior stage was not
1016
1053
  multiplexed, otherwise a list of TaskDicts for each multiplexed task.
1017
1054
  Or None if no "after" keyword was found."""
1018
1055
  inputs: list[InputDef] = stage.get("inputs", [])
1019
- input_with_after = next((inp for inp in inputs if "after" in inp), None)
1056
+ input_with_after = (
1057
+ input
1058
+ if input is not None and "after" in input
1059
+ else next((inp for inp in inputs if "after" in inp), None)
1060
+ )
1020
1061
 
1021
1062
  if not input_with_after:
1022
1063
  return None
@@ -1371,9 +1412,10 @@ class Processing(ProcessingLike):
1371
1412
  image_rows: dict[
1372
1413
  str, ImageRow
1373
1414
  ] = {} # We use a dict[abspath -> imagerow] because there might be duplicate outputs from prior stages
1415
+ producers: dict[str, str] = {}
1374
1416
 
1375
1417
  assert self.stage
1376
- prior_tasks = self._get_prior_tasks(self.stage)
1418
+ prior_tasks = self._get_prior_tasks(self.stage, input=input)
1377
1419
  if not prior_tasks:
1378
1420
  raise ValueError("Input definition with 'after' must refer to a valid prior stage.")
1379
1421
 
@@ -1454,7 +1496,12 @@ class Processing(ProcessingLike):
1454
1496
  {"requires": filename_requires}, output_rows
1455
1497
  )
1456
1498
  for img in output_rows:
1457
- image_rows[img["abspath"]] = img
1499
+ # Key on the canonical spelling so a consumer
1500
+ # asking for ``.fit`` still matches when Siril
1501
+ # wrote ``.fits`` (or vice versa).
1502
+ key = canonical_fits_path(img["abspath"])
1503
+ image_rows[key] = img
1504
+ producers[key] = task["name"]
1458
1505
  except NotEnoughFilesError as e:
1459
1506
  child_exception = e # In case we need to raise later
1460
1507
  # just because one prior task doesn't have what we need, we shouldn't stop looking
@@ -1470,6 +1517,31 @@ class Processing(ProcessingLike):
1470
1517
  "No prior stage outputs matched the input filename filter", []
1471
1518
  )
1472
1519
 
1520
+ image_rows = {
1521
+ path: row
1522
+ for path, row in image_rows.items()
1523
+ if not self._light_was_extracted(producers.get(path, ""), prior_tasks, input)
1524
+ }
1525
+ earlier = prior_tasks if isinstance(prior_tasks, list) else [prior_tasks]
1526
+ graph = [
1527
+ task
1528
+ for task in [*earlier, *getattr(self, "_built_tasks", [])]
1529
+ if isinstance(task, dict) and isinstance(task.get("meta"), dict)
1530
+ ]
1531
+ produced_by = {
1532
+ canonical_fits_path(row["abspath"]): task["name"]
1533
+ for task in graph
1534
+ if isinstance(output := task["meta"]["context"].get("output"), FileInfo)
1535
+ for row in output.image_rows or []
1536
+ }
1537
+ image_rows = self._prefer_later_matches(image_rows, produced_by, graph)
1538
+ if filename_requires and len(image_rows) == 0 and not input.get("optional", False):
1539
+ # Prior outputs existed but none matched the filename filter, or
1540
+ # every match belonged to a night channel extraction rewrote.
1541
+ raise NotEnoughFilesError(
1542
+ "No prior stage outputs matched the input filename filter", []
1543
+ )
1544
+
1473
1545
  if min_count_requires:
1474
1546
  # Apply min_count to this input group's aggregate, rather than to
1475
1547
  # each multiplexed upstream task. This keeps the requirement
@@ -1506,6 +1578,83 @@ class Processing(ProcessingLike):
1506
1578
  definition=input,
1507
1579
  provenance=provenance,
1508
1580
  sequence_provenance=sequence_provenance or None,
1581
+ producers=producers,
1582
+ )
1583
+
1584
+ @staticmethod
1585
+ def _prefer_later_matches(
1586
+ image_rows: dict[str, ImageRow],
1587
+ producers: dict[str, str],
1588
+ prior_tasks: list[TaskDict],
1589
+ ) -> dict[str, ImageRow]:
1590
+ """Drop a match only when a later match was produced from it.
1591
+
1592
+ ``after = "(denoise|crop)"`` matches both. Denoise consumes blur, and
1593
+ blur consumes the crop, so the chain has to be walked: the blend wants
1594
+ the processed file. A named reference (the Ha plate ``stack_broadband``
1595
+ reads) is not input 0, so it is not a file this output replaces.
1596
+ """
1597
+ by_name = {task["name"]: task for task in prior_tasks}
1598
+
1599
+ def transformed_by(task_name: str) -> set[str]:
1600
+ task = by_name.get(task_name)
1601
+ if task is None:
1602
+ return set()
1603
+ task_inputs = task["meta"]["context"].get("input", {})
1604
+ return {
1605
+ canonical_fits_path(row["abspath"])
1606
+ for key in (0, "0")
1607
+ if isinstance(file_info := task_inputs.get(key), FileInfo)
1608
+ for row in file_info.image_rows or []
1609
+ }
1610
+
1611
+ earlier: set[str] = set()
1612
+ for path, task_name in producers.items():
1613
+ if path not in image_rows:
1614
+ continue
1615
+ pending = transformed_by(task_name) - {path}
1616
+ seen: set[str] = set()
1617
+ while pending:
1618
+ candidate = pending.pop()
1619
+ if candidate in seen:
1620
+ continue
1621
+ seen.add(candidate)
1622
+ if candidate in image_rows:
1623
+ earlier.add(candidate)
1624
+ continue
1625
+ producer = producers.get(candidate)
1626
+ if producer:
1627
+ pending.update(transformed_by(producer) - {candidate})
1628
+ if earlier and set(image_rows) - earlier:
1629
+ return {path: row for path, row in image_rows.items() if path not in earlier}
1630
+ return image_rows
1631
+
1632
+ def _light_was_extracted(
1633
+ self, task_name: str, prior_tasks: list[TaskDict], input: InputDef
1634
+ ) -> bool:
1635
+ """Whether channel extraction rewrote the session that produced this file.
1636
+
1637
+ A light stage declares ``bkg_pp_light`` for every night. Extraction
1638
+ rewrites a duo night but publishes only the new names, so the original
1639
+ is still a light output. An input that follows both stages and asks for
1640
+ the original name means the nights extraction left alone.
1641
+ """
1642
+ if not task_name.startswith("light") or "seqextract_haoiii" not in str(
1643
+ input.get("after", "")
1644
+ ):
1645
+ return False
1646
+ session_id = next(
1647
+ (
1648
+ task["meta"]["context"].get("session", {}).get("id")
1649
+ for task in prior_tasks
1650
+ if task["name"] == task_name
1651
+ ),
1652
+ None,
1653
+ )
1654
+ return any(
1655
+ task_to_stage(task).get("name") == "seqextract_haoiii"
1656
+ and task["meta"]["context"].get("session", {}).get("id") == session_id
1657
+ for task in prior_tasks
1509
1658
  )
1510
1659
 
1511
1660
  @staticmethod
@@ -1546,19 +1695,26 @@ class Processing(ProcessingLike):
1546
1695
 
1547
1696
  return [t for t in tasks if tool_available(t)]
1548
1697
 
1549
- def preflight_tasks(self, pt: ProcessedTarget, tasks: list[TaskDict]) -> list[TaskDict]:
1550
- # if user has excluded any stages, we need to respect that (remove matching stages)
1551
- tasks = remove_excluded_tasks(tasks)
1698
+ def _exclude_conflicting_stages(self, pt: ProcessedTarget, tasks: list[TaskDict]) -> bool:
1699
+ """Exclude all but one producer of each target file.
1552
1700
 
1553
- # drop any stages whose required tool isn't installed on this machine
1554
- tasks = self._remove_missing_tool_tasks(tasks)
1701
+ A file may only be written by one stage. When several stages claim the
1702
+ same one (two stacking recipes that both produce ``stacked_Ha.fits``, say)
1703
+ the first task - the list arrives in priority order - keeps it and every
1704
+ other claimant is recorded as excluded in the target's (or the session's)
1705
+ ``[[stages]]`` config, exactly as a user exclusion would be.
1555
1706
 
1707
+ Returns True when a stage was newly excluded, because the task graph the
1708
+ caller just built still contains *consumers* of that stage and has to be
1709
+ rebuilt (see ``_build_target_tasks``).
1710
+ """
1556
1711
  # multimap from target file to tasks that produce it
1557
1712
  target_to_tasks = MultiDict[TaskDict]()
1558
1713
  for task in tasks:
1559
1714
  for target in task.get("targets", []):
1560
1715
  target_to_tasks.add(target, task)
1561
1716
 
1717
+ newly_excluded = False
1562
1718
  # check for tasks that are writing to the same target (which is not allowed). If we
1563
1719
  # find such tasks we'll have to pick ONE based on priority and let the user know in the future
1564
1720
  # they could pick something else.
@@ -1582,9 +1738,26 @@ class Processing(ProcessingLike):
1582
1738
  session = task_to_session(producing_tasks[0])
1583
1739
  if not session:
1584
1740
  session = pt.default_stages
1741
+ if any(
1742
+ not is_excluded(session, stage.get("name", "")) for stage in stages_to_exclude
1743
+ ):
1744
+ newly_excluded = True
1585
1745
  mark_excluded(session, stages_to_exclude)
1586
1746
 
1587
- tasks = remove_excluded_tasks(tasks)
1747
+ return newly_excluded
1748
+
1749
+ def preflight_tasks(self, tasks: list[TaskDict]) -> list[TaskDict]:
1750
+ """Apply the target's exclusions and tool availability to a built graph.
1751
+
1752
+ A stage that loses a conflict over an output file is handled earlier, by
1753
+ ``_build_target_tasks``: that exclusion must be known *before* consumers
1754
+ are built (see ``_exclude_conflicting_stages``).
1755
+ """
1756
+ # if user has excluded any stages, we need to respect that (remove matching stages)
1757
+ tasks = remove_excluded_tasks(tasks)
1758
+
1759
+ # drop any stages whose required tool isn't installed on this machine
1760
+ tasks = self._remove_missing_tool_tasks(tasks)
1588
1761
 
1589
1762
  set_used_stages_from_tasks(tasks)
1590
1763