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
}