File size: 4,212 Bytes
a014e55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22045db
 
 
 
0c2150a
22045db
2952455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a014e55
0c2150a
 
22045db
0c2150a
 
22045db
a014e55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22045db
 
 
 
0c2150a
22045db
a014e55
 
 
 
 
 
0c2150a
a014e55
 
0c2150a
a014e55
 
 
2952455
 
0c2150a
 
a014e55
2952455
 
a014e55
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
"""Gradio application for the Oxford-IIIT Pet breed and species classifier.

This script is independent of the training workflow. It rebuilds the deployed
architecture (ResNet18 with a 37-class head), loads the fine-tuned weights from
``pet_breed_model.pth``, and serves single-image predictions with latency.
"""

from __future__ import annotations

import os
from pathlib import Path

import gradio as gr
import torch
from PIL import Image

from src.dataset import build_eval_transform
from src.model import NUM_CLASSES, build_resnet18_classifier
from src.utils import CLASS_NAMES, format_breed_name, predict_image

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
MODEL_PATH = Path(os.environ.get("PET_MODEL_PATH", Path(__file__).parent / "pet_breed_model.pth"))
EVAL_TRANSFORM = build_eval_transform()


def load_deployed_model(weights_path: Path, device: str) -> torch.nn.Module:
    """Build the ResNet18 classifier and load the saved state_dict in evaluation mode."""
    if not weights_path.is_file() or weights_path.stat().st_size == 0:
        raise FileNotFoundError(
            f"Model weights not found or empty at '{weights_path}'. "
            "Train the model with notebooks/train.ipynb and save pet_breed_model.pth."
        )
    network = build_resnet18_classifier(num_classes=NUM_CLASSES, pretrained=False)
    state_dict = torch.load(weights_path, map_location=device)
    network.load_state_dict(state_dict)
    network.to(device)
    network.eval()
    return network


DEPLOYED_MODEL = load_deployed_model(MODEL_PATH, DEVICE)

# Breed-level accuracy of the deployed ResNet18 on the held-out Oxford-IIIT Pet test
# partition (3,669 images), as measured in notebooks/train.ipynb. Update this value
# if the model is retrained.
TEST_ACCURACY_PERCENT = 87.1
ACCURACY_NOTE = f"**Estimated Model Accuracy on Test Set (%):** {TEST_ACCURACY_PERCENT}%"

EXAMPLES_DIRECTORY = Path(__file__).parent / "images"
EXAMPLE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}


def collect_example_images(directory: Path) -> list[list[str]]:
    """Find sample photos in ``directory`` in the format expected by ``gr.Interface``."""
    if not directory.is_dir():
        return []
    image_paths = sorted(
        path for path in directory.iterdir() if path.suffix.lower() in EXAMPLE_EXTENSIONS
    )
    return [[str(path)] for path in image_paths]


EXAMPLE_INPUTS = collect_example_images(EXAMPLES_DIRECTORY)


def classify_pet(image: Image.Image | None) -> tuple[dict[str, float], str, float, str]:
    """Predict breed probabilities, species, and inference latency for one image.

    The final element is a fixed note with the model's overall test-set accuracy. It
    describes the model, not this particular prediction.
    """
    if image is None:
        raise gr.Error("Please upload a pet photo before running the classifier.")

    result = predict_image(
        DEPLOYED_MODEL,
        image,
        device=DEVICE,
        transform=EVAL_TRANSFORM,
        class_names=CLASS_NAMES,
        top_k=3,
    )
    breed_probabilities = {
        format_breed_name(breed): probability
        for breed, probability in result["probabilities"].items()
    }
    return (
        breed_probabilities,
        result["species"],
        round(result["inference_seconds"], 6),
        ACCURACY_NOTE,
    )


demo = gr.Interface(
    fn=classify_pet,
    inputs=gr.Image(type="pil", label="Upload Pet Photo"),
    outputs=[
        gr.Label(num_top_classes=3, label="Top Predicted Breeds (Confidence %)"),
        gr.Textbox(label="Detected Species (Cat vs. Dog)"),
        gr.Number(label="Inference Latency (seconds)"),
        gr.Markdown(value=ACCURACY_NOTE),
    ],
    title="Pet Breed Classifier",
    description=(
        "Drag and drop a photograph of a cat or dog into the upload area, or select one of "
        "the sample photos below. The model predicts the breed among the 37 Oxford-IIIT Pet "
        "categories, infers the species from the predicted breed, and reports the "
        "forward-pass latency for the single image."
    ),
    examples=EXAMPLE_INPUTS or None,
    cache_examples=False,
    flagging_mode="never",
)

if __name__ == "__main__":
    demo.launch()