File size: 13,070 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import io
import os
import sys
import time
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Optional, Dict, Any

from PIL import Image
import torch
import torch.nn as nn
import torch.nn.functional as F
from fastapi import FastAPI, File, UploadFile, Form, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from fastapi.responses import RedirectResponse

# Ensure project root is in sys.path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

# Ensure internal dinov2 imports map to FoMo4Wheat across all platforms
if "dinov2" not in sys.modules:
    try:
        import FoMo4Wheat
        sys.modules["dinov2"] = FoMo4Wheat
    except Exception:
        pass

from FoMo4Wheat.models.vision_transformer import vit_base
from FoMo4Wheat.utils.utils import load_pretrained_weights
from FoMo4Wheat.data.transforms import make_classification_eval_transform
from experiments.train_classifier import GrowthStageLinearHead, CLASSES
from api.schemas import (
    PredictionResponse,
    PredictionData,
    StageProbabilities,
    ModelMetadata,
    AgronomicAdvisory,
    HealthResponse,
)
from api.rules import get_advisory_for_stage, AGRONOMIC_MATRIX

# Paths
DEFAULT_BACKBONE_PATH = PROJECT_ROOT / "weight" / "FoMo4Wheat_base.pth"
DEFAULT_HEAD_PATH = PROJECT_ROOT / "weight" / "nextgenyeild_wgsp_head_v1.pth"
MODEL_VERSION = "fomo4wheat-wgsp-v1"

# Global pipeline state (loaded in lifespan)
app_state: Dict[str, Any] = {
    "backbone": None,
    "head": None,
    "transform": None,
    "device": None,
    "device_name": None,
    "checkpoint_meta": {},
}


def load_model_pipeline(backbone_path: Path, head_path: Path):
    """Loads the frozen ViT backbone and linear classification head."""
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    device_name = torch.cuda.get_device_name(0) if torch.cuda.is_available() else "CPU"
    print(f"Loading NextGenYeild AI Pipeline on: {device} ({device_name})...")

    if not backbone_path.exists():
        print(f"Backbone weights missing at: {backbone_path}")
        print("Auto-downloading FoMo4Wheat_base.pth (~346 MB) from official repository...")
        backbone_path.parent.mkdir(parents=True, exist_ok=True)
        url = "https://huggingface.co/PheniX-Lab/FoMo4Wheat/resolve/main/weight/FoMo4Wheat_base.pth"
        import urllib.request
        try:
            urllib.request.urlretrieve(url, str(backbone_path))
            print("✓ Backbone download complete!")
        except Exception as e:
            raise FileNotFoundError(f"Failed to auto-download backbone from {url}: {e}")
    if not head_path.exists():
        raise FileNotFoundError(f"Trained head checkpoint missing at: {head_path}")

    # 1. Backbone (ViT-B/14, 518x518, frozen)
    backbone = vit_base(
        patch_size=14,
        img_size=518,
        init_values=1.0,
        ffn_layer="swiglu",
        block_chunks=4,
        num_register_tokens=4,
    )
    raw_obj = torch.load(str(backbone_path), map_location="cpu", weights_only=False)
    sd = raw_obj.state_dict() if isinstance(raw_obj, torch.nn.Module) else raw_obj
    if isinstance(sd, dict) and "teacher" in sd:
        sd = sd["teacher"]
    clean_sd = {k.replace("module.", "").replace("backbone.", ""): v for k, v in sd.items()}
    backbone.load_state_dict(clean_sd, strict=True)
    for param in backbone.parameters():
        param.requires_grad = False
    
    if device.type == "cuda":
        backbone = backbone.to(device).half()
    else:
        backbone = backbone.to(device).float()
    backbone.eval()
    print("✓ Pretrained ViT-B/14 backbone loaded with strict=True and frozen.")

    # 2. Linear Head
    checkpoint = torch.load(head_path, map_location=device, weights_only=False)
    in_features = checkpoint.get("in_features", 1536)
    num_classes = checkpoint.get("num_classes", 6)
    head = GrowthStageLinearHead(in_features=in_features, num_classes=num_classes).to(device)
    head.load_state_dict(checkpoint["state_dict"])
    head.eval()

    # 3. Preprocessing transform
    transform = make_classification_eval_transform(resize_size=518, crop_size=518)

    app_state["backbone"] = backbone
    app_state["head"] = head
    app_state["transform"] = transform
    app_state["device"] = device
    app_state["device_name"] = device_name
    app_state["checkpoint_meta"] = checkpoint
    print("✓ Model pipeline successfully initialized and ready for real-time requests!")


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup: Load models into GPU/CPU
    load_model_pipeline(DEFAULT_BACKBONE_PATH, DEFAULT_HEAD_PATH)
    yield
    # Shutdown
    if app_state["device"] and app_state["device"].type == "cuda":
        torch.cuda.empty_cache()


