Unverified Commit 00fa8b12 authored by cclauss's avatar cclauss Committed by GitHub
Browse files

Merge branch 'master' into patch-13

parents 6d257a4f 1f34fcaf
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.myorg</groupId>
<artifactId>label-image</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<exec.mainClass>LabelImage</exec.mainClass>
<!-- The sample code requires at least JDK 1.7. -->
<!-- The maven compiler plugin defaults to a lower version -->
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.tensorflow</groupId>
<artifactId>tensorflow</artifactId>
<version>1.4.0</version>
</dependency>
<!-- For ByteStreams.toByteArray: https://google.github.io/guava/releases/23.0/api/docs/com/google/common/io/ByteStreams.html -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.6-jre</version>
</dependency>
</dependencies>
</project>
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
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
http://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.
==============================================================================*/
import com.google.common.io.ByteStreams;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.Tensors;
/**
* Simplified version of
* https://github.com/tensorflow/tensorflow/blob/r1.4/tensorflow/java/src/main/java/org/tensorflow/examples/LabelImage.java
*/
public class LabelImage {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("USAGE: Provide a list of image filenames");
System.exit(1);
}
final List<String> labels = loadLabels();
try (Graph graph = new Graph();
Session session = new Session(graph)) {
graph.importGraphDef(loadGraphDef());
float[] probabilities = null;
for (String filename : args) {
byte[] bytes = Files.readAllBytes(Paths.get(filename));
try (Tensor<String> input = Tensors.create(bytes);
Tensor<Float> output =
session
.runner()
.feed("encoded_image_bytes", input)
.fetch("probabilities")
.run()
.get(0)
.expect(Float.class)) {
if (probabilities == null) {
probabilities = new float[(int) output.shape()[0]];
}
output.copyTo(probabilities);
int label = argmax(probabilities);
System.out.printf(
"%-30s --> %-15s (%.2f%% likely)\n",
filename, labels.get(label), probabilities[label] * 100.0);
}
}
}
}
private static byte[] loadGraphDef() throws IOException {
try (InputStream is = LabelImage.class.getClassLoader().getResourceAsStream("graph.pb")) {
return ByteStreams.toByteArray(is);
}
}
private static ArrayList<String> loadLabels() throws IOException {
ArrayList<String> labels = new ArrayList<String>();
String line;
final InputStream is = LabelImage.class.getClassLoader().getResourceAsStream("labels.txt");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
while ((line = reader.readLine()) != null) {
labels.add(line);
}
}
return labels;
}
private static int argmax(float[] probabilities) {
int best = 0;
for (int i = 1; i < probabilities.length; ++i) {
if (probabilities[i] > probabilities[best]) {
best = i;
}
}
return best;
}
}
images
labels
models
src/main/protobuf
target
# Object Detection in Java
Example of using pre-trained models of the [TensorFlow Object Detection
API](https://github.com/tensorflow/models/tree/master/research/object_detection)
in Java.
## Quickstart
1. Download some metadata files:
```
./download.sh
```
2. Download a model from the [object detection API model
zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md).
For example:
```
mkdir -p models
curl -L \
http://download.tensorflow.org/models/object_detection/ssd_inception_v2_coco_2017_11_17.tar.gz \
| tar -xz -C models/
```
3. Have some test images handy. For example:
```
mkdir -p images
curl -L -o images/test.jpg \
https://pixnio.com/free-images/people/mother-father-and-children-washing-dog-labrador-retriever-outside-in-the-fresh-air-725x483.jpg
```
4. Compile and run!
```
mvn -q compile exec:java \
-Dexec.args="models/ssd_inception_v2_coco_2017_11_17/saved_model labels/mscoco_label_map.pbtxt images/test.jpg"
```
## Notes
- This example demonstrates the use of the TensorFlow [SavedModel
format](https://www.tensorflow.org/programmers_guide/saved_model). If you have
TensorFlow for Python installed, you could explore the model to get the names
of the tensors using `saved_model_cli` command. For example:
```
saved_model_cli show --dir models/ssd_inception_v2_coco_2017_11_17/saved_model/ --all
```
- The file in `src/main/object_detection/protos/` was generated using:
```
./download.sh
protoc -Isrc/main/protobuf --java_out=src/main/java src/main/protobuf/string_int_label_map.proto
```
Where `protoc` was downloaded from
https://github.com/google/protobuf/releases/tag/v3.5.1
#!/bin/bash
set -ex
DIR="$(cd "$(dirname "$0")" && pwd -P)"
cd "${DIR}"
# The protobuf file needed for mapping labels to human readable names.
# From:
# https://github.com/tensorflow/models/blob/f87a58c/research/object_detection/protos/string_int_label_map.proto
mkdir -p src/main/protobuf
curl -L -o src/main/protobuf/string_int_label_map.proto "https://raw.githubusercontent.com/tensorflow/models/f87a58cd96d45de73c9a8330a06b2ab56749a7fa/research/object_detection/protos/string_int_label_map.proto"
# Labels from:
# https://github.com/tensorflow/models/tree/865c14c/research/object_detection/data
mkdir -p labels
curl -L -o labels/mscoco_label_map.pbtxt "https://raw.githubusercontent.com/tensorflow/models/865c14c1209cb9ae188b2a1b5f0883c72e050d4c/research/object_detection/data/mscoco_label_map.pbtxt"
curl -L -o labels/oid_bbox_trainable_label_map.pbtxt "https://raw.githubusercontent.com/tensorflow/models/865c14c1209cb9ae188b2a1b5f0883c72e050d4c/research/object_detection/data/oid_bbox_trainable_label_map.pbtxt"
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.myorg</groupId>
<artifactId>detect-objects</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<exec.mainClass>DetectObjects</exec.mainClass>
<!-- The sample code requires at least JDK 1.7. -->
<!-- The maven compiler plugin defaults to a lower version -->
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.tensorflow</groupId>
<artifactId>tensorflow</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.tensorflow</groupId>
<artifactId>proto</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
</project>
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
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
http://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.
==============================================================================*/
import static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap;
import static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem;
import com.google.protobuf.TextFormat;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import org.tensorflow.SavedModelBundle;
import org.tensorflow.Tensor;
import org.tensorflow.framework.MetaGraphDef;
import org.tensorflow.framework.SignatureDef;
import org.tensorflow.framework.TensorInfo;
import org.tensorflow.types.UInt8;
/**
* Java inference for the Object Detection API at:
* https://github.com/tensorflow/models/blob/master/research/object_detection/
*/
public class DetectObjects {
public static void main(String[] args) throws Exception {
if (args.length < 3) {
printUsage(System.err);
System.exit(1);
}
final String[] labels = loadLabels(args[1]);
try (SavedModelBundle model = SavedModelBundle.load(args[0], "serve")) {
printSignature(model);
for (int arg = 2; arg < args.length; arg++) {
final String filename = args[arg];
List<Tensor<?>> outputs = null;
try (Tensor<UInt8> input = makeImageTensor(filename)) {
outputs =
model
.session()
.runner()
.feed("image_tensor", input)
.fetch("detection_scores")
.fetch("detection_classes")
.fetch("detection_boxes")
.run();
}
try (Tensor<Float> scoresT = outputs.get(0).expect(Float.class);
Tensor<Float> classesT = outputs.get(1).expect(Float.class);
Tensor<Float> boxesT = outputs.get(2).expect(Float.class)) {
// All these tensors have:
// - 1 as the first dimension
// - maxObjects as the second dimension
// While boxesT will have 4 as the third dimension (2 sets of (x, y) coordinates).
// This can be verified by looking at scoresT.shape() etc.
int maxObjects = (int) scoresT.shape()[1];
float[] scores = scoresT.copyTo(new float[1][maxObjects])[0];
float[] classes = classesT.copyTo(new float[1][maxObjects])[0];
float[][] boxes = boxesT.copyTo(new float[1][maxObjects][4])[0];
// Print all objects whose score is at least 0.5.
System.out.printf("* %s\n", filename);
boolean foundSomething = false;
for (int i = 0; i < scores.length; ++i) {
if (scores[i] < 0.5) {
continue;
}
foundSomething = true;
System.out.printf("\tFound %-20s (score: %.4f)\n", labels[(int) classes[i]], scores[i]);
}
if (!foundSomething) {
System.out.println("No objects detected with a high enough score.");
}
}
}
}
}
private static void printSignature(SavedModelBundle model) throws Exception {
MetaGraphDef m = MetaGraphDef.parseFrom(model.metaGraphDef());
SignatureDef sig = m.getSignatureDefOrThrow("serving_default");
int numInputs = sig.getInputsCount();
int i = 1;
System.out.println("MODEL SIGNATURE");
System.out.println("Inputs:");
for (Map.Entry<String, TensorInfo> entry : sig.getInputsMap().entrySet()) {
TensorInfo t = entry.getValue();
System.out.printf(
"%d of %d: %-20s (Node name in graph: %-20s, type: %s)\n",
i++, numInputs, entry.getKey(), t.getName(), t.getDtype());
}
int numOutputs = sig.getOutputsCount();
i = 1;
System.out.println("Outputs:");
for (Map.Entry<String, TensorInfo> entry : sig.getOutputsMap().entrySet()) {
TensorInfo t = entry.getValue();
System.out.printf(
"%d of %d: %-20s (Node name in graph: %-20s, type: %s)\n",
i++, numOutputs, entry.getKey(), t.getName(), t.getDtype());
}
System.out.println("-----------------------------------------------");
}
private static String[] loadLabels(String filename) throws Exception {
String text = new String(Files.readAllBytes(Paths.get(filename)), StandardCharsets.UTF_8);
StringIntLabelMap.Builder builder = StringIntLabelMap.newBuilder();
TextFormat.merge(text, builder);
StringIntLabelMap proto = builder.build();
int maxId = 0;
for (StringIntLabelMapItem item : proto.getItemList()) {
if (item.getId() > maxId) {
maxId = item.getId();
}
}
String[] ret = new String[maxId + 1];
for (StringIntLabelMapItem item : proto.getItemList()) {
ret[item.getId()] = item.getDisplayName();
}
return ret;
}
private static void bgr2rgb(byte[] data) {
for (int i = 0; i < data.length; i += 3) {
byte tmp = data[i];
data[i] = data[i + 2];
data[i + 2] = tmp;
}
}
private static Tensor<UInt8> makeImageTensor(String filename) throws IOException {
BufferedImage img = ImageIO.read(new File(filename));
if (img.getType() != BufferedImage.TYPE_3BYTE_BGR) {
throw new IOException(
String.format(
"Expected 3-byte BGR encoding in BufferedImage, found %d (file: %s). This code could be made more robust",
img.getType(), filename));
}
byte[] data = ((DataBufferByte) img.getData().getDataBuffer()).getData();
// ImageIO.read seems to produce BGR-encoded images, but the model expects RGB.
bgr2rgb(data);
final long BATCH_SIZE = 1;
final long CHANNELS = 3;
long[] shape = new long[] {BATCH_SIZE, img.getHeight(), img.getWidth(), CHANNELS};
return Tensor.create(UInt8.class, shape, ByteBuffer.wrap(data));
}
private static void printUsage(PrintStream s) {
s.println("USAGE: <model> <label_map> <image> [<image>] [<image>]");
s.println("");
s.println("Where");
s.println("<model> is the path to the SavedModel directory of the model to use.");
s.println(" For example, the saved_model directory in tarballs from ");
s.println(
" https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md)");
s.println("");
s.println(
"<label_map> is the path to a file containing information about the labels detected by the model.");
s.println(" For example, one of the .pbtxt files from ");
s.println(
" https://github.com/tensorflow/models/tree/master/research/object_detection/data");
s.println("");
s.println("<image> is the path to an image file.");
s.println(" Sample images can be found from the COCO, Kitti, or Open Images dataset.");
s.println(
" See: https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md");
}
}
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: string_int_label_map.proto
package object_detection.protos;
public final class StringIntLabelMapOuterClass {
private StringIntLabelMapOuterClass() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
public interface StringIntLabelMapItemOrBuilder extends
// @@protoc_insertion_point(interface_extends:object_detection.protos.StringIntLabelMapItem)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* String name. The most common practice is to set this to a MID or synsets
* id.
* </pre>
*
* <code>optional string name = 1;</code>
*/
boolean hasName();
/**
* <pre>
* String name. The most common practice is to set this to a MID or synsets
* id.
* </pre>
*
* <code>optional string name = 1;</code>
*/
java.lang.String getName();
/**
* <pre>
* String name. The most common practice is to set this to a MID or synsets
* id.
* </pre>
*
* <code>optional string name = 1;</code>
*/
com.google.protobuf.ByteString
getNameBytes();
/**
* <pre>
* Integer id that maps to the string name above. Label ids should start from
* 1.
* </pre>
*
* <code>optional int32 id = 2;</code>
*/
boolean hasId();
/**
* <pre>
* Integer id that maps to the string name above. Label ids should start from
* 1.
* </pre>
*
* <code>optional int32 id = 2;</code>
*/
int getId();
/**
* <pre>
* Human readable string label.
* </pre>
*
* <code>optional string display_name = 3;</code>
*/
boolean hasDisplayName();
/**
* <pre>
* Human readable string label.
* </pre>
*
* <code>optional string display_name = 3;</code>
*/
java.lang.String getDisplayName();
/**
* <pre>
* Human readable string label.
* </pre>
*
* <code>optional string display_name = 3;</code>
*/
com.google.protobuf.ByteString
getDisplayNameBytes();
}
/**
* Protobuf type {@code object_detection.protos.StringIntLabelMapItem}
*/
public static final class StringIntLabelMapItem extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:object_detection.protos.StringIntLabelMapItem)
StringIntLabelMapItemOrBuilder {
private static final long serialVersionUID = 0L;
// Use StringIntLabelMapItem.newBuilder() to construct.
private StringIntLabelMapItem(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private StringIntLabelMapItem() {
name_ = "";
id_ = 0;
displayName_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private StringIntLabelMapItem(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000001;
name_ = bs;
break;
}
case 16: {
bitField0_ |= 0x00000002;
id_ = input.readInt32();
break;
}
case 26: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000004;
displayName_ = bs;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return object_detection.protos.StringIntLabelMapOuterClass.internal_static_object_detection_protos_StringIntLabelMapItem_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return object_detection.protos.StringIntLabelMapOuterClass.internal_static_object_detection_protos_StringIntLabelMapItem_fieldAccessorTable
.ensureFieldAccessorsInitialized(
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.class, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.Builder.class);
}
private int bitField0_;
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
* <pre>
* String name. The most common practice is to set this to a MID or synsets
* id.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <pre>
* String name. The most common practice is to set this to a MID or synsets
* id.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
}
}
/**
* <pre>
* String name. The most common practice is to set this to a MID or synsets
* id.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ID_FIELD_NUMBER = 2;
private int id_;
/**
* <pre>
* Integer id that maps to the string name above. Label ids should start from
* 1.
* </pre>
*
* <code>optional int32 id = 2;</code>
*/
public boolean hasId() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <pre>
* Integer id that maps to the string name above. Label ids should start from
* 1.
* </pre>
*
* <code>optional int32 id = 2;</code>
*/
public int getId() {
return id_;
}
public static final int DISPLAY_NAME_FIELD_NUMBER = 3;
private volatile java.lang.Object displayName_;
/**
* <pre>
* Human readable string label.
* </pre>
*
* <code>optional string display_name = 3;</code>
*/
public boolean hasDisplayName() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <pre>
* Human readable string label.
* </pre>
*
* <code>optional string display_name = 3;</code>
*/
public java.lang.String getDisplayName() {
java.lang.Object ref = displayName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
displayName_ = s;
}
return s;
}
}
/**
* <pre>
* Human readable string label.
* </pre>
*
* <code>optional string display_name = 3;</code>
*/
public com.google.protobuf.ByteString
getDisplayNameBytes() {
java.lang.Object ref = displayName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
displayName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeInt32(2, id_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, displayName_);
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(2, id_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, displayName_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem)) {
return super.equals(obj);
}
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem other = (object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem) obj;
boolean result = true;
result = result && (hasName() == other.hasName());
if (hasName()) {
result = result && getName()
.equals(other.getName());
}
result = result && (hasId() == other.hasId());
if (hasId()) {
result = result && (getId()
== other.getId());
}
result = result && (hasDisplayName() == other.hasDisplayName());
if (hasDisplayName()) {
result = result && getDisplayName()
.equals(other.getDisplayName());
}
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasName()) {
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
}
if (hasId()) {
hash = (37 * hash) + ID_FIELD_NUMBER;
hash = (53 * hash) + getId();
}
if (hasDisplayName()) {
hash = (37 * hash) + DISPLAY_NAME_FIELD_NUMBER;
hash = (53 * hash) + getDisplayName().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code object_detection.protos.StringIntLabelMapItem}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:object_detection.protos.StringIntLabelMapItem)
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItemOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return object_detection.protos.StringIntLabelMapOuterClass.internal_static_object_detection_protos_StringIntLabelMapItem_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return object_detection.protos.StringIntLabelMapOuterClass.internal_static_object_detection_protos_StringIntLabelMapItem_fieldAccessorTable
.ensureFieldAccessorsInitialized(
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.class, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.Builder.class);
}
// Construct using object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
name_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
id_ = 0;
bitField0_ = (bitField0_ & ~0x00000002);
displayName_ = "";
bitField0_ = (bitField0_ & ~0x00000004);
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return object_detection.protos.StringIntLabelMapOuterClass.internal_static_object_detection_protos_StringIntLabelMapItem_descriptor;
}
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem getDefaultInstanceForType() {
return object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.getDefaultInstance();
}
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem build() {
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem buildPartial() {
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem result = new object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.name_ = name_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.id_ = id_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.displayName_ = displayName_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem) {
return mergeFrom((object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem other) {
if (other == object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.getDefaultInstance()) return this;
if (other.hasName()) {
bitField0_ |= 0x00000001;
name_ = other.name_;
onChanged();
}
if (other.hasId()) {
setId(other.getId());
}
if (other.hasDisplayName()) {
bitField0_ |= 0x00000004;
displayName_ = other.displayName_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object name_ = "";
/**
* <pre>
* String name. The most common practice is to set this to a MID or synsets
* id.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <pre>
* String name. The most common practice is to set this to a MID or synsets
* id.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* String name. The most common practice is to set this to a MID or synsets
* id.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* String name. The most common practice is to set this to a MID or synsets
* id.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public Builder setName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
name_ = value;
onChanged();
return this;
}
/**
* <pre>
* String name. The most common practice is to set this to a MID or synsets
* id.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public Builder clearName() {
bitField0_ = (bitField0_ & ~0x00000001);
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <pre>
* String name. The most common practice is to set this to a MID or synsets
* id.
* </pre>
*
* <code>optional string name = 1;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
name_ = value;
onChanged();
return this;
}
private int id_ ;
/**
* <pre>
* Integer id that maps to the string name above. Label ids should start from
* 1.
* </pre>
*
* <code>optional int32 id = 2;</code>
*/
public boolean hasId() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <pre>
* Integer id that maps to the string name above. Label ids should start from
* 1.
* </pre>
*
* <code>optional int32 id = 2;</code>
*/
public int getId() {
return id_;
}
/**
* <pre>
* Integer id that maps to the string name above. Label ids should start from
* 1.
* </pre>
*
* <code>optional int32 id = 2;</code>
*/
public Builder setId(int value) {
bitField0_ |= 0x00000002;
id_ = value;
onChanged();
return this;
}
/**
* <pre>
* Integer id that maps to the string name above. Label ids should start from
* 1.
* </pre>
*
* <code>optional int32 id = 2;</code>
*/
public Builder clearId() {
bitField0_ = (bitField0_ & ~0x00000002);
id_ = 0;
onChanged();
return this;
}
private java.lang.Object displayName_ = "";
/**
* <pre>
* Human readable string label.
* </pre>
*
* <code>optional string display_name = 3;</code>
*/
public boolean hasDisplayName() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <pre>
* Human readable string label.
* </pre>
*
* <code>optional string display_name = 3;</code>
*/
public java.lang.String getDisplayName() {
java.lang.Object ref = displayName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
displayName_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Human readable string label.
* </pre>
*
* <code>optional string display_name = 3;</code>
*/
public com.google.protobuf.ByteString
getDisplayNameBytes() {
java.lang.Object ref = displayName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
displayName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Human readable string label.
* </pre>
*
* <code>optional string display_name = 3;</code>
*/
public Builder setDisplayName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
displayName_ = value;
onChanged();
return this;
}
/**
* <pre>
* Human readable string label.
* </pre>
*
* <code>optional string display_name = 3;</code>
*/
public Builder clearDisplayName() {
bitField0_ = (bitField0_ & ~0x00000004);
displayName_ = getDefaultInstance().getDisplayName();
onChanged();
return this;
}
/**
* <pre>
* Human readable string label.
* </pre>
*
* <code>optional string display_name = 3;</code>
*/
public Builder setDisplayNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
displayName_ = value;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:object_detection.protos.StringIntLabelMapItem)
}
// @@protoc_insertion_point(class_scope:object_detection.protos.StringIntLabelMapItem)
private static final object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem();
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem getDefaultInstance() {
return DEFAULT_INSTANCE;
}
@java.lang.Deprecated public static final com.google.protobuf.Parser<StringIntLabelMapItem>
PARSER = new com.google.protobuf.AbstractParser<StringIntLabelMapItem>() {
public StringIntLabelMapItem parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new StringIntLabelMapItem(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<StringIntLabelMapItem> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<StringIntLabelMapItem> getParserForType() {
return PARSER;
}
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface StringIntLabelMapOrBuilder extends
// @@protoc_insertion_point(interface_extends:object_detection.protos.StringIntLabelMap)
com.google.protobuf.MessageOrBuilder {
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
java.util.List<object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem>
getItemList();
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem getItem(int index);
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
int getItemCount();
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
java.util.List<? extends object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItemOrBuilder>
getItemOrBuilderList();
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItemOrBuilder getItemOrBuilder(
int index);
}
/**
* Protobuf type {@code object_detection.protos.StringIntLabelMap}
*/
public static final class StringIntLabelMap extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:object_detection.protos.StringIntLabelMap)
StringIntLabelMapOrBuilder {
private static final long serialVersionUID = 0L;
// Use StringIntLabelMap.newBuilder() to construct.
private StringIntLabelMap(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private StringIntLabelMap() {
item_ = java.util.Collections.emptyList();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private StringIntLabelMap(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
item_ = new java.util.ArrayList<object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem>();
mutable_bitField0_ |= 0x00000001;
}
item_.add(
input.readMessage(object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.PARSER, extensionRegistry));
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
item_ = java.util.Collections.unmodifiableList(item_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return object_detection.protos.StringIntLabelMapOuterClass.internal_static_object_detection_protos_StringIntLabelMap_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return object_detection.protos.StringIntLabelMapOuterClass.internal_static_object_detection_protos_StringIntLabelMap_fieldAccessorTable
.ensureFieldAccessorsInitialized(
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap.class, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap.Builder.class);
}
public static final int ITEM_FIELD_NUMBER = 1;
private java.util.List<object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem> item_;
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public java.util.List<object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem> getItemList() {
return item_;
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public java.util.List<? extends object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItemOrBuilder>
getItemOrBuilderList() {
return item_;
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public int getItemCount() {
return item_.size();
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem getItem(int index) {
return item_.get(index);
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItemOrBuilder getItemOrBuilder(
int index) {
return item_.get(index);
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
for (int i = 0; i < item_.size(); i++) {
output.writeMessage(1, item_.get(i));
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < item_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, item_.get(i));
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap)) {
return super.equals(obj);
}
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap other = (object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap) obj;
boolean result = true;
result = result && getItemList()
.equals(other.getItemList());
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getItemCount() > 0) {
hash = (37 * hash) + ITEM_FIELD_NUMBER;
hash = (53 * hash) + getItemList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code object_detection.protos.StringIntLabelMap}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:object_detection.protos.StringIntLabelMap)
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return object_detection.protos.StringIntLabelMapOuterClass.internal_static_object_detection_protos_StringIntLabelMap_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return object_detection.protos.StringIntLabelMapOuterClass.internal_static_object_detection_protos_StringIntLabelMap_fieldAccessorTable
.ensureFieldAccessorsInitialized(
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap.class, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap.Builder.class);
}
// Construct using object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getItemFieldBuilder();
}
}
public Builder clear() {
super.clear();
if (itemBuilder_ == null) {
item_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
itemBuilder_.clear();
}
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return object_detection.protos.StringIntLabelMapOuterClass.internal_static_object_detection_protos_StringIntLabelMap_descriptor;
}
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap getDefaultInstanceForType() {
return object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap.getDefaultInstance();
}
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap build() {
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap buildPartial() {
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap result = new object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap(this);
int from_bitField0_ = bitField0_;
if (itemBuilder_ == null) {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
item_ = java.util.Collections.unmodifiableList(item_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.item_ = item_;
} else {
result.item_ = itemBuilder_.build();
}
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap) {
return mergeFrom((object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap other) {
if (other == object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap.getDefaultInstance()) return this;
if (itemBuilder_ == null) {
if (!other.item_.isEmpty()) {
if (item_.isEmpty()) {
item_ = other.item_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureItemIsMutable();
item_.addAll(other.item_);
}
onChanged();
}
} else {
if (!other.item_.isEmpty()) {
if (itemBuilder_.isEmpty()) {
itemBuilder_.dispose();
itemBuilder_ = null;
item_ = other.item_;
bitField0_ = (bitField0_ & ~0x00000001);
itemBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getItemFieldBuilder() : null;
} else {
itemBuilder_.addAllMessages(other.item_);
}
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem> item_ =
java.util.Collections.emptyList();
private void ensureItemIsMutable() {
if (!((bitField0_ & 0x00000001) == 0x00000001)) {
item_ = new java.util.ArrayList<object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem>(item_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.Builder, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItemOrBuilder> itemBuilder_;
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public java.util.List<object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem> getItemList() {
if (itemBuilder_ == null) {
return java.util.Collections.unmodifiableList(item_);
} else {
return itemBuilder_.getMessageList();
}
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public int getItemCount() {
if (itemBuilder_ == null) {
return item_.size();
} else {
return itemBuilder_.getCount();
}
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem getItem(int index) {
if (itemBuilder_ == null) {
return item_.get(index);
} else {
return itemBuilder_.getMessage(index);
}
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public Builder setItem(
int index, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem value) {
if (itemBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureItemIsMutable();
item_.set(index, value);
onChanged();
} else {
itemBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public Builder setItem(
int index, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.Builder builderForValue) {
if (itemBuilder_ == null) {
ensureItemIsMutable();
item_.set(index, builderForValue.build());
onChanged();
} else {
itemBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public Builder addItem(object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem value) {
if (itemBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureItemIsMutable();
item_.add(value);
onChanged();
} else {
itemBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public Builder addItem(
int index, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem value) {
if (itemBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureItemIsMutable();
item_.add(index, value);
onChanged();
} else {
itemBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public Builder addItem(
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.Builder builderForValue) {
if (itemBuilder_ == null) {
ensureItemIsMutable();
item_.add(builderForValue.build());
onChanged();
} else {
itemBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public Builder addItem(
int index, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.Builder builderForValue) {
if (itemBuilder_ == null) {
ensureItemIsMutable();
item_.add(index, builderForValue.build());
onChanged();
} else {
itemBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public Builder addAllItem(
java.lang.Iterable<? extends object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem> values) {
if (itemBuilder_ == null) {
ensureItemIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, item_);
onChanged();
} else {
itemBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public Builder clearItem() {
if (itemBuilder_ == null) {
item_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
itemBuilder_.clear();
}
return this;
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public Builder removeItem(int index) {
if (itemBuilder_ == null) {
ensureItemIsMutable();
item_.remove(index);
onChanged();
} else {
itemBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.Builder getItemBuilder(
int index) {
return getItemFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItemOrBuilder getItemOrBuilder(
int index) {
if (itemBuilder_ == null) {
return item_.get(index); } else {
return itemBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public java.util.List<? extends object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItemOrBuilder>
getItemOrBuilderList() {
if (itemBuilder_ != null) {
return itemBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(item_);
}
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.Builder addItemBuilder() {
return getItemFieldBuilder().addBuilder(
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.getDefaultInstance());
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.Builder addItemBuilder(
int index) {
return getItemFieldBuilder().addBuilder(
index, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.getDefaultInstance());
}
/**
* <code>repeated .object_detection.protos.StringIntLabelMapItem item = 1;</code>
*/
public java.util.List<object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.Builder>
getItemBuilderList() {
return getItemFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.Builder, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItemOrBuilder>
getItemFieldBuilder() {
if (itemBuilder_ == null) {
itemBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItem.Builder, object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMapItemOrBuilder>(
item_,
((bitField0_ & 0x00000001) == 0x00000001),
getParentForChildren(),
isClean());
item_ = null;
}
return itemBuilder_;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:object_detection.protos.StringIntLabelMap)
}
// @@protoc_insertion_point(class_scope:object_detection.protos.StringIntLabelMap)
private static final object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap();
}
public static object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap getDefaultInstance() {
return DEFAULT_INSTANCE;
}
@java.lang.Deprecated public static final com.google.protobuf.Parser<StringIntLabelMap>
PARSER = new com.google.protobuf.AbstractParser<StringIntLabelMap>() {
public StringIntLabelMap parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new StringIntLabelMap(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<StringIntLabelMap> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<StringIntLabelMap> getParserForType() {
return PARSER;
}
public object_detection.protos.StringIntLabelMapOuterClass.StringIntLabelMap getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_object_detection_protos_StringIntLabelMapItem_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_object_detection_protos_StringIntLabelMapItem_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_object_detection_protos_StringIntLabelMap_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_object_detection_protos_StringIntLabelMap_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\032string_int_label_map.proto\022\027object_det" +
"ection.protos\"G\n\025StringIntLabelMapItem\022\014" +
"\n\004name\030\001 \001(\t\022\n\n\002id\030\002 \001(\005\022\024\n\014display_name" +
"\030\003 \001(\t\"Q\n\021StringIntLabelMap\022<\n\004item\030\001 \003(" +
"\0132..object_detection.protos.StringIntLab" +
"elMapItem"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
internal_static_object_detection_protos_StringIntLabelMapItem_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_object_detection_protos_StringIntLabelMapItem_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_object_detection_protos_StringIntLabelMapItem_descriptor,
new java.lang.String[] { "Name", "Id", "DisplayName", });
internal_static_object_detection_protos_StringIntLabelMap_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_object_detection_protos_StringIntLabelMap_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_object_detection_protos_StringIntLabelMap_descriptor,
new java.lang.String[] { "Item", });
}
// @@protoc_insertion_point(outer_class_scope)
}
# Training models in Java
Example of training a model (and saving and restoring checkpoints) using the
TensorFlow Java API.
## Quickstart
1. Train for a few steps:
```
mvn -q compile exec:java -Dexec.args="model/graph.pb checkpoint"
```
2. Resume training from previous checkpoint and train some more:
```
mvn -q exec:java -Dexec.args="model/graph.pb checkpoint"
```
3. Delete checkpoint:
```
rm -rf checkpoint
```
## Details
The model in `model/graph.pb` represents a very simple linear model:
```
y = x * W + b
```
The `graph.pb` file is generated by executing `create_graph.py` in Python.
The training is orchestrated by `src/main/java/Train.java`, which generates
training data of the form `y = 3.0 * x + 2.0` and over time, using gradient
descent, the model should "learn" and the value of `W` should converge to 3.0,
and `b` to 2.0.
from __future__ import print_function
import tensorflow as tf
x = tf.placeholder(tf.float32, name='input')
y_ = tf.placeholder(tf.float32, name='target')
W = tf.Variable(5., name='W')
b = tf.Variable(3., name='b')
y = x * W + b
y = tf.identity(y, name='output')
loss = tf.reduce_mean(tf.square(y - y_))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(loss, name='train')
init = tf.global_variables_initializer()
# Creating a tf.train.Saver adds operations to the graph to save and
# restore variables from checkpoints.
saver_def = tf.train.Saver().as_saver_def()
print('Operation to initialize variables: ', init.name)
print('Tensor to feed as input data: ', x.name)
print('Tensor to feed as training targets: ', y_.name)
print('Tensor to fetch as prediction: ', y.name)
print('Operation to train one step: ', train_op.name)
print('Tensor to be fed for checkpoint filename:', saver_def.filename_tensor_name)
print('Operation to save a checkpoint: ', saver_def.save_tensor_name)
print('Operation to restore a checkpoint: ', saver_def.restore_op_name)
print('Tensor to read value of W ', W.value().name)
print('Tensor to read value of b ', b.value().name)
with open('graph.pb', 'w') as f:
f.write(tf.get_default_graph().as_graph_def().SerializeToString())
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.myorg</groupId>
<artifactId>training</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<exec.mainClass>Train</exec.mainClass>
<!-- The sample code requires at least JDK 1.7. -->
<!-- The maven compiler plugin defaults to a lower version -->
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.tensorflow</groupId>
<artifactId>tensorflow</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
</project>
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
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
http://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.
==============================================================================*/
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Random;
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.Tensors;
/**
* Training a trivial linear model.
*/
public class Train {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Require two arguments: The GraphDef file and checkpoint directory");
System.exit(1);
}
final byte[] graphDef = Files.readAllBytes(Paths.get(args[0]));
final String checkpointDir = args[1];
final boolean checkpointExists = Files.exists(Paths.get(checkpointDir));
try (Graph graph = new Graph();
Session sess = new Session(graph);
Tensor<String> checkpointPrefix =
Tensors.create(Paths.get(checkpointDir, "ckpt").toString())) {
graph.importGraphDef(graphDef);
// Initialize or restore
if (checkpointExists) {
sess.runner().feed("save/Const", checkpointPrefix).addTarget("save/restore_all").run();
} else {
sess.runner().addTarget("init").run();
}
System.out.print("Starting from : ");
printVariables(sess);
// Train a bunch of times.
// (Will be much more efficient if we sent batches instead of individual values).
final Random r = new Random();
final int NUM_EXAMPLES = 500;
for (int i = 1; i <= 5; i++) {
for (int n = 0; n < NUM_EXAMPLES; n++) {
float in = r.nextFloat();
try (Tensor<Float> input = Tensors.create(in);
Tensor<Float> target = Tensors.create(3 * in + 2)) {
sess.runner().feed("input", input).feed("target", target).addTarget("train").run();
}
}
System.out.printf("After %5d examples: ", i*NUM_EXAMPLES);
printVariables(sess);
}
// Checkpoint
sess.runner().feed("save/Const", checkpointPrefix).addTarget("save/control_dependency").run();
// Example of "inference" in the same graph:
try (Tensor<Float> input = Tensors.create(1.0f);
Tensor<Float> output =
sess.runner().feed("input", input).fetch("output").run().get(0).expect(Float.class)) {
System.out.printf(
"For input %f, produced %f (ideally would produce 3*%f + 2)\n",
input.floatValue(), output.floatValue(), input.floatValue());
}
}
}
private static void printVariables(Session sess) {
List<Tensor<?>> values = sess.runner().fetch("W/read").fetch("b/read").run();
System.out.printf("W = %f\tb = %f\n", values.get(0).floatValue(), values.get(1).floatValue());
for (Tensor<?> t : values) {
t.close();
}
}
}
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# Distributed_TensorFlow under the License is Distributed_TensorFlow 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.
# ==============================================================================
# This is the complete code for the following blogpost:
# https://developers.googleblog.com/2017/12/creating-custom-estimators-in-tensorflow.html
import tensorflow as tf
import os
import sys
import six.moves.urllib.request as request
tf.logging.set_verbosity(tf.logging.INFO)
# Check that we have correct TensorFlow version installed
tf_version = tf.__version__
tf.logging.info("TensorFlow version: {}".format(tf_version))
assert "1.4" <= tf_version, "TensorFlow r1.4 or later is needed"
# Windows users: You only need to change PATH, rest is platform independent
PATH = "/tmp/tf_custom_estimators"
# Fetch and store Training and Test dataset files
PATH_DATASET = PATH + os.sep + "dataset"
FILE_TRAIN = PATH_DATASET + os.sep + "iris_training.csv"
FILE_TEST = PATH_DATASET + os.sep + "iris_test.csv"
URL_TRAIN = "http://download.tensorflow.org/data/iris_training.csv"
URL_TEST = "http://download.tensorflow.org/data/iris_test.csv"
def downloadDataset(url, file):
if not os.path.exists(PATH_DATASET):
os.makedirs(PATH_DATASET)
if not os.path.exists(file):
data = request.urlopen(url).read()
with open(file, "wb") as f:
f.write(data)
f.close()
downloadDataset(URL_TRAIN, FILE_TRAIN)
downloadDataset(URL_TEST, FILE_TEST)
# The CSV features in our training & test data
feature_names = [
'SepalLength',
'SepalWidth',
'PetalLength',
'PetalWidth']
# Create an input function reading a file using the Dataset API
# Then provide the results to the Estimator API
def my_input_fn(file_path, repeat_count=1, shuffle_count=1):
def decode_csv(line):
parsed_line = tf.decode_csv(line, [[0.], [0.], [0.], [0.], [0]])
label = parsed_line[-1] # Last element is the label
del parsed_line[-1] # Delete last element
features = parsed_line # Everything but last elements are the features
d = dict(zip(feature_names, features)), label
return d
dataset = (tf.data.TextLineDataset(file_path) # Read text file
.skip(1) # Skip header row
.map(decode_csv, num_parallel_calls=4) # Decode each line
.cache() # Warning: Caches entire dataset, can cause out of memory
.shuffle(shuffle_count) # Randomize elems (1 == no operation)
.repeat(repeat_count) # Repeats dataset this # times
.batch(32)
.prefetch(1) # Make sure you always have 1 batch ready to serve
)
iterator = dataset.make_one_shot_iterator()
batch_features, batch_labels = iterator.get_next()
return batch_features, batch_labels
def my_model_fn(
features, # This is batch_features from input_fn
labels, # This is batch_labels from input_fn
mode): # And instance of tf.estimator.ModeKeys, see below
if mode == tf.estimator.ModeKeys.PREDICT:
tf.logging.info("my_model_fn: PREDICT, {}".format(mode))
elif mode == tf.estimator.ModeKeys.EVAL:
tf.logging.info("my_model_fn: EVAL, {}".format(mode))
elif mode == tf.estimator.ModeKeys.TRAIN:
tf.logging.info("my_model_fn: TRAIN, {}".format(mode))
# All our inputs are feature columns of type numeric_column
feature_columns = [
tf.feature_column.numeric_column(feature_names[0]),
tf.feature_column.numeric_column(feature_names[1]),
tf.feature_column.numeric_column(feature_names[2]),
tf.feature_column.numeric_column(feature_names[3])
]
# Create the layer of input
input_layer = tf.feature_column.input_layer(features, feature_columns)
# Definition of hidden layer: h1
# We implement it as a fully-connected layer (tf.layers.dense)
# Has 10 neurons, and uses ReLU as the activation function
# Takes input_layer as input
h1 = tf.layers.Dense(10, activation=tf.nn.relu)(input_layer)
# Definition of hidden layer: h2 (this is the logits layer)
# Similar to h1, but takes h1 as input
h2 = tf.layers.Dense(10, activation=tf.nn.relu)(h1)
# Output 'logits' layer is three number = probability distribution
# between Iris Setosa, Versicolor, and Viginica
logits = tf.layers.Dense(3)(h2)
# class_ids will be the model prediction for the class (Iris flower type)
# The output node with the highest value is our prediction
predictions = { 'class_ids': tf.argmax(input=logits, axis=1) }
# 1. Prediction mode
# Return our prediction
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode, predictions=predictions)
# Evaluation and Training mode
# Calculate the loss
loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)
# Calculate the accuracy between the true labels, and our predictions
accuracy = tf.metrics.accuracy(labels, predictions['class_ids'])
# 2. Evaluation mode
# Return our loss (which is used to evaluate our model)
# Set the TensorBoard scalar my_accurace to the accuracy
# Obs: This function only sets value during mode == ModeKeys.EVAL
# To set values during training, see tf.summary.scalar
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(
mode,
loss=loss,
eval_metric_ops={'my_accuracy': accuracy})
# If mode is not PREDICT nor EVAL, then we must be in TRAIN
assert mode == tf.estimator.ModeKeys.TRAIN, "TRAIN is only ModeKey left"
# 3. Training mode
# Default optimizer for DNNClassifier: Adagrad with learning rate=0.05
# Our objective (train_op) is to minimize loss
# Provide global step counter (used to count gradient updates)
optimizer = tf.train.AdagradOptimizer(0.05)
train_op = optimizer.minimize(
loss,
global_step=tf.train.get_global_step())
# Set the TensorBoard scalar my_accuracy to the accuracy
# Obs: This function only sets the value during mode == ModeKeys.TRAIN
# To set values during evaluation, see eval_metrics_ops
tf.summary.scalar('my_accuracy', accuracy[1])
# Return training operations: loss and train_op
return tf.estimator.EstimatorSpec(
mode,
loss=loss,
train_op=train_op)
# Create a custom estimator using my_model_fn to define the model
tf.logging.info("Before classifier construction")
classifier = tf.estimator.Estimator(
model_fn=my_model_fn,
model_dir=PATH) # Path to where checkpoints etc are stored
tf.logging.info("...done constructing classifier")
# 500 epochs = 500 * 120 records [60000] = (500 * 120) / 32 batches = 1875 batches
# 4 epochs = 4 * 30 records = (4 * 30) / 32 batches = 3.75 batches
# Train our model, use the previously function my_input_fn
# Input to training is a file with training example
# Stop training after 8 iterations of train data (epochs)
tf.logging.info("Before classifier.train")
classifier.train(
input_fn=lambda: my_input_fn(FILE_TRAIN, 500, 256))
tf.logging.info("...done classifier.train")
# Evaluate our model using the examples contained in FILE_TEST
# Return value will contain evaluation_metrics such as: loss & average_loss
tf.logging.info("Before classifier.evaluate")
evaluate_result = classifier.evaluate(
input_fn=lambda: my_input_fn(FILE_TEST, 4))
tf.logging.info("...done classifier.evaluate")
tf.logging.info("Evaluation results")
for key in evaluate_result:
tf.logging.info(" {}, was: {}".format(key, evaluate_result[key]))
# Predict the type of some Iris flowers.
# Let's predict the examples in FILE_TEST, repeat only once.
predict_results = classifier.predict(
input_fn=lambda: my_input_fn(FILE_TEST, 1))
tf.logging.info("Prediction on test file")
for prediction in predict_results:
# Will print the predicted class, i.e: 0, 1, or 2 if the prediction
# is Iris Setosa, Vericolor, Virginica, respectively.
tf.logging.info("...{}".format(prediction["class_ids"]))
# Let create a dataset for prediction
# We've taken the first 3 examples in FILE_TEST
prediction_input = [[5.9, 3.0, 4.2, 1.5], # -> 1, Iris Versicolor
[6.9, 3.1, 5.4, 2.1], # -> 2, Iris Virginica
[5.1, 3.3, 1.7, 0.5]] # -> 0, Iris Setosa
def new_input_fn():
def decode(x):
x = tf.split(x, 4) # Need to split into our 4 features
return dict(zip(feature_names, x)) # To build a dict of them
dataset = tf.data.Dataset.from_tensor_slices(prediction_input)
dataset = dataset.map(decode)
iterator = dataset.make_one_shot_iterator()
next_feature_batch = iterator.get_next()
return next_feature_batch, None # In prediction, we have no labels
# Predict all our prediction_input
predict_results = classifier.predict(input_fn=new_input_fn)
# Print results
tf.logging.info("Predictions on memory")
for idx, prediction in enumerate(predict_results):
type = prediction["class_ids"] # Get the predicted class (index)
if type == 0:
tf.logging.info("...I think: {}, is Iris Setosa".format(prediction_input[idx]))
elif type == 1:
tf.logging.info("...I think: {}, is Iris Versicolor".format(prediction_input[idx]))
else:
tf.logging.info("...I think: {}, is Iris Virginica".format(prediction_input[idx]))
......@@ -65,7 +65,7 @@ feature_names = [
def my_input_fn(file_path, perform_shuffle=False, repeat_count=1):
def decode_csv(line):
parsed_line = tf.decode_csv(line, [[0.], [0.], [0.], [0.], [0]])
label = parsed_line[-1:] # Last element is the label
label = parsed_line[-1] # Last element is the label
del parsed_line[-1] # Delete last element
features = parsed_line # Everything but last elements are the features
d = dict(zip(feature_names, features)), label
......
......@@ -19,17 +19,19 @@ unzip -p source-archive.zip word2vec/trunk/questions-words.txt > questions-word
rm text8.zip source-archive.zip
```
You will need to compile the ops as follows:
You will need to compile the ops as follows (See
[Adding a New Op to TensorFlow](https://www.tensorflow.org/how_tos/adding_an_op/#building_the_op_library)
for more details).:
```shell
TF_INC=$(python -c 'import tensorflow as tf; print(tf.sysconfig.get_include())')
g++ -std=c++11 -shared word2vec_ops.cc word2vec_kernels.cc -o word2vec_ops.so -fPIC -I $TF_INC -O2 -D_GLIBCXX_USE_CXX11_ABI=0
TF_CFLAGS=( $(python -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_compile_flags()))') )
TF_LFLAGS=( $(python -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_link_flags()))') )
g++ -std=c++11 -shared word2vec_ops.cc word2vec_kernels.cc -o word2vec_ops.so -fPIC ${TF_CFLAGS[@]} ${TF_LFLAGS[@]} -O2 -D_GLIBCXX_USE_CXX11_ABI=0
```
On Mac, add `-undefined dynamic_lookup` to the g++ command.
On Mac, add `-undefined dynamic_lookup` to the g++ command. The flag `-D_GLIBCXX_USE_CXX11_ABI=0` is included to support newer versions of gcc. However, if you compiled TensorFlow from source using gcc 5 or later, you may need to exclude the flag. Specifically, if you get an error similar to the following: `word2vec_ops.so: undefined symbol: _ZN10tensorflow7strings6StrCatERKNS0_8AlphaNumES3_S3_S3_` then you likely need to exclude the flag.
(For an explanation of what this is doing, see the tutorial on [Adding a New Op to TensorFlow](https://www.tensorflow.org/how_tos/adding_an_op/#building_the_op_library). The flag `-D_GLIBCXX_USE_CXX11_ABI=0` is included to support newer versions of gcc. However, if you compiled TensorFlow from source using gcc 5 or later, you may need to exclude the flag.)
Then run using:
Once you've successfully compiled the ops, run the model as follows:
```shell
python word2vec_optimized.py \
......
**NOTE: For users interested in multi-GPU, we recommend looking at the newer [cifar10_estimator](https://github.com/tensorflow/models/tree/master/tutorials/image/cifar10_estimator) example instead.**
---
CIFAR-10 is a common benchmark in machine learning for image recognition.
http://www.cs.toronto.edu/~kriz/cifar.html
......@@ -7,4 +11,3 @@ Code in this directory demonstrates how to use TensorFlow to train and evaluate
Detailed instructions on how to get started available at:
http://tensorflow.org/tutorials/deep_cnn/
......@@ -35,7 +35,6 @@ from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import re
import sys
......@@ -46,19 +45,15 @@ import tensorflow as tf
import cifar10_input
parser = argparse.ArgumentParser()
FLAGS = tf.app.flags.FLAGS
# Basic model parameters.
parser.add_argument('--batch_size', type=int, default=128,
help='Number of images to process in a batch.')
parser.add_argument('--data_dir', type=str, default='/tmp/cifar10_data',
help='Path to the CIFAR-10 data directory.')
parser.add_argument('--use_fp16', type=bool, default=False,
help='Train the model using fp16.')
FLAGS = parser.parse_args()
tf.app.flags.DEFINE_integer('batch_size', 128,
"""Number of images to process in a batch.""")
tf.app.flags.DEFINE_string('data_dir', '/tmp/cifar10_data',
"""Path to the CIFAR-10 data directory.""")
tf.app.flags.DEFINE_boolean('use_fp16', False,
"""Train the model using fp16.""")
# Global constants describing the CIFAR-10 data set.
IMAGE_SIZE = cifar10_input.IMAGE_SIZE
......@@ -78,7 +73,7 @@ INITIAL_LEARNING_RATE = 0.1 # Initial learning rate.
# names of the summaries when visualizing a model.
TOWER_NAME = 'tower'
DATA_URL = 'http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz'
DATA_URL = 'https://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz'
def _activation_summary(x):
......
......@@ -43,25 +43,20 @@ import tensorflow as tf
import cifar10
parser = cifar10.parser
parser.add_argument('--eval_dir', type=str, default='/tmp/cifar10_eval',
help='Directory where to write event logs.')
parser.add_argument('--eval_data', type=str, default='test',
help='Either `test` or `train_eval`.')
parser.add_argument('--checkpoint_dir', type=str, default='/tmp/cifar10_train',
help='Directory where to read model checkpoints.')
parser.add_argument('--eval_interval_secs', type=int, default=60*5,
help='How often to run the eval.')
parser.add_argument('--num_examples', type=int, default=10000,
help='Number of examples to run.')
parser.add_argument('--run_once', type=bool, default=False,
help='Whether to run eval only once.')
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('eval_dir', '/tmp/cifar10_eval',
"""Directory where to write event logs.""")
tf.app.flags.DEFINE_string('eval_data', 'test',
"""Either 'test' or 'train_eval'.""")
tf.app.flags.DEFINE_string('checkpoint_dir', '/tmp/cifar10_train',
"""Directory where to read model checkpoints.""")
tf.app.flags.DEFINE_integer('eval_interval_secs', 60 * 5,
"""How often to run the eval.""")
tf.app.flags.DEFINE_integer('num_examples', 10000,
"""Number of examples to run.""")
tf.app.flags.DEFINE_boolean('run_once', False,
"""Whether to run eval only once.""")
def eval_once(saver, summary_writer, top_k_op, summary_op):
......@@ -159,5 +154,4 @@ def main(argv=None): # pylint: disable=unused-argument
if __name__ == '__main__':
FLAGS = parser.parse_args()
tf.app.run()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment