Spaces:
Sleeping
Sleeping
Download plant_classifier/inference.py from ZZW45/image-classifier: direct link, hf CLI and curl.
- Browser
- Download file 5.78 kB
-
https://huggingface.co/spaces/ZZW45/image-classifier/resolve/main/plant_classifier/inference.py
- Command line
-
hf download hf://spaces/ZZW45/image-classifier/plant_classifier/inference.py
-
curl -L -o inference.py https://huggingface.co/spaces/ZZW45/image-classifier/resolve/main/plant_classifier/inference.py
5.78 kB
| """Offline image prediction using the metadata stored with model weights.""" | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| from typing import Any | |
| from PIL import Image, UnidentifiedImageError | |
| import torch | |
| from .checkpoint import load_checkpoint | |
| from .data import make_transform | |
| IMAGE_EXTENSIONS = frozenset({".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"}) | |
| def resolve_device(device: str = "auto") -> torch.device: | |
| """Choose a device, without silently ignoring an explicit CUDA request.""" | |
| if device == "auto": | |
| return torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| try: | |
| selected = torch.device(device) | |
| except (RuntimeError, ValueError) as exc: | |
| raise ValueError(f"Invalid device {device!r}; use auto, cpu, cuda, or cuda:N.") from exc | |
| if selected.type not in {"cpu", "cuda"}: | |
| raise ValueError("Supported devices are auto, cpu, cuda, and cuda:N.") | |
| if selected.type == "cuda": | |
| if not torch.cuda.is_available(): | |
| raise ValueError("CUDA was requested but is unavailable; use --device cpu or enable Docker GPU access.") | |
| if selected.index is not None and selected.index >= torch.cuda.device_count(): | |
| raise ValueError(f"CUDA device index {selected.index} is unavailable.") | |
| return selected | |
| def prediction_transform(checkpoint: dict[str, Any]): | |
| """Reconstruct deterministic preprocessing from the checkpoint itself.""" | |
| preprocessing = checkpoint["preprocessing"] | |
| return make_transform( | |
| image_size=preprocessing["image_size"], | |
| augment=False, | |
| mean=preprocessing["mean"], | |
| std=preprocessing["std"], | |
| ) | |
| def _image_paths(inputs: list[str]) -> list[Path]: | |
| if not inputs: | |
| raise ValueError("Provide at least one image path or directory.") | |
| paths: list[Path] = [] | |
| seen: set[Path] = set() | |
| for item in inputs: | |
| path = Path(item).expanduser().resolve() | |
| if not path.exists(): | |
| raise FileNotFoundError(f"Input does not exist: {path}") | |
| if path.is_dir(): | |
| candidates = sorted( | |
| candidate for candidate in path.rglob("*") | |
| if candidate.is_file() and candidate.suffix.lower() in IMAGE_EXTENSIONS | |
| ) | |
| if not candidates: | |
| raise ValueError(f"No supported images found in directory: {path}") | |
| elif path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS: | |
| candidates = [path] | |
| else: | |
| raise ValueError(f"Unsupported image input: {path}") | |
| for candidate in candidates: | |
| if candidate not in seen: | |
| seen.add(candidate) | |
| paths.append(candidate) | |
| return paths | |
| def write_json(path: str | Path, value: Any) -> None: | |
| """Write a complete result atomically, so failed runs do not leave partial JSON.""" | |
| destination = Path(path) | |
| destination.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = destination.with_suffix(destination.suffix + ".tmp") | |
| temporary.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n", encoding="utf-8") | |
| temporary.replace(destination) | |
| def predict( | |
| checkpoint_path: str, | |
| inputs: list[str], | |
| output_path: str | None = None, | |
| top_k: int = 5, | |
| device: str = "auto", | |
| batch_size: int = 64, | |
| ) -> list[dict[str, Any]]: | |
| """Predict files or recursively discovered images; never access the dataset.""" | |
| if not isinstance(batch_size, int) or isinstance(batch_size, bool) or batch_size < 1: | |
| raise ValueError("batch_size must be a positive integer.") | |
| selected_device = resolve_device(device) | |
| model, checkpoint = load_checkpoint(checkpoint_path, selected_device) | |
| class_names = checkpoint["class_names"] | |
| if not isinstance(top_k, int) or isinstance(top_k, bool) or not 1 <= top_k <= len(class_names): | |
| raise ValueError(f"top_k must be an integer from 1 to {len(class_names)}.") | |
| paths = _image_paths(inputs) | |
| transform = prediction_transform(checkpoint) | |
| model.eval() | |
| results: list[dict[str, Any]] = [] | |
| with torch.inference_mode(): | |
| for start in range(0, len(paths), batch_size): | |
| batch_paths = paths[start:start + batch_size] | |
| tensors = [] | |
| for path in batch_paths: | |
| try: | |
| with Image.open(path) as image: | |
| tensors.append(transform(image)) | |
| except (UnidentifiedImageError, OSError, ValueError) as exc: | |
| raise ValueError(f"Cannot decode image {path}: {exc}") from exc | |
| logits = model(torch.stack(tensors).to(selected_device)) | |
| if logits.shape != (len(batch_paths), len(class_names)): | |
| raise ValueError("Model output shape does not match the checkpoint class mapping.") | |
| probabilities = logits.float().softmax(dim=1) | |
| if not torch.isfinite(probabilities).all(): | |
| raise ValueError("Model produced non-finite prediction probabilities.") | |
| values, indices = probabilities.topk(top_k, dim=1) | |
| for path, scores, labels in zip(batch_paths, values.cpu().tolist(), indices.cpu().tolist()): | |
| ranking = [ | |
| {"class_id": index, "label": class_names[index], "probability": float(score)} | |
| for score, index in zip(scores, labels) | |
| ] | |
| results.append({ | |
| "path": str(path), | |
| "prediction": ranking[0]["label"], | |
| "confidence": ranking[0]["probability"], | |
| "top_k": ranking, | |
| }) | |
| if output_path is not None: | |
| write_json(output_path, results) | |
| return results | |