WeiHuang95 commited on
Commit
f43ea7a
·
verified ·
1 Parent(s): effd0ee

Restore original UniBuild layout with verified training integration

Browse files
README.md CHANGED
@@ -1,76 +1,127 @@
1
- ---
2
- pretty_name: UniBuild building segmentation collection (reviewed subset)
3
- license: other
4
- license_name: unibuild-component-licenses
5
- license_link: LICENSE.md
6
- task_categories:
7
- - image-segmentation
8
- tags:
9
- - remote-sensing
10
- - buildings
11
- - geospatial
12
- ---
13
-
14
- # UniBuild building segmentation collection
15
-
16
- A curated subset of the processed datasets used by UniBuild. **Planet is excluded.** This is not the complete original training corpus: datasets without verified redistribution rights and explicitly listed OpenEarthMap regions are excluded. See `excluded_datasets.json` and `release_plan.json`.
17
-
18
- Each source retains its own licence and attribution. Read `LICENSE.md`, `dataset_licenses.json`, and `region_licenses.json` before use. This collection includes noncommercial and academic-only components; commercial users must select only eligible components.
19
-
20
- | Dataset | Train | Val | Test | Licence |
21
- | --- | ---: | ---: | ---: | --- |
22
- | inria | 14400 | 1800 | 1800 | Public domain (original imagery and official raster labels) |
23
- | gf7 | 3106 | 1034 | 1035 | CC BY 4.0 |
24
- | loveda | 10088 | 3338 | 3338 | CC BY-NC-SA 4.0; academic use only; Google Earth terms also apply |
25
- | spacenet2 | 8474 | 1059 | 1060 | CC BY-SA 4.0 |
26
- | landcover-ai | 8539 | 1067 | 1068 | CC BY-NC-SA 4.0 |
27
- | orbitalnet | 115443 | 6413 | 6414 | CC BY 4.0 |
28
- | openearthmap | 6128 | 780 | 767 | Per-region; imagery and labels can have different terms |
29
- | sentinel2 | 40000 | 5000 | 5000 | Copernicus imagery; ODbL 1.0 OSM-derived annotation database (provider-confirmed) |
30
-
31
- ## Contents and preparation
32
-
33
- Only image/mask files referenced by the included splits, ORBITaL-Net georeferencing, split files, source attributions and reproducibility metadata are included. Duplicate LMDB stores, unused originals, old archives, predictions and checkpoints are omitted. Source file bytes and mask values are preserved. Image crop/format preparation predates this export; the exact original preprocessing commands are not available for every source.
34
-
35
- OpenEarthMap is filtered per region. Regions with unspecified imagery redistribution terms and xBD regions with unverified local imagery provenance are omitted. This changes sample counts; excluded region counts are recorded in `release_plan.json`. Labels on public-domain source imagery are still CC BY-NC-SA 4.0, as required by OpenEarthMap.
36
-
37
- The train/val/test sets are the existing **UniBuild** splits. They are not necessarily the official benchmark splits. Geographic separation and overlap between different datasets have not been audited; do not interpret these splits as an independent cross-dataset benchmark.
38
-
39
- ## Download and extract
40
-
41
- Download this repository, then extract each `data/<dataset>/*.tar` into a common `data/` directory. Archives contain paths such as `inria/Kitsap/image/...`. For example:
42
-
43
- ```bash
44
- mkdir -p data
45
- for archive in data/*/*.tar; do tar -xf "$archive" -C data; done
46
- ```
47
-
48
- Per-shard SHA-256 checksums and per-member hashes are under `checksums/`. Every member was read back and verified during packaging. `SHA256SUMS` covers each final archive. `manifests/<dataset>.jsonl` maps every image and mask to its split, region and licence. Extraction must be performed on archives obtained from this repository; always use a safe extraction tool.
49
-
50
- ## Use with UniBuild
51
-
52
- Set each selected entry's `data_dir`, `split_dir`, and `use_lmdb=False` using `dataset_configs.json`. Paths there are relative to the extracted repository. Preserve each entry's `class_dict` and `ignore_idx=255`; the masks have not all been converted to the same class IDs. For example, LoveDA 0 is ignored, LoveDA 2 is building, OpenEarthMap 8 is building, and LandCover.ai 1 is building.
53
-
54
- Use `load_unibuild_configs.py` to restore integer label IDs and resolve paths:
55
-
56
- ```python
57
- from load_unibuild_configs import load_dataset_configs
58
- cfg.datasets_dict = load_dataset_configs("/path/to/extracted/release")
59
- cfg.datasets = list(cfg.datasets_dict)
60
- ```
61
-
62
- ## Attribution
63
-
64
- Authors, providers, source URLs, source release metadata and licences are in `LICENSE.md`, `dataset_licenses.json`, `region_licenses.json`, and `provenance/`. Cite the original datasets when publishing research. ORBITaL-Net imagery: (c) 2025 Maxar; public release approval A706, as stated by its data descriptor. The dataset release on Figshare is CC BY 4.0; the paper's separate licence is not used as the data licence.
65
-
66
- ## Additional licence review
67
-
68
- See [the licence recheck](provenance/license_recheck_20261120.json) for the current evidence on withheld components. Permission has not been verified; this is not a claim that all withheld datasets explicitly prohibit redistribution. Sentinel-2 has since been added following the data provider's explicit confirmation that the training labels are OSM derived. Supplied source markers are retained and documented in `provenance/sentinel2_source_declaration.json`; they are not silently normalized.
69
-
70
- ## Sentinel-2 source database and preparation
71
-
72
- Sentinel-2 contributes 40,000 training, 5,000 validation and 5,000 test image/mask pairs, with original bytes and UniBuild splits preserved. The component also includes the 23,412 source annotation JSON files and corresponding ROI GeoJSON records needed for these samples, plus `build_mask_from_json.py` and `crop_pairs_512.py` used in preparation. These are necessary provenance/database materials, not duplicate LMDBs or unused imagery.
73
-
74
- Contains information from OpenStreetMap, made available under ODbL 1.0; (c) OpenStreetMap contributors. Contains modified Copernicus Sentinel data. The annotation database is provided to support ODbL database-sharing obligations. The data-provider source statement and unchanged source fields are documented separately. The configured native spatial resolution is 10 m; the processing pipeline may resample imagery, so do not infer native sensor resolution from patch pixel spacing.
75
-
76
- The conversion scripts describe the original preparation logic. They are included as a record; no full-corpus mask regeneration or independent reconstruction of the original download history was performed for this export. Existing masks have not been changed.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: UniBuild building segmentation collection (training-ready subset)
3
+ license: other
4
+ license_name: unibuild-component-licenses
5
+ license_link: LICENSE.md
6
+ task_categories:
7
+ - image-segmentation
8
+ tags:
9
+ - remote-sensing
10
+ - buildings
11
+ - geospatial
12
+ ---
13
+
14
+ # UniBuild building segmentation collection
15
+
16
+ The published subset contains **8 dataset components and 247,151 image/mask pairs**. Planet is excluded. Potsdam, WHU-Mix and Alabama remain outside this release while redistribution terms are unverified. Some OpenEarthMap regions are also filtered. See `excluded_datasets.json` and `release_plan.json`.
17
+
18
+ Each component retains its own licence. The collection includes noncommercial and academic-only data; it does not have a single uniform permissive licence. Read `LICENSE.md`, `dataset_licenses.json`, `region_licenses.json`, and the Sentinel-2 source declaration before use.
19
+
20
+ ## Use directly with the UniBuild training code
21
+
22
+ Start with a UniBuild training checkout and its normal Python environment. The dataset repository supplies data and preparation tools; it does not replace the model/training code. The example below assumes the training checkout is `./UniBuild`:
23
+
24
+ ```bash
25
+ # Download alongside the training checkout. snapshot_download also works with
26
+ # huggingface_hub 0.30.2, which is pinned by the training environment.
27
+ python -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='WeiHuang95/UniBuild', repo_type='dataset', local_dir='./UniBuild-dataset')"
28
+
29
+ # Verify/extract data into the original RSSeg folder structure and configure paths.
30
+ python UniBuild-dataset/prepare_for_unibuild.py --code-root ./UniBuild
31
+
32
+ cd UniBuild
33
+ bash scripts/training/train.sh
34
+ ```
35
+
36
+ If the repository has already been downloaded, start at the preparation command. The preparation tool uses the Python standard library and does not need a new package installation. Extraction verifies each archive and each extracted file against the published SHA-256 catalogs. It is resumable: existing matching image/mask files are reused; different contents are not silently overwritten.
37
+
38
+ For another data disk or a selected subset:
39
+
40
+ ```bash
41
+ python UniBuild-dataset/prepare_for_unibuild.py --code-root ./UniBuild --data-root /mnt/data/RSSeg --datasets inria gf7 sentinel2
42
+ ```
43
+
44
+ The full download is about 116 GB, and the extracted files need a further similar amount of disk space. `--data-root` selects the directory that corresponds to the original `/home/Datasets/RSSeg` root.
45
+
46
+ ### Prepared directory layout
47
+
48
+ The original dataset folder names, internal image/mask paths and filenames are preserved:
49
+
50
+ ```text
51
+ UniBuild/
52
+ configs.py
53
+ unibuild_data.py
54
+ data/
55
+ unibuild_release.json
56
+ RSSeg/
57
+ INRIA/
58
+ GF7_Buildings/
59
+ LoveDA/
60
+ SpaceNet2/
61
+ Landcover_ai/
62
+ ORBITaLNet/
63
+ OpenEarthMap_wo_xBD_512/
64
+ Sentinel2_Buildings/
65
+ splits/
66
+ inria/{train,val,test}.txt
67
+ gf7/{train,val,test}.txt
68
+ ...
69
+ ```
70
+
71
+ `unibuild_layout.json` maps the archive prefixes to those original folder names. All image/mask relative paths within each dataset remain the paths used by UniBuild. Split text is copied from this release into `data/splits/<dataset>/`; use these release splits because OpenEarthMap was filtered for publication.
72
+
73
+ ### What preparation configures
74
+
75
+ The tool installs `unibuild_data.py` and a small hook in `Config.__init__`, without changing learning parameters, model options or label definitions. Existing changed configuration/split files are backed up with `.before_hf_<hash>` suffixes. It writes a machine-specific registry at `data/unibuild_release.json`; do not copy that registry between machines, rerun preparation instead.
76
+
77
+ The registry selects the downloaded published components, resolves their local data and split paths, and sets `use_lmdb=False`. Duplicate LMDB stores were intentionally omitted from the download. Integer class IDs are restored from JSON: for example, LoveDA 0 remains ignored (255), LoveDA 2 is building, OpenEarthMap 8 is building, and LandCover.ai 1 is building. The supplied masks are not rewritten.
78
+
79
+ For the older launcher that hardcoded `datasets=('potsdam')`, preparation backs up that launcher and changes this example default to `datasets=()`, so it follows the prepared configuration. Dataset overrides still work as before:
80
+
81
+ ```bash
82
+ TRAIN_DATASETS="inria gf7" bash scripts/training/train.sh
83
+ # Or pass the existing train.py --datasets option.
84
+ ```
85
+
86
+ Without a prepared registry, the integration helper leaves the ordinary local dataset configuration unchanged. A different registry can be selected with `UNIBUILD_RELEASE_CONFIG`.
87
+
88
+ ## Published sample counts
89
+
90
+ | Dataset | Train | Val | Test | Component licence |
91
+ | --- | ---: | ---: | ---: | --- |
92
+ | inria | 14400 | 1800 | 1800 | Public domain (original imagery and official raster labels) |
93
+ | gf7 | 3106 | 1034 | 1035 | CC BY 4.0 |
94
+ | loveda | 10088 | 3338 | 3338 | CC BY-NC-SA 4.0; academic use only; Google Earth terms also apply |
95
+ | spacenet2 | 8474 | 1059 | 1060 | CC BY-SA 4.0 |
96
+ | landcover-ai | 8539 | 1067 | 1068 | CC BY-NC-SA 4.0 |
97
+ | orbitalnet | 115443 | 6413 | 6414 | CC BY 4.0 |
98
+ | openearthmap | 6128 | 780 | 767 | Per-region; imagery and labels can have different terms |
99
+ | sentinel2 | 40000 | 5000 | 5000 | Imagery: Copernicus Sentinel legal notice; annotation database: ODbL 1.0 (provider-confirmed OSM origin) |
100
+
101
+ ## Contents and splits
102
+
103
+ Only referenced image/mask files, required source/provenance materials, splits and integration metadata are included. Duplicate LMDBs, unused originals, old archives, predictions and checkpoints are omitted. Original source bytes and mask values are preserved. The 58 tar shards have per-archive SHA-256 hashes in `SHA256SUMS` and per-member hashes under `checksums/`. All members were independently read back and checked during packaging; remote archive hashes were verified after upload.
104
+
105
+ These train/val/test sets are the existing **UniBuild** splits, not necessarily the official benchmark splits. Geographic separation and inter-dataset overlap were not audited. Original crop/channel/file-format preparation predates this export and is not fully reconstructable for every source.
106
+
107
+ OpenEarthMap excludes 11 selected regions whose imagery redistribution terms were not established. Labels on public-domain source imagery still carry CC BY-NC-SA 4.0 as stated by OpenEarthMap. Region providers and separate imagery/label terms are recorded in `region_licenses.json` and per-sample manifests.
108
+
109
+ ## Sentinel-2 source database
110
+
111
+ The data provider explicitly confirmed that the training labels are OpenStreetMap derived and explicitly authorized public release of the complete supplement, including the supplied source vectors. Contains information from OpenStreetMap, made available under ODbL 1.0; (c) OpenStreetMap contributors. Imagery contains modified Copernicus Sentinel data.
112
+
113
+ The component includes 23,412 source annotation JSON files, corresponding ROI GeoJSON records, and the original mask rasterization/cropping scripts. These source/database materials support provenance and ODbL database-sharing requirements. The supplied GeoJSON retains `osm`, `google`, and `3dglobfp` source attributes unchanged. The provider's source statement and those observed marker values are documented separately in `provenance/sentinel2_source_declaration.json`; their historical meaning was not independently verified. No source attributes were removed or silently relabelled.
114
+
115
+ The configured native Sentinel-2 resolution is 10 m; the preparation pipeline may resample imagery, so patch pixel spacing need not equal native sensor resolution. No full-corpus mask regeneration was performed for this export.
116
+
117
+ ## Validation
118
+
119
+ `training_integration_verification.json` records an actual loader smoke test using one real image/mask pair per published component: preparation of an older Config, all 8 components through the original `MultiDatasetSeg` training and validation paths, and 5 resolution-grouped training DataLoader batches. It also checks label/ignore mapping, repeat preparation, backups, and rejection of unsafe tar paths. The tiny smoke-test fixture reuses its samples across test splits; the published splits are not modified by that test. No model-training epoch was run.
120
+
121
+ ## Attribution and licences
122
+
123
+ Source authors, providers, licence links and release metadata are in `LICENSE.md`, `dataset_licenses.json`, `region_licenses.json` and `provenance/`. Cite the original datasets. ORBITaL-Net imagery: (c) 2025 Maxar; public release approval A706 as stated in its data descriptor. Its Figshare dataset licence is CC BY 4.0; the paper's separate licence is not used as the data licence.
124
+
125
+ `provenance/whu_mix_paper_review.json` records the additional paper review for withheld WHU-Mix. Unverified redistribution terms are not a claim that every withheld dataset explicitly forbids redistribution.
126
+
127
+ The newly supplied integration helpers `prepare_for_unibuild.py` and `unibuild_data.py` are MIT licensed under `licenses/unibuild-integration-mit.txt`. This code licence does not relicense any dataset or the separate UniBuild training/model code.
licenses/unibuild-integration-mit.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 UniBuild contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ Scope: prepare_for_unibuild.py and unibuild_data.py only. Dataset and original
24
+ training-code licences are separate.
prepare_for_unibuild.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+ """Restore the original UniBuild RSSeg layout and configure an existing code checkout.
3
+
4
+ Download WeiHuang95/UniBuild, then run this file from that download:
5
+ python prepare_for_unibuild.py --code-root /path/to/UniBuild
6
+ Data defaults to /path/to/UniBuild/data/RSSeg; use --data-root for another disk.
7
+ Existing images are never replaced with different contents. Changed code/split
8
+ files are backed up before the small integration hook is installed.
9
+ """
10
+ import argparse
11
+ import ast
12
+ import hashlib
13
+ import json
14
+ from pathlib import Path, PurePosixPath
15
+ import re
16
+ import tarfile
17
+ import tempfile
18
+
19
+
20
+ def sha256(path):
21
+ h = hashlib.sha256()
22
+ with Path(path).open('rb') as file:
23
+ for chunk in iter(lambda: file.read(8*1024*1024), b''):
24
+ h.update(chunk)
25
+ return h.hexdigest()
26
+
27
+
28
+ def write_with_backup(path, data):
29
+ path = Path(path)
30
+ path.parent.mkdir(parents=True, exist_ok=True)
31
+ mode = path.stat().st_mode & 0o777 if path.exists() else None
32
+ if path.exists():
33
+ old = path.read_bytes()
34
+ if old == data:
35
+ return
36
+ backup = path.with_name(path.name + '.before_hf_' + hashlib.sha256(old).hexdigest()[:12])
37
+ if not backup.exists():
38
+ backup.write_bytes(old)
39
+ temporary = path.with_name(path.name + '.hf_tmp')
40
+ temporary.write_bytes(data)
41
+ if mode is not None:
42
+ temporary.chmod(mode)
43
+ temporary.replace(path)
44
+
45
+
46
+ def extract_shard(archive_path, expected, dataset, destination, archive_hash):
47
+ if sha256(archive_path) != archive_hash:
48
+ raise ValueError(f'Archive SHA-256 mismatch: {archive_path}')
49
+ seen = set()
50
+ destination = destination.resolve()
51
+ destination.mkdir(parents=True, exist_ok=True)
52
+ with tarfile.open(archive_path, 'r:') as archive:
53
+ for member in archive:
54
+ parts = PurePosixPath(member.name).parts
55
+ if (not member.isfile() or not parts or parts[0] != dataset
56
+ or '..' in parts or PurePosixPath(member.name).is_absolute()
57
+ or '\\' in member.name or ':' in member.name):
58
+ raise ValueError(f'Unexpected or unsafe archive member: {member.name}')
59
+ record = expected.get(member.name)
60
+ if record is None or record['size'] != member.size or member.name in seen:
61
+ raise ValueError(f'Archive member differs from catalog: {member.name}')
62
+ seen.add(member.name)
63
+ target = destination.joinpath(*parts[1:])
64
+ if not target.resolve().is_relative_to(destination):
65
+ raise ValueError(f'Archive target leaves dataset directory: {target}')
66
+ if target.exists():
67
+ if target.is_file() and target.stat().st_size == member.size and sha256(target) == record['sha256']:
68
+ continue
69
+ raise FileExistsError(f'Existing data differs; it has not been overwritten: {target}')
70
+ target.parent.mkdir(parents=True, exist_ok=True)
71
+ temporary = None
72
+ try:
73
+ h = hashlib.sha256()
74
+ with archive.extractfile(member) as source, tempfile.NamedTemporaryFile(
75
+ dir=target.parent, prefix='.unibuild_', suffix='.part', delete=False) as output:
76
+ temporary = Path(output.name)
77
+ for chunk in iter(lambda: source.read(1024*1024), b''):
78
+ output.write(chunk)
79
+ h.update(chunk)
80
+ if h.hexdigest() != record['sha256']:
81
+ raise ValueError(f'Extracted member SHA-256 mismatch: {member.name}')
82
+ temporary.chmod(0o644)
83
+ temporary.replace(target)
84
+ finally:
85
+ if temporary is not None and temporary.exists():
86
+ temporary.unlink()
87
+ if seen != set(expected):
88
+ raise ValueError(f'Archive is missing expected members: {archive_path}')
89
+
90
+
91
+ def install_hook(code_root, release_root):
92
+ helper = release_root / 'unibuild_data.py'
93
+ if not helper.is_file():
94
+ raise FileNotFoundError(f'Missing integration helper: {helper}')
95
+ config_path = code_root / 'configs.py'
96
+ source = config_path.read_text(encoding='utf-8-sig')
97
+ tree = ast.parse(source)
98
+ cls = next((n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Config'), None)
99
+ init = next((n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == '__init__'), None) if cls else None
100
+ if init is None:
101
+ raise ValueError('Expected Config.__init__ in configs.py; no code has been changed')
102
+ hook_present = any(isinstance(n, ast.Call) and isinstance(n.func, ast.Name)
103
+ and n.func.id == 'apply_release_config' for n in ast.walk(init))
104
+ if not hook_present:
105
+ lines = source.splitlines(keepends=True)
106
+ hook = '\n # Optional paths/settings installed by the HF dataset preparation tool.\n'
107
+ hook += ' from unibuild_data import apply_release_config\n'
108
+ hook += ' apply_release_config(self, __file__)\n'
109
+ lines.insert(init.end_lineno, hook)
110
+ source = ''.join(lines)
111
+ ast.parse(source)
112
+ write_with_backup(code_root/'unibuild_data.py', helper.read_bytes())
113
+ write_with_backup(config_path, source.encode('utf-8'))
114
+ launcher = code_root/'scripts/training/train.sh'
115
+ if launcher.is_file():
116
+ shell = launcher.read_text(encoding='utf-8')
117
+ # The published UniBuild launcher previously forced the withheld Potsdam
118
+ # dataset; respect Config/--datasets instead of that stale example default.
119
+ updated = re.sub(r"(?m)^datasets=\((?:'potsdam'|\"potsdam\"|potsdam)\)\s*$",
120
+ 'datasets=()', shell)
121
+ if updated != shell:
122
+ write_with_backup(launcher, updated.encode('utf-8'))
123
+
124
+
125
+ def main():
126
+ parser = argparse.ArgumentParser(description=__doc__)
127
+ parser.add_argument('--release-root', type=Path, default=Path(__file__).resolve().parent)
128
+ parser.add_argument('--code-root', type=Path, required=True)
129
+ parser.add_argument('--data-root', type=Path, help='RSSeg directory; default: CODE_ROOT/data/RSSeg')
130
+ parser.add_argument('--datasets', nargs='+', help='Default: all published components')
131
+ args = parser.parse_args()
132
+ release = args.release_root.expanduser().resolve()
133
+ code = args.code_root.expanduser().resolve()
134
+ if not (code/'configs.py').is_file() or not (code/'train.py').is_file():
135
+ parser.error('--code-root must be a UniBuild training checkout with configs.py and train.py')
136
+ if release == code:
137
+ parser.error('Use separate directories for the HF download and the training checkout')
138
+ data = (args.data_root.expanduser() if args.data_root else code/'data/RSSeg').resolve()
139
+ layout = json.loads((release/'unibuild_layout.json').read_text(encoding='utf-8'))
140
+ catalog = json.loads((release/'dataset_configs.json').read_text(encoding='utf-8'))
141
+ selected = args.datasets or list(catalog)
142
+ if not selected or len(selected) != len(set(selected)) or any(n not in catalog or n not in layout['datasets'] for n in selected):
143
+ parser.error('--datasets must be distinct published dataset names')
144
+ sums = dict(line.strip().split(None, 1)[::-1] for line in (release/'SHA256SUMS').read_text().splitlines() if line.strip())
145
+ pending = {}
146
+ for name in selected:
147
+ original_folder = PurePosixPath(layout['datasets'][name]['original_folder'])
148
+ if (not original_folder.parts or original_folder.is_absolute() or '..' in original_folder.parts
149
+ or '\\' in str(original_folder) or ':' in str(original_folder)):
150
+ raise ValueError(f'Unsafe original dataset directory: {original_folder}')
151
+ records = [json.loads(p.read_text()) for p in sorted((release/'checksums'/name).glob('*.json'))]
152
+ if not records:
153
+ raise FileNotFoundError(f'No archive checksums for {name}; download its complete component')
154
+ # Preflight all shards before extracting this component.
155
+ for record in records:
156
+ relative = PurePosixPath(record['archive'])
157
+ archive = release.joinpath(*relative.parts)
158
+ if (relative.is_absolute() or '..' in relative.parts or not archive.resolve().is_relative_to(release)
159
+ or sums.get(record['archive']) != record['sha256'] or not archive.is_file()):
160
+ raise ValueError(f'Missing/unsafe archive or inconsistent checksum: {record["archive"]}')
161
+ target = data.joinpath(*original_folder.parts)
162
+ if not target.resolve().is_relative_to(data):
163
+ raise ValueError(f'Dataset path leaves RSSeg root: {target}')
164
+ for record in records:
165
+ expected = {member['path']: member for member in record['members']}
166
+ extract_shard(release/record['archive'], expected, name, target, record['sha256'])
167
+ print('EXTRACTED_VERIFIED', record['archive'], flush=True)
168
+ split_root = code/'data/splits'/name
169
+ for split in ['train', 'val', 'test']:
170
+ original = release/'splits'/name/f'{split}.txt'
171
+ text = original.read_text(encoding='utf-8')
172
+ for line in text.splitlines():
173
+ if not line.strip():
174
+ continue
175
+ pair = line.split()
176
+ if len(pair) != 2:
177
+ raise ValueError(f'Invalid split row in {original}')
178
+ for relative in pair:
179
+ actual = (target/relative).resolve()
180
+ if not actual.is_relative_to(target.resolve()) or not actual.is_file():
181
+ raise ValueError(f'Split references missing/unsafe file: {relative}')
182
+ write_with_backup(split_root/f'{split}.txt', text.encode('utf-8'))
183
+ entry = dict(catalog[name])
184
+ entry.update(data_dir=str(target), split_dir=str(split_root), use_lmdb=False)
185
+ pending[name] = entry
186
+ print('PREPARED', name, str(target), flush=True)
187
+ state = {'format_version':1, 'repo_id':'WeiHuang95/UniBuild', 'datasets':selected, 'datasets_dict':pending}
188
+ install_hook(code, release)
189
+ registry = code/'data/unibuild_release.json'
190
+ write_with_backup(registry, (json.dumps(state,indent=2)+'\n').encode('utf-8'))
191
+ print('UNIBUILD_READY', str(registry), flush=True)
192
+ print('Train from the code checkout: bash scripts/training/train.sh', flush=True)
193
+ print('Override a subset as usual with TRAIN_DATASETS or train.py --datasets.', flush=True)
194
+
195
+
196
+ if __name__ == '__main__':
197
+ main()
provenance/sentinel2_public_release_authorization.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "confirmed_date": "2026-11-20",
3
+ "scope": "Public release of the complete Sentinel-2 supplement: 50,000 image/mask pairs and the supplied original annotations, including preserved google/3dglobfp source fields.",
4
+ "basis": "Explicit authorization from the dataset provider.",
5
+ "provider_source_statement": "OpenStreetMap",
6
+ "independent_reconstruction_of_historical_marker_meanings": false,
7
+ "source_declaration": "provenance/sentinel2_source_declaration.json"
8
+ }
training_integration_verification.json ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "result": "PASS",
3
+ "fixture": "One actual image/mask pair from each published component; reused across splits only for this smoke test",
4
+ "datasets": {
5
+ "inria": {
6
+ "validation_label_values": [
7
+ 0
8
+ ],
9
+ "training_and_validation_read": "PASS"
10
+ },
11
+ "gf7": {
12
+ "validation_label_values": [
13
+ 0,
14
+ 1
15
+ ],
16
+ "training_and_validation_read": "PASS"
17
+ },
18
+ "loveda": {
19
+ "validation_label_values": [
20
+ 0,
21
+ 255
22
+ ],
23
+ "training_and_validation_read": "PASS"
24
+ },
25
+ "spacenet2": {
26
+ "validation_label_values": [
27
+ 0
28
+ ],
29
+ "training_and_validation_read": "PASS"
30
+ },
31
+ "landcover-ai": {
32
+ "validation_label_values": [
33
+ 0
34
+ ],
35
+ "training_and_validation_read": "PASS"
36
+ },
37
+ "orbitalnet": {
38
+ "validation_label_values": [
39
+ 0
40
+ ],
41
+ "training_and_validation_read": "PASS"
42
+ },
43
+ "openearthmap": {
44
+ "validation_label_values": [
45
+ 0,
46
+ 1,
47
+ 255
48
+ ],
49
+ "training_and_validation_read": "PASS"
50
+ },
51
+ "sentinel2": {
52
+ "validation_label_values": [
53
+ 0,
54
+ 1
55
+ ],
56
+ "training_and_validation_read": "PASS"
57
+ }
58
+ },
59
+ "image_shape": [
60
+ 3,
61
+ 512,
62
+ 512
63
+ ],
64
+ "training_batches_loaded": 5,
65
+ "checks": [
66
+ "Original RSSeg directory names and split paths restored",
67
+ "Legacy Config hook installed without changing learning parameters",
68
+ "Prepared selection excludes unpublished/private datasets",
69
+ "File mode works without LMDB",
70
+ "Class mapping and LoveDA ignore value preserved",
71
+ "Actual MultiDatasetSeg train and val paths loaded",
72
+ "Actual resolution-grouped DataLoader batches loaded",
73
+ "Repeated preparation keeps image bytes and mtime",
74
+ "Original config/launcher backups retained",
75
+ "Unsafe archive path rejected"
76
+ ],
77
+ "scope": "Data preparation and training-loader smoke test; no model-training epoch was run."
78
+ }
unibuild_data.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: MIT
2
+ """Apply prepared Hugging Face data paths without changing training parameters."""
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+
7
+
8
+ def apply_release_config(config, config_file):
9
+ """Return False for an ordinary local install; apply a prepared release otherwise."""
10
+ code_root = Path(config_file).resolve().parent
11
+ explicit = os.environ.get('UNIBUILD_RELEASE_CONFIG')
12
+ registry = Path(explicit).expanduser() if explicit else code_root / 'data/unibuild_release.json'
13
+ if not registry.is_file():
14
+ if explicit:
15
+ raise FileNotFoundError(f'UNIBUILD_RELEASE_CONFIG does not exist: {registry}')
16
+ return False
17
+ state = json.loads(registry.read_text(encoding='utf-8'))
18
+ if state.get('format_version') != 1:
19
+ raise ValueError(f'Unsupported prepared UniBuild data registry: {registry}')
20
+ prepared = {}
21
+ for name, original in state['datasets_dict'].items():
22
+ entry = dict(original)
23
+ entry['class_dict'] = {int(k): tuple(v) for k, v in entry['class_dict'].items()}
24
+ for key in ['data_dir', 'split_dir']:
25
+ path = Path(entry[key])
26
+ entry[key] = str(path if path.is_absolute() else code_root / path)
27
+ entry['use_lmdb'] = False
28
+ if not Path(entry['data_dir']).is_dir() or not Path(entry['split_dir']).is_dir():
29
+ raise FileNotFoundError(f'Prepared dataset paths are missing for {name}; rerun prepare_for_unibuild.py')
30
+ prepared[name] = entry
31
+ selected = state['datasets']
32
+ if not selected or any(name not in prepared for name in selected):
33
+ raise ValueError('Prepared dataset selection is empty or invalid')
34
+ config.datasets_dict.update(prepared)
35
+ config.datasets = list(selected)
36
+ config.unibuild_release_registry = str(registry.resolve())
37
+ return True
unibuild_layout.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": 1,
3
+ "layout_root": "RSSeg",
4
+ "datasets": {
5
+ "inria": {
6
+ "archive_prefix": "inria",
7
+ "original_folder": "INRIA"
8
+ },
9
+ "gf7": {
10
+ "archive_prefix": "gf7",
11
+ "original_folder": "GF7_Buildings"
12
+ },
13
+ "loveda": {
14
+ "archive_prefix": "loveda",
15
+ "original_folder": "LoveDA"
16
+ },
17
+ "spacenet2": {
18
+ "archive_prefix": "spacenet2",
19
+ "original_folder": "SpaceNet2"
20
+ },
21
+ "landcover-ai": {
22
+ "archive_prefix": "landcover-ai",
23
+ "original_folder": "Landcover_ai"
24
+ },
25
+ "orbitalnet": {
26
+ "archive_prefix": "orbitalnet",
27
+ "original_folder": "ORBITaLNet"
28
+ },
29
+ "openearthmap": {
30
+ "archive_prefix": "openearthmap",
31
+ "original_folder": "OpenEarthMap_wo_xBD_512"
32
+ },
33
+ "sentinel2": {
34
+ "archive_prefix": "sentinel2",
35
+ "original_folder": "Sentinel2_Buildings"
36
+ }
37
+ },
38
+ "split_layout": "CODE_ROOT/data/splits/<dataset>/{train,val,test}.txt",
39
+ "default_data_root": "CODE_ROOT/data/RSSeg",
40
+ "prepared_registry": "CODE_ROOT/data/unibuild_release.json"
41
+ }