age-gender-model / handler.py
fanclan's picture
Upload folder using huggingface_hub
3818f17 verified
Raw History Blame Contribute Delete
11.5 kB
#!/usr/bin/env python3
import os
import io
import json
import torch
import numpy as np
from PIL import Image
import onnxruntime as ort
from torchvision import transforms
import glob
class AgeGenderPredictor:
def __init__(self, model_path=None):
# Load the model - search in multiple locations
if model_path is None:
model_path = os.environ.get("MODEL_PATH", "model_quantized.onnx")
# Try different potential locations for the model file
possible_paths = [
model_path,
os.path.join(os.path.dirname(__file__), model_path),
os.path.join("/repository", model_path),
os.path.join("/app", model_path),
os.path.join("/repository", "model_quantized.onnx"),
os.path.join("/app", "model_quantized.onnx"),
]
# Also search for any .onnx files in the current directory
onnx_files = (
glob.glob("*.onnx")
+ glob.glob("/repository/*.onnx")
+ glob.glob("/app/*.onnx")
)
possible_paths.extend(onnx_files)
# Try to load the model from any of the possible paths
model_loaded = False
for path in possible_paths:
if os.path.exists(path):
print(f"Found model at: {path}")
try:
self.session = ort.InferenceSession(path)
model_loaded = True
print(f"Successfully loaded model from: {path}")
break
except Exception as e:
print(f"Error loading model from {path}: {str(e)}")
if not model_loaded:
available_files = os.listdir(os.path.dirname(__file__))
raise RuntimeError(
f"Could not find model file. Searched paths: {possible_paths}. Available files: {available_files}"
)
self.input_name = self.session.get_inputs()[0].name
self.output_names = [output.name for output in self.session.get_outputs()]
# Image preprocessing
self.transform = transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]
)
# Load class mappings (this should be adjusted based on your actual classes)
# Age classes (example, replace with your actual mappings)
self.age_classes = os.environ.get(
"AGE_CLASSES", "18-24,25-34,35-44,45-54,55+"
).split(",")
# Gender classes
self.gender_classes = ["Woman", "Man"]
def preprocess(self, image_bytes):
# Convert bytes to PIL Image
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
# Apply transformations
image_tensor = self.transform(image)
# Add batch dimension
image_tensor = image_tensor.unsqueeze(0)
return image_tensor.numpy()
def predict(self, image_bytes):
# Preprocess the image
input_data = self.preprocess(image_bytes)
# Run inference
results = self.session.run(self.output_names, {self.input_name: input_data})
# Process results
age_logits, gender_logits = results
# Reshape if needed
if age_logits.ndim == 1:
age_logits = age_logits.reshape(1, -1)
if gender_logits.ndim == 1:
gender_logits = gender_logits.reshape(1, -1)
age_pred = np.argmax(age_logits, axis=1)[0]
gender_pred = np.argmax(gender_logits, axis=1)[0]
# Calculate probabilities
age_probs = np.exp(age_logits) / np.sum(
np.exp(age_logits), axis=1, keepdims=True
)
gender_probs = np.exp(gender_logits) / np.sum(
np.exp(gender_logits), axis=1, keepdims=True
)
# Get prediction with confidence
age_confidence = float(age_probs[0][age_pred])
gender_confidence = float(gender_probs[0][gender_pred])
return {
"age": {
"prediction": self.age_classes[age_pred],
"confidence": age_confidence,
"all_probabilities": {
self.age_classes[i]: float(age_probs[0][i])
for i in range(len(self.age_classes))
},
},
"gender": {
"prediction": self.gender_classes[gender_pred],
"confidence": gender_confidence,
"all_probabilities": {
self.gender_classes[i]: float(gender_probs[0][i])
for i in range(len(self.gender_classes))
},
},
}
# HuggingFace Inference API EndpointHandler
class EndpointHandler:
def __init__(self, path=""):
"""Initialize the model"""
print(f"Initializing EndpointHandler with path: {path}")
try:
self.predictor = AgeGenderPredictor(path)
print("Predictor initialized successfully")
except Exception as e:
import traceback
print(f"Error initializing predictor: {str(e)}")
print(traceback.format_exc())
raise e
def __call__(self, data, headers=None):
try:
image_bytes = None
content_type = headers.get("content-type", "").lower() if headers else ""
# Check if data might be wrapped in {"inputs": <binary_data>} even with image Content-Type
potential_inputs = data
if isinstance(data, dict) and "inputs" in data:
potential_inputs = data["inputs"]
# Priority for direct binary/file uploads or wrapped binary data
if "image/" in content_type or "application/octet-stream" in content_type:
if isinstance(potential_inputs, bytes):
image_bytes = potential_inputs
elif hasattr(potential_inputs, "read"): # For file-like objects
image_bytes = potential_inputs.read()
# If not handled by direct/wrapped binary, check for JSON payloads (URL or base64)
if image_bytes is None:
# This 'potential_inputs' is the one already extracted if data was {"inputs": ...}
# If data was not a dict with "inputs", potential_inputs is still the original 'data'
# If it was a JSON request for URL/base64, 'inputs' would have been extracted above.
# We need to re-evaluate 'potential_inputs' or the original 'data' for URL/base64 cases.
current_data_to_check = data # Start with original data for JSON checks
if isinstance(data, dict) and "inputs" in data:
current_data_to_check = data[
"inputs"
] # Use content of 'inputs' for JSON struct
if (
isinstance(current_data_to_check, dict)
and "url" in current_data_to_check
):
import requests
image_url = current_data_to_check["url"]
request_headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
resp = requests.get(image_url, headers=request_headers)
if resp.status_code != 200:
return [
{
"label": "error",
"score": 0.0,
"detail": f"Failed to download image from URL: {image_url} (Status: {resp.status_code})",
}
]
image_bytes = resp.content
elif isinstance(current_data_to_check, str):
import base64
try:
image_bytes = base64.b64decode(current_data_to_check)
except Exception:
return [
{
"label": "error",
"score": 0.0,
"detail": "Invalid base64 string",
}
]
# Final fallback for raw bytes if no other case matched and image_bytes is still None
elif isinstance(data, bytes) and image_bytes is None:
image_bytes = (
data # Use original data if it's bytes and not yet processed
)
if image_bytes is None:
return [
{
"label": "error",
"score": 0.0,
"detail": "Could not determine image data from input. Final check.",
}
]
# Get predictions
result = self.predictor.predict(image_bytes)
# Format output as required by Hugging Face (Array<{label, score}>)
output = [
{
"label": f"age: {result['age']['prediction']}",
"score": result["age"]["confidence"],
},
{
"label": f"gender: {result['gender']['prediction']}",
"score": result["gender"]["confidence"],
},
]
return output
except Exception as e:
import traceback
return [
{
"label": "error",
"score": 0.0,
"detail": str(e),
"traceback": traceback.format_exc(),
}
]
# Initialize the predictor for direct use
try:
predictor = AgeGenderPredictor()
except Exception as e:
import sys
print(f"Error initializing standalone predictor: {str(e)}", file=sys.stderr)
predictor = None
# Handler function for backward compatibility
def handler(data, context):
"""Handle inference requests"""
try:
if not data:
return {"error": "No data provided"}
# Check if the request contains binary data (image)
if context and context.get("content-type") in [
"image/jpeg",
"image/png",
"application/octet-stream",
]:
# Process binary image data
image_bytes = data
elif hasattr(data, "read"):
# Handle file-like objects
image_bytes = data.read()
else:
# Try to parse as base64 string
try:
import base64
image_bytes = base64.b64decode(data)
except:
return {"error": "Invalid image format. Please provide a valid image."}
# Get predictions
if predictor is None:
# Create a temporary predictor
temp_predictor = AgeGenderPredictor()
predictions = temp_predictor.predict(image_bytes)
else:
predictions = predictor.predict(image_bytes)
return predictions
except Exception as e:
import traceback
return {"error": str(e), "traceback": traceback.format_exc()}