File size: 3,086 Bytes
72b9a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Script untuk test Python API secara lokal
"""

import requests
import base64
import sys
import json

def test_health(api_url):
    """Test health check endpoint"""
    print(f"\n{'='*50}")
    print("Testing /health endpoint...")
    print(f"{'='*50}")

    try:
        response = requests.get(f"{api_url}/health", timeout=10)
        print(f"Status Code: {response.status_code}")
        print(f"Response:\n{json.dumps(response.json(), indent=2)}")
        return response.status_code == 200
    except Exception as e:
        print(f"Error: {e}")
        return False

def test_classify(api_url, image_path):
    """Test classification endpoint"""
    print(f"\n{'='*50}")
    print("Testing /classify endpoint...")
    print(f"{'='*50}")

    try:
        # Read and encode image
        with open(image_path, 'rb') as f:
            img_data = base64.b64encode(f.read()).decode()

        # Prepare request
        payload = {
            'image': f'data:image/jpeg;base64,{img_data}'
        }

        # Send request
        print(f"Sending image: {image_path}")
        response = requests.post(
            f"{api_url}/classify",
            json=payload,
            timeout=30
        )

        print(f"Status Code: {response.status_code}")
        result = response.json()
        print(f"\nPrediction Result:")
        print(f"  Class: {result.get('predicted_class')}")
        print(f"  Confidence: {result.get('confidence', 0)*100:.2f}%")
        print(f"  Mode: {result.get('mode', 'unknown')}")
        print(f"\n  Probabilities:")
        for cls, prob in result.get('probabilities', {}).items():
            print(f"    {cls}: {prob*100:.2f}%")

        return response.status_code == 200

    except FileNotFoundError:
        print(f"Error: Image file not found: {image_path}")
        return False
    except Exception as e:
        print(f"Error: {e}")
        return False

def main():
    # Configuration
    API_URL = "http://localhost:5000"  # Change this to your deployed URL

    if len(sys.argv) > 1:
        API_URL = sys.argv[1]

    print(f"\n{'#'*50}")
    print(f"# Testing Palm Seedling Classifier API")
    print(f"# API URL: {API_URL}")
    print(f"{'#'*50}")

    # Test health endpoint
    health_ok = test_health(API_URL)

    if not health_ok:
        print("\n❌ Health check failed! Please check if the API is running.")
        return

    print("\n✓ Health check passed!")

    # Test classification (only if image provided)
    if len(sys.argv) > 2:
        image_path = sys.argv[2]
        classify_ok = test_classify(API_URL, image_path)

        if classify_ok:
            print("\n✓ Classification test passed!")
        else:
            print("\n❌ Classification test failed!")
    else:
        print("\n⚠ No image provided for classification test.")
        print("Usage: python test_local.py [API_URL] [IMAGE_PATH]")
        print("Example: python test_local.py http://localhost:5000 bibit.jpg")

    print("\n" + "="*50)
    print("Test completed!")
    print("="*50 + "\n")

if __name__ == "__main__":
    main()