How to serve with input as base64
I trying to follow the hub/examples/image_retraining/ example to export a saved model. The problem is I don't know how to change the input to base64, currently it only accept a Tensor
I code snippet of what you are trying to do with a resulting error would help here. Are you following the canonical TF serving example ( https://github.com/tensorflow/serving/blob/master/tensorflow_serving/example/resnet_client.py) on the client side to perform inference?
On Mon, Nov 19, 2018 at 2:56 AM phachutoan [email protected] wrote:
I trying to follow the hub/examples/image_retraining/ example to export a saved model. The problem is I don't know how to change the input to base64, currently it only accept a Tensor
— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/tensorflow/hub/issues/192, or mute the thread https://github.com/notifications/unsubscribe-auth/AbunTDneTE3veEbv6TAPyuu5tffHPsHaks5uwg_EgaJpZM4YoRzH .
@akhorlin This may be the client I want but what about server, how to export the model so that it can accept base64 input?
I tried to modified the export_model function like below
def export_model(module_spec, class_count, saved_model_dir):
"""Exports model for serving.
Args:
module_spec: The hub.ModuleSpec for the image module being used.
class_count: The number of classes.
saved_model_dir: Directory in which to save exported model and variables.
"""
# The SavedModel should hold the eval graph.
sess, in_image, _, _, _, _ = build_eval_session(module_spec, class_count)
# Shape of [None] means we can have a batch of images.
image = tf.placeholder(shape=[None], dtype=tf.string)
with sess.graph.as_default() as graph:
tf.saved_model.simple_save(
sess,
saved_model_dir,
#inputs={'image': in_image},
inputs = {'image_bytes': image},
outputs={'prediction': graph.get_tensor_by_name('final_result:0')},
legacy_init_op=tf.group(tf.tables_initializer(), name='legacy_init_op')
)
But i got error when call the prediction with REST api
{
"error": "Tensor Placeholder_1:0, specified in either feed_devices or fetch_devices was not found in the Graph"
}
I think the general advice for processing base64 input like mentioned for example on this thread https://stackoverflow.com/questions/47943133/how-to-pass-base64-encoded-image-to-tensorflow-prediction would still apply.
On Tue, Nov 20, 2018 at 12:45 AM phachutoan [email protected] wrote:
@akhorlin https://github.com/akhorlin This may be the client I want but what about server, how to export the model so that it can accept base64 input?
— You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/tensorflow/hub/issues/192#issuecomment-440083469, or mute the thread https://github.com/notifications/unsubscribe-auth/AbunTJgrWCXCmWrNEi1nAYLYxuO5hEfyks5uw0KvgaJpZM4YoRzH .
Please re-open if the reference to the stackoverflow thread wasn't helpful in resolving this issue.
I tried using that thread, but it still doesn't work. Here is my code:
` def export_model(module_spec, class_count, saved_model_dir): sess, in_image, _, _, _, _ = build_eval_session(module_spec, class_count)
image = tf.placeholder(shape=[None], dtype=tf.string) export_dir = "/tmp/save/"
inputs = {'image_bytes': image} with sess.graph.as_default() as graph: tf.saved_model.simple_save(sess, export_dir, inputs, {'prediction': graph.get_tensor_by_name('final_result:0')}) `
hello, got any solution now?
Hi. I have also been dealing with this particular problem on using images as input for tf serving. Documentation only deals with either serve side or client-side separately.
So far, there are no standard method established for both server-side and client-side for b64 encoding in tf serving. If anyone has an idea where we can find documentation/guide for both sides, that would be great.
For tensorflow object detection api, the first step is to export the trained model in the appropriate format. Use export_inference_graph.py like this
python export_inference_graph \
--input_type encoded_image_string_tensor \
--pipeline_config_path path/to/ssd_inception_v2.config \
--trained_checkpoint_prefix path/to/model.ckpt \
--output_directory path/to/exported_model_directory
in the above code snippet, it is important to specify
--input_type encoded_image_string_tensor
after exporting the model, run the tensorflow server as usual with the newly exported model.
The inference code will look like this:
from __future__ import print_function
import base64
import requests
SERVER_URL = 'http://localhost:8501/v1/models/vedNet:predict'
IMAGE_URL = 'test_images/19_inp.jpg'
def main():
with open(IMAGE_URL, "rb") as image_file:
jpeg_bytes = base64.b64encode(image_file.read()).decode('utf-8')
predict_request = '{"instances" : [{"b64": "%s"}]}' % jpeg_bytes
response = requests.post(SERVER_URL, predict_request)
response.raise_for_status()
prediction = response.json()['predictions'][0]
if __name__ == '__main__':
main()
you can do that :
def build_mnist_model():
input = Input(shape=(28, 28, 1), name='input')
x = Conv2D(filters=64, kernel_size=(3, 3))(input)
x = AveragePooling2D(2)(x)
x = Conv2D(filters=64, kernel_size=(3, 3))(x)
x = AveragePooling2D(2)(x)
x = Flatten()(x)
x = Dense(128)(x)
output = Dense(10, activation='softmax', name='output')(x)
model = tf.keras.Model(input, output)
model.summary()
model.compile(optimizer=tf.optimizers.Adam(), loss=tf.losses.SparseCategoricalCrossentropy(), metrics=['acc'])
return model
def train_model():
from tensorflow.keras.datasets import mnist
(train_x, train_y), (test_x, test_y) = mnist.load_data()
print(train_y[:10])
model = build_mnist_model()
model.fit(train_x, train_y, validation_data=(test_x, test_y), epochs=1)
model_path = '/tmp/mymodel.h5'
model.save(model_path)
def load_model():
model_path = '/tmp/mymodel.h5'
model = tf.keras.models.load_model(model_path)
model.summary()
def decode_jpeg(x):
x = tf.io.decode_base64(x)
x =tf.image.resize(tf.image.decode_jpeg(x, channels=1), [28, 28])
x = tf.reshape(x, [28, 28, 1])
return x
@tf.function()
def serve_predict(input):
model_base64_input = tf.map_fn(lambda x: decode_jpeg(x), input, fn_output_signature=tf.float32)
pixels = model_base64_input
input = {
'input': pixels,
}
prediction = model(input)
return prediction
serve_predict = serve_predict.get_concrete_function(input=tf.TensorSpec([None, ], dtype=tf.string))
tf.saved_model.save(
model,
'/tmp/tf_model',
signatures=serve_predict
)
pass
def predict():
tf_model_path = '/tmp/tf_model'
loaded = tf.saved_model.load(tf_model_path)
sig_name = list(loaded.signatures.keys())[0]
print(sig_name)
infer = loaded.signatures[sig_name]
base64_str = get_base64_str()
nd_array = np.array([base64_str])
print(nd_array)
tensor = tf.convert_to_tensor(nd_array)
output = infer(tensor)
print(output)
@boluoyu i ran the same code as you for my model, but i am getting error
Invalid character found in base64.
[[{{node StatefulPartitionedCall/map/while/body/_98/map/while/DecodeBase64}}]] [Op:__inference_signature_wrapper_9028]
can you help ?
@boluoyu i ran the same code as you for my model, but i am getting error
Invalid character found in base64. [[{{node StatefulPartitionedCall/map/while/body/_98/map/while/DecodeBase64}}]] [Op:__inference_signature_wrapper_9028]can you help ? @kunalchamoli you can use web-safe base 64 encoding ,in python
base64.urlsafe_b64encode(image_bytes)