File size: 7,585 Bytes
148d4ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
"""Shared, deterministic X1.1 Space inputs and release asset validation.

This module does not import Gradio, PyTorch, ONNX Runtime or CUDA. Backend
initialization belongs to app.py; both Spaces use this exact preprocessing.
"""
import hashlib
import json
import os
from pathlib import Path

import numpy as np
from PIL import Image, ImageOps


MODEL_REPO = "Grio43/OppaiOracle-experimental-X1.1"
MODEL_REVISION = "d7b2aaeb14d4f97b4337810765894d6f3fe6bf69"
VOCAB_SHA256 = "e3e6ccc137d9152d8a17fbd19e0c1ae595b2317a6c55893fd25779620b4b8087"
NUM_OUTPUTS = 14996
FILE_SHA256 = {
    "config.json": "39e218e1674f5fb4e00023aa4bcea778c09704d856f9f833ef01bb251d1415fd",
    "model.onnx": "49ba0f66f83ba88a101b6edac54ec39f0a12eab66743e13ae42efc3570745bf7",
    "model.safetensors": "ec07d0034f48ba3ceff8624993baf3ea30fa3a2e3cc8908682eb3e4f84eda766",
}


def _verify_file(path, filename):
    digest = hashlib.sha256()
    with Path(path).open("rb") as stream:
        for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""):
            digest.update(chunk)
    if digest.hexdigest() != FILE_SHA256[filename]:
        raise ValueError(f"{filename} checksum differs from the pinned X1.1 release")


def vocabulary_sha256(vocabulary):
    canonical = json.dumps(vocabulary, ensure_ascii=False, sort_keys=True,
                           separators=(",", ":")).encode("utf-8")
    return hashlib.sha256(canonical).hexdigest()


def _validate_preprocessing(metadata):
    expected = {
        "image_size": 448,
        "color_order": "RGB",
        "pad_color": [114, 114, 114],
        "normalize_mean": [0.5, 0.5, 0.5],
        "normalize_std": [0.5, 0.5, 0.5],
        "resize_filter": "LANCZOS",
        "upscale": False,
    }
    for key, value in expected.items():
        if metadata.get(key) != value:
            raise ValueError(f"Expected X1.1 preprocessing {key}={value!r}")


def _validate_config_vocab(config, vocabulary):
    _validate_preprocessing(config["preprocessing"])
    if (config.get("repo_id") != MODEL_REPO
            or config.get("release") != "experimental-X1.1"
            or config.get("image_size") != 448
            or config.get("num_labels") != NUM_OUTPUTS
            or config["architecture"].get("image_size") != 448
            or config["architecture"].get("num_tags") != NUM_OUTPUTS):
        raise ValueError("Configuration is not the pinned X1.1 448px model")
    if (config.get("vocab_sha256") != VOCAB_SHA256
            or vocabulary_sha256(vocabulary) != VOCAB_SHA256):
        raise ValueError("Vocabulary checksum differs from the pinned X1.1 release")
    names = vocabulary["index_to_tag"]
    if set(names) != {str(i) for i in range(NUM_OUTPUTS)}:
        raise ValueError("Vocabulary indices must cover every model output exactly")
    if names["0"] != "<PAD>" or names["1"] != "<UNK>":
        raise ValueError("Expected PAD=0 and UNK=1")
    if vocabulary["tag_to_index"] != {tag: int(index) for index, tag in names.items()}:
        raise ValueError("Vocabulary index maps disagree")
    if len(set(names.values())) != NUM_OUTPUTS:
        raise ValueError("Vocabulary names must be unique")
    if not 0 <= float(config["threshold"]) <= 1:
        raise ValueError("Invalid configured prediction threshold")


