File size: 5,035 Bytes
d812b8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Export a trained FER2013 Keras model to a verified browser ONNX bundle.

Run from project_demo, or pass --output-dir explicitly. No training occurs.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path

os.environ.setdefault('TF_CPP_MIN_LOG_LEVEL', '2')
LABELS = ['Angry', 'Disgust', 'Fear', 'Happy', 'Neutral', 'Sad', 'Surprise']


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--checkpoint', type=Path, required=True)
    parser.add_argument('--id', choices=['cnn', 'resnet', 'mobilenet', 'vgg16'], default='cnn')
    parser.add_argument('--output-dir', type=Path, default=Path(__file__).resolve().parents[1] / 'models')
    parser.add_argument('--verify-images', type=Path, help='Optional directory of cropped face images; checks at most 32.')
    args = parser.parse_args()
    if not args.checkpoint.is_file():
        parser.error(f'Checkpoint not found: {args.checkpoint}')
    import numpy as np
    import tensorflow as tf
    import tf2onnx
    import onnxruntime as ort

    model = tf.keras.models.load_model(args.checkpoint, compile=False)
    if isinstance(model.input_shape, list) or tuple(model.input_shape[1:]) != (48, 48, 3):
        raise ValueError(f'Expected one RGB input (None,48,48,3), got {model.input_shape}')
    if isinstance(model.output_shape, list) or model.output_shape[-1] != 7:
        raise ValueError(f'Expected one seven-class output, got {model.output_shape}')
    signature = [tf.TensorSpec([1, 48, 48, 3], tf.float32, name='face_rgb')]

    @tf.function(input_signature=signature)
    def inference(face_rgb):
        return tf.identity(model(face_rgb, training=False), name='probabilities')

    args.output_dir.mkdir(parents=True, exist_ok=True)
    output_path = args.output_dir / f'{args.id}.onnx'
    temporary_path = args.output_dir / f'.{args.id}.temporary.onnx'
    try:
        tf2onnx.convert.from_function(inference, input_signature=signature, opset=17, output_path=str(temporary_path))
        session = ort.InferenceSession(str(temporary_path), providers=['CPUExecutionProvider'])
        input_name = session.get_inputs()[0].name
        output_name = session.get_outputs()[0].name
        rng = np.random.default_rng(42)
        samples = [np.zeros((1, 48, 48, 3), dtype=np.float32), np.ones((1, 48, 48, 3), dtype=np.float32)]
        samples += [rng.integers(0, 256, (1, 48, 48, 3)).astype(np.float32) / 255 for _ in range(6)]
        if args.verify_images:
            if not args.verify_images.is_dir():
                raise ValueError('--verify-images must be an existing directory.')
            import cv2
            files = sorted(p for p in args.verify_images.rglob('*') if p.suffix.lower() in {'.jpg', '.jpeg', '.png', '.webp'})[:32]
            if not files:
                raise ValueError('No supported cropped face images found in --verify-images.')
            for file in files:
                image = cv2.imread(str(file), cv2.IMREAD_COLOR)
                if image is None:
                    raise ValueError(f'Could not decode image: {file}')
                rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                rgb = cv2.resize(rgb, (48, 48), interpolation=cv2.INTER_AREA)
                samples.append(rgb.astype(np.float32)[None, ...] / 255)
        max_error = 0.0
        for sample in samples:
            original = model(sample, training=False).numpy()
            converted = session.run([output_name], {input_name: sample})[0]
            np.testing.assert_allclose(converted, original, atol=1e-4, rtol=1e-3)
            if converted.shape != (1, 7) or not np.isfinite(converted).all() or np.min(converted) < 0:
                raise ValueError('The exported model did not return seven valid probabilities.')
            np.testing.assert_allclose(converted.sum(axis=1), [1], atol=1e-3)
            max_error = max(max_error, float(np.abs(converted - original).max()))
        # Publish a matching pair only after conversion checks pass.
        temporary_path.replace(output_path)
        metadata = dict(
            format='onnx', modelFile=output_path.name, inputLayout='NHWC',
            inputShape=[1, 48, 48, 3], normalization='rgb/255', labels=LABELS,
            inputName=input_name, outputName=output_name,
            sha256=hashlib.sha256(output_path.read_bytes()).hexdigest(),
            checkpoint=args.checkpoint.name,
            verification={'samples': len(samples), 'maxAbsoluteError': max_error,
                          'note': 'Conversion parity check; not a new FER2013 accuracy measurement.'}
        )
        (args.output_dir / f'{args.id}.json').write_text(json.dumps(metadata, indent=2) + '\n', encoding='utf-8')
        print(f'Exported {output_path.name} and {args.id}.json')
        print(f'Keras/ONNX parity: {len(samples)} inputs; maximum difference {max_error:.8f}')
        print('Label order: ' + ', '.join(LABELS))
    finally:
        temporary_path.unlink(missing_ok=True)


if __name__ == '__main__':
    main()