LiteRT Metadata Writer APIStay organized with collectionsSave and categorize content based on your preferences.
Copyright 2024 The AI Edge Authors.
Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
ImageClassifierWriter=image_classifier.MetadataWriter_MODEL_PATH="mobilenet_v2_1.0_224.tflite"# Task Library expects label files that are in the same format as the one below._LABEL_FILE="mobilenet_labels.txt"_SAVE_TO_PATH="mobilenet_v2_1.0_224_metadata.tflite"# Normalization parameters is required when reprocessing the image. It is# optional if the image pixel values are in range of [0, 255] and the input# tensor is quantized to uint8. See the introduction for normalization and# quantization parameters below for more details.# https://www.tensorflow.org/lite/models/convert/metadata#normalization_and_quantization_parameters)_INPUT_NORM_MEAN=127.5_INPUT_NORM_STD=127.5# Create the metadata writer.writer=ImageClassifierWriter.create_for_inference(writer_utils.load_file(_MODEL_PATH),[_INPUT_NORM_MEAN],[_INPUT_NORM_STD],[_LABEL_FILE])# Verify the metadata generated by metadata writer.print(writer.get_metadata_json())# Populate the metadata into the model.writer_utils.save_file(writer.populate(),_SAVE_TO_PATH)
ObjectDetectorWriter=object_detector.MetadataWriter_MODEL_PATH="ssd_mobilenet_v1.tflite"# Task Library expects label files that are in the same format as the one below._LABEL_FILE="ssd_mobilenet_labels.txt"_SAVE_TO_PATH="ssd_mobilenet_v1_metadata.tflite"# Normalization parameters is required when reprocessing the image. It is# optional if the image pixel values are in range of [0, 255] and the input# tensor is quantized to uint8. See the introduction for normalization and# quantization parameters below for more details.# https://ai.google.dev/edge/litert/conversion/tensorflow/metadata#normalization_and_quantization_parameters)_INPUT_NORM_MEAN=127.5_INPUT_NORM_STD=127.5# Create the metadata writer.writer=ObjectDetectorWriter.create_for_inference(writer_utils.load_file(_MODEL_PATH),[_INPUT_NORM_MEAN],[_INPUT_NORM_STD],[_LABEL_FILE])# Verify the metadata generated by metadata writer.print(writer.get_metadata_json())# Populate the metadata into the model.writer_utils.save_file(writer.populate(),_SAVE_TO_PATH)
ImageSegmenterWriter=image_segmenter.MetadataWriter_MODEL_PATH="deeplabv3.tflite"# Task Library expects label files that are in the same format as the one below._LABEL_FILE="deeplabv3_labels.txt"_SAVE_TO_PATH="deeplabv3_metadata.tflite"# Normalization parameters is required when reprocessing the image. It is# optional if the image pixel values are in range of [0, 255] and the input# tensor is quantized to uint8. See the introduction for normalization and# quantization parameters below for more details.# https://ai.google.dev/edge/litert/conversion/tensorflow/metadata#normalization_and_quantization_parameters)_INPUT_NORM_MEAN=127.5_INPUT_NORM_STD=127.5# Create the metadata writer.writer=ImageSegmenterWriter.create_for_inference(writer_utils.load_file(_MODEL_PATH),[_INPUT_NORM_MEAN],[_INPUT_NORM_STD],[_LABEL_FILE])# Verify the metadata generated by metadata writer.print(writer.get_metadata_json())# Populate the metadata into the model.writer_utils.save_file(writer.populate(),_SAVE_TO_PATH)
NLClassifierWriter=nl_classifier.MetadataWriter_MODEL_PATH="movie_review.tflite"# Task Library expects label files and vocab files that are in the same formats# as the ones below._LABEL_FILE="movie_review_labels.txt"_VOCAB_FILE="movie_review_vocab.txt"# NLClassifier supports tokenize input string using the regex tokenizer. See# more details about how to set up RegexTokenizer below:# https://github.com/tensorflow/tflite-support/blob/master/tensorflow_lite_support/metadata/python/metadata_writers/metadata_info.py#L130_DELIM_REGEX_PATTERN=r"[^\w\']+"_SAVE_TO_PATH="moview_review_metadata.tflite"# Create the metadata writer.writer=nl_classifier.MetadataWriter.create_for_inference(writer_utils.load_file(_MODEL_PATH),metadata_info.RegexTokenizerMd(_DELIM_REGEX_PATTERN,_VOCAB_FILE),[_LABEL_FILE])# Verify the metadata generated by metadata writer.print(writer.get_metadata_json())# Populate the metadata into the model.writer_utils.save_file(writer.populate(),_SAVE_TO_PATH)
AudioClassifierWriter=audio_classifier.MetadataWriter_MODEL_PATH="yamnet.tflite"# Task Library expects label files that are in the same format as the one below._LABEL_FILE="yamnet_labels.txt"# Expected sampling rate of the input audio buffer._SAMPLE_RATE=16000# Expected number of channels of the input audio buffer. Note, Task library only# support single channel so far._CHANNELS=1_SAVE_TO_PATH="yamnet_metadata.tflite"# Create the metadata writer.writer=AudioClassifierWriter.create_for_inference(writer_utils.load_file(_MODEL_PATH),_SAMPLE_RATE,_CHANNELS,[_LABEL_FILE])# Verify the metadata generated by metadata writer.print(writer.get_metadata_json())# Populate the metadata into the model.writer_utils.save_file(writer.populate(),_SAVE_TO_PATH)
Create Model Metadata with semantic information
You can fill in more descriptive information about the model and each tensor through the Metadata Writer API to help improve model understanding. It can be done through the 'create_from_metadata_info' method in each metadata writer. In general, you can fill in data through the parameters of 'create_from_metadata_info', i.e.general_md,input_md, andoutput_md. See the example below to create a rich Model Metadata for image classifers.
model_buffer=writer_utils.load_file("mobilenet_v2_1.0_224.tflite")# Create general model information.general_md=metadata_info.GeneralMd(name="ImageClassifier",version="v1",description=("Identify the most prominent object in the image from a ""known set of categories."),author="LiteRT",licenses="Apache License. Version 2.0")# Create input tensor information.input_md=metadata_info.InputImageTensorMd(name="input image",description=("Input image to be classified. The expected image is ""128 x 128, with three channels (red, blue, and green) per ""pixel. Each element in the tensor is a value between min and ""max, where (per-channel) min is [0] and max is [255]."),norm_mean=[127.5],norm_std=[127.5],color_space_type=_metadata_fb.ColorSpaceType.RGB,tensor_type=writer_utils.get_input_tensor_types(model_buffer)[0])# Create output tensor information.output_md=metadata_info.ClassificationTensorMd(name="probability",description="Probabilities of the 1001 labels respectively.",label_files=[metadata_info.LabelFileMd(file_path="mobilenet_labels.txt",locale="en")],tensor_type=writer_utils.get_output_tensor_types(model_buffer)[0])
Step 4: Create metadata writer and populate.
ImageClassifierWriter=image_classifier.MetadataWriter# Create the metadata writer.writer=ImageClassifierWriter.create_from_metadata_info(model_buffer,general_md,input_md,output_md)# Verify the metadata generated by metadata writer.print(writer.get_metadata_json())# Populate the metadata into the model.writer_utils.save_file(writer.populate(),_SAVE_TO_PATH)
Read the metadata populated to your model.
You can display the metadata and associated files in a TFLite model through the following code:
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-05-28 UTC."],[],[]]