Spaces:
Running
Running
File size: 39,982 Bytes
2b1482e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 |
{
"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": [
"<IPython.core.display.HTML object>"
],
"text/html": [
"\n",
" <input type=\"file\" id=\"files-db89ec8f-2417-43fa-a522-3ace03ec68d3\" name=\"files[]\" multiple disabled\n",
" style=\"border:none\" />\n",
" <output id=\"result-db89ec8f-2417-43fa-a522-3ace03ec68d3\">\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",
" </output>\n",
" <script>// Copyright 2017 Google LLC\n",
"//\n",
"// Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"// you may not use this file except in compliance with the License.\n",
"// You may obtain a copy of the License at\n",
"//\n",
"// http://www.apache.org/licenses/LICENSE-2.0\n",
"//\n",
"// Unless required by applicable law or agreed to in writing, software\n",
"// distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"// See the License for the specific language governing permissions and\n",
"// limitations under the License.\n",
"\n",
"/**\n",
" * @fileoverview Helpers for google.colab Python module.\n",
" */\n",
"(function(scope) {\n",
"function span(text, styleAttributes = {}) {\n",
" const element = document.createElement('span');\n",
" element.textContent = text;\n",
" for (const key of Object.keys(styleAttributes)) {\n",
" element.style[key] = styleAttributes[key];\n",
" }\n",
" return element;\n",
"}\n",
"\n",
"// Max number of bytes which will be uploaded at a time.\n",
"const MAX_PAYLOAD_SIZE = 100 * 1024;\n",
"\n",
"function _uploadFiles(inputId, outputId) {\n",
" const steps = uploadFilesStep(inputId, outputId);\n",
" const outputElement = document.getElementById(outputId);\n",
" // Cache steps on the outputElement to make it available for the next call\n",
" // to uploadFilesContinue from Python.\n",
" outputElement.steps = steps;\n",
"\n",
" return _uploadFilesContinue(outputId);\n",
"}\n",
"\n",
"// This is roughly an async generator (not supported in the browser yet),\n",
"// where there are multiple asynchronous steps and the Python side is going\n",
"// to poll for completion of each step.\n",
"// This uses a Promise to block the python side on completion of each step,\n",
"// then passes the result of the previous step as the input to the next step.\n",
"function _uploadFilesContinue(outputId) {\n",
" const outputElement = document.getElementById(outputId);\n",
" const steps = outputElement.steps;\n",
"\n",
" const next = steps.next(outputElement.lastPromiseValue);\n",
" return Promise.resolve(next.value.promise).then((value) => {\n",
" // Cache the last promise value to make it available to the next\n",
" // step of the generator.\n",
" outputElement.lastPromiseValue = value;\n",
" return next.value.response;\n",
" });\n",
"}\n",
"\n",
"/**\n",
" * Generator function which is called between each async step of the upload\n",
" * process.\n",
" * @param {string} inputId Element ID of the input file picker element.\n",
" * @param {string} outputId Element ID of the output display.\n",
" * @return {!Iterable<!Object>} Iterable of next steps.\n",
" */\n",
"function* uploadFilesStep(inputId, outputId) {\n",
" const inputElement = document.getElementById(inputId);\n",
" inputElement.disabled = false;\n",
"\n",
" const outputElement = document.getElementById(outputId);\n",
" outputElement.innerHTML = '';\n",
"\n",
" const pickedPromise = new Promise((resolve) => {\n",
" inputElement.addEventListener('change', (e) => {\n",
" resolve(e.target.files);\n",
" });\n",
" });\n",
"\n",
" const cancel = document.createElement('button');\n",
" inputElement.parentElement.appendChild(cancel);\n",
" cancel.textContent = 'Cancel upload';\n",
" const cancelPromise = new Promise((resolve) => {\n",
" cancel.onclick = () => {\n",
" resolve(null);\n",
" };\n",
" });\n",
"\n",
" // Wait for the user to pick the files.\n",
" const files = yield {\n",
" promise: Promise.race([pickedPromise, cancelPromise]),\n",
" response: {\n",
" action: 'starting',\n",
" }\n",
" };\n",
"\n",
" cancel.remove();\n",
"\n",
" // Disable the input element since further picks are not allowed.\n",
" inputElement.disabled = true;\n",
"\n",
" if (!files) {\n",
" return {\n",
" response: {\n",
" action: 'complete',\n",
" }\n",
" };\n",
" }\n",
"\n",
" for (const file of files) {\n",
" const li = document.createElement('li');\n",
" li.append(span(file.name, {fontWeight: 'bold'}));\n",
" li.append(span(\n",
" `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n",
" `last modified: ${\n",
" file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n",
" 'n/a'} - `));\n",
" const percent = span('0% done');\n",
" li.appendChild(percent);\n",
"\n",
" outputElement.appendChild(li);\n",
"\n",
" const fileDataPromise = new Promise((resolve) => {\n",
" const reader = new FileReader();\n",
" reader.onload = (e) => {\n",
" resolve(e.target.result);\n",
" };\n",
" reader.readAsArrayBuffer(file);\n",
" });\n",
" // Wait for the data to be ready.\n",
" let fileData = yield {\n",
" promise: fileDataPromise,\n",
" response: {\n",
" action: 'continue',\n",
" }\n",
" };\n",
"\n",
" // Use a chunked sending to avoid message size limits. See b/62115660.\n",
" let position = 0;\n",
" do {\n",
" const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n",
" const chunk = new Uint8Array(fileData, position, length);\n",
" position += length;\n",
"\n",
" const base64 = btoa(String.fromCharCode.apply(null, chunk));\n",
" yield {\n",
" response: {\n",
" action: 'append',\n",
" file: file.name,\n",
" data: base64,\n",
" },\n",
" };\n",
"\n",
" let percentDone = fileData.byteLength === 0 ?\n",
" 100 :\n",
" Math.round((position / fileData.byteLength) * 100);\n",
" percent.textContent = `${percentDone}% done`;\n",
"\n",
" } while (position < fileData.byteLength);\n",
" }\n",
"\n",
" // All done.\n",
" yield {\n",
" response: {\n",
" action: 'complete',\n",
" }\n",
" };\n",
"}\n",
"\n",
"scope.google = scope.google || {};\n",
"scope.google.colab = scope.google.colab || {};\n",
"scope.google.colab._files = {\n",
" _uploadFiles,\n",
" _uploadFilesContinue,\n",
"};\n",
"})(self);\n",
"</script> "
]
},
"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": [
"<IPython.core.display.HTML object>"
],
"text/html": [
"<div><iframe src=\"https://0b58124b323893b4d0.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
]
},
"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",
" <input type=\"file\" id=\"files-58b75fb6-d2ef-4c0f-9173-8ba3c9d66e40\" name=\"files[]\" multiple disabled\n",
" style=\"border:none\" />\n",
" <output id=\"result-58b75fb6-d2ef-4c0f-9173-8ba3c9d66e40\">\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",
" </output>\n",
" <script>// Copyright 2017 Google LLC\n",
"//\n",
"// Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"// you may not use this file except in compliance with the License.\n",
"// You may obtain a copy of the License at\n",
"//\n",
"// http://www.apache.org/licenses/LICENSE-2.0\n",
"//\n",
"// Unless required by applicable law or agreed to in writing, software\n",
"// distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"// See the License for the specific language governing permissions and\n",
"// limitations under the License.\n",
"\n",
"/**\n",
" * @fileoverview Helpers for google.colab Python module.\n",
" */\n",
"(function(scope) {\n",
"function span(text, styleAttributes = {}) {\n",
" const element = document.createElement('span');\n",
" element.textContent = text;\n",
" for (const key of Object.keys(styleAttributes)) {\n",
" element.style[key] = styleAttributes[key];\n",
" }\n",
" return element;\n",
"}\n",
"\n",
"// Max number of bytes which will be uploaded at a time.\n",
"const MAX_PAYLOAD_SIZE = 100 * 1024;\n",
"\n",
"function _uploadFiles(inputId, outputId) {\n",
" const steps = uploadFilesStep(inputId, outputId);\n",
" const outputElement = document.getElementById(outputId);\n",
" // Cache steps on the outputElement to make it available for the next call\n",
" // to uploadFilesContinue from Python.\n",
" outputElement.steps = steps;\n",
"\n",
" return _uploadFilesContinue(outputId);\n",
"}\n",
"\n",
"// This is roughly an async generator (not supported in the browser yet),\n",
"// where there are multiple asynchronous steps and the Python side is going\n",
"// to poll for completion of each step.\n",
"// This uses a Promise to block the python side on completion of each step,\n",
"// then passes the result of the previous step as the input to the next step.\n",
"function _uploadFilesContinue(outputId) {\n",
" const outputElement = document.getElementById(outputId);\n",
" const steps = outputElement.steps;\n",
"\n",
" const next = steps.next(outputElement.lastPromiseValue);\n",
" return Promise.resolve(next.value.promise).then((value) => {\n",
" // Cache the last promise value to make it available to the next\n",
" // step of the generator.\n",
" outputElement.lastPromiseValue = value;\n",
" return next.value.response;\n",
" });\n",
"}\n",
"\n",
"/**\n",
" * Generator function which is called between each async step of the upload\n",
" * process.\n",
" * @param {string} inputId Element ID of the input file picker element.\n",
" * @param {string} outputId Element ID of the output display.\n",
" * @return {!Iterable<!Object>} Iterable of next steps.\n",
" */\n",
"function* uploadFilesStep(inputId, outputId) {\n",
" const inputElement = document.getElementById(inputId);\n",
" inputElement.disabled = false;\n",
"\n",
" const outputElement = document.getElementById(outputId);\n",
" outputElement.innerHTML = '';\n",
"\n",
" const pickedPromise = new Promise((resolve) => {\n",
" inputElement.addEventListener('change', (e) => {\n",
" resolve(e.target.files);\n",
" });\n",
" });\n",
"\n",
" const cancel = document.createElement('button');\n",
" inputElement.parentElement.appendChild(cancel);\n",
" cancel.textContent = 'Cancel upload';\n",
" const cancelPromise = new Promise((resolve) => {\n",
" cancel.onclick = () => {\n",
" resolve(null);\n",
" };\n",
" });\n",
"\n",
" // Wait for the user to pick the files.\n",
" const files = yield {\n",
" promise: Promise.race([pickedPromise, cancelPromise]),\n",
" response: {\n",
" action: 'starting',\n",
" }\n",
" };\n",
"\n",
" cancel.remove();\n",
"\n",
" // Disable the input element since further picks are not allowed.\n",
" inputElement.disabled = true;\n",
"\n",
" if (!files) {\n",
" return {\n",
" response: {\n",
" action: 'complete',\n",
" }\n",
" };\n",
" }\n",
"\n",
" for (const file of files) {\n",
" const li = document.createElement('li');\n",
" li.append(span(file.name, {fontWeight: 'bold'}));\n",
" li.append(span(\n",
" `(${file.type || 'n/a'}) - ${file.size} bytes, ` +\n",
" `last modified: ${\n",
" file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() :\n",
" 'n/a'} - `));\n",
" const percent = span('0% done');\n",
" li.appendChild(percent);\n",
"\n",
" outputElement.appendChild(li);\n",
"\n",
" const fileDataPromise = new Promise((resolve) => {\n",
" const reader = new FileReader();\n",
" reader.onload = (e) => {\n",
" resolve(e.target.result);\n",
" };\n",
" reader.readAsArrayBuffer(file);\n",
" });\n",
" // Wait for the data to be ready.\n",
" let fileData = yield {\n",
" promise: fileDataPromise,\n",
" response: {\n",
" action: 'continue',\n",
" }\n",
" };\n",
"\n",
" // Use a chunked sending to avoid message size limits. See b/62115660.\n",
" let position = 0;\n",
" do {\n",
" const length = Math.min(fileData.byteLength - position, MAX_PAYLOAD_SIZE);\n",
" const chunk = new Uint8Array(fileData, position, length);\n",
" position += length;\n",
"\n",
" const base64 = btoa(String.fromCharCode.apply(null, chunk));\n",
" yield {\n",
" response: {\n",
" action: 'append',\n",
" file: file.name,\n",
" data: base64,\n",
" },\n",
" };\n",
"\n",
" let percentDone = fileData.byteLength === 0 ?\n",
" 100 :\n",
" Math.round((position / fileData.byteLength) * 100);\n",
" percent.textContent = `${percentDone}% done`;\n",
"\n",
" } while (position < fileData.byteLength);\n",
" }\n",
"\n",
" // All done.\n",
" yield {\n",
" response: {\n",
" action: 'complete',\n",
" }\n",
" };\n",
"}\n",
"\n",
"scope.google = scope.google || {};\n",
"scope.google.colab = scope.google.colab || {};\n",
"scope.google.colab._files = {\n",
" _uploadFiles,\n",
" _uploadFilesContinue,\n",
"};\n",
"})(self);\n",
"</script> "
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"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"
]
}
]
}
]
} |