duchaba's picture
Update app.py
341d826 verified
import gradio as gr
import fastai
import sys
from fastai.vision.all import load_learner, PILImage
import json # Import the json library
print(f"Current Gradio version: {gr.__version__}: tested: 5.49.1")
print(f"CurrentFastai version: {fastai.__version__}: tested: 2.8.5")
print(f"Current Python sys version: {sys.version}: tested: 3.12.12")
# load learner
fname = './butterfly_learner_1762396100.pkl'
learn = load_learner(fname)
#
print("load learner complete")
# Define the classify_butterfly function
def classify_butterfly(image):
pred, pred_idx, probs = learn.predict(PILImage(image))
# Create a dictionary with the results
results = {
"prediction": str(pred), # Convert prediction to string
"prediction_index": int(pred_idx), # Convert prediction index to int
"probabilities": probs.tolist() # Convert probabilities to a list
}
# Return the results as a JSON string
return json.dumps(results, indent=2)
#
# Gradio
cnn_butterfly = gr.Interface(fn=classify_butterfly,
inputs=gr.Image(type="pil"),
outputs=gr.Json(label="Prediction (JSON)"), # Change output type to Json
title="Butterfly CNN Tester",
description="Upload a butterfly image to get the model’s prediction and class probabilities in JSON format.",
)
#
# lauch it
cnn_butterfly.launch()
#Gradio version: 5.49.1
#Fastai version: 2.8.5
#