summaryrefslogtreecommitdiff
path: root/jni/com/google/android/textclassifier/AnnotatorModel.java
blob: 47a369e56bec0c812eb2ce65c41a9bdc03ee69bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * 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.
 */

package com.google.android.textclassifier;

import android.content.res.AssetFileDescriptor;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;

/**
 * Java wrapper for Annotator native library interface. This library is used for detecting entities
 * in text.
 *
 * @hide
 */
public final class AnnotatorModel implements AutoCloseable {
  private final AtomicBoolean isClosed = new AtomicBoolean(false);

  static {
    System.loadLibrary("textclassifier");
  }

  // Keep these in sync with the constants defined in AOSP.
  static final String TYPE_UNKNOWN = "";
  static final String TYPE_OTHER = "other";
  static final String TYPE_EMAIL = "email";
  static final String TYPE_PHONE = "phone";
  static final String TYPE_ADDRESS = "address";
  static final String TYPE_URL = "url";
  static final String TYPE_DATE = "date";
  static final String TYPE_DATE_TIME = "datetime";
  static final String TYPE_FLIGHT_NUMBER = "flight";

  public static final double INVALID_LATITUDE = 180;
  public static final double INVALID_LONGITUDE = 360;
  public static final float INVALID_LOCATION_ACCURACY_METERS = 0;

  private long annotatorPtr;
  // To tell GC to keep the LangID model alive at least as long as this object.
  @Nullable private LangIdModel langIdModel;

  /** Enumeration for specifying the usecase of the annotations. */
  public static enum AnnotationUsecase {
    /** Results are optimized for Smart{Select,Share,Linkify}. */
    SMART(0),

    /**
     * Results are optimized for using TextClassifier as an infrastructure that annotates as much as
     * possible.
     */
    RAW(1);

    private final int value;

    AnnotationUsecase(int value) {
      this.value = value;
    }

    public int getValue() {
      return value;
    }
  };

  /** Enumeration for specifying the annotate mode. */
  public static enum AnnotateMode {
    /** Result contains entity annotation for each input fragment. */
    ENTITY_ANNOTATION(0),

    /** Result will include both entity annotation and topicality annotation. */
    ENTITY_AND_TOPICALITY_ANNOTATION(1);

    private final int value;

    AnnotateMode(int value) {
      this.value = value;
    }

    public int getValue() {
      return value;
    }
  };

  /**
   * Creates a new instance of SmartSelect predictor, using the provided model image, given as a
   * file descriptor.
   */
  public AnnotatorModel(int fileDescriptor) {
    annotatorPtr = nativeNewAnnotator(fileDescriptor);
    if (annotatorPtr == 0L) {
      throw new IllegalArgumentException("Couldn't initialize TC from file descriptor.");
    }
  }

  /**
   * Creates a new instance of SmartSelect predictor, using the provided model image, given as a
   * file path.
   */
  public AnnotatorModel(String path) {
    annotatorPtr = nativeNewAnnotatorFromPath(path);
    if (annotatorPtr == 0L) {
      throw new IllegalArgumentException("Couldn't initialize TC from given file.");
    }
  }

  /**
   * Creates a new instance of SmartSelect predictor, using the provided model image, given as an
   * {@link AssetFileDescriptor}.
   */
  public AnnotatorModel(AssetFileDescriptor assetFileDescriptor) {
    annotatorPtr =
        nativeNewAnnotatorWithOffset(
            assetFileDescriptor.getParcelFileDescriptor().getFd(),
            assetFileDescriptor.getStartOffset(),
            assetFileDescriptor.getLength());
    if (annotatorPtr == 0L) {
      throw new IllegalArgumentException("Couldn't initialize TC from asset file descriptor.");
    }
  }

  /** Initializes the knowledge engine, passing the given serialized config to it. */
  public void initializeKnowledgeEngine(byte[] serializedConfig) {
    if (!nativeInitializeKnowledgeEngine(annotatorPtr, serializedConfig)) {
      throw new IllegalArgumentException("Couldn't initialize the KG engine");
    }
  }

  /** Initializes the contact engine, passing the given serialized config to it. */
  public void initializeContactEngine(byte[] serializedConfig) {
    if (!nativeInitializeContactEngine(annotatorPtr, serializedConfig)) {
      throw new IllegalArgumentException("Couldn't initialize the contact engine");
    }
  }

  /** Initializes the installed app engine, passing the given serialized config to it. */
  public void initializeInstalledAppEngine(byte[] serializedConfig) {
    if (!nativeInitializeInstalledAppEngine(annotatorPtr, serializedConfig)) {
      throw new IllegalArgumentException("Couldn't initialize the installed app engine");
    }
  }

