"""Real inference; no training or external inference APIs.""" import argparse import json import os import warnings from pathlib import Path import numpy as np from PIL import Image, UnidentifiedImageError from src.common import CLASSES, preprocess WARNING = ( "Out-of-distribution warning: this model was trained on 64×64 Sentinel-2 EuroSAT RGB patches. " "Ordinary photographs, maps, other sensors or scales can produce unreliable results. " "No validated automatic out-of-distribution detector is available. " "Softmax probabilities are not calibrated confidence. This model does not identify geographic location." ) MAX_BYTES = 10 * 1024 * 1024 MAX_PIXELS = 16_000_000 Image.MAX_IMAGE_PIXELS = MAX_PIXELS def validate_image(path): path = Path(path) if not path.is_file() or path.stat().st_size > MAX_BYTES: raise ValueError("Upload a JPEG or PNG file no larger than 10 MiB.") try: with warnings.catch_warnings(): warnings.simplefilter("error", Image.DecompressionBombWarning) with Image.open(path) as image: if ( image.format not in ("JPEG", "PNG") or image.width * image.height > MAX_PIXELS ): raise ValueError( "Only JPEG/PNG images up to 16 megapixels are accepted." ) image.verify() with Image.open(path) as image: return preprocess(image) except ( UnidentifiedImageError, OSError, Image.DecompressionBombError, Image.DecompressionBombWarning, ) as exc: raise ValueError("The image is corrupt, unsupported or too large.") from exc class Predictor: def __init__(self, model_dir=None): import tensorflow as tf directory = Path( model_dir or os.getenv("CELYRIX_MODEL_DIR", "artifacts/release") ) repo = os.getenv("CELYRIX_MODEL_REPO") if repo: revision = os.getenv("CELYRIX_MODEL_REVISION", "") if len(revision) != 40 or any( c not in "0123456789abcdef" for c in revision.lower() ): raise ValueError( "Remote model requires a full pinned commit SHA in CELYRIX_MODEL_REVISION." ) from huggingface_hub import snapshot_download directory = Path( snapshot_download( repo, revision=revision, allow_patterns=["model.keras", "class_mapping.json"], ) ) mapping = json.loads((directory / "class_mapping.json").read_text()) if mapping != {str(i): c for i, c in enumerate(CLASSES)}: raise ValueError("Class mapping does not match CELYRIX 1.0.0.") self.model = tf.keras.models.load_model( directory / "model.keras", compile=False, safe_mode=True ) if self.model.input_shape != (None, 64, 64, 3) or self.model.output_shape != ( None, 5, ): raise ValueError("Unexpected model input/output shape.") def predict(self, path): x = validate_image(path) p = np.asarray(self.model(x[None], training=False))[0] if ( not np.isfinite(p).all() or np.any(p < 0) or not np.isclose(p.sum(), 1, atol=1e-5) ): raise RuntimeError("Model returned an invalid probability distribution.") return { "label": CLASSES[int(p.argmax())], "probabilities": dict(zip(CLASSES, map(float, p))), "model_version": "1.0.0", "warning": WARNING, } def main(): parser = argparse.ArgumentParser() parser.add_argument("image") parser.add_argument("--model-dir") args = parser.parse_args() print(json.dumps(Predictor(args.model_dir).predict(args.image), indent=2)) if __name__ == "__main__": main()