deepcontrail-opencontrails 0.1.0__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.
@@ -0,0 +1,211 @@
1
+ Copyright (c) 2026 EUROCONTROL
2
+
3
+ # European Union Public Licence v. 1.2
4
+
5
+ EUPL © the European Union 2007, 2016
6
+
7
+ This European Union Public Licence (the *EUPL*) applies to the Work (as defined below) which is provided under the
8
+ terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such
9
+ use is covered by a right of the copyright holder of the Work).
10
+ The Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following
11
+ notice immediately following the copyright notice for the Work:
12
+
13
+ *Licensed under the EUPL or has expressed by any other means his willingness to license under the EUPL.*
14
+
15
+ ## 1. Definitions
16
+
17
+ In this Licence, the following terms have the following meaning:
18
+
19
+ * *The Licence*:this Licence.
20
+ * *The Original Work*:the work or software distributed or communicated by the Licensor under this Licence, available
21
+ as Source Code and also as Executable Code as the case may be.
22
+ * *Derivative Works*:the works or software that could be created by the Licensee, based upon the Original Work or
23
+ modifications thereof. This Licence does not define the extent of modification or dependence on the Original Work
24
+ required in order to classify a work as a Derivative Work; this extent is determined by copyright law applicable in
25
+ the country mentioned in Article 15.
26
+ * *The Work*:the Original Work or its Derivative Works.
27
+ * *The Source Code*:the human-readable form of the Work which is the most convenient for people to study and
28
+ modify.
29
+ * *The Executable Code*:any code which has generally been compiled and which is meant to be interpreted by
30
+ a computer as a program.
31
+ * *The Licensor*:the natural or legal person that distributes or communicates the Work under the Licence.
32
+ * *Contributor(s)*:any natural or legal person who modifies the Work under the Licence, or otherwise contributes to
33
+ the creation of a Derivative Work.
34
+ * *The Licensee* or *You*:any natural or legal person who makes any usage of the Work under the terms of the
35
+ Licence.
36
+ * *Distribution* or *Communication*:any act of selling, giving, lending, renting, distributing, communicating,
37
+ transmitting, or otherwise making available, online or offline, copies of the Work or providing access to its essential
38
+ functionalities at the disposal of any other natural or legal person.
39
+
40
+ ## 2. Scope of the rights granted by the Licence
41
+
42
+ The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, sublicensable licence to do the following, for
43
+ the duration of copyright vested in the Original Work:
44
+
45
+ * use the Work in any circumstance and for all usage,
46
+ * reproduce the Work,
47
+ * modify the Work, and make Derivative Works based upon the Work,
48
+ * communicate to the public, including the right to make available or display the Work or copies thereof to the public
49
+ and perform publicly, as the case may be, the Work,
50
+ * distribute the Work or copies thereof,
51
+ * lend and rent the Work or copies thereof,
52
+ * sublicense rights in the Work or copies thereof.
53
+ Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the
54
+ applicable law permits so.
55
+ In the countries where moral rights apply, the Licensor waives his right to exercise his moral right to the extent allowed
56
+ by law in order to make effective the licence of the economic rights here above listed.
57
+ The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to any patents held by the Licensor, to the
58
+ extent necessary to make use of the rights granted on the Work under this Licence.
59
+
60
+ ## 3. Communication of the Source Code
61
+
62
+ The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as
63
+ Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with
64
+ each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to
65
+ the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to
66
+ distribute or communicate the Work.
67
+
68
+ ## 4. Limitations on copyright
69
+
70
+ Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the
71
+ exclusive rights of the rights owners in the Work, of the exhaustion of those rights or of other applicable limitations
72
+ thereto.
73
+
74
+ ## 5. Obligations of the Licensee
75
+
76
+ The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the Licensee. Those
77
+ obligations are the following:
78
+
79
+ **Attribution right**: The Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to
80
+ the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the
81
+ Licence with every copy of the Work he/she distributes or communicates. The Licensee must cause any Derivative Work
82
+ to carry prominent notices stating that the Work has been modified and the date of modification.
83
+
84
+ **Copyleft clause**: If the Licensee distributes or communicates copies of the Original Works or Derivative Works, this
85
+ Distribution or Communication will be done under the terms of this Licence or of a later version of this Licence unless
86
+ the Original Work is expressly distributed only under this version of the Licence — for example by communicating
87
+ *EUPL v. 1.2 only*. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the
88
+ Work or Derivative Work that alter or restrict the terms of the Licence.
89
+
90
+ **Compatibility clause**: If the Licensee Distributes or Communicates Derivative Works or copies thereof based upon both
91
+ the Work and another work licensed under a Compatible Licence, this Distribution or Communication can be done
92
+ under the terms of this Compatible Licence. For the sake of this clause, *Compatible Licence* refers to the licences listed
93
+ in the appendix attached to this Licence. Should the Licensee's obligations under the Compatible Licence conflict with
94
+ his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail.
95
+
96
+ **Provision of Source Code**: When distributing or communicating copies of the Work, the Licensee will provide
97
+ a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available
98
+ for as long as the Licensee continues to distribute or communicate the Work.
99
+ Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names
100
+ of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and
101
+ reproducing the content of the copyright notice.
102
+
103
+ ## 6. Chain of Authorship
104
+
105
+ The original Licensor warrants that the copyright in the Original Work granted hereunder is owned by him/her or
106
+ licensed to him/her and that he/she has the power and authority to grant the Licence.
107
+ Each Contributor warrants that the copyright in the modifications he/she brings to the Work are owned by him/her or
108
+ licensed to him/her and that he/she has the power and authority to grant the Licence.
109
+ Each time You accept the Licence, the original Licensor and subsequent Contributors grant You a licence to their contributions
110
+ to the Work, under the terms of this Licence.
111
+
112
+ ## 7. Disclaimer of Warranty
113
+
114
+ The Work is a work in progress, which is continuously improved by numerous Contributors. It is not a finished work
115
+ and may therefore contain defects or *bugs* inherent to this type of development.
116
+ For the above reason, the Work is provided under the Licence on an *as is* basis and without warranties of any kind
117
+ concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or
118
+ errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this
119
+ Licence.
120
+ This disclaimer of warranty is an essential part of the Licence and a condition for the grant of any rights to the Work.
121
+
122
+ ## 8. Disclaimer of Liability
123
+
124
+ Except in the cases of wilful misconduct or damages directly caused to natural persons, the Licensor will in no event be
125
+ liable for any direct or indirect, material or moral, damages of any kind, arising out of the Licence or of the use of the
126
+ Work, including without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss
127
+ of data or any commercial damage, even if the Licensor has been advised of the possibility of such damage. However,
128
+ the Licensor will be liable under statutory product liability laws as far such laws apply to the Work.
129
+
130
+ ## 9. Additional agreements
131
+
132
+ While distributing the Work, You may choose to conclude an additional agreement, defining obligations or services
133
+ consistent with this Licence. However, if accepting obligations, You may act only on your own behalf and on your sole
134
+ responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify,
135
+ defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by
136
+ the fact You have accepted any warranty or additional liability.
137
+
138
+ ## 10. Acceptance of the Licence
139
+
140
+ The provisions of this Licence can be accepted by clicking on an icon *I agree* placed under the bottom of a window
141
+ displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of
142
+ applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms
143
+ and conditions.
144
+ Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You
145
+ by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution
146
+ or Communication by You of the Work or copies thereof.
147
+
148
+ ## 11. Information to the public
149
+
150
+ In case of any Distribution or Communication of the Work by means of electronic communication by You (for example,
151
+ by offering to download the Work from a remote location) the distribution channel or media (for example, a website)
152
+ must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence
153
+ and the way it may be accessible, concluded, stored and reproduced by the Licensee.
154
+
155
+ ## 12. Termination of the Licence
156
+
157
+ The Licence and the rights granted hereunder will terminate automatically upon any breach by the Licensee of the terms
158
+ of the Licence.
159
+ Such a termination will not terminate the licences of any person who has received the Work from the Licensee under
160
+ the Licence, provided such persons remain in full compliance with the Licence.
161
+
162
+ ## 13. Miscellaneous
163
+
164
+ Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the
165
+ Work.
166
+ If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or
167
+ enforceability of the Licence as a whole. Such provision will be construed or reformed so as necessary to make it valid
168
+ and enforceable.
169
+ The European Commission may publish other linguistic versions or new versions of this Licence or updated versions of
170
+ the Appendix, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence.
171
+ New versions of the Licence will be published with a unique version number.
172
+ All linguistic versions of this Licence, approved by the European Commission, have identical value. Parties can take
173
+ advantage of the linguistic version of their choice.
174
+
175
+ ## 14. Jurisdiction
176
+
177
+ Without prejudice to specific agreement between parties,
178
+
179
+ * any litigation resulting from the interpretation of this License, arising between the European Union institutions,
180
+ bodies, offices or agencies, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice
181
+ of the European Union, as laid down in article 272 of the Treaty on the Functioning of the European Union,
182
+ * any litigation arising between other parties and resulting from the interpretation of this License, will be subject to
183
+ the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business.
184
+
185
+ ## 15. Applicable Law
186
+
187
+ Without prejudice to specific agreement between parties,
188
+
189
+ * this Licence shall be governed by the law of the European Union Member State where the Licensor has his seat,
190
+ resides or has his registered office,
191
+ * this licence shall be governed by Belgian law if the Licensor has no seat, residence or registered office inside
192
+ a European Union Member State.
193
+
194
+ ## Appendix
195
+
196
+ *Compatible* Licences according to Article 5 EUPL are:
197
+
198
+ * GNU General Public License (GPL) v. 2, v. 3
199
+ * GNU Affero General Public License (AGPL) v. 3
200
+ * Open Software License (OSL) v. 2.1, v. 3.0
201
+ * Eclipse Public License (EPL) v. 1.0
202
+ * CeCILL v. 2.0, v. 2.1
203
+ * Mozilla Public Licence (MPL) v. 2
204
+ * GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
205
+ * Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for works other than software
206
+ * European Union Public Licence (EUPL) v. 1.1, v. 1.2
207
+ * Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong Reciprocity (LiLiQ-R+).
208
+ The European Commission may update this Appendix to later versions of the above licences without producing
209
+ a new version of the EUPL, as long as they provide the rights granted in Article 2 of this Licence and protect the
210
+ covered Source Code from exclusive appropriation.
211
+ All other changes or additions to this Appendix require the production of a new EUPL version.
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: deepcontrail-opencontrails
3
+ Version: 0.1.0
4
+ Summary: Converter from the raw OpenContrails TFRecords to the DeepContrail dataset layout.
5
+ Keywords: contrails,OpenContrails,GOES,remote-sensing,satellite,dataset
6
+ Author: EUROCONTROL
7
+ License-Expression: EUPL-1.2
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
15
+ Requires-Dist: deepcontrail-core>=0.1,<0.2
16
+ Requires-Dist: numpy>=1.24
17
+ Requires-Dist: pillow>=10.0
18
+ Requires-Dist: tensorflow>=2.21,<3
19
+ Requires-Python: >=3.11
20
+ Project-URL: Homepage, https://github.com/eurocontrol-asu/deepcontrail
21
+ Project-URL: Documentation, https://github.com/eurocontrol-asu/deepcontrail/tree/main/tools/opencontrails#readme
22
+ Project-URL: Repository, https://github.com/eurocontrol-asu/deepcontrail
23
+ Project-URL: Issues, https://github.com/eurocontrol-asu/deepcontrail/issues
24
+ Project-URL: Changelog, https://github.com/eurocontrol-asu/deepcontrail/blob/main/CHANGELOG.md
25
+ Description-Content-Type: text/markdown
26
+
27
+ # deepcontrail-opencontrails
28
+
29
+ Converts the raw [OpenContrails](https://sites.research.google/gr/contrails/public-datasets/) GOES-16
30
+ TFRecords into the [DeepContrail dataset format](https://github.com/eurocontrol-asu/deepcontrail/tree/main/packages/core). It is one producer of that
31
+ format, not part of the library, and it needs TensorFlow.
32
+
33
+ The TFRecords are in the public Google Cloud Storage bucket `goes_contrails_dataset`; download an
34
+ export with the [Google Cloud CLI](https://cloud.google.com/sdk/docs/install):
35
+
36
+ ```bash
37
+ gcloud storage cp -r gs://goes_contrails_dataset/20250305 .
38
+ ```
39
+
40
+ The OpenContrails data is published by Google Research under the
41
+ [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) licence; GOES-16 imagery is courtesy of
42
+ NOAA. If you use it, cite Ng et al. (2024), "Contrail Detection on GOES-16 ABI With the
43
+ OpenContrails Dataset", *IEEE Transactions on Geoscience and Remote Sensing* 62, 1-14.
44
+
45
+ ```bash
46
+ pip install deepcontrail-opencontrails # installs TensorFlow and deepcontrail-core
47
+ deepcontrail-convert-opencontrails \
48
+ --tfrecord-dir /path/to/20250305/tfrecords --output-dir /path/to/dataset
49
+ deepcontrail-validate /path/to/dataset --deep
50
+ ```
51
+
52
+ - Training shards go to `train/`, validation shards to `test/` (the holdout).
53
+ - Each record is named by its OpenContrails `record_id`, so a subset of shards (`--file-glob`)
54
+ converts to the same names as a full run.
55
+ - Conversion resumes: complete records are skipped (`--no-skip-existing` rewrites them).
56
+ - `spectral_bands/<id>.npy` holds 10 channels: 9 infrared ABI bands and their split-window
57
+ difference. `bands.json` maps each key to its ABI band (`data_10um` is band 13, `cloud_top`
58
+ band 11). The preview JPEGs use the standard ash RGB.
59
+ - `metadata/dataset_info.json` records the export and its pixel shift: `20250305` masks are
60
+ aligned with the images (0.0), `20230419` masks follow the Kaggle convention (0.5).
61
+ - `--metadata-only` rewrites just the two metadata files of an already converted dataset,
62
+ without the TFRecords or TensorFlow.
@@ -0,0 +1,36 @@
1
+ # deepcontrail-opencontrails
2
+
3
+ Converts the raw [OpenContrails](https://sites.research.google/gr/contrails/public-datasets/) GOES-16
4
+ TFRecords into the [DeepContrail dataset format](https://github.com/eurocontrol-asu/deepcontrail/tree/main/packages/core). It is one producer of that
5
+ format, not part of the library, and it needs TensorFlow.
6
+
7
+ The TFRecords are in the public Google Cloud Storage bucket `goes_contrails_dataset`; download an
8
+ export with the [Google Cloud CLI](https://cloud.google.com/sdk/docs/install):
9
+
10
+ ```bash
11
+ gcloud storage cp -r gs://goes_contrails_dataset/20250305 .
12
+ ```
13
+
14
+ The OpenContrails data is published by Google Research under the
15
+ [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) licence; GOES-16 imagery is courtesy of
16
+ NOAA. If you use it, cite Ng et al. (2024), "Contrail Detection on GOES-16 ABI With the
17
+ OpenContrails Dataset", *IEEE Transactions on Geoscience and Remote Sensing* 62, 1-14.
18
+
19
+ ```bash
20
+ pip install deepcontrail-opencontrails # installs TensorFlow and deepcontrail-core
21
+ deepcontrail-convert-opencontrails \
22
+ --tfrecord-dir /path/to/20250305/tfrecords --output-dir /path/to/dataset
23
+ deepcontrail-validate /path/to/dataset --deep
24
+ ```
25
+
26
+ - Training shards go to `train/`, validation shards to `test/` (the holdout).
27
+ - Each record is named by its OpenContrails `record_id`, so a subset of shards (`--file-glob`)
28
+ converts to the same names as a full run.
29
+ - Conversion resumes: complete records are skipped (`--no-skip-existing` rewrites them).
30
+ - `spectral_bands/<id>.npy` holds 10 channels: 9 infrared ABI bands and their split-window
31
+ difference. `bands.json` maps each key to its ABI band (`data_10um` is band 13, `cloud_top`
32
+ band 11). The preview JPEGs use the standard ash RGB.
33
+ - `metadata/dataset_info.json` records the export and its pixel shift: `20250305` masks are
34
+ aligned with the images (0.0), `20230419` masks follow the Kaggle convention (0.5).
35
+ - `--metadata-only` rewrites just the two metadata files of an already converted dataset,
36
+ without the TFRecords or TensorFlow.
@@ -0,0 +1,59 @@
1
+ [project]
2
+ name = "deepcontrail-opencontrails"
3
+ version = "0.1.0"
4
+ description = "Converter from the raw OpenContrails TFRecords to the DeepContrail dataset layout."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "EUPL-1.2"
8
+ license-files = ["LICENSE"]
9
+ keywords = [
10
+ "contrails",
11
+ "OpenContrails",
12
+ "GOES",
13
+ "remote-sensing",
14
+ "satellite",
15
+ "dataset",
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 3 - Alpha",
19
+ "Intended Audience :: Science/Research",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Scientific/Engineering :: Image Processing",
24
+ ]
25
+ dependencies = [
26
+ "deepcontrail-core>=0.1,<0.2",
27
+ "numpy>=1.24",
28
+ "pillow>=10.0",
29
+ "tensorflow>=2.21,<3",
30
+ ]
31
+
32
+ [[project.authors]]
33
+ name = "EUROCONTROL"
34
+
35
+ [project.scripts]
36
+ deepcontrail-convert-opencontrails = "deepcontrail.opencontrails.convert:main"
37
+
38
+ [project.urls]
39
+ Homepage = "https://github.com/eurocontrol-asu/deepcontrail"
40
+ Documentation = "https://github.com/eurocontrol-asu/deepcontrail/tree/main/tools/opencontrails#readme"
41
+ Repository = "https://github.com/eurocontrol-asu/deepcontrail"
42
+ Issues = "https://github.com/eurocontrol-asu/deepcontrail/issues"
43
+ Changelog = "https://github.com/eurocontrol-asu/deepcontrail/blob/main/CHANGELOG.md"
44
+
45
+ [dependency-groups]
46
+ dev = [
47
+ "pytest>=7.4",
48
+ "pyright>=1.1",
49
+ ]
50
+
51
+ [tool.uv.sources.deepcontrail-core]
52
+ workspace = true
53
+
54
+ [tool.uv.build-backend]
55
+ module-name = "deepcontrail.opencontrails"
56
+
57
+ [build-system]
58
+ requires = ["uv_build>=0.10.2,<0.14.0"]
59
+ build-backend = "uv_build"
@@ -0,0 +1,48 @@
1
+ [project]
2
+ name = "deepcontrail-opencontrails"
3
+ version = "0.1.0"
4
+ description = "Converter from the raw OpenContrails TFRecords to the DeepContrail dataset layout."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "EUPL-1.2"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "EUROCONTROL" }]
10
+ keywords = ["contrails", "OpenContrails", "GOES", "remote-sensing", "satellite", "dataset"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: Science/Research",
14
+ "Programming Language :: Python :: 3.11",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3.13",
17
+ "Topic :: Scientific/Engineering :: Image Processing",
18
+ ]
19
+ dependencies = [
20
+ "deepcontrail-core>=0.1,<0.2",
21
+ "numpy>=1.24",
22
+ "pillow>=10.0",
23
+ # The lock holds the tested version; pip users get any 2.x from it on.
24
+ "tensorflow>=2.21,<3",
25
+ ]
26
+
27
+ [project.scripts]
28
+ deepcontrail-convert-opencontrails = "deepcontrail.opencontrails.convert:main"
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/eurocontrol-asu/deepcontrail"
32
+ Documentation = "https://github.com/eurocontrol-asu/deepcontrail/tree/main/tools/opencontrails#readme"
33
+ Repository = "https://github.com/eurocontrol-asu/deepcontrail"
34
+ Issues = "https://github.com/eurocontrol-asu/deepcontrail/issues"
35
+ Changelog = "https://github.com/eurocontrol-asu/deepcontrail/blob/main/CHANGELOG.md"
36
+
37
+ [dependency-groups]
38
+ dev = ["pytest>=7.4", "pyright>=1.1"]
39
+
40
+ [tool.uv.sources]
41
+ deepcontrail-core = { workspace = true }
42
+
43
+ [build-system]
44
+ requires = ["uv_build>=0.10.2,<0.14.0"]
45
+ build-backend = "uv_build"
46
+
47
+ [tool.uv.build-backend]
48
+ module-name = "deepcontrail.opencontrails"
@@ -0,0 +1,7 @@
1
+ """Converter from the raw OpenContrails TFRecords to the DeepContrail dataset layout."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("deepcontrail-opencontrails")
6
+
7
+ __all__ = ["__version__"]
@@ -0,0 +1,69 @@
1
+ """OpenContrails spectral band keys and what each one holds (written to bands.json).
2
+
3
+ Channel order of every ``spectral_bands/{split}/{stem}.npy`` file written by the converter.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import dataclasses
9
+ from typing import Literal, get_args
10
+
11
+ SpectralBand = Literal[
12
+ "data_10um",
13
+ "data_11um",
14
+ "data_12um",
15
+ "brightness_temperature_difference",
16
+ "cloud_top",
17
+ "co2",
18
+ "low_vapor",
19
+ "mid_vapor",
20
+ "upper_vapor",
21
+ "ozone",
22
+ ]
23
+ """OpenContrails band key.
24
+
25
+ ``data_10um`` is ABI band 13 (10.3 µm); ``cloud_top`` is ABI band 11 (8.4 µm).
26
+ """
27
+
28
+ SPECTRAL_BAND_KEYS: tuple[str, ...] = get_args(SpectralBand)
29
+ """Channel order of every ``spectral_bands/{split}/{stem}.npy`` file, shape ``(H, W, 10)``."""
30
+
31
+
32
+ @dataclasses.dataclass(frozen=True)
33
+ class SpectralBandInfo:
34
+ """What one OpenContrails band key holds.
35
+
36
+ Parameters
37
+ ----------
38
+ abi_band
39
+ GOES-16 ABI band number, or ``None`` for a derived channel.
40
+ wavelength_um
41
+ ABI central wavelength in µm, or ``None`` for a derived channel.
42
+ name
43
+ NOAA name of the band (or a description of the derived channel).
44
+ derived_from
45
+ ``(a, b)`` when the channel is ``a - b`` of two other keys.
46
+ """
47
+
48
+ abi_band: int | None
49
+ wavelength_um: float | None
50
+ name: str
51
+ derived_from: tuple[str, str] | None = None
52
+
53
+
54
+ # Verified by exact match of OpenContrails TFRecord keys against Kaggle's labelled band_XX files.
55
+ SPECTRAL_BAND_INFO: dict[str, SpectralBandInfo] = {
56
+ "data_10um": SpectralBandInfo(13, 10.33, "Clean IR longwave window"),
57
+ "data_11um": SpectralBandInfo(14, 11.19, "IR longwave window"),
58
+ "data_12um": SpectralBandInfo(15, 12.27, "Dirty IR longwave window"),
59
+ "brightness_temperature_difference": SpectralBandInfo(
60
+ None, None, "Split-window difference", derived_from=("data_11um", "data_12um")
61
+ ),
62
+ "cloud_top": SpectralBandInfo(11, 8.44, "Cloud-top phase"),
63
+ "co2": SpectralBandInfo(16, 13.27, "CO2 longwave IR"),
64
+ "low_vapor": SpectralBandInfo(10, 7.34, "Lower-level tropospheric water vapor"),
65
+ "mid_vapor": SpectralBandInfo(9, 6.93, "Mid-level tropospheric water vapor"),
66
+ "upper_vapor": SpectralBandInfo(8, 6.19, "Upper-level tropospheric water vapor"),
67
+ "ozone": SpectralBandInfo(12, 9.61, "Ozone"),
68
+ }
69
+ """Band number, wavelength and name of each ``SPECTRAL_BAND_KEYS`` entry."""
@@ -0,0 +1,703 @@
1
+ """Convert raw OpenContrails TFRecords into the DeepContrail filesystem layout.
2
+
3
+ The raw OpenContrails export stores each sample as one TFRecord holding serialized
4
+ fields (thermal bands, per-annotator masks, the consensus pixel mask, ...). This
5
+ module decodes the shards into the layout the rest of the pipeline expects::
6
+
7
+ <output-dir>/
8
+ spectral_bands/{train,test}/{stem}.npy # float32 (H, W, 10), SPECTRAL_BAND_KEYS order
9
+ spectral_bands/bands.json # format v1: channel key, sensor band, units
10
+ images_semantic/{train,test}/{stem}.jpg # uint8 preview, standard ash RGB
11
+ semantic_masks/{train,test}/{stem}.png # consensus mask, values {0, 255}
12
+ probability_masks/{train,test}/{stem}.npy # float32 (H, W), mean of the annotators
13
+ annotator_masks/{train,test}/{stem}.npy # uint8 (H, W, n_annotators)
14
+ instance_masks/{train,test}/{stem}.npy # int8 (N, H, W, K), 20250305 only
15
+ splits_{train,test}.txt # stems with a consensus mask
16
+ metadata/dataset_info.json # format v1: counts, labels, pixel_shift
17
+
18
+ Each sample is named after its TFRecord ``record_id`` (``{stem}`` above), so a name
19
+ does not depend on shard order: any subset of shards (``--file-glob``) converts to
20
+ the same names as a full run.
21
+
22
+ * Raw ``train`` shards go to ``train/``. Validation is drawn from ``train/`` at
23
+ load time (``SegmentationDataConfig.val_fraction`` or ``fold``), so no ``val/`` folder exists.
24
+ * Raw ``validation`` shards (Kaggle's validation set) go to ``test/``.
25
+
26
+ No composite is stored as ``.npy``: training builds it at load time from
27
+ ``spectral_bands/`` with the bands configured in ``SegmentationDataConfig.false_color``.
28
+
29
+ Two export flavours are handled transparently (auto-detected from the first record):
30
+
31
+ * **20250305 (single-frame):** bands are ``(H, W, 1)``; instance masks are present.
32
+ * **20230419 (temporal clips):** bands are ``(H, W, 8)``: ``n_times_before`` frames,
33
+ the labelled frame, then ``n_times_after`` frames. Every frame is written; only the
34
+ labelled frame (plain ``{stem}``) has masks. Context frames are named by their
35
+ distance to it: ``{stem}_b4`` … ``{stem}_b1`` and ``{stem}_a1`` … ``{stem}_a3``.
36
+ No instance masks.
37
+
38
+ Every file is written atomically (temp file + rename), so an existing file is always
39
+ complete. By default a record is skipped when its consensus mask and every frame's
40
+ spectral bands and preview exist, which makes an interrupted run resumable;
41
+ ``--no-skip-existing`` rewrites everything.
42
+
43
+ Run it as ``deepcontrail-convert-opencontrails --tfrecord-dir ... --output-dir ...``
44
+ (``uv sync --group convert`` installs it with TensorFlow).
45
+
46
+ TensorFlow is imported lazily, only when shards are
47
+ decoded, so this module can be imported next to torch (e.g. in the test suite).
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import argparse
53
+ import dataclasses
54
+ import fnmatch
55
+ import functools
56
+ import os
57
+ import sys
58
+ from pathlib import Path
59
+ from typing import TYPE_CHECKING
60
+
61
+ import numpy as np
62
+ from PIL import Image
63
+
64
+ from deepcontrail.core.contract import (
65
+ BAND_MANIFEST_PATH,
66
+ DATASET_INFO_PATH,
67
+ BandChannel,
68
+ BandManifest,
69
+ DatasetContractError,
70
+ DatasetInfo,
71
+ Label,
72
+ read_dataset_info,
73
+ )
74
+ from deepcontrail.core.false_color import (
75
+ FalseColorChannel,
76
+ FalseColorConfig,
77
+ false_color_from_spectral,
78
+ )
79
+ from deepcontrail.core.splits import context_frames
80
+ from deepcontrail.opencontrails.bands import SPECTRAL_BAND_INFO, SPECTRAL_BAND_KEYS
81
+
82
+ if TYPE_CHECKING:
83
+ import tensorflow as tf
84
+
85
+ # Silence TensorFlow's CUDA/GPU chatter; this is a CPU-bound conversion.
86
+ os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")
87
+
88
+ _SPLITS = ("train", "test")
89
+
90
+
91
+ @dataclasses.dataclass(frozen=True)
92
+ class FormatInfo:
93
+ """Auto-detected TFRecord format metadata."""
94
+
95
+ is_temporal: bool
96
+ has_instance_masks: bool
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # Protobuf field extraction
101
+ # ---------------------------------------------------------------------------
102
+
103
+
104
+ def _feature_bytes(example: tf.train.Example, key: str) -> bytes | None:
105
+ """Return the first serialized ``bytes_list`` value for ``key``, or ``None``."""
106
+ fv = example.features.feature.get(key, None)
107
+ if fv is None or fv.WhichOneof("kind") != "bytes_list":
108
+ return None
109
+ values = list(fv.bytes_list.value)
110
+ return values[0] if values else None
111
+
112
+
113
+ def _scalar_int(example: tf.train.Example, key: str) -> int | None:
114
+ """Return the first ``int64_list`` scalar for ``key``, or ``None``."""
115
+ fv = example.features.feature.get(key, None)
116
+ if fv is None or fv.WhichOneof("kind") != "int64_list":
117
+ return None
118
+ values = list(fv.int64_list.value)
119
+ return int(values[0]) if values else None
120
+
121
+
122
+ def _decode_mask(example: tf.train.Example, key: str) -> np.ndarray | None:
123
+ """Decode a serialized int32 mask tensor, or ``None`` if the field is absent."""
124
+ import tensorflow as tf
125
+
126
+ raw = _feature_bytes(example, key)
127
+ if raw is None:
128
+ return None
129
+ return tf.io.parse_tensor(raw, out_type=tf.int32).numpy()
130
+
131
+
132
+ def _decode_bands(example: tf.train.Example) -> dict[str, np.ndarray]:
133
+ """Decode all spectral band tensors into ``(H, W, T)`` float64 arrays."""
134
+ import tensorflow as tf
135
+
136
+ decoded: dict[str, np.ndarray] = {}
137
+ for key in SPECTRAL_BAND_KEYS:
138
+ raw = _feature_bytes(example, key)
139
+ if raw is not None:
140
+ decoded[key] = tf.io.parse_tensor(raw, out_type=tf.float64).numpy()
141
+ return decoded
142
+
143
+
144
+ # ---------------------------------------------------------------------------
145
+ # Naming
146
+ # ---------------------------------------------------------------------------
147
+
148
+
149
+ def _record_stem(record_id: int | None) -> str:
150
+ """Name a sample after its TFRecord ``record_id``.
151
+
152
+ Raises
153
+ ------
154
+ ValueError
155
+ If the record has no ``record_id``: there is no order-independent name.
156
+ """
157
+ if record_id is None:
158
+ msg = "TFRecord has no record_id; cannot name the sample"
159
+ raise ValueError(msg)
160
+ return str(record_id)
161
+
162
+
163
+ def _frame_stem(base_stem: str, t: int, label_idx: int, n_frames: int) -> str:
164
+ """Compute the output filename stem for frame ``t`` within a clip."""
165
+ if n_frames == 1 or t == label_idx:
166
+ return base_stem
167
+ if t < label_idx:
168
+ return f"{base_stem}_b{label_idx - t}"
169
+ return f"{base_stem}_a{t - label_idx}"
170
+
171
+
172
+ # ---------------------------------------------------------------------------
173
+ # Per-frame extraction
174
+ # ---------------------------------------------------------------------------
175
+
176
+
177
+ def _band_frame(bands: dict[str, np.ndarray], key: str, t: int) -> np.ndarray:
178
+ """Return band ``key`` at frame ``t`` as a 2-D ``(H, W)`` float64 array."""
179
+ return bands[key][:, :, t]
180
+
181
+
182
+ # Standard ash RGB (OpenContrails paper): G = band14 - band11, i.e. data_11um - cloud_top.
183
+ _PREVIEW_FALSE_COLOR = FalseColorConfig(
184
+ channels=(
185
+ FalseColorChannel(bands=("data_12um", "data_11um"), bounds=(-4.0, 2.0)),
186
+ FalseColorChannel(bands=("data_11um", "cloud_top"), bounds=(-4.0, 5.0)),
187
+ FalseColorChannel(bands=("data_11um",), bounds=(243.0, 303.0)),
188
+ )
189
+ )
190
+
191
+
192
+ def _preview_rgb(spectral: np.ndarray) -> np.ndarray:
193
+ """Render a ``(H, W, 10)`` spectral frame as a uint8 standard ash RGB preview.
194
+
195
+ Written to ``images_semantic/``. Spectral training does not use these; it
196
+ builds its composite at load time from ``spectral_bands/`` with the bands
197
+ set in ``SegmentationDataConfig.false_color``.
198
+ """
199
+ rgb = false_color_from_spectral(spectral, _PREVIEW_FALSE_COLOR, _band_manifest())
200
+ return (rgb * 255).astype(np.uint8)
201
+
202
+
203
+ def _spectral_bands_frame(bands: dict[str, np.ndarray], t: int) -> np.ndarray:
204
+ """Stack all 10 thermal bands at frame ``t`` into ``(H, W, 10)`` float32."""
205
+ return np.stack([_band_frame(bands, key, t) for key in SPECTRAL_BAND_KEYS], axis=-1).astype(
206
+ np.float32
207
+ )
208
+
209
+
210
+ # ---------------------------------------------------------------------------
211
+ # Mask processing
212
+ # ---------------------------------------------------------------------------
213
+
214
+
215
+ def _probability_mask(individual: np.ndarray) -> np.ndarray:
216
+ """Consensus probability mask = mean of the annotators' binary masks.
217
+
218
+ ``individual`` has shape ``(H, W, 1, A)``; the result is ``(H, W)`` float32.
219
+ """
220
+ return (
221
+ individual.reshape(individual.shape[0], individual.shape[1], -1)
222
+ .mean(axis=-1)
223
+ .astype(np.float32)
224
+ )
225
+
226
+
227
+ def _annotator_masks(individual: np.ndarray) -> np.ndarray:
228
+ """Return the per-annotator binary masks as ``(H, W, A)`` uint8."""
229
+ return individual.reshape(individual.shape[0], individual.shape[1], -1).astype(np.uint8)
230
+
231
+
232
+ def _instance_masks(instance: np.ndarray) -> np.ndarray:
233
+ """Return instance masks as ``(N, H, W, K)`` int8.
234
+
235
+ Source shape is ``(N, H, W, 1, K)``; the trailing ``(1, K)`` collapses to a
236
+ single ``K`` dim whose width varies per sample. Records with no annotated
237
+ instances have ``N == 0`` and are emitted as an empty ``(0, H, W, K)`` array.
238
+ """
239
+ lead = list(instance.shape[:3])
240
+ trailing = 1
241
+ for dim in instance.shape[3:]:
242
+ trailing *= dim
243
+ return instance.reshape(*tuple(lead), trailing).astype(np.int8)
244
+
245
+
246
+ def _consensus_mask_png(pixel_mask: np.ndarray) -> np.ndarray:
247
+ """Binary consensus mask as a ``(H, W)`` uint8 array with values {0, 255}."""
248
+ mask = pixel_mask.reshape(pixel_mask.shape[0], pixel_mask.shape[1])
249
+ return (mask * 255).astype(np.uint8)
250
+
251
+
252
+ def _verify_consensus(png_path: Path, pixel_mask: np.ndarray, stem: str) -> None:
253
+ """Raise if the record's consensus mask differs from an existing PNG.
254
+
255
+ Used when re-converting into an existing dataset: a mismatch means the data
256
+ on disk and the TFRecords disagree, so fail loudly rather than overwrite.
257
+ """
258
+ with Image.open(png_path) as img:
259
+ png = np.array(img.convert("L"), dtype=np.uint8)
260
+ binary = (png > 0).astype(np.uint8)
261
+ consensus = pixel_mask.reshape(pixel_mask.shape[0], pixel_mask.shape[1])
262
+
263
+ if binary.shape != consensus.shape:
264
+ msg = f"{stem}: shape mismatch png {binary.shape} vs consensus {consensus.shape}"
265
+ raise ValueError(msg)
266
+
267
+ diffs = int(np.sum(binary != consensus))
268
+ if diffs:
269
+ msg = f"{stem}: verification failed — {diffs} differing pixels"
270
+ raise ValueError(msg)
271
+
272
+
273
+ # ---------------------------------------------------------------------------
274
+ # Writing and resume
275
+ # ---------------------------------------------------------------------------
276
+
277
+
278
+ def _tmp_path(path: Path) -> Path:
279
+ return path.with_name(f".{path.name}.tmp")
280
+
281
+
282
+ def _save_npy(path: Path, array: np.ndarray) -> None:
283
+ """Write ``array`` to ``path`` atomically (temp file + rename)."""
284
+ tmp = _tmp_path(path)
285
+ with tmp.open("wb") as f:
286
+ np.save(f, array)
287
+ tmp.replace(path)
288
+
289
+
290
+ def _save_image(path: Path, image: Image.Image, fmt: str) -> None:
291
+ """Write ``image`` to ``path`` in ``fmt`` (``"PNG"``/``"JPEG"``) atomically."""
292
+ tmp = _tmp_path(path)
293
+ image.save(tmp, format=fmt)
294
+ tmp.replace(path)
295
+
296
+
297
+ def _record_complete(output_dir: Path, split: str, stem: str, frame_stems: list[str]) -> bool:
298
+ """Whether a record's consensus mask and every frame's bands and preview exist."""
299
+ if not (output_dir / "semantic_masks" / split / f"{stem}.png").exists():
300
+ return False
301
+ return all(
302
+ (output_dir / "spectral_bands" / split / f"{f}.npy").exists()
303
+ and (output_dir / "images_semantic" / split / f"{f}.jpg").exists()
304
+ for f in frame_stems
305
+ )
306
+
307
+
308
+ # ---------------------------------------------------------------------------
309
+ # Format detection
310
+ # ---------------------------------------------------------------------------
311
+
312
+
313
+ def _probe_format(shards: list[Path]) -> FormatInfo:
314
+ """Auto-detect the TFRecord format by examining the first available record."""
315
+ import tensorflow as tf
316
+
317
+ for shard in shards:
318
+ for raw in tf.data.TFRecordDataset(str(shard)):
319
+ example = tf.train.Example()
320
+ example.ParseFromString(raw.numpy())
321
+ band_raw = _feature_bytes(example, "data_11um")
322
+ if band_raw is not None:
323
+ band = tf.io.parse_tensor(band_raw, out_type=tf.float64).numpy()
324
+ is_temporal = band.shape[2] > 1
325
+ else:
326
+ is_temporal = False
327
+ has_instance = _feature_bytes(example, "human_individual_instance_masks") is not None
328
+ return FormatInfo(is_temporal=is_temporal, has_instance_masks=has_instance)
329
+ msg = "No records found in any shard"
330
+ raise FileNotFoundError(msg)
331
+
332
+
333
+ # ---------------------------------------------------------------------------
334
+ # Shard processing
335
+ # ---------------------------------------------------------------------------
336
+
337
+
338
+ def _list_shards(tf_dir: Path, prefix: str, file_glob: str | None) -> list[Path]:
339
+ """Sorted shard paths in ``tf_dir`` matching ``prefix`` and optional glob."""
340
+ candidates = sorted(p for p in tf_dir.glob(f"{prefix}-*") if p.is_file())
341
+ if file_glob is None:
342
+ return candidates
343
+ return [p for p in candidates if fnmatch.fnmatch(p.name, file_glob)]
344
+
345
+
346
+ def _process_shard(
347
+ shard_path: Path,
348
+ output_dir: Path,
349
+ *,
350
+ fmt: FormatInfo,
351
+ split: str,
352
+ skip_existing: bool,
353
+ verify: bool,
354
+ ) -> tuple[int, int]:
355
+ """Decode one shard into ``split``; return ``(processed, skipped)`` record counts."""
356
+ import tensorflow as tf
357
+
358
+ processed = 0
359
+ skipped = 0
360
+ for raw in tf.data.TFRecordDataset(str(shard_path)):
361
+ example = tf.train.Example()
362
+ example.ParseFromString(raw.numpy())
363
+ stem = _record_stem(_scalar_int(example, "record_id"))
364
+
365
+ if fmt.is_temporal:
366
+ nb_raw = _scalar_int(example, "n_times_before")
367
+ nt_raw = _scalar_int(example, "n_times")
368
+ na_raw = _scalar_int(example, "n_times_after")
369
+ nb = nb_raw if nb_raw is not None else 4
370
+ nt = nt_raw if nt_raw is not None else 1
371
+ na = na_raw if na_raw is not None else 3
372
+ n_frames = nb + nt + na
373
+ label_frame = nb
374
+ else:
375
+ n_frames = 1
376
+ label_frame = 0
377
+ frame_stems = [_frame_stem(stem, t, label_frame, n_frames) for t in range(n_frames)]
378
+
379
+ if skip_existing and _record_complete(output_dir, split, stem, frame_stems):
380
+ skipped += 1
381
+ continue
382
+
383
+ bands = _decode_bands(example)
384
+ pixel_mask = _decode_mask(example, "human_pixel_masks")
385
+ individual = _decode_mask(example, "human_individual_masks")
386
+
387
+ if pixel_mask is not None:
388
+ mask_path = output_dir / "semantic_masks" / split / f"{stem}.png"
389
+ if verify and mask_path.exists():
390
+ _verify_consensus(mask_path, pixel_mask, stem)
391
+ _save_image(
392
+ mask_path, Image.fromarray(_consensus_mask_png(pixel_mask), mode="L"), "PNG"
393
+ )
394
+
395
+ if individual is not None:
396
+ _save_npy(
397
+ output_dir / "probability_masks" / split / f"{stem}.npy",
398
+ _probability_mask(individual),
399
+ )
400
+ _save_npy(
401
+ output_dir / "annotator_masks" / split / f"{stem}.npy",
402
+ _annotator_masks(individual),
403
+ )
404
+
405
+ if fmt.has_instance_masks:
406
+ instance = _decode_mask(example, "human_individual_instance_masks")
407
+ if instance is not None:
408
+ _save_npy(
409
+ output_dir / "instance_masks" / split / f"{stem}.npy",
410
+ _instance_masks(instance),
411
+ )
412
+
413
+ for t, fstem in enumerate(frame_stems):
414
+ spectral = _spectral_bands_frame(bands, t)
415
+ _save_npy(output_dir / "spectral_bands" / split / f"{fstem}.npy", spectral)
416
+ _save_image(
417
+ output_dir / "images_semantic" / split / f"{fstem}.jpg",
418
+ Image.fromarray(_preview_rgb(spectral), mode="RGB"),
419
+ "JPEG",
420
+ )
421
+
422
+ processed += 1
423
+
424
+ return processed, skipped
425
+
426
+
427
+ # ---------------------------------------------------------------------------
428
+ # Output layout
429
+ # ---------------------------------------------------------------------------
430
+
431
+
432
+ _OUTPUT_SUBDIRS = (
433
+ "images_semantic",
434
+ "semantic_masks",
435
+ "probability_masks",
436
+ "annotator_masks",
437
+ "instance_masks",
438
+ "spectral_bands",
439
+ )
440
+
441
+
442
+ _LABEL_DIRS: dict[Label, str] = {
443
+ "semantic": "semantic_masks",
444
+ "probability": "probability_masks",
445
+ "annotator": "annotator_masks",
446
+ "instance": "instance_masks",
447
+ }
448
+
449
+
450
+ @functools.cache
451
+ def _band_manifest() -> BandManifest:
452
+ """Describe the channels of ``spectral_bands/*.npy`` (dataset format v1)."""
453
+ channels = tuple(
454
+ BandChannel(
455
+ index=index,
456
+ key=key,
457
+ units="K",
458
+ sensor_band=None if info.abi_band is None else str(info.abi_band),
459
+ wavelength_um=info.wavelength_um,
460
+ name=info.name,
461
+ derived_from=info.derived_from,
462
+ )
463
+ for index, (key, info) in enumerate((k, SPECTRAL_BAND_INFO[k]) for k in SPECTRAL_BAND_KEYS)
464
+ )
465
+ return BandManifest(
466
+ format_version=1,
467
+ sensor="GOES-16 ABI",
468
+ dtype="float32",
469
+ channels=channels,
470
+ description="Brightness temperatures of spectral_bands/{split}/{stem}.npy, shape (H, W, C)",
471
+ )
472
+
473
+
474
+ def _write_band_manifest(output_dir: Path) -> None:
475
+ """Write ``spectral_bands/bands.json``."""
476
+ path = output_dir / BAND_MANIFEST_PATH
477
+ path.parent.mkdir(parents=True, exist_ok=True)
478
+ path.write_text(_band_manifest().model_dump_json(indent=2) + "\n")
479
+
480
+
481
+ def _prepare_output_dir(output_dir: Path) -> None:
482
+ """Create the output layout and write ``spectral_bands/bands.json``."""
483
+ (output_dir / "metadata").mkdir(parents=True, exist_ok=True)
484
+ for sub in _OUTPUT_SUBDIRS:
485
+ for split in _SPLITS:
486
+ (output_dir / sub / split).mkdir(parents=True, exist_ok=True)
487
+ _write_band_manifest(output_dir)
488
+
489
+
490
+ def _labels_on_disk(output_dir: Path) -> tuple[Label, ...]:
491
+ """Label kinds whose directory holds at least one file, in ``_LABEL_DIRS`` order."""
492
+
493
+ def has_files(directory: Path) -> bool:
494
+ return directory.is_dir() and next(directory.iterdir(), None) is not None
495
+
496
+ return tuple(
497
+ label
498
+ for label, sub in _LABEL_DIRS.items()
499
+ if any(has_files(output_dir / sub / split) for split in _SPLITS)
500
+ )
501
+
502
+
503
+ def _format_from_disk(output_dir: Path) -> FormatInfo:
504
+ """Detect the export flavour from an already converted dataset (no TFRecords needed).
505
+
506
+ A ``temporal`` value already declared in ``metadata/dataset_info.json`` is kept. Only a
507
+ dataset without valid metadata (e.g. converted before format v1) is inspected: it is
508
+ temporal when some file is a context frame (``<id>_b<k>`` / ``<id>_a<k>``) of a record.
509
+ """
510
+ try:
511
+ declared = read_dataset_info(output_dir).temporal
512
+ except DatasetContractError:
513
+ declared = None
514
+ if declared is not None:
515
+ is_temporal = declared
516
+ else:
517
+ is_temporal = any(
518
+ context_frames(
519
+ [p.stem for p in (output_dir / "spectral_bands" / split).glob("*.npy")],
520
+ temporal=True,
521
+ )
522
+ for split in _SPLITS
523
+ )
524
+ return FormatInfo(
525
+ is_temporal=is_temporal, has_instance_masks="instance" in _labels_on_disk(output_dir)
526
+ )
527
+
528
+
529
+ def _write_split_lists(output_dir: Path) -> None:
530
+ """Write ``splits_{split}.txt`` from the consensus masks on disk (complete after resumes)."""
531
+ for split in _SPLITS:
532
+ stems = sorted(p.stem for p in (output_dir / "semantic_masks" / split).glob("*.png"))
533
+ (output_dir / f"splits_{split}.txt").write_text("".join(f"{s}\n" for s in stems))
534
+
535
+
536
+ # Measured on the two OpenContrails exports: same images, but 20250305 masks are
537
+ # rasterised ~0.5 px up-left of the 20230419 (Kaggle-convention) ones.
538
+ _KNOWN_EXPORTS: dict[tuple[bool, bool], tuple[str, float]] = {
539
+ (True, False): ("20230419", 0.5),
540
+ (False, True): ("20250305", 0.0),
541
+ }
542
+
543
+
544
+ def _dataset_info(
545
+ fmt: FormatInfo, records: dict[str, int], labels: tuple[Label, ...]
546
+ ) -> DatasetInfo:
547
+ """Describe a converted dataset, including the ``pixel_shift`` to train it with."""
548
+ export, shift = _KNOWN_EXPORTS.get((fmt.is_temporal, fmt.has_instance_masks), (None, None))
549
+ note = (
550
+ "Use as the data config's pixel_shift. 20230419 masks follow the Kaggle convention (0.5); "
551
+ "20250305 masks are already aligned with the images (0.0)."
552
+ if export
553
+ else "Unknown export: measure the image/mask alignment before choosing pixel_shift."
554
+ )
555
+ return DatasetInfo(
556
+ format_version=1,
557
+ source="OpenContrails GOES-16 ABI TFRecords",
558
+ records={"train": records["train"], "test": records["test"]},
559
+ labels=labels,
560
+ recommended_pixel_shift=shift,
561
+ temporal=fmt.is_temporal,
562
+ export=export,
563
+ naming="record_id",
564
+ pixel_shift_note=note,
565
+ )
566
+
567
+
568
+ def _write_dataset_info(output_dir: Path, fmt: FormatInfo) -> None:
569
+ """Write ``metadata/dataset_info.json`` from ``splits_*.txt`` and the label dirs on disk."""
570
+ records = {s: len((output_dir / f"splits_{s}.txt").read_text().split()) for s in _SPLITS}
571
+ info = _dataset_info(fmt, records, _labels_on_disk(output_dir))
572
+ path = output_dir / DATASET_INFO_PATH
573
+ path.parent.mkdir(parents=True, exist_ok=True)
574
+ path.write_text(info.model_dump_json(indent=2) + "\n")
575
+
576
+
577
+ # ---------------------------------------------------------------------------
578
+ # CLI
579
+ # ---------------------------------------------------------------------------
580
+
581
+
582
+ def _parse_args(argv: list[str] | None) -> argparse.Namespace:
583
+ parser = argparse.ArgumentParser(description=(__doc__ or "").partition("\n")[0])
584
+ parser.add_argument(
585
+ "--tfrecord-dir",
586
+ type=Path,
587
+ default=None,
588
+ help="Directory holding ``train.tfrecords-*`` and ``validation.tfrecords-*`` shards "
589
+ "(required unless --metadata-only).",
590
+ )
591
+ parser.add_argument("--output-dir", type=Path, required=True, help="Dataset root to write.")
592
+ parser.add_argument(
593
+ "--skip-existing",
594
+ action=argparse.BooleanOptionalAction,
595
+ default=True,
596
+ help="Skip records whose mask and every frame's bands and preview already exist, "
597
+ "so an interrupted run resumes (default). --no-skip-existing rewrites them.",
598
+ )
599
+ parser.add_argument(
600
+ "--no-verify",
601
+ dest="verify",
602
+ action="store_false",
603
+ default=True,
604
+ help="Skip the pixel-identical check of consensus masks against existing PNGs.",
605
+ )
606
+ parser.add_argument(
607
+ "--file-glob",
608
+ default=None,
609
+ help="Only process shards whose basename matches this fnmatch glob "
610
+ '(e.g. "*.tfrecords-00000-of-00100"). Names do not depend on shard order, '
611
+ "so a subset converts to the same files as a full run.",
612
+ )
613
+ parser.add_argument(
614
+ "--metadata-only",
615
+ action="store_true",
616
+ help="Only rewrite spectral_bands/bands.json and metadata/dataset_info.json of an "
617
+ "already converted --output-dir (detects the export from the files on disk; no "
618
+ "TFRecords or TensorFlow needed).",
619
+ )
620
+ args = parser.parse_args(argv)
621
+ if args.tfrecord_dir is None and not args.metadata_only:
622
+ parser.error("--tfrecord-dir is required unless --metadata-only is given")
623
+ return args
624
+
625
+
626
+ def _print_summary(output_dir: Path) -> None:
627
+ info = DatasetInfo.model_validate_json((output_dir / DATASET_INFO_PATH).read_text())
628
+ print(
629
+ f"Dataset now holds {info.records['train']} train + {info.records['test']} test records "
630
+ f"(labels: {', '.join(info.labels)}); recommended pixel_shift: "
631
+ f"{info.recommended_pixel_shift}"
632
+ )
633
+ print("Done.")
634
+
635
+
636
+ def main(argv: list[str] | None = None) -> int:
637
+ """Convert the TFRecord shards to the filesystem layout.
638
+
639
+ Returns
640
+ -------
641
+ int
642
+ 0 on success; 2 when ``--tfrecord-dir`` is not a directory or holds no matching
643
+ shards. In the latter case ``--output-dir`` is left untouched, so a failed run
644
+ never leaves a half-made dataset behind.
645
+ """
646
+ args = _parse_args(argv)
647
+ output_dir = Path(args.output_dir)
648
+
649
+ if args.metadata_only:
650
+ fmt = _format_from_disk(output_dir)
651
+ _write_band_manifest(output_dir)
652
+ _write_dataset_info(output_dir, fmt)
653
+ _print_summary(output_dir)
654
+ return 0
655
+
656
+ tf_dir = Path(args.tfrecord_dir)
657
+ if not tf_dir.is_dir():
658
+ print(f"error: --tfrecord-dir {tf_dir} is not a directory", file=sys.stderr)
659
+ return 2
660
+ shards_by_split = {
661
+ "train": _list_shards(tf_dir, "train.tfrecords", args.file_glob),
662
+ "test": _list_shards(tf_dir, "validation.tfrecords", args.file_glob),
663
+ }
664
+ all_shards = shards_by_split["train"] + shards_by_split["test"]
665
+ if not all_shards:
666
+ print(f"error: no TFRecord shards in {tf_dir} (glob {args.file_glob!r})", file=sys.stderr)
667
+ return 2
668
+ _prepare_output_dir(output_dir)
669
+
670
+ fmt = _probe_format(all_shards)
671
+ label = "temporal (multi-frame)" if fmt.is_temporal else "single-frame"
672
+ print(f"Detected format: {label}, instance_masks={'yes' if fmt.has_instance_masks else 'no'}")
673
+ print(
674
+ f"Processing {len(shards_by_split['train'])} train + "
675
+ f"{len(shards_by_split['test'])} validation shard(s)"
676
+ )
677
+
678
+ done = 0
679
+ for split, shards in shards_by_split.items():
680
+ for shard in shards:
681
+ done += 1
682
+ proc, skipped = _process_shard(
683
+ shard,
684
+ output_dir,
685
+ fmt=fmt,
686
+ split=split,
687
+ skip_existing=args.skip_existing,
688
+ verify=args.verify,
689
+ )
690
+ print(
691
+ f"[shard {done}/{len(all_shards)}] {split}: "
692
+ f"processed {proc} records ({skipped} skipped)",
693
+ flush=True,
694
+ )
695
+
696
+ _write_split_lists(output_dir)
697
+ _write_dataset_info(output_dir, fmt)
698
+ _print_summary(output_dir)
699
+ return 0
700
+
701
+
702
+ if __name__ == "__main__":
703
+ raise SystemExit(main())