|
Download docs/MOBILE_API_INTEGRATION_GUIDE.md from dormant78612/nextgenyeild-api: direct link, hf CLI and curl.
- Browser
- Download file 8.5 kB
-
https://huggingface.co/spaces/dormant78612/nextgenyeild-api/resolve/main/docs/MOBILE_API_INTEGRATION_GUIDE.md
- Command line
-
hf download hf://spaces/dormant78612/nextgenyeild-api/docs/MOBILE_API_INTEGRATION_GUIDE.md
-
curl -L -o MOBILE_API_INTEGRATION_GUIDE.md https://huggingface.co/spaces/dormant78612/nextgenyeild-api/resolve/main/docs/MOBILE_API_INTEGRATION_GUIDE.md
8.5 kB
| # 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 | |
| ``` | |