{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":14774,"databundleVersionId":875431,"sourceType":"competition"},{"sourceId":8221415,"sourceType":"datasetVersion","datasetId":4873993},{"sourceId":9205893,"sourceType":"datasetVersion","datasetId":5566198},{"sourceId":9200009,"sourceType":"datasetVersion","datasetId":5562109}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import img_to_array, ImageDataGenerator\nimport cv2\nimport numpy as np\nfrom PIL import Image\nimport os\nimport ipywidgets as widgets\nfrom IPython.display import display, clear_output\nfrom tkinter import Tk\nfrom tkinter.filedialog import askopenfilename\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import img_to_array, ImageDataGenerator\nimport cv2\nimport numpy as np\nfrom PIL import Image\nimport ipywidgets as widgets\nfrom IPython.display import display, clear_output\nimport matplotlib.pyplot as plt\nimport os\n","metadata":{"execution":{"iopub.status.busy":"2024-08-19T22:57:55.88982Z","iopub.execute_input":"2024-08-19T22:57:55.89013Z","iopub.status.idle":"2024-08-19T22:58:09.212512Z","shell.execute_reply.started":"2024-08-19T22:57:55.890102Z","shell.execute_reply":"2024-08-19T22:58:09.211382Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_stages_3 = tf.keras.models.load_model('/kaggle/input/modelos-experimento-paper/model_stages_inceptionv3.h5')\n\nmodel_biomarkers_3 = tf.keras.models.load_model( '/kaggle/input/modelos-experimento-paper/model_biomarkers_inceptionv3.h5')","metadata":{"execution":{"iopub.status.busy":"2024-08-19T22:58:49.121426Z","iopub.execute_input":"2024-08-19T22:58:49.122068Z","iopub.status.idle":"2024-08-19T22:59:00.546308Z","shell.execute_reply.started":"2024-08-19T22:58:49.12203Z","shell.execute_reply":"2024-08-19T22:59:00.545322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"names = ['Microneurysm', 'Haemorrhage', 'Hard Exudate', 'Soft Exudate']","metadata":{"execution":{"iopub.status.busy":"2024-08-19T22:59:00.548804Z","iopub.execute_input":"2024-08-19T22:59:00.549333Z","iopub.status.idle":"2024-08-19T22:59:00.555316Z","shell.execute_reply.started":"2024-08-19T22:59:00.549291Z","shell.execute_reply":"2024-08-19T22:59:00.554223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagen = ImageDataGenerator(\n    featurewise_center=True,\n    featurewise_std_normalization=True,\n)\n\ndef prepare_image(img):\n    img = img.resize((224, 224))  # Redimensionar la imagen a 224x224\n    img = np.array(img)  # Convertir la imagen a un array numpy\n    img = img / 255.0  # Normalizar la imagen\n    img = img_to_array(img)\n    img = np.expand_dims(img, axis=0)\n    img = datagen.standardize(img[0])  \n    img = np.expand_dims(img, axis=0)\n    return img\n\ndef predict_image_1(img, dataResults, model_1):\n    prediction = model_1.predict(img)\n    pred_index = np.argmax(prediction, axis=1)[0]\n    try:\n        result = dataResults[pred_index]\n    except IndexError:\n        result = \"Unknown\"  # Manejo del error si el índice está fuera de rango\n    return prediction.tolist(), [pred_index, result]\ndef prepare_model_biomarker_1(img, model_1):\n    predictions = model_1.predict(img)\n    predicted_classes_indices = np.where(predictions > 0.5)[1]\n    predicted_classes = [names[i] for i in predicted_classes_indices]\n    return predictions.tolist(), predicted_classes\n\n","metadata":{"execution":{"iopub.status.busy":"2024-08-19T23:04:19.98277Z","iopub.execute_input":"2024-08-19T23:04:19.983215Z","iopub.status.idle":"2024-08-19T23:04:19.994339Z","shell.execute_reply.started":"2024-08-19T23:04:19.983176Z","shell.execute_reply":"2024-08-19T23:04:19.993152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def prepare_diagnosis(img):\n    img = prepare_image(img)\n    res_disease = \"0\"\n    res_retinopathy = \"3\"\n    res_stages = \"-1\"\n    res_biomarker = \"-1\"\n    \n    if str(res_disease[0]) == \"0\": \n        if str(res_retinopathy[0]) == \"3\":\n            res_stages_vector, res_stages = predict_image_1(img, [\"Mild Nonproliferative Retinopathy\", \"Moderate Nonproliferative Retinopathy\", \"Severe Nonproliferative Retinopathy\", \"Proliferative Diabetic Retinopathy\"], model_stages_3)\n            res_biomarker_vector, res_biomarker = prepare_model_biomarker_1(img, model_biomarkers_3)\n    \n    return {\n        \"stages\": res_stages,\n        \"stages_vector\": res_stages_vector,\n        \"biomarkers\": res_biomarker,\n        \"biomarkers_vector\": res_biomarker_vector,\n    }\n\n\n","metadata":{"execution":{"iopub.status.busy":"2024-08-19T23:04:25.289527Z","iopub.execute_input":"2024-08-19T23:04:25.290241Z","iopub.status.idle":"2024-08-19T23:04:25.297932Z","shell.execute_reply.started":"2024-08-19T23:04:25.290203Z","shell.execute_reply":"2024-08-19T23:04:25.29655Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from IPython.display import display, clear_output\nstages_results = None\nbiomarkers_results = None\nimage_name_results = None\nstages_vector_results = None\nbiomarkers_vector_results = None\nimg_show_results = None\ndef on_image_upload(change):\n    global stages_results  # Usar la variable global\n    global biomarkers_results  # Usar la variable global\n    global stages_vector_results  # Usar la variable global\n    global biomarkers_vector_results  # Usar la variable global\n    global image_name_results  # Usar la variable global\n    global img_show_results  # Usar la variable global\n    uploaded_file = change['new']\n    if uploaded_file:\n        clear_output(wait=True)  # Clear previous output\n\n      \n        # Extraer el primer archivo subido\n        file_info = next(iter(uploaded_file.values()))\n       \n        # Leer el contenido binario del archivo\n        img_content = file_info['content']\n\n        print(img_content)\n        # Convertir el contenido binario a una imagen utilizando PIL\n        img = Image.open(io.BytesIO(img_content))\n  \n        # Mostrar la imagen seleccionada\n        plt.imshow(img)\n        plt.axis('off')\n        plt.show()\n        \n        # Realizar las predicciones\n        print(img)\n        results = prepare_diagnosis(img)\n       \n        \n        # Mostrar los resultados\n        img_show_results = img\n        biomarkers_results = results['biomarkers']\n        biomarkers_vector_results = results['biomarkers_vector']\n        stages_vector_results = results['stages_vector']\n        stages_results = results['stages']\n        image_name_results = file_info['metadata']['name']\n        print(f\"Image: {file_info['metadata']['name']}\")\n        print(f\"Stages: {results['stages']}\")\n        print(f\"Stages Vector: {results['stages_vector']}\")\n        print(f\"Biomarkers: {', '.join(results['biomarkers'])}\")\n        print(f\"Biomarkers Vector: {results['biomarkers_vector']}\")\n    else:\n        print(\"No image selected.\")\n","metadata":{"execution":{"iopub.status.busy":"2024-08-19T23:31:27.034147Z","iopub.execute_input":"2024-08-19T23:31:27.035111Z","iopub.status.idle":"2024-08-19T23:31:27.046169Z","shell.execute_reply.started":"2024-08-19T23:31:27.03506Z","shell.execute_reply":"2024-08-19T23:31:27.045164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import io\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom IPython.display import display, clear_output\nimport ipywidgets as widgets\n\n\n\n# Crear el widget FileUpload\n\nupload_button = widgets.FileUpload(accept='image/*', multiple=False)\nupload_button.observe(on_image_upload, names='value')\ndisplay(upload_button)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-08-19T23:31:57.676189Z","iopub.execute_input":"2024-08-19T23:31:57.676601Z","iopub.status.idle":"2024-08-19T23:31:57.689456Z","shell.execute_reply.started":"2024-08-19T23:31:57.676566Z","shell.execute_reply":"2024-08-19T23:31:57.688501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Nombre imagen:')\nprint(image_name_results) \nprint('--------------------------')\nprint('Resultados Etapas:')\nprint(stages_results )\nprint('--------------------------')\nprint('Etapas Vector:')\nprint(stages_vector_results)\nprint('--------------------------')\nprint('Resultados Biomarkers:')\nprint(biomarkers_results)\nprint('--------------------------')\nprint('Biomarker Vector:')\nprint(biomarkers_vector_results)\nprint('--------------------------')\nplt.imshow(img_show_results)\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-19T23:32:22.373805Z","iopub.execute_input":"2024-08-19T23:32:22.374235Z","iopub.status.idle":"2024-08-19T23:32:23.262948Z","shell.execute_reply.started":"2024-08-19T23:32:22.374201Z","shell.execute_reply":"2024-08-19T23:32:23.261807Z"},"trusted":true},"execution_count":null,"outputs":[]}]}