Datasets:
Download verify_examples.py from riccardode/s2_res: direct link, hf CLI and curl.
- Browser
- Download file 4.1 kB
-
https://huggingface.co/datasets/riccardode/s2_res/resolve/main/verify_examples.py
- Command line
-
hf download hf://datasets/riccardode/s2_res/verify_examples.py
-
curl -L -o verify_examples.py https://huggingface.co/datasets/riccardode/s2_res/resolve/main/verify_examples.py
4.1 kB
| """Run the portable package in an isolated environment against original predictions.""" | |
| import importlib.metadata | |
| import json | |
| import os | |
| from pathlib import Path | |
| import shutil | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| import numpy as np | |
| import rasterio | |
| import torch | |
| from affine import Affine | |
| from modis_s2.io import ROOT, load_model, load_sample, predict, write_prediction | |
| from modis_s2.evaluate import evaluate | |
| torch.set_num_threads(2) | |
| started = time.monotonic() | |
| assert not any(("ndvi-dit/lib/python" in x and "site-packages" in x) or "/repos/modis-to-s2" in x for x in sys.path) | |
| assert not (Path(sys.prefix) / "pyvenv.cfg").read_text().split("include-system-site-packages = ")[1].splitlines()[0].lower() == "true" | |
| assert Path(torch.__file__).resolve().is_relative_to(Path(sys.prefix).resolve()) | |
| assert Path(np.__file__).resolve().is_relative_to(Path(sys.prefix).resolve()) | |
| model = load_model("cpu") | |
| records = [] | |
| for directory in sorted((ROOT/"demo").iterdir()): | |
| if not directory.is_dir(): | |
| continue | |
| begin = time.monotonic() | |
| inputs, metadata = load_sample(directory) | |
| values = predict(model, inputs) | |
| reference = np.load(directory/"reference_cpu.npy", allow_pickle=False) | |
| np.testing.assert_allclose(values, reference, atol=1e-5, rtol=1e-5) | |
| assert values.shape == (256, 256) and -1 <= values.min() <= values.max() <= 1 | |
| records.append({"id": directory.name, "max_absolute_difference": float(np.abs(values-reference).max()), | |
| "seconds": time.monotonic()-begin}) | |
| print("MATCH", directory.name, records[-1], flush=True) | |
| assert len(records) == 10 | |
| sample = ROOT/"demo"/records[0]["id"] | |
| with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary: | |
| temporary = Path(temporary) | |
| inputs_only = temporary/"inputs_only" | |
| inputs_only.mkdir() | |
| for name in ("inputs.npz", "metadata.json"): | |
| shutil.copyfile(sample/name, inputs_only/name) | |
| result = temporary/"prediction.tif" | |
| subprocess.run([sys.executable, "-m", "modis_s2.predict", "--sample", str(inputs_only), | |
| "--output", str(result)], check=True) | |
| _, metadata = load_sample(sample) | |
| reference = np.load(sample/"reference_cpu.npy", allow_pickle=False) | |
| with rasterio.open(result) as dataset: | |
| assert dataset.count == 1 and dataset.dtypes == ("float32",) | |
| assert dataset.crs == rasterio.crs.CRS.from_string(metadata["geometry"]["crs"]) | |
| assert dataset.transform == Affine(*metadata["geometry"]["transform"]) | |
| np.testing.assert_allclose(dataset.read(1), reference, atol=1e-5, rtol=1e-5) | |
| with np.load(sample/"inputs.npz", allow_pickle=False) as archive: | |
| broken = {key: archive[key] for key in archive.files if key != "s2"} | |
| np.savez_compressed(inputs_only/"inputs.npz", **broken) | |
| try: | |
| load_sample(inputs_only) | |
| except ValueError as error: | |
| assert "missing=['s2']" in str(error) | |
| else: | |
| raise AssertionError("A missing sensor input was silently accepted") | |
| metrics = evaluate(ROOT/"demo", output=ROOT/"demo_metrics_cpu.json") | |
| result = {"passed": True, "device": "cpu", "precision": "fp32", "demo_scenes": len(records), | |
| "prediction_tolerance": {"atol": 1e-5, "rtol": 1e-5}, | |
| "original_vs_portable_predictions": records, | |
| "max_absolute_difference": max(x["max_absolute_difference"] for x in records), | |
| "fresh_environment": True, "system_site_packages": False, | |
| "training_repository_imported": False, "target_free_cli_inference": True, | |
| "geotiff_grid_and_values_verified": True, "missing_input_rejected": True, | |
| "demo_evaluation_completed": True, | |
| "full_validation_predictions_recomputed": False, | |
| "python": sys.version.split()[0], | |
| "packages": {p: importlib.metadata.version(p) for p in | |
| ("torch", "numpy", "scipy", "safetensors", "rasterio", "huggingface-hub")}, | |
| "seconds": time.monotonic()-started} | |
| (ROOT/"test_results.json").write_text(json.dumps(result, indent=2, allow_nan=False)) | |
| print("PORTABLE PACKAGE TESTS PASSED", flush=True) | |