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)