Spaces:
Sleeping
Sleeping
File size: 30,891 Bytes
21885f8 | 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 | {
"cells": [
{
"cell_type": "code",
"execution_count": 4,
"id": "ea9b6ff2",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"==================================================\n",
"π TESTING NITROSENSE AI APPLICATION\n",
"==================================================\n",
"\n",
"π Test 1: Checking folder structure...\n",
" β
models folder exists\n",
" β
utils folder exists\n",
" β
templates folder exists\n",
" β
static folder exists\n",
" β
u2net folder exists\n",
" β
u2net/weights folder exists\n",
" β
u2net/model folder exists\n",
" β
static/uploads folder exists\n",
"\n",
"π Test 2: Checking required files...\n",
" β
models\\Pyramid_fusion_densenet121_model.h5 exists (59.70 MB)\n",
" β
utils\\background_removal.py exists\n",
" β
utils\\edge_detection.py exists\n",
" β
utils\\preprocessing.py exists\n",
" β
utils/scalers\\scaler_y.pkl exists\n",
" β
utils/scalers\\continuous_scaler.pkl exists\n",
" β
utils/scalers\\days_scaler.pkl exists\n",
" β
utils/scalers\\nitrogen_map.pkl exists\n",
" β
utils\\temperature_means.pkl exists\n",
" β
templates\\index.html exists\n",
" β
templates\\estimation.html exists\n",
" β
templates\\about.html exists\n",
" β
templates\\team.html exists\n",
" β
templates\\how-it-works.html exists\n",
" β
templates\\contact.html exists\n",
" β
templates\\capture.html exists\n",
" β
templates\\result.html exists\n",
" β
u2net/weights\\u2net.pth exists (168.12 MB)\n",
"\n",
"π§ Test 3: Testing utility imports...\n",
" β
BackgroundRemover imported\n",
" β
EdgeDetector imported\n",
" β
ImagePreprocessor imported\n",
"\n",
"π Test 4: Testing BackgroundRemover initialization...\n",
"β
U2Net source already present\n",
"β
BackgroundRemover initialized with U2Net model\n",
" β
BackgroundRemover initialized successfully\n",
" β
Background removal works - output shape: (224, 224, 3)\n",
" β
Mask generated - shape: (224, 224)\n",
"\n",
"πΌοΈ Test 5: Testing preprocessing pipeline...\n",
" β
Edge detection works - output shape: (100, 100, 3)\n",
" β
Preprocessor works with target_size=(224, 224) - output shape: (224, 224, 3)\n",
" β
Output range: [1.00, 1.00]\n",
"\n",
"π€ Test 6: Checking model file...\n",
" β
Model file found: models\\Pyramid_fusion_densenet121_model.h5\n",
" π File size: 59.70 MB\n",
" β
Model file is valid HDF5 format\n",
"\n",
"π Test 7: Checking scaler files...\n",
" β
Target scaler loaded successfully\n",
" β
Temperature scaler loaded successfully\n",
" β
Days scaler loaded successfully\n",
" β
Nitrogen map loaded successfully\n",
" β
Temperature means loaded successfully\n",
"\n",
"βοΈ Test 8: Checking Flask app syntax...\n",
" β
Flask app syntax is valid\n",
"\n",
"π Test 9: Checking template files...\n",
" βΉοΈ index.html appears to be a static page (no Jinja syntax)\n",
" βΉοΈ estimation.html appears to be a static page (no Jinja syntax)\n",
" βΉοΈ about.html appears to be a static page (no Jinja syntax)\n",
" βΉοΈ team.html appears to be a static page (no Jinja syntax)\n",
" βΉοΈ how-it-works.html appears to be a static page (no Jinja syntax)\n",
" βΉοΈ contact.html appears to be a static page (no Jinja syntax)\n",
" βΉοΈ capture.html appears to be a static page (no Jinja syntax)\n",
" β
result.html contains Jinja syntax\n",
"\n",
"π§ Test 10: Checking U2Net weights...\n",
" β
U2Net weights found: u2net\\weights\\u2net.pth\n",
" π File size: 168.12 MB\n",
"\n",
"==================================================\n",
"π TEST SUMMARY\n",
"==================================================\n",
"\n",
"β
All folders and files are in place!\n",
"\n",
"π Your NitroSense AI application is ready to run!\n",
"\n",
"β
All critical components present!\n",
"\n",
"==================================================\n",
"π TO RUN THE APPLICATION:\n",
"==================================================\n",
"\n",
"Open a terminal/command prompt and run:\n",
" cd C:\\Users\\HP\\NitroSense-AI\n",
" python app.py\n",
"\n",
"Then open your browser and go to:\n",
" http://localhost:5000\n",
" http://192.168.175.5:5000 (for other devices on same network)\n",
"\n",
"==================================================\n",
"\n",
"==================================================\n",
"π§ͺ TESTING MODEL PREDICTION WITH DUMMY DATA\n",
"==================================================\n",
"Loading model...\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
" File \"app.py\", line 81\n",
" print(\"\n",
" ^\n",
"SyntaxError: unterminated string literal (detected at line 81)\n",
"\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"β
Model loaded successfully\n",
"\n",
"π Model input shapes:\n",
" Input 1: image_input - Shape: (None, 224, 224, 3)\n",
" Input 2: tabular_input - Shape: (None, 4)\n",
"\n",
"π Creating dummy test data with size 224x224...\n",
" Dummy image shape: (1, 224, 224, 3)\n",
" Dummy features shape: (1, 4)\n",
" Dummy features: [0.7880997 0.7509771 0.22307786 0.90968657]\n",
"\n",
"π Making prediction...\n",
"β
Model prediction successful: -1.375976\n",
" Prediction shape: (1, 1)\n",
"\n",
"π Testing with different feature values:\n",
" Test 1 - Features: [0.1 0.1 0. 0.1] β Prediction: -1.174216\n",
" Test 2 - Features: [0.5 0.5 3. 0.5] β Prediction: -0.676204\n",
" Test 3 - Features: [0.9 0.9 7. 0.9] β Prediction: -0.284522\n",
"\n",
"π Testing prediction variation with different features:\n",
" Features [0. 0. 0. 0.] β -1.143696\n",
" Features [0.2 0.2 1. 0.2] β -1.029661\n",
" Features [0.4 0.4 3. 0.4] β -0.645686\n",
" Features [0.6 0.6 5. 0.6] β -0.089085\n",
" Features [0.8 0.8 6. 0.8] β -0.237164\n",
" Features [1. 1. 7. 1.] β -0.312324\n",
"\n",
"β
Model produces varying outputs for different inputs - good!\n",
"\n",
"π Testing denormalization with scaler_y:\n",
" Scaler_y mean: 3.6249, scale: 0.7252\n",
"\n",
"π Denormalized values (should be in range 2-5%):\n",
" Normalized: -1.143696 β Original Nitrogen: 2.80%\n",
" Normalized: -1.029661 β Original Nitrogen: 2.88%\n",
" Normalized: -0.645686 β Original Nitrogen: 3.16%\n",
" Normalized: -0.089085 β Original Nitrogen: 3.56%\n",
" Normalized: -0.237164 β Original Nitrogen: 3.45%\n",
" Normalized: -0.312324 β Original Nitrogen: 3.40%\n",
"\n",
"π Note: After denormalization, values should be in the range 2-5%\n"
]
}
],
"source": [
"# %% [markdown]\n",
"# # Step 8: Test Complete Application\n",
"# ## Verify all components are working\n",
"\n",
"# %%\n",
"import os\n",
"import sys\n",
"import importlib\n",
"import numpy as np\n",
"import traceback\n",
"\n",
"# %%\n",
"print(\"=\"*50)\n",
"print(\"π TESTING NITROSENSE AI APPLICATION\")\n",
"print(\"=\"*50)\n",
"\n",
"# Test 1: Check folder structure\n",
"print(\"\\nπ Test 1: Checking folder structure...\")\n",
"required_folders = ['models', 'utils', 'templates', 'static', 'u2net', 'u2net/weights', 'u2net/model', 'static/uploads']\n",
"all_folders_ok = True\n",
"\n",
"for folder in required_folders:\n",
" if os.path.exists(folder):\n",
" print(f\" β
{folder} folder exists\")\n",
" else:\n",
" print(f\" β {folder} folder missing\")\n",
" all_folders_ok = False\n",
"\n",
"# %%\n",
"# Test 2: Check required files\n",
"print(\"\\nπ Test 2: Checking required files...\")\n",
"\n",
"required_files = [\n",
" ('models', 'Pyramid_fusion_densenet121_model.h5'),\n",
" ('utils', 'background_removal.py'),\n",
" ('utils', 'edge_detection.py'),\n",
" ('utils', 'preprocessing.py'),\n",
" ('utils/scalers', 'scaler_y.pkl'),\n",
" ('utils/scalers', 'continuous_scaler.pkl'),\n",
" ('utils/scalers', 'days_scaler.pkl'),\n",
" ('utils/scalers', 'nitrogen_map.pkl'),\n",
" ('utils', 'temperature_means.pkl'),\n",
" ('templates', 'index.html'),\n",
" ('templates', 'estimation.html'),\n",
" ('templates', 'about.html'),\n",
" ('templates', 'team.html'),\n",
" ('templates', 'how-it-works.html'),\n",
" ('templates', 'contact.html'),\n",
" ('templates', 'capture.html'),\n",
" ('templates', 'result.html'),\n",
" ('u2net/weights', 'u2net.pth'),\n",
"]\n",
"\n",
"all_files_ok = True\n",
"for folder, filename in required_files:\n",
" filepath = os.path.join(folder, filename)\n",
" if os.path.exists(filepath):\n",
" file_size = os.path.getsize(filepath) / (1024 * 1024) if filename.endswith('.pth') or filename.endswith('.h5') else 0\n",
" size_display = f\" ({file_size:.2f} MB)\" if file_size > 0 else \"\"\n",
" print(f\" β
{filepath} exists{size_display}\")\n",
" else:\n",
" print(f\" β {filepath} missing\")\n",
" all_files_ok = False\n",
"\n",
"# %%\n",
"# Test 3: Import utilities\n",
"print(\"\\nπ§ Test 3: Testing utility imports...\")\n",
"\n",
"sys.path.append(os.path.join(os.getcwd(), 'utils'))\n",
"\n",
"try:\n",
" from background_removal import BackgroundRemover\n",
" print(\" β
BackgroundRemover imported\")\n",
"except Exception as e:\n",
" print(f\" β BackgroundRemover import failed: {e}\")\n",
"\n",
"try:\n",
" from edge_detection import EdgeDetector\n",
" print(\" β
EdgeDetector imported\")\n",
"except Exception as e:\n",
" print(f\" β EdgeDetector import failed: {e}\")\n",
"\n",
"try:\n",
" from preprocessing import ImagePreprocessor\n",
" print(\" β
ImagePreprocessor imported\")\n",
"except Exception as e:\n",
" print(f\" β ImagePreprocessor import failed: {e}\")\n",
"\n",
"# %%\n",
"# Test 4: Test BackgroundRemover initialization\n",
"print(\"\\nπ Test 4: Testing BackgroundRemover initialization...\")\n",
"\n",
"try:\n",
" # Test with portable initialization (no path needed)\n",
" bg_remover = BackgroundRemover()\n",
" print(\" β
BackgroundRemover initialized successfully\")\n",
" \n",
" # Test with a dummy image\n",
" dummy_image = np.zeros((100, 100, 3), dtype=np.uint8)\n",
" dummy_image[:] = [100, 150, 200]\n",
" \n",
" result, mask = bg_remover.remove_background(dummy_image, target_size=(224, 224))\n",
" print(f\" β
Background removal works - output shape: {result.shape}\")\n",
" if mask is not None:\n",
" print(f\" β
Mask generated - shape: {mask.shape}\")\n",
" else:\n",
" print(f\" βΉοΈ No mask generated (running in fallback mode)\")\n",
" \n",
"except Exception as e:\n",
" print(f\" β BackgroundRemover test failed: {e}\")\n",
" traceback.print_exc()\n",
"\n",
"# %%\n",
"# Test 5: Quick test of preprocessing pipeline\n",
"print(\"\\nπΌοΈ Test 5: Testing preprocessing pipeline...\")\n",
"\n",
"try:\n",
" # Create a dummy image\n",
" import cv2\n",
" from PIL import Image\n",
" \n",
" dummy_image = np.zeros((100, 100, 3), dtype=np.uint8)\n",
" dummy_image[:] = [100, 150, 200]\n",
" \n",
" # Test edge detection\n",
" edge_detector = EdgeDetector()\n",
" edge_image, edges = edge_detector.detect_edges(dummy_image)\n",
" print(f\" β
Edge detection works - output shape: {edge_image.shape}\")\n",
" \n",
" # Test preprocessor - use 224x224 to match model\n",
" preprocessor = ImagePreprocessor(target_size=(224, 224))\n",
" processed = preprocessor.preprocess_for_model(edge_image)\n",
" print(f\" β
Preprocessor works with target_size=(224, 224) - output shape: {processed.shape}\")\n",
" print(f\" β
Output range: [{processed.min():.2f}, {processed.max():.2f}]\")\n",
" \n",
"except Exception as e:\n",
" print(f\" β Preprocessing test failed: {e}\")\n",
" traceback.print_exc()\n",
"\n",
"# %%\n",
"# Test 6: Check model file\n",
"print(\"\\nπ€ Test 6: Checking model file...\")\n",
"\n",
"model_path = os.path.join('models', 'Pyramid_fusion_densenet121_model.h5')\n",
"if os.path.exists(model_path):\n",
" file_size = os.path.getsize(model_path) / (1024 * 1024) # MB\n",
" print(f\" β
Model file found: {model_path}\")\n",
" print(f\" π File size: {file_size:.2f} MB\")\n",
" \n",
" # Quick model structure check without loading\n",
" try:\n",
" import h5py\n",
" with h5py.File(model_path, 'r') as f:\n",
" print(f\" β
Model file is valid HDF5 format\")\n",
" except Exception as e:\n",
" print(f\" β οΈ Could not verify model file: {e}\")\n",
"else:\n",
" print(f\" β Model file not found at: {model_path}\")\n",
"\n",
"# %%\n",
"# Test 7: Check scaler files\n",
"print(\"\\nπ Test 7: Checking scaler files...\")\n",
"\n",
"try:\n",
" import pickle\n",
" \n",
" scaler_files = [\n",
" ('utils/scalers/scaler_y.pkl', 'Target scaler'),\n",
" ('utils/scalers/continuous_scaler.pkl', 'Temperature scaler'),\n",
" ('utils/scalers/days_scaler.pkl', 'Days scaler'),\n",
" ('utils/scalers/nitrogen_map.pkl', 'Nitrogen map'),\n",
" ('utils/temperature_means.pkl', 'Temperature means')\n",
" ]\n",
" \n",
" for filepath, description in scaler_files:\n",
" if os.path.exists(filepath):\n",
" with open(filepath, 'rb') as f:\n",
" data = pickle.load(f)\n",
" print(f\" β
{description} loaded successfully\")\n",
" else:\n",
" print(f\" β {filepath} missing\")\n",
" \n",
"except Exception as e:\n",
" print(f\" β Scaler test failed: {e}\")\n",
" traceback.print_exc()\n",
"\n",
"# %%\n",
"# Test 8: Check Flask app syntax\n",
"print(\"\\nβοΈ Test 8: Checking Flask app syntax...\")\n",
"\n",
"try:\n",
" import py_compile\n",
" py_compile.compile('app.py')\n",
" print(\" β
Flask app syntax is valid\")\n",
"except Exception as e:\n",
" print(f\" β Flask app syntax error: {e}\")\n",
" traceback.print_exc()\n",
"\n",
"# %%\n",
"# Test 9: Check template files for Jinja syntax\n",
"print(\"\\nπ Test 9: Checking template files...\")\n",
"\n",
"template_files = ['index.html', 'estimation.html', 'about.html', 'team.html', \n",
" 'how-it-works.html', 'contact.html', 'capture.html', 'result.html']\n",
"\n",
"for template in template_files:\n",
" template_path = os.path.join('templates', template)\n",
" if os.path.exists(template_path):\n",
" with open(template_path, 'r', encoding='utf-8') as f:\n",
" content = f.read()\n",
" # Quick check for Jinja syntax\n",
" if '{{' in content and '}}' in content:\n",
" print(f\" β
{template} contains Jinja syntax\")\n",
" else:\n",
" print(f\" βΉοΈ {template} appears to be a static page (no Jinja syntax)\")\n",
" else:\n",
" print(f\" β {template} missing\")\n",
"\n",
"# %%\n",
"# Test 10: Check U2Net weights\n",
"print(\"\\nπ§ Test 10: Checking U2Net weights...\")\n",
"\n",
"weights_path = os.path.join('u2net', 'weights', 'u2net.pth')\n",
"if os.path.exists(weights_path):\n",
" file_size = os.path.getsize(weights_path) / (1024 * 1024) # MB\n",
" print(f\" β
U2Net weights found: {weights_path}\")\n",
" print(f\" π File size: {file_size:.2f} MB\")\n",
"else:\n",
" print(f\" β οΈ U2Net weights not found at: {weights_path}\")\n",
" print(\" Background removal will run in fallback mode\")\n",
"\n",
"# %%\n",
"# Summary\n",
"print(\"\\n\" + \"=\"*50)\n",
"print(\"π TEST SUMMARY\")\n",
"print(\"=\"*50)\n",
"\n",
"if all_folders_ok and all_files_ok:\n",
" print(\"\\nβ
All folders and files are in place!\")\n",
" print(\"\\nπ Your NitroSense AI application is ready to run!\")\n",
"else:\n",
" print(\"\\nβ οΈ Some files/folders are missing. Check the β marks above.\")\n",
"\n",
"# Check if any critical components are missing\n",
"critical_missing = []\n",
"if not os.path.exists('models/Pyramid_fusion_densenet121_model.h5'):\n",
" critical_missing.append(\"Model file\")\n",
"if not os.path.exists('utils/background_removal.py'):\n",
" critical_missing.append(\"Background remover\")\n",
"if not os.path.exists('templates/index.html'):\n",
" critical_missing.append(\"Templates\")\n",
"\n",
"if critical_missing:\n",
" print(\"\\nβ Critical components missing:\")\n",
" for item in critical_missing:\n",
" print(f\" - {item}\")\n",
" print(\"\\nPlease fix these before running the application.\")\n",
"else:\n",
" print(\"\\nβ
All critical components present!\")\n",
"\n",
"print(\"\\n\" + \"=\"*50)\n",
"print(\"π TO RUN THE APPLICATION:\")\n",
"print(\"=\"*50)\n",
"print(\"\\nOpen a terminal/command prompt and run:\")\n",
"print(\" cd C:\\\\Users\\\\HP\\\\NitroSense-AI\")\n",
"print(\" python app.py\")\n",
"print(\"\\nThen open your browser and go to:\")\n",
"print(\" http://localhost:5000\")\n",
"\n",
"# Optional: Print network URL for sharing\n",
"import socket\n",
"hostname = socket.gethostname()\n",
"try:\n",
" local_ip = socket.gethostbyname(hostname)\n",
" print(f\" http://{local_ip}:5000 (for other devices on same network)\")\n",
"except:\n",
" print(\" Could not determine local IP\")\n",
"\n",
"print(\"\\n\" + \"=\"*50)\n",
"\n",
"\n",
"# %% [markdown]\n",
"# # Additional Test: Test Model Prediction with Dummy Data\n",
"\n",
"# %%\n",
"print(\"\\n\" + \"=\"*50)\n",
"print(\"π§ͺ TESTING MODEL PREDICTION WITH DUMMY DATA\")\n",
"print(\"=\"*50)\n",
"\n",
"try:\n",
" import tensorflow as tf\n",
" from tensorflow.keras import backend as K\n",
" import pickle\n",
" \n",
" # ============= DEFINE CUSTOM ACTIVATION FUNCTIONS =============\n",
" def mish_activation(x):\n",
" \"\"\"\n",
" Mish activation function: x * tanh(softplus(x))\n",
" \"\"\"\n",
" return x * tf.math.tanh(tf.math.softplus(x))\n",
" \n",
" def swish_activation(x):\n",
" \"\"\"\n",
" Swish activation function: x * sigmoid(x)\n",
" \"\"\"\n",
" return x * tf.nn.sigmoid(x)\n",
" # ============================================================\n",
" \n",
" # Load the model\n",
" model_path = os.path.join('models', 'Pyramid_fusion_densenet121_model.h5')\n",
" \n",
" # Define custom metrics\n",
" def rmse(y_true, y_pred):\n",
" return K.sqrt(K.mean(K.square(y_pred - y_true)))\n",
" \n",
" def r2(y_true, y_pred):\n",
" SS_res = K.sum(K.square(y_true - y_pred))\n",
" SS_tot = K.sum(K.square(y_true - K.mean(y_true)))\n",
" return 1 - SS_res/(SS_tot + K.epsilon())\n",
" \n",
" def mae(y_true, y_pred):\n",
" return K.mean(K.abs(y_pred - y_true))\n",
" \n",
" # Add custom activation functions to custom_objects\n",
" custom_objects = {\n",
" 'mse': tf.keras.losses.MeanSquaredError(),\n",
" 'MSE': tf.keras.losses.MeanSquaredError(),\n",
" 'mean_squared_error': tf.keras.losses.MeanSquaredError(),\n",
" 'mae': mae,\n",
" 'MAE': mae,\n",
" 'mean_absolute_error': mae,\n",
" 'rmse': rmse,\n",
" 'RMSE': rmse,\n",
" 'root_mean_squared_error': rmse,\n",
" 'r2': r2,\n",
" 'R2': r2,\n",
" 'r_squared': r2,\n",
" 'R_squared': r2,\n",
" # Add custom activation functions\n",
" 'mish_activation': mish_activation,\n",
" 'swish_activation': swish_activation,\n",
" }\n",
" \n",
" # Register custom activations globally (as fallback)\n",
" tf.keras.utils.get_custom_objects()['mish_activation'] = mish_activation\n",
" tf.keras.utils.get_custom_objects()['swish_activation'] = swish_activation\n",
" \n",
" # Load model\n",
" print(\"Loading model...\")\n",
" model = tf.keras.models.load_model(model_path, custom_objects=custom_objects, compile=False)\n",
" print(\"β
Model loaded successfully\")\n",
" \n",
" # Print model input shapes to verify\n",
" print(\"\\nπ Model input shapes:\")\n",
" for i, input_layer in enumerate(model.inputs):\n",
" print(f\" Input {i+1}: {input_layer.name} - Shape: {input_layer.shape}\")\n",
" \n",
" # Create dummy test data with CORRECT size (224x224 for DenseNet121)\n",
" print(\"\\nπ Creating dummy test data with size 224x224...\")\n",
" dummy_image = np.random.rand(1, 224, 224, 3).astype(np.float32)\n",
" dummy_features = np.random.rand(1, 4).astype(np.float32)\n",
" \n",
" print(f\" Dummy image shape: {dummy_image.shape}\")\n",
" print(f\" Dummy features shape: {dummy_features.shape}\")\n",
" print(f\" Dummy features: {dummy_features[0]}\")\n",
" \n",
" # Make prediction\n",
" print(\"\\nπ Making prediction...\")\n",
" prediction = model.predict([dummy_image, dummy_features], verbose=0)\n",
" print(f\"β
Model prediction successful: {prediction[0][0]:.6f}\")\n",
" print(f\" Prediction shape: {prediction.shape}\")\n",
" \n",
" # Test with different feature values to see if output changes\n",
" print(\"\\nπ Testing with different feature values:\")\n",
" \n",
" test_features = [\n",
" np.array([[0.1, 0.1, 0, 0.1]], dtype=np.float32),\n",
" np.array([[0.5, 0.5, 3, 0.5]], dtype=np.float32),\n",
" np.array([[0.9, 0.9, 7, 0.9]], dtype=np.float32)\n",
" ]\n",
" \n",
" for i, features in enumerate(test_features):\n",
" pred = model.predict([dummy_image, features], verbose=0)\n",
" print(f\" Test {i+1} - Features: {features[0]} β Prediction: {pred[0][0]:.6f}\")\n",
" \n",
" # Test with multiple feature variations to check if model responds to inputs\n",
" print(\"\\nπ Testing prediction variation with different features:\")\n",
" feature_sets = [\n",
" np.array([[0.0, 0.0, 0, 0.0]], dtype=np.float32),\n",
" np.array([[0.2, 0.2, 1, 0.2]], dtype=np.float32),\n",
" np.array([[0.4, 0.4, 3, 0.4]], dtype=np.float32),\n",
" np.array([[0.6, 0.6, 5, 0.6]], dtype=np.float32),\n",
" np.array([[0.8, 0.8, 6, 0.8]], dtype=np.float32),\n",
" np.array([[1.0, 1.0, 7, 1.0]], dtype=np.float32)\n",
" ]\n",
" \n",
" predictions = []\n",
" for features in feature_sets:\n",
" pred = model.predict([dummy_image, features], verbose=0)[0][0]\n",
" predictions.append(pred)\n",
" print(f\" Features {features[0]} β {pred:.6f}\")\n",
" \n",
" # Check if all predictions are the same\n",
" if len(set(predictions)) == 1:\n",
" print(\"\\nβ οΈ WARNING: All predictions are identical! Model might not be working correctly.\")\n",
" else:\n",
" print(\"\\nβ
Model produces varying outputs for different inputs - good!\")\n",
" \n",
" # Test with scaler_y if available\n",
" try:\n",
" scaler_y_path = os.path.join('utils/scalers', 'scaler_y.pkl')\n",
" if os.path.exists(scaler_y_path):\n",
" with open(scaler_y_path, 'rb') as f:\n",
" scaler_y = pickle.load(f)\n",
" print(f\"\\nπ Testing denormalization with scaler_y:\")\n",
" print(f\" Scaler_y mean: {scaler_y.mean_[0]:.4f}, scale: {scaler_y.scale_[0]:.4f}\")\n",
" \n",
" # Denormalize the predictions\n",
" pred_array = np.array([[p] for p in predictions])\n",
" original_values = scaler_y.inverse_transform(pred_array)\n",
" print(f\"\\nπ Denormalized values (should be in range 2-5%):\")\n",
" for i, (norm, orig) in enumerate(zip(predictions, original_values)):\n",
" print(f\" Normalized: {norm:.6f} β Original Nitrogen: {orig[0]:.2f}%\")\n",
" except Exception as e:\n",
" print(f\" Could not test denormalization: {e}\")\n",
" \n",
" # Compare with the sample prediction from model testing\n",
" print(f\"\\nπ Note: After denormalization, values should be in the range 2-5%\")\n",
" \n",
"except Exception as e:\n",
" print(f\"β Model test failed: {e}\")\n",
" traceback.print_exc()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "feed142c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"==================================================\n",
"π U2Net DIAGNOSTIC\n",
"==================================================\n",
"\n",
"π Checking directories:\n",
" u2net_dir exists: True\n",
" model_dir exists: True\n",
" weights_dir exists: True\n",
"\n",
"π Checking u2net.py:\n",
" Path: u2net\\model\\u2net.py\n",
" Exists: True\n",
" Size: 14.37 KB\n",
"\n",
"βοΈ Checking weights:\n",
" Path: u2net\\weights\\u2net.pth\n",
" Exists: True\n",
" Size: 168.12 MB\n",
"\n",
"π Trying to import U2Net module:\n",
" β
Successfully imported U2NET\n",
" U2NET type: <class 'type'>\n",
"\n",
"π Initializing BackgroundRemover:\n",
"β
U2Net source already present\n",
"β
BackgroundRemover initialized with U2Net model\n",
" u2net_available: True\n",
" model loaded: True\n"
]
}
],
"source": [
"# Diagnostic for U2Net\n",
"print(\"=\"*50)\n",
"print(\"π U2Net DIAGNOSTIC\")\n",
"print(\"=\"*50)\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"# Check if u2net directory exists\n",
"u2net_dir = 'u2net'\n",
"model_dir = os.path.join(u2net_dir, 'model')\n",
"weights_dir = os.path.join(u2net_dir, 'weights')\n",
"\n",
"print(f\"\\nπ Checking directories:\")\n",
"print(f\" u2net_dir exists: {os.path.exists(u2net_dir)}\")\n",
"print(f\" model_dir exists: {os.path.exists(model_dir)}\")\n",
"print(f\" weights_dir exists: {os.path.exists(weights_dir)}\")\n",
"\n",
"# Check for u2net.py\n",
"u2net_py = os.path.join(model_dir, 'u2net.py')\n",
"print(f\"\\nπ Checking u2net.py:\")\n",
"print(f\" Path: {u2net_py}\")\n",
"print(f\" Exists: {os.path.exists(u2net_py)}\")\n",
"if os.path.exists(u2net_py):\n",
" file_size = os.path.getsize(u2net_py) / 1024\n",
" print(f\" Size: {file_size:.2f} KB\")\n",
"\n",
"# Check for weights\n",
"weights_path = os.path.join(weights_dir, 'u2net.pth')\n",
"print(f\"\\nβοΈ Checking weights:\")\n",
"print(f\" Path: {weights_path}\")\n",
"print(f\" Exists: {os.path.exists(weights_path)}\")\n",
"if os.path.exists(weights_path):\n",
" file_size = os.path.getsize(weights_path) / (1024 * 1024)\n",
" print(f\" Size: {file_size:.2f} MB\")\n",
"\n",
"# Try to import\n",
"print(f\"\\nπ Trying to import U2Net module:\")\n",
"sys.path.insert(0, os.path.abspath(model_dir))\n",
"try:\n",
" from u2net import U2NET\n",
" print(f\" β
Successfully imported U2NET\")\n",
" print(f\" U2NET type: {type(U2NET)}\")\n",
"except Exception as e:\n",
" print(f\" β Import failed: {e}\")\n",
"\n",
"# Initialize BackgroundRemover with verbose output\n",
"print(f\"\\nπ Initializing BackgroundRemover:\")\n",
"from utils.background_removal import BackgroundRemover\n",
"bg_remover = BackgroundRemover()\n",
"print(f\" u2net_available: {bg_remover.u2net_available}\")\n",
"print(f\" model loaded: {bg_remover.model is not None}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a0274133",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|