Upload 7 files
Browse files- DATASET_GUIDE.md +207 -0
- README.md +18 -0
- class_names.txt +55 -0
- docs/BACKEND_SYSTEM_DOCUMENTATION.md +253 -0
- docs/STANDALONE_HTML_DOCUMENTATION.md +163 -0
- scripts/download_dataset.py +107 -0
- scripts/prepare_dataset.py +193 -0
DATASET_GUIDE.md
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CropGuard GH — Dataset Guide
|
| 2 |
+
|
| 3 |
+
**How to assemble the training dataset for the crop disease detection model.**
|
| 4 |
+
Final Year Project · Oppong David · BTech Computer Technology, Kumasi Technical University
|
| 5 |
+
|
| 6 |
+
---
|
| 7 |
+
|
| 8 |
+
## Read this first (important and honest)
|
| 9 |
+
|
| 10 |
+
There is **no single "CropGuard dataset" file to download.** The model is trained on a *combination* of public, peer-reviewed image datasets, plus any images you collect yourself. This guide tells you exactly which datasets to download, where, under what licence, and how to arrange them into the folder layout the training script expects.
|
| 11 |
+
|
| 12 |
+
Two reasons it works this way:
|
| 13 |
+
|
| 14 |
+
1. **The images are large and third-party.** The datasets below total tens of gigabytes and are published by other researchers under their own licences. They cannot be repackaged here — but every one is free to download from its official repository, linked below.
|
| 15 |
+
2. **"All crops" means "all crops we have data for."** A model can only learn a disease it has seen. The 14 crops / 55 classes are the crops Ghanaian smallholders grow *and* for which labelled images exist. Coverage is uneven (see the **Coverage tier** column) — be honest about this in your report and viva.
|
| 16 |
+
|
| 17 |
+
The single most field-realistic source is the **CCMT dataset**, which was collected on farms in Ghana and covers cashew, cassava, maize and tomato. It is the backbone of this project. Everything else fills gaps.
|
| 18 |
+
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
## 1. Folder layout the training script expects
|
| 22 |
+
|
| 23 |
+
`backend/train.py` loads images with Keras `image_dataset_from_directory`, i.e. one folder per class, split into `train` / `val` / `test`:
|
| 24 |
+
|
| 25 |
+
```
|
| 26 |
+
data/
|
| 27 |
+
├── train/
|
| 28 |
+
│ ├── maize_healthy/ *.jpg
|
| 29 |
+
│ ├── maize_gls/ *.jpg
|
| 30 |
+
│ ├── cassava_cmd/ *.jpg
|
| 31 |
+
│ └── ... (one folder per class)
|
| 32 |
+
├── val/
|
| 33 |
+
│ └── ... (same class folders)
|
| 34 |
+
└── test/
|
| 35 |
+
└── ... (same class folders)
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
- **Folder names must exactly match the 55 class keys** (see `class_names.txt`) — these are the same keys as in `backend/recommendations.json`, so the API can look up treatment advice by predicted class.
|
| 39 |
+
- A 70 / 15 / 15 train/val/test split is assumed (§3.4.3 of the report). `scripts/prepare_dataset.py` does the splitting for you.
|
| 40 |
+
|
| 41 |
+
The 55 classes, by crop:
|
| 42 |
+
|
| 43 |
+
| Crop | Classes |
|
| 44 |
+
|---|---|
|
| 45 |
+
| Maize | `maize_healthy` `maize_gls` `maize_nclb` `maize_rust` `maize_msv` `maize_faw` |
|
| 46 |
+
| Cassava | `cassava_healthy` `cassava_cmd` `cassava_cbsd` `cassava_cbb` |
|
| 47 |
+
| Tomato | `tomato_healthy` `tomato_early` `tomato_late` `tomato_wilt` `tomato_septoria` `tomato_tylcv` |
|
| 48 |
+
| Cocoa | `cocoa_healthy` `cocoa_blackpod` `cocoa_cssvd` `cocoa_capsid` |
|
| 49 |
+
| Cashew | `cashew_healthy` `cashew_anthracnose` `cashew_gumosis` `cashew_leafminer` |
|
| 50 |
+
| Plantain | `plantain_healthy` `plantain_sigatoka` `plantain_bbtv` `plantain_panama` |
|
| 51 |
+
| Yam | `yam_healthy` `yam_anthracnose` `yam_mosaic` |
|
| 52 |
+
| Pepper | `pepper_healthy` `pepper_bacterialspot` `pepper_anthracnose` |
|
| 53 |
+
| Cowpea | `cowpea_healthy` `cowpea_blight` `cowpea_mosaic` `cowpea_cercospora` |
|
| 54 |
+
| Groundnut | `groundnut_healthy` `groundnut_leafspot` `groundnut_rosette` `groundnut_rust` |
|
| 55 |
+
| Rice | `rice_healthy` `rice_blast` `rice_blb` `rice_brownspot` |
|
| 56 |
+
| Okra | `okra_healthy` `okra_yvmv` `okra_leafspot` |
|
| 57 |
+
| Garden Egg | `gardenegg_healthy` `gardenegg_wilt` `gardenegg_leafspot` |
|
| 58 |
+
| Mango | `mango_healthy` `mango_anthracnose` `mango_bacterialspot` |
|
| 59 |
+
|
| 60 |
+
---
|
| 61 |
+
|
| 62 |
+
## 2. The datasets (verified sources)
|
| 63 |
+
|
| 64 |
+
> ⚠️ **Always confirm the licence on each page before any non-research use.** Mendeley Data sets are usually CC BY 4.0; Kaggle competition data is governed by its competition rules. The notes below were accurate at the time of writing — verify on the page.
|
| 65 |
+
|
| 66 |
+
### A. CCMT — Cashew, Cassava, Maize, Tomato (collected in Ghana) ★ primary
|
| 67 |
+
- **Source:** Mendeley Data — *Dataset for Crop Pest and Disease Detection* (Mensah, Akoto-Adjepong, Adu et al., *Data in Brief* 49, 2023, art. 109306).
|
| 68 |
+
- **DOI:** `10.17632/bwh3zbpkpv.1` → https://data.mendeley.com/datasets/bwh3zbpkpv/1 (also mirrored on Kaggle)
|
| 69 |
+
- **Size:** 24,881 raw images (`Raw Data.zip`, ~1.22 GB) and 102,976 augmented images (`CCMT Dataset.zip`, ~6.81 GB). 22 classes across the four crops.
|
| 70 |
+
- **Collected:** University of Energy & Natural Resources, Sunyani, Ghana, Oct–Dec 2022. Field, white, dark and illuminated backgrounds.
|
| 71 |
+
- **Licence:** Mendeley Data (typically CC BY 4.0 — verify).
|
| 72 |
+
- **Folder → class mapping:**
|
| 73 |
+
- Cashew → `Anthracnose`→`cashew_anthracnose`, `Gummosis`→`cashew_gumosis`, `Leaf miner`→`cashew_leafminer`, `Healthy`→`cashew_healthy` (`Red rust` has no CropGuard class — skip or add one)
|
| 74 |
+
- Cassava → `Mosaic`→`cassava_cmd`, `Bacterial blight`→`cassava_cbb`, `Healthy`→`cassava_healthy` (CCMT `Brown spot` and `Green mite` ≠ our classes — skip; CCMT has **no** brown-streak/CBSD, get that from Cassava-Kaggle below)
|
| 75 |
+
- Maize → `Fall armyworm`→`maize_faw`, `Streak virus`→`maize_msv`, `Leaf blight`→`maize_nclb`, `Leaf spot`→`maize_gls`, `Healthy`→`maize_healthy` (CCMT `Grasshopper`, `Leaf beetle` ≠ our classes — skip; **common rust** comes from PlantVillage corn)
|
| 76 |
+
- Tomato → `Leaf blight`→`tomato_late` *(approx.)*, `Leaf curl`→`tomato_tylcv`, `Septoria leaf spot`→`tomato_septoria`, `Verticillium wilt`→`tomato_wilt`, `Healthy`→`tomato_healthy`
|
| 77 |
+
|
| 78 |
+
### B. PlantVillage — tomato, pepper (and cross-checks)
|
| 79 |
+
- **Source:** Hughes & Salathé (2015). Mendeley Data DOI `10.17632/tywbtsjrjv.1`; GitHub `spMohanty/PlantVillage-Dataset`; several Kaggle mirrors (e.g. `abdallahalidev/plantvillage-dataset`).
|
| 80 |
+
- **Size:** ~54,000 lab images, white backgrounds, 14 crops / 26+ classes.
|
| 81 |
+
- **Licence:** free for research (verify the specific mirror).
|
| 82 |
+
- **Folder → class mapping (the crops we keep):**
|
| 83 |
+
- `Tomato___healthy`→`tomato_healthy`, `Tomato___Early_blight`→`tomato_early`, `Tomato___Late_blight`→`tomato_late`, `Tomato___Septoria_leaf_spot`→`tomato_septoria`, `Tomato___Tomato_Yellow_Leaf_Curl_Virus`→`tomato_tylcv`
|
| 84 |
+
- `Pepper,_bell___Bacterial_spot`→`pepper_bacterialspot`, `Pepper,_bell___healthy`→`pepper_healthy`
|
| 85 |
+
- `Corn_(maize)___Common_rust_`→`maize_rust`, `Corn_(maize)___Northern_Leaf_Blight`→`maize_nclb`, `Corn_(maize)___Cercospora…Gray_leaf_spot`→`maize_gls`, `Corn_(maize)___healthy`→`maize_healthy`
|
| 86 |
+
- *(ignore PlantVillage's apple/grape/cherry/etc. — not Ghanaian crops)*
|
| 87 |
+
|
| 88 |
+
### C. Cassava Leaf Disease (Makerere University / Kaggle)
|
| 89 |
+
- **Source:** Kaggle competition `cassava-leaf-disease-classification` (2020).
|
| 90 |
+
- **Size:** ~21,400 labelled field images from Uganda.
|
| 91 |
+
- **Licence:** Kaggle competition rules (research/educational).
|
| 92 |
+
- **Folder → class mapping:** `Cassava Mosaic Disease (CMD)`→`cassava_cmd`, `Cassava Brown Streak Disease (CBSD)`→`cassava_cbsd`, `Cassava Bacterial Blight (CBB)`→`cassava_cbb`, `Healthy`→`cassava_healthy`. **This is your source for `cassava_cbsd`,** which CCMT lacks.
|
| 93 |
+
|
| 94 |
+
### D. MangoLeafBD — mango
|
| 95 |
+
- **Source:** Ahmed et al. (2023), Mendeley Data DOI `10.17632/hxsnvwty3r.1` → https://data.mendeley.com/datasets/hxsnvwty3r/1
|
| 96 |
+
- **Size:** 4,000 images, 8 classes, 500 per class. Bangladesh.
|
| 97 |
+
- **Licence:** CC BY 4.0 (verify).
|
| 98 |
+
- **Folder → class mapping:** `Healthy`→`mango_healthy`, `Anthracnose`→`mango_anthracnose`, `Bacterial Canker`→`mango_bacterialspot` *(approx. — bacterial black spot)*. (Other classes unused.)
|
| 99 |
+
|
| 100 |
+
### E. Rice Leaf Disease Image Samples (Sethy) — rice
|
| 101 |
+
- **Source:** Sethy et al. (2020), Mendeley Data DOI `10.17632/fwcj7stb8r.1` → https://data.mendeley.com/datasets/fwcj7stb8r/1
|
| 102 |
+
- **Size:** 5,932 images. India.
|
| 103 |
+
- **Licence:** CC BY 4.0 (verify).
|
| 104 |
+
- **Folder → class mapping:** `Blast`→`rice_blast`, `Bacterial blight`→`rice_blb`, `Brown Spot`→`rice_brownspot`. (`Tungro` unused.) For `rice_healthy`, add healthy-rice images (e.g. from the Dhan-Shomadhan or RiceLeafs datasets, or your own).
|
| 105 |
+
|
| 106 |
+
### F. Groundnut Leaf Dataset (Sasmal) — groundnut
|
| 107 |
+
- **Source:** Sasmal, Das, Dhal et al. (2024), Mendeley Data DOI `10.17632/x6x5jkk873.2` → https://data.mendeley.com/datasets/x6x5jkk873/2
|
| 108 |
+
- **Size:** 1,720 field images. India.
|
| 109 |
+
- **Licence:** CC BY 4.0 (verify).
|
| 110 |
+
- **Folder → class mapping:** `Healthy`→`groundnut_healthy`, `Leaf spot (early and late)`→`groundnut_leafspot`, `Rust`→`groundnut_rust`, `Rosette`→`groundnut_rosette`. (`Alternaria leaf spot` unused.)
|
| 111 |
+
|
| 112 |
+
### G. Cocoa (KaraAgroAI + Kaggle) — cocoa
|
| 113 |
+
- **CSSVD + healthy + anthracnose:** *KaraAgroAI Cocoa Dataset* (Atuhurra et al., 2024, arXiv:2405.04535) — classes Healthy / CSSVD / Anthracnose → `cocoa_healthy`, `cocoa_cssvd`.
|
| 114 |
+
- **Black pod:** Kaggle *Cocoa Diseases (YOLOv4)* (`serranosebas/enfermedades-cacao-yolov4`) and/or GitHub `Br-Al/Cocoa-diseases` (black pod rot, healthy) → `cocoa_blackpod`.
|
| 115 |
+
- **`cocoa_capsid`:** no good public image set — **collect locally** (COCOBOD/CRIG can advise) or drop the class.
|
| 116 |
+
- **Licence:** verify each (research/educational).
|
| 117 |
+
|
| 118 |
+
### H. BananaLSD — plantain/banana
|
| 119 |
+
- **Source:** Ahmed et al. (2023), *Data in Brief* — BananaLSD (ScienceDirect S2352340923006959; Kaggle mirrors exist).
|
| 120 |
+
- **Size:** 937 images + ~1,600 augmented, classes Sigatoka / Cordana / Pestalotiopsis / Healthy. Bangladesh.
|
| 121 |
+
- **Folder → class mapping:** `Sigatoka`→`plantain_sigatoka` *(approx. black sigatoka)*, `Healthy`→`plantain_healthy`.
|
| 122 |
+
- **`plantain_bbtv` (bunchy top) and `plantain_panama` (Fusarium wilt):** not in BananaLSD — **collect locally** or source separately.
|
| 123 |
+
|
| 124 |
+
### I. Crops with little/no dedicated public dataset — collect locally
|
| 125 |
+
These Ghanaian crops/classes have weak public coverage. Plan to photograph them in the field (extension officers, research stations, and the crops themselves are the source). Until then, the model will be unreliable on them and you should say so:
|
| 126 |
+
|
| 127 |
+
- **Cowpea** — `cowpea_healthy` `cowpea_blight` `cowpea_mosaic` `cowpea_cercospora`
|
| 128 |
+
- **Yam** — `yam_healthy` `yam_anthracnose` `yam_mosaic`
|
| 129 |
+
- **Okra** — `okra_healthy` `okra_yvmv` `okra_leafspot`
|
| 130 |
+
- **Garden Egg** — `gardenegg_healthy` `gardenegg_wilt` `gardenegg_leafspot`
|
| 131 |
+
- **Pepper** — `pepper_anthracnose` (chili-anthracnose sets exist on Kaggle; pepper bacterial spot + healthy come from PlantVillage)
|
| 132 |
+
|
| 133 |
+
---
|
| 134 |
+
|
| 135 |
+
## 3. Coverage tiers (put this in your report)
|
| 136 |
+
|
| 137 |
+
| Tier | Meaning | Crops / classes |
|
| 138 |
+
|---|---|---|
|
| 139 |
+
| **Strong (Ghana field data)** | Collected in Ghana, field-realistic | cashew, cassava, maize, tomato (via CCMT + Cassava-Kaggle) |
|
| 140 |
+
| **Good (non-Ghana public data)** | Solid labelled images, but a domain/region gap | mango, rice, groundnut, cocoa (CSSVD/black pod), plantain (sigatoka), pepper (bacterial spot) |
|
| 141 |
+
| **Weak (little/no public data)** | Needs locally collected images to be usable | cowpea, yam, okra, garden egg, plantain bbtv/panama, cocoa capsid, pepper anthracnose |
|
| 142 |
+
|
| 143 |
+
This is why `train.py` reports the **real** held-out test accuracy at the end of training rather than assuming the ~98% target: accuracy will be high on the well-covered crops and lower on the weak ones until you add local images. The ~98% figure is consistent with the literature on this kind of benchmark (Mohanty et al. 2016 = 99.35%; Ferentinos 2018 = 99.53%) but must be *earned* on your test set, not declared.
|
| 144 |
+
|
| 145 |
+
---
|
| 146 |
+
|
| 147 |
+
## 4. How to download
|
| 148 |
+
|
| 149 |
+
### Option 1 — Kaggle CLI (fastest for the Kaggle-hosted sets)
|
| 150 |
+
```bash
|
| 151 |
+
pip install kaggle # then put kaggle.json in ~/.kaggle/
|
| 152 |
+
kaggle competitions download -c cassava-leaf-disease-classification
|
| 153 |
+
kaggle datasets download -d abdallahalidev/plantvillage-dataset
|
| 154 |
+
kaggle datasets download -d serranosebas/enfermedades-cacao-yolov4
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
### Option 2 — Mendeley Data (CCMT, MangoLeafBD, Rice, Groundnut)
|
| 158 |
+
Open the DOI link in a browser and click **Download** (Mendeley serves a redirect to the file; scripted download is unreliable, so do these by hand):
|
| 159 |
+
- CCMT: https://data.mendeley.com/datasets/bwh3zbpkpv/1
|
| 160 |
+
- MangoLeafBD: https://data.mendeley.com/datasets/hxsnvwty3r/1
|
| 161 |
+
- Rice: https://data.mendeley.com/datasets/fwcj7stb8r/1
|
| 162 |
+
- Groundnut: https://data.mendeley.com/datasets/x6x5jkk873/2
|
| 163 |
+
|
| 164 |
+
### Option 3 — helper script
|
| 165 |
+
`scripts/download_dataset.py` lists every dataset, attempts the Kaggle downloads automatically (if the Kaggle CLI is configured) and prints the manual links for the Mendeley/GitHub sets. See `scripts/` for usage.
|
| 166 |
+
|
| 167 |
+
Unzip everything into a single working folder, e.g. `raw_downloads/`.
|
| 168 |
+
|
| 169 |
+
---
|
| 170 |
+
|
| 171 |
+
## 5. How to turn the downloads into `data/`
|
| 172 |
+
|
| 173 |
+
`scripts/prepare_dataset.py`:
|
| 174 |
+
1. reads a **MAPPING** (source dataset + subfolder → CropGuard class key — pre-filled from the tables above),
|
| 175 |
+
2. copies images into a flat `data_flat/<class>/` tree,
|
| 176 |
+
3. splits each class 70/15/15 into `data/train|val|test/<class>/`.
|
| 177 |
+
|
| 178 |
+
```bash
|
| 179 |
+
python scripts/prepare_dataset.py --raw ./raw_downloads --out ./data
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
Open the script and adjust the source paths to match where you unzipped each dataset (folder names differ slightly between mirrors). It prints a per-class image count at the end so you can see which classes are thin and need local images.
|
| 183 |
+
|
| 184 |
+
---
|
| 185 |
+
|
| 186 |
+
## 6. Then train
|
| 187 |
+
|
| 188 |
+
```bash
|
| 189 |
+
cd backend
|
| 190 |
+
pip install -r requirements.txt
|
| 191 |
+
python train.py --data ../data --arch efficientnet --epochs-head 20 --epochs-fine 30
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
`train.py` will print the class list it found, train in two phases, and report the held-out **test accuracy vs the ~0.98 target**. If you are below target, the script tells you what to do (use EfficientNetB0, add field data, or train longer).
|
| 195 |
+
|
| 196 |
+
---
|
| 197 |
+
|
| 198 |
+
## 7. Citations (add these to your references)
|
| 199 |
+
|
| 200 |
+
- Mensah, P.K., Akoto-Adjepong, V., Adu, K., et al. (2023). *CCMT: Dataset for crop pest and disease detection.* Data in Brief, 49, 109306.
|
| 201 |
+
- Hughes, D.P. & Salathé, M. (2015). *An open access repository of images on plant health…* (PlantVillage). arXiv:1511.08060.
|
| 202 |
+
- Makerere University AI Lab (2020). *Cassava Leaf Disease Classification.* Kaggle.
|
| 203 |
+
- Ahmed, S.I., Ibrahim, M., Nadim, M., et al. (2023). *MangoLeafBD: A comprehensive image dataset…* Data in Brief, 47, 108941.
|
| 204 |
+
- Sethy, P.K., Barpanda, N.K., Rath, A.K. & Behera, S.K. (2020). *Rice Leaf Disease Image Samples.* Mendeley Data.
|
| 205 |
+
- Sasmal, B., Das, A., Dhal, K.G., et al. (2024). *A novel groundnut leaf dataset…* Data in Brief, 55, 110763.
|
| 206 |
+
- Atuhurra, J., Douha, N.Y.-R., Lenka, P. (2024). *Image Classification for CSSVD Detection in Cacao Plants* (KaraAgroAI Cocoa Dataset). arXiv:2405.04535.
|
| 207 |
+
- Ahmed, S.I., et al. (2023). *BananaLSD: A banana leaf images dataset…* Data in Brief.
|
README.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CropGuard GH — Dataset Kit
|
| 2 |
+
|
| 3 |
+
Everything you need to assemble the training dataset and understand both systems.
|
| 4 |
+
|
| 5 |
+
## Contents
|
| 6 |
+
- **DATASET_GUIDE.md** — which datasets to download, from where, under what licence, how they map to the 55 classes, and how to build the `data/` folder. **Start here.**
|
| 7 |
+
- **class_names.txt** — the canonical 55 class names (must match the training folders and `recommendations.json`).
|
| 8 |
+
- **scripts/download_dataset.py** — lists every source, auto-downloads the Kaggle sets, prints manual links for the rest.
|
| 9 |
+
- **scripts/prepare_dataset.py** — maps the downloaded raw folders into the 55 class folders and splits 70/15/15 into `train/val/test`.
|
| 10 |
+
- **docs/STANDALONE_HTML_DOCUMENTATION.md** — full docs for the single-file browser app (`cropguard.html`).
|
| 11 |
+
- **docs/BACKEND_SYSTEM_DOCUMENTATION.md** — full docs for the training + FastAPI + React stack.
|
| 12 |
+
|
| 13 |
+
## Quick path
|
| 14 |
+
```bash
|
| 15 |
+
python scripts/download_dataset.py --out ./raw_downloads # then unzip everything
|
| 16 |
+
python scripts/prepare_dataset.py --raw ./raw_downloads --out ./data
|
| 17 |
+
cd ../cropguard-system/backend && python train.py --data ../../data --arch efficientnet
|
| 18 |
+
```
|
class_names.txt
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
maize_healthy
|
| 2 |
+
maize_gls
|
| 3 |
+
maize_nclb
|
| 4 |
+
maize_rust
|
| 5 |
+
maize_msv
|
| 6 |
+
maize_faw
|
| 7 |
+
cassava_healthy
|
| 8 |
+
cassava_cmd
|
| 9 |
+
cassava_cbsd
|
| 10 |
+
cassava_cbb
|
| 11 |
+
tomato_healthy
|
| 12 |
+
tomato_early
|
| 13 |
+
tomato_late
|
| 14 |
+
tomato_wilt
|
| 15 |
+
tomato_septoria
|
| 16 |
+
tomato_tylcv
|
| 17 |
+
cocoa_healthy
|
| 18 |
+
cocoa_blackpod
|
| 19 |
+
cocoa_cssvd
|
| 20 |
+
cocoa_capsid
|
| 21 |
+
cashew_healthy
|
| 22 |
+
cashew_anthracnose
|
| 23 |
+
cashew_gumosis
|
| 24 |
+
cashew_leafminer
|
| 25 |
+
plantain_healthy
|
| 26 |
+
plantain_sigatoka
|
| 27 |
+
plantain_bbtv
|
| 28 |
+
plantain_panama
|
| 29 |
+
yam_healthy
|
| 30 |
+
yam_anthracnose
|
| 31 |
+
yam_mosaic
|
| 32 |
+
pepper_healthy
|
| 33 |
+
pepper_bacterialspot
|
| 34 |
+
pepper_anthracnose
|
| 35 |
+
cowpea_healthy
|
| 36 |
+
cowpea_blight
|
| 37 |
+
cowpea_mosaic
|
| 38 |
+
cowpea_cercospora
|
| 39 |
+
groundnut_healthy
|
| 40 |
+
groundnut_leafspot
|
| 41 |
+
groundnut_rosette
|
| 42 |
+
groundnut_rust
|
| 43 |
+
rice_healthy
|
| 44 |
+
rice_blast
|
| 45 |
+
rice_blb
|
| 46 |
+
rice_brownspot
|
| 47 |
+
okra_healthy
|
| 48 |
+
okra_yvmv
|
| 49 |
+
okra_leafspot
|
| 50 |
+
gardenegg_healthy
|
| 51 |
+
gardenegg_wilt
|
| 52 |
+
gardenegg_leafspot
|
| 53 |
+
mango_healthy
|
| 54 |
+
mango_anthracnose
|
| 55 |
+
mango_bacterialspot
|
docs/BACKEND_SYSTEM_DOCUMENTATION.md
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CropGuard GH — Backend & Tools System Documentation
|
| 2 |
+
|
| 3 |
+
**The full production stack: model training, inference API, and React frontend.**
|
| 4 |
+
Final Year Project · Oppong David · BTech Computer Technology, Kumasi Technical University
|
| 5 |
+
|
| 6 |
+
This documents the `cropguard-system/` bundle — the real Chapter 3 implementation. For the single-file browser app, see the *Standalone HTML App Documentation*.
|
| 7 |
+
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
## 1. What this is
|
| 11 |
+
|
| 12 |
+
A three-part client–server system that detects crop disease with a trained convolutional neural network:
|
| 13 |
+
|
| 14 |
+
```
|
| 15 |
+
┌───────────────────────────┐ HTTPS / multipart ┌────────────────────────────┐
|
| 16 |
+
│ Frontend (client) │ ── POST /predict (image) ─▶ │ Backend (server) │
|
| 17 |
+
│ • React app (CropGuard.jsx) │ FastAPI (app.py) │
|
| 18 |
+
│ • OR the single-file HTML │ ◀── JSON diagnosis ── │ ├─ trained CNN model │
|
| 19 |
+
│ app │ │ ├─ severity estimator │
|
| 20 |
+
└───────────────────────────┘ │ └─ recommendations.json │
|
| 21 |
+
└────────────────────────────┘
|
| 22 |
+
▲
|
| 23 |
+
│ trained offline by
|
| 24 |
+
train.py → crop_model.keras + classes.json
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
Three components:
|
| 28 |
+
1. **`backend/train.py`** — trains the model from a folder of labelled images.
|
| 29 |
+
2. **`backend/app.py`** — a FastAPI server that loads the trained model and serves predictions.
|
| 30 |
+
3. **`frontend/src/CropGuard.jsx`** — a React UI that calls the server. (The standalone HTML app can be used as the client instead.)
|
| 31 |
+
|
| 32 |
+
Plus **`backend/recommendations.json`** — the bilingual-source treatment knowledge base (55 classes), used by the server to attach advice to each prediction.
|
| 33 |
+
|
| 34 |
+
### File tree
|
| 35 |
+
```
|
| 36 |
+
cropguard-system/
|
| 37 |
+
├── backend/
|
| 38 |
+
│ ├── train.py # model training (transfer learning)
|
| 39 |
+
│ ├── app.py # FastAPI inference server
|
| 40 |
+
│ ├── recommendations.json # 55-class treatment knowledge base (English)
|
| 41 |
+
│ └── requirements.txt
|
| 42 |
+
├── frontend/
|
| 43 |
+
│ └── src/CropGuard.jsx # React frontend
|
| 44 |
+
├── cropguard.html # the standalone app (also bundled here)
|
| 45 |
+
├── cropguard-en.html
|
| 46 |
+
├── cropguard-tw.html
|
| 47 |
+
└── docs/DOCUMENTATION.md # combined system doc
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
---
|
| 51 |
+
|
| 52 |
+
## 2. Model & training — `train.py`
|
| 53 |
+
|
| 54 |
+
A transfer-learning image classifier, exactly as described in Chapter 3.
|
| 55 |
+
|
| 56 |
+
### Architecture (§3.6)
|
| 57 |
+
- **Input:** 224×224 RGB, standardised with ImageNet channel mean/std.
|
| 58 |
+
- **Backbone:** ImageNet-pretrained, selectable with `--arch`:
|
| 59 |
+
- `mobilenet` → **MobileNetV2** (fast, light; ~97–98% on this benchmark)
|
| 60 |
+
- `efficientnet` → **EfficientNetB0** (typically ~98–99%; preferred to reach the ~98% target across all crops)
|
| 61 |
+
- **Custom head (§3.6.4):** GlobalAveragePooling → BatchNorm → Dense(512, ReLU, L2 1e-4) → Dropout(0.4) → Dense(num_classes, softmax).
|
| 62 |
+
|
| 63 |
+
### Training strategy (§3.7)
|
| 64 |
+
- **Two phases:** (1) freeze the backbone and train the head (Adam 1e-3); (2) unfreeze the top 30% of the backbone and fine-tune at a low rate (Adam 1e-4).
|
| 65 |
+
- **Class weighting** to handle uneven class sizes (computed from the train folder).
|
| 66 |
+
- **Augmentation** (§3.5.2): random flip, rotation, zoom, brightness, contrast.
|
| 67 |
+
- **Label smoothing** (0.05) for calibration and a small accuracy gain.
|
| 68 |
+
- **Callbacks:** EarlyStopping (restore best weights) and ReduceLROnPlateau.
|
| 69 |
+
|
| 70 |
+
### Dataset layout it expects
|
| 71 |
+
ImageFolder style — one folder per class, split into train/val/test (see the **Dataset Guide** for how to assemble this):
|
| 72 |
+
```
|
| 73 |
+
data/
|
| 74 |
+
├── train/<class_name>/*.jpg
|
| 75 |
+
├── val/<class_name>/*.jpg
|
| 76 |
+
└── test/<class_name>/*.jpg
|
| 77 |
+
```
|
| 78 |
+
**Class folder names must match the keys in `recommendations.json`** (the 55 classes in `class_names.txt`).
|
| 79 |
+
|
| 80 |
+
### Run it
|
| 81 |
+
```bash
|
| 82 |
+
cd backend
|
| 83 |
+
pip install -r requirements.txt
|
| 84 |
+
python train.py --data ../data --arch efficientnet --epochs-head 20 --epochs-fine 30
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
### Arguments
|
| 88 |
+
| Flag | Default | Meaning |
|
| 89 |
+
|---|---|---|
|
| 90 |
+
| `--data` | `./data` | dataset root (expects `train/`, `val/`, `test/`) |
|
| 91 |
+
| `--arch` | `mobilenet` | `mobilenet` or `efficientnet` |
|
| 92 |
+
| `--epochs-head` | `20` | phase-1 epochs (frozen backbone) |
|
| 93 |
+
| `--epochs-fine` | `30` | phase-2 fine-tuning epochs |
|
| 94 |
+
| `--out` | `model` | output directory |
|
| 95 |
+
|
| 96 |
+
### Outputs
|
| 97 |
+
- `model/crop_model.keras` — the trained model (loaded by `app.py`).
|
| 98 |
+
- `model/classes.json` — the class-name list in label order (so the server maps a prediction index → class key).
|
| 99 |
+
|
| 100 |
+
### Honesty about accuracy
|
| 101 |
+
At the end, `train.py` evaluates on the **held-out test set** and prints the real test accuracy against the ~0.98 target. The target is consistent with the literature (Mohanty et al. 2016 = 99.35%; Ferentinos 2018 = 99.53%) but is **measured, not assumed** — if the run is below target, the script suggests using EfficientNetB0, adding more field-condition data, or training longer. Accuracy will be high on well-covered crops (cashew, cassava, maize, tomato — the Ghana-collected CCMT data) and lower on crops with thin data until you add local images (see the Dataset Guide's coverage tiers).
|
| 102 |
+
|
| 103 |
+
---
|
| 104 |
+
|
| 105 |
+
## 3. Inference API — `app.py` (FastAPI)
|
| 106 |
+
|
| 107 |
+
Loads the trained model once (lazily, kept resident in memory) and serves predictions to either frontend.
|
| 108 |
+
|
| 109 |
+
### Endpoints
|
| 110 |
+
| Method | Path | Returns |
|
| 111 |
+
|---|---|---|
|
| 112 |
+
| GET | `/health` | `{"status":"ok","model_loaded": bool}` |
|
| 113 |
+
| GET | `/diseases` | the full `recommendations.json` knowledge base |
|
| 114 |
+
| POST | `/predict` | multipart image → diagnosis JSON (below) |
|
| 115 |
+
|
| 116 |
+
### `POST /predict` response shape
|
| 117 |
+
```json
|
| 118 |
+
{
|
| 119 |
+
"class_id": "tomato_late",
|
| 120 |
+
"confidence": 0.94,
|
| 121 |
+
"severity": "moderate", // null when the class is healthy
|
| 122 |
+
"diseased_ratio": 0.42,
|
| 123 |
+
"disease": { ...full record from recommendations.json... }
|
| 124 |
+
}
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
### How a prediction is produced
|
| 128 |
+
1. The uploaded image is opened with Pillow, converted to RGB, resized to 224×224 and standardised (same preprocessing as training).
|
| 129 |
+
2. The model returns class probabilities; the top class and its confidence are taken.
|
| 130 |
+
3. If the class is **not** healthy, `estimate_severity()` measures the diseased-area ratio (colour thresholding on a 128×128 copy: yellow/brown/dark vs leaf area; §3.8) and maps it to early/moderate/severe.
|
| 131 |
+
4. The matching treatment record is attached from `recommendations.json`.
|
| 132 |
+
5. **The image is discarded** — it is never written to disk (privacy-by-design, §3.10/§3.13).
|
| 133 |
+
|
| 134 |
+
### Run it
|
| 135 |
+
```bash
|
| 136 |
+
cd backend
|
| 137 |
+
uvicorn app:app --host 0.0.0.0 --port 8000 --reload
|
| 138 |
+
# health check:
|
| 139 |
+
curl http://localhost:8000/health
|
| 140 |
+
```
|
| 141 |
+
Set `MODEL_DIR` if your model is not in `./model`. CORS is open (`allow_origins=["*"]`) so a browser-based client can call it; tighten this for production.
|
| 142 |
+
|
| 143 |
+
---
|
| 144 |
+
|
| 145 |
+
## 4. Treatment knowledge base — `recommendations.json`
|
| 146 |
+
|
| 147 |
+
A JSON object keyed by the 55 class IDs. Each record is one of:
|
| 148 |
+
|
| 149 |
+
```jsonc
|
| 150 |
+
// healthy class
|
| 151 |
+
"maize_healthy": { "crop": "Maize", "name": "Healthy Maize", "healthy": true }
|
| 152 |
+
|
| 153 |
+
// disease class
|
| 154 |
+
"maize_gls": {
|
| 155 |
+
"crop": "Maize",
|
| 156 |
+
"name": "Grey Leaf Spot",
|
| 157 |
+
"cause": "A fungus (Cercospora zeae-maydis) that thrives in warm, humid weather...",
|
| 158 |
+
"treatment": ["Remove badly spotted lower leaves...", "Spray a strobilurin...", ...],
|
| 159 |
+
"products": ["Azoxystrobin", "Propiconazole"]
|
| 160 |
+
}
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
This is the English knowledge base used by the server. The standalone HTML app carries its own bilingual (English + Twi) copy of the same content inline. To add or edit advice, change the record here **and** in the HTML app's `DATA.diseases` (keep the keys identical).
|
| 164 |
+
|
| 165 |
+
---
|
| 166 |
+
|
| 167 |
+
## 5. React frontend — `frontend/src/CropGuard.jsx`
|
| 168 |
+
|
| 169 |
+
A React implementation of the same four-step farmer flow (`home → preview → loading → result`).
|
| 170 |
+
|
| 171 |
+
- **API base URL** comes from a Vite env var: `VITE_API_URL` (defaults to `http://localhost:8000`).
|
| 172 |
+
- `analyse()` posts the chosen file to `${API}/predict` and renders the returned diagnosis, with the same severity colours and treatment list as the HTML app.
|
| 173 |
+
- It expects to run in a standard Vite + React project.
|
| 174 |
+
|
| 175 |
+
### Run it (typical Vite setup)
|
| 176 |
+
```bash
|
| 177 |
+
# in a Vite React app that includes CropGuard.jsx
|
| 178 |
+
echo "VITE_API_URL=http://localhost:8000" > .env
|
| 179 |
+
npm install
|
| 180 |
+
npm run dev
|
| 181 |
+
```
|
| 182 |
+
|
| 183 |
+
> Note: the **standalone HTML app** already provides a complete, dependency-free client and can be used instead of the React frontend — it talks to the same `/predict` endpoint. Use the React app if you want to embed CropGuard in a larger React project; use the HTML app for the simplest possible deployment.
|
| 184 |
+
|
| 185 |
+
---
|
| 186 |
+
|
| 187 |
+
## 6. Dependencies — `requirements.txt`
|
| 188 |
+
|
| 189 |
+
```
|
| 190 |
+
fastapi==0.111.0
|
| 191 |
+
uvicorn[standard]==0.30.1
|
| 192 |
+
python-multipart==0.0.9
|
| 193 |
+
pillow==10.3.0
|
| 194 |
+
numpy==1.26.4
|
| 195 |
+
tensorflow==2.16.1 # training; also needed to load the model when serving
|
| 196 |
+
scikit-learn==1.4.2 # class-weight computation during training
|
| 197 |
+
```
|
| 198 |
+
To **serve** a pre-trained model you still need TensorFlow to load `crop_model.keras`. To only **train**, all of the above are required.
|
| 199 |
+
|
| 200 |
+
---
|
| 201 |
+
|
| 202 |
+
## 7. End-to-end: from zero to a working system
|
| 203 |
+
|
| 204 |
+
```bash
|
| 205 |
+
# 1. Get the data (see Dataset Guide)
|
| 206 |
+
python ../cropguard-dataset-kit/scripts/download_dataset.py --out ./raw_downloads
|
| 207 |
+
python ../cropguard-dataset-kit/scripts/prepare_dataset.py --raw ./raw_downloads --out ./data
|
| 208 |
+
|
| 209 |
+
# 2. Train
|
| 210 |
+
cd backend
|
| 211 |
+
pip install -r requirements.txt
|
| 212 |
+
python train.py --data ../data --arch efficientnet # writes model/crop_model.keras + classes.json
|
| 213 |
+
|
| 214 |
+
# 3. Serve
|
| 215 |
+
uvicorn app:app --host 0.0.0.0 --port 8000
|
| 216 |
+
|
| 217 |
+
# 4. Use a client
|
| 218 |
+
# • open cropguard.html and set localStorage.cropguard_api = "http://localhost:8000", OR
|
| 219 |
+
# • run the React frontend with VITE_API_URL=http://localhost:8000
|
| 220 |
+
```
|
| 221 |
+
|
| 222 |
+
---
|
| 223 |
+
|
| 224 |
+
## 8. Deployment notes
|
| 225 |
+
|
| 226 |
+
- **Backend:** any host that can run Python + TensorFlow — a VM (DigitalOcean, AWS EC2, GCP), a container, or a platform like Render/Railway. Put it behind HTTPS (e.g. an Nginx reverse proxy) for production, and restrict CORS to your frontend's origin.
|
| 227 |
+
- **Model size / speed:** MobileNetV2 is light enough to serve on CPU; EfficientNetB0 is a little heavier but still CPU-servable. Keep the model resident (the app already loads it once).
|
| 228 |
+
- **Frontend:** the HTML app is a static file (host anywhere); the React app builds to static assets via `npm run build`.
|
| 229 |
+
- **Scaling:** prediction is stateless, so you can run multiple backend workers/instances behind a load balancer.
|
| 230 |
+
|
| 231 |
+
---
|
| 232 |
+
|
| 233 |
+
## 9. Performance evaluation (§3.12)
|
| 234 |
+
|
| 235 |
+
Evaluate the trained model on the held-out test set with standard metrics — accuracy, precision, recall, F1-score — and, to quantify the lab-vs-field gap discussed in the report, evaluate separately on (a) controlled-condition images and (b) field-condition images. `train.py` reports overall test accuracy; per-class precision/recall and a confusion matrix can be produced from the saved model with scikit-learn on the test set.
|
| 236 |
+
|
| 237 |
+
---
|
| 238 |
+
|
| 239 |
+
## 10. How this maps to the report (Chapter 3)
|
| 240 |
+
|
| 241 |
+
| Report section | Where it lives |
|
| 242 |
+
|---|---|
|
| 243 |
+
| §3.3 System architecture | the client–server diagram above |
|
| 244 |
+
| §3.4 Dataset collection & curation | Dataset Guide + `prepare_dataset.py` |
|
| 245 |
+
| §3.5 Preprocessing | `standardise()` + augmentation in `train.py` |
|
| 246 |
+
| §3.6 Model selection & architecture | `build_model()` in `train.py` (`--arch`) |
|
| 247 |
+
| §3.7 Training | two-phase fit, class weights, callbacks in `train.py` |
|
| 248 |
+
| §3.8 Severity classification | `estimate_severity()` in `app.py` |
|
| 249 |
+
| §3.9 Treatment recommendations | `recommendations.json` |
|
| 250 |
+
| §3.10 Web application | `CropGuard.jsx` + the standalone HTML app |
|
| 251 |
+
| §3.11 Integration & deployment | §7–§8 above |
|
| 252 |
+
| §3.12 Evaluation framework | §9 above |
|
| 253 |
+
| §3.13 Ethics / privacy | image discarded after prediction; no storage |
|
docs/STANDALONE_HTML_DOCUMENTATION.md
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CropGuard GH — Standalone HTML App Documentation
|
| 2 |
+
|
| 3 |
+
**The self-contained, single-file browser application.**
|
| 4 |
+
Final Year Project · Oppong David · BTech Computer Technology, Kumasi Technical University
|
| 5 |
+
|
| 6 |
+
---
|
| 7 |
+
|
| 8 |
+
## 1. What this is
|
| 9 |
+
|
| 10 |
+
A complete crop disease detection front end in **one HTML file** — no install, no build step, no server required to open it. A user takes or chooses a photo of a crop leaf and immediately gets a disease name, a confidence score, a severity level (with colour), an urgency level, ordered treatment steps and suggested products.
|
| 11 |
+
|
| 12 |
+
It is the most accessible deliverable in the project: email the file, host it on any static link, or open it straight from a phone's storage. It works on a basic Android phone with no app-store download.
|
| 13 |
+
|
| 14 |
+
### The three files
|
| 15 |
+
|
| 16 |
+
| File | Language | Notes |
|
| 17 |
+
|---|---|---|
|
| 18 |
+
| `cropguard.html` | **Bilingual** | English ⇄ Twi toggle in the header. This is the main app. |
|
| 19 |
+
| `cropguard-en.html` | English only | Same app, no toggle — for English-only deployment. |
|
| 20 |
+
| `cropguard-tw.html` | Twi only | Same app, no toggle — for Twi-only deployment. |
|
| 21 |
+
|
| 22 |
+
All three are byte-for-byte self-contained: HTML, CSS and JavaScript in a single file, fonts from Google Fonts, no other external dependencies.
|
| 23 |
+
|
| 24 |
+
### Coverage
|
| 25 |
+
14 Ghanaian crops, 55 disease/healthy classes: maize, cassava, tomato, cocoa, cashew, plantain, yam, pepper, cowpea, groundnut, rice, okra, garden egg, mango.
|
| 26 |
+
|
| 27 |
+
---
|
| 28 |
+
|
| 29 |
+
## 2. How to use it
|
| 30 |
+
|
| 31 |
+
1. **Open** the file in any modern browser (phone or computer) — double-click it, or host it and visit the link.
|
| 32 |
+
2. **Take a photo** ("Take a photo of a leaf") or **Choose from gallery**. On a phone the camera button opens the rear camera directly.
|
| 33 |
+
3. **Check the photo** on the preview screen — the app reminds the user to fill the frame with the diseased leaf in good light — then tap **Analyse crop**.
|
| 34 |
+
4. **Read the result:** crop + disease, confidence bar, severity badge (green/amber/red), urgency, a numbered treatment list (most urgent first), suggested products and a short "about this disease" note.
|
| 35 |
+
5. **Scan another leaf** or **Share result** (uses the device share sheet, or copies to clipboard).
|
| 36 |
+
|
| 37 |
+
A **Help** sheet on the home screen explains all of this to first-time users, in the selected language.
|
| 38 |
+
|
| 39 |
+
---
|
| 40 |
+
|
| 41 |
+
## 3. The four-screen flow
|
| 42 |
+
|
| 43 |
+
The app is a single-page application with four screens (`home → preview → loading → result`) toggled by a small `show()` function — there is no routing library and no page reload.
|
| 44 |
+
|
| 45 |
+
```
|
| 46 |
+
HOME ──tap camera/gallery──▶ PREVIEW ──tap Analyse──▶ LOADING ──result ready──▶ RESULT
|
| 47 |
+
▲ │
|
| 48 |
+
└───────────────────────────── "Scan another leaf" ────────────────────────────┘
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
---
|
| 52 |
+
|
| 53 |
+
## 4. How the diagnosis works — two modes
|
| 54 |
+
|
| 55 |
+
The app is designed to **never be broken**, so it has two inference paths and picks automatically:
|
| 56 |
+
|
| 57 |
+
### Mode A — Connected to the trained model (accurate)
|
| 58 |
+
If an API URL is configured, the app sends the photo to the backend (`POST /predict`) and shows the real CNN prediction. This is the accurate mode and the one to use for real diagnosis. Set it by either:
|
| 59 |
+
- running `localStorage.setItem('cropguard_api', 'https://your-server:8000')` in the browser console, or
|
| 60 |
+
- hosting the app and pointing it at your deployed FastAPI server (see the backend documentation).
|
| 61 |
+
|
| 62 |
+
The footer shows **"Connected to AI model"** with a live dot when an API URL is set.
|
| 63 |
+
|
| 64 |
+
### Mode B — On-device estimate (offline fallback)
|
| 65 |
+
When **no** API URL is set, the app runs a genuine on-device image analysis in JavaScript using an HTML `<canvas>`. It:
|
| 66 |
+
1. draws the photo to a 180×180 canvas and reads the pixels,
|
| 67 |
+
2. drops near-white background pixels,
|
| 68 |
+
3. measures the proportion of **green**, **yellow**, **brown** and **dark** leaf pixels,
|
| 69 |
+
4. converts that into a *diseased-area ratio*, which sets the severity (early < 0.20 ≤ moderate < 0.55 ≤ severe), and
|
| 70 |
+
5. maps the dominant colour signature to a likely disease among common Ghanaian field patterns.
|
| 71 |
+
|
| 72 |
+
The footer shows **"On-device analysis"** in this mode.
|
| 73 |
+
|
| 74 |
+
> **Be honest about Mode B.** It is a real colour/lesion heuristic, not the trained model, and it is **not** the ~98% system. It is a reasonable offline estimate and a graceful fallback so the app still does something useful with no connectivity — but accurate, all-crop diagnosis comes from Mode A (the connected CNN). The on-screen confidence in Mode B is an estimate, and the app's disclaimer says clearly that this is a diagnostic aid, not a replacement for an extension officer.
|
| 75 |
+
|
| 76 |
+
---
|
| 77 |
+
|
| 78 |
+
## 5. Bilingual design (`cropguard.html`)
|
| 79 |
+
|
| 80 |
+
Everything the user sees exists in both English and Twi. The header toggle calls `setLang('en' | 'tw')`, which:
|
| 81 |
+
- stores the choice in `localStorage` (`cropguard_lang`) so it persists,
|
| 82 |
+
- swaps every UI string (elements tagged `data-i="key"` are filled from the language table),
|
| 83 |
+
- rebuilds the crop "pills" list in the chosen language,
|
| 84 |
+
- re-renders the current result in the new language if one is showing.
|
| 85 |
+
|
| 86 |
+
### Data model
|
| 87 |
+
All content lives in one JavaScript object, `DATA`, injected into the file:
|
| 88 |
+
|
| 89 |
+
```js
|
| 90 |
+
const DATA = {
|
| 91 |
+
crops: { en: [...14 names...], tw: [...14 names...] },
|
| 92 |
+
t: { en: {...UI strings...}, tw: {...} }, // labels, buttons, help text
|
| 93 |
+
severity: { en: {early/moderate/severe...}, tw: {...} },
|
| 94 |
+
help: { en: [[title, body], ...], tw: [...] },
|
| 95 |
+
diseases: {
|
| 96 |
+
"cocoa_blackpod": {
|
| 97 |
+
crop: { en: "Cocoa", tw: "Kookoo" },
|
| 98 |
+
name: { en: "Cocoa Black Pod", tw: "Kookoo Aba Tuntum Yare" },
|
| 99 |
+
cause:{ en: "...", tw: "..." },
|
| 100 |
+
tx: { en: ["step 1", ...], tw: ["..."] }, // treatment steps
|
| 101 |
+
chem: { en: ["Copper hydroxide", ...], tw: ["..."] } // suggested products
|
| 102 |
+
},
|
| 103 |
+
"maize_healthy": { crop:{...}, name:{...}, healthy: true },
|
| 104 |
+
...
|
| 105 |
+
}
|
| 106 |
+
};
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
The single-language files (`-en` / `-tw`) use the same structure flattened to one language and have no toggle.
|
| 110 |
+
|
| 111 |
+
> The Twi agronomic text was written carefully, but for the more specialised crops (cocoa, cashew, plantain, yam, etc.) a local agricultural extension officer or MoFA/COCOBOD agent should review it before farmer-facing release — some disease terms have no settled Twi equivalent.
|
| 112 |
+
|
| 113 |
+
---
|
| 114 |
+
|
| 115 |
+
## 6. Severity and urgency
|
| 116 |
+
|
| 117 |
+
Severity is derived from the diseased-area ratio (Mode B) or returned by the server (Mode A) and is shown with a colour and an urgency level:
|
| 118 |
+
|
| 119 |
+
| Severity | Colour | Urgency | Meaning |
|
| 120 |
+
|---|---|---|---|
|
| 121 |
+
| Early stage | 🟢 green | Routine | Small/localised (<~20% of leaf). Act soon. |
|
| 122 |
+
| Moderate stage | 🟠 amber | Urgent | ~20–60% of leaf; can spread fast. Treat this week. |
|
| 123 |
+
| Severe stage | 🔴 red | Emergency | >~60% affected. Act today. |
|
| 124 |
+
|
| 125 |
+
Healthy results skip severity and show a "no disease detected — keep monitoring" panel instead.
|
| 126 |
+
|
| 127 |
+
---
|
| 128 |
+
|
| 129 |
+
## 7. Privacy
|
| 130 |
+
|
| 131 |
+
No sign-up, no account, no analytics, no tracking. In Mode B the photo never leaves the device. In Mode A the photo is sent to the configured server only for the single prediction and is discarded there (the backend never writes it to disk). This matches the privacy-by-design intent of the report (§3.10/§3.13).
|
| 132 |
+
|
| 133 |
+
---
|
| 134 |
+
|
| 135 |
+
## 8. Deploying the HTML app
|
| 136 |
+
|
| 137 |
+
Because it is one static file, hosting is trivial. Any of these work:
|
| 138 |
+
|
| 139 |
+
- **Email / copy:** send `cropguard.html`; the recipient opens it on their phone.
|
| 140 |
+
- **Static host:** GitHub Pages, Netlify, Vercel, Firebase Hosting, or any web server — just upload the file.
|
| 141 |
+
- **Local:** open directly from storage (the camera/gallery inputs still work).
|
| 142 |
+
|
| 143 |
+
To connect it to your trained model in production, host the FastAPI backend (see the backend documentation), enable HTTPS, and set `cropguard_api` to its URL. CORS is already open on the backend so the browser can call it.
|
| 144 |
+
|
| 145 |
+
---
|
| 146 |
+
|
| 147 |
+
## 9. Customising it
|
| 148 |
+
|
| 149 |
+
- **Change treatment text / add a crop's advice:** edit the matching record in the `DATA.diseases` object (keep the `en`/`tw` shape, or just the one language in the single-language files). Class keys must match `recommendations.json` / `classes.json` so server predictions resolve to the right record.
|
| 150 |
+
- **Point at a different server:** change `localStorage.cropguard_api`.
|
| 151 |
+
- **Re-theme:** all colours are CSS variables at the top of the `<style>` block (`--leaf`, `--gold`, `--early/moderate/severe`, etc.).
|
| 152 |
+
|
| 153 |
+
> If you add a brand-new crop, you must also add labelled training images and retrain the model (see the Dataset Guide and backend documentation) — the HTML app can *display* a new class, but only the trained model can *detect* it.
|
| 154 |
+
|
| 155 |
+
---
|
| 156 |
+
|
| 157 |
+
## 10. Limitations & browser support
|
| 158 |
+
|
| 159 |
+
- **Mode B is an estimate, not the CNN** — see §4. For real diagnosis, connect the model.
|
| 160 |
+
- **A photo that isn't a clear leaf** is caught by a "not a clear leaf" check and the user is asked to retake it.
|
| 161 |
+
- **Very small lesions, extreme lighting, or a crop/disease not in the model** can still be misread — the disclaimer makes this clear.
|
| 162 |
+
- **Browsers:** any current Chrome, Firefox, Safari or Edge (mobile or desktop). The camera capture uses the standard file-input `capture` attribute; on desktop without a camera it falls back to file selection.
|
| 163 |
+
- **Connectivity:** Mode A needs internet to reach the server; Mode B needs none.
|
scripts/download_dataset.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
download_dataset.py — fetch the public datasets that make up the CropGuard corpus.
|
| 4 |
+
|
| 5 |
+
What it does:
|
| 6 |
+
* Lists every source dataset with its licence and link.
|
| 7 |
+
* Attempts the Kaggle-hosted downloads automatically IF the Kaggle CLI is
|
| 8 |
+
configured (pip install kaggle, and ~/.kaggle/kaggle.json in place).
|
| 9 |
+
* Prints the Mendeley / GitHub links for the sets that must be downloaded by
|
| 10 |
+
hand (Mendeley serves a JS redirect, so scripted download is unreliable).
|
| 11 |
+
|
| 12 |
+
It does NOT organise images into class folders — run prepare_dataset.py for that.
|
| 13 |
+
|
| 14 |
+
Usage:
|
| 15 |
+
python download_dataset.py # show the plan + try Kaggle downloads
|
| 16 |
+
python download_dataset.py --list # just print the registry, download nothing
|
| 17 |
+
python download_dataset.py --out ./raw_downloads
|
| 18 |
+
"""
|
| 19 |
+
import argparse, os, shutil, subprocess, sys, textwrap
|
| 20 |
+
|
| 21 |
+
# (name, kind, identifier, licence note)
|
| 22 |
+
REGISTRY = [
|
| 23 |
+
("CCMT (Cashew/Cassava/Maize/Tomato — collected in Ghana) [PRIMARY]",
|
| 24 |
+
"mendeley", "https://data.mendeley.com/datasets/bwh3zbpkpv/1",
|
| 25 |
+
"Mendeley, typically CC BY 4.0 — verify on page"),
|
| 26 |
+
("PlantVillage (tomato, pepper, maize cross-checks)",
|
| 27 |
+
"kaggle-dataset", "abdallahalidev/plantvillage-dataset",
|
| 28 |
+
"Free for research — verify the mirror"),
|
| 29 |
+
("Cassava Leaf Disease (Makerere) — source for cassava_cbsd",
|
| 30 |
+
"kaggle-competition", "cassava-leaf-disease-classification",
|
| 31 |
+
"Kaggle competition rules (research/educational)"),
|
| 32 |
+
("MangoLeafBD (mango)",
|
| 33 |
+
"mendeley", "https://data.mendeley.com/datasets/hxsnvwty3r/1",
|
| 34 |
+
"CC BY 4.0 — verify"),
|
| 35 |
+
("Rice Leaf Disease Image Samples (Sethy)",
|
| 36 |
+
"mendeley", "https://data.mendeley.com/datasets/fwcj7stb8r/1",
|
| 37 |
+
"CC BY 4.0 — verify"),
|
| 38 |
+
("Groundnut Leaf Dataset (Sasmal)",
|
| 39 |
+
"mendeley", "https://data.mendeley.com/datasets/x6x5jkk873/2",
|
| 40 |
+
"CC BY 4.0 — verify"),
|
| 41 |
+
("Cocoa Diseases YOLOv4 (black pod) — Kaggle",
|
| 42 |
+
"kaggle-dataset", "serranosebas/enfermedades-cacao-yolov4",
|
| 43 |
+
"Verify on page"),
|
| 44 |
+
("KaraAgroAI Cocoa (CSSVD/healthy/anthracnose)",
|
| 45 |
+
"manual", "arXiv:2405.04535 — see the paper for the dataset repository link",
|
| 46 |
+
"Research/educational — verify"),
|
| 47 |
+
("BananaLSD (plantain/banana — sigatoka, healthy)",
|
| 48 |
+
"manual", "Data in Brief S2352340923006959 (Kaggle mirrors exist; search 'BananaLSD')",
|
| 49 |
+
"CC BY 4.0 — verify"),
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
NOTE_LOCAL = textwrap.dedent("""
|
| 53 |
+
Crops that need LOCALLY COLLECTED images (weak/no public dataset):
|
| 54 |
+
cowpea (all classes), yam (all), okra (all), garden egg (all),
|
| 55 |
+
plantain_bbtv, plantain_panama, cocoa_capsid, pepper_anthracnose.
|
| 56 |
+
Photograph these in the field — extension officers / research stations can help.
|
| 57 |
+
""")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def kaggle_available():
|
| 61 |
+
return shutil.which("kaggle") is not None
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def try_kaggle(kind, ident, out):
|
| 65 |
+
if not kaggle_available():
|
| 66 |
+
print(" ! Kaggle CLI not found — skipping (pip install kaggle, add ~/.kaggle/kaggle.json)")
|
| 67 |
+
return
|
| 68 |
+
os.makedirs(out, exist_ok=True)
|
| 69 |
+
if kind == "kaggle-competition":
|
| 70 |
+
cmd = ["kaggle", "competitions", "download", "-c", ident, "-p", out]
|
| 71 |
+
else:
|
| 72 |
+
cmd = ["kaggle", "datasets", "download", "-d", ident, "-p", out]
|
| 73 |
+
print(" >", " ".join(cmd))
|
| 74 |
+
try:
|
| 75 |
+
subprocess.run(cmd, check=True)
|
| 76 |
+
print(" ✓ downloaded (unzip it inside the raw folder)")
|
| 77 |
+
except subprocess.CalledProcessError as e:
|
| 78 |
+
print(f" ! Kaggle download failed ({e}). For competitions you must accept the rules on the website first.")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def main():
|
| 82 |
+
ap = argparse.ArgumentParser()
|
| 83 |
+
ap.add_argument("--out", default="./raw_downloads")
|
| 84 |
+
ap.add_argument("--list", action="store_true", help="print the registry only")
|
| 85 |
+
args = ap.parse_args()
|
| 86 |
+
|
| 87 |
+
print("=" * 72)
|
| 88 |
+
print("CropGuard GH — dataset sources")
|
| 89 |
+
print("=" * 72)
|
| 90 |
+
for i, (name, kind, ident, lic) in enumerate(REGISTRY, 1):
|
| 91 |
+
print(f"\n[{i}] {name}")
|
| 92 |
+
print(f" kind: {kind}")
|
| 93 |
+
print(f" source: {ident}")
|
| 94 |
+
print(f" licence: {lic}")
|
| 95 |
+
if args.list:
|
| 96 |
+
continue
|
| 97 |
+
if kind.startswith("kaggle"):
|
| 98 |
+
try_kaggle(kind, ident, args.out)
|
| 99 |
+
else:
|
| 100 |
+
print(" → download by hand from the link above into:", args.out)
|
| 101 |
+
|
| 102 |
+
print(NOTE_LOCAL)
|
| 103 |
+
print("Next: unzip everything into the raw folder, then run prepare_dataset.py")
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
main()
|
scripts/prepare_dataset.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
prepare_dataset.py — turn the downloaded raw datasets into the train/val/test
|
| 4 |
+
folder tree that backend/train.py expects.
|
| 5 |
+
|
| 6 |
+
Pipeline:
|
| 7 |
+
1. Read MAPPING below (raw subfolder -> CropGuard class key).
|
| 8 |
+
2. Copy every matched image into <out>_flat/<class>/ .
|
| 9 |
+
3. Split each class 70/15/15 into <out>/train|val|test/<class>/ .
|
| 10 |
+
4. Print a per-class count so you can see which classes are thin.
|
| 11 |
+
|
| 12 |
+
IMPORTANT — you must edit the SOURCE PATHS in MAPPING to match where you
|
| 13 |
+
actually unzipped each dataset. Mirror folder names differ slightly, so adjust
|
| 14 |
+
the left-hand paths (relative to --raw) until they point at real folders.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
python prepare_dataset.py --raw ./raw_downloads --out ./data
|
| 18 |
+
python prepare_dataset.py --raw ./raw_downloads --out ./data --check # report only, copy nothing
|
| 19 |
+
"""
|
| 20 |
+
import argparse, os, random, shutil
|
| 21 |
+
from collections import defaultdict
|
| 22 |
+
|
| 23 |
+
random.seed(42)
|
| 24 |
+
IMG_EXT = (".jpg", ".jpeg", ".png", ".bmp", ".webp")
|
| 25 |
+
|
| 26 |
+
# ----------------------------------------------------------------------------
|
| 27 |
+
# MAPPING: { class_key : [ list of raw subfolders (relative to --raw) ] }
|
| 28 |
+
# Multiple source folders can feed one class; edit paths to match your unzip.
|
| 29 |
+
# Folders that don't exist are simply skipped (with a warning), so it's safe to
|
| 30 |
+
# fill in only the datasets you have downloaded so far.
|
| 31 |
+
# ----------------------------------------------------------------------------
|
| 32 |
+
MAPPING = {
|
| 33 |
+
# ---- Maize (CCMT + PlantVillage) ----
|
| 34 |
+
"maize_healthy": ["CCMT/Maize/healthy", "plantvillage/Corn_(maize)___healthy"],
|
| 35 |
+
"maize_gls": ["CCMT/Maize/leaf spot", "plantvillage/Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot"],
|
| 36 |
+
"maize_nclb": ["CCMT/Maize/leaf blight", "plantvillage/Corn_(maize)___Northern_Leaf_Blight"],
|
| 37 |
+
"maize_rust": ["plantvillage/Corn_(maize)___Common_rust_"],
|
| 38 |
+
"maize_msv": ["CCMT/Maize/streak virus"],
|
| 39 |
+
"maize_faw": ["CCMT/Maize/fall armyworm"],
|
| 40 |
+
# ---- Cassava (Cassava-Kaggle + CCMT) ----
|
| 41 |
+
"cassava_healthy":["cassava/healthy", "CCMT/Cassava/healthy"],
|
| 42 |
+
"cassava_cmd": ["cassava/cmd", "CCMT/Cassava/mosaic"],
|
| 43 |
+
"cassava_cbsd": ["cassava/cbsd"],
|
| 44 |
+
"cassava_cbb": ["cassava/cbb", "CCMT/Cassava/bacterial blight"],
|
| 45 |
+
# ---- Tomato (CCMT + PlantVillage) ----
|
| 46 |
+
"tomato_healthy": ["CCMT/Tomato/healthy", "plantvillage/Tomato___healthy"],
|
| 47 |
+
"tomato_early": ["plantvillage/Tomato___Early_blight"],
|
| 48 |
+
"tomato_late": ["plantvillage/Tomato___Late_blight", "CCMT/Tomato/leaf blight"],
|
| 49 |
+
"tomato_wilt": ["CCMT/Tomato/verticillium wilt"],
|
| 50 |
+
"tomato_septoria":["plantvillage/Tomato___Septoria_leaf_spot", "CCMT/Tomato/septoria"],
|
| 51 |
+
"tomato_tylcv": ["plantvillage/Tomato___Tomato_Yellow_Leaf_Curl_Virus", "CCMT/Tomato/leaf curl"],
|
| 52 |
+
# ---- Cocoa (KaraAgroAI + Kaggle cocoa) ----
|
| 53 |
+
"cocoa_healthy": ["cocoa/healthy"],
|
| 54 |
+
"cocoa_blackpod": ["cocoa/black_pod"],
|
| 55 |
+
"cocoa_cssvd": ["cocoa/cssvd"],
|
| 56 |
+
"cocoa_capsid": ["LOCAL/cocoa_capsid"], # collect locally
|
| 57 |
+
# ---- Cashew (CCMT) ----
|
| 58 |
+
"cashew_healthy": ["CCMT/Cashew/healthy"],
|
| 59 |
+
"cashew_anthracnose":["CCMT/Cashew/anthracnose"],
|
| 60 |
+
"cashew_gumosis": ["CCMT/Cashew/gummosis"],
|
| 61 |
+
"cashew_leafminer": ["CCMT/Cashew/leaf miner"],
|
| 62 |
+
# ---- Plantain (BananaLSD + local) ----
|
| 63 |
+
"plantain_healthy": ["bananalsd/healthy"],
|
| 64 |
+
"plantain_sigatoka": ["bananalsd/sigatoka"],
|
| 65 |
+
"plantain_bbtv": ["LOCAL/plantain_bbtv"], # collect locally
|
| 66 |
+
"plantain_panama": ["LOCAL/plantain_panama"], # collect locally
|
| 67 |
+
# ---- Yam (local) ----
|
| 68 |
+
"yam_healthy": ["LOCAL/yam_healthy"],
|
| 69 |
+
"yam_anthracnose":["LOCAL/yam_anthracnose"],
|
| 70 |
+
"yam_mosaic": ["LOCAL/yam_mosaic"],
|
| 71 |
+
# ---- Pepper (PlantVillage + chili anthracnose/local) ----
|
| 72 |
+
"pepper_healthy": ["plantvillage/Pepper,_bell___healthy"],
|
| 73 |
+
"pepper_bacterialspot":["plantvillage/Pepper,_bell___Bacterial_spot"],
|
| 74 |
+
"pepper_anthracnose": ["LOCAL/pepper_anthracnose"],
|
| 75 |
+
# ---- Cowpea (local) ----
|
| 76 |
+
"cowpea_healthy": ["LOCAL/cowpea_healthy"],
|
| 77 |
+
"cowpea_blight": ["LOCAL/cowpea_blight"],
|
| 78 |
+
"cowpea_mosaic": ["LOCAL/cowpea_mosaic"],
|
| 79 |
+
"cowpea_cercospora":["LOCAL/cowpea_cercospora"],
|
| 80 |
+
# ---- Groundnut (Sasmal) ----
|
| 81 |
+
"groundnut_healthy": ["groundnut/HEALTHY"],
|
| 82 |
+
"groundnut_leafspot":["groundnut/LEAF SPOT (EARLY AND LATE)"],
|
| 83 |
+
"groundnut_rosette": ["groundnut/ROSETTE"],
|
| 84 |
+
"groundnut_rust": ["groundnut/RUST"],
|
| 85 |
+
# ---- Rice (Sethy + healthy source/local) ----
|
| 86 |
+
"rice_healthy": ["LOCAL/rice_healthy"],
|
| 87 |
+
"rice_blast": ["rice/Blast"],
|
| 88 |
+
"rice_blb": ["rice/Bacterialblight"],
|
| 89 |
+
"rice_brownspot": ["rice/Brownspot"],
|
| 90 |
+
# ---- Okra (local) ----
|
| 91 |
+
"okra_healthy": ["LOCAL/okra_healthy"],
|
| 92 |
+
"okra_yvmv": ["LOCAL/okra_yvmv"],
|
| 93 |
+
"okra_leafspot":["LOCAL/okra_leafspot"],
|
| 94 |
+
# ---- Garden egg (local) ----
|
| 95 |
+
"gardenegg_healthy": ["LOCAL/gardenegg_healthy"],
|
| 96 |
+
"gardenegg_wilt": ["LOCAL/gardenegg_wilt"],
|
| 97 |
+
"gardenegg_leafspot":["LOCAL/gardenegg_leafspot"],
|
| 98 |
+
# ---- Mango (MangoLeafBD) ----
|
| 99 |
+
"mango_healthy": ["mangoleafbd/Healthy"],
|
| 100 |
+
"mango_anthracnose": ["mangoleafbd/Anthracnose"],
|
| 101 |
+
"mango_bacterialspot":["mangoleafbd/Bacterial Canker"],
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def list_images(folder):
|
| 106 |
+
if not os.path.isdir(folder):
|
| 107 |
+
return []
|
| 108 |
+
out = []
|
| 109 |
+
for root, _, files in os.walk(folder):
|
| 110 |
+
for f in files:
|
| 111 |
+
if f.lower().endswith(IMG_EXT):
|
| 112 |
+
out.append(os.path.join(root, f))
|
| 113 |
+
return out
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def main():
|
| 117 |
+
ap = argparse.ArgumentParser()
|
| 118 |
+
ap.add_argument("--raw", default="./raw_downloads")
|
| 119 |
+
ap.add_argument("--out", default="./data")
|
| 120 |
+
ap.add_argument("--check", action="store_true", help="report counts only, copy nothing")
|
| 121 |
+
ap.add_argument("--val", type=float, default=0.15)
|
| 122 |
+
ap.add_argument("--test", type=float, default=0.15)
|
| 123 |
+
args = ap.parse_args()
|
| 124 |
+
|
| 125 |
+
flat = args.out + "_flat"
|
| 126 |
+
counts = {}
|
| 127 |
+
missing = []
|
| 128 |
+
|
| 129 |
+
for cls, sources in MAPPING.items():
|
| 130 |
+
imgs = []
|
| 131 |
+
for s in sources:
|
| 132 |
+
p = os.path.join(args.raw, s)
|
| 133 |
+
found = list_images(p)
|
| 134 |
+
if not found and not s.startswith("LOCAL/"):
|
| 135 |
+
missing.append((cls, s))
|
| 136 |
+
imgs += found
|
| 137 |
+
counts[cls] = len(imgs)
|
| 138 |
+
if args.check:
|
| 139 |
+
continue
|
| 140 |
+
# copy into flat/<cls>/
|
| 141 |
+
dst = os.path.join(flat, cls)
|
| 142 |
+
os.makedirs(dst, exist_ok=True)
|
| 143 |
+
for i, src in enumerate(imgs):
|
| 144 |
+
ext = os.path.splitext(src)[1].lower()
|
| 145 |
+
shutil.copy2(src, os.path.join(dst, f"{cls}_{i:05d}{ext}"))
|
| 146 |
+
|
| 147 |
+
# ---- split flat -> train/val/test ----
|
| 148 |
+
if not args.check:
|
| 149 |
+
for cls in MAPPING:
|
| 150 |
+
files = list_images(os.path.join(flat, cls))
|
| 151 |
+
random.shuffle(files)
|
| 152 |
+
n = len(files)
|
| 153 |
+
n_test = int(n * args.test)
|
| 154 |
+
n_val = int(n * args.val)
|
| 155 |
+
buckets = {
|
| 156 |
+
"test": files[:n_test],
|
| 157 |
+
"val": files[n_test:n_test + n_val],
|
| 158 |
+
"train": files[n_test + n_val:],
|
| 159 |
+
}
|
| 160 |
+
for split, fs in buckets.items():
|
| 161 |
+
d = os.path.join(args.out, split, cls)
|
| 162 |
+
os.makedirs(d, exist_ok=True)
|
| 163 |
+
for f in fs:
|
| 164 |
+
shutil.copy2(f, os.path.join(d, os.path.basename(f)))
|
| 165 |
+
|
| 166 |
+
# ---- report ----
|
| 167 |
+
print("\nPer-class image counts:")
|
| 168 |
+
weak = []
|
| 169 |
+
for cls in MAPPING:
|
| 170 |
+
c = counts[cls]
|
| 171 |
+
tag = ""
|
| 172 |
+
if c == 0:
|
| 173 |
+
tag = " <-- EMPTY (fix the source path, or collect images)"
|
| 174 |
+
weak.append(cls)
|
| 175 |
+
elif c < 100:
|
| 176 |
+
tag = " <-- thin (<100); model will be weak here"
|
| 177 |
+
weak.append(cls)
|
| 178 |
+
print(f" {cls:<22} {c:>6}{tag}")
|
| 179 |
+
print(f"\nTotal images: {sum(counts.values())}")
|
| 180 |
+
if missing:
|
| 181 |
+
print(f"\n{len(missing)} mapped source folder(s) not found — edit the paths in MAPPING:")
|
| 182 |
+
for cls, s in missing[:40]:
|
| 183 |
+
print(f" {cls}: {s}")
|
| 184 |
+
if weak:
|
| 185 |
+
print(f"\n{len(weak)} class(es) empty or thin — collect local images for these before relying on them.")
|
| 186 |
+
if args.check:
|
| 187 |
+
print("\n(--check: nothing was copied)")
|
| 188 |
+
else:
|
| 189 |
+
print(f"\nDone. Train with:\n cd backend && python train.py --data ../{os.path.basename(args.out)} --arch efficientnet")
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
if __name__ == "__main__":
|
| 193 |
+
main()
|