  /**
   * Sets the LangId model to the annotator. Do not call close on the given LangIdModel object
   * before this object is closed. Also, this object does not take the memory ownership of the given
   * LangIdModel object.
   */
  public void setLangIdModel(@Nullable LangIdModel langIdModel) {
    this.langIdModel = langIdModel;
    nativeSetLangId(annotatorPtr, langIdModel == null ? 0 : langIdModel.getNativePointer());
  }

  /**
   * Initializes the person name engine, using the provided model image, given as an {@link
   * AssetFileDescriptor}.
   */
  public void initializePersonNameEngine(AssetFileDescriptor assetFileDescriptor) {
    if (!nativeInitializePersonNameEngine(
        annotatorPtr,
        assetFileDescriptor.getParcelFileDescriptor().getFd(),
        assetFileDescriptor.getStartOffset(),
        assetFileDescriptor.getLength())) {
      throw new IllegalArgumentException("Couldn't initialize the person name engine");
    }
  }

  /**
   * Given a string context and current selection, computes the selection suggestion.
   *
   * <p>The begin and end are character indices into the context UTF8 string. selectionBegin is the
   * character index where the selection begins, and selectionEnd is the index of one character past
   * the selection span.
   *
   * <p>The return value is an array of two ints: suggested selection beginning and end, with the
   * same semantics as the input selectionBeginning and selectionEnd.
   */
  public int[] suggestSelection(
      String context, int selectionBegin, int selectionEnd, SelectionOptions options) {
    return nativeSuggestSelection(annotatorPtr, context, selectionBegin, selectionEnd, options);
  }

  /**
   * Given a string context and current selection, classifies the type of the selected text.
   *
   * <p>The begin and end params are character indices in the context string.
   *
   * <p>Returns an array of ClassificationResult objects with the probability scores for different
   * collections.
   */
  public ClassificationResult[] classifyText(
      String context, int selectionBegin, int selectionEnd, ClassificationOptions options) {
    return classifyText(
        context,
        selectionBegin,
        selectionEnd,
        options,
        /*appContext=*/ null,
        /*resourcesLocale=*/ null);
  }

  public ClassificationResult[] classifyText(
      String context,
      int selectionBegin,
      int selectionEnd,
      ClassificationOptions options,
      Object appContext,
      String resourcesLocale) {
    return nativeClassifyText(
        annotatorPtr, context, selectionBegin, selectionEnd, options, appContext, resourcesLocale);
  }

  /**
   * Annotates given input text. The annotations should cover the whole input context except for
   * whitespaces, and are sorted by their position in the context string.
   */
  public AnnotatedSpan[] annotate(String text, AnnotationOptions options) {
    return nativeAnnotate(annotatorPtr, text, options);
  }

  /**
   * Annotates multiple fragments of text at once. There will be one AnnotatedSpan array for each
   * input fragment to annotate.
   */
  public Annotations annotateStructuredInput(InputFragment[] fragments, AnnotationOptions options) {
    return nativeAnnotateStructuredInput(annotatorPtr, fragments, options);
  }

  /**
   * Looks up a knowledge entity by its identifier. Returns null if the entity is not found or on
   * error.
   */
  public byte[] lookUpKnowledgeEntity(String id) {
    return nativeLookUpKnowledgeEntity(annotatorPtr, id);
  }

  /** Frees up the allocated memory. */
  @Override
  public void close() {
    if (isClosed.compareAndSet(false, true)) {
      nativeCloseAnnotator(annotatorPtr);
      annotatorPtr = 0L;
    }
  }

  @Override
  protected void finalize() throws Throwable {
    try {
      close();
    } finally {
      super.finalize();
    }
  }

  /** Returns a comma separated list of locales supported by the model as BCP 47 tags. */
  public static String getLocales(int fd) {
    return nativeGetLocales(fd);
  }

  /** Returns a comma separated list of locales supported by the model as BCP 47 tags. */
  public static String getLocales(AssetFileDescriptor assetFileDescriptor) {
    return nativeGetLocalesWithOffset(
        assetFileDescriptor.getParcelFileDescriptor().getFd(),
        assetFileDescriptor.getStartOffset(),
        assetFileDescriptor.getLength());
  }

  /** Returns the version of the model. */
  public static int getVersion(int fd) {
    return nativeGetVersion(fd);
  }

  /** Returns the version of the model. */
  public static int getVersion(AssetFileDescriptor assetFileDescriptor) {
    return nativeGetVersionWithOffset(
        assetFileDescriptor.getParcelFileDescriptor().getFd(),
        assetFileDescriptor.getStartOffset(),
        assetFileDescriptor.getLength());
  }

  /** Returns the name of the model. */
  public static String getName(int fd) {
    return nativeGetName(fd);
  }

