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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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
"""Shared helpers: class metadata, timed inference, training loop, and metrics.

The inference helpers (``predict_image`` and the species mapping) depend only on
``torch``, ``torchvision``, and ``Pillow`` so that ``app.py`` can import this
module in the deployment environment. Training-time metrics rely on
``scikit-learn`` and ``matplotlib``, which are imported lazily inside the
functions that need them.
"""

from __future__ import annotations

import copy
import random
import time
from typing import Any

import numpy as np
import torch
from PIL import Image
from torch import nn
from torch.utils.data import DataLoader

from .dataset import build_eval_transform

# Class names in the label order used by torchvision.datasets.OxfordIIITPet.
CLASS_NAMES: tuple[str, ...] = (
    "Abyssinian",
    "American Bulldog",
    "American Pit Bull Terrier",
    "Basset Hound",
    "Beagle",
    "Bengal",
    "Birman",
    "Bombay",
    "Boxer",
    "British Shorthair",
    "Chihuahua",
    "Egyptian Mau",
    "English Cocker Spaniel",
    "English Setter",
    "German Shorthaired",
    "Great Pyrenees",
    "Havanese",
    "Japanese Chin",
    "Keeshond",
    "Leonberger",
    "Maine Coon",
    "Miniature Pinscher",
    "Newfoundland",
    "Persian",
    "Pomeranian",
    "Pug",
    "Ragdoll",
    "Russian Blue",
    "Saint Bernard",
    "Samoyed",
    "Scottish Terrier",
    "Shiba Inu",
    "Siamese",
    "Sphynx",
    "Staffordshire Bull Terrier",
    "Wheaten Terrier",
    "Yorkshire Terrier",
)

CAT_BREEDS: frozenset[str] = frozenset(
    {
        "Abyssinian",
        "Bengal",
        "Birman",
        "Bombay",
        "British Shorthair",
        "Egyptian Mau",
        "Maine Coon",
        "Persian",
        "Ragdoll",
        "Russian Blue",
        "Siamese",
        "Sphynx",
    }
)


# ---------------------------------------------------------------------------
# Reproducibility and class metadata
# ---------------------------------------------------------------------------
def set_seed(seed: int = 42) -> None:
    """Seed Python, NumPy, and PyTorch (CPU and CUDA) for reproducible runs."""
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)


def get_species(predicted_breed: str) -> str:
    """Resolve species from a predicted breed using the fixed cat-breed set."""
    return "Cat" if predicted_breed in CAT_BREEDS else "Dog"


def format_breed_name(breed: str) -> str:
    """Convert a dataset class name (for example 'american bulldog') to display form."""
    return breed.title()


# ---------------------------------------------------------------------------
# Single-image inference with latency measurement
# ---------------------------------------------------------------------------
def predict_image(
    network: nn.Module,
    image: Image.Image,
    device: torch.device | str,
    transform: Any = None,
    class_names: tuple[str, ...] = CLASS_NAMES,
    top_k: int = 3,
) -> dict[str, Any]:
    """Classify one PIL image and measure the forward-pass latency.

    The reported ``inference_seconds`` covers the forward pass and softmax, as
    specified in the project guidelines. Preprocessing time is reported
    separately as ``preprocessing_seconds`` so that both figures are available.

    Returns:
        A dictionary with the predicted breed, species, the top-k predictions,
        the full probability dictionary, and the timing measurements.
    """
    device = torch.device(device)
    transform = transform if transform is not None else build_eval_transform()

    preprocessing_start = time.perf_counter()
    # transform(...) yields a (3, H, W) tensor; unsqueeze(0) prepends the batch
    # dimension so the network receives (1, 3, H, W).
    image_tensor = transform(image.convert("RGB")).unsqueeze(0).to(device)
    preprocessing_seconds = time.perf_counter() - preprocessing_start

    network.eval()
    if device.type == "cuda":
        torch.cuda.synchronize()
    start_time = time.perf_counter()
    with torch.inference_mode():
        logits = network(image_tensor)
        probs = torch.softmax(logits, dim=1)
    if device.type == "cuda":
        torch.cuda.synchronize()
    inference_time = time.perf_counter() - start_time

    # probs has shape (1, num_classes); squeeze(0) removes only the batch axis.
    probability_vector = probs.squeeze(0).cpu()
    top_values, top_indices = torch.topk(probability_vector, k=top_k)
    top_predictions = [
        (class_names[index], float(value))
        for value, index in zip(top_values.tolist(), top_indices.tolist())
    ]
    predicted_breed = top_predictions[0][0]
    return {
        "breed": predicted_breed,
        "species": get_species(predicted_breed),
        "confidence": top_predictions[0][1],
        "top_predictions": top_predictions,
        "probabilities": {
            class_names[index]: float(value)
            for index, value in enumerate(probability_vector.tolist())
        },
        "inference_seconds": inference_time,
        "preprocessing_seconds": preprocessing_seconds,
    }


