jeysshon commited on
Commit
f4aa6fb
1 Parent(s): acf438d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -116
app.py CHANGED
@@ -1,133 +1,138 @@
1
  import fastai
2
- import fastai.vision
3
  import PIL
4
- import gradio
5
- import matplotlib
6
- import numpy
7
- import pandas
8
  from fastai.vision.all import *
9
 
10
  # Crear la clase
11
  class ADA_SKIN(object):
12
 
13
- # Inicializar el objeto
14
- def __init__(self, name="Wallaby", verbose=True, *args, **kwargs):
15
- super(ADA_SKIN, self).__init__(*args, **kwargs)
16
- self.author = "Jey"
17
- self.name = name
18
- if verbose:
19
- self._ph()
20
- self._pp("Hola desde la clase", str(self.__class__) + " Clase: " + str(self.__class__.__name__))
21
- self._pp("Nombre del código", self.name)
22
- self._pp("Autor", self.author)
23
- self._ph()
24
-
25
- self.article = '<h3>Predice las siguientes patologias en piel</h3><ol>'
26
- self.article += '<li>Enfermedad de Bowen (AKIEC)</li>'
27
- self.article += '<li>Carcinoma de células basales</li>'
28
- self.article += '<li>Lesiones benignas similares a queratosis</li>'
29
- self.article += '<li>Dermatofibroma</li>'
30
- self.article += '<li>Melanoma</li>'
31
- self.article += '<li>Lunares melanocíticos</li>'
32
- self.article += '<li>Carcinoma de células escamosas</li>'
33
- self.article += '<li>Lesiones vasculares</li>'
34
- self.article += '<li>Benigno</li>'
35
- self.article += '<li></li></ol>'
36
- self.article += '<h3> Prueba Jey(2023)</h3><ul>'
37
- self.examples = ['akiec1.jpg','bcc1.jpg','bkl1.jpg','df1.jpg','mel1.jpg',
38
- 'nevi1.jpg','scc1.jpg','vl1.jpg','benign1.jpg','benign3.jpg']
39
- self.title = "Predicción Cáncer de Piel prueba "
40
- return
41
-
42
- # Imprimir de manera legible el nombre y valor de una línea
43
- def _pp(self, a, b):
44
- print("%34s : %s" % (str(a), str(b)))
45
- return
46
-
47
- # Imprimir la línea de encabezado o pie de página
48
- def _ph(self):
49
- print("-" * 34, ":", "-" * 34)
50
- return
51
-
52
- def _predict_image(self, img, cat):
53
- pred, idx, probs = learn.predict(img)
54
- return dict(zip(cat, map(float, probs)))
55
-
56
- def _predict_image2(self, img, cat):
57
- pred, idx, probs = learn2.predict(img)
58
- return dict(zip(cat, map(float, probs)))
59
-
60
- def _draw_pred(self, df_pred, df2):
61
- canvas, pic = matplotlib.pyplot.subplots(1, 2, figsize=(12, 6))
62
- ti = df_pred["vocab"].head(3).values
63
- ti2 = df2["vocab"].head(2).values
64
-
65
- try:
66
- df_pred["pred"].head(3).plot(ax=pic[0], kind="pie",
67
- cmap="Set2", labels=ti, explode=(0.02, 0, 0),
68
- wedgeprops=dict(width=.4),
69
- normalize=False)
70
- df2["pred"].head(2).plot(ax=pic[1], kind="pie",
71
- colors=["cornflowerblue", "darkorange"], labels=ti2, explode=(0.02, 0),
72
- wedgeprops=dict(width=.4),
73
- normalize=False)
74
- except:
75
- df_pred["pred"].head(3).plot(ax=pic[0], kind="pie",
76
- cmap="Set2", labels=ti, explode=(0.02, 0, 0),
77
- wedgeprops=dict(width=.4))
78
- df2["pred"].head(2).plot(ax=pic[1], kind="pie",
79
- colors=["cornflowerblue", "darkorange"], labels=ti2, explode=(0.02, 0),
80
- wedgeprops=dict(width=.4))
81
-
82
- t = str(ti[0]) + ": " + str(numpy.round(df_pred.head(1).pred.values[0] * 100, 2)) + "% de predicción"
83
- pic[0].set_title(t, fontsize=14.0, fontweight="bold")
84
- pic[0].axis('off')
85
- pic[0].legend(ti, loc="lower right", title="Cáncer de Piel: ")
86
-
87
- k0 = numpy.round(df2.head(1).pred.values[0] * 100, 2)
88
- k1 = numpy.round(df2.tail(1).pred.values[0] * 100, 2)
89
- if k0 > k1:
90
- t2 = str(ti2[0]) + ": " + str(k0) + "% de predicción"
91
- else:
92
- t2 = str(ti2[1]) + ": " + str(k1) + "% de predicción"
93
- pic[1].set_title(t2, fontsize=14.0, fontweight="bold")
94
- pic[1].axis('off')
95
- pic[1].legend(ti2, loc="lower right", title="Prediccíon Cáncer de Piel:")
96
-
97
- canvas.tight_layout()
98
- return canvas
99
-
100
- def predict_donut(self, img):
101
- d = self._predict_image(img, self.categories)
102
- df = pandas.DataFrame(d, index=[0])
103
- df = df.transpose().reset_index()
104
- df.columns = ["vocab", "pred"]
105
- df.sort_values("pred", inplace=True, ascending=False, ignore_index=True)
106
-
107
- d2 = self._predict_image2(img, self.categories2)
108
- df2 = pandas.DataFrame(d2, index=[0])
109
- df2 = df2.transpose().reset_index()
110
- df2.columns = ["vocab", "pred"]
111
-
112
- canvas = self._draw_pred(df, df2)
113
- return canvas
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  maxi = ADA_SKIN(verbose=False)
116
 
 
117
  learn = fastai.learner.load_learner('ada_learn_skin_norm2000.pkl')