  /** Returns the name of the model. */
  public static String getName(AssetFileDescriptor assetFileDescriptor) {
    return nativeGetNameWithOffset(
        assetFileDescriptor.getParcelFileDescriptor().getFd(),
        assetFileDescriptor.getStartOffset(),
        assetFileDescriptor.getLength());
  }

  /** Information about a parsed time/date. */
  public static final class DatetimeResult {

    public static final int GRANULARITY_YEAR = 0;
    public static final int GRANULARITY_MONTH = 1;
    public static final int GRANULARITY_WEEK = 2;
    public static final int GRANULARITY_DAY = 3;
    public static final int GRANULARITY_HOUR = 4;
    public static final int GRANULARITY_MINUTE = 5;
    public static final int GRANULARITY_SECOND = 6;

    private final long timeMsUtc;
    private final int granularity;

    public DatetimeResult(long timeMsUtc, int granularity) {
      this.timeMsUtc = timeMsUtc;
      this.granularity = granularity;
    }

    public long getTimeMsUtc() {
      return timeMsUtc;
    }

    public int getGranularity() {
      return granularity;
    }
  }

  /** Classification result for classifyText method. */
  public static final class ClassificationResult {
    private final String collection;
    private final float score;
    @Nullable private final DatetimeResult datetimeResult;
    @Nullable private final byte[] serializedKnowledgeResult;
    @Nullable private final String contactName;
    @Nullable private final String contactGivenName;
    @Nullable private final String contactFamilyName;
    @Nullable private final String contactNickname;
    @Nullable private final String contactEmailAddress;
    @Nullable private final String contactPhoneNumber;
    @Nullable private final String contactAccountType;
    @Nullable private final String contactAccountName;
    @Nullable private final String contactId;
    @Nullable private final String appName;
    @Nullable private final String appPackageName;
    @Nullable private final NamedVariant[] entityData;
    @Nullable private final byte[] serializedEntityData;
    @Nullable private final RemoteActionTemplate[] remoteActionTemplates;
    private final long durationMs;
    private final long numericValue;
    private final double numericDoubleValue;

    public ClassificationResult(
        String collection,
        float score,
        @Nullable DatetimeResult datetimeResult,
        @Nullable byte[] serializedKnowledgeResult,
        @Nullable String contactName,
        @Nullable String contactGivenName,
        @Nullable String contactFamilyName,
        @Nullable String contactNickname,
        @Nullable String contactEmailAddress,
        @Nullable String contactPhoneNumber,
        @Nullable String contactAccountType,
        @Nullable String contactAccountName,
        @Nullable String contactId,
        @Nullable String appName,
        @Nullable String appPackageName,
        @Nullable NamedVariant[] entityData,
        @Nullable byte[] serializedEntityData,
        @Nullable RemoteActionTemplate[] remoteActionTemplates,
        long durationMs,
        long numericValue,
        double numericDoubleValue) {
      this.collection = collection;
      this.score = score;
      this.datetimeResult = datetimeResult;
      this.serializedKnowledgeResult = serializedKnowledgeResult;
      this.contactName = contactName;
      this.contactGivenName = contactGivenName;
      this.contactFamilyName = contactFamilyName;
      this.contactNickname = contactNickname;
      this.contactEmailAddress = contactEmailAddress;
      this.contactPhoneNumber = contactPhoneNumber;
      this.contactAccountType = contactAccountType;
      this.contactAccountName = contactAccountName;
      this.contactId = contactId;
      this.appName = appName;
      this.appPackageName = appPackageName;
      this.entityData = entityData;
      this.serializedEntityData = serializedEntityData;
      this.remoteActionTemplates = remoteActionTemplates;
      this.durationMs = durationMs;
      this.numericValue = numericValue;
      this.numericDoubleValue = numericDoubleValue;
    }

    /** Returns the classified entity type. */
    public String getCollection() {
      return collection;
    }

    /** Confidence score between 0 and 1. */
    public float getScore() {
      return score;
    }

    @Nullable
    public DatetimeResult getDatetimeResult() {
      return datetimeResult;
    }

    @Nullable
    public byte[] getSerializedKnowledgeResult() {
      return serializedKnowledgeResult;
    }

    @Nullable
    public String getContactName() {
      return contactName;
    }

    @Nullable
    public String getContactGivenName() {
      return contactGivenName;
    }

    @Nullable
    public String getContactFamilyName() {
      return contactFamilyName;
    }

    @Nullable
    public String getContactNickname() {
      return contactNickname;
    }

    @Nullable
    public String getContactEmailAddress() {
      return contactEmailAddress;
    }

    @Nullable
    public String getContactPhoneNumber() {
      return contactPhoneNumber;
    }