def benchmark_latency(
    network: nn.Module,
    images: list[Image.Image],
    device: torch.device | str,
    warmup: int = 3,
) -> dict[str, float]:
    """Measure single-image latency statistics over a list of PIL images."""
    for warmup_image in images[:warmup]:
        predict_image(network, warmup_image, device)
    timings = np.array(
        [predict_image(network, sample, device)["inference_seconds"] for sample in images]
    )
    return {
        "mean_seconds": float(timings.mean()),
        "std_seconds": float(timings.std()),
        "median_seconds": float(np.median(timings)),
        "max_seconds": float(timings.max()),
        "samples": int(len(timings)),
    }


# ---------------------------------------------------------------------------
# Training and evaluation loops
# ---------------------------------------------------------------------------
def train_one_epoch(
    network: nn.Module,
    loader: DataLoader,
    criterion: nn.Module,
    optimizer: torch.optim.Optimizer,
    device: torch.device | str,
) -> dict[str, float]:
    """Run one optimization pass over ``loader`` and return mean loss and accuracy."""
    network.train()
    loss_sum, correct, seen = 0.0, 0, 0
    for batch_images, batch_labels in loader:
        batch_images = batch_images.to(device, non_blocking=True)
        batch_labels = batch_labels.to(device, non_blocking=True)

        optimizer.zero_grad(set_to_none=True)
        logits = network(batch_images)
        loss_value = criterion(logits, batch_labels)
        loss_value.backward()
        optimizer.step()

        batch_size = batch_labels.size(0)
        loss_sum += loss_value.item() * batch_size
        correct += (logits.argmax(dim=1) == batch_labels).sum().item()
        seen += batch_size
    return {"loss": loss_sum / seen, "accuracy": correct / seen}


def evaluate_loader(
    network: nn.Module,
    loader: DataLoader,
    criterion: nn.Module,
    device: torch.device | str,
) -> dict[str, Any]:
    """Evaluate ``network`` on ``loader`` without gradient tracking.

    Returns the mean loss, accuracy, and the true and predicted label arrays so
    that downstream code can compute precision, recall, F1, and the confusion
    matrix.
    """
    network.eval()
    loss_sum, seen = 0.0, 0
    true_batches: list[np.ndarray] = []
    predicted_batches: list[np.ndarray] = []
    with torch.inference_mode():
        for batch_images, batch_labels in loader:
            batch_images = batch_images.to(device, non_blocking=True)
            batch_labels = batch_labels.to(device, non_blocking=True)

            logits = network(batch_images)
            loss_value = criterion(logits, batch_labels)

            loss_sum += loss_value.item() * batch_labels.size(0)
            seen += batch_labels.size(0)
            true_batches.append(batch_labels.cpu().numpy())
            predicted_batches.append(logits.argmax(dim=1).cpu().numpy())
    true_labels = np.concatenate(true_batches)
    predicted_labels = np.concatenate(predicted_batches)
    return {
        "loss": loss_sum / seen,
        "accuracy": float((true_labels == predicted_labels).mean()),
        "y_true": true_labels,
        "y_pred": predicted_labels,
    }