118
  learn2 = fastai.learner.load_learner('ada_learn_malben.pkl')
119
  maxi.categories = learn.dls.vocab
120
  maxi.categories2 = learn2.dls.vocab
121
- hf_image = gradio.inputs.Image(shape=(192, 192))
122
- hf_label = gradio.outputs.Label()
123
 
124
- intf = gradio.Interface(fn=maxi.predict_donut,
125
- inputs=hf_image,
126
- outputs=["plot"],
127
- examples=maxi.examples,
128
- title=maxi.title,
129
- live=True,
130
- article=maxi.article)
 
 
 
 
 
 
 
131
 
132
- intf.launch(inline=False, share=True)
133
 
 
1
  import fastai
 
2
  import PIL
3
+ import gradio as gr
4
+ import matplotlib.pyplot as plt
5
+ import numpy as np
6
+ import pandas as pd
7
  from fastai.vision.all import *
8
 
9
  # Crear la clase
10
  class ADA_SKIN(object):
11
 
12
+ # Inicializar el objeto
13
+ def __init__(self, name="Wallaby", verbose=True, *args, **kwargs):
14
+ super(ADA_SKIN, self).__init__(*args, **kwargs)
15
+ self.author = "Jey"
16
+ self.name = name
17
+ if verbose:
18
+ self._ph()
19
+ self._pp("Hola desde la clase", str(self.__class__) + " Clase: " + str(self.__class__.__name__))
20
+ self._pp("Nombre del código", self.name)
21
+ self._pp("Autor", self.author)
22
+ self._ph()
23
+
24
+ self.article = '<h3>Predice las siguientes patologias en piel</h3><ol>'
25
+ self.article += '<li>Enfermedad de Bowen (AKIEC)</li>'
26
+ self.article += '<li>Carcinoma de células basales</li>'
27
+ self.article += '<li>Lesiones benignas similares a queratosis</li>'
28
+ self.article += '<li>Dermatofibroma</li>'
29
+ self.article += '<li>Melanoma</li>'
30
+ self.article += '<li>Lunares melanocíticos</li>'
31
+ self.article += '<li>Carcinoma de células escamosas</li>'
32
+ self.article += '<li>Lesiones vasculares</li>'
33
+ self.article += '<li>Benigno</li>'
34
+ self.article += '<li></li></ol>'
35
+ self.article += '<h3> Prueba Jey(2023)</h3><ul>'
36
+ self.examples = ['akiec1.jpg','bcc1.jpg','bkl1.jpg','df1.jpg','mel1.jpg',
37
+ 'nevi1.jpg','scc1.jpg','vl1.jpg','benign1.jpg','benign3.jpg']
38
+ self.title = "Predicción Cáncer de Piel prueba "
39
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ # Imprimir de manera legible el nombre y valor de una línea
42
+ def _pp(self, a, b):
43
+ print("%34s : %s" % (str(a), str(b)))
44
+ return
45
+
46
+ # Imprimir la línea de encabezado o pie de página
47
+ def _ph(self):
48
+ print("-" * 34, ":", "-" * 34)
49
+ return
50
+
51
+ def _predict_image(self, img, cat):
52
+ pred, idx, probs = learn.predict(img)
53
+ return dict(zip(cat, map(float, probs)))
54
+
55
+ def _predict_image2(self, img, cat):
56
+ pred, idx, probs = learn2.predict(img)
57
+ return dict(zip(cat, map(float, probs)))
58
+
59
+ def _draw_pred(self, df_pred, df2):
60
+ fig, pic = plt.subplots(1, 2, figsize=(12, 6))
61
+ ti = df_pred["vocab"].head(3).values
62
+ ti2 = df2["vocab"].head(2).values
63
+
64
+ try:
65
+ df_pred["pred"].head(3).plot(ax=pic[0], kind="pie",
66
+ cmap="Set2", labels=ti, explode=(0.02, 0, 0),
67
+ wedgeprops=dict(width=.4),
68
+ normalize=False)
69
+ df2["pred"].head(2).plot(ax=pic[1], kind="pie",
70
+ colors=["cornflowerblue", "darkorange"], labels=ti2, explode=(0.02, 0),
71
+ wedgeprops=dict(width=.4),
72
+ normalize=False)
73
+ except:
74
+ df_pred["pred"].head(3).plot(ax=pic[0], kind="pie",
75
+ cmap="Set2", labels=ti, explode=(0.02, 0, 0),
76
+ wedgeprops=dict(width=.4))
77
+ df2["pred"].head(2).plot(ax=pic[1], kind="pie",
78
+ colors=["cornflowerblue", "darkorange"], labels=ti2, explode=(0.02, 0),
79
+ wedgeprops=dict(width=.4))
80
+
81
+ t = str(ti[0]) + ": " + str(np.round(df_pred.head(1).pred.values[0] * 100, 2)) + "% de predicción"
82
+ pic[0].set_title(t, fontsize=14.0, fontweight="bold")
83
+ pic[0].axis('off')
84
+ pic[0].legend(ti, loc="lower right", title="Cáncer de Piel: ")
85
+
86
+ k0 = np.round(df2.head(1).pred.values[0] * 100, 2)
87
+ k1 = np.round(df2.tail(1).pred.values[0] * 100, 2)
88
+ if k0 > k1:
89
+ t2 = str(ti2[0]) + ": " + str(k0) + "% de predicción"
90
+ else:
91
+ t2 = str(ti2[1]) + ": " + str(k1) + "% de predicción"
92
+ pic[1].set_title(t2, fontsize=14.0, fontweight="bold")
93
+ pic[1].axis('off')
94
+ pic[1].legend(ti2, loc="lower right", title="Predicción Cáncer de Piel:")
95
+
96
+ fig.tight_layout()
97
+ return fig
98
+
99
+ def predict_donut(self, img):
100
+ d = self._predict_image(img, self.categories)
101
+ df = pd.DataFrame(d, index=[0])
102
+ df = df.transpose().reset_index()
103
+ df.columns = ["vocab", "pred"]
104
+ df.sort_values("pred", inplace=True, ascending=False, ignore_index=True)
105
+
106
+ d2 = self._predict_image2(img, self.categories2)
107
+ df2 = pd.DataFrame(d2, index=[0])
108
+ df2 = df2.transpose().reset_index()
109
+ df2.columns = ["vocab", "pred"]
110
+
111
+ fig = self._draw_pred(df, df2)
112
+ return fig
113
+
114
+ # Inicializar el objeto ADA_SKIN
115
  maxi = ADA_SKIN(verbose=False)
116
 
117
+ # Cargar modelos
118
  learn = fastai.learner.load_learner('ada_learn_skin_norm2000.pkl')
119
  learn2 = fastai.learner.load_learner('ada_learn_malben.pkl')
120
  maxi.categories = learn.dls.vocab
121
  maxi.categories2 = learn2.dls.vocab
 
 
122
 
123
+ # Crear la interfaz de Gradio
124
+ hf_image = gr.inputs.Image(type='pil', shape=(192, 192))
125
+ hf_plot = gr.outputs.Plot()
126
+
127
+ intf = gr.Interface(fn=maxi.predict_donut,
128
+ inputs=hf_image,
129
+ outputs=hf_plot,
130
+ examples=maxi.examples,
131
+ title=maxi.title,
132
+ live=True,
133
+ article=maxi.article)
134
+
135
+ # Lanzar la interfaz
136
+ intf.launch(sh
137
 
 
138