{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "H7ENjELwQyjR", "outputId": "95d2f8a3-9d3f-442f-8106-bd4c89521476" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Overwriting requirements.txt\n" ] } ], "source": [ "%%writefile requirements.txt\n", "gradio\n", "tensorflow\n", "numpy\n", "pillow\n", "opencv-python-headless\n" ] }, { "cell_type": "code", "source": [ "!pip install gradio" ], "metadata": { "id": "fbc_INKXRIg-" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "from google.colab import files\n", "\n", "uploaded = files.upload()\n", "\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 73 }, "id": "EUidXLRmSQs9", "outputId": "bb6a5fac-a734-4aa8-8fac-75ebbe6dbbff" }, "execution_count": null, "outputs": [ { "output_type": "display_data", "data": { "text/plain": [ "" ], "text/html": [ "\n", " \n", " \n", " Upload widget is only available when the cell has been executed in the\n", " current browser session. Please rerun this cell to enable.\n", " \n", " " ] }, "metadata": {} }, { "output_type": "stream", "name": "stdout", "text": [ "Saving chest_xray_weights.h5 to chest_xray_weights.h5\n" ] } ] }, { "cell_type": "code", "source": [ "!ls" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "X7itk4Fdu1pA", "outputId": "a8772aa3-e115-4dfe-c97f-241b2ec8d148" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "chest_xray_weights.h5 requirements.txt sample_data\n" ] } ] }, { "cell_type": "code", "source": [ "%%writefile app.py\n", "import gradio as gr\n", "import tensorflow as tf\n", "from tensorflow.keras.models import load_model\n", "import numpy as np\n", "from PIL import Image\n", "import cv2\n", "from tensorflow.keras.initializers import GlorotUniform\n", "from tensorflow.keras.utils import custom_object_scope\n", "\n", "# Load your trained model (upload your .h5 file to this directory or specify the path)\n", "# Use a custom object scope to handle potential compatibility issues with GlorotUniform\n", "with custom_object_scope({'GlorotUniform': GlorotUniform}):\n", " model = load_model('chest_xray_weights.h5') # Replace with your actual filename\n", "\n", "\n", "# Define your model's classes (update based on your training labels)\n", "anatomy_classes = [\n", " \"No Finding\",\n", " \"Atelectasis\",\n", " \"Cardiomegaly\",\n", " \"Consolidation\",\n", " \"Edema\",\n", " \"Effusion\",\n", " \"Emphysema\",\n", " \"Fibrosis\",\n", " \"Hernia\",\n", " \"Infiltration\",\n", " \"Mass\",\n", " \"Nodule\",\n", " \"Pneumonia\",\n", " \"Pneumothorax\"\n", "]\n", "\n", "def predict_abnormality(image):\n", " try:\n", " # Preprocess the image (match your training setup)\n", " img = Image.fromarray(image).resize((224, 224)) # Adjust size to your model's input\n", " img_array = np.array(img)\n", "\n", " # Convert to grayscale if your model expects it\n", " if len(img_array.shape) == 3:\n", " img_array = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)\n", "\n", " img_array = img_array / 255.0 # Normalize\n", " img_array = np.expand_dims(img_array, axis=0) # Add batch dimension\n", " img_array = np.expand_dims(img_array, axis=-1) # Add channel if needed\n", "\n", " # Run prediction\n", " predictions = model.predict(img_array) # Removed [0] to inspect full output first\n", " predicted_index = np.argmax(predictions[0]) # Access the first prediction output\n", " confidence = predictions[0][predicted_index]\n", "\n", " # Format output\n", " if predicted_index == 0: # Assuming index 0 is \"Normal\"\n", " return f\"No abnormality detected. Confidence: {confidence:.2%}\"\n", " else:\n", " issue = anatomy_classes[predicted_index]\n", " return f\"Detected issue: {issue}. Confidence: {confidence:.2%}. Please consult a doctor.\"\n", "\n", " except Exception as e:\n", " print(f\"Error details: {e}\") # Print error details\n", " # Added print statements to help diagnose the error\n", " try:\n", " print(f\"Shape of predictions: {predictions.shape}\")\n", " print(f\"Predictions: {predictions}\")\n", " print(f\"Predicted index: {predicted_index}\")\n", " print(f\"Number of anatomy classes: {len(anatomy_classes)}\")\n", "\n", " except NameError:\n", " print(\"Predictions or predicted_index not defined before error.\")\n", "\n", " return f\"Error: {str(e)}. Try another image.\"\n", "\n", "# Create the Gradio interface\n", "demo = gr.Interface(\n", " fn=predict_abnormality,\n", " inputs=gr.Image(label=\"Upload Chest X-Ray Image\", type=\"numpy\"),\n", " outputs=gr.Textbox(label=\"Analysis Result\"),\n", " title=\"Chest X-Ray Abnormality Detector\",\n", " description=\"Upload an X-ray image to detect potential issues. For educational use only—not a medical diagnosis.\",\n", " examples=[[\"sample_xray.jpg\"]], # Add paths to example images if available\n", " allow_flagging=\"never\"\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n" ], "metadata": { "id": "na8gwSs_5rPj" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "import gradio as gr\n", "import tensorflow as tf\n", "from tensorflow.keras.models import load_model\n", "import numpy as np\n", "from PIL import Image\n", "import cv2\n", "from tensorflow.keras.initializers import GlorotUniform\n", "from tensorflow.keras.utils import custom_object_scope\n", "\n", "# Load your trained model (upload your .h5 file to this directory or specify the path)\n", "# Use a custom object scope to handle potential compatibility issues with GlorotUniform\n", "with custom_object_scope({'GlorotUniform': GlorotUniform}):\n", " model = load_model('chest_xray_weights.h5') # Replace with your actual filename\n", "\n", "\n", "# Define your model's classes (update based on your training labels)\n", "anatomy_classes = [\n", " \"No Finding\",\n", " \"Atelectasis\",\n", " \"Cardiomegaly\",\n", " \"Consolidation\",\n", " \"Edema\",\n", " \"Effusion\",\n", " \"Emphysema\",\n", " \"Fibrosis\",\n", " \"Hernia\",\n", " \"Infiltration\",\n", " \"Mass\",\n", " \"Nodule\",\n", " \"Pneumonia\",\n", " \"Pneumothorax\"\n", "]\n", "\n", "def predict_abnormality(image):\n", " try:\n", " # Preprocess the image (match your training setup)\n", " img = Image.fromarray(image).resize((224, 224)) # Adjust size to your model's input\n", " img_array = np.array(img)\n", "\n", " # Convert to grayscale if your model expects it\n", " if len(img_array.shape) == 3:\n", " img_array = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)\n", "\n", " img_array = img_array / 255.0 # Normalize\n", " img_array = np.expand_dims(img_array, axis=0) # Add batch dimension\n", " img_array = np.expand_dims(img_array, axis=-1) # Add channel if needed\n", "\n", " # Run prediction\n", " predictions = model.predict(img_array) # Removed [0] to inspect full output first\n", " predicted_index = np.argmax(predictions[0]) # Access the first prediction output\n", " confidence = predictions[0][predicted_index]\n", "\n", " # Format output\n", " if predicted_index == 0: # Assuming index 0 is \"Normal\"\n", " return f\"No abnormality detected. Confidence: {confidence:.2%}\"\n", " else:\n", " issue = anatomy_classes[predicted_index]\n", " return f\"Detected issue: {issue}. Confidence: {confidence:.2%}. Please consult a doctor.\"\n", "\n", " except Exception as e:\n", " print(f\"Error details: {e}\") # Print error details\n", " # Added print statements to help diagnose the error\n", " try:\n", " print(f\"Shape of predictions: {predictions.shape}\")\n", " print(f\"Predictions: {predictions}\")\n", " print(f\"Predicted index: {predicted_index}\")\n", " print(f\"Number of anatomy classes: {len(anatomy_classes)}\")\n", "\n", " except NameError:\n", " print(\"Predictions or predicted_index not defined before error.\")\n", "\n", " return f\"Error: {str(e)}. Try another image.\"\n", "\n", "# Create the Gradio interface\n", "demo = gr.Interface(\n", " fn=predict_abnormality,\n", " inputs=gr.Image(label=\"Upload Chest X-Ray Image\", type=\"numpy\"),\n", " outputs=gr.Textbox(label=\"Analysis Result\"),\n", " title=\"Chest X-Ray Abnormality Detector\",\n", " description=\"Upload an X-ray image to detect potential issues. For educational use only—not a medical diagnosis.\",\n", " examples=[[\"sample_xray.jpg\"]], # Add paths to example images if available\n", " allow_flagging=\"never\"\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 685 }, "id": "ABo9ZTOIROmK", "outputId": "db3f3be7-9332-46b9-8de9-fa8d76d8c407" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stderr", "text": [ "/usr/local/lib/python3.11/dist-packages/gradio/interface.py:416: UserWarning: The `allow_flagging` parameter in `Interface` is deprecated.Use `flagging_mode` instead.\n", " warnings.warn(\n" ] }, { "output_type": "stream", "name": "stdout", "text": [ "It looks like you are running Gradio on a hosted a Jupyter notebook. For the Gradio app to work, sharing must be enabled. Automatically setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).\n", "\n", "Colab notebook detected. To show errors in colab notebook, set debug=True in launch()\n", "* Running on public URL: https://0b58124b323893b4d0.gradio.live\n", "\n", "This share link expires in 1 week. For free permanent hosting and GPU upgrades, run `gradio deploy` from the terminal in the working directory to deploy to Hugging Face Spaces (https://huggingface.co/spaces)\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "" ], "text/html": [ "
" ] }, "metadata": {} } ] }, { "cell_type": "code", "source": [ "from google.colab import drive\n", "drive.mount('/content/drive')" ], "metadata": { "id": "0mtpdQN3w9wr" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "!gradio deploy" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Eo8HYkzt3vET", "outputId": "428c29ab-d2dc-4ecb-b4a3-6b96d4da4532" }, "execution_count": null, "outputs": [ { "metadata": { "tags": null }, "name": "stdout", "output_type": "stream", "text": [ "Creating new Spaces Repo in \u001b[32m'/content'\u001b[0m. Collecting metadata, press Enter to \n", "accept default value.\n", "Enter Spaces app title [content]: " ] } ] }, { "cell_type": "code", "source": [ "!pip install h5py tensorflow\n" ], "metadata": { "id": "GmlxHeAXTP-a" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# Script: Upload and Handle .h5 File in Colab\n", "\n", "# Step 1: Import necessary libraries\n", "from google.colab import files\n", "from tensorflow.keras.models import load_model\n", "import h5py\n", "import os\n", "\n", "# Step 2: Upload the .h5 file\n", "print(\"Please upload your .h5 file:\")\n", "uploaded = files.upload()\n", "\n", "# Step 3: Get the uploaded filename (assumes single file upload)\n", "filename = list(uploaded.keys())[0] # e.g., 'chest_xray_model.h5'\n", "print(f\"Uploaded file: {filename}\")\n", "\n", "# Step 4: Verify file existence and size\n", "if os.path.exists(filename):\n", " file_size = os.path.getsize(filename) / (1024 * 1024) # Size in MB\n", " print(f\"File size: {file_size:.2f} MB\")\n", "else:\n", " print(\"Upload failed. Please try again.\")\n", " raise SystemExit\n", "\n", "# Step 5: Handle as HDF5 file (general inspection)\n", "with h5py.File(filename, 'r') as f:\n", " print(\"HDF5 keys:\", list(f.keys()))\n", "\n", "# Step 6: Load as Keras model (if it's a model file)\n", "try:\n", " model = load_model(filename)\n", " print(\"Model loaded successfully!\")\n", " model.summary() # Print model architecture\n", "except Exception as e:\n", " print(f\"Error loading as Keras model: {e}\")\n", "\n", "# Optional: Save or process further\n", "# model.save('processed_model.h5') # Example: Resave if modified\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 56 }, "id": "__-Yt8VdTT8b", "outputId": "251ea0b2-627f-4e15-e4b7-9859ee027e25" }, "execution_count": null, "outputs": [ { "metadata": { "tags": null }, "name": "stdout", "output_type": "stream", "text": [ "Please upload your .h5 file:\n" ] }, { "data": { "text/html": [ "\n", " \n", " \n", " Upload widget is only available when the cell has been executed in the\n", " current browser session. Please rerun this cell to enable.\n", " \n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ] }, { "cell_type": "code", "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "f6c9da65", "outputId": "4ffa4d8e-5717-4864-8791-427eb6c0d2cd" }, "source": [ "# Uninstall current TensorFlow version\n", "!pip uninstall tensorflow -y\n", "\n", "# Install TensorFlow 2.8\n", "!pip install tensorflow==2.8\n", "\n", "# After running this cell, restart the Colab runtime (Runtime -> Restart runtime)\n", "# Then, re-run the cell containing your model loading and Gradio interface code (cell ID ABo9ZTOIROmK)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Found existing installation: tensorflow 2.18.0\n", "Uninstalling tensorflow-2.18.0:\n", " Successfully uninstalled tensorflow-2.18.0\n", "\u001b[31mERROR: Could not find a version that satisfies the requirement tensorflow==2.8 (from versions: 2.12.0rc0, 2.12.0rc1, 2.12.0, 2.12.1, 2.13.0rc0, 2.13.0rc1, 2.13.0rc2, 2.13.0, 2.13.1, 2.14.0rc0, 2.14.0rc1, 2.14.0, 2.14.1, 2.15.0rc0, 2.15.0rc1, 2.15.0, 2.15.0.post1, 2.15.1, 2.16.0rc0, 2.16.1, 2.16.2, 2.17.0rc0, 2.17.0rc1, 2.17.0, 2.17.1, 2.18.0rc0, 2.18.0rc1, 2.18.0rc2, 2.18.0, 2.18.1, 2.19.0rc0, 2.19.0)\u001b[0m\u001b[31m\n", "\u001b[0m\u001b[31mERROR: No matching distribution found for tensorflow==2.8\u001b[0m\u001b[31m\n", "\u001b[0m" ] } ] }, { "cell_type": "code", "source": [ "model.summary()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "De7ShZSR0RBq", "outputId": "f9e2c149-3007-4851-b330-b886238fcc40" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Model: \"sequential\"\n", "_________________________________________________________________\n", " Layer (type) Output Shape Param # \n", "=================================================================\n", " conv2d (Conv2D) (None, 222, 222, 32) 320 \n", " \n", " max_pooling2d (MaxPooling2D (None, 111, 111, 32) 0 \n", " ) \n", " \n", " conv2d_1 (Conv2D) (None, 109, 109, 64) 18496 \n", " \n", " max_pooling2d_1 (MaxPooling (None, 54, 54, 64) 0 \n", " 2D) \n", " \n", " conv2d_2 (Conv2D) (None, 52, 52, 128) 73856 \n", " \n", " max_pooling2d_2 (MaxPooling (None, 26, 26, 128) 0 \n", " 2D) \n", " \n", " flatten (Flatten) (None, 86528) 0 \n", " \n", " dense (Dense) (None, 128) 11075712 \n", " \n", " dropout (Dropout) (None, 128) 0 \n", " \n", " dense_1 (Dense) (None, 14) 1806 \n", " \n", "=================================================================\n", "Total params: 11,170,190\n", "Trainable params: 11,170,190\n", "Non-trainable params: 0\n", "_________________________________________________________________\n" ] } ] } ] }