File size: 2,620 Bytes
de70591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d312b8
de70591
 
 
 
0d312b8
 
de70591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Original GenImage validation examples and dataset-label presentation."""

from pathlib import Path
import hashlib
import json

ROOT = Path(__file__).absolute().parent
SAMPLES = json.loads((ROOT / "examples/manifest.json").read_text())
GENERATOR_NAMES = {
    "stable_diffusion_v_1_4": "Stable Diffusion 1.4",
    "Midjourney": "Midjourney",
    "ADM": "ADM",
    "BigGAN": "BigGAN",
}


def sample_at(index):
    if isinstance(index, (list, tuple)):
        index = index[0]
    if (
        isinstance(index, bool)
        or not isinstance(index, int)
        or not 0 <= index < len(SAMPLES)
    ):
        raise ValueError("Unknown example selection.")
    sample = SAMPLES[index]
    return sample, ROOT / "examples" / sample["file"]


def gallery_items():
    return [
        (
            str(ROOT / "examples" / sample["file"]),
            f"{'Real' if sample['label'] == 0 else 'Generated'} {index % 4 + 1:02d} 路 "
            + (
                "ImageNet"
                if sample["label"] == 0
                else GENERATOR_NAMES[sample["generator"]]
            ),
        )
        for index, sample in enumerate(SAMPLES)
    ]


def annotate_example(outputs, sample):
    metadata = {
        key: sample[key]
        for key in (
            "id",
            "dataset",
            "split",
            "label",
            "label_name",
            "generator",
            "sha256",
        )
    }
    outputs[4]["example"] = metadata
    outputs[13]["result"]["example"] = metadata
    label = "Real" if sample["label"] == 0 else "Generated"
    generator = (
        "ImageNet" if sample["label"] == 0 else GENERATOR_NAMES[sample["generator"]]
    )
    return (
        f"Selected **{sample['id']}** 路 Dataset label: **{label}** 路 {generator} 路 "
        f"{sample['width']} 脳 {sample['height']}. Model prediction scores are shown above."
    )


def same_image_as_state(path, state):
    """An example response already contains its analysis; do not clear it on File.change.

    Gradio copies the returned example into its file cache, so the paths can differ
    even though the original bytes are identical.
    """
    if not path or not state or not state.get("path"):
        return False
    first, second = Path(path), Path(state["path"])
    try:
        if first == second:
            return first.is_file()
        if first.stat().st_size != second.stat().st_size:
            return False
        return (
            hashlib.sha256(first.read_bytes()).digest()
            == hashlib.sha256(second.read_bytes()).digest()
        )
    except OSError:
        return False