File size: 8,499 Bytes
c54c1bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# NextGenYeild — Mobile App API Integration Guide

> **Document Purpose:** Complete specification and integration guide for mobile developers (Flutter / React Native / Swift / Kotlin) connecting the NextGenYeild mobile application to the AI Growth-Stage Prediction backend.  
> **Backend Service:** FastAPI running `FoMo4Wheat_base` (ViT-B/14) + Downstream 6-Class Linear Classifier (`nextgenyeild_wgsp_head_v1`).  
> **Target Environment:** Development / Testing / Local Field Trials.  

---

## 1. Quick Reference & Network Addressing

| Parameter | Value |
| :--- | :--- |
| **API Base URL** | `http://<HOST_IP>:8000` |
| **Interactive Swagger Docs** | `http://<HOST_IP>:8000/docs` (Try endpoints directly in browser) |
| **ReDoc Documentation** | `http://<HOST_IP>:8000/redoc` |
| **CORS Support** | Fully enabled (`*` origins, all headers, all methods) |
| **Inference Latency** | ~18–25 ms per image on NVIDIA RTX 5070 GPU |

### Choosing the Correct `<HOST_IP>` for Your Development Setup

Depending on how the mobile developer is running the app:

1. **Android Emulator (Running on the same PC):**
   * Use: `http://10.0.2.2:8000`
   * *(Android automatically maps `10.0.2.2` to the host computer's `localhost`)*.

2. **iOS Simulator (Running on Mac):**
   * Use: `http://localhost:8000` or `http://127.0.0.1:8000`.

3. **Physical Android Phone connected via USB Cable (Fastest & Most Reliable):**
   * On your computer terminal, run:
     ```bash
     adb reverse tcp:8000 tcp:8000
     ```
   * Now, the physical phone can query `http://localhost:8000` directly as if the server were on the phone!

4. **Physical Phone over the Same Wi-Fi Network:**
   * Host PC Wi-Fi IP is: `192.168.0.199`
   * Base URL: `http://192.168.0.199:8000`
   * *(Ensure Windows Defender Firewall allows incoming traffic on port 8000)*.

---

## 2. API Endpoints

### Endpoint 1: Health & Device Check
* **Route:** `GET /api/v1/health` (or `GET /health`)
* **Purpose:** Verify that the server is online and the GPU model is initialized before opening the camera.
* **Response (`200 OK`):**
```json
{
  "status": "healthy",
  "model_loaded": true,
  "device": "cuda",
  "device_name": "NVIDIA GeForce RTX 5070",
  "gpu_memory_allocated_mb": 184.04,
  "model_version": "fomo4wheat-wgsp-v1",
  "timestamp": "2026-10-18 10:44:04 UTC"
}
```

---

### Endpoint 2: Wheat Growth Stage Prediction (Primary)
* **Route:** `POST /api/v1/ai/growth-stage/predict`
* **Content-Type:** `multipart/form-data`
* **Request Parameters:**

| Field Name | Type | Required? | Description |
| :--- | :---: | :---: | :--- |
| `image` | `File` (Binary) | **Yes** | Wheat canopy photo (`.jpg`, `.jpeg`, `.png`, `.webp`). Recommended resolution: $518 \times 518$ or standard smartphone photo (auto-resized). |
| `field_id` | `String` | No | Client field identifier or UUID (e.g., `"field_punjab_north_04"`). |
| `crop_type` | `String` | No | Defaults to `"wheat"`. |

#### Response Payload (`200 OK`):
```json
{
  "status": "success",
  "data": {
    "stage_index": 2,
    "stage_name": "booting",
    "raw_class": "2_booting",
    "confidence": 0.9421,
    "confidence_rating": "high",
    "field_id": "field_punjab_north_04",
    "crop_type": "wheat",
    "probabilities": {
      "tillering": 0.0012,
      "jointing": 0.0451,
      "booting": 0.9421,
      "anthesis": 0.0104,
      "grain_filling": 0.0011,
      "maturity": 0.0001
    },
    "model_metadata": {
      "backbone": "FoMo4Wheat_base (ViT-B/14)",
      "classifier_head": "nextgenyeild_wgsp_head_v1",
      "version": "fomo4wheat-wgsp-v1",
      "device": "cuda",
      "inference_latency_ms": 19.75
    },
    "advisory": {
      "display_name": "Booting",
      "primary_objective": "Pollen development and wheat spike protection inside the flag leaf sheath.",
      "summary": "Crop is in the Booting stage. The head is actively swelling inside the sheath of the flag leaf.",
      "irrigation_guidance": "Critical moisture window. Water deficit during booting irreversibly reduces potential spikelet count and head length.",
      "nutrient_guidance": "Avoid heavy granular nitrogen. Apply corrective foliar micronutrients (Zinc, Boron) if micronutrient deficiency symptoms are visible.",
      "protection_guidance": "Protect the flag leaf at all costs (it drives > 50% of eventual grain yield). Spray protective fungicide if stripe rust or powdery mildew is present in the field.",
      "risk_alerts": [
        "Flag leaf damage directly slashes ultimate harvest yield by up to 50%.",
        "Moisture stress right before heading causes sterile florets."
      ]
    }
  }
}
```

---

## 3. UI Guidelines for Mobile Developers

1. **Stage Badge Color Coding (`confidence_rating`):**
   * `"high"` ($\ge 80\%$): Render green badge (`#10B981`) — prediction is highly reliable.
   * `"moderate"` ($60\% - 79\%$): Render amber/yellow badge (`#F59E0B`) — recommend farmer confirm visual features.
   * `"low / uncertain"` ($< 60\%$): Render orange/red badge (`#EF4444`) — prompt user: *"Image uncertain. Please retake photo from directly above the canopy without blur or harsh shadow."*

2. **Growth Timeline Stepper:**
   The `stage_index` integer ($0$ to $5$) maps directly to the horizontal growth stage progress bar:
   * **0:** Tillering
   * **1:** Jointing
   * **2:** Booting
   * **3:** Anthesis
   * **4:** Grain Filling
   * **5:** Maturity

3. **Agronomic Advice Cards:**
   The `advisory` object should be rendered in clean cards:
   * 💧 **Water Management:** `advisory.irrigation_guidance`
   * 🧪 **Nutrient / Fertilizer:** `advisory.nutrient_guidance`
   * 🛡️ **Scouting & Protection:** `advisory.protection_guidance`
   * ⚠️ **Risk Warnings:** Bulleted list from `advisory.risk_alerts`

---

## 4. Ready-to-Use Code Snippets

### Flutter (Dart) Implementation

Using the standard `http` package:

```dart
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

class GrowthStageService {
  // Use http://10.0.2.2:8000 for Android Emulator, or http://192.168.0.199:8000 for Wi-Fi
  static const String baseUrl = 'http://10.0.2.2:8000';

  static Future<Map<String, dynamic>> predictStage({
    required File imageFile,
    String? fieldId,
  }) async {
    final uri = Uri.parse('$baseUrl/api/v1/ai/growth-stage/predict');
    final request = http.MultipartRequest('POST', uri);

    // Attach image
    request.files.add(await http.MultipartFile.fromPath(
      'image',
      imageFile.path,
    ));

    // Optional parameters
    if (fieldId != null) {
      request.fields['field_id'] = fieldId;
    }
    request.fields['crop_type'] = 'wheat';

    final streamedResponse = await request.send();
    final response = await http.Response.fromStream(streamedResponse);

    if (response.statusCode == 200) {
      final jsonResponse = jsonDecode(response.body);
      return jsonResponse['data'];
    } else {
      throw Exception('Prediction failed [${response.statusCode}]: ${response.body}');
    }
  }
}
```

---

### React Native (JavaScript / TypeScript) Implementation

```typescript
export async function predictGrowthStage(
  imageUri: string,
  fieldId?: string
): Promise<any> {
  // Use http://10.0.2.2:8000 for Android Emulator
  const BASE_URL = 'http://10.0.2.2:8000';

  const formData = new FormData();
  formData.append('image', {
    uri: imageUri,
    type: 'image/jpeg',
    name: 'canopy_photo.jpg',
  } as any);

  if (fieldId) {
    formData.append('field_id', fieldId);
  }
  formData.append('crop_type', 'wheat');

  const response = await fetch(`${BASE_URL}/api/v1/ai/growth-stage/predict`, {
    method: 'POST',
    body: formData,
    headers: {
      'Accept': 'application/json',
    },
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Server returned ${response.status}: ${errorText}`);
  }

  const json = await response.json();
  return json.data;
}
```

---

### cURL (Command Line / Postman)

```bash
curl -X POST "http://localhost:8000/api/v1/ai/growth-stage/predict" \
  -F "image=@/path/to/wheat_photo.jpg" \
  -F "field_id=field-punjab-04" \
  -F "crop_type=wheat"
```

---

## 5. How to Start the Backend Server

To keep the API server running on the host machine:

```bash
# 1. Activate environment
conda activate FoMo4Wheat

# 2. Navigate to project root
cd /home/shawaiz/fyp/FoMo4Wheat

# 3. Start server binding to all network interfaces on port 8000
python -m api.server --host 0.0.0.0 --port 8000
```