    @Nullable
    public String getContactAccountType() {
      return contactAccountType;
    }

    @Nullable
    public String getContactAccountName() {
      return contactAccountName;
    }

    @Nullable
    public String getContactId() {
      return contactId;
    }

    @Nullable
    public String getAppName() {
      return appName;
    }

    @Nullable
    public String getAppPackageName() {
      return appPackageName;
    }

    @Nullable
    public NamedVariant[] getEntityData() {
      return entityData;
    }

    @Nullable
    public byte[] getSerializedEntityData() {
      return serializedEntityData;
    }

    @Nullable
    public RemoteActionTemplate[] getRemoteActionTemplates() {
      return remoteActionTemplates;
    }

    public long getDurationMs() {
      return durationMs;
    }

    public long getNumericValue() {
      return numericValue;
    }

    public double getNumericDoubleValue() {
      return numericDoubleValue;
    }
  }

  /** Represents a result of Annotate call. */
  public static final class AnnotatedSpan {
    private final int startIndex;
    private final int endIndex;
    private final ClassificationResult[] classification;

    AnnotatedSpan(int startIndex, int endIndex, ClassificationResult[] classification) {
      this.startIndex = startIndex;
      this.endIndex = endIndex;
      this.classification = classification;
    }

    public int getStartIndex() {
      return startIndex;
    }

    public int getEndIndex() {
      return endIndex;
    }

    public ClassificationResult[] getClassification() {
      return classification;
    }
  }

  /**
   * Represents a result of Annotate call, which will include both entity annotations and topicality
   * annotations.
   */
  public static final class Annotations {
    private final AnnotatedSpan[][] annotatedSpans;
    private final ClassificationResult[] topicalityResults;

    Annotations(AnnotatedSpan[][] annotatedSpans, ClassificationResult[] topicalityResults) {
      this.annotatedSpans = annotatedSpans;
      this.topicalityResults = topicalityResults;
    }

    public AnnotatedSpan[][] getAnnotatedSpans() {
      return annotatedSpans;
    }

    public ClassificationResult[] getTopicalityResults() {
      return topicalityResults;
    }
  }

  /** Represents a fragment of text to the AnnotateStructuredInput call. */
  public static final class InputFragment {

    /** Encapsulates the data required to set the relative time of an InputFragment. */
    public static final class DatetimeOptions {
      private final String referenceTimezone;
      private final Long referenceTimeMsUtc;

      public DatetimeOptions(String referenceTimezone, Long referenceTimeMsUtc) {
        this.referenceTimeMsUtc = referenceTimeMsUtc;
        this.referenceTimezone = referenceTimezone;
      }
    }

    public InputFragment(String text) {
      this.text = text;
      this.datetimeOptionsNullable = null;
      this.boundingBoxTop = 0;
      this.boundingBoxHeight = 0;
    }

    public InputFragment(
        String text,
        DatetimeOptions datetimeOptions,
        float boundingBoxTop,
        float boundingBoxHeight) {
      this.text = text;
      this.datetimeOptionsNullable = datetimeOptions;
      this.boundingBoxTop = boundingBoxTop;
      this.boundingBoxHeight = boundingBoxHeight;
    }

    private final String text;
    // The DatetimeOptions can't be Optional because the _api16 build of the TCLib SDK does not
    // support java.util.Optional.
    private final DatetimeOptions datetimeOptionsNullable;
    private final float boundingBoxTop;
    private final float boundingBoxHeight;

    public String getText() {
      return text;
    }

    public float getBoundingBoxTop() {
      return boundingBoxTop;
    }

    public float getBoundingBoxHeight() {
      return boundingBoxHeight;
    }

    public boolean hasDatetimeOptions() {
      return datetimeOptionsNullable != null;
    }

    public long getReferenceTimeMsUtc() {
      return datetimeOptionsNullable.referenceTimeMsUtc;
    }

    public String getReferenceTimezone() {
      return datetimeOptionsNullable.referenceTimezone;
    }
  }

  /** Represents options for the suggestSelection call. */
  public static final class SelectionOptions {
    @Nullable private final String locales;
    @Nullable private final String detectedTextLanguageTags;
    private final int annotationUsecase;
    private final double userLocationLat;
    private final double userLocationLng;
    private final float userLocationAccuracyMeters;
    private final boolean usePodNer;
    private final boolean useVocabAnnotator;

    private SelectionOptions(
        @Nullable String locales,
        @Nullable String detectedTextLanguageTags,
        int annotationUsecase,
        double userLocationLat,
        double userLocationLng,
        float userLocationAccuracyMeters,
        boolean usePodNer,
        boolean useVocabAnnotator) {
      this.locales = locales;
      this.detectedTextLanguageTags = detectedTextLanguageTags;
      this.annotationUsecase = annotationUsecase;
      this.userLocationLat = userLocationLat;
      this.userLocationLng = userLocationLng;
      this.userLocationAccuracyMeters = userLocationAccuracyMeters;
      this.usePodNer = usePodNer;
      this.useVocabAnnotator = useVocabAnnotator;
    }

