crossprism commited on
Commit
1a8eef2
1 Parent(s): 3451cbe

Setup space and examples for demoing keyed model

Browse files
Files changed (6) hide show
  1. app.py +28 -0
  2. helper.py +70 -0
  3. requirements.txt +2 -0
  4. test1.jpg +0 -0
  5. test2.jpg +0 -0
  6. test3.jpg +0 -0
app.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import platform
4
+ from helper import CoreMLPipeline
5
+
6
+ force_tf = os.environ.get('FORCE_TF', False)
7
+ auth_key = os.environ.get('HF_TOKEN', True)
8
+
9
+ config = { "coreml_extractor_repoid":"crossprism/efficientnetv2-21k-fv-m",
10
+ "coreml_extractor_path":"efficientnetV2M21kExtractor.mlmodel",
11
+ "tf_extractor_repoid":"crossprism/efficientnetv2-21k-fv-m-tf",
12
+ "tf_extractor_path":"efficientnetv2-21k-fv-m",
13
+ "coreml_classifier_repoid":"crossprism/tesla_sentry_keyed",
14
+ "coreml_classifier_path":"sentry_keyed.mlpackage/Data/com.apple.CoreML/sentry_keyed.mlmodel"
15
+ }
16
+ use_tf = force_tf or (platform.system() != 'Darwin')
17
+
18
+ helper = CoreMLPipeline(config, auth_key, use_tf)
19
+
20
+ def classify_image(image):
21
+ resized = image.resize((480,480))
22
+ return helper.classify(resized)
23
+
24
+ image = gr.Image(type='pil')
25
+ label = gr.Label(num_top_classes=3)
26
+
27
+ gr.Interface(fn=classify_image, inputs=image, outputs=label, examples = [["test1.jpg"],["test2.jpg"],["test3.jpg"]]).launch()
28
+
helper.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+ import coremltools as ct
3
+ import numpy as np
4
+ import PIL
5
+ from huggingface_hub import hf_hub_download
6
+ from huggingface_hub import snapshot_download
7
+ import os
8
+
9
+ # Helper class to extract features from one model, and then feed those features into a classification head
10
+ # Because coremltools will only perform inference on OSX, an alternative tensorflow inference pipeline uses
11
+ # a tensorflow feature extractor and feeds the features into a dynamically created keras model based on the coreml classification head.
12
+ class CoreMLPipeline:
13
+ def __init__(self, config, auth_key, use_tf):
14
+ self.config = config
15
+ self.use_tf = use_tf
16
+ if use_tf:
17
+ extractor_path = snapshot_download(repo_id=config["tf_extractor_repoid"], use_auth_token = auth_key)
18
+ else:
19
+ extractor_path = hf_hub_download(repo_id=config["coreml_extractor_repoid"],
20
+ filename=config["coreml_extractor_path"], use_auth_token = auth_key)
21
+
22
+ classifier_path = hf_hub_download(repo_id=config["coreml_classifier_repoid"], filename=config["coreml_classifier_path"],
23
+ use_auth_token = auth_key)
24
+
25
+ print(f"Loading extractor...{extractor_path}")
26
+ if use_tf:
27
+ self.extractor = tf.saved_model.load(os.path.join(extractor_path, config["tf_extractor_path"]))
28
+ else:
29
+ self.extractor = ct.models.MLModel(extractor_path)
30
+
31
+ print(f"Loading classifier...{classifier_path}")
32
+ self.classifier = ct.models.MLModel(classifier_path)
33
+
34
+ if use_tf:
35
+ self.make_keras_model()
36
+
37
+ #Only MacOS can run inference on CoreML models. Convert it to tensorflow to match the tf feature extractor
38
+ def make_keras_model(self):
39
+ spec = self.classifier.get_spec()
40
+ nnClassifier = spec.neuralNetworkClassifier
41
+ labels = nnClassifier.stringClassLabels.vector
42
+ input = tf.keras.Input(shape = (1280))
43
+ activation = "sigmoid" if len(labels) == 1 else "softmax"
44
+ x = tf.keras.layers.Dense(len(labels), activation = activation)(input)
45
+ model = tf.keras.Model(input,x, trainable = False)
46
+ weights = np.array(nnClassifier.layers[0].innerProduct.weights.floatValue)
47
+ weights = weights.reshape((len(labels),1280))
48
+ weights = weights.T
49
+ bias = np.array(nnClassifier.layers[0].innerProduct.bias.floatValue)
50
+ model.set_weights([weights,bias])
51
+ self.tf_model = model
52
+ self.labels = labels
53
+
54
+ def classify(self,resized):
55
+ if self.use_tf:
56
+ image = tf.image.convert_image_dtype(resized, tf.float32)
57
+ image = tf.expand_dims(image, 0)
58
+ features = self.extractor.signatures['serving_default'](image)
59
+ input = {"input_1":features["output_1"]}
60
+ output = self.tf_model.predict(input)
61
+ results = {}
62
+ for i,label in enumerate(self.labels):
63
+ results[label] = output[i]
64
+ else:
65
+ features = self.extractor.predict({"image":resized})
66
+ features = features["Identity"]
67
+ output = self.classifier.predict({"features":features[0]})
68
+ results = output["Identity"]
69
+ return results
70
+
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ coremltools==7.2
2
+ tensorflow==2.15
test1.jpg ADDED
test2.jpg ADDED
test3.jpg ADDED