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 = '
Warning:
Do NOT use this for any medical diagnosis.
'
self.article += 'I am not a dermatologist, and NO dermatologist has endorsed it. '
self.article += 'This DL model is for my independent research.
Please refer to the GPL 3.0 for usage and license.'
self.article += '
Citation:
- '
self.article += 'Author/Dev: Duc Haba, 2022.
'
self.article += '- https://linkedin.com/in/duchaba
'
self.article += '- The training dataset are from the International Skin Imaging Collaboration (ISIC)
'
self.article += '- The Skin Cancer Identification are from 3 seperate datasets.
'
self.article += ''
self.article += '- https://www.kaggle.com/datasets/surajghuwalewala/ham1000-segmentation-and-classification
'
self.article += '- https://www.kaggle.com/datasets/andrewmvd/isic-2019
'
self.article += '- https://www.kaggle.com/datasets/jnegrini/skin-lesions-act-keratosis-and-melanoma
'
self.article += '- '
self.article += 'The Malignant versus Benign dataset
'
self.article += '- https://www.kaggle.com/datasets/fanconic/skin-cancer-malignant-vs-benign
'
self.article += '
'
self.article += 'Articles:
'
self.article += 'Example Images: (left to right)
'
self.article += '- Bowen Disease (AKIEC)
'
self.article += '- Basal Cell Carcinoma
'
self.article += '- Benign Keratosis-like Lesions
'
self.article += '- Dermatofibroma
'
self.article += '- Melanoma
'
self.article += '- Melanocytic Nevi
'
self.article += '- Squamous Cell Carcinoma
'
self.article += '- Vascular Lesions
'
self.article += '- Benign
'
self.article += '- Benign 2
'
self.article += 'Train Result:
'
self.article += '- Skin Cancer Classificaiton: F1-Score, Precision, and Recall Graph
'
self.article += '- '
self.article += '
- Skin Cancer Malignant or Benign: F1-Score, Precision, and Recall Graph
'
self.article += '- '
self.article += '
'
self.article += 'Dev Stack:
'
self.article += '- Jupyter Notebook, Python, Pandas, Matplotlib, Sklearn
'
self.article += '- Fast.ai, PyTorch
'
self.article += '
'
self.article += 'Licenses:
'
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["vocab"].head(3).values
ti2 = df2["vocab"].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 = ["vocab", "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 = ["vocab", "pred"]
#
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)