summaryrefslogtreecommitdiff
path: root/native/annotator/annotator_jni_common.cc
blob: a6f636f4cc8b0312731b4b515d0333bccc6076b3 (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
/*
 * 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.
 */

#include "annotator/annotator_jni_common.h"

#include "annotator/knowledge/knowledge-engine-types.h"
#include "utils/java/jni-base.h"
#include "utils/java/jni-helper.h"

namespace libtextclassifier3 {
namespace {

StatusOr<std::unordered_set<std::string>> EntityTypesFromJObject(
    JNIEnv* env, const jobject& jobject) {
  std::unordered_set<std::string> entity_types;
  jobjectArray jentity_types = reinterpret_cast<jobjectArray>(jobject);
  TC3_ASSIGN_OR_RETURN(const int size,
                       JniHelper::GetArrayLength(env, jentity_types));
  for (int i = 0; i < size; ++i) {
    TC3_ASSIGN_OR_RETURN(
        ScopedLocalRef<jstring> jentity_type,
        JniHelper::GetObjectArrayElement<jstring>(env, jentity_types, i));
    TC3_ASSIGN_OR_RETURN(std::string entity_type,
                         JStringToUtf8String(env, jentity_type.get()));
    entity_types.insert(entity_type);
  }
  return entity_types;
}

template <typename T>
StatusOr<T> FromJavaOptionsInternal(JNIEnv* env, jobject joptions,
                                    const std::string& class_name) {
  if (!joptions) {
    return {Status::UNKNOWN};
  }

  TC3_ASSIGN_OR_RETURN(ScopedLocalRef<jclass> options_class,
                       JniHelper::FindClass(env, class_name.c_str()));

  // .getLocale()
  TC3_ASSIGN_OR_RETURN(
      jmethodID get_locale,
      JniHelper::GetMethodID(env, options_class.get(), "getLocale",
                             "()Ljava/lang/String;"));
  TC3_ASSIGN_OR_RETURN(
      ScopedLocalRef<jstring> locales,
      JniHelper::CallObjectMethod<jstring>(env, joptions, get_locale));

  // .getReferenceTimeMsUtc()
  TC3_ASSIGN_OR_RETURN(jmethodID get_reference_time_method,
                       JniHelper::GetMethodID(env, options_class.get(),
                                              "getReferenceTimeMsUtc", "()J"));
  TC3_ASSIGN_OR_RETURN(
      int64 reference_time,
      JniHelper::CallLongMethod(env, joptions, get_reference_time_method));

  // .getReferenceTimezone()
  TC3_ASSIGN_OR_RETURN(
      jmethodID get_reference_timezone_method,
      JniHelper::GetMethodID(env, options_class.get(), "getReferenceTimezone",
                             "()Ljava/lang/String;"));
  TC3_ASSIGN_OR_RETURN(ScopedLocalRef<jstring> reference_timezone,
                       JniHelper::CallObjectMethod<jstring>(
                           env, joptions, get_reference_timezone_method));

  // .getDetectedTextLanguageTags()
  TC3_ASSIGN_OR_RETURN(jmethodID get_detected_text_language_tags_method,
                       JniHelper::GetMethodID(env, options_class.get(),
                                              "getDetectedTextLanguageTags",
                                              "()Ljava/lang/String;"));
  TC3_ASSIGN_OR_RETURN(
      ScopedLocalRef<jstring> detected_text_language_tags,
      JniHelper::CallObjectMethod<jstring>(
          env, joptions, get_detected_text_language_tags_method));

  // .getAnnotationUsecase()
  TC3_ASSIGN_OR_RETURN(jmethodID get_annotation_usecase,
                       JniHelper::GetMethodID(env, options_class.get(),
                                              "getAnnotationUsecase", "()I"));
  TC3_ASSIGN_OR_RETURN(
      int32 annotation_usecase,
      JniHelper::CallIntMethod(env, joptions, get_annotation_usecase));

  // .getUserLocationLat()
  TC3_ASSIGN_OR_RETURN(jmethodID get_user_location_lat,
                       JniHelper::GetMethodID(env, options_class.get(),
                                              "getUserLocationLat", "()D"));
  TC3_ASSIGN_OR_RETURN(
      double user_location_lat,
      JniHelper::CallDoubleMethod(env, joptions, get_user_location_lat));

  // .getUserLocationLng()
  TC3_ASSIGN_OR_RETURN(jmethodID get_user_location_lng,
                       JniHelper::GetMethodID(env, options_class.get(),
                                              "getUserLocationLng", "()D"));
  TC3_ASSIGN_OR_RETURN(
      double user_location_lng,
      JniHelper::CallDoubleMethod(env, joptions, get_user_location_lng));

  // .getUserLocationAccuracyMeters()
  TC3_ASSIGN_OR_RETURN(
      jmethodID get_user_location_accuracy_meters,
      JniHelper::GetMethodID(env, options_class.get(),
                             "getUserLocationAccuracyMeters", "()F"));
  TC3_ASSIGN_OR_RETURN(float user_location_accuracy_meters,
                       JniHelper::CallFloatMethod(
                           env, joptions, get_user_location_accuracy_meters));

  // .getUsePodNer()
  TC3_ASSIGN_OR_RETURN(
      jmethodID get_use_pod_ner,
      JniHelper::GetMethodID(env, options_class.get(), "getUsePodNer", "()Z"));
  TC3_ASSIGN_OR_RETURN(bool use_pod_ner, JniHelper::CallBooleanMethod(
                                             env, joptions, get_use_pod_ner));

  // .getUseVocabAnnotator()
  TC3_ASSIGN_OR_RETURN(jmethodID get_use_vocab_annotator,
                       JniHelper::GetMethodID(env, options_class.get(),
                                              "getUseVocabAnnotator", "()Z"));
  TC3_ASSIGN_OR_RETURN(
      bool use_vocab_annotator,
      JniHelper::CallBooleanMethod(env, joptions, get_use_vocab_annotator));
  T options;
  TC3_ASSIGN_OR_RETURN(options.locales,
                       JStringToUtf8String(env, locales.get()));
  TC3_ASSIGN_OR_RETURN(options.reference_timezone,
                       JStringToUtf8String(env, reference_timezone.get()));
  options.reference_time_ms_utc = reference_time;
  TC3_ASSIGN_OR_RETURN(
      options.detected_text_language_tags,
      JStringToUtf8String(env, detected_text_language_tags.get()));
  options.annotation_usecase =
      static_cast<AnnotationUsecase>(annotation_usecase);
  options.location_context = {user_location_lat, user_location_lng,
                              user_location_accuracy_meters};
  options.use_pod_ner = use_pod_ner;
  options.use_vocab_annotator = use_vocab_annotator;
  return options;
}
}  // namespace

StatusOr<SelectionOptions> FromJavaSelectionOptions(JNIEnv* env,
                                                    jobject joptions) {
  if (!joptions) {
    // Falling back to default options in case joptions is null
    SelectionOptions default_selection_options;
    return default_selection_options;
  }

  TC3_ASSIGN_OR_RETURN(
      ScopedLocalRef<jclass> options_class,
      JniHelper::FindClass(env, TC3_PACKAGE_PATH TC3_ANNOTATOR_CLASS_NAME_STR
                           "$SelectionOptions"));

  // .getLocale()
  TC3_ASSIGN_OR_RETURN(
      jmethodID get_locales,
      JniHelper::GetMethodID(env, options_class.get(), "getLocales",
                             "()Ljava/lang/String;"));
  TC3_ASSIGN_OR_RETURN(
      ScopedLocalRef<jstring> locales,
      JniHelper::CallObjectMethod<jstring>(env, joptions, get_locales));

  // .getDetectedTextLanguageTags()
  TC3_ASSIGN_OR_RETURN(jmethodID get_detected_text_language_tags_method,
                       JniHelper::GetMethodID(env, options_class.get(),
                                              "getDetectedTextLanguageTags",
                                              "()Ljava/lang/String;"));
  TC3_ASSIGN_OR_RETURN(
      ScopedLocalRef<jstring> detected_text_language_tags,
      JniHelper::CallObjectMethod<jstring>(
          env, joptions, get_detected_text_language_tags_method));

  // .getAnnotationUsecase()
  TC3_ASSIGN_OR_RETURN(jmethodID get_annotation_usecase,
                       JniHelper::GetMethodID(env, options_class.get(),
                                              "getAnnotationUsecase", "()I"));
  TC3_ASSIGN_OR_RETURN(
      int32 annotation_usecase,
      JniHelper::CallIntMethod(env, joptions, get_annotation_usecase));

  // .getUserLocationLat()
  TC3_ASSIGN_OR_RETURN(jmethodID get_user_location_lat,
                       JniHelper::GetMethodID(env, options_class.get(),
                                              "getUserLocationLat", "()D"));
  TC3_ASSIGN_OR_RETURN(
      double user_location_lat,
      JniHelper::CallDoubleMethod(env, joptions, get_user_location_lat));

  // .getUserLocationLng()
  TC3_ASSIGN_OR_RETURN(jmethodID get_user_location_lng,
                       JniHelper::GetMethodID(env, options_class.get(),
                                              "getUserLocationLng", "()D"));
  TC3_ASSIGN_OR_RETURN(
      double user_location_lng,
      JniHelper::CallDoubleMethod(env, joptions, get_user_location_lng));

  // .getUserLocationAccuracyMeters()
  TC3_ASSIGN_OR_RETURN(
      jmethodID get_user_location_accuracy_meters,
      JniHelper::GetMethodID(env, options_class.get(),
                             "getUserLocationAccuracyMeters", "()F"));
  TC3_ASSIGN_OR_RETURN(float user_location_accuracy_meters,
                       JniHelper::CallFloatMethod(
                           env, joptions, get_user_location_accuracy_meters));

  // .getUsePodNer()
  TC3_ASSIGN_OR_RETURN(
      jmethodID get_use_pod_ner,
      JniHelper::GetMethodID(env, options_class.get(), "getUsePodNer", "()Z"));
  TC3_ASSIGN_OR_RETURN(bool use_pod_ner, JniHelper::CallBooleanMethod(
                                             env, joptions, get_use_pod_ner));

  SelectionOptions options;
  TC3_ASSIGN_OR_RETURN(options.locales,
                       JStringToUtf8String(env, locales.get()));
  options.annotation_usecase =
      static_cast<AnnotationUsecase>(annotation_usecase);
  TC3_ASSIGN_OR_RETURN(
      options.detected_text_language_tags,
      JStringToUtf8String(env, detected_text_language_tags.get()));
  options.location_context = {user_location_lat, user_location_lng,
                              user_location_accuracy_meters};
  options.use_pod_ner = use_pod_ner;
  return options;
}

StatusOr<ClassificationOptions> FromJavaClassificationOptions(
    JNIEnv* env, jobject joptions) {
  if (!joptions) {
    // Falling back to default options in case joptions is null
    ClassificationOptions default_classification_options;
    return default_classification_options;
  }

  TC3_ASSIGN_OR_RETURN(ClassificationOptions classifier_options,
                       FromJavaOptionsInternal<ClassificationOptions>(
                           env, joptions,
                           TC3_PACKAGE_PATH TC3_ANNOTATOR_CLASS_NAME_STR
                           "$ClassificationOptions"));

  TC3_ASSIGN_OR_RETURN(
      ScopedLocalRef<jclass> options_class,
      JniHelper::FindClass(env, TC3_PACKAGE_PATH TC3_ANNOTATOR_CLASS_NAME_STR
                           "$ClassificationOptions"));
  // .getUserFamiliarLanguageTags()
  TC3_ASSIGN_OR_RETURN(jmethodID get_user_familiar_language_tags,
                       JniHelper::GetMethodID(env, options_class.get(),
                                              "getUserFamiliarLanguageTags",
                                              "()Ljava/lang/String;"));
  TC3_ASSIGN_OR_RETURN(ScopedLocalRef<jstring> user_familiar_language_tags,
                       JniHelper::CallObjectMethod<jstring>(
                           env, joptions, get_user_familiar_language_tags));

  TC3_ASSIGN_OR_RETURN(
      classifier_options.user_familiar_language_tags,
      JStringToUtf8String(env, user_familiar_language_tags.get()));

  // .getTriggerDictionaryOnBeginnerWords()
  TC3_ASSIGN_OR_RETURN(
      jmethodID get_trigger_dictionary_on_beginner_words,
      JniHelper::GetMethodID(env, options_class.get(),
                             "getTriggerDictionaryOnBeginnerWords", "()Z"));
  TC3_ASSIGN_OR_RETURN(
      classifier_options.trigger_dictionary_on_beginner_words,
      JniHelper::CallBooleanMethod(env, joptions,
                                   get_trigger_dictionary_on_beginner_words));

  return classifier_options;
}

StatusOr<AnnotationOptions> FromJavaAnnotationOptions(JNIEnv* env,
                                                      jobject joptions) {
  if (!joptions) {
    // Falling back to default options in case joptions is null
    AnnotationOptions default_annotation_options;
    return default_annotation_options;
  }

  TC3_ASSIGN_OR_RETURN(
      ScopedLocalRef<jclass> options_class,
      JniHelper::FindClass(env, TC3_PACKAGE_PATH TC3_ANNOTATOR_CLASS_NAME_STR
                           "$AnnotationOptions"));

  // .getEntityTypes()
  TC3_ASSIGN_OR_RETURN(
      jmethodID get_entity_types,
      JniHelper::GetMethodID(env, options_class.get(), "getEntityTypes",
                             "()[Ljava/lang/String;"));
  TC3_ASSIGN_OR_RETURN(
      ScopedLocalRef<jobject> entity_types,
      JniHelper::CallObjectMethod<jobject>(env, joptions, get_entity_types));

  // .isSerializedEntityDataEnabled()
  TC3_ASSIGN_OR_RETURN(
      jmethodID is_serialized_entity_data_enabled_method,
      JniHelper::GetMethodID(env, options_class.get(),
                             "isSerializedEntityDataEnabled", "()Z"));
  TC3_ASSIGN_OR_RETURN(
      bool is_serialized_entity_data_enabled,
      JniHelper::CallBooleanMethod(env, joptions,
                                   is_serialized_entity_data_enabled_method));

  // .hasLocationPermission()
  TC3_ASSIGN_OR_RETURN(jmethodID has_location_permission_method,
                       JniHelper::GetMethodID(env, options_class.get(),
                                              "hasLocationPermission", "()Z"));
  TC3_ASSIGN_OR_RETURN(bool has_location_permission,
                       JniHelper::CallBooleanMethod(
                           env, joptions, has_location_permission_method));

  // .hasPersonalizationPermission()
  TC3_ASSIGN_OR_RETURN(
      jmethodID has_personalization_permission_method,
      JniHelper::GetMethodID(env, options_class.get(),
                             "hasPersonalizationPermission", "()Z"));
  TC3_ASSIGN_OR_RETURN(
      bool has_personalization_permission,
      JniHelper::CallBooleanMethod(env, joptions,
                                   has_personalization_permission_method));
  // .getAnnotateMode()
  TC3_ASSIGN_OR_RETURN(jmethodID get_annotate_mode,
                       JniHelper::GetMethodID(env, options_class.get(),
                                              "getAnnotateMode", "()I"));
  TC3_ASSIGN_OR_RETURN(
      int32 annotate_mode,
      JniHelper::CallIntMethod(env, joptions, get_annotate_mode));

  TC3_ASSIGN_OR_RETURN(
      AnnotationOptions annotation_options,
      FromJavaOptionsInternal<AnnotationOptions>(
          env, joptions,
          TC3_PACKAGE_PATH TC3_ANNOTATOR_CLASS_NAME_STR "$AnnotationOptions"));
  TC3_ASSIGN_OR_RETURN(annotation_options.entity_types,
                       EntityTypesFromJObject(env, entity_types.get()));
  annotation_options.is_serialized_entity_data_enabled =
      is_serialized_entity_data_enabled;
  annotation_options.permissions.has_location_permission =
      has_location_permission;
  annotation_options.permissions.has_personalization_permission =
      has_personalization_permission;
  annotation_options.annotate_mode = static_cast<AnnotateMode>(annotate_mode);

  // .getTriggerDictionaryOnBeginnerWords()
  TC3_ASSIGN_OR_RETURN(
      jmethodID get_trigger_dictionary_on_beginner_words,
      JniHelper::GetMethodID(env, options_class.get(),
                             "getTriggerDictionaryOnBeginnerWords", "()Z"));
  TC3_ASSIGN_OR_RETURN(
      annotation_options.trigger_dictionary_on_beginner_words,
      JniHelper::CallBooleanMethod(env, joptions,
                                   get_trigger_dictionary_on_beginner_words));
  return annotation_options;
}

StatusOr<InputFragment> FromJavaInputFragment(JNIEnv* env, jobject jfragment) {
  if (!jfragment) {
    return Status(StatusCode::INTERNAL, "Called with null input fragment.");
  }
  InputFragment fragment;

  TC3_ASSIGN_OR_RETURN(
      ScopedLocalRef<jclass> fragment_class,
      JniHelper::FindClass(
          env, TC3_PACKAGE_PATH TC3_ANNOTATOR_CLASS_NAME_STR "$InputFragment"));

  // .getText()
  TC3_ASSIGN_OR_RETURN(
      jmethodID get_text,
      JniHelper::GetMethodID(env, fragment_class.get(), "getText",
                             "()Ljava/lang/String;"));

  TC3_ASSIGN_OR_RETURN(
      ScopedLocalRef<jstring> text,
      JniHelper::CallObjectMethod<jstring>(env, jfragment, get_text));

  TC3_ASSIGN_OR_RETURN(fragment.text, JStringToUtf8String(env, text.get()));

  // .hasDatetimeOptions()
  TC3_ASSIGN_OR_RETURN(jmethodID has_date_time_options_method,
                       JniHelper::GetMethodID(env, fragment_class.get(),
                                              "hasDatetimeOptions", "()Z"));

  TC3_ASSIGN_OR_RETURN(bool has_date_time_options,
                       JniHelper::CallBooleanMethod(
                           env, jfragment, has_date_time_options_method));

  if (has_date_time_options) {
    // .getReferenceTimeMsUtc()
    TC3_ASSIGN_OR_RETURN(
        jmethodID get_reference_time_method,
        JniHelper::GetMethodID(env, fragment_class.get(),
                               "getReferenceTimeMsUtc", "()J"));

    TC3_ASSIGN_OR_RETURN(
        int64 reference_time,
        JniHelper::CallLongMethod(env, jfragment, get_reference_time_method));

    // .getReferenceTimezone()
    TC3_ASSIGN_OR_RETURN(
        jmethodID get_reference_timezone_method,
        JniHelper::GetMethodID(env, fragment_class.get(),
                               "getReferenceTimezone", "()Ljava/lang/String;"));

    TC3_ASSIGN_OR_RETURN(ScopedLocalRef<jstring> jreference_timezone,
                         JniHelper::CallObjectMethod<jstring>(
                             env, jfragment, get_reference_timezone_method));

    TC3_ASSIGN_OR_RETURN(std::string reference_timezone,
                         JStringToUtf8String(env, jreference_timezone.get()));

    fragment.datetime_options =
        DatetimeOptions{.reference_time_ms_utc = reference_time,
                        .reference_timezone = reference_timezone};
  }

  // .getBoundingBoxHeight()
  TC3_ASSIGN_OR_RETURN(jmethodID get_bounding_box_height,
                       JniHelper::GetMethodID(env, fragment_class.get(),
                                              "getBoundingBoxHeight", "()F"));
  TC3_ASSIGN_OR_RETURN(
      float bounding_box_height,
      JniHelper::CallFloatMethod(env, jfragment, get_bounding_box_height));

  fragment.bounding_box_height = bounding_box_height;

  // .getBoundingBoxTop()
  TC3_ASSIGN_OR_RETURN(jmethodID get_bounding_box_top,
                       JniHelper::GetMethodID(env, fragment_class.get(),
                                              "getBoundingBoxTop", "()F"));
  TC3_ASSIGN_OR_RETURN(
      float bounding_box_top,
      JniHelper::CallFloatMethod(env, jfragment, get_bounding_box_top));
  fragment.bounding_box_top = bounding_box_top;
  return fragment;
}
}  // namespace libtextclassifier3