""" Inference module for Noita spell icon classification. 优先使用 ONNX Runtime 进行快速 CPU 推理;若不可用则回退到 PyTorch。 """ from __future__ import annotations import json from pathlib import Path import numpy as np import torch from PIL import Image from torchvision import models try: import onnxruntime as ort except ImportError: ort = None # ─── Configuration ─────────────────────────────────────────────────────────── MODEL_DIR = Path("models") ONNX_MODEL_PATH = MODEL_DIR / "spell_classifier.onnx" PTH_MODEL_PATH = MODEL_DIR / "best_model.pth" CLASS_NAMES_PATH = MODEL_DIR / "class_names.json" IMG_SIZE = 64 class SpellClassifier: """Spell icon classifier.""" def __init__( self, onnx_path: str | Path = ONNX_MODEL_PATH, pth_path: str | Path = PTH_MODEL_PATH, class_names_path: str | Path = CLASS_NAMES_PATH, ): self.onnx_path = Path(onnx_path) self.pth_path = Path(pth_path) self.class_names_path = Path(class_names_path) self.use_onnx = bool(ort is not None and self.onnx_path.exists() and self.class_names_path.exists()) if self.use_onnx: with open(self.class_names_path, "r", encoding="utf-8") as f: self.class_names = json.load(f) so = ort.SessionOptions() so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL self.session = ort.InferenceSession( str(self.onnx_path), sess_options=so, providers=["CPUExecutionProvider"], ) self.input_name = self.session.get_inputs()[0].name print(f"Loaded ONNX model: {self.onnx_path}") elif self.pth_path.exists(): checkpoint = torch.load(self.pth_path, weights_only=False, map_location="cpu") self.class_names = checkpoint["class_names"] num_classes = checkpoint["num_classes"] self.model = models.resnet18() self.model.fc = torch.nn.Linear(self.model.fc.in_features, num_classes) self.model.load_state_dict(checkpoint["model_state_dict"]) self.model.eval() print(f"Loaded PyTorch checkpoint: {self.pth_path} (Epoch {checkpoint.get('epoch', 0)})") else: raise FileNotFoundError(f"No model found at {self.onnx_path} or {self.pth_path}") print(f"Classes: {len(self.class_names)}") def preprocess(self, image: Image.Image, center_crop_ratio: float = 1.0) -> np.ndarray: """Preprocess a PIL image for inference.""" if center_crop_ratio < 1.0: w, h = image.size cw, ch = int(w * center_crop_ratio), int(h * center_crop_ratio) left = (w - cw) // 2 top = (h - ch) // 2 image = image.crop((left, top, left + cw, top + ch)) if image.mode == "RGBA": bg = Image.new("RGB", image.size, (30, 30, 30)) bg.paste(image, mask=image.split()[3]) image = bg else: image = image.convert("RGB") image = image.resize((IMG_SIZE, IMG_SIZE), Image.Resampling.LANCZOS) arr = np.array(image, dtype=np.float32) / 255.0 arr = (arr - 0.5) / 0.5 arr = arr.transpose(2, 0, 1) return arr[np.newaxis, ...] def classify(self, image: Image.Image | str | Path, top_k: int = 5, center_crop_ratio: float = 1.0) -> list[tuple[str, float]]: """Classify one image.""" if isinstance(image, (str, Path)): image = Image.open(image) input_tensor = self.preprocess(image, center_crop_ratio=center_crop_ratio) if self.use_onnx: logits = self.session.run(None, {self.input_name: input_tensor})[0] exp_logits = np.exp(logits - logits.max(axis=1, keepdims=True)) probs = exp_logits / exp_logits.sum(axis=1, keepdims=True) probs = probs[0] else: with torch.no_grad(): tensor = torch.from_numpy(input_tensor) logits = self.model(tensor) probs = torch.nn.functional.softmax(logits, dim=1).numpy()[0] top_indices = probs.argsort()[::-1][:top_k] return [(self.class_names[i], float(probs[i])) for i in top_indices] def classify_batch(self, images: list[Image.Image], top_k: int = 5, center_crop_ratio: float = 1.0) -> list[list[tuple[str, float]]]: """Classify multiple images.""" inputs = np.concatenate([self.preprocess(img, center_crop_ratio=center_crop_ratio) for img in images], axis=0) if self.use_onnx: logits = self.session.run(None, {self.input_name: inputs})[0] exp_logits = np.exp(logits - logits.max(axis=1, keepdims=True)) probs = exp_logits / exp_logits.sum(axis=1, keepdims=True) else: with torch.no_grad(): tensor = torch.from_numpy(inputs) logits = self.model(tensor) probs = torch.nn.functional.softmax(logits, dim=1).numpy() results = [] for prob in probs: top_indices = prob.argsort()[::-1][:top_k] results.append([(self.class_names[i], float(prob[i])) for i in top_indices]) return results _classifier = None def classify_icon(image, top_k=5): global _classifier if _classifier is None: _classifier = SpellClassifier() return _classifier.classify(image, top_k=top_k) if __name__ == "__main__": import sys if len(sys.argv) < 2: print("Usage: python inference.py ") raise SystemExit(1) classifier = SpellClassifier() results = classifier.classify(sys.argv[1]) print("\nPredictions:") for name, conf in results: print(f" {conf*100:5.1f}% {name}")