# CropGuard GH — Backend & Tools System Documentation **The full production stack: model training, inference API, and React frontend.** Final Year Project · Oppong David · BTech Computer Technology, Kumasi Technical University This documents the `cropguard-system/` bundle — the real Chapter 3 implementation. For the single-file browser app, see the *Standalone HTML App Documentation*. --- ## 1. What this is A three-part client–server system that detects crop disease with a trained convolutional neural network: ``` ┌───────────────────────────┐ HTTPS / multipart ┌────────────────────────────┐ │ Frontend (client) │ ── POST /predict (image) ─▶ │ Backend (server) │ │ • React app (CropGuard.jsx) │ FastAPI (app.py) │ │ • OR the single-file HTML │ ◀── JSON diagnosis ── │ ├─ trained CNN model │ │ app │ │ ├─ severity estimator │ └───────────────────────────┘ │ └─ recommendations.json │ └────────────────────────────┘ ▲ │ trained offline by train.py → crop_model.keras + classes.json ``` Three components: 1. **`backend/train.py`** — trains the model from a folder of labelled images. 2. **`backend/app.py`** — a FastAPI server that loads the trained model and serves predictions. 3. **`frontend/src/CropGuard.jsx`** — a React UI that calls the server. (The standalone HTML app can be used as the client instead.) Plus **`backend/recommendations.json`** — the bilingual-source treatment knowledge base (55 classes), used by the server to attach advice to each prediction. ### File tree ``` cropguard-system/ ├── backend/ │ ├── train.py # model training (transfer learning) │ ├── app.py # FastAPI inference server │ ├── recommendations.json # 55-class treatment knowledge base (English) │ └── requirements.txt ├── frontend/ │ └── src/CropGuard.jsx # React frontend ├── cropguard.html # the standalone app (also bundled here) ├── cropguard-en.html ├── cropguard-tw.html └── docs/DOCUMENTATION.md # combined system doc ``` --- ## 2. Model & training — `train.py` A transfer-learning image classifier, exactly as described in Chapter 3. ### Architecture (§3.6) - **Input:** 224×224 RGB, standardised with ImageNet channel mean/std. - **Backbone:** ImageNet-pretrained, selectable with `--arch`: - `mobilenet` → **MobileNetV2** (fast, light; ~97–98% on this benchmark) - `efficientnet` → **EfficientNetB0** (typically ~98–99%; preferred to reach the ~98% target across all crops) - **Custom head (§3.6.4):** GlobalAveragePooling → BatchNorm → Dense(512, ReLU, L2 1e-4) → Dropout(0.4) → Dense(num_classes, softmax). ### Training strategy (§3.7) - **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). - **Class weighting** to handle uneven class sizes (computed from the train folder). - **Augmentation** (§3.5.2): random flip, rotation, zoom, brightness, contrast. - **Label smoothing** (0.05) for calibration and a small accuracy gain. - **Callbacks:** EarlyStopping (restore best weights) and ReduceLROnPlateau. ### Dataset layout it expects ImageFolder style — one folder per class, split into train/val/test (see the **Dataset Guide** for how to assemble this): ``` data/ ├── train//*.jpg ├── val//*.jpg └── test//*.jpg ``` **Class folder names must match the keys in `recommendations.json`** (the 55 classes in `class_names.txt`). ### Run it ```bash cd backend pip install -r requirements.txt python train.py --data ../data --arch efficientnet --epochs-head 20 --epochs-fine 30 ``` ### Arguments | Flag | Default | Meaning | |---|---|---| | `--data` | `./data` | dataset root (expects `train/`, `val/`, `test/`) | | `--arch` | `mobilenet` | `mobilenet` or `efficientnet` | | `--epochs-head` | `20` | phase-1 epochs (frozen backbone) | | `--epochs-fine` | `30` | phase-2 fine-tuning epochs | | `--out` | `model` | output directory | ### Outputs - `model/crop_model.keras` — the trained model (loaded by `app.py`). - `model/classes.json` — the class-name list in label order (so the server maps a prediction index → class key). ### Honesty about accuracy 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). --- ## 3. Inference API — `app.py` (FastAPI) Loads the trained model once (lazily, kept resident in memory) and serves predictions to either frontend. ### Endpoints | Method | Path | Returns | |---|---|---| | GET | `/health` | `{"status":"ok","model_loaded": bool}` | | GET | `/diseases` | the full `recommendations.json` knowledge base | | POST | `/predict` | multipart image → diagnosis JSON (below) | ### `POST /predict` response shape ```json { "class_id": "tomato_late", "confidence": 0.94, "severity": "moderate", // null when the class is healthy "diseased_ratio": 0.42, "disease": { ...full record from recommendations.json... } } ``` ### How a prediction is produced 1. The uploaded image is opened with Pillow, converted to RGB, resized to 224×224 and standardised (same preprocessing as training). 2. The model returns class probabilities; the top class and its confidence are taken. 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. 4. The matching treatment record is attached from `recommendations.json`. 5. **The image is discarded** — it is never written to disk (privacy-by-design, §3.10/§3.13). ### Run it ```bash cd backend uvicorn app:app --host 0.0.0.0 --port 8000 --reload # health check: curl http://localhost:8000/health ``` 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. --- ## 4. Treatment knowledge base — `recommendations.json` A JSON object keyed by the 55 class IDs. Each record is one of: ```jsonc // healthy class "maize_healthy": { "crop": "Maize", "name": "Healthy Maize", "healthy": true } // disease class "maize_gls": { "crop": "Maize", "name": "Grey Leaf Spot", "cause": "A fungus (Cercospora zeae-maydis) that thrives in warm, humid weather...", "treatment": ["Remove badly spotted lower leaves...", "Spray a strobilurin...", ...], "products": ["Azoxystrobin", "Propiconazole"] } ``` 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). --- ## 5. React frontend — `frontend/src/CropGuard.jsx` A React implementation of the same four-step farmer flow (`home → preview → loading → result`). - **API base URL** comes from a Vite env var: `VITE_API_URL` (defaults to `http://localhost:8000`). - `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. - It expects to run in a standard Vite + React project. ### Run it (typical Vite setup) ```bash # in a Vite React app that includes CropGuard.jsx echo "VITE_API_URL=http://localhost:8000" > .env npm install npm run dev ``` > 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. --- ## 6. Dependencies — `requirements.txt` ``` fastapi==0.111.0 uvicorn[standard]==0.30.1 python-multipart==0.0.9 pillow==10.3.0 numpy==1.26.4 tensorflow==2.16.1 # training; also needed to load the model when serving scikit-learn==1.4.2 # class-weight computation during training ``` To **serve** a pre-trained model you still need TensorFlow to load `crop_model.keras`. To only **train**, all of the above are required. --- ## 7. End-to-end: from zero to a working system ```bash # 1. Get the data (see Dataset Guide) python ../cropguard-dataset-kit/scripts/download_dataset.py --out ./raw_downloads python ../cropguard-dataset-kit/scripts/prepare_dataset.py --raw ./raw_downloads --out ./data # 2. Train cd backend pip install -r requirements.txt python train.py --data ../data --arch efficientnet # writes model/crop_model.keras + classes.json # 3. Serve uvicorn app:app --host 0.0.0.0 --port 8000 # 4. Use a client # • open cropguard.html and set localStorage.cropguard_api = "http://localhost:8000", OR # • run the React frontend with VITE_API_URL=http://localhost:8000 ``` --- ## 8. Deployment notes - **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. - **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). - **Frontend:** the HTML app is a static file (host anywhere); the React app builds to static assets via `npm run build`. - **Scaling:** prediction is stateless, so you can run multiple backend workers/instances behind a load balancer. --- ## 9. Performance evaluation (§3.12) 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. --- ## 10. How this maps to the report (Chapter 3) | Report section | Where it lives | |---|---| | §3.3 System architecture | the client–server diagram above | | §3.4 Dataset collection & curation | Dataset Guide + `prepare_dataset.py` | | §3.5 Preprocessing | `standardise()` + augmentation in `train.py` | | §3.6 Model selection & architecture | `build_model()` in `train.py` (`--arch`) | | §3.7 Training | two-phase fit, class weights, callbacks in `train.py` | | §3.8 Severity classification | `estimate_severity()` in `app.py` | | §3.9 Treatment recommendations | `recommendations.json` | | §3.10 Web application | `CropGuard.jsx` + the standalone HTML app | | §3.11 Integration & deployment | §7–§8 above | | §3.12 Evaluation framework | §9 above | | §3.13 Ethics / privacy | image discarded after prediction; no storage |