B ny`^@sFddlZddlZddlZddlZd ddZddZddZ d d Z dS) N5https://tfhub.dev/google/imagenet/{}/classification/2c Csd}d||}||}tjtd}t|}|}|dj} |d} dt | | di} || d} tj j | dd} tj j | |ddd\}}||d }| ttgtjj||| |d WdQRX|S) aDownload a model from TensorFlow Hub, add inputs and outputs suitable for serving inference requests, and export the resulting graph as a SavedModel. This function should work for most image classification model on TensorFlow Hub. Args: model_name (str): The model name (e.g. mobilenet_v2_140_224) export_path (str): The exported model will be saved at / uri_pattern (str): Optional. The model name is combined with this pattern to form a TensorFlow Hub uri. The default value works for MobileNetV2, but a different pattern may be needed for other models. Returns: str: The path to the exported SavedModel (including model_name and version). z{}/{}/00000001)graphimagesN)nameT)ksortedr)classes probabilities)inputsoutputs)formattfSessionGraphhubModuleget_input_info_dictdtype get_shape placeholdernnsoftmaxtop_krunglobal_variables_initializertables_initializer saved_model simple_save) model_name export_pathZ uri_patternZtopk model_pathZ tfhub_urisessmoduleZ input_paramsrshaper logitsrprobsr r r'>/root/amazon-sagemaker-tensorflow-serving-grpc/sample_utils.pytfhub_to_savedmodels*      r)cCs`t|}tj|dtjd}t|tj}t|}t| ddddtj }tj |dd}|S)zReads an image file and coverts it to a tensor (ndarray). Resizing of input is done (224x224 for the mobilenet_v2_140_224 model). Args: path (str): The file name or path to the image file. )r*)Zdsize interpolationfloatNr)axis) cv2ZimreadresizeZ INTER_CUBICZcvtColorZ COLOR_BGR2RGBnpasarray normalizeastypeZ NORM_MINMAX expand_dims)pathimager'r'r(image_file_to_tensor=s  r8c s\gtdd}dd|DWdQRXx.|dD]"}fdd|dD}||d <q2WdS) zvAdd imagenet class labels to the prediction result. The prediction_result argument will be modified in place. z labels.txtrcSsg|] }|qSr')strip).0lr'r'r( Wsz'add_imagenet_labels..N predictionscsg|]}|dqS)r-r')r;x)labelsr'r(r=[sr r@)open)prediction_resultfpredZprediction_labelsr')r@r(add_imagenet_labelsOs  rEcCsXxR|dD]F}x:tdt|dD]$}td|d||d|q"Wtq WdS)z!Print the labelled results." r>rr@z {:1.7f} {}r N)rangelenprintr )Zlabelled_resultrDir'r'r(print_probabilities_and_labels_s  rJ)r) tensorflowrtensorflow_hubrnumpyr1r/r)r8rErJr'r'r'r(s 5