age-gender-model / test_handler.py
fanclan's picture
Upload folder using huggingface_hub
241b45e verified
Raw History Blame Contribute Delete
4.5 kB
#!/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'}.")