-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathNaztronomy-Mono_PP.py
More file actions
6639 lines (5923 loc) · 282 KB
/
Copy pathNaztronomy-Mono_PP.py
File metadata and controls
6639 lines (5923 loc) · 282 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
(c) Nazmus Nasir 2026
SPDX-License-Identifier: GPL-3.0-or-later
Naztronomy - Mono Image Preprocessing script
Version: 1.0.0
=====================================
The author of this script is Nazmus Nasir (Naztronomy) and can be reached at:
https://www.Naztronomy.com or https://www.YouTube.com/Naztronomy
Join discord for support and discussion: https://discord.gg/yXKqrawpjr
Support me on Patreon: https://www.patreon.com/c/naztronomy
Support me on Buy me a Coffee: https://www.buymeacoffee.com/naztronomy
This script is designed to process MONOCHROME images only. Frames are never debayered.
Only FITS files (.fit / .fits) are accepted as input.
Lights and flats are automatically split by optical filter, read from the FITS FILTER header
(e.g. RED/R, GREEN/G, BLUE/B, LUM/L, HA, SII, OIII) or, as a fallback, from a parent folder name
matching a known filter. Each filter is processed as its own session and produces its own final
stacked image. Darks and biases carry no filter and are shared across all filters in the same drop.
This script can be run from any directory but recommended to create a blank directory.
Symlinks will only work if your home directory is in the same drive as your images, Symlinks also need to be enabled (on windows, enable developer mode).
Target modes:
- Single target: all sessions are of the same target and are combined into a single final stack for EACH filter. Final recomposition is done by the user.
- Mosaic: sessions are mosaic panels. The parent folder for each panel must contain the token "Panel X" (where x is a number) somewhere in its name, e.g.
"Panel 3" or "Lagoon Nebula Panel 3". Each panel directory can have
unlimited sessions and filters within. Each panel is stacked individually by filter. If a filter exists multiple times in a panel, they get combined.
Each panel for a specific filter then gets stitched together so you'll have one giant mosaic for each filter. Final recomposition is done by the user.
Folder conventions (drag & drop an object folder to auto-detect the mode):
- Single target: object/<date>/lights (+ darks/flats/biases). Sessions pooled into one final stack per filter.
- Mosaic: object/Panel N/<date>/lights — subfolders whose name contains "Panel 1", "panel2", "Panel_03"
(case-insensitive, token may be part of a longer name like "Lagoon Nebula Panel 3") mark mosaic
tiles. The same panel across several nights is pooled and
integrated once, then all panels are stitched. Mosaic mode is selected automatically.
- Absence of a "Panel N" level means single target, single panel.
- Structures inside the parent directory matters less because the script will read fits headers to determine the filter and object name.
The script will also read the parent folder names to determine the filter and panel if fits headers are missing (unlikely and not recommended).
"""
"""
CHANGELOG:
1.0.0 - initial release (Mono preprocessing)
- Derived from the Naztronomy OSC preprocessing script
- Monochrome-only pipeline (no debayering / CFA handling)
- Accepts only FITS (.fit / .fits) input
- Target modes: Single target and Mosaic
- Filter awareness: lights/flats split by optical filter (FITS FILTER header, folder-name
fallback); each filter becomes its own session and produces its own final stack; darks
and biases shared across filters
- Panel awareness: dropping an object folder organised as object/Panel N/<date>/frames is
detected as a mosaic; folders without a "Panel N" level are treated as single target.
Same-panel sessions (one tile across multiple nights) are pooled and integrated once per
(panel, filter) before stitching, avoiding stacking-of-stacks. Mosaic mode is selected
automatically and the panel is shown in the session label, e.g. "Session 1 (Panel 1 - RCW 105 - HA)"
- Session labels show target name (FITS OBJECT header) and filter, e.g. "Session 1 (RCW 105 - HA)"
- Single-target final stacks pool the calibrated lights from every session and integrate
them in a single stack per filter (better pixel rejection / per-frame weighting) instead
of stacking each session and combining the stacks
- Optional "Register final frames": aligns all final stacks to each other (common max
framing) and saves r_-prefixed registered copies alongside the regular output for easy
multi-filter compositing
- Initial copy from Naztronomy - OSC Preprocessing script
"""
from pathlib import Path
import shutil
import sirilpy as s
# Themes requirements: qt_themes, pyside6, qtpy
s.ensure_installed("PyQt6", "numpy", "astropy", "qt_themes", "pyside6", "qtpy")
from PyQt6.QtCore import Qt, QUrl
from PyQt6.QtWidgets import (
QApplication,
QMainWindow,
QWidget,
QVBoxLayout,
QHBoxLayout,
QGridLayout,
QPushButton,
QLabel,
QComboBox,
QFrame,
QLineEdit,
QTreeWidget,
QTreeWidgetItem,
QHeaderView,
QSpinBox,
QDoubleSpinBox,
QCheckBox,
QRadioButton,
QButtonGroup,
QTabWidget,
QGroupBox,
QFileDialog,
QMessageBox,
QAbstractItemView,
QToolButton,
QMenu,
QDialog,
QTextBrowser,
QSizePolicy,
QScrollArea,
)
from PyQt6.QtGui import (
QFont,
QShortcut,
QKeySequence,
QAction,
QDesktopServices,
QDragEnterEvent,
QDropEvent,
QPainter,
QColor,
QBrush,
)
from datetime import datetime, timedelta
import csv
import time
import os
import sys
import json
import re
import qt_themes
from sirilpy import LogColor, NoImageError
from astropy.io import fits
import numpy as np
from dataclasses import dataclass, field
from typing import List, Dict
APP_NAME = "Naztronomy - Mono Image Preprocessor"
VERSION = "1.0.0"
BUILD = "20260709"
AUTHOR = "Nazmus Nasir"
WEBSITE = "https://www.Naztronomy.com"
YOUTUBE = "https://www.YouTube.com/Naztronomy"
DISCORD = "https://discord.gg/yXKqrawpjr"
PATREON = "https://www.patreon.com/c/naztronomy"
BUY_ME_A_COFFEE = "https://www.buymeacoffee.com/naztronomy"
UI_DEFAULTS = {
"feather_amount": 20,
"filter_round": 3.0,
"filter_wfwhm": 3.0,
"filter_stars": 3.0,
"filter_bkg": 3.0,
"drizzle_amount": 1.0,
"pixel_fraction": 1.0,
}
# Controls how files are staged into the sessions/ folder before processing.
# False (default): symlink files on the same drive, copy files from a different drive.
# Cross-drive symlinks cause Siril/libraw to read through untrusted mounts and
# fail with I/O errors (WinError 448), so they are always copied.
# True: always symlink regardless of drive. Use only if your OS / mount allows it
# and you want to avoid the disk copy (e.g. large raw files on a trusted NAS).
ALWAYS_SYMLINK: bool = False
FRAME_TYPES = ("lights", "darks", "flats", "biases")
# This script only accepts monochrome FITS data. Any other file types
# (raw camera files, TIFF, PNG, etc.) are ignored on selection / drop.
FITS_INPUT_EXTENSIONS = (".fit", ".fits", ".fit.fz", ".fits.fz")
def _is_fits_file(path) -> bool:
"""Return True if `path` looks like a FITS file by extension."""
name = str(path).lower()
return any(name.endswith(ext) for ext in FITS_INPUT_EXTENSIONS)
# Master calibration frames exported from other tools (e.g. PixInsight) often
# arrive as a single XISF file named masterDark / masterFlat / masterBias. Siril
# can read XISF natively but must convert it to FITS first, and astropy cannot
# open XISF at all — so XISF masters are accepted as input but their filter is
# detected from the file name rather than the header.
XISF_INPUT_EXTENSIONS = (".xisf",)
def _is_xisf_file(path) -> bool:
"""Return True if `path` looks like an XISF file by extension."""
name = str(path).lower()
return any(name.endswith(ext) for ext in XISF_INPUT_EXTENSIONS)
def _is_supported_input(path) -> bool:
"""Return True if `path` is an accepted input frame (FITS or XISF)."""
return _is_fits_file(path) or _is_xisf_file(path)
# Master / stacked calibration files identified by file name. Recognises both
# Siril-style "..._darks_stacked" tokens and PixInsight-style "masterDark"
# naming (with or without separators, any case).
_STACKED_NAME_MAP = {
"_darks_stacked": "darks",
"_flats_stacked": "flats",
"_biases_stacked": "biases",
}
_MASTER_NAME_RE = re.compile(r"master[\s_\-]*(dark|flat|bias)", re.IGNORECASE)
_MASTER_TYPE_MAP = {"dark": "darks", "flat": "flats", "bias": "biases"}
def _detect_master_frame_type(name) -> str | None:
"""Return 'darks'/'flats'/'biases' if `name` looks like a master/stacked
calibration file, else None."""
stem = Path(name).stem.lower()
for suffix, frame_type in _STACKED_NAME_MAP.items():
if suffix in stem:
return frame_type
match = _MASTER_NAME_RE.search(stem)
if match:
return _MASTER_TYPE_MAP[match.group(1).lower()]
return None
# Frame-type categorisation from a FITS IMAGETYP header value. Used as a
# fallback for dropped folders that have no recognised lights/darks/flats/biases
# subfolder structure. Matching is case-insensitive on the stripped value.
_IMAGETYP_MAP = {
"light": "lights",
"light frame": "lights",
"object": "lights",
"science": "lights",
"dark": "darks",
"dark frame": "darks",
"flat": "flats",
"flat frame": "flats",
"flat field": "flats",
"flatfield": "flats",
"bias": "biases",
"bias frame": "biases",
"zero": "biases",
"dark flat": "biases",
"dark_flat": "biases",
"darkflat": "biases",
}
def _read_fits_imagetyp(path) -> str | None:
"""Return the canonical frame type ('lights'/'darks'/'flats'/'biases') from a
FITS file's IMAGETYP header, or None when absent or unrecognised."""
try:
with fits.open(str(path)) as hdul:
for hdu in hdul:
header = getattr(hdu, "header", None)
if header is None:
continue
value = header.get("IMAGETYP")
if value not in (None, ""):
key = str(value).strip().lower()
if key in _IMAGETYP_MAP:
return _IMAGETYP_MAP[key]
except Exception:
return None
return None
# ── Filter awareness ─────────────────────────────────────────────────────────
# Canonical filter names mapped to the aliases that may appear either in a FITS
# "FILTER" header value or in a folder name. Matching is case-insensitive and
# ignores surrounding whitespace. Unknown filters are kept as-is (uppercased).
FILTER_ALIASES = {
"LUM": ("L", "LUM", "LUMINANCE", "CLEAR"),
"RED": ("R", "RED"),
"GREEN": ("G", "GREEN"),
"BLUE": ("B", "BLUE"),
"HA": ("HA", "H-ALPHA", "HALPHA", "H_ALPHA", "HYDROGEN", "H"),
"SII": ("SII", "S2", "S-II", "S", "SULFUR"),
"OIII": ("OIII", "O3", "O-III", "O", "OXYGEN"),
}
# Reverse lookup: alias (uppercased) -> canonical filter name.
_FILTER_ALIAS_LOOKUP = {
alias.upper(): canonical
for canonical, aliases in FILTER_ALIASES.items()
for alias in aliases
}
# Placeholder used when no filter can be determined for a frame.
NO_FILTER = "NOFILTER"
# Preferred processing/display order for known filters.
_FILTER_ORDER = ("LUM", "RED", "GREEN", "BLUE", "HA", "SII", "OIII")
def _filter_sort_key(name: str):
"""Sort key placing known filters in `_FILTER_ORDER`, others alphabetically last."""
try:
return (0, _FILTER_ORDER.index(name))
except ValueError:
return (1, str(name))
def _canonical_filter(raw) -> str | None:
"""Normalise a raw filter string (header value or folder name) to a canonical name.
Returns None when `raw` is empty/None. Unknown filters are returned
uppercased and stripped so they still group consistently.
"""
if raw is None:
return None
text = str(raw).strip()
if not text:
return None
return _FILTER_ALIAS_LOOKUP.get(text.upper(), text.upper())
def _read_fits_filter(path) -> str | None:
"""Return the canonical filter from a FITS file's FILTER header, or None."""
try:
with fits.open(str(path)) as hdul:
for hdu in hdul:
header = getattr(hdu, "header", None)
if header is None:
continue
value = header.get("FILTER")
if value not in (None, ""):
return _canonical_filter(value)
except Exception:
return None
return None
def _detect_filter(path) -> str:
"""Determine the canonical filter for a frame.
Priority: FITS FILTER header → a parent folder name that matches a known
filter alias. Falls back to NO_FILTER when nothing can be determined.
"""
header_filter = _read_fits_filter(path)
if header_filter:
return header_filter
for parent in Path(path).parents:
name = parent.name
if name and name.upper() in _FILTER_ALIAS_LOOKUP:
return _FILTER_ALIAS_LOOKUP[name.upper()]
return NO_FILTER
def _detect_filter_from_name(name) -> str | None:
"""Detect a canonical filter from a file name's tokens.
Splits the name on common separators (``_ - . space``) and returns the first
token that matches a known filter alias, e.g.
``session1_RED_-4.9C_..._flats_stacked`` -> ``RED``. Returns None when no
token matches. Used as a fallback for stacked master frames whose FITS
FILTER header may have been dropped during integration.
"""
stem = Path(name).stem
for token in re.split(r"[\s_\-.]+", stem):
if token and token.upper() in _FILTER_ALIAS_LOOKUP:
return _FILTER_ALIAS_LOOKUP[token.upper()]
return None
def _read_fits_object(path) -> str | None:
"""Return the target name from a FITS file's OBJECT header, or None."""
try:
with fits.open(str(path)) as hdul:
for hdu in hdul:
header = getattr(hdu, "header", None)
if header is None:
continue
value = header.get("OBJECT")
if value not in (None, ""):
text = str(value).strip()
if text:
return text
except Exception:
return None
return None
def _detect_object(paths) -> str | None:
"""Return a single object name shared by `paths`, or None.
`paths` may be a single path or an iterable of paths. The OBJECT header is
read from each frame; a name is returned only when every frame that has one
agrees. Returns None when no frame carries an OBJECT header or when frames
disagree.
"""
if isinstance(paths, (str, Path)):
paths = [paths]
found = {obj for obj in (_read_fits_object(p) for p in paths) if obj}
if len(found) == 1:
return next(iter(found))
return None
# ── Exposure / temperature detection for master-dark matching ──────────────
# Master darks are matched to a session by exposure time (must agree) and sensor
# temperature (nearest within a tolerance). For FITS masters the values come from
# the EXPTIME/EXPOSURE and CCD-TEMP/CCD_TEMP/TEMP headers. astropy cannot read
# XISF, so for XISF masters the values are parsed from the file name instead
# (e.g. "masterDark_300s_-10C.xisf", "masterDark_EXPTIME-300.00s_-10degC.xisf").
# Temperature tolerance (°C) when matching a master dark to a session.
MASTER_DARK_TEMP_TOLERANCE: float = 3.0
# Exposure tolerance (seconds) when matching a master dark to a session.
MASTER_DARK_EXP_TOLERANCE: float = 1.0
_EXPTIME_NAME_RE = re.compile(
r"exp(?:osure|time)?[\s_\-]*([0-9]+(?:\.[0-9]+)?)\s*(?:s|sec|secs|seconds)?",
re.IGNORECASE,
)
_EXPTIME_NAME_RE_GENERIC = re.compile(
r"([0-9]+(?:\.[0-9]+)?)\s*(?:s|sec|secs|seconds)\b",
re.IGNORECASE,
)
_TEMP_NAME_RE = re.compile(
# A single separator (space/_/=/:/-) is allowed between the key and the
# value; the value's own leading "-" is preserved so PixInsight-style
# "TEMP--15.0" (separator dash + negative value) parses as -15.0 rather
# than dropping the sign.
r"(?:ccd[\s_\-]*temp|temp)[\s_=:\-]?(-?[0-9]+(?:\.[0-9]+)?)",
re.IGNORECASE,
)
_TEMP_NAME_RE_GENERIC = re.compile(
r"(-?[0-9]+(?:\.[0-9]+)?)\s*(?:deg)?\s*c(?![a-z])",
re.IGNORECASE,
)
def _read_fits_exptime(path) -> float | None:
"""Return the exposure time (seconds) from a FITS EXPTIME/EXPOSURE header."""
try:
with fits.open(str(path)) as hdul:
for hdu in hdul:
header = getattr(hdu, "header", None)
if header is None:
continue
for key in ("EXPTIME", "EXPOSURE"):
value = header.get(key)
if value not in (None, ""):
try:
return float(value)
except (TypeError, ValueError):
continue
except Exception:
return None
return None
def _read_fits_temp(path) -> float | None:
"""Return the sensor temperature (°C) from a FITS CCD-TEMP header."""
try:
with fits.open(str(path)) as hdul:
for hdu in hdul:
header = getattr(hdu, "header", None)
if header is None:
continue
for key in ("CCD-TEMP", "CCD_TEMP", "CCDTEMP", "TEMP"):
value = header.get(key)
if value not in (None, ""):
try:
return float(value)
except (TypeError, ValueError):
continue
except Exception:
return None
return None
def _parse_exptime_from_name(name) -> float | None:
"""Parse an exposure time (seconds) from a file name, or None."""
stem = Path(name).stem
match = _EXPTIME_NAME_RE.search(stem) or _EXPTIME_NAME_RE_GENERIC.search(stem)
if match:
try:
return float(match.group(1))
except (TypeError, ValueError):
return None
return None
def _parse_temp_from_name(name) -> float | None:
"""Parse a sensor temperature (°C) from a file name, or None."""
stem = Path(name).stem
match = _TEMP_NAME_RE.search(stem) or _TEMP_NAME_RE_GENERIC.search(stem)
if match:
try:
return float(match.group(1))
except (TypeError, ValueError):
return None
return None
def _get_exptime_temp(path) -> tuple[float | None, float | None]:
"""Return (exposure_seconds, temperature_C) for a frame.
FITS frames are read from their headers, falling back to the file name for
any value the header does not provide. XISF frames (which astropy cannot
open) are parsed from the file name only.
"""
if _is_fits_file(path):
exptime = _read_fits_exptime(path)
temp = _read_fits_temp(path)
if exptime is None:
exptime = _parse_exptime_from_name(path)
if temp is None:
temp = _parse_temp_from_name(path)
return exptime, temp
return _parse_exptime_from_name(path), _parse_temp_from_name(path)
def _parse_dateobs_night(value) -> str | None:
"""Convert a FITS DATE-OBS value to the acquisition-night date (YYYY-MM-DD).
DATE-OBS is a UTC timestamp at the start of the exposure. Subtracting 12
hours before taking the date rolls frames captured after midnight back into
the night the session started, which is the convention AstroBin expects.
Returns None when the value cannot be parsed.
"""
if value in (None, ""):
return None
text = str(value).strip().rstrip("Z")
try:
dt = datetime.fromisoformat(text)
except ValueError:
# Date-only header (no time component): use the date as-is, since there
# is no exposure time to roll back across midnight.
try:
return datetime.strptime(text[:10], "%Y-%m-%d").date().isoformat()
except ValueError:
return None
return (dt - timedelta(hours=12)).date().isoformat()
def _read_light_metadata(path) -> dict:
"""Read AstroBin-relevant metadata from a single light frame's FITS header.
Returns a dict with any of: date, filterName, binning, gain, sensorCooling,
fNumber, duration. Missing values are omitted. XISF frames (which astropy
cannot open) yield only what can be parsed from the file name.
"""
meta: dict = {}
exptime, temp = _get_exptime_temp(path)
if exptime is not None:
meta["duration"] = exptime
if temp is not None:
meta["sensorCooling"] = temp
if not _is_fits_file(path):
return meta
try:
with fits.open(str(path)) as hdul:
header = {}
for hdu in hdul:
hdr = getattr(hdu, "header", None)
if hdr is not None:
for key in hdr.keys():
if key and key not in header:
header[key] = hdr.get(key)
except Exception:
return meta
def _first(*keys):
for key in keys:
val = header.get(key)
if val not in (None, ""):
return val
return None
night = _parse_dateobs_night(_first("DATE-OBS", "DATE_OBS"))
if night:
meta["date"] = night
filter_name = _first("FILTER")
if filter_name not in (None, ""):
meta["filterName"] = str(filter_name).strip()
binning = _first("XBINNING", "BINNING", "BINX")
if binning not in (None, ""):
try:
meta["binning"] = int(float(binning))
except (TypeError, ValueError):
pass
gain = _first("GAIN", "EGAIN")
if gain not in (None, ""):
try:
meta["gain"] = float(gain)
except (TypeError, ValueError):
pass
if "sensorCooling" not in meta:
cooling = _first("CCD-TEMP", "CCD_TEMP", "CCDTEMP", "SET-TEMP", "TEMP")
if cooling not in (None, ""):
try:
meta["sensorCooling"] = float(cooling)
except (TypeError, ValueError):
pass
fnumber = _first("FOCRATIO", "FNUMBER", "F-RATIO")
if fnumber not in (None, ""):
try:
meta["fNumber"] = float(fnumber)
except (TypeError, ValueError):
pass
if "duration" not in meta:
dur = _first("EXPTIME", "EXPOSURE")
if dur not in (None, ""):
try:
meta["duration"] = float(dur)
except (TypeError, ValueError):
pass
return meta
# ── Panel awareness (mosaic projects) ────────────────────────────────────────
# A "panel" is an optional grouping layer between the object folder and the
# session (date) folders. A folder is treated as a panel when its name contains
# the token "panel <n>" (case-insensitive, optional separators) anywhere in the
# name: "Panel 1", "panel1", "Panel_02", "PANEL-3", and also descriptive names
# like "Lagoon Nebula Panel 3" or "M8-M20 Panel_04". Panels let multiple
# sessions (e.g. the same tile shot on different nights, with their own
# calibration) be pooled into one stack per panel before the panels are
# stitched into a mosaic.
_PANEL_RE = re.compile(r"\bpanel[\s_\-]*0*(\d+)\b", re.IGNORECASE)
def _canonical_panel(name) -> str | None:
"""Return a normalised panel label ("Panel 1") for a folder name, or None.
The "panel <n>" token may appear anywhere in the name, so both a bare
"Panel 3" and a descriptive "Lagoon Nebula Panel 3" normalise to "Panel 3".
"""
if name is None:
return None
match = _PANEL_RE.search(str(name).strip())
if not match:
return None
return f"Panel {int(match.group(1))}"
def _panel_sort_key(name: str):
"""Sort key ordering panels numerically ("Panel 2" before "Panel 10")."""
match = _PANEL_RE.search(str(name).strip())
if match:
return (0, int(match.group(1)))
return (1, str(name))
@dataclass
class Session:
lights: List[Path] = field(default_factory=list)
darks: List[Path] = field(default_factory=list)
flats: List[Path] = field(default_factory=list)
biases: List[Path] = field(default_factory=list)
filter: str | None = None
object_name: str | None = None
panel: str | None = None
def add_files(self, image_type: str, file_paths: List[Path]):
if not hasattr(self, image_type):
raise ValueError(f"Unknown frame type: {image_type}")
getattr(self, image_type).extend(file_paths)
def get_file_lists(self) -> Dict[str, List[Path]]:
return {
"lights": self.lights,
"darks": self.darks,
"flats": self.flats,
"biases": self.biases,
}
def get_files_by_type(self, image_type: str) -> List[Path]:
if not hasattr(self, image_type):
raise ValueError(f"Unknown frame type: {image_type}")
return getattr(self, image_type)
def get_file_count(self) -> Dict[str, int]:
return {
"lights": len(self.lights),
"darks": len(self.darks),
"flats": len(self.flats),
"biases": len(self.biases),
}
def __str__(self):
counts = self.get_file_count()
return f"Session(L: {counts['lights']}, D: {counts['darks']}, F: {counts['flats']}, B: {counts['biases']})"
def reset(self):
self.lights.clear()
self.darks.clear()
self.flats.clear()
self.biases.clear()
self.filter = None
self.object_name = None
self.panel = None
class FileTypeDialog(QDialog):
"""Prompt the user to choose a frame type for drag-and-dropped files."""
FRAME_TYPES = ["Lights", "Darks", "Flats", "Biases"]
MASTER_TYPES = ["Master Dark", "Master Flat", "Master Bias"]
def __init__(
self,
file_count: int,
current_session_name: str = "Current Session",
all_session_names: list | None = None,
current_session_index: int = 0,
auto_filter: bool = False,
parent=None,
):
super().__init__(parent)
self._current_session_name = current_session_name
self._all_session_names = all_session_names or [current_session_name]
self._current_session_index = current_session_index
self._auto_filter = auto_filter
self.setWindowTitle("Select Frame Type")
self.setModal(True)
self.setMinimumWidth(320)
self.chosen_type: str | None = None
self.chosen_scope: str = "current" # "current", "selected", or "all"
self.chosen_session_indices: list = [current_session_index]
layout = QVBoxLayout(self)
plural = "s" if file_count != 1 else ""
layout.addWidget(
QLabel(
f"You dropped {file_count} file{plural}.\nWhat type of frames are these?"
)
)
for frame_type in self.FRAME_TYPES:
btn = QPushButton(frame_type)
btn.setMinimumHeight(50)
btn.setMinimumWidth(100)
if self._routes_by_filter(frame_type):
btn.clicked.connect(lambda checked, t=frame_type: self._select(t))
else:
btn.clicked.connect(
lambda checked, t=frame_type: self._select_master(t)
)
layout.addWidget(btn)
sep = QLabel("— Master calibration frames —")
sep.setAlignment(Qt.AlignmentFlag.AlignCenter)
sep.setStyleSheet(
"color: #888; font-style: italic; font-size: 11px; margin-top: 4px;"
)
layout.addWidget(sep)
for master_type in self.MASTER_TYPES:
btn = QPushButton(master_type)
btn.setMinimumHeight(50)
btn.setMinimumWidth(100)
btn.setStyleSheet(
"QPushButton { background-color: #e8f4e8; color: #1d4e2d; }"
" QPushButton:hover { background-color: #c3e6cb; }"
)
if self._routes_by_filter(master_type):
btn.clicked.connect(lambda checked, t=master_type: self._select(t))
else:
btn.clicked.connect(
lambda checked, t=master_type: self._select_master(t)
)
layout.addWidget(btn)
cancel_btn = QPushButton("Cancel")
cancel_btn.clicked.connect(self.reject)
layout.addWidget(cancel_btn)
def _routes_by_filter(self, type_str: str) -> bool:
"""Whether a frame type is routed to sessions by its FITS filter.
Lights always route by filter (one session per filter / current session).
In ``auto_filter`` mode (single-target drops) flats and master flats also
route by filter, so they skip the current/all/selected scope sub-prompt.
Darks and biases are filter-agnostic and keep the scope prompt.
"""
t = type_str.lower()
if t == "lights":
return True
if self._auto_filter and t in ("flats", "master flat"):
return True
return False
def _select(self, frame_type: str):
self.chosen_type = frame_type
self.chosen_scope = "current"
self.accept()
def _select_master(self, frame_type: str):
if len(self._all_session_names) <= 1:
self.chosen_type = frame_type
self.chosen_scope = "current"
self.accept()
return
sub = QDialog(self)
sub.setWindowTitle("Apply to which sessions?")
sub.setModal(True)
sub.setMinimumWidth(420)
sub_layout = QVBoxLayout(sub)
sub_layout.addWidget(QLabel(f"Add <b>{frame_type}</b> to:"))
# Put the session checkboxes inside a scroll area so that, with many
# sessions, the dialog stays a fixed height and the buttons below remain
# accessible instead of being pushed off-screen.
scroll = QScrollArea(sub)
scroll.setWidgetResizable(True)
scroll.setMaximumHeight(360)
scroll.setFrameShape(QFrame.Shape.NoFrame)
scroll_content = QWidget()
scroll_layout = QVBoxLayout(scroll_content)
scroll_layout.setContentsMargins(0, 0, 0, 0)
scroll_layout.setSpacing(4)
checkboxes: list[QCheckBox] = []
for i, name in enumerate(self._all_session_names):
cb = QCheckBox(name)
cb.setChecked(i == self._current_session_index)
checkboxes.append(cb)
scroll_layout.addWidget(cb)
scroll_layout.addStretch(1)
scroll.setWidget(scroll_content)
sub_layout.addWidget(scroll)
btn_row = QHBoxLayout()
selected_btn = QPushButton("Selected Sessions")
all_btn = QPushButton("All Sessions")
cancel_btn = QPushButton("Cancel")
btn_row.addWidget(selected_btn)
btn_row.addWidget(all_btn)
btn_row.addWidget(cancel_btn)
sub_layout.addLayout(btn_row)
result = {"action": None}
def on_selected():
result["action"] = "selected"
sub.accept()
def on_all():
result["action"] = "all"
sub.accept()
selected_btn.clicked.connect(on_selected)
all_btn.clicked.connect(on_all)
cancel_btn.clicked.connect(sub.reject)
if sub.exec() != QDialog.DialogCode.Accepted:
return # stay in outer dialog
if result["action"] == "all":
self.chosen_type = frame_type
self.chosen_scope = "all"
self.chosen_session_indices = list(range(len(self._all_session_names)))
self.accept()
elif result["action"] == "selected":
indices = [i for i, cb in enumerate(checkboxes) if cb.isChecked()]
if not indices:
return # nothing checked — stay in dialog
self.chosen_type = frame_type
self.chosen_scope = "selected"
self.chosen_session_indices = indices
self.accept()
# else: cancel — stay in outer dialog
class SortableTreeItem(QTreeWidgetItem):
"""Tree item with type-aware sorting.
The "#" column (column 0) sorts numerically rather than as text. Group-header
rows (those with ``group_order`` set) always keep their fixed insertion order
so the Lights/Darks/Flats/Biases sections never shuffle, no matter which
column the user sorts by.
"""
group_order = None # set on group-header rows to pin their position
def __lt__(self, other):
# Group headers are only ever compared against sibling group headers.
if (
self.group_order is not None
and getattr(other, "group_order", None) is not None
):
return self.group_order < other.group_order
tree = self.treeWidget()
column = tree.sortColumn() if tree is not None else 0
if column == 0:
return self._as_int(self.text(0)) < self._as_int(other.text(0))
return self.text(column).lower() < other.text(column).lower()
@staticmethod
def _as_int(text):
try:
return int(text)
except (TypeError, ValueError):
return 0
class DragDropTreeWidget(QTreeWidget):
"""A QTreeWidget (multi-column) that accepts file drag-and-drop and emits the dropped paths."""
_NORMAL_STYLE = ""
_HOVER_STYLE = (
"QTreeWidget { border: 2px dashed #2563eb;"
" background-color: rgba(37, 99, 235, 0.07); }"
)
def __init__(self, on_drop_callback, on_delete_callback=None, parent=None):
super().__init__(parent)
self._on_drop = on_drop_callback
self._on_delete = on_delete_callback
self.setAcceptDrops(True)
self.setDragDropMode(QAbstractItemView.DragDropMode.DropOnly)
def keyPressEvent(self, event):
if (
self._on_delete is not None
and self.selectedItems()
and event.key() in (Qt.Key.Key_Delete, Qt.Key.Key_Backspace)
):
self._on_delete()
else:
super().keyPressEvent(event)
def paintEvent(self, event):
super().paintEvent(event)
if self.topLevelItemCount() == 0:
painter = QPainter(self.viewport())
painter.save()
pen_color = self.palette().color(self.palette().ColorRole.PlaceholderText)
painter.setPen(pen_color)
font = painter.font()
font.setPointSize(9)
font.setItalic(True)
painter.setFont(font)
painter.drawText(
self.viewport().rect(),
Qt.AlignmentFlag.AlignCenter,
"Drop files or folders here\nor use the Add buttons above",
)
painter.restore()
def dragEnterEvent(self, event: QDragEnterEvent | None):
if event is None:
return
mime = event.mimeData()
if mime is not None and mime.hasUrls():
self.setStyleSheet(self._HOVER_STYLE)
event.acceptProposedAction()
else:
event.ignore()
def dragMoveEvent(self, event):
if event is None:
return
mime = event.mimeData()
if mime is not None and mime.hasUrls():
event.acceptProposedAction()
else:
event.ignore()
def dragLeaveEvent(self, event):
self.setStyleSheet(self._NORMAL_STYLE)
super().dragLeaveEvent(event)
def dropEvent(self, event: QDropEvent | None):
self.setStyleSheet(self._NORMAL_STYLE)
if event is None:
return
mime = event.mimeData()
if mime is None or not mime.hasUrls():
event.ignore()
return
paths = [Path(u.toLocalFile()) for u in mime.urls() if u.isLocalFile()]
if paths:
event.acceptProposedAction()
self._on_drop(paths)
else:
event.ignore()
class PreprocessingInterface(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle(f"{APP_NAME} - v{VERSION}")