120dog_breeds / app.py
duchaba's picture
update to dog1a
70d787e
#
import fastai
import fastai.vision
import PIL
import gradio
import matplotlib
import numpy
import pandas
from fastai.vision.all import *
#
# create class
class ADA_DOGS(object):
#
# initialize the object
def __init__(self, name="Wallaby",verbose=True,*args, **kwargs):
super(ADA_DOGS, self).__init__(*args, **kwargs)
self.author = "Duc Haba"
self.name = name
if (verbose):
self._ph()
self._pp("Hello from class", str(self.__class__) + " Class: " + str(self.__class__.__name__))
self._pp("Code name", self.name)
self._pp("Author is", self.author)
self._ph()
#
self.article = '<div><h3>Citation:</h3><ul><li>'
self.article += 'Author/Dev: Duc Haba, 2022.</li>'
self.article += '<li><a target="_blank" href="https://linkedin.com/in/duchaba">https://linkedin.com/in/duchaba</a></li>'
self.article += '<li>The training dataset is from the Data Scientist at Department of Health '
self.article += 'and Social Care London, England, United Kingdom.</li>'
self.article += '<li>https://www.kaggle.com/datasets/amandam1/120-dog-breeds-breed-classification</li>'
self.article += '</ul>'
self.article += '<h3>Articles:</h3><ul>'
self.article += '<li><a target="_blank" href="https://www.linkedin.com/pulse/120-dog-breeds-hugging-face-duc-haba/">"120 Dog Breeds on Hugging Face"</a> on LinkedIn, '
self.article += 'on <a target="_blank" href="https://duchaba.medium.com/120-dog-breeds-on-hugging-face-75288c7952d6">Medium.</a></li>'
self.article += '</ul>'
self.article += '<h3>Train Result:</h3><ul>'
self.article += '<li>F1-Score, Precision, and Recall -- Take the output from method sklearn.metrics.classification_report(), import to Pandas Data Fame, sorted, and graph it.</li>'
self.article += '<li><img src="file/ada_f1.png" alt="F1-Score, Precision, and Recall Graph" width="640"</li>'
self.article += '</ul>'
self.article += '<h3>Dev Stack:</h3><ul>'
self.article += '<li>Jupyter Notebook, Python, Pandas, Matplotlib, Sklearn</li>'
self.article += '<li>Fast.ai, PyTorch</li>'
self.article += '</ul>'
self.article += '<h3>Licenses:</h3><ul>'
self.article += '<li>GNU GPL 3.0, https://www.gnu.org/licenses/gpl-3.0.txt</li>'
self.article += '</ul></div>'
self.examples = ['dog1a.jpg','dog2.jpg','dog3.jpg','dog4.jpg','dog5.png','dog6.jpg', 'dog7.jpg','duc.jpg']
self.title = "120 Dog Breeds Prediction"
return
#
# pretty print output name-value line
def _pp(self, a, b):
print("%34s : %s" % (str(a), str(b)))
return
#
# pretty print the header or footer lines
def _ph(self):
print("-" * 34, ":", "-" * 34)
return
#
def _predict_image(self,img,cat):
pred,idx,probs = learn.predict(img)
return dict(zip(cat, map(float,probs)))
#
def _draw_pred(self,df_pred):
canvas, pic = matplotlib.pyplot.subplots(1,1, figsize=(6,6))
ti = df_pred["breeds"].head(5).values
# special case
#if (matplotlib.__version__) >= "3.5.2":
try:
df_pred["pred"].head(5).plot(ax=pic,kind="pie",figsize=(6,6),
cmap="Set2",labels=ti, explode=(0.02,0,0,0,0.),
normalize=False)
except:
df_pred["pred"].head(5).plot(ax=pic,kind="pie",figsize=(6,6),
cmap="Set2",labels=ti, explode=(0.02,0,0,0,0.))
t = str(ti[0]) + ": " + str(numpy.round(df_pred.head(1).pred.values[0]*100, 2)) + "% Certainty"
pic.set_title(t,fontsize=14.0, fontweight="bold")
pic.axis('off')
#
# draw circle
centre_circle = matplotlib.pyplot.Circle((0, 0), 0.6, fc='white')
canvas = matplotlib.pyplot.gcf()
# Adding Circle in Pie chart
canvas.gca().add_artist(centre_circle)
#
canvas.legend(ti, loc="lower right",title="120 Dog Breeds: Top 5")
#
canvas.tight_layout()
return canvas
#
def predict_donut(self,img):
d = self._predict_image(img,self.categories)
df = pandas.DataFrame(d, index=[0])
df = df.transpose().reset_index()
df.columns = ["breeds", "pred"]
df.sort_values("pred", inplace=True,ascending=False, ignore_index=True)
canvas = self._draw_pred(df)
return canvas
#
maxi = ADA_DOGS(verbose=False)
#
learn = fastai.learner.load_learner('ada.pkl')
maxi.categories = learn.dls.vocab
hf_image = gradio.inputs.Image(shape=(192, 192))
hf_label = gradio.outputs.Label()
intf = gradio.Interface(fn=maxi.predict_donut,
inputs=hf_image,
outputs=["plot"],
examples=maxi.examples,
title=maxi.title,
live=True,
article=maxi.article)
intf.launch(inline=False,share=True)