def fit_model(
    network: nn.Module,
    loaders: dict[str, DataLoader],
    criterion: nn.Module,
    optimizer: torch.optim.Optimizer,
    scheduler: torch.optim.lr_scheduler.ReduceLROnPlateau,
    device: torch.device | str,
    max_epochs: int,
    early_stopping_patience: int,
    run_name: str = "model",
) -> dict[str, Any]:
    """Train with validation-loss monitoring, LR scheduling, and early stopping.

    ``scheduler`` is stepped on the validation loss. Training stops when the
    validation loss has not improved for ``early_stopping_patience`` epochs. The
    weights from the epoch with the lowest validation loss are returned.
    """
    history: dict[str, list[float]] = {
        "train_loss": [],
        "train_accuracy": [],
        "validation_loss": [],
        "validation_accuracy": [],
        "learning_rate": [],
    }
    best_validation_loss = float("inf")
    best_validation_accuracy = 0.0
    best_epoch = 0
    best_state: dict[str, torch.Tensor] = {}
    epochs_without_improvement = 0
    training_start = time.perf_counter()

    for epoch in range(1, max_epochs + 1):
        train_scores = train_one_epoch(network, loaders["train"], criterion, optimizer, device)
        validation_scores = evaluate_loader(network, loaders["validation"], criterion, device)
        scheduler.step(validation_scores["loss"])

        history["train_loss"].append(train_scores["loss"])
        history["train_accuracy"].append(train_scores["accuracy"])
        history["validation_loss"].append(validation_scores["loss"])
        history["validation_accuracy"].append(validation_scores["accuracy"])
        history["learning_rate"].append(optimizer.param_groups[0]["lr"])

        improved = validation_scores["loss"] < best_validation_loss
        if improved:
            best_validation_loss = validation_scores["loss"]
            best_validation_accuracy = validation_scores["accuracy"]
            best_epoch = epoch
            best_state = copy.deepcopy(
                {key: value.detach().cpu() for key, value in network.state_dict().items()}
            )
            epochs_without_improvement = 0
        else:
            epochs_without_improvement += 1

        print(
            f"[{run_name}] epoch {epoch:02d}/{max_epochs} | "
            f"train loss {train_scores['loss']:.4f} acc {train_scores['accuracy']:.4f} | "
            f"val loss {validation_scores['loss']:.4f} acc {validation_scores['accuracy']:.4f} | "
            f"lr {history['learning_rate'][-1]:.2e}" + (" *" if improved else "")
        )
        if epochs_without_improvement >= early_stopping_patience:
            print(f"[{run_name}] early stopping at epoch {epoch} (best epoch {best_epoch}).")
            break

    network.load_state_dict(best_state)
    return {
        "history": history,
        "best_epoch": best_epoch,
        "best_validation_loss": best_validation_loss,
        "best_validation_accuracy": best_validation_accuracy,
        "epochs_run": len(history["train_loss"]),
        "training_seconds": time.perf_counter() - training_start,
        "best_state": best_state,
    }


# ---------------------------------------------------------------------------
# Metrics and plots (training environment only)
# ---------------------------------------------------------------------------
def compute_classification_metrics(
    y_true: np.ndarray,
    y_pred: np.ndarray,
    class_names: tuple[str, ...] = CLASS_NAMES,
) -> dict[str, Any]:
    """Compute breed-level and derived species-level classification metrics."""
    from sklearn.metrics import (
        accuracy_score,
        classification_report,
        confusion_matrix,
        precision_recall_fscore_support,
    )

    label_ids = list(range(len(class_names)))
    macro_precision, macro_recall, macro_f1, _ = precision_recall_fscore_support(
        y_true, y_pred, labels=label_ids, average="macro", zero_division=0
    )
    weighted_precision, weighted_recall, weighted_f1, _ = precision_recall_fscore_support(
        y_true, y_pred, labels=label_ids, average="weighted", zero_division=0
    )

    species_true = np.array([get_species(class_names[index]) for index in y_true])
    species_pred = np.array([get_species(class_names[index]) for index in y_pred])

    return {
        "accuracy": float(accuracy_score(y_true, y_pred)),
        "macro_precision": float(macro_precision),
        "macro_recall": float(macro_recall),
        "macro_f1": float(macro_f1),
        "weighted_precision": float(weighted_precision),
        "weighted_recall": float(weighted_recall),
        "weighted_f1": float(weighted_f1),
        "species_accuracy": float(accuracy_score(species_true, species_pred)),
        "confusion_matrix": confusion_matrix(y_true, y_pred, labels=label_ids),
        "species_confusion_matrix": confusion_matrix(
            species_true, species_pred, labels=["Cat", "Dog"]
        ),
        "report": classification_report(
            y_true,
            y_pred,
            labels=label_ids,
            target_names=[format_breed_name(name) for name in class_names],
            zero_division=0,
        ),
    }