    /** Can be used to build a SelectionsOptions instance. */
    public static class Builder {
      @Nullable private String locales;
      @Nullable private String detectedTextLanguageTags;
      private int annotationUsecase = AnnotationUsecase.SMART.getValue();
      private double userLocationLat = INVALID_LATITUDE;
      private double userLocationLng = INVALID_LONGITUDE;
      private float userLocationAccuracyMeters = INVALID_LOCATION_ACCURACY_METERS;
      private boolean usePodNer = true;
      private boolean useVocabAnnotator = true;

      public Builder setLocales(@Nullable String locales) {
        this.locales = locales;
        return this;
      }

      public Builder setDetectedTextLanguageTags(@Nullable String detectedTextLanguageTags) {
        this.detectedTextLanguageTags = detectedTextLanguageTags;
        return this;
      }

      public Builder setAnnotationUsecase(int annotationUsecase) {
        this.annotationUsecase = annotationUsecase;
        return this;
      }

      public Builder setUserLocationLat(double userLocationLat) {
        this.userLocationLat = userLocationLat;
        return this;
      }

      public Builder setUserLocationLng(double userLocationLng) {
        this.userLocationLng = userLocationLng;
        return this;
      }

      public Builder setUserLocationAccuracyMeters(float userLocationAccuracyMeters) {
        this.userLocationAccuracyMeters = userLocationAccuracyMeters;
        return this;
      }

      public Builder setUsePodNer(boolean usePodNer) {
        this.usePodNer = usePodNer;
        return this;
      }

      public Builder setUseVocabAnnotator(boolean useVocabAnnotator) {
        this.useVocabAnnotator = useVocabAnnotator;
        return this;
      }

      public SelectionOptions build() {
        return new SelectionOptions(
            locales,
            detectedTextLanguageTags,
            annotationUsecase,
            userLocationLat,
            userLocationLng,
            userLocationAccuracyMeters,
            usePodNer,
            useVocabAnnotator);
      }
    }

    public static Builder builder() {
      return new Builder();
    }

    @Nullable
    public String getLocales() {
      return locales;
    }

    /** Returns a comma separated list of BCP 47 language tags. */
    @Nullable
    public String getDetectedTextLanguageTags() {
      return detectedTextLanguageTags;
    }

    public int getAnnotationUsecase() {
      return annotationUsecase;
    }

    public double getUserLocationLat() {
      return userLocationLat;
    }

    public double getUserLocationLng() {
      return userLocationLng;
    }

    public float getUserLocationAccuracyMeters() {
      return userLocationAccuracyMeters;
    }

    public boolean getUsePodNer() {
      return usePodNer;
    }

    public boolean getUseVocabAnnotator() {
      return useVocabAnnotator;
    }
  }

  /** Represents options for the classifyText call. */
  public static final class ClassificationOptions {
    private final long referenceTimeMsUtc;
    private final String referenceTimezone;
    @Nullable private final String locales;
    @Nullable private final String detectedTextLanguageTags;
    private final int annotationUsecase;
    private final double userLocationLat;
    private final double userLocationLng;
    private final float userLocationAccuracyMeters;
    private final String userFamiliarLanguageTags;
    private final boolean usePodNer;
    private final boolean triggerDictionaryOnBeginnerWords;
    private final boolean useVocabAnnotator;

    private ClassificationOptions(
        long referenceTimeMsUtc,
        String referenceTimezone,
        @Nullable String locales,
        @Nullable String detectedTextLanguageTags,
        int annotationUsecase,
        double userLocationLat,
        double userLocationLng,
        float userLocationAccuracyMeters,
        String userFamiliarLanguageTags,
        boolean usePodNer,
        boolean triggerDictionaryOnBeginnerWords,
        boolean useVocabAnnotator) {
      this.referenceTimeMsUtc = referenceTimeMsUtc;
      this.referenceTimezone = referenceTimezone;
      this.locales = locales;
      this.detectedTextLanguageTags = detectedTextLanguageTags;
      this.annotationUsecase = annotationUsecase;
      this.userLocationLat = userLocationLat;
      this.userLocationLng = userLocationLng;
      this.userLocationAccuracyMeters = userLocationAccuracyMeters;
      this.userFamiliarLanguageTags = userFamiliarLanguageTags;
      this.usePodNer = usePodNer;
      this.triggerDictionaryOnBeginnerWords = triggerDictionaryOnBeginnerWords;
      this.useVocabAnnotator = useVocabAnnotator;
    }

