# %% | |
#|default_exp app | |
# %% [markdown] | |
# # Bear Classifier App | |
# | |
# This notebook creates uses an exported model `export.pkl` for a bear classifier, to create a python script which can run the model on HuggingFace. | |
# %% | |
#|export | |
from fastai.vision.all import * | |
import gradio as gr | |
# %% [markdown] | |
# Let's take a look at an example picture: | |
# %% | |
#im = PILImage.create('teddybear.jpg') | |
#im = PILImage.create('grizzly.jpg') | |
im = PILImage.create('blackbear.jpg') | |
im.thumbnail((192, 192)) | |
im | |
# %% [markdown] | |
# Let's import the model and create the learner: | |
# %% | |
#|export | |
import pathlib | |
plt = platform.system() | |
if plt == 'Windows': pathlib.WindowsPath = pathlib.PosixPath | |
learn = load_learner('export.pkl') | |
# %% [markdown] | |
# With the learner we can to the predictions (inference): | |
# %% | |
learn.predict(im) | |
# %% [markdown] | |
# The available categories are contained in the vocab: | |
# %% | |
learn.dls.vocab | |
# %% [markdown] | |
# This is the function to classify the images: | |
# %% | |
#|export | |
def classify_image(img): | |
pred,pred_idx,probs = learn.predict(img) | |
return dict(zip(learn.dls.vocab, map(float, probs))) | |
# %% [markdown] | |
# Testing the function: | |
# %% | |
classify_image(im) | |
# %% [markdown] | |
# ## Gradio App | |
# | |
# Now it is time to create the gradio app: | |
# %% | |
# commented, because it produced warnings | |
#image = gr.inputs.Image(shape=(192,192)) | |
#label = gr.outputs.Label() | |
# %% | |
#|export | |
image = gr.components.Image(shape=(192,192)) | |
label = gr.components.Label() | |
examples = ['teddybear.jpg', 'grizzly.jpg', 'blackbear.jpg'] | |
intf = gr.Interface(fn=classify_image, inputs=image, outputs=label, examples=examples) | |
intf.launch(inline=False) | |
# %% | |
intf.close() | |
# %% [markdown] | |
# ## Export | |
# | |
# Finally, we export the code in the cells which are marked with `#|export`: | |
# %% | |
# %% | |
# %% | |