def top_confusions(
    confusion: np.ndarray,
    class_names: tuple[str, ...] = CLASS_NAMES,
    count: int = 10,
) -> list[tuple[str, str, int]]:
    """Return the most frequent off-diagonal (true, predicted, count) breed pairs."""
    off_diagonal = confusion.copy()
    np.fill_diagonal(off_diagonal, 0)
    flat_order = np.argsort(off_diagonal, axis=None)[::-1][:count]
    pairs: list[tuple[str, str, int]] = []
    for flat_index in flat_order:
        true_index, predicted_index = np.unravel_index(flat_index, off_diagonal.shape)
        if off_diagonal[true_index, predicted_index] == 0:
            break
        pairs.append(
            (
                format_breed_name(class_names[true_index]),
                format_breed_name(class_names[predicted_index]),
                int(off_diagonal[true_index, predicted_index]),
            )
        )
    return pairs


def plot_confusion_matrix(
    confusion: np.ndarray,
    class_names: tuple[str, ...] | list[str],
    title: str,
    normalize: bool = True,
):
    """Render a confusion matrix heat map and return the matplotlib figure."""
    import matplotlib.pyplot as plt

    matrix = confusion.astype(float)
    if normalize:
        row_totals = matrix.sum(axis=1, keepdims=True)
        matrix = np.divide(matrix, row_totals, out=np.zeros_like(matrix), where=row_totals > 0)

    large = len(class_names) > 10
    figure, axes = plt.subplots(figsize=(14, 12) if large else (5, 4))
    image_artist = axes.imshow(matrix, cmap="Blues", vmin=0.0, vmax=1.0 if normalize else None)
    figure.colorbar(image_artist, ax=axes, fraction=0.046, pad=0.04)
    axes.set_xticks(range(len(class_names)))
    axes.set_yticks(range(len(class_names)))
    labels = [format_breed_name(name) for name in class_names] if large else list(class_names)
    axes.set_xticklabels(labels, rotation=90, fontsize=7 if large else 10)
    axes.set_yticklabels(labels, fontsize=7 if large else 10)
    axes.set_xlabel("Predicted label")
    axes.set_ylabel("True label")
    axes.set_title(title)
    if not large:
        for row in range(matrix.shape[0]):
            for column in range(matrix.shape[1]):
                axes.text(
                    column,
                    row,
                    f"{confusion[row, column]}",
                    ha="center",
                    va="center",
                    color="white" if matrix[row, column] > 0.5 else "black",
                )
    figure.tight_layout()
    return figure


def plot_training_curves(fit_results: dict[str, dict[str, Any]]):
    """Plot loss and accuracy curves for each named training run."""
    import matplotlib.pyplot as plt

    figure, (loss_axes, accuracy_axes) = plt.subplots(1, 2, figsize=(13, 4.5))
    for run_name, result in fit_results.items():
        run_history = result["history"]
        epochs = range(1, len(run_history["train_loss"]) + 1)
        loss_axes.plot(epochs, run_history["train_loss"], linestyle="--", label=f"{run_name} train")
        loss_axes.plot(epochs, run_history["validation_loss"], label=f"{run_name} validation")
        accuracy_axes.plot(
            epochs, run_history["train_accuracy"], linestyle="--", label=f"{run_name} train"
        )
        accuracy_axes.plot(
            epochs, run_history["validation_accuracy"], label=f"{run_name} validation"
        )
    loss_axes.set_title("Cross-entropy loss")
    loss_axes.set_xlabel("Epoch")
    loss_axes.set_ylabel("Loss")
    accuracy_axes.set_title("Accuracy")
    accuracy_axes.set_xlabel("Epoch")
    accuracy_axes.set_ylabel("Accuracy")
    for axes in (loss_axes, accuracy_axes):
        axes.grid(alpha=0.3)
        axes.legend()
    figure.tight_layout()
    return figure