    /** Can be used to build a ClassificationOptions instance. */
    public static class Builder {
      private long referenceTimeMsUtc;
      @Nullable private String referenceTimezone;
      @Nullable private String locales;
      @Nullable private String detectedTextLanguageTags;
      private int annotationUsecase = AnnotationUsecase.SMART.getValue();
      private double userLocationLat = INVALID_LATITUDE;
      private double userLocationLng = INVALID_LONGITUDE;
      private float userLocationAccuracyMeters = INVALID_LOCATION_ACCURACY_METERS;
      private String userFamiliarLanguageTags = "";
      private boolean usePodNer = true;
      private boolean triggerDictionaryOnBeginnerWords = false;
      private boolean useVocabAnnotator = true;

      public Builder setReferenceTimeMsUtc(long referenceTimeMsUtc) {
        this.referenceTimeMsUtc = referenceTimeMsUtc;
        return this;
      }

      public Builder setReferenceTimezone(String referenceTimezone) {
        this.referenceTimezone = referenceTimezone;
        return this;
      }

      public Builder setLocales(@Nullable String locales) {
        this.locales = locales;
        return this;
      }

      public Builder setDetectedTextLanguageTags(@Nullable String detectedTextLanguageTags) {
        this.detectedTextLanguageTags = detectedTextLanguageTags;
        return this;
      }

      public Builder setAnnotationUsecase(int annotationUsecase) {
        this.annotationUsecase = annotationUsecase;
        return this;
      }

      public Builder setUserLocationLat(double userLocationLat) {
        this.userLocationLat = userLocationLat;
        return this;
      }

      public Builder setUserLocationLng(double userLocationLng) {
        this.userLocationLng = userLocationLng;
        return this;
      }

      public Builder setUserLocationAccuracyMeters(float userLocationAccuracyMeters) {
        this.userLocationAccuracyMeters = userLocationAccuracyMeters;
        return this;
      }

      public Builder setUserFamiliarLanguageTags(String userFamiliarLanguageTags) {
        this.userFamiliarLanguageTags = userFamiliarLanguageTags;
        return this;
      }

      public Builder setUsePodNer(boolean usePodNer) {
        this.usePodNer = usePodNer;
        return this;
      }

      public Builder setTrigerringDictionaryOnBeginnerWords(
          boolean triggerDictionaryOnBeginnerWords) {
        this.triggerDictionaryOnBeginnerWords = triggerDictionaryOnBeginnerWords;
        return this;
      }

      public Builder setUseVocabAnnotator(boolean useVocabAnnotator) {
        this.useVocabAnnotator = useVocabAnnotator;
        return this;
      }

      public ClassificationOptions build() {
        return new ClassificationOptions(
            referenceTimeMsUtc,
            referenceTimezone,
            locales,
            detectedTextLanguageTags,
            annotationUsecase,
            userLocationLat,
            userLocationLng,
            userLocationAccuracyMeters,
            userFamiliarLanguageTags,
            usePodNer,
            triggerDictionaryOnBeginnerWords,
            useVocabAnnotator);
      }
    }

    public static Builder builder() {
      return new Builder();
    }

    public long getReferenceTimeMsUtc() {
      return referenceTimeMsUtc;
    }

    public String getReferenceTimezone() {
      return referenceTimezone;
    }

    @Nullable
    public String getLocale() {
      return locales;
    }

    /** Returns a comma separated list of BCP 47 language tags. */
    @Nullable
    public String getDetectedTextLanguageTags() {
      return detectedTextLanguageTags;
    }

    public int getAnnotationUsecase() {
      return annotationUsecase;
    }

    public double getUserLocationLat() {
      return userLocationLat;
    }

    public double getUserLocationLng() {
      return userLocationLng;
    }

    public float getUserLocationAccuracyMeters() {
      return userLocationAccuracyMeters;
    }

    public String getUserFamiliarLanguageTags() {
      return userFamiliarLanguageTags;
    }

    public boolean getUsePodNer() {
      return usePodNer;
    }

    public boolean getTriggerDictionaryOnBeginnerWords() {
      return triggerDictionaryOnBeginnerWords;
    }

    public boolean getUseVocabAnnotator() {
      return useVocabAnnotator;
    }
  }

  /** Represents options for the annotate call. */
  public static final class AnnotationOptions {
    private final long referenceTimeMsUtc;
    private final String referenceTimezone;
    @Nullable private final String locales;
    @Nullable private final String detectedTextLanguageTags;
    private final String[] entityTypes;
    private final int annotateMode;
    private final int annotationUsecase;
    private final boolean hasLocationPermission;
    private final boolean hasPersonalizationPermission;
    private final boolean isSerializedEntityDataEnabled;
    private final double userLocationLat;
    private final double userLocationLng;
    private final float userLocationAccuracyMeters;
    private final boolean usePodNer;
    private final boolean triggerDictionaryOnBeginnerWords;
    private final boolean useVocabAnnotator;

