File size: 4,499 Bytes
376fec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241b45e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376fec0
241b45e
376fec0
 
 
 
 
 
 
 
 
 
 
 
241b45e
376fec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Test script to verify the updated handler.py can find and load the model correctly.
"""
import os
import sys
import time
from PIL import Image
import io


def test_handler():
    print("Testing handler.py with model loading...")

    # Temporarily rename model to simulate different path configurations
    orig_model_path = "model_quantized.onnx"
    temp_model_path = "renamed_model.onnx"

    # Check if model exists
    if not os.path.exists(orig_model_path):
        print(
            f"Error: {orig_model_path} not found. Please make sure the model file exists."
        )
        return False

    try:
        # Simulate different model locations
        os.rename(orig_model_path, temp_model_path)

        # Set environment variable to point to the renamed model
        os.environ["MODEL_PATH"] = temp_model_path

        # Import the handler module
        print("Importing handler module...")
        import handler

        # Check if predictor was created successfully
        if not hasattr(handler, "predictor"):
            print("Error: Predictor not created in handler module.")
            return False

        # Test the EndpointHandler class (for Hugging Face Inference API)
        print(
            "\nTesting EndpointHandler class (required for Hugging Face Inference API)..."
        )
        try:
            endpoint_handler = handler.EndpointHandler(temp_model_path)
            print("EndpointHandler initialized successfully.")

            # Test with a sample image
            if os.path.exists("test_image.jpg"):
                print("Testing EndpointHandler with test_image.jpg...")
                with open("test_image.jpg", "rb") as f:
                    image_bytes = f.read()

                # Call the EndpointHandler
                result = endpoint_handler(image_bytes, {"content-type": "image/jpeg"})

                # Check result
                if "error" in result:
                    print(f"Error in EndpointHandler prediction: {result['error']}")
                    return False

                # Print prediction results
                print("\nEndpointHandler Prediction Results:")
                print(
                    f"Age: {result['age']['prediction']} (Confidence: {result['age']['confidence']*100:.2f}%)"
                )
                print(
                    f"Gender: {result['gender']['prediction']} (Confidence: {result['gender']['confidence']*100:.2f}%)"
                )
            else:
                print(
                    "Warning: test_image.jpg not found. Skipping EndpointHandler prediction test."
                )
        except Exception as e:
            print(f"Error testing EndpointHandler: {str(e)}")
            import traceback

            print(traceback.format_exc())
            return False

        # Test the legacy handler function
        if os.path.exists("test_image.jpg"):
            print("\nTesting legacy handler function...")
            with open("test_image.jpg", "rb") as f:
                image_bytes = f.read()

            # Call the handler
            result = handler.handler(image_bytes, {"content-type": "image/jpeg"})

            # Check result
            if "error" in result:
                print(f"Error in prediction: {result['error']}")
                return False

            # Print prediction results
            print("\nLegacy Handler Prediction Results:")
            print(
                f"Age: {result['age']['prediction']} (Confidence: {result['age']['confidence']*100:.2f}%)"
            )
            print(
                f"Gender: {result['gender']['prediction']} (Confidence: {result['gender']['confidence']*100:.2f}%)"
            )
            print("\nTest completed successfully!")

        else:
            print("Warning: test_image.jpg not found. Skipping prediction test.")

        return True

    except Exception as e:
        print(f"Error testing handler: {str(e)}")
        import traceback

        print(traceback.format_exc())
        return False

    finally:
        # Restore original model name
        try:
            if os.path.exists(temp_model_path):
                os.rename(temp_model_path, orig_model_path)
                os.environ.pop("MODEL_PATH", None)
        except Exception as e:
            print(f"Error restoring model file: {str(e)}")


if __name__ == "__main__":
    success = test_handler()
    print(f"\nTest {'succeeded' if success else 'failed'}.")