niplinig commited on
Commit
e96bea6
·
verified ·
1 Parent(s): b5df98b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -34
app.py CHANGED
@@ -1,6 +1,7 @@
1
- import gradio as gr
2
  import numpy as np
3
  import pandas as pd
 
4
  from pickle import load
5
  from datetime import date
6
  from radiomics import featureextractor
@@ -9,17 +10,6 @@ extractor3D = featureextractor.RadiomicsFeatureExtractor("3DParams.yaml")
9
 
10
  with open("model.pickle", "rb") as file:
11
  loaded_model = load(file)
12
-
13
- class TextStream:
14
- def __init__(self):
15
- self.data : list = []
16
-
17
- def write(self, s):
18
- if s.strip():
19
- self.data.append(s.strip())
20
-
21
- def flush(self):
22
- pass
23
 
24
  def image_classifier(image, segment):
25
  features3D = extractor3D.execute(imageFilepath=image, maskFilepath=segment)
@@ -31,9 +21,9 @@ def image_classifier(image, segment):
31
  dict[key] = [value]
32
  dataframe = pd.DataFrame(dict).select_dtypes(exclude=["object"]).to_numpy()
33
  prediction = loaded_model.predict_proba(dataframe).tolist()[0]
34
- return {"Grade 1": prediction[0], "Grade 2": prediction[1]}
35
 
36
- def logging(image, label_output):
37
  grade1 = list(label_output.values())[0]
38
  grade2 = list(label_output.values())[1]
39
  now = date.today()
@@ -41,19 +31,32 @@ def logging(image, label_output):
41
  "Imagen": [image],
42
  "Grado 1": [grade1],
43
  "Grado 2": [grade2],
44
- "Observación": [""],
45
  "Fecha": [now.strftime("%d/%m/%Y")],
46
- "Acción": [f"\"\"\"[Descargar]({image})\"\"\""]
47
  }
48
  dataframe = pd.DataFrame(data=dictionary)
49
  dataframe.to_csv(path_or_buf="log.csv", sep=";", mode="a", index=False)
50
- print(dataframe)
51
-
52
  # Logger = gr.SimpleCSVLogger()
53
 
 
 
 
 
 
54
  with gr.Blocks(title="Historial de diagnósticos") as ViewingHistory:
55
- dataframe = pd.read_csv(filepath_or_buffer="log.csv", sep=";")
56
- gr.Dataframe(
 
 
 
 
 
 
 
 
 
57
  value=dataframe,
58
  headers=["Imagen", "Grado 1", "Grado 2", "Observación", "Fecha", "Acción"],
59
  datatype=["str", "number", "number", "str", "date", "markdown"],
@@ -64,21 +67,31 @@ with gr.Blocks(title="Historial de diagnósticos") as ViewingHistory:
64
  with gr.Blocks(title="Base de datos") as Database:
65
  with gr.Row():
66
  with gr.Column():
67
- gr.Dropdown(
68
- choices=["Usuarios", "Imágenes", "Resultados"],
69
- filterable=True, label="Tabla",
70
- scale=2
71
  )
 
 
 
72
  with gr.Row():
73
- gr.Dataframe(
74
- headers=["Imagen", "Grado 1", "Grado 2", "Observación", "Fecha"],
75
- datatype=["str", "number", "number", "str", "date"],
76
- row_count=(3, "dynamic"),
77
- col_count=(5, "dynamic"),
78
  type="pandas",
79
  wrap=True,
80
  interactive=False
81
  )
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  with gr.Blocks(title="Información de usuario") as AdminInformation:
84
  with gr.Row():
@@ -104,20 +117,21 @@ with gr.Blocks(title="Información de usuario") as AdminInformation:
104
  with gr.Blocks(title="Clasificación") as MyModel:
105
  with gr.Row():
106
  with gr.Column():
107
- image_file = gr.File(file_count="single", file_types=[".nii.gz", ".nii"], type="filepath", label="Imagen")
108
- segment_file = gr.File(file_count="single", file_types=[".nii.gz", ".nii"], type="filepath", label="Segmento")
109
  with gr.Column():
110
  label_output = gr.Label(label="Resultado")
 
111
  with gr.Row():
112
  with gr.Column():
113
  with gr.Row():
114
  with gr.Column():
115
- clear_button = gr.ClearButton(value="Borrar", components=[image_file, segment_file, label_output])
116
  with gr.Column():
117
  submit_button = gr.Button(value="Enviar", variant="primary")
118
  with gr.Column():
119
  flag_button = gr.Button(value="Marcar")
120
- flag_button.click(fn=logging, inputs=[image_file, label_output])
121
  submit_button.click(fn=image_classifier, inputs=[image_file, segment_file], outputs=[label_output])
122
 
123
  # MainModel = gr.Interface(
@@ -139,7 +153,36 @@ demo = gr.TabbedInterface(
139
  tab_names=["Aplicación", "Historial", "Base de datos", "Administrador"],
140
  )
141
 
142
- demo.launch(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  share=True,
144
  debug=True
145
  )
 
1
+ import os
2
  import numpy as np
3
  import pandas as pd
4
+ import gradio as gr
5
  from pickle import load
6
  from datetime import date
7
  from radiomics import featureextractor
 
10
 
11
  with open("model.pickle", "rb") as file:
12
  loaded_model = load(file)
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  def image_classifier(image, segment):
15
  features3D = extractor3D.execute(imageFilepath=image, maskFilepath=segment)
 
21
  dict[key] = [value]
22
  dataframe = pd.DataFrame(dict).select_dtypes(exclude=["object"]).to_numpy()
23
  prediction = loaded_model.predict_proba(dataframe).tolist()[0]
24
+ return {"Grado 1": prediction[0], "Grado 2": prediction[1]}
25
 
26
+ def logging(image, label_output, comment_output):
27
  grade1 = list(label_output.values())[0]
28
  grade2 = list(label_output.values())[1]
29
  now = date.today()
 
31
  "Imagen": [image],
32
  "Grado 1": [grade1],
33
  "Grado 2": [grade2],
34
+ "Observación": [comment_output],
35
  "Fecha": [now.strftime("%d/%m/%Y")],
36
+ "Acción": [f"[Descargar]({image})"]
37
  }
38
  dataframe = pd.DataFrame(data=dictionary)
39
  dataframe.to_csv(path_or_buf="log.csv", sep=";", mode="a", index=False)
40
+ return dataframe
 
41
  # Logger = gr.SimpleCSVLogger()
42
 
43
+ def on_selected(event : gr.SelectData):
44
+ return f"You selected {event.value} at {event.index} from {event.target}"
45
+
46
+ gradioDataframe = gr.DataFrame()
47
+
48
  with gr.Blocks(title="Historial de diagnósticos") as ViewingHistory:
49
+ dataframe = pd.DataFrame({
50
+ "Imagen": [""],
51
+ "Grado 1": [0],
52
+ "Grado 2": [0],
53
+ "Observación": [""],
54
+ "Fecha": [""],
55
+ "Acción": [""],
56
+ })
57
+ if os.path.isfile("log.csv"):
58
+ dataframe = pd.read_csv(filepath_or_buffer="log.csv", sep=";")
59
+ gradioDataframe = gr.Dataframe(
60
  value=dataframe,
61
  headers=["Imagen", "Grado 1", "Grado 2", "Observación", "Fecha", "Acción"],
62
  datatype=["str", "number", "number", "str", "date", "markdown"],
 
67
  with gr.Blocks(title="Base de datos") as Database:
68
  with gr.Row():
69
  with gr.Column():
70
+ dropdown = gr.Dropdown(
71
+ choices=["Usuarios", "Imágenes", "Resultados"],
72
+ filterable=False, label="Tabla",
73
+ scale=2
74
  )
75
+ with gr.Column():
76
+ button = gr.Button(value="Buscar")
77
+
78
  with gr.Row():
79
+ dataframe = gr.Dataframe(
 
 
 
 
80
  type="pandas",
81
  wrap=True,
82
  interactive=False
83
  )
84
+
85
+ def on_selected(selected_value):
86
+ if selected_value == "Usuarios":
87
+ db_df = pd.read_sql_table("users", "sqlite:///database.db")
88
+ elif selected_value == "Imágenes":
89
+ db_df = pd.read_sql_table("images", "sqlite:///database.db")
90
+ else:
91
+ db_df = pd.read_sql_table("predictions", "sqlite:///database.db")
92
+ return db_df
93
+
94
+ button.click(on_selected, dropdown, dataframe)
95
 
96
  with gr.Blocks(title="Información de usuario") as AdminInformation:
97
  with gr.Row():
 
117
  with gr.Blocks(title="Clasificación") as MyModel:
118
  with gr.Row():
119
  with gr.Column():
120
+ image_file = gr.File(file_count="single", file_types=[".nii.gz", ".nii"], type="binary", label="Imagen")
121
+ segment_file = gr.File(file_count="single", file_types=[".nii.gz", ".nii"], type="binary", label="Segmento")
122
  with gr.Column():
123
  label_output = gr.Label(label="Resultado")
124
+ comment_output = gr.Textbox(label="Observación", type="text", interactive=True)
125
  with gr.Row():
126
  with gr.Column():
127
  with gr.Row():
128
  with gr.Column():
129
+ clear_button = gr.ClearButton(value="Borrar", components=[image_file, segment_file, label_output, comment_output])
130
  with gr.Column():
131
  submit_button = gr.Button(value="Enviar", variant="primary")
132
  with gr.Column():
133
  flag_button = gr.Button(value="Marcar")
134
+ flag_button.click(fn=logging, inputs=[image_file, label_output, comment_output], outputs=[gradioDataframe])
135
  submit_button.click(fn=image_classifier, inputs=[image_file, segment_file], outputs=[label_output])
136
 
137
  # MainModel = gr.Interface(
 
153
  tab_names=["Aplicación", "Historial", "Base de datos", "Administrador"],
154
  )
155
 
156
+ with gr.Blocks(title="Inicio de sesión") as Login:
157
+ with gr.Column():
158
+ email = gr.Textbox(label="Correo electrónico", interactive=True, type="email", max_lines=1)
159
+ password = gr.Textbox(label="Contraseña", interactive=True, type="password", max_lines=1)
160
+ button = gr.Button("Acceder", variant="primary")
161
+
162
+ def password_validation(emailInput, passwordInput):
163
+
164
+ if emailInput == "" or passwordInput == "":
165
+ return gr.Info("Ingresar correo eléctronico y contraseña")
166
+
167
+ userTable = pd.read_sql_table("users", "sqlite:///database.db")
168
+ userRow = userTable[userTable["email"] == emailInput]
169
+
170
+ if userRow.empty:
171
+ return gr.Warning("Correo electrónico o contraseña incorrecta")
172
+
173
+ userPassword = userRow["password"].to_numpy().tolist()[0]
174
+ print(userPassword, passwordInput, userPassword == passwordInput)
175
+
176
+ if userPassword == passwordInput:
177
+ Login = demo.launch(inline=True)
178
+ else:
179
+ return gr.Warning("Correo electrónico o contraseña incorrecta")
180
+
181
+ button.click(password_validation, inputs=[email, password])
182
+
183
+
184
+
185
+ Login.launch(
186
  share=True,
187
  debug=True
188
  )