def download_assets(backend):
    """Return (model_path, config, vocabulary) from one verified Hub revision.

    config.json is downloaded first because it is actually consumed for model,
    preprocessing and threshold setup, and participates in normal Hub download
    counting. No synthetic tracking requests or per-inference network calls are
    made. OPPAI_MODEL_DIR selects a fully local copy for verification/offline use.
    """
    if backend not in ("onnx", "safetensors"):
        raise ValueError("Backend must be onnx or safetensors")
    local_directory = os.environ.get("OPPAI_MODEL_DIR")
    if local_directory:
        directory = Path(local_directory).expanduser().resolve()

        def obtain(filename):
            return directory / filename
    else:
        from huggingface_hub import hf_hub_download

        def obtain(filename):
            return Path(hf_hub_download(
                repo_id=MODEL_REPO, filename=filename, revision=MODEL_REVISION))

    config_path = obtain("config.json")
    _verify_file(config_path, "config.json")
    config = json.loads(config_path.read_text(encoding="utf-8-sig"))
    vocabulary_path = obtain("vocabulary.json")
    vocabulary = json.loads(vocabulary_path.read_text(encoding="utf-8-sig"))
    _validate_config_vocab(config, vocabulary)
    filename = f"model.{backend}"
    if config[f"model_file_{backend}"] != filename:
        raise ValueError("Configuration points to an unexpected model file")
    model_path = obtain(filename)
    _verify_file(model_path, filename)
    return model_path, config, vocabulary


def preprocess(image, metadata):
    """PIL image -> contiguous CHW float32 pixels and HW bool padding mask.

    This matches release infer.py exactly: EXIF transpose, alpha compositing,
    downscale-only LANCZOS and centered 114-gray padding. True means padding.
    The caller retains ownership of its PIL image.
    """
    _validate_preprocessing(metadata)
    if not isinstance(image, Image.Image):
        raise TypeError("Expected a PIL image")
    if image.width < 1 or image.height < 1:
        raise ValueError("Image dimensions must be positive")
    size = int(metadata["image_size"])
    pad = tuple(metadata["pad_color"])
    img = ImageOps.exif_transpose(image)
    if img.mode in ("RGBA", "LA") or "transparency" in img.info:
        rgba = img.convert("RGBA")
        background = Image.new("RGB", img.size, pad)
        background.paste(rgba.convert("RGB"), mask=rgba.getchannel("A"))
        img = background
    else:
        img = img.convert("RGB")
    scale = min(1.0, size / img.width, size / img.height)
    width = max(1, round(img.width * scale))
    height = max(1, round(img.height * scale))
    resized = img.resize((width, height), Image.Resampling.LANCZOS)
    canvas = Image.new("RGB", (size, size), pad)
    left, top = (size - width) // 2, (size - height) // 2
    canvas.paste(resized, (left, top))
    array = np.asarray(canvas, dtype=np.float32)
    mean = np.asarray(metadata["normalize_mean"], dtype=np.float32)
    std = np.asarray(metadata["normalize_std"], dtype=np.float32)
    array = (array / 255.0 - mean) / std
    mask = np.ones((size, size), dtype=bool)
    mask[top:top + height, left:left + width] = False
    return np.ascontiguousarray(array.transpose(2, 0, 1)), mask


def select_predictions(scores, vocabulary, threshold, top_k):
    """Return score-ordered names without dropping or renaming ordinary tags."""
    scores = np.asarray(scores)
    names = vocabulary["index_to_tag"]
    if scores.ndim != 1 or len(scores) != len(names):
        raise ValueError("Model output shape does not match vocabulary")
    if not np.isfinite(scores).all() or ((scores < 0) | (scores > 1)).any():
        raise ValueError("Model returned invalid probabilities")
    if not 0 <= float(threshold) <= 1:
        raise ValueError("Threshold must be between zero and one")
    if isinstance(top_k, bool) or int(top_k) != top_k or top_k < 0:
        raise ValueError("top_k must be a nonnegative integer")
    indices = np.flatnonzero(scores >= threshold)
    indices = indices[indices >= 2]
    indices = indices[np.argsort(-scores[indices], kind="stable")]
    if top_k:
        indices = indices[:int(top_k)]
    return {names[str(int(index))]: float(scores[index]) for index in indices}