1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.textclassifier; 18 19 import androidx.annotation.FloatRange; 20 import com.google.common.base.Objects; 21 import com.google.common.base.Preconditions; 22 23 /** A representation of an identified entity with the confidence score */ 24 public final class Entity implements Comparable<Entity> { 25 26 private final String entityType; 27 private final float score; 28 Entity(String entityType, float score)29 public Entity(String entityType, float score) { 30 this.entityType = Preconditions.checkNotNull(entityType); 31 this.score = score; 32 } 33 getEntityType()34 public String getEntityType() { 35 return entityType; 36 } 37 38 /** 39 * Returns the confidence score of the entity, which ranged from 0.0 (low confidence) to 1.0 (high 40 * confidence). 41 */ 42 @FloatRange(from = 0.0, to = 1.0) getScore()43 public Float getScore() { 44 return score; 45 } 46 47 @Override hashCode()48 public int hashCode() { 49 return Objects.hashCode(entityType, score); 50 } 51 52 @Override equals(Object o)53 public boolean equals(Object o) { 54 if (this == o) { 55 return true; 56 } 57 if (o == null || getClass() != o.getClass()) { 58 return false; 59 } 60 Entity entity = (Entity) o; 61 return Float.compare(entity.score, score) == 0 62 && java.util.Objects.equals(entityType, entity.entityType); 63 } 64 65 @Override toString()66 public String toString() { 67 return "Entity{" + entityType + ": " + score + "}"; 68 } 69 70 @Override compareTo(Entity entity)71 public int compareTo(Entity entity) { 72 // This method is implemented for sorting Entity. Sort the entities by the confidence score 73 // in descending order firstly. If the scores are the same, then sort them by the entity 74 // type in ascending order. 75 int result = Float.compare(entity.getScore(), score); 76 if (result == 0) { 77 return entityType.compareTo(entity.getEntityType()); 78 } 79 return result; 80 } 81 } 82