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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -165
app.py CHANGED
@@ -1,188 +1,170 @@
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
 
8
 
9
  extractor3D = featureextractor.RadiomicsFeatureExtractor("3DParams.yaml")
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)
16
- dict = {}
17
- for key, value in zip(features3D.keys(), features3D.values()):
18
- if isinstance(value, np.ndarray):
19
- dict[key] = [value.tolist()]
20
- else:
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()
30
- dictionary = {
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"],
63
- type="pandas",
64
- wrap=True
65
- )
66
 
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():
98
- with gr.Column():
99
- gr.Image(interactive=True)
100
- with gr.Column():
101
- gr.Textbox(value="Nicolás Andrés", label="Nombres", interactive=True, show_copy_button=True, type="text", max_lines=1, container=False)
102
- gr.Textbox(value="niplinig", label="Usuario", interactive=False, show_copy_button=True, type="text", max_lines=1, container=False)
103
- gr.Textbox(value="Administrador", label="Rol", interactive=False, show_copy_button=True, type="text", max_lines=1, container=False)
104
- with gr.Column():
105
- gr.Textbox(value="Plaza Iñiguez", label="Apellidos", interactive=True, show_copy_button=True, type="text", max_lines=1, container=False)
106
- gr.Textbox(value="niplinig@espol.edu.ec", label="Correo electrónico", interactive=True, show_copy_button=True, type="email", max_lines=1, container=False)
107
- gr.Textbox(value="0939552946", label="Número de teléfono", interactive=True, show_copy_button=True, type="text", max_lines=1, container=False)
108
- with gr.Row():
109
- gr.Button(value="Guardar")
110
-
111
- # def on_select(event : gr.SelectData):
112
- # print(event.value, event.index, event.target, sep=",")
113
- # return f"You selected {event.value} at {event.index} from {event.target}"
114
-
115
- # image_file.select(fn=on_select, inputs=None, outputs=None)
116
-
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(
138
- # fn=image_classifier,
139
- # inputs=[image_file, segment_file],
140
- # outputs=[gr.Label(label="Resultado")],
141
- # title="Clasificación",
142
- # description="Clasificación",
143
- # allow_flagging="manual",
144
- # flagging_callback=Logger,
145
- # submit_btn="Enviar",
146
- # stop_btn="Suspender",
147
- # clear_btn="Borrar",
148
- # show_progress="full",
149
- # )
150
-
151
- demo = gr.TabbedInterface(
152
- interface_list=[MyModel, ViewingHistory, Database, AdminInformation],
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
- )
 
 
 
 
1
+ import sqlite3
2
  import numpy as np
3
  import pandas as pd
4
  import gradio as gr
5
  from pickle import load
6
+ import sqlalchemy
7
  from radiomics import featureextractor
8
+ from sqlalchemy.orm import sessionmaker
9
 
10
  extractor3D = featureextractor.RadiomicsFeatureExtractor("3DParams.yaml")
 
11
  with open("model.pickle", "rb") as file:
12
  loaded_model = load(file)
13
+
14
+ def validation(username : str, password : str):
15
+ if username == "" or password == "":
16
+ return False
17
+ table = pd.read_sql_table(table_name="Usuarios", con="sqlite:///database_test.db")
18
+ row = table[table["Usuario"] == username]
19
+ if row.empty:
20
+ return False
21
+ password_db = row["Contraseña"].to_numpy().tolist()[0]
22
+ return password == password_db
23
+
24
+ with gr.Blocks(title="Clasificación") as AIModel:
25
+ with gr.Row():
26
+ with gr.Column():
27
+ image_file = gr.File(file_count="single", file_types=[".nii.gz", ".nii"], type="filepath", label="Imagen")
28
+ segment_file = gr.File(file_count="single", file_types=[".nii.gz", ".nii"], type="filepath", label="Segmento")
29
+ with gr.Column():
30
+ label_output = gr.Label(label="Resultado")
31
+ comment_output = gr.Textbox(label="Observación", type="text", interactive=True)
32
+ with gr.Row():
33
+ with gr.Column():
34
+ with gr.Row():
35
+ with gr.Column():
36
+ clear_button = gr.ClearButton(value="Borrar", components=[image_file, segment_file, label_output, comment_output])
37
+ with gr.Column():
38
+ submit_button = gr.Button(value="Enviar", variant="primary")
39
+ with gr.Column():
40
+ flag_button = gr.Button(value="Marcar")
41
+
42
+ def make_prediction(image, label_output, comment_output):
43
+ grade1 = list(label_output.values())[0]
44
+ grade2 = list(label_output.values())[1]
45
+ engine = sqlalchemy.create_engine("sqlite:///database.db", echo=False)
46
+ Session = sessionmaker(bind=engine)
47
+ session = Session()
48
+ new_prediction = {
49
+ "Imagen": image,
50
+ "Grado 1": grade1,
51
+ "Grado 2": grade2,
52
+ "Observacion": comment_output,
53
+ "Usuario ID": 1,
54
+ }
55
+ stmt = predictions.insert().values(**new_prediction)
56
+ session.execute(stmt)
57
+ session.commit()
58
+
59
+ def image_classifier(image, segment):
60
+ features3D = extractor3D.execute(imageFilepath=image, maskFilepath=segment)
61
+ dict = {}
62
+ for key, value in zip(features3D.keys(), features3D.values()):
63
+ if isinstance(value, np.ndarray):
64
+ dict[key] = [value.tolist()]
65
+ else:
66
+ dict[key] = [value]
67
+ temp = pd.DataFrame(dict).select_dtypes(exclude=["object"]).to_numpy()
68
+ prediction = loaded_model.predict_proba(temp).tolist()[0]
69
+ return {"Grado 1": prediction[0], "Grado 2": prediction[1]}
70
+
71
+ flag_button.click(fn=make_prediction, inputs=[image_file, label_output, comment_output])
72
+ submit_button.click(fn=image_classifier, inputs=[image_file, segment_file], outputs=[label_output])
73
 
74
  with gr.Blocks(title="Historial de diagnósticos") as ViewingHistory:
75
+ temp = pd.read_sql_table("Predicciones", "sqlite:///database_test.db")
76
+ gr.Dataframe(temp, type="pandas", wrap=True, interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
  with gr.Blocks(title="Base de datos") as Database:
79
+ with gr.Row():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  with gr.Column():
81
+ dropdown = gr.Dropdown(choices=["Usuarios", "Predicciones"],
82
+ filterable=False, label="Tabla")
83
  with gr.Column():
84
+ button = gr.Button(value="Buscar", variant="primary")
85
+ with gr.Row():
86
+ dataframe = gr.Dataframe(type="pandas", wrap=True, interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
+ def on_selected(selected_value):
89
+ return pd.read_sql_table(selected_value, "sqlite:///database_test.db")
90
 
91
+ button.click(on_selected, dropdown, dataframe)
 
92
 
93
+ with gr.Blocks(title="Información de usuario", delete_cache=[60, 120]) as AdminInformation:
 
94
 
95
+ username : str = ""
96
+ first_names : str = ""
97
+ last_names : str = ""
98
+ email : str = ""
99
+ phone : int = 0
100
+ is_admin : bool = False
101
 
102
+ table = pd.read_sql_table(table_name="Usuarios", con="sqlite:///database_test.db")
103
+ row = table[table["ID"] == 1]
104
+
105
+ def make_interactive(input_first_names, input_username, input_last_names, input_email, input_phone):
106
+ return (
107
+ gr.Textbox(label="Nombres", interactive=True, max_lines=1),
108
+ gr.Textbox(label="Usuario", interactive=True, max_lines=1),
109
+ gr.Textbox(label="Apellidos", interactive=True, max_lines=1),
110
+ gr.Textbox(label="Correo electrónico", interactive=True, max_lines=1),
111
+ gr.Textbox(label="Número de teléfono", interactive=True, max_lines=1)
112
+ )
113
+
114
+ def save(input_first_names, input_username, input_last_names, input_email, input_phone):
115
+
116
+ connection = sqlite3.connect("database_test.db")
117
+ cursor = connection.cursor()
118
+ data = cursor.execute(f'''UPDATE Usuarios SET Nombres = '{input_first_names}', Usuario = '{input_username}', Apellidos = '{input_last_names}', "Correo electronico" = '{input_email}', Telefono = '{input_phone}' WHERE ID==1;''')
119
+ connection.commit()
120
+ connection.close()
121
+
122
+ return (
123
+ gr.Textbox(value=input_first_names, label="Nombres", interactive=False, max_lines=1),
124
+ gr.Textbox(value=input_username, label="Usuario", interactive=False, max_lines=1),
125
+ gr.Textbox(value=input_last_names, label="Apellidos", interactive=False, max_lines=1),
126
+ gr.Textbox(value=input_email, label="Correo electrónico", interactive=False, max_lines=1),
127
+ gr.Textbox(value=input_phone, label="Número de teléfono", interactive=False, max_lines=1)
128
+ )
129
+
130
+ if not row.empty:
131
+ username = row["Usuario"].to_numpy().tolist()[0]
132
+ first_names = row["Nombres"].to_numpy().tolist()[0]
133
+ last_names = row["Apellidos"].to_numpy().tolist()[0]
134
+ email = row["Correo electronico"].to_numpy().tolist()[0]
135
+ phone = row["Telefono"].to_numpy().tolist()[0]
136
+ is_admin = row["Es Administrador"].to_numpy().tolist()[0]
137
+
138
+ with gr.Row():
139
+ with gr.Column():
140
+ input_profile_image = gr.Image(interactive=False)
141
+ with gr.Column():
142
+ input_first_names = gr.Textbox(value=first_names, label="Nombres", interactive=False, type="text", max_lines=1)
143
+ input_username = gr.Textbox(value=username, label="Usuario", interactive=False, type="text", max_lines=1)
144
+ #gr.Textbox(value="Administrador", label="Rol", interactive=False, show_copy_button=True, type="text", max_lines=1, container=False)
145
+ with gr.Column():
146
+ input_last_names = gr.Textbox(value=last_names, label="Apellidos", interactive=False, type="text", max_lines=1)
147
+ input_email = gr.Textbox(value=email, label="Correo electrónico", interactive=False, type="email", max_lines=1)
148
+ input_phone = gr.Textbox(value=phone, label="Número de teléfono", interactive=False, type="text", max_lines=1)
149
+ with gr.Row():
150
+ with gr.Row():
151
+ edit_button = gr.Button(value="Editar")
152
+ save_button = gr.Button(value="Guardar", variant="primary")
153
+
154
+ edit_button.click(make_interactive, inputs=[input_first_names, input_username, input_last_names, input_email, input_phone],
155
+ outputs=[input_first_names, input_username, input_last_names, input_email, input_phone])
156
+ save_button.click(save, inputs=[input_first_names, input_username, input_last_names, input_email, input_phone], outputs=[input_first_names, input_username, input_last_names, input_email, input_phone])
157
 
 
 
 
 
 
 
 
158
 
159
+ Demo = gr.TabbedInterface(
160
+ interface_list=[AIModel, ViewingHistory, Database, AdminInformation],
161
+ tab_names=["Aplicación", "Historial", "Base de datos", "Administrador"],
162
+ )
163
 
164
+ if __name__ == "__main__":
165
+ Demo.launch(
166
+ share=True,
167
+ debug=True,
168
+ inbrowser=True,
169
+ auth=validation
170
+ )