File size: 2,138 Bytes
b0d8bdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright 2026 Nikhil Raghavendra
# SPDX-License-Identifier: Apache-2.0
"""Shared fixtures: deterministic structured images and the weights guard."""

from __future__ import annotations

from importlib.util import find_spec
from typing import TYPE_CHECKING

import numpy as np
import pytest

from sen_bridge import weights

if TYPE_CHECKING:
    from numpy.typing import NDArray

_SIZE = 128
_BLUR = 5

# Skip modules whose framework is not installed instead of failing collection.
collect_ignore: list[str] = []
if find_spec("torch") is None:
    collect_ignore += ["test_metrics.py", "test_parity.py"]
if find_spec("jax") is None:
    collect_ignore.append("test_parity.py")


def structured_images(n: int, seed: int = 0) -> NDArray[np.float32]:
    """Make deterministic images in [-1, 1]: smoothed noise plus a gradient.

    Args:
        n: Number of images.
        seed: Seed of the noise.

    Returns:
        Float32 array of shape ``[n, 3, 128, 128]``.
    """
    rng = np.random.default_rng(seed)
    a = rng.random((n, 3, _SIZE, _SIZE)).astype(np.float32)
    kernel = np.ones(_BLUR, np.float32) / _BLUR
    for axis in (2, 3):
        a = np.apply_along_axis(
            lambda v: np.convolve(v, kernel, mode="same"), axis, a
        )
    g = np.linspace(-1, 1, _SIZE, dtype=np.float32)
    ramp = 0.5 * g[None, None, :, None] * g[None, None, None, :]
    return np.clip(a * 3 - 1 + ramp, -1, 1).astype(np.float32)


@pytest.fixture(scope="session")
def pair() -> tuple[NDArray[np.float32], NDArray[np.float32]]:
    """Return a batch of images and a noisy copy of it."""
    x = structured_images(12)
    noise = np.random.default_rng(1).standard_normal(x.shape).astype(np.float32)
    return x, np.clip(x + 0.15 * noise, -1, 1).astype(np.float32)


@pytest.fixture(scope="session")
def weights_ready() -> None:
    """Make sure the metric weights are available, or skip the test."""
    try:
        weights.path("fid_inception")
        weights.path("lpips_vgg")
    # Offline or the host is unavailable.
    except Exception as exc:  # ruff: ignore[blind-except]
        pytest.skip(f"weights unavailable: {exc}")