age_detection_regression / inference_log.py
Sharris's picture
Upload folder using huggingface_hub
de3c81a verified
import traceback
from pathlib import Path
log_path = Path('inference_log.txt')
with log_path.open('w', encoding='utf-8') as f:
def log(*args, **kwargs):
print(*args, file=f, **kwargs)
f.flush()
try:
log('Starting inference log')
import tensorflow as tf
import numpy as np
from PIL import Image
model_path = 'saved_model_age_regressor'
img_path = Path('data/UTKFace/53_1_1_20170110122449716.jpg.chip.jpg')
log('Model path:', model_path)
log('Image path:', str(img_path))
log('Attempting to load model with compile=False...')
m = tf.keras.models.load_model(model_path, compile=False)
log('Loaded model type:', type(m))
try:
m.summary(print_fn=lambda *a, **k: log(*a, **k))
except Exception as e:
log('model.summary failed:', e)
img = Image.open(img_path).convert('RGB').resize((224,224))
arr = np.array(img, dtype=np.float32)/255.0
x = np.expand_dims(arr, 0)
log('Input shape:', x.shape)
log('Running predict...')
pred = m.predict(x)
log('Raw prediction output:', pred, 'shape:', getattr(pred, 'shape', None))
try:
log('Predicted age:', float(pred.flatten()[0]))
except Exception as e:
log('Error converting prediction to float:', e)
log('Inference finished successfully')
except Exception:
traceback.print_exc(file=f)
log('Inference script caught exception')