    private AnnotationOptions(
        long referenceTimeMsUtc,
        String referenceTimezone,
        @Nullable String locales,
        @Nullable String detectedTextLanguageTags,
        @Nullable Collection<String> entityTypes,
        int annotateMode,
        int annotationUsecase,
        boolean hasLocationPermission,
        boolean hasPersonalizationPermission,
        boolean isSerializedEntityDataEnabled,
        double userLocationLat,
        double userLocationLng,
        float userLocationAccuracyMeters,
        boolean usePodNer,
        boolean triggerDictionaryOnBeginnerWords,
        boolean useVocabAnnotator) {
      this.referenceTimeMsUtc = referenceTimeMsUtc;
      this.referenceTimezone = referenceTimezone;
      this.locales = locales;
      this.detectedTextLanguageTags = detectedTextLanguageTags;
      this.entityTypes = entityTypes == null ? new String[0] : entityTypes.toArray(new String[0]);
      this.annotateMode = annotateMode;
      this.annotationUsecase = annotationUsecase;
      this.isSerializedEntityDataEnabled = isSerializedEntityDataEnabled;
      this.userLocationLat = userLocationLat;
      this.userLocationLng = userLocationLng;
      this.userLocationAccuracyMeters = userLocationAccuracyMeters;
      this.hasLocationPermission = hasLocationPermission;
      this.hasPersonalizationPermission = hasPersonalizationPermission;
      this.usePodNer = usePodNer;
      this.triggerDictionaryOnBeginnerWords = triggerDictionaryOnBeginnerWords;
      this.useVocabAnnotator = useVocabAnnotator;
    }

    /** Can be used to build an AnnotationOptions instance. */
    public static class Builder {
      private long referenceTimeMsUtc;
      @Nullable private String referenceTimezone;
      @Nullable private String locales;
      @Nullable private String detectedTextLanguageTags;
      @Nullable private Collection<String> entityTypes;
      private int annotateMode = AnnotateMode.ENTITY_ANNOTATION.getValue();
      private int annotationUsecase = AnnotationUsecase.SMART.getValue();
      private boolean hasLocationPermission = true;
      private boolean hasPersonalizationPermission = true;
      private boolean isSerializedEntityDataEnabled = false;
      private double userLocationLat = INVALID_LATITUDE;
      private double userLocationLng = INVALID_LONGITUDE;
      private float userLocationAccuracyMeters = INVALID_LOCATION_ACCURACY_METERS;
      private boolean usePodNer = true;
      private boolean triggerDictionaryOnBeginnerWords = false;
      private boolean useVocabAnnotator = true;

      public Builder setReferenceTimeMsUtc(long referenceTimeMsUtc) {
        this.referenceTimeMsUtc = referenceTimeMsUtc;
        return this;
      }

      public Builder setReferenceTimezone(String referenceTimezone) {
        this.referenceTimezone = referenceTimezone;
        return this;
      }

      public Builder setLocales(@Nullable String locales) {
        this.locales = locales;
        return this;
      }

      public Builder setDetectedTextLanguageTags(@Nullable String detectedTextLanguageTags) {
        this.detectedTextLanguageTags = detectedTextLanguageTags;
        return this;
      }

      public Builder setEntityTypes(Collection<String> entityTypes) {
        this.entityTypes = entityTypes;
        return this;
      }

      public Builder setAnnotateMode(int annotateMode) {
        this.annotateMode = annotateMode;
        return this;
      }

      public Builder setAnnotationUsecase(int annotationUsecase) {
        this.annotationUsecase = annotationUsecase;
        return this;
      }

      public Builder setHasLocationPermission(boolean hasLocationPermission) {
        this.hasLocationPermission = hasLocationPermission;
        return this;
      }

      public Builder setHasPersonalizationPermission(boolean hasPersonalizationPermission) {
        this.hasPersonalizationPermission = hasPersonalizationPermission;
        return this;
      }

      public Builder setIsSerializedEntityDataEnabled(boolean isSerializedEntityDataEnabled) {
        this.isSerializedEntityDataEnabled = isSerializedEntityDataEnabled;
        return this;
      }

      public Builder setUserLocationLat(double userLocationLat) {
        this.userLocationLat = userLocationLat;
        return this;
      }

      public Builder setUserLocationLng(double userLocationLng) {
        this.userLocationLng = userLocationLng;
        return this;
      }

