File size: 8,279 Bytes
d0344ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
#!/usr/bin/env python3
"""
Simple Gradio app for testing an EyeQ QC model.

Example
-------
python app_eyeq.py \
    --checkpoint ./checkpoints/eyeq_vit_base/best.pt

Then open the printed local URL in your browser.
"""

import argparse
from pathlib import Path

import gradio as gr
import numpy as np
import torch
from PIL import Image
from torchvision import transforms
import timm


ID_TO_LABEL = {0: "Good", 1: "Usable", 2: "Reject"}


def build_transform(img_size: int):
    return transforms.Compose([
        transforms.Resize((img_size, img_size)),
        transforms.ToTensor(),
        transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
    ])


def load_model(checkpoint_path: str, device: torch.device):
    ckpt = torch.load(checkpoint_path, map_location="cpu")

    args = ckpt.get("args", {})
    model_name = args.get("model", "vit_base_patch16_224")
    img_size = int(args.get("img_size", 224))

    id_to_label = ckpt.get("id_to_label", ID_TO_LABEL)
    id_to_label = {int(k): v for k, v in id_to_label.items()}

    model = timm.create_model(
        model_name,
        pretrained=False,
        num_classes=len(id_to_label),
    )
    model.load_state_dict(ckpt["model"], strict=True)
    model.to(device)
    model.eval()

    tfm = build_transform(img_size)
    return model, tfm, id_to_label, model_name, img_size


def get_eyeq_class_ids(id_to_label):
    """Return class IDs for Good, Usable, Reject.

    Falls back to the standard EyeQ ordering if the checkpoint does not store
    string labels in the expected form.
    """
    label_to_id = {str(v).lower(): int(k) for k, v in id_to_label.items()}

    good_id = label_to_id.get("good", 0)
    usable_id = label_to_id.get("usable", 1)
    reject_id = label_to_id.get("reject", 2)

    return good_id, usable_id, reject_id


def soft_eyeq_decision(probs, id_to_label, reject_threshold=0.60, reject_margin=0.15):
    """Apply a conservative Reject rule.

    Reject is only returned when:
      1. P(Reject) >= reject_threshold, and
      2. P(Reject) beats the best non-Reject class by reject_margin.

    Otherwise, the prediction is forced to Good vs Usable.
    """
    good_id, usable_id, reject_id = get_eyeq_class_ids(id_to_label)

    prob_good = float(probs[good_id])
    prob_usable = float(probs[usable_id])
    prob_reject = float(probs[reject_id])

    best_non_reject_id = good_id if prob_good >= prob_usable else usable_id
    best_non_reject_prob = max(prob_good, prob_usable)

    if (
        prob_reject >= reject_threshold
        and (prob_reject - best_non_reject_prob) >= reject_margin
    ):
        pred_id = reject_id
        decision = "Soft rule: Reject threshold and margin were both satisfied."
    else:
        pred_id = best_non_reject_id
        decision = "Soft rule: Reject was not confident enough, so prediction was forced to Good/Usable."

    return pred_id, id_to_label[pred_id], decision


def update_margin_slider(reject_threshold, reject_margin):
    """Keep reject_margin within a sensible range for the current threshold."""
    max_margin = min(0.50, float(reject_threshold))
    reject_margin = min(float(reject_margin), max_margin)

    return gr.update(
        maximum=max_margin,
        value=reject_margin,
    )


@torch.no_grad()
def predict_quality(
    image: Image.Image,
    model,
    tfm,
    id_to_label,
    device,
    reject_threshold=0.60,
    reject_margin=0.15,
):
    if image is None:
        return None, {}, "Upload an image to run QC."

    image = image.convert("RGB")
    x = tfm(image).unsqueeze(0).to(device)

    logits = model(x)
    probs = torch.softmax(logits, dim=1)[0].detach().cpu().numpy()

    raw_pred_id = int(np.argmax(probs))
    raw_pred_label = id_to_label[raw_pred_id]

    soft_pred_id, soft_pred_label, decision = soft_eyeq_decision(
        probs=probs,
        id_to_label=id_to_label,
        reject_threshold=reject_threshold,
        reject_margin=reject_margin,
    )

    prob_dict = {
        id_to_label[i]: float(probs[i])
        for i in range(len(probs))
    }

    detail = (
        f"Raw argmax: {raw_pred_label}\n"
        f"Soft decision: {soft_pred_label}\n"
        f"Reject threshold: {reject_threshold:.2f} | Reject margin: {reject_margin:.2f}\n"
        f"{decision}"
    )

    return soft_pred_label, prob_dict, detail


def make_app(checkpoint_path: str):
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model, tfm, id_to_label, model_name, img_size = load_model(checkpoint_path, device)

    def run(image, reject_threshold, reject_margin):
        pred_label, prob_dict, detail = predict_quality(
            image=image,
            model=model,
            tfm=tfm,
            id_to_label=id_to_label,
            device=device,
            reject_threshold=reject_threshold,
            reject_margin=reject_margin,
        )
        return pred_label, prob_dict, detail

    with gr.Blocks(title="EyeQ CFP Quality Control") as demo:
        gr.Markdown("# EyeQ CFP Quality Control")
        gr.Markdown(
            f"Model: `{model_name}`  \n"
            f"Input size: `{img_size} × {img_size}`  \n"
            f"Device: `{device}`  \n"
            f"Checkpoint: `{checkpoint_path}`"
        )

        with gr.Row():
            with gr.Column(scale=1):
                image_input = gr.Image(
                    label="Input CFP",
                    type="pil",
                    height=520,
                )
                with gr.Accordion("Soft Reject rule", open=True):
                    reject_threshold = gr.Slider(
                        minimum=0.40,
                        maximum=0.95,
                        value=0.60,
                        step=0.01,
                        label="Reject threshold",
                        info="Minimum Reject probability required before an image can be called Reject.",
                    )
                    reject_margin = gr.Slider(
                        minimum=0.00,
                        maximum=0.50,
                        value=0.15,
                        step=0.01,
                        label="Reject margin",
                        info="Reject must beat both Good and Usable by at least this much.",
                    )

                run_button = gr.Button("Run QC", variant="primary")

            with gr.Column(scale=1):
                pred_output = gr.Label(label="Predicted quality")
                prob_output = gr.Label(label="Class probabilities", num_top_classes=3)
                decision_output = gr.Textbox(
                    label="Decision details",
                    lines=4,
                    interactive=False,
                )

        run_inputs = [image_input, reject_threshold, reject_margin]
        run_outputs = [pred_output, prob_output, decision_output]

        run_button.click(
            fn=run,
            inputs=run_inputs,
            outputs=run_outputs,
        )

        image_input.change(
            fn=run,
            inputs=run_inputs,
            outputs=run_outputs,
        )

        reject_threshold.change(
            fn=update_margin_slider,
            inputs=[reject_threshold, reject_margin],
            outputs=reject_margin,
        ).then(
            fn=run,
            inputs=run_inputs,
            outputs=run_outputs,
        )

        reject_margin.change(
            fn=run,
            inputs=run_inputs,
            outputs=run_outputs,
        )

    return demo


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--checkpoint", type=str, default="./checkpoints/eyeq_vit_base/eyeq_deploy.pt")
    parser.add_argument("--host", type=str, default="0.0.0.0")
    parser.add_argument("--port", type=int, default=7860)
    parser.add_argument("--share", action="store_true")
    return parser.parse_args()


def main():
    args = parse_args()

    checkpoint_path = Path(args.checkpoint)
    if not checkpoint_path.exists():
        raise FileNotFoundError(f"Checkpoint not found: {checkpoint_path}")

    demo = make_app(str(checkpoint_path))
    demo.launch(
        # server_name=args.host,
        # server_port=args.port,
        # share=args.share,
    )


if __name__ == "__main__":
    main()