File size: 22,667 Bytes
fb24e2a
 
 
2c2645a
fb24e2a
 
2c2645a
fb24e2a
2c2645a
 
fb24e2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c2645a
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
---
title: Potato_Diseases_Detection_with_Deep_Learning
emoji: ๐Ÿจ
colorFrom: red
colorTo: blue
sdk: docker
pinned: true
license: apache-2.0
thumbnail: >-
  https://cdn-uploads.huggingface.co/production/uploads/68650ad8b3fa513b48afad7f/2dUQzI09CvADaIJX_pPeE.png
---





# ๐Ÿฅ” Potato Skin Disease Detection Using Deep Learning

[![Python](https://img.shields.io/badge/Python-3.8+-blue.svg)](https://www.python.org/)
[![TensorFlow](https://img.shields.io/badge/TensorFlow-2.x-orange.svg)](https://tensorflow.org/)
[![Keras](https://img.shields.io/badge/Keras-2.x-red.svg)](https://keras.io/)
[![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)

> ๐Ÿ”ฌ An AI-powered computer vision system for detecting and classifying potato skin diseases using deep learning techniques.

## ๐Ÿ“‹ Table of Contents

- [๐ŸŽฏ Project Overview](#-project-overview)
- [๐ŸŒŸ Features](#-features)
- [๐Ÿ“Š Dataset](#-dataset)
- [๐Ÿš€ Getting Started](#-getting-started)
- [๐Ÿ’ป Usage](#-usage)
- [๐Ÿ—๏ธ Model Architecture](#-model-architecture)
- [๐Ÿ“ˆ Results](#-results)
- [๐Ÿš€ Next Steps](#-Next-Steps)
- [๐Ÿ“„ License](#-license)

## ๐ŸŽฏ Project Overview

This project implements a **Convolutional Neural Network (CNN)** using TensorFlow/Keras to automatically detect and classify potato skin diseases from digital images. The system can identify three main categories:

- ๐Ÿƒ **Healthy Potatoes**
- ๐Ÿฆ  **Early Blight Disease**
- ๐Ÿ„ **Late Blight Disease**

### ๐ŸŽฅ Demo

<details>
<summary>Click to see sample predictions</summary>

```
Input: potato_image.jpg
Output: "Early Blight Disease" (Confidence: 94.2%)
```

</details>

## ๐ŸŒŸ Features

- โœ… **Multi-class Classification**: Detects 3 types of potato conditions
- โœ… **Data Augmentation**: Improves model robustness with image transformations
- โœ… **Interactive Visualization**: Displays sample images with predictions
- โœ… **Optimized Performance**: Uses caching and prefetching for faster training
- โœ… **Scalable Architecture**: Easy to extend to more disease types
- โœ… **Real-time Inference**: Fast prediction on new images

## ๐Ÿ“Š Dataset

### ๐Ÿ“ˆ Dataset Statistics

- **Total Images**: 2,152
- **Classes**: 3 (Early Blight, Late Blight, Healthy)
- **Image Size**: 256ร—256 pixels
- **Color Channels**: RGB (3 channels)
- **Data Split**: 80% Train, 10% Validation, 10% Test

## ๐Ÿ“ Project Structure

```
potato-disease-detection/
โ”œโ”€โ”€ ๐Ÿ““ POTATO_Skin_Diseases_Detection_Using_Deep_Learning.ipynb
โ”œโ”€โ”€ ๐Ÿ“„ README.md
โ”œโ”€โ”€ ๐Ÿ“‹ requirements.txt
โ”œโ”€โ”€ ๐Ÿ“ PlantVillage/
โ”‚   โ”œโ”€โ”€ ๐Ÿ“ Potato___Early_blight/
โ”‚   โ”œโ”€โ”€ ๐Ÿ“ Potato___Late_blight/
โ”‚   โ””โ”€โ”€ ๐Ÿ“ Potato___healthy/
โ”œโ”€โ”€ ๐Ÿ“ models/
โ”‚   โ””โ”€โ”€ ๐Ÿ’พ trained_model.h5
โ””โ”€โ”€ ๐Ÿ“ results/
    โ”œโ”€โ”€ ๐Ÿ“Š training_plots.png
    โ””โ”€โ”€ ๐Ÿ“ˆ confusion_matrix.png
```

๐Ÿ“‚ Root Directory/
โ”œโ”€โ”€ ๐Ÿ app.py # Main Flask application
โ”œโ”€โ”€ ๐Ÿ“ฆ requirements.txt # Dependencies
โ”œโ”€โ”€ ๐Ÿš€ run_flask_app.bat # Easy startup script
โ”œโ”€โ”€ ๐Ÿ“š README_Flask.md # Complete documentation
โ”œโ”€โ”€ ๐Ÿ“‚ templates/
โ”‚ โ””โ”€โ”€ ๐ŸŒ index.html # Web interface
โ””โ”€โ”€ ๐Ÿ“‚ static/
โ”œโ”€โ”€ ๐Ÿ“‚ css/
โ”‚ โ””โ”€โ”€ ๐Ÿ’„ style.css # Beautiful styling
โ””โ”€โ”€ ๐Ÿ“‚ js/
โ””โ”€โ”€ โšก script.js # Interactive functionality

## ๐Ÿš€ Getting Started

### ๐Ÿ“‹ Prerequisites

```bash
Python 3.8+
TensorFlow 2.x
Matplotlib
NumPy
```

### โšก Quick Start and Installation

### ๐Ÿ Environment Setup

```bash
# Create virtual environment
python -m venv potato_env

# Activate environment
# Windows:
potato_env\Scripts\activate
# macOS/Linux:
source potato_env/bin/activate

# Install packages
pip install -r requirements.txt
```

# Run Application

#### **Step 1: Install Dependencies**

```cmd
pip install -r requirements.txt
```

#### **Step 2: Run the Application**

```cmd
python app.py
```

#### **Step 3: Open Your Browser**

- **Main App**: http://localhost:5000
- **Health Check**: http://localhost:5000/health

## ๐Ÿ’ป Usage

### ๐Ÿ”ง Training the Model

The notebook includes the complete pipeline:

1. **Data Loading & Preprocessing**

   ```python
   # Load dataset
   dataset = tf.keras.preprocessing.image_dataset_from_directory(
       "PlantVillage",
       image_size=(256, 256),
       batch_size=32
   )
   ```

2. **Data Augmentation**

   ```python
   # Apply data augmentation
   data_augmentation = tf.keras.Sequential([
       tf.keras.layers.RandomFlip("horizontal_and_vertical"),
       tf.keras.layers.RandomRotation(0.2)
   ])
   ```

3. **Model Configuration**
   ```python
   IMAGE_SIZE = 256
   BATCH_SIZE = 32
   CHANNELS = 3
   EPOCHS = 50
   ```

### ๐ŸŽฏ Making Predictions

```python
# Load your trained model
model = tf.keras.models.load_model('potato_disease_model.h5')

# Make prediction
prediction = model.predict(new_image)
predicted_class = class_names[np.argmax(prediction)]
```

## ๐Ÿ—๏ธ Model Architecture

### ๐Ÿง  Network Components

1. **Input Layer**: 256ร—256ร—3 RGB images
2. **Preprocessing**:
   - Image resizing and rescaling (1.0/255)
   - Data augmentation (RandomFlip, RandomRotation)
3. **Feature Extraction**: CNN layers for pattern recognition
4. **Classification**: Dense layers for final prediction

### โš™๏ธ Training Configuration

- **Optimizer**: Adam (recommended)
- **Loss Function**: Sparse Categorical Crossentropy
- **Metrics**: Accuracy
- **Epochs**: 50
- **Batch Size**: 32

## ๐Ÿ“ˆ Results

### ๐Ÿ“Š Performance Metrics

| Metric              | Score |
| ------------------- | ----- |
| Training Accuracy   | XX.X% |
| Validation Accuracy | XX.X% |
| Test Accuracy       | XX.X% |
| F1-Score            | XX.X% |

### ๐ŸŽจ Visualization

The notebook includes:

- โœ… Sample image visualization
- โœ… Training/validation loss curves
- โœ… Confusion matrix
- โœ… Class-wise accuracy

# ๐Ÿฅ” Potato Disease Detection - Flask Web Application

A modern Flask web application for detecting potato diseases using deep learning. Upload images or use your camera to get instant disease predictions with confidence scores and treatment recommendations.

## โœจ Features

### ๐Ÿ–ผ๏ธ **Dual Input Methods**

- **๐Ÿ“ File Upload**: Drag & drop or browse to select images
- **๐Ÿ“ธ Camera Capture**: Take photos directly from your device camera

### ๐Ÿง  **AI-Powered Detection**

- **๐ŸŽฏ Accurate Predictions**: Uses trained CNN model for disease detection
- **๐Ÿ“Š Confidence Scores**: Shows prediction confidence with color-coded badges
- **๐Ÿ“ˆ Probability Breakdown**: Displays probabilities for all disease classes

### ๐Ÿ’ก **Smart Recommendations**

- **๐Ÿฅ Treatment Advice**: Provides specific recommendations for each condition
- **๐Ÿšจ Urgency Levels**: Different advice based on disease severity
- **๐Ÿ“‹ Downloadable Reports**: Generate and download analysis reports

### ๐ŸŽจ **Modern Interface**

- **๐Ÿ“ฑ Responsive Design**: Works perfectly on mobile and desktop
- **๐ŸŒŸ Beautiful UI**: Modern design with smooth animations
- **๐Ÿ”„ Real-time Analysis**: Instant predictions with loading indicators

## ๐Ÿฆ  Detected Diseases

1. **๐Ÿ‚ Early Blight** - Common fungal disease affecting potato leaves
2. **๐Ÿ’€ Late Blight** - Serious disease that can destroy entire crops
3. **โœ… Healthy** - No disease detected

## ๐ŸŽฏ How to Use

### **๐Ÿ“ Upload Method**

1. **Select Upload** tab (default)
2. **Drag & drop** an image or **click to browse**
3. **Click "Analyze Disease"** button
4. **View results** with predictions and recommendations

### **๐Ÿ“ธ Camera Method**

1. **Click Camera** tab
2. **Click "Start Camera"** (allow permissions)
3. **Click "Capture Photo"** when ready
4. **Click "Analyze Disease"** button
5. **View results** with predictions and recommendations

### **๐Ÿ“Š Understanding Results**

- **๐ŸŽฏ Primary Diagnosis**: Main prediction with confidence score
- **๐Ÿ“ˆ Probability Breakdown**: All disease probabilities
- **๐Ÿ’ก Recommendations**: Treatment and care advice
- **๐Ÿ“‹ Download Report**: Save results as text file

## ๐Ÿ”ง Technical Details

- **๐Ÿ Backend**: Flask 2.3+ with Python
- **๐Ÿง  AI Model**: TensorFlow/Keras CNN
- **๐Ÿ–ผ๏ธ Image Processing**: PIL/Pillow for preprocessing
- **๐ŸŽจ Frontend**: HTML5, CSS3, Vanilla JavaScript
- **๐Ÿ“ฑ Camera**: WebRTC getUserMedia API
- **๐Ÿ’พ Storage**: Local file system for uploads

## ๐Ÿ“‹ Requirements

- **๐Ÿ Python**: 3.8+ (Recommended: 3.10+)
- **๐Ÿ’ป OS**: Windows, macOS, or Linux
- **๐Ÿง  Memory**: 4GB+ RAM (8GB recommended)
- **๐Ÿ’พ Storage**: ~2GB for dependencies and models
- **๐ŸŒ Browser**: Chrome, Firefox, Safari, Edge (latest versions)

## ๐Ÿ› ๏ธ Troubleshooting

### โŒ **Model Not Loading**

```
Error: Model not loaded! Please check the model file path.
```

**Solution:**

- Ensure `models/1.h5` exists
- Check TensorFlow installation: `pip install tensorflow>=2.13.0`

### โŒ **Camera Not Working**

```
Could not access camera. Please check permissions.
```

**Solution:**

- Allow camera permissions in your browser
- Use HTTPS for camera access (or localhost)
- Check if another app is using the camera

### โŒ **Port Already in Use**

```
Address already in use
```

**Solution:**

- Close other Flask applications
- Change port in `app.py`: `app.run(port=5001)`
- Kill process: `taskkill /f /im python.exe` (Windows)

### โŒ **File Upload Issues**

```
Invalid file type or File too large
```

**Solution:**

- Use supported formats: PNG, JPG, JPEG
- Keep file size under 16MB
- Check image isn't corrupted

## ๐ŸŽจ Customization

### **๐ŸŽฏ Add New Disease Classes**

1. Update `CLASS_NAMES` in `app.py`
2. Add descriptions in `CLASS_DESCRIPTIONS`
3. Update recommendations in `get_recommendations()`
4. Retrain model with new classes

## ๐Ÿ“ฑ Mobile Responsiveness

The application is now **fully responsive** and optimized for mobile devices:

### ๐Ÿ“ฒ Mobile Features:

- โœ… **Touch-friendly interface** with larger touch targets (44px minimum)
- โœ… **Responsive design** that adapts to screen sizes from 320px to desktop
- โœ… **Mobile camera support** with environment (back) camera preference
- โœ… **Optimized image display** for mobile viewports
- โœ… **Landscape/Portrait orientation** support
- โœ… **iOS Safari compatibility** with viewport fixes
- โœ… **Prevent accidental zoom** on form inputs
- โœ… **Touch-optimized drag & drop** for file uploads

### **๐ŸŽจ Modify UI**

- **Colors**: Edit CSS variables in `style.css`
- **Layout**: Modify templates in `templates/`
- **Functionality**: Update JavaScript in `static/js/`

### **โš™๏ธ Configuration**

- **Upload size**: Change `MAX_CONTENT_LENGTH` in `app.py`
- **Image size**: Modify `IMAGE_SIZE` parameter
- **Port**: Update `app.run(port=5000)` line

## ๐Ÿ”’ Security Notes

- **๐Ÿšซ Production Use**: This is for development/research only
- **๐Ÿ” Secret Key**: Change `app.secret_key` for production
- **๐Ÿ“ File Validation**: Only accepts image files
- **๐Ÿ’พ File Cleanup**: Consider automatic cleanup of old uploads

## ๐Ÿ“ˆ Performance Tips

- **๐Ÿ“ธ Image Quality**: Use clear, well-lit potato leaf images
- **๐ŸŽฏ Focus**: Ensure leaves fill most of the frame
- **๐Ÿ“ Size**: Optimal size is 256x256 pixels or larger
- **๐ŸŒŸ Lighting**: Good natural lighting gives best results

## ๐ŸŒ Browser Compatibility

- โœ… **Chrome**: 90+
- โœ… **Firefox**: 88+
- โœ… **Safari**: 14+
- โœ… **Edge**: 90+
- โš ๏ธ **Mobile**: Camera features may vary

## ๐Ÿ“„ API Endpoints

- `GET /` - Main web interface
- `POST /predict` - Upload image prediction
- `POST /predict_camera` - Camera image prediction
- `GET /health` - Application health check

## ๐Ÿค Support

For issues or questions:

1. Check the troubleshooting section above
2. Verify your Python and dependencies versions
3. Ensure model files are in the correct location
4. Test with the provided sample images

---

## ๐Ÿš€ Next Steps

### ๐Ÿ”ฎ Future Enhancements

- [ ] **Model Optimization**: Implement transfer learning with pre-trained models
- [ ] **Web Application**: Create a Flask/Streamlit web interface
- [ ] **Mobile App**: Develop a mobile application for field use
- [ ] **More Diseases**: Expand to detect additional potato diseases
- [ ] **Real-time Detection**: Implement live camera feed processing
- [ ] **API Development**: Create REST API for integration

### ๐ŸŽฏ Improvement Ideas

- [ ] **Hyperparameter Tuning**: Optimize model parameters
- [ ] **Cross-validation**: Implement k-fold cross-validation
- [ ] **Ensemble Methods**: Combine multiple models
- [ ] **Data Balancing**: Handle class imbalance if present

### ๐Ÿ› Bug Reports

If you find a bug, please create an issue with:

- Description of the problem
- Steps to reproduce
- Expected vs actual behavior
- System information

### ๐Ÿ’ก Feature Requests

For new features, please provide:

- Clear description of the feature
- Use case and benefits
- Implementation suggestions```

# ==================DEBUGGING AND TROUBLESHOOTING GUIDE:===========================

# ๐Ÿฅ” Potato Disease Detection - Upload Functionality Guide

## ๐Ÿš€ Quick Start

1. **Run the Application**:

   ```bash
   python app.py
   ```

   Or double-click `run_and_test.bat`

2. **Access the App**:
   - Main app: http://localhost:5000
   - Debug upload page: http://localhost:5000/debug
   - Health check: http://localhost:5000/health

## ๐Ÿ“‹ Testing Upload Functionality

### Step 1: Check System Health

1. Go to http://localhost:5000/debug
2. Click "๐Ÿ” Check System Health"
3. Verify all items show โœ…:
   - Status: healthy
   - Model Loaded: Yes
   - Upload Dir Exists: Yes
   - Upload Dir Writable: Yes

### Step 2: Test Upload Directory

1. Click "๐Ÿ“‚ Test Upload Directory"
2. Should show "Upload directory is working correctly"

### Step 3: Test Image Upload

1. Click "๐Ÿ“ Click here to select an image" or drag an image
2. Select a potato leaf image (JPG, PNG, JPEG)
3. Preview should appear
4. Click "๐Ÿ”ฌ Analyze Disease"
5. Results should show:
   - Disease name and confidence
   - Recommendations
   - The analyzed image displayed

## ๐Ÿ”ง Troubleshooting Upload Issues

### Issue: "No file uploaded" Error

**Solutions:**

1. Ensure you're clicking the upload area or browse link
2. Check browser console for JavaScript errors (F12)
3. Try the debug page: http://localhost:5000/debug
4. **Mobile**: Tap firmly on upload area, wait for file picker

### Issue: File Not Saving

**Solutions:**

1. Check upload directory permissions:
   ```bash
   mkdir static/uploads
   ```
2. Run as administrator if on Windows
3. Check disk space
4. **Mobile**: Ensure stable network connection

### Issue: Camera Not Working (Mobile)

**Solutions:**

1. **Grant camera permissions** when prompted
2. **Use HTTPS** for camera access on mobile (required by browsers)
3. **Check camera availability** - some devices block camera access
4. **Try different browsers** (Chrome/Safari work best)
5. **Close other camera apps** that might be using the camera

### Issue: Touch/Tap Not Working (Mobile)

**Solutions:**

1. **Clear browser cache** and reload
2. **Disable browser zoom** if enabled
3. **Try two-finger tap** if single tap doesn't work
4. **Check touch targets** - buttons should be at least 44px
5. **Restart browser app** on mobile device

### Issue: Image Too Small/Large on Mobile

**Solutions:**

1. **Portrait orientation** usually works better
2. **Pinch to zoom** on images if needed
3. **Landscape mode** available for wider screens
4. **Image auto-resizes** based on screen size

### Issue: Slow Performance on Mobile

**Solutions:**

1. **Close other browser tabs** to free memory
2. **Use smaller image files** (under 5MB recommended)
3. **Ensure good network connection** for uploads
4. **Clear browser cache** regularly
5. **Restart browser** if app becomes unresponsive

### Issue: Model Not Loading

**Solutions:**

1. Verify model file exists: `models/1.h5`
2. Install required packages:
   ```bash
   pip install tensorflow pillow flask
   ```

### Issue: JavaScript Errors

**Solutions:**

1. Clear browser cache (Ctrl+F5)
2. Check browser console (F12)
3. Try a different browser
4. Disable browser extensions

### Issue: Image Not Displaying in Results

**Solutions:**

1. Check browser network tab (F12) for failed requests
2. Verify uploaded file in `static/uploads/` folder
3. Check Flask console for file save errors

## ๐Ÿงช Debug Features

### Console Logging

The JavaScript includes extensive console logging. Open browser developer tools (F12) to see:

- File selection events
- Upload progress
- Server responses
- Error details

### Debug Endpoints

- `/health` - System status
- `/debug/upload-test` - Upload directory test
- `/debug` - Interactive upload test page

### Manual Testing

1. **File Input Test**:

   ```javascript
   document.getElementById("fileInput").click();
   ```

2. **Check Selected File**:

   ```javascript
   console.log(selectedFile);
   ```

3. **Test FormData**:
   ```javascript
   const formData = new FormData();
   formData.append("file", selectedFile);
   console.log([...formData.entries()]);
   ```

## ๐Ÿ’ก Tips for Success

1. **Use supported image formats**: JPG, PNG, JPEG, GIF
2. **Keep file size under 16MB**
3. **Use clear potato leaf images**
4. **Check browser compatibility** (modern browsers work best)
5. **Enable JavaScript**
6. **Allow camera permissions** (for camera capture feature)

## ๐Ÿ†˜ Getting Help

If upload functionality still doesn't work:

1. **Check Flask console output** for error messages
2. **Check browser console** (F12 โ†’ Console tab)
3. **Try the debug page** at `/debug`
4. **Test with different image files**
5. **Restart the Flask app**
6. **Check file permissions** on the upload directory

## ๐ŸŽฏ Expected Results

After successful upload and analysis:

- โœ… Disease classification (Early Blight, Late Blight, or Healthy)
- โœ… Confidence percentage
- โœ… Treatment recommendations
- โœ… Analyzed image displayed in results
- โœ… Timestamp of analysis

# PDF Report Download Upgrade Guide

## ๐ŸŽ‰ New Features Added

### โœจ **PDF Format**

- Professional PDF reports instead of simple text files
- Includes header, footer, tables, and proper formatting
- Company branding and professional layout

### ๐Ÿ“ **Folder Selection**

- Choose where to save your PDF reports
- Modern file picker dialog (supported browsers)
- Automatic fallback to default downloads folder

### ๐ŸŽจ **Enhanced Report Content**

- **Report Header**: Timestamp, analysis method, model version
- **Analyzed Image**: Embedded image (if available)
- **Diagnosis Section**: Disease name, confidence, risk assessment
- **Probability Breakdown**: Table showing all class probabilities
- **Treatment Recommendations**: Numbered list of actionable advice
- **Professional Footer**: Branding and copyright information

## ๐Ÿš€ Installation Requirements

Add to your `requirements.txt`:

```
reportlab>=4.0.0
```

Install the new dependency:

```bash
pip install reportlab>=4.0.0
```

# PDF Generation Troubleshooting Guide

## ๐Ÿ”ง If PDF Generation is Failing

### Quick Fix Steps

1. **Install ReportLab Library**

   ```bash
   pip install reportlab>=4.0.0
   ```

2. **Run Installation Script**

   - **Windows**: Double-click `install_pdf_deps.bat`
   - **Linux/Mac**: Run `bash install_pdf_deps.sh`

3. **Restart the Application**
   ```bash
   python app.py
   ```

### Common Issues and Solutions

#### โŒ **"ReportLab not available" Error**

**Problem**: ReportLab library is not installed.

**Solution**:

```bash
pip install reportlab
# or
pip install reportlab>=4.0.0
```

**Alternative**: Use virtual environment

```bash
python -m venv pdf_env
source pdf_env/bin/activate  # Linux/Mac
# or
pdf_env\Scripts\activate     # Windows
pip install reportlab
```

#### โŒ **"Permission denied" or "Access denied" Errors**

**Problem**: Insufficient permissions to install packages.

**Solutions**:

1. **Use --user flag**:

   ```bash
   pip install --user reportlab
   ```

2. **Run as administrator** (Windows):

   - Right-click Command Prompt โ†’ "Run as administrator"
   - Then run: `pip install reportlab`

3. **Use sudo** (Linux/Mac):
   ```bash
   sudo pip install reportlab
   ```

#### โŒ **"Module not found" Error Despite Installation**

**Problem**: ReportLab installed in different Python environment.

**Solutions**:

1. **Check Python version**:

   ```bash
   python --version
   which python  # Linux/Mac
   where python  # Windows
   ```

2. **Install for specific Python version**:

   ```bash
   python3 -m pip install reportlab
   # or
   python3.9 -m pip install reportlab
   ```

3. **Verify installation**:
   ```bash
   python -c "import reportlab; print('ReportLab available')"
   ```

#### โŒ **PDF Generation Works but Images Missing**

**Problem**: Image files not accessible or corrupted.

**Solutions**:

1. **Check upload folder permissions**:

   ```bash
   ls -la static/uploads/  # Linux/Mac
   dir static\uploads\     # Windows
   ```

2. **Verify image exists**:

   - Check browser developer tools for 404 errors
   - Ensure images are properly saved during upload

3. **Check image format**:
   - Ensure images are JPG, PNG, or supported formats
   - ReportLab may have issues with some image formats

#### โŒ **Client-side PDF Generation Fails**

**Problem**: jsPDF library not loading.

**Solutions**:

1. **Check internet connection** (jsPDF loads from CDN)

2. **Check browser console** for JavaScript errors

#### โŒ **Folder Selection Not Working**

**Problem**: File System Access API not supported.

**Solutions**:

1. **Update browser**:

   - Chrome 86+ or Edge 86+ required for folder selection
   - Firefox and Safari will use default download folder

2. **Enable experimental features** (Chrome):

   - Go to `chrome://flags`
   - Enable "Experimental Web Platform features"

3. **Accept automatic download** to default folder

The system should work with any clear image of a potato plant leaf!

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™ Acknowledgments

- **PlantVillage Dataset**: For providing the potato disease dataset
- **TensorFlow Team**: For the amazing deep learning framework
- **Open Source Community**: For inspiration and resources

## ๐Ÿ“ž Contact

- **Author**: Lucky Sharma
- **Email**: [email protected]
- **LinkedIn**: https://www.linkedin.com/in/lucky-sharma918894599977
- **GitHub**: https://github.com/itsluckysharma01

---

<div align="center">
  <p>โญ Star this repository if you found it helpful!</p>
  <p>๐Ÿ€ Happy coding and may your potatoes be healthy!</p>
</div>
"