app = FastAPI(
    title="NextGenYeild — Wheat Growth Stage Prediction API",
    description=(
        "Production-ready AI REST API for wheat phenological growth-stage classification. "
        "Powered by the FoMo4Wheat Vision Transformer foundation model and deterministic "
        "agronomic decision support rules."
    ),
    version="1.0.0",
    lifespan=lifespan,
)

# Enable CORS for Mobile Apps (Flutter, React Native) and Web Clients
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/", include_in_schema=False)
async def root():
    """Redirect root directly to interactive Swagger API documentation."""
    return RedirectResponse(url="/docs")


@app.get("/api/v1/info", tags=["General"])
async def service_info():
    return {
        "service": "NextGenYeild Growth Stage Prediction API",
        "version": MODEL_VERSION,
        "docs_url": "/docs",
        "health_check": "/api/v1/health",
        "predict_endpoint": "/api/v1/ai/growth-stage/predict",
    }


@app.get("/health", response_model=HealthResponse, tags=["Monitoring"])
@app.get("/api/v1/health", response_model=HealthResponse, tags=["Monitoring"])
async def health_check():
    """Returns system health, active compute device, and GPU memory metrics."""
    device = app_state.get("device")
    device_str = str(device) if device else "unknown"
    mem_mb = None
    if device and device.type == "cuda":
        mem_mb = round(torch.cuda.memory_allocated(0) / (1024 * 1024), 2)

    return HealthResponse(
        status="healthy",
        model_loaded=app_state.get("backbone") is not None,
        device=device_str,
        device_name=app_state.get("device_name"),
        gpu_memory_allocated_mb=mem_mb,
        model_version=MODEL_VERSION,
        timestamp=time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()),
    )


@app.get("/api/v1/ai/growth-stage/stages", tags=["Agronomy"])
async def list_growth_stages():
    """Returns the standardized 6-stage taxonomy and agronomic reference rules."""
    stages = []
    for raw_key, info in AGRONOMIC_MATRIX.items():
        stages.append({
            "stage_index": info["stage_index"],
            "raw_key": raw_key,
            "stage_name": raw_key.split("_", 1)[1] if "_" in raw_key else raw_key,
            "display_name": info["display_name"],
            "primary_objective": info["primary_objective"],
            "summary": info["summary"],
        })
    return {"crop_type": "wheat", "total_stages": len(stages), "stages": stages}


