from fastapi import APIRouter, HTTPException from app.services.vision_openai import VisionService from app.schemas.vision import VisionRequest, VisionResponse, DiseaseDetection, BBCHDetection router = APIRouter() vision_service = VisionService() @router.post("/vision/analyze", response_model=VisionResponse) async def analyze_image(request: VisionRequest): try: # Call vision service to analyze the image result = await vision_service.analyze_image( image_base64=request.image_base64, crop_type=request.crop_type, bbch_stage=request.bbch_stage ) # Handle crop identification identified_crop = None if result.get("identified_crop"): identified_crop = result["identified_crop"].get("crop_name") # Handle BBCH prediction predicted_bbch = None if result.get("predicted_bbch"): predicted_bbch = BBCHDetection( predicted_stage=result["predicted_bbch"].get("predicted_stage", "unknown"), confidence=result["predicted_bbch"].get("confidence", 0.0), description=result["predicted_bbch"].get("description", "") ) # Handle disease detections detections = [] for detection in result.get("detections", []): detections.append(DiseaseDetection( condition=detection.get("condition", "Unknown"), confidence=detection.get("confidence", 0.0), description=detection.get("description", ""), treatment=detection.get("treatment", "Consult a local agronomist") )) # Get overall health and recommendations overall_health = result.get("overall_health", "Unable to determine") recommendations = result.get("recommendations", ["Consult local agricultural expert"]) # Return formatted response return VisionResponse( identified_crop=identified_crop, predicted_bbch=predicted_bbch, detections=detections, overall_health=overall_health, recommendations=recommendations ) except Exception as e: raise HTTPException(status_code=500, detail=f"Vision analysis failed: {str(e)}")