Spaces:
Runtime error
Runtime error
File size: 6,892 Bytes
104b180 |
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
import fastai
import fastai.vision
import PIL
import gradio
import matplotlib
import numpy
import pandas
from fastai.vision.all import *
#
# create class
class ADA_SKIN(object):
#
# initialize the object
def __init__(self, name="Wallaby",verbose=True,*args, **kwargs):
super(ADA_SKIN, 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 the combination of three datasets</li>'
self.article += '<ol>'
self.article += '<li>https://www.kaggle.com/datasets/surajghuwalewala/ham1000-segmentation-and-classification</li>'
self.article += '<li>https://www.kaggle.com/datasets/andrewmvd/isic-2019</li>'
self.article += '<li>https://www.kaggle.com/datasets/jnegrini/skin-lesions-act-keratosis-and-melanoma</li>'
self.article += '</ol></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/">'
self.article += '"Skin Cancer Diagnose"</a> on LinkedIn, on <a target="_blank" href='
self.article += '"https://duchaba.medium.com/120-dog-breeds-on-hugging-face-75288c7952d6">Medium.</a></li>'
self.article += '</ul>'
self.article += '<h3>Example Images: (left to right)</h3><ol>'
self.article += '<li>Bowen Disease (AKIEC)</li>'
self.article += '<li>Basal Cell Carcinoma</li>'
self.article += '<li>Benign Keratosis-like Lesions</li>'
self.article += '<li>Dermatofibroma</li>'
self.article += '<li>Melanoma</li>'
self.article += '<li>Melanocytic Nevi</li>'
self.article += '<li>Squamous Cell Carcinoma</li>'
self.article += '<li>Vascular Lesions</li>'
self.article += '<li>Benign</li>'
self.article += '<li>Benign 2</li></ol>'
self.article += '<h3>Train Result:</h3><ul>'
self.article += '<li>Skin Cancer Classificaiton: F1-Score, Precision, and Recall Graph</li>'
self.article += '<li><img src="file/ada_f1_skin.png" alt="F1-Score, Precision, and Recall Graph" width="640"</li>'
self.article += '<li>Skin Cancer Malignant or Benign: F1-Score, Precision, and Recall Graph</li>'
self.article += '<li><img src="file/ada_f1_skin_be.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 = ['akiec1.jpg','bcc1.jpg','bkl1.jpg','df1.jpg','mel1.jpg',
'nevi1.jpg','scc1.jpg','vl1.jpg','benign1.jpg','benign3.jpg']
self.title = "Skin Cancer Diagnose"
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 _predict_image2(self,img,cat):
pred,idx,probs = learn2.predict(img)
return dict(zip(cat, map(float,probs)))
#
def _draw_pred(self,df_pred, df2):
canvas, pic = matplotlib.pyplot.subplots(1,2, figsize=(12,6))
ti = df_pred["breeds"].head(3).values
ti2 = df2["breeds"].head(2).values
# special case
#if (matplotlib.__version__) >= "3.5.2":
try:
df_pred["pred"].head(3).plot(ax=pic[0],kind="pie",
cmap="Set2",labels=ti, explode=(0.02,0,0),
wedgeprops=dict(width=.4),
normalize=False)
df2["pred"].head(2).plot(ax=pic[1],kind="pie",
colors=["cornflowerblue","darkorange"],labels=ti2, explode=(0.02,0),
wedgeprops=dict(width=.4),
normalize=False)
except:
df_pred["pred"].head(3).plot(ax=pic[0],kind="pie",
cmap="Set2",labels=ti, explode=(0.02,0,0),
wedgeprops=dict(width=.4))
df2["pred"].head(2).plot(ax=pic[1],kind="pie",
colors=["cornflowerblue","darkorange"],labels=ti2, explode=(0.02,0),
wedgeprops=dict(width=.4))
t = str(ti[0]) + ": " + str(numpy.round(df_pred.head(1).pred.values[0]*100, 2)) + "% Certainty"
pic[0].set_title(t,fontsize=14.0, fontweight="bold")
pic[0].axis('off')
pic[0].legend(ti, loc="lower right",title="Skin Cancers: Top 3")
#
k0 = numpy.round(df2.head(1).pred.values[0]*100, 2)
k1 = numpy.round(df2.tail(1).pred.values[0]*100, 2)
if (k0 > k1):
t2 = str(ti2[0]) + ": " + str(k0) + "% Certainty"
else:
t2 = str(ti2[1]) + ": " + str(k1) + "% Certainty"
pic[1].set_title(t2,fontsize=14.0, fontweight="bold")
pic[1].axis('off')
pic[1].legend(ti2, loc="lower right",title="Skin Cancers:")
#
# # draw circle
# centre_circle = matplotlib.pyplot.Circle((0, 0), 0.6, fc='white')
# p = matplotlib.pyplot.gcf()
# # Adding Circle in Pie chart
# p.gca().add_artist(centre_circle)
#
#p=plt.gcf()
#p.gca().add_artist(my_circle)
#
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)
#
d2 = self._predict_image2(img,self.categories2)
df2 = pandas.DataFrame(d2, index=[0])
df2 = df2.transpose().reset_index()
df2.columns = ["breeds", "pred"]
#df2.sort_values("pred", inplace=True,ascending=False, ignore_index=True)
#
canvas = self._draw_pred(df,df2)
return canvas
#
maxi = ADA_SKIN(verbose=False)
#
learn = fastai.learner.load_learner('ada_learn_skin_norm2000.pkl')
learn2 = fastai.learner.load_learner('ada_learn_malben.pkl')
maxi.categories = learn.dls.vocab
maxi.categories2 = learn2.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) |