@app.post(
    "/api/v1/ai/growth-stage/predict",
    response_model=PredictionResponse,
    status_code=status.HTTP_200_OK,
    tags=["Prediction"],
    summary="Predict wheat growth stage from canopy image",
)
async def predict_growth_stage(
    image: UploadFile = File(..., description="RGB wheat canopy image file (JPEG, PNG, WebP)"),
    field_id: Optional[str] = Form(None, description="Optional client-side field UUID or tracking ID"),
    crop_type: str = Form("wheat", description="Crop type (defaults to 'wheat')"),
):
    """
    Primary Mobile & Web Inference Endpoint:
    1. Validates and decodes uploaded image.
    2. Runs feature extraction through frozen FoMo4Wheat ViT-B/14.
    3. Infers 6 growth stage probabilities via trained linear classifier head.
    4. Attaches deterministic agronomic management rules & risk alerts.
    """
    if app_state["backbone"] is None or app_state["head"] is None:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="AI model is currently initializing. Please retry in a moment.",
        )

    # 1. Validate MIME type
    valid_content_types = {"image/jpeg", "image/png", "image/webp", "image/bmp", "image/tiff"}
    if image.content_type and image.content_type.lower() not in valid_content_types:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Invalid file type: '{image.content_type}'. Please upload an RGB image (JPEG, PNG, WebP).",
        )

    start_time = time.perf_counter()

    # 2. Read and decode image with PIL
    try:
        image_bytes = await image.read()
        pil_image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Failed to decode image file: {str(e)}",
        )

    # 3. Preprocessing
    device = app_state["device"]
    transform = app_state["transform"]
    try:
        tensor = transform(pil_image).unsqueeze(0).to(device)
        if device.type == "cuda":
            tensor = tensor.half()
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Error in image preprocessing: {str(e)}",
        )

    # 4. Neural Network Inference
    backbone = app_state["backbone"]
    head = app_state["head"]

    with torch.no_grad():
        feats_dict = backbone.forward_features(tensor)
        cls_tok = feats_dict["x_norm_clstoken"]  # [1, 768]
        patch_toks = feats_dict["x_norm_patchtokens"]  # [1, 1369, 768]
        mean_patch = torch.mean(patch_toks, dim=1)  # [1, 768]
        pooled = torch.cat([cls_tok, mean_patch], dim=-1).float()  # [1, 1536]

        logits = head(pooled)
        probs = F.softmax(logits, dim=-1).squeeze(0).cpu().numpy()

    latency_ms = round((time.perf_counter() - start_time) * 1000, 2)

    # 5. Extract top prediction
    top_idx = int(probs.argmax())
    raw_class = CLASSES[top_idx]  # e.g. "2_booting"
    stage_name = raw_class.split("_", 1)[1] if "_" in raw_class else raw_class
    confidence = float(probs[top_idx])

    # 6. Qualitative confidence rating
    if confidence >= 0.80:
        confidence_rating = "high"
    elif confidence >= 0.60:
        confidence_rating = "moderate"
    else:
        confidence_rating = "low / uncertain"

    # 7. Probability mapping
    prob_dict = {
        "tillering": round(float(probs[0]), 4),
        "jointing": round(float(probs[1]), 4),
        "booting": round(float(probs[2]), 4),
        "anthesis": round(float(probs[3]), 4),
        "grain_filling": round(float(probs[4]), 4),
        "maturity": round(float(probs[5]), 4),
    }

    # 8. Retrieve agronomic advisory
    advisory_raw = get_advisory_for_stage(raw_class)
    advisory_obj = AgronomicAdvisory(
        display_name=advisory_raw["display_name"],
        primary_objective=advisory_raw["primary_objective"],
        summary=advisory_raw["summary"],
        irrigation_guidance=advisory_raw["irrigation_guidance"],
        nutrient_guidance=advisory_raw["nutrient_guidance"],
        protection_guidance=advisory_raw["protection_guidance"],
        risk_alerts=advisory_raw["risk_alerts"],
    )

    # 9. Format response
    response_data = PredictionData(
        stage_index=top_idx,
        stage_name=stage_name,
        raw_class=raw_class,
        confidence=round(confidence, 4),
        confidence_rating=confidence_rating,
        field_id=field_id,
        crop_type=crop_type,
        probabilities=StageProbabilities(**prob_dict),
        model_metadata=ModelMetadata(
            backbone="FoMo4Wheat_base (ViT-B/14)",
            classifier_head="nextgenyeild_wgsp_head_v1",
            version=MODEL_VERSION,
            device=str(device),
            inference_latency_ms=latency_ms,
        ),
        advisory=advisory_obj,
    )

    return PredictionResponse(status="success", data=response_data)


if __name__ == "__main__":
    import argparse
    default_port = int(os.environ.get("PORT", 8000))
    parser = argparse.ArgumentParser(description="NextGenYeild REST API Server")
    parser.add_argument("--host", type=str, default="0.0.0.0", help="Binding host (default 0.0.0.0)")
    parser.add_argument("--port", type=int, default=default_port, help=f"Binding port (default {default_port})")
    args = parser.parse_args()

    print(f"Starting NextGenYeild Growth Stage API on http://{args.host}:{args.port}")
    uvicorn.run("api.server:app", host=args.host, port=args.port, reload=False)