Spaces:
Sleeping
Sleeping
Download plant_classifier/checkpoint.py from ZZW45/image-classifier: direct link, hf CLI and curl.
- Browser
- Download file 3.01 kB
-
https://huggingface.co/spaces/ZZW45/image-classifier/resolve/main/plant_classifier/checkpoint.py
- Command line
-
hf download hf://spaces/ZZW45/image-classifier/plant_classifier/checkpoint.py
-
curl -L -o checkpoint.py https://huggingface.co/spaces/ZZW45/image-classifier/resolve/main/plant_classifier/checkpoint.py
3.01 kB
| """Portable, metadata-validated checkpoints without pickled model objects.""" | |
| from __future__ import annotations | |
| import math | |
| from pathlib import Path | |
| from typing import Any | |
| import torch | |
| from .model import PlantDiseaseCNN | |
| SCHEMA_VERSION = 1 | |
| def _validate_metadata(checkpoint: Any) -> None: | |
| if ( | |
| not isinstance(checkpoint, dict) | |
| or type(checkpoint.get("schema_version")) is not int | |
| or checkpoint["schema_version"] != SCHEMA_VERSION | |
| ): | |
| raise ValueError("Unsupported checkpoint schema; expected schema_version=1") | |
| model_config = checkpoint.get("model_config") | |
| if not isinstance(model_config, dict) or set(model_config) != { | |
| "num_classes", "channels", "dropout" | |
| }: | |
| raise ValueError("Checkpoint has an invalid model_config") | |
| names = checkpoint.get("class_names") | |
| if ( | |
| not isinstance(names, list) | |
| or not all(isinstance(name, str) and name for name in names) | |
| or len(set(names)) != len(names) | |
| or len(names) != model_config["num_classes"] | |
| ): | |
| raise ValueError("Checkpoint class_names must uniquely match the model outputs") | |
| preprocessing = checkpoint.get("preprocessing") | |
| if not isinstance(preprocessing, dict): | |
| raise ValueError("Checkpoint is missing preprocessing metadata") | |
| size = preprocessing.get("image_size") | |
| if isinstance(size, bool) or not isinstance(size, int) or size < 16: | |
| raise ValueError("Checkpoint image_size must be an integer of at least 16") | |
| for name in ("mean", "std"): | |
| values = preprocessing.get(name) | |
| if ( | |
| not isinstance(values, (list, tuple)) | |
| or len(values) != 3 | |
| or any( | |
| isinstance(value, bool) | |
| or not isinstance(value, (int, float)) | |
| or not math.isfinite(value) | |
| or (name == "std" and value <= 0) | |
| for value in values | |
| ) | |
| ): | |
| raise ValueError(f"Checkpoint {name} must contain three valid RGB values") | |
| state = checkpoint.get("model_state_dict") | |
| if not isinstance(state, dict) or not state or any( | |
| not isinstance(key, str) or not isinstance(value, torch.Tensor) | |
| for key, value in state.items() | |
| ): | |
| raise ValueError("Checkpoint model_state_dict is missing or invalid") | |
| def load_checkpoint( | |
| path: str | Path, device: str | torch.device = "cpu" | |
| ) -> tuple[PlantDiseaseCNN, dict[str, Any]]: | |
| """Load on CPU, validate metadata, then move the reconstructed CNN.""" | |
| checkpoint = torch.load(path, map_location="cpu", weights_only=True) | |
| _validate_metadata(checkpoint) | |
| try: | |
| model = PlantDiseaseCNN(**checkpoint["model_config"]) | |
| model.load_state_dict(checkpoint["model_state_dict"], strict=True) | |
| except (TypeError, ValueError, RuntimeError) as exc: | |
| raise ValueError(f"Checkpoint model configuration/weights are incompatible: {exc}") from exc | |
| model.to(device) | |
| model.eval() | |
| return model, checkpoint | |