      public Builder setUserLocationAccuracyMeters(float userLocationAccuracyMeters) {
        this.userLocationAccuracyMeters = userLocationAccuracyMeters;
        return this;
      }

      public Builder setUsePodNer(boolean usePodNer) {
        this.usePodNer = usePodNer;
        return this;
      }

      public Builder setTriggerDictionaryOnBeginnerWords(boolean triggerDictionaryOnBeginnerWords) {
        this.triggerDictionaryOnBeginnerWords = triggerDictionaryOnBeginnerWords;
        return this;
      }

      public Builder setUseVocabAnnotator(boolean useVocabAnnotator) {
        this.useVocabAnnotator = useVocabAnnotator;
        return this;
      }

      public AnnotationOptions build() {
        return new AnnotationOptions(
            referenceTimeMsUtc,
            referenceTimezone,
            locales,
            detectedTextLanguageTags,
            entityTypes,
            annotateMode,
            annotationUsecase,
            hasLocationPermission,
            hasPersonalizationPermission,
            isSerializedEntityDataEnabled,
            userLocationLat,
            userLocationLng,
            userLocationAccuracyMeters,
            usePodNer,
            triggerDictionaryOnBeginnerWords,
            useVocabAnnotator);
      }
    }

    public static Builder builder() {
      return new Builder();
    }

    public long getReferenceTimeMsUtc() {
      return referenceTimeMsUtc;
    }

    public String getReferenceTimezone() {
      return referenceTimezone;
    }

    @Nullable
    public String getLocale() {
      return locales;
    }

    /** Returns a comma separated list of BCP 47 language tags. */
    @Nullable
    public String getDetectedTextLanguageTags() {
      return detectedTextLanguageTags;
    }

    public String[] getEntityTypes() {
      return entityTypes;
    }

    public int getAnnotateMode() {
      return annotateMode;
    }

    public int getAnnotationUsecase() {
      return annotationUsecase;
    }

    public boolean isSerializedEntityDataEnabled() {
      return isSerializedEntityDataEnabled;
    }

    public double getUserLocationLat() {
      return userLocationLat;
    }

    public double getUserLocationLng() {
      return userLocationLng;
    }

    public float getUserLocationAccuracyMeters() {
      return userLocationAccuracyMeters;
    }

    public boolean hasLocationPermission() {
      return hasLocationPermission;
    }

    public boolean hasPersonalizationPermission() {
      return hasPersonalizationPermission;
    }

    public boolean getUsePodNer() {
      return usePodNer;
    }

    public boolean getTriggerDictionaryOnBeginnerWords() {
      return triggerDictionaryOnBeginnerWords;
    }

    public boolean getUseVocabAnnotator() {
      return useVocabAnnotator;
    }
  }

  /**
   * Retrieves the pointer to the native object. Note: Need to keep the AnnotatorModel alive as long
   * as the pointer is used.
   */
  long getNativeAnnotatorPointer() {
    return nativeGetNativeModelPtr(annotatorPtr);
  }

  private static native long nativeNewAnnotator(int fd);

  private static native long nativeNewAnnotatorFromPath(String path);

  private static native long nativeNewAnnotatorWithOffset(int fd, long offset, long size);

  private static native String nativeGetLocales(int fd);

  private static native String nativeGetLocalesWithOffset(int fd, long offset, long size);

  private static native int nativeGetVersion(int fd);

  private static native int nativeGetVersionWithOffset(int fd, long offset, long size);

  private static native String nativeGetName(int fd);

  private static native String nativeGetNameWithOffset(int fd, long offset, long size);

  private native long nativeGetNativeModelPtr(long context);

  private native boolean nativeInitializeKnowledgeEngine(long context, byte[] serializedConfig);

  private native boolean nativeInitializeContactEngine(long context, byte[] serializedConfig);

  private native boolean nativeInitializeInstalledAppEngine(long context, byte[] serializedConfig);

  private native boolean nativeInitializePersonNameEngine(
      long context, int fd, long offset, long size);

  private native void nativeSetLangId(long annotatorPtr, long langIdPtr);

  private native int[] nativeSuggestSelection(
      long context, String text, int selectionBegin, int selectionEnd, SelectionOptions options);

  private native ClassificationResult[] nativeClassifyText(
      long context,
      String text,
      int selectionBegin,
      int selectionEnd,
      ClassificationOptions options,
      Object appContext,
      String resourceLocales);

  private native AnnotatedSpan[] nativeAnnotate(
      long context, String text, AnnotationOptions options);

  private native Annotations nativeAnnotateStructuredInput(
      long context, InputFragment[] inputFragments, AnnotationOptions options);

  private native byte[] nativeLookUpKnowledgeEntity(long context, String id);

  private native void nativeCloseAnnotator(long context);
}