import os import sys import glob from pathlib import Path import urllib.request import urllib.error import mimetypes import uuid import json PROJECT_ROOT = Path(__file__).resolve().parent.parent def post_multipart(url: str, filepath: Path, fields: dict = None): fields = fields or {} boundary = uuid.uuid4().hex body = bytearray() for k, v in fields.items(): body.extend(f"--{boundary}\r\n".encode("utf-8")) body.extend(f'Content-Disposition: form-data; name="{k}"\r\n\r\n'.encode("utf-8")) body.extend(f"{v}\r\n".encode("utf-8")) content_type, _ = mimetypes.guess_type(str(filepath)) content_type = content_type or "image/png" filename = filepath.name body.extend(f"--{boundary}\r\n".encode("utf-8")) body.extend(f'Content-Disposition: form-data; name="image"; filename="{filename}"\r\n'.encode("utf-8")) body.extend(f"Content-Type: {content_type}\r\n\r\n".encode("utf-8")) with open(filepath, "rb") as f: body.extend(f.read()) body.extend(b"\r\n") body.extend(f"--{boundary}--\r\n".encode("utf-8")) req = urllib.request.Request(url, data=bytes(body)) req.add_header("Content-Type", f"multipart/form-data; boundary={boundary}") with urllib.request.urlopen(req) as resp: return json.loads(resp.read().decode("utf-8")) def test_api(): base_url = "http://127.0.0.1:8000" print("=" * 70) print("Testing NextGenYeild Growth-Stage API") print(f"Target: {base_url}") print("=" * 70) # 1. Health check with urllib.request.urlopen(f"{base_url}/api/v1/health") as resp: health = json.loads(resp.read().decode("utf-8")) print(f"\n1. Health Check: {health['status'].upper()}") print(f" Device : {health['device']} ({health['device_name']})") print(f" VRAM Allocated : {health['gpu_memory_allocated_mb']} MB") print(f" Model Version : {health['model_version']}") # 2. Stage predictions stages = ["0_tillering", "1_jointing", "2_booting", "3_anthesis", "4_grain_filling", "5_maturity"] print("\n2. Testing Single-Image Predictions across all 6 Stages:") header = f"{'True Stage':18s} | {'Predicted Stage':18s} | {'Confidence':10s} | {'Rating':10s} | {'Latency':8s}" print(header) print("-" * len(header)) predict_url = f"{base_url}/api/v1/ai/growth-stage/predict" for st in stages: files = list((PROJECT_ROOT / "data" / "test" / st).glob("*.png")) if not files: continue test_file = files[0] try: res = post_multipart(predict_url, test_file, {"field_id": f"field-{st[:3]}"}) d = res["data"] lat = f"{d['model_metadata']['inference_latency_ms']}ms" conf = f"{d['confidence']*100:.1f}%" print(f"{st:18s} | {d['raw_class']:18s} | {conf:10s} | {d['confidence_rating']:10s} | {lat:8s}") except Exception as e: print(f"{st:18s} | ERROR: {e}") print("=" * 70) if __name__ == "__main__": test_api()