File size: 2,137 Bytes
9351b33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
085d6fc
 
9351b33
 
 
 
 
 
 
 
 
fbad270
9351b33
 
 
 
 
 
 
 
 
 
 
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
"""Gradio web app for the Flowers102 classifier.

Usage:
    python app.py
"""
import hashlib
from pathlib import Path

import gradio as gr
from PIL import Image

from predict import load_model, predict_image

model, class_names = load_model()
example_paths = sorted((Path(__file__).resolve().parent / "examples").glob("*.jpg"))
example_images = [str(path) for path in example_paths]


def pixel_hash(image):
    # Fingerprint the decoded pixels, which match however an example photo reaches the app.
    return hashlib.md5(image.convert("RGB").tobytes()).hexdigest()


# Each example file is named after its true class, e.g. bird_of_paradise.jpg
example_classes = {
    pixel_hash(Image.open(path)): path.stem.replace("_", " ") for path in example_paths
}


def classify_flower(image):
    # Return the top 5 flower categories, the actual class for example photos, and the timed prediction.
    if image is None:
        raise gr.Error("Upload a flower photo first.")
    predictions, seconds = predict_image(model, class_names, image)
    actual_class = example_classes.get(pixel_hash(image), "")
    return predictions, actual_class, f"{seconds:.4f} seconds"


demo = gr.Interface(
    fn=classify_flower,
    # Fixed panel height in pixels so photo dimensions don't resize it; vh grows with the Spaces iframe
    inputs=gr.Image(type="pil", label="Flower photo", height=360),
    outputs=[
        gr.Label(num_top_classes=5, label="Top 5 predictions"),
        # Blank for uploaded photos, which have no known class
        gr.Textbox(label="Actual class"),
        gr.Textbox(label="Prediction time")
    ],
    examples=example_images,
    # One unseen test photo per class, 34 per page across 3 pages
    examples_per_page=34,
    preload_example=False,
    title="FloraFind",
    description=(
        "Upload a flower photo to predict which of the 102 Oxford Flowers102 categories it shows. "
        "The model is an EfficientNet-B0 fine-tuned in PyTorch; the timer covers preprocessing, "
        "the forward pass, and softmax for one image."
    ),
    flagging_mode="never"
)

if __name__ == "__main__":
    demo.launch()