Update app.py
Browse files1234562 unmodified lines9101112131415161718192021222324255 unmodified lines3132333435363738391 unmodified line414243444546474849505152535455565758594 unmodified lines64656667686970717273747576777879808182838419 unmodified lines10410510610710810911011111211311411511611711811912012112212315 unmodified lines139140141142143144145import gradio as grimport numpy as npimport pandas as pdfrom pickle import loadfrom datetime import datefrom radiomics import featureextractor2 unmodified lineswith open("model.pickle", "rb") as file:loaded_model = load(file)class TextStream:def __init__(self):self.data : list = []def write(self, s):if s.strip():self.data.append(s.strip())def flush(self):passdef image_classifier(image, segment):features3D = extractor3D.execute(imageFilepath=image, maskFilepath=segment)5 unmodified linesdict[key] = [value]dataframe = pd.DataFrame(dict).select_dtypes(exclude=["object"]).to_numpy()prediction = loaded_model.predict_proba(dataframe).tolist()[0]return {"Grade 1": prediction[0], "Grade 2": prediction[1]}def logging(image, label_output):grade1 = list(label_output.values())[0]grade2 = list(label_output.values())[1]now = date.today()1 unmodified line"Imagen": [image],"Grado 1": [grade1],"Grado 2": [grade2],"Observación": [""],"Fecha": [now.strftime("%d/%m/%Y")],"Acción": [f"\"\"\"[Descargar]({image})\"\"\""]}dataframe = pd.DataFrame(data=dictionary)dataframe.to_csv(path_or_buf="log.csv", sep=";", mode="a", index=False)print(dataframe)# Logger = gr.SimpleCSVLogger()with gr.Blocks(title="Historial de diagnósticos") as ViewingHistory:dataframe = pd.read_csv(filepath_or_buffer="log.csv", sep=";")gr.Dataframe(value=dataframe,headers=["Imagen", "Grado 1", "Grado 2", "Observación", "Fecha", "Acción"],datatype=["str", "number", "number", "str", "date", "markdown"],4 unmodified lineswith gr.Blocks(title="Base de datos") as Database:with gr.Row():with gr.Column():gr.Dropdown(choices=["Usuarios", "Imágenes", "Resultados"],filterable=True, label="Tabla",scale=2)with gr.Row():gr.Dataframe(headers=["Imagen", "Grado 1", "Grado 2", "Observación", "Fecha"],datatype=["str", "number", "number", "str", "date"],row_count=(3, "dynamic"),col_count=(5, "dynamic"),type="pandas",wrap=True,interactive=False)with gr.Blocks(title="Información de usuario") as AdminInformation:with gr.Row():19 unmodified lineswith gr.Blocks(title="Clasificación") as MyModel:with gr.Row():with gr.Column():image_file = gr.File(file_count="single", file_types=[".nii.gz", ".nii"], type="filepath", label="Imagen")segment_file = gr.File(file_count="single", file_types=[".nii.gz", ".nii"], type="filepath", label="Segmento")with gr.Column():label_output = gr.Label(label="Resultado")with gr.Row():with gr.Column():with gr.Row():with gr.Column():clear_button = gr.ClearButton(value="Borrar", components=[image_file, segment_file, label_output])with gr.Column():submit_button = gr.Button(value="Enviar", variant="primary")with gr.Column():flag_button = gr.Button(value="Marcar")flag_button.click(fn=logging, inputs=[image_file, label_output])submit_button.click(fn=image_classifier, inputs=[image_file, segment_file], outputs=[label_output])# MainModel = gr.Interface(15 unmodified linestab_names=["Aplicación", "Historial", "Base de datos", "Administrador"],)demo.launch(share=True,debug=True)12345672 unmodified lines1011121314155 unmodified lines2122232425262728291 unmodified line31323334353637383940414243444546474849505152535455565758596061624 unmodified lines6768697071727374757677787980818283848586878889909192939495969719 unmodified lines11711811912012112212312412512612712812913013113213313413513613715 unmodified lines153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188import osimport numpy as npimport pandas as pdimport gradio as grfrom pickle import loadfrom datetime import datefrom radiomics import featureextractor2 unmodified lineswith open("model.pickle", "rb") as file:loaded_model = load(file)def image_classifier(image, segment):features3D = extractor3D.execute(imageFilepath=image, maskFilepath=segment)5 unmodified linesdict[key] = [value]dataframe = pd.DataFrame(dict).select_dtypes(exclude=["object"]).to_numpy()prediction = loaded_model.predict_proba(dataframe).tolist()[0]return {"Grado 1": prediction[0], "Grado 2": prediction[1]}def logging(image, label_output, comment_output):grade1 = list(label_output.values())[0]grade2 = list(label_output.values())[1]now = date.today()1 unmodified line"Imagen": [image],"Grado 1": [grade1],"Grado 2": [grade2],"Observación": [comment_output],"Fecha": [now.strftime("%d/%m/%Y")],"Acción": [f"[Descargar]({image})"]}dataframe = pd.DataFrame(data=dictionary)dataframe.to_csv(path_or_buf="log.csv", sep=";", mode="a", index=False)return dataframe# Logger = gr.SimpleCSVLogger()def on_selected(event : gr.SelectData):return f"You selected {event.value} at {event.index} from {event.target}"gradioDataframe = gr.DataFrame()with gr.Blocks(title="Historial de diagnósticos") as ViewingHistory:dataframe = pd.DataFrame({"Imagen": [""],"Grado 1": [0],"Grado 2": [0],"Observación": [""],"Fecha": [""],"Acción": [""],})if os.path.isfile("log.csv"):dataframe = pd.read_csv(filepath_or_buffer="log.csv", sep=";")gradioDataframe = gr.Dataframe(value=dataframe,headers=["Imagen", "Grado 1", "Grado 2", "Observación", "Fecha", "Acción"],datatype=["str", "number", "number", "str", "date", "markdown"],4 unmodified lineswith gr.Blocks(title="Base de datos") as Database:with gr.Row():with gr.Column():dropdown = gr.Dropdown(choices=["Usuarios", "Imágenes", "Resultados"],filterable=False, label="Tabla",scale=2)with gr.Column():button = gr.Button(value="Buscar")with gr.Row():dataframe = gr.Dataframe(type="pandas",wrap=True,interactive=False)def on_selected(selected_value):if selected_value == "Usuarios":db_df = pd.read_sql_table("users", "sqlite:///database.db")elif selected_value == "Imágenes":db_df = pd.read_sql_table("images", "sqlite:///database.db")else:db_df = pd.read_sql_table("predictions", "sqlite:///database.db")return db_dfbutton.click(on_selected, dropdown, dataframe)with gr.Blocks(title="Información de usuario") as AdminInformation:with gr.Row():19 unmodified lineswith gr.Blocks(title="Clasificación") as MyModel:with gr.Row():with gr.Column():image_file = gr.File(file_count="single", file_types=[".nii.gz", ".nii"], type="binary", label="Imagen")segment_file = gr.File(file_count="single", file_types=[".nii.gz", ".nii"], type="binary", label="Segmento")with gr.Column():label_output = gr.Label(label="Resultado")comment_output = gr.Textbox(label="Observación", type="text", interactive=True)with gr.Row():with gr.Column():with gr.Row():with gr.Column():clear_button = gr.ClearButton(value="Borrar", components=[image_file, segment_file, label_output, comment_output])with gr.Column():submit_button = gr.Button(value="Enviar", variant="primary")with gr.Column():flag_button = gr.Button(value="Marcar")flag_button.click(fn=logging, inputs=[image_file, label_output, comment_output], outputs=[gradioDataframe])submit_button.click(fn=image_classifier, inputs=[image_file, segment_file], outputs=[label_output])# MainModel = gr.Interface(15 unmodified linestab_names=["Aplicación", "Historial", "Base de datos", "Administrador"],)with gr.Blocks(title="Inicio de sesión") as Login:with gr.Column():email = gr.Textbox(label="Correo electrónico", interactive=True, type="email", max_lines=1)password = gr.Textbox(label="Contraseña", interactive=True, type="password", max_lines=1)button = gr.Button("Acceder", variant="primary")def password_validation(emailInput, passwordInput):if emailInput == "" or passwordInput == "":return gr.Info("Ingresar correo eléctronico y contraseña")userTable = pd.read_sql_table("users", "sqlite:///database.db")userRow = userTable[userTable["email"] == emailInput]if userRow.empty:return gr.Warning("Correo electrónico o contraseña incorrecta")userPassword = userRow["password"].to_numpy().tolist()[0]print(userPassword, passwordInput, userPassword == passwordInput)if userPassword == passwordInput:Login = demo.launch(inline=True)else:return gr.Warning("Correo electrónico o contraseña incorrecta")button.click(password_validation, inputs=[email, password])Login.launch(share=True,debug=True)
app.py+77-34