duchaba commited on
Commit
104b180
1 Parent(s): 08c9c30

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +167 -0
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import fastai
3
+ import fastai.vision
4
+ import PIL
5
+ import gradio
6
+ import matplotlib
7
+ import numpy
8
+ import pandas
9
+ from fastai.vision.all import *
10
+ #
11
+ # create class
12
+ class ADA_SKIN(object):
13
+ #
14
+ # initialize the object
15
+ def __init__(self, name="Wallaby",verbose=True,*args, **kwargs):
16
+ super(ADA_SKIN, self).__init__(*args, **kwargs)
17
+ self.author = "Duc Haba"
18
+ self.name = name
19
+ if (verbose):
20
+ self._ph()
21
+ self._pp("Hello from class", str(self.__class__) + " Class: " + str(self.__class__.__name__))
22
+ self._pp("Code name", self.name)
23
+ self._pp("Author is", self.author)
24
+ self._ph()
25
+ #
26
+ self.article = '<div><h3>Citation:</h3><ul><li>'
27
+ self.article += 'Author/Dev: Duc Haba, 2022.</li>'
28
+ self.article += '<li><a target="_blank" href="https://linkedin.com/in/duchaba">https://linkedin.com/in/duchaba</a></li>'
29
+ self.article += '<li>The training dataset the combination of three datasets</li>'
30
+ self.article += '<ol>'
31
+ self.article += '<li>https://www.kaggle.com/datasets/surajghuwalewala/ham1000-segmentation-and-classification</li>'
32
+ self.article += '<li>https://www.kaggle.com/datasets/andrewmvd/isic-2019</li>'
33
+ self.article += '<li>https://www.kaggle.com/datasets/jnegrini/skin-lesions-act-keratosis-and-melanoma</li>'
34
+ self.article += '</ol></ul>'
35
+ self.article += '<h3>Articles:</h3><ul>'
36
+ self.article += '<li><a target="_blank" href="https://www.linkedin.com/pulse/120-dog-breeds-hugging-face-duc-haba/">'
37
+ self.article += '"Skin Cancer Diagnose"</a> on LinkedIn, on <a target="_blank" href='
38
+ self.article += '"https://duchaba.medium.com/120-dog-breeds-on-hugging-face-75288c7952d6">Medium.</a></li>'
39
+ self.article += '</ul>'
40
+ self.article += '<h3>Example Images: (left to right)</h3><ol>'
41
+ self.article += '<li>Bowen Disease (AKIEC)</li>'
42
+ self.article += '<li>Basal Cell Carcinoma</li>'
43
+ self.article += '<li>Benign Keratosis-like Lesions</li>'
44
+ self.article += '<li>Dermatofibroma</li>'
45
+ self.article += '<li>Melanoma</li>'
46
+ self.article += '<li>Melanocytic Nevi</li>'
47
+ self.article += '<li>Squamous Cell Carcinoma</li>'
48
+ self.article += '<li>Vascular Lesions</li>'
49
+ self.article += '<li>Benign</li>'
50
+ self.article += '<li>Benign 2</li></ol>'
51
+ self.article += '<h3>Train Result:</h3><ul>'
52
+ self.article += '<li>Skin Cancer Classificaiton: F1-Score, Precision, and Recall Graph</li>'
53
+ self.article += '<li><img src="file/ada_f1_skin.png" alt="F1-Score, Precision, and Recall Graph" width="640"</li>'
54
+ self.article += '<li>Skin Cancer Malignant or Benign: F1-Score, Precision, and Recall Graph</li>'
55
+ self.article += '<li><img src="file/ada_f1_skin_be.png" alt="F1-Score, Precision, and Recall Graph" width="640"</li>'
56
+ self.article += '</ul>'
57
+ self.article += '<h3>Dev Stack:</h3><ul>'
58
+ self.article += '<li>Jupyter Notebook, Python, Pandas, Matplotlib, Sklearn</li>'
59
+ self.article += '<li>Fast.ai, PyTorch</li>'
60
+ self.article += '</ul>'
61
+ self.article += '<h3>Licenses:</h3><ul>'
62
+ self.article += '<li>GNU GPL 3.0, https://www.gnu.org/licenses/gpl-3.0.txt</li>'
63
+ self.article += '</ul></div>'
64
+ self.examples = ['akiec1.jpg','bcc1.jpg','bkl1.jpg','df1.jpg','mel1.jpg',
65
+ 'nevi1.jpg','scc1.jpg','vl1.jpg','benign1.jpg','benign3.jpg']
66
+ self.title = "Skin Cancer Diagnose"
67
+ return
68
+ #
69
+ # pretty print output name-value line
70
+ def _pp(self, a, b):
71
+ print("%34s : %s" % (str(a), str(b)))
72
+ return
73
+ #
74
+ # pretty print the header or footer lines
75
+ def _ph(self):
76
+ print("-" * 34, ":", "-" * 34)
77
+ return
78
+ #
79
+ def _predict_image(self,img,cat):
80
+ pred,idx,probs = learn.predict(img)
81
+ return dict(zip(cat, map(float,probs)))
82
+ #
83
+ def _predict_image2(self,img,cat):
84
+ pred,idx,probs = learn2.predict(img)
85
+ return dict(zip(cat, map(float,probs)))
86
+ #
87
+ def _draw_pred(self,df_pred, df2):
88
+ canvas, pic = matplotlib.pyplot.subplots(1,2, figsize=(12,6))
89
+ ti = df_pred["breeds"].head(3).values
90
+ ti2 = df2["breeds"].head(2).values
91
+ # special case
92
+ #if (matplotlib.__version__) >= "3.5.2":
93
+ try:
94
+ df_pred["pred"].head(3).plot(ax=pic[0],kind="pie",
95
+ cmap="Set2",labels=ti, explode=(0.02,0,0),
96
+ wedgeprops=dict(width=.4),
97
+ normalize=False)
98
+ df2["pred"].head(2).plot(ax=pic[1],kind="pie",
99
+ colors=["cornflowerblue","darkorange"],labels=ti2, explode=(0.02,0),
100
+ wedgeprops=dict(width=.4),
101
+ normalize=False)
102
+ except:
103
+ df_pred["pred"].head(3).plot(ax=pic[0],kind="pie",
104
+ cmap="Set2",labels=ti, explode=(0.02,0,0),
105
+ wedgeprops=dict(width=.4))
106
+ df2["pred"].head(2).plot(ax=pic[1],kind="pie",
107
+ colors=["cornflowerblue","darkorange"],labels=ti2, explode=(0.02,0),
108
+ wedgeprops=dict(width=.4))
109
+ t = str(ti[0]) + ": " + str(numpy.round(df_pred.head(1).pred.values[0]*100, 2)) + "% Certainty"
110
+ pic[0].set_title(t,fontsize=14.0, fontweight="bold")
111
+ pic[0].axis('off')
112
+ pic[0].legend(ti, loc="lower right",title="Skin Cancers: Top 3")
113
+ #
114
+ k0 = numpy.round(df2.head(1).pred.values[0]*100, 2)
115
+ k1 = numpy.round(df2.tail(1).pred.values[0]*100, 2)
116
+ if (k0 > k1):
117
+ t2 = str(ti2[0]) + ": " + str(k0) + "% Certainty"
118
+ else:
119
+ t2 = str(ti2[1]) + ": " + str(k1) + "% Certainty"
120
+ pic[1].set_title(t2,fontsize=14.0, fontweight="bold")
121
+ pic[1].axis('off')
122
+ pic[1].legend(ti2, loc="lower right",title="Skin Cancers:")
123
+ #
124
+ # # draw circle
125
+ # centre_circle = matplotlib.pyplot.Circle((0, 0), 0.6, fc='white')
126
+ # p = matplotlib.pyplot.gcf()
127
+ # # Adding Circle in Pie chart
128
+ # p.gca().add_artist(centre_circle)
129
+ #
130
+ #p=plt.gcf()
131
+ #p.gca().add_artist(my_circle)
132
+ #
133
+ canvas.tight_layout()
134
+ return canvas
135
+ #
136
+ def predict_donut(self,img):
137
+ d = self._predict_image(img,self.categories)
138
+ df = pandas.DataFrame(d, index=[0])
139
+ df = df.transpose().reset_index()
140
+ df.columns = ["breeds", "pred"]
141
+ df.sort_values("pred", inplace=True,ascending=False, ignore_index=True)
142
+ #
143
+ d2 = self._predict_image2(img,self.categories2)
144
+ df2 = pandas.DataFrame(d2, index=[0])
145
+ df2 = df2.transpose().reset_index()
146
+ df2.columns = ["breeds", "pred"]
147
+ #df2.sort_values("pred", inplace=True,ascending=False, ignore_index=True)
148
+ #
149
+ canvas = self._draw_pred(df,df2)
150
+ return canvas
151
+ #
152
+ maxi = ADA_SKIN(verbose=False)
153
+ #
154
+ learn = fastai.learner.load_learner('ada_learn_skin_norm2000.pkl')
155
+ learn2 = fastai.learner.load_learner('ada_learn_malben.pkl')
156
+ maxi.categories = learn.dls.vocab
157
+ maxi.categories2 = learn2.dls.vocab
158
+ hf_image = gradio.inputs.Image(shape=(192, 192))
159
+ hf_label = gradio.outputs.Label()
160
+ intf = gradio.Interface(fn=maxi.predict_donut,
161
+ inputs=hf_image,
162
+ outputs=["plot"],
163
+ examples=maxi.examples,
164
+ title=maxi.title,
165
+ live=True,
166
+ article=maxi.article)
167
+ intf.launch(inline=False,share=True)