Spaces:
Paused
Paused
File size: 5,165 Bytes
03ca3fa 66e9ecc 333220f 03ca3fa 333220f 03ca3fa fc10439 |
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 |
---
title: Crop Guard
emoji: πΎ
colorFrom: green
colorTo: green
sdk: docker
sdk_version: "1.0"
app_file: main.py
pinned: false
---
# Crop Disease Detection API Server
A **FastAPI** server hosting multiple Xceptionβbased deep learning models for detecting diseases in maize, cassava, cashew, and tomato leaves. Send images via HTTP and receive back the predicted disease, confidence score, and recommended treatment.
---
## π Features
- **Onβdemand model loading**: Each model is loaded the first time itβs requested and then cached.
- **Unified image pipeline**: Shared resizing, normalization, and inference logic.
- **Interactive docs**: Builtβin Swagger UI at `/docs`.
- **CORS enabled**: Accepts requests from any origin (customize as needed).
---
## π Quick Start
### 1. Clone & Prepare
```bash
git clone https://github.com/Bawah-Joy/Ghana-Hack-AI.git
cd Ghana-Hack-AI/crop-guard-backend
python -m venv venv
source venv/bin/activate # macOS/Linux
venv\Scripts\activate # Windows
pip install --upgrade pip
pip install -r requirements.txt
```
### 2. Download & Place Models
Create a `model/` directory in the project root and download the pre-trained `.keras` files (examples below) into it:
```
model/
ββ xception_maize.keras
ββ xception_cassava.keras
ββ xception_cashew.keras
ββ xception_tomato.keras
```
**Download links** (example Google Drive):
- [Maize Model](https://drive.google.com/file/d/1TLtyN5uzFUwMVL6TjTN3ejKZtZBXi2hw/view)
- [Cassava Model](https://drive.google.com/file/d/11mvp4TuIQ5NATksrRki-z2gWjJyU-j85/view)
- [Cashew Model](https://drive.google.com/file/d/1lxlHR6lWyOJJwZb9n6JST8yEd8VtcZK/view)
- [Tomato Model](https://drive.google.com/file/d/1A9a-t3kspjdxqmqz11OoK62D9JPortw3/view)
### 3. Run Locally
#### Start the API
```bash
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
```
#### (Optional) Ngrok Tunneling
```bash
ngrok http 8000
```
Copy the HTTPS URL (e.g. `https://abcd1234.ngrok.io`) and use it in your frontend or API clients.
---
## βοΈ Configuration
- No secrets required by default.
- CORS is enabled for all origins in `app/main.py` via:
```python
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
```
---
## π API Reference
### Interactive Docs
Browse and test all endpoints at:
```
http://localhost:8000/docs
```
### `/predict`
- **Method:** `POST`
- **Content-Type:** `multipart/form-data`
- **Fields:**
- `file` (binary image file, e.g. JPEG/PNG)
- `model_name` (string; one of `xception_maize`, `xception_cassava`, `xception_cashew`, `xception_tomato`)
#### Example `curl`
```bash
curl -X POST "https://<YOUR_NGROK>.ngrok.io/predict" \
-F "file=@/path/to/leaf.jpg;type=image/jpeg" \
-F "model_name=xception_maize"
```
#### Sample Response
```json
{
"label": "leaf blight",
"confidence": 0.87,
"details": {
"description": "Fungal disease that causes dead streaks on leaves.",
"symptoms": ["Long, greyish lesions", "Yellowing and dying leaves"],
"treatment": "Apply fungicides like Mancozeb. Ensure good air circulation.",
"prevention": "Avoid overhead watering; plant in well-spaced rows.",
"message": "Maize leaf blight detected. Spray fungicide and avoid wetting leaves during irrigation."
}
}
```
---
## π Model Loading & Inference Flow
_All contained in `app/api/predict.py`:_
1. **Load model on first request**
```python
def load_model(name):
path = MODEL_DIR / f"{name}.keras"
return keras_load_model(path)
```
2. **Preprocess & predict**
```python
def predict_image(file_bytes, model, model_name):
img = Image.open(BytesIO(file_bytes)).convert("RGB")
img = img.resize((299, 299))
arr = preprocess_input(np.expand_dims(np.array(img), 0))
preds = model.predict(arr)
idx = int(np.argmax(preds))
label = CLASS_NAMES[model_name][idx]
conf = float(np.max(preds))
return label, conf, DISEASE_DATA[model_name][label]
```
3. **Return JSON** with `label`, `confidence`, and rich `details`.
---
## βοΈ Deployment on Render
1. Ensure `render.yml` is present in the project root.
2. Push to GitHub and connect the repo in Render.
3. Render will:
- Install dependencies: `pip install -r requirements.txt`
- Launch the app using:
```bash
uvicorn app.main:app --host 0.0.0.0 --port $PORT
```
---
## ποΈ Project Structure
```
crop-guard-backend/
ββ app/
β ββ api/
β β ββ predict.py # Routes & inference logic
β ββ core/
β β ββ model.py # Model manager & loader
β ββ pipelines/
β β ββ main_pipeline.py # Shared preprocessing flow
β ββ schemas/
β β ββ predict.py # Request/response Pydantic models
β ββ main.py # FastAPI app setup + CORS
ββ model/ # Place downloaded .keras files here
ββ requirements.txt # Python dependencies
ββ render.yml # Render deployment config
ββ README.md # This file
```
---
|