File size: 11,464 Bytes
b2812ca 376fec0 b2812ca 241b45e 376fec0 241b45e 376fec0 241b45e 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 b2812ca 376fec0 241b45e 62f817f 241b45e 95742d9 3818f17 6c49d4c 3818f17 6c49d4c 3818f17 6c49d4c 3818f17 6c49d4c 241b45e 95742d9 6c49d4c 95742d9 6c49d4c 95742d9 6c49d4c 95742d9 241b45e 95742d9 241b45e 376fec0 241b45e 376fec0 b2812ca 241b45e b2812ca 376fec0 b2812ca 241b45e 376fec0 b2812ca 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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | #!/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()}
|