Spaces:
Runtime error
Runtime error
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>Warning:</h3>Do NOT use this for any medical diagnosis.<br>' | |
self.article += 'I am not a dermatologist, and NO dermatologist has endorsed it. ' | |
self.article += 'This DL model is for my independent research. <br>Please refer to the GPL 3.0 for usage and license.' | |
self.article += '<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 are from the International Skin Imaging Collaboration (ISIC)</li>' | |
self.article += '<li>The Skin Cancer Identification are from 3 seperate 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 += '<ul><li>' | |
self.article += 'The Malignant versus Benign dataset</li>' | |
self.article += '<ol><li>https://www.kaggle.com/datasets/fanconic/skin-cancer-malignant-vs-benign</li>' | |
self.article += '</ol></ul>' | |
self.article += '<h3>Articles:</h3><ul>' | |
self.article += '<li><a target="_blank" href="https://www.linkedin.com/pulse/skin-cancer-diagnose-using-deep-learning-duc-haba/">' | |
self.article += '"Skin Cancer Diagnose"</a> on LinkedIn, on <a target="_blank" href=' | |
self.article += '"https://www.linkedin.com/pulse/skin-cancer-diagnose-using-deep-learning-duc-haba/">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><a target="_blank" href="https://www.gnu.org/licenses/gpl-3.0.txt">GNU GPL 3.0</a></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["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) |