"""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()