Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2017 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 android.view.textclassifier; |
| 18 | |
| 19 | import android.annotation.NonNull; |
Abodunrinwa Toki | 6b76675 | 2017-01-17 16:25:38 -0800 | [diff] [blame] | 20 | import android.annotation.Nullable; |
Abodunrinwa Toki | ad52f4b | 2018-02-06 23:32:41 +0000 | [diff] [blame] | 21 | import android.annotation.WorkerThread; |
Jan Althaus | 20d346e | 2018-03-23 14:03:52 +0100 | [diff] [blame] | 22 | import android.app.RemoteAction; |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 23 | import android.content.Context; |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 24 | import android.content.Intent; |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 25 | import android.icu.util.ULocale; |
Jan Althaus | 05e0051 | 2018-02-02 15:28:34 +0100 | [diff] [blame] | 26 | import android.os.Bundle; |
Abodunrinwa Toki | 4cfda0b | 2017-02-28 18:56:47 +0000 | [diff] [blame] | 27 | import android.os.LocaleList; |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 28 | import android.os.ParcelFileDescriptor; |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 29 | import android.util.ArrayMap; |
| 30 | import android.util.ArraySet; |
| 31 | import android.util.Pair; |
Tony Mak | 20fe187 | 2019-03-22 15:35:15 +0000 | [diff] [blame] | 32 | import android.view.textclassifier.ActionsModelParamsSupplier.ActionsModelParams; |
Tony Mak | 8ab9b18 | 2019-03-01 16:44:17 +0000 | [diff] [blame] | 33 | import android.view.textclassifier.intent.ClassificationIntentFactory; |
| 34 | import android.view.textclassifier.intent.LabeledIntent; |
| 35 | import android.view.textclassifier.intent.LegacyClassificationIntentFactory; |
| 36 | import android.view.textclassifier.intent.TemplateClassificationIntentFactory; |
| 37 | import android.view.textclassifier.intent.TemplateIntentFactory; |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 38 | |
Abodunrinwa Toki | c39006a1 | 2017-03-29 01:25:23 +0100 | [diff] [blame] | 39 | import com.android.internal.annotations.GuardedBy; |
Tony Mak | f93e9e5 | 2018-07-16 14:46:29 +0200 | [diff] [blame] | 40 | import com.android.internal.util.IndentingPrintWriter; |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 41 | import com.android.internal.util.Preconditions; |
| 42 | |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 43 | import com.google.android.textclassifier.ActionsSuggestionsModel; |
Tony Mak | 64c4cb2 | 2018-09-25 13:38:28 +0100 | [diff] [blame] | 44 | import com.google.android.textclassifier.AnnotatorModel; |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 45 | import com.google.android.textclassifier.LangIdModel; |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 46 | import com.google.android.textclassifier.LangIdModel.LanguageResult; |
Tony Mak | 64c4cb2 | 2018-09-25 13:38:28 +0100 | [diff] [blame] | 47 | |
Abodunrinwa Toki | c39006a1 | 2017-03-29 01:25:23 +0100 | [diff] [blame] | 48 | import java.io.File; |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 49 | import java.io.FileNotFoundException; |
Abodunrinwa Toki | 146d0d4 | 2017-04-25 01:39:19 +0100 | [diff] [blame] | 50 | import java.io.IOException; |
Jan Althaus | a1652cf | 2018-03-29 17:51:57 +0200 | [diff] [blame] | 51 | import java.time.Instant; |
| 52 | import java.time.ZonedDateTime; |
Abodunrinwa Toki | 6b76675 | 2017-01-17 16:25:38 -0800 | [diff] [blame] | 53 | import java.util.ArrayList; |
Richard Ledley | db18a57 | 2017-11-30 17:33:51 +0000 | [diff] [blame] | 54 | import java.util.Collection; |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 55 | import java.util.Collections; |
Abodunrinwa Toki | 6b76675 | 2017-01-17 16:25:38 -0800 | [diff] [blame] | 56 | import java.util.List; |
Abodunrinwa Toki | 9b4c82a | 2017-02-06 20:29:36 +0000 | [diff] [blame] | 57 | import java.util.Locale; |
Abodunrinwa Toki | 6b76675 | 2017-01-17 16:25:38 -0800 | [diff] [blame] | 58 | import java.util.Map; |
Abodunrinwa Toki | c39006a1 | 2017-03-29 01:25:23 +0100 | [diff] [blame] | 59 | import java.util.Objects; |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 60 | import java.util.Set; |
Tony Mak | 20fe187 | 2019-03-22 15:35:15 +0000 | [diff] [blame] | 61 | import java.util.function.Supplier; |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 62 | |
| 63 | /** |
| 64 | * Default implementation of the {@link TextClassifier} interface. |
| 65 | * |
| 66 | * <p>This class uses machine learning to recognize entities in text. |
| 67 | * Unless otherwise stated, methods of this class are blocking operations and should most |
| 68 | * likely not be called on the UI thread. |
| 69 | * |
| 70 | * @hide |
| 71 | */ |
Abodunrinwa Toki | d32906c | 2018-01-18 04:34:44 -0800 | [diff] [blame] | 72 | public final class TextClassifierImpl implements TextClassifier { |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 73 | |
Abodunrinwa Toki | 692b196 | 2017-08-15 15:05:11 +0100 | [diff] [blame] | 74 | private static final String LOG_TAG = DEFAULT_LOG_TAG; |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 75 | |
Tony Mak | e94e078 | 2018-12-14 11:57:54 +0800 | [diff] [blame] | 76 | private static final boolean DEBUG = false; |
| 77 | |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 78 | private static final File FACTORY_MODEL_DIR = new File("/etc/textclassifier/"); |
| 79 | // Annotator |
| 80 | private static final String ANNOTATOR_FACTORY_MODEL_FILENAME_REGEX = |
| 81 | "textclassifier\\.(.*)\\.model"; |
| 82 | private static final File ANNOTATOR_UPDATED_MODEL_FILE = |
| 83 | new File("/data/misc/textclassifier/textclassifier.model"); |
| 84 | |
| 85 | // LangID |
| 86 | private static final String LANG_ID_FACTORY_MODEL_FILENAME_REGEX = "lang_id.model"; |
| 87 | private static final File UPDATED_LANG_ID_MODEL_FILE = |
| 88 | new File("/data/misc/textclassifier/lang_id.model"); |
Abodunrinwa Toki | b89cf02 | 2017-02-06 19:53:22 +0000 | [diff] [blame] | 89 | |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 90 | // Actions |
Tony Mak | 237f37b | 2019-03-22 13:35:40 +0000 | [diff] [blame] | 91 | private static final String ACTIONS_FACTORY_MODEL_FILENAME_REGEX = |
| 92 | "actions_suggestions\\.(.*)\\.model"; |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 93 | private static final File UPDATED_ACTIONS_MODEL = |
| 94 | new File("/data/misc/textclassifier/actions_suggestions.model"); |
| 95 | |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 96 | private final Context mContext; |
Abodunrinwa Toki | d32906c | 2018-01-18 04:34:44 -0800 | [diff] [blame] | 97 | private final TextClassifier mFallback; |
Jan Althaus | 31efdc3 | 2018-02-19 22:23:13 +0100 | [diff] [blame] | 98 | private final GenerateLinksLogger mGenerateLinksLogger; |
Abodunrinwa Toki | 1d77557 | 2017-05-08 16:03:01 +0100 | [diff] [blame] | 99 | |
Abodunrinwa Toki | d32906c | 2018-01-18 04:34:44 -0800 | [diff] [blame] | 100 | private final Object mLock = new Object(); |
Tony Mak | 6fc4318 | 2019-03-07 17:30:33 +0000 | [diff] [blame] | 101 | |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 102 | @GuardedBy("mLock") |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 103 | private ModelFileManager.ModelFile mAnnotatorModelInUse; |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 104 | @GuardedBy("mLock") |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 105 | private AnnotatorModel mAnnotatorImpl; |
Tony Mak | 6fc4318 | 2019-03-07 17:30:33 +0000 | [diff] [blame] | 106 | |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 107 | @GuardedBy("mLock") |
Tony Mak | 6fc4318 | 2019-03-07 17:30:33 +0000 | [diff] [blame] | 108 | private ModelFileManager.ModelFile mLangIdModelInUse; |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 109 | @GuardedBy("mLock") |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 110 | private LangIdModel mLangIdImpl; |
Tony Mak | 6fc4318 | 2019-03-07 17:30:33 +0000 | [diff] [blame] | 111 | |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 112 | @GuardedBy("mLock") |
Tony Mak | e94e078 | 2018-12-14 11:57:54 +0800 | [diff] [blame] | 113 | private ModelFileManager.ModelFile mActionModelInUse; |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 114 | @GuardedBy("mLock") |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 115 | private ActionsSuggestionsModel mActionsImpl; |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 116 | |
Tony Mak | 5a5f0d5 | 2019-01-08 11:07:23 +0000 | [diff] [blame] | 117 | private final SelectionSessionLogger mSessionLogger = new SelectionSessionLogger(); |
| 118 | private final TextClassifierEventTronLogger mTextClassifierEventTronLogger = |
| 119 | new TextClassifierEventTronLogger(); |
Abodunrinwa Toki | 3bb4436 | 2017-12-05 07:33:41 +0000 | [diff] [blame] | 120 | |
Abodunrinwa Toki | db8fc31 | 2018-02-26 21:37:51 +0000 | [diff] [blame] | 121 | private final TextClassificationConstants mSettings; |
Abodunrinwa Toki | 0e6b43e | 2017-09-19 23:18:40 +0100 | [diff] [blame] | 122 | |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 123 | private final ModelFileManager mAnnotatorModelFileManager; |
| 124 | private final ModelFileManager mLangIdModelFileManager; |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 125 | private final ModelFileManager mActionsModelFileManager; |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 126 | |
Tony Mak | 8ab9b18 | 2019-03-01 16:44:17 +0000 | [diff] [blame] | 127 | private final ClassificationIntentFactory mClassificationIntentFactory; |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 128 | private final TemplateIntentFactory mTemplateIntentFactory; |
Tony Mak | 20fe187 | 2019-03-22 15:35:15 +0000 | [diff] [blame] | 129 | private final Supplier<ActionsModelParams> mActionsModelParamsSupplier; |
Tony Mak | fc039c3 | 2019-01-17 19:32:08 +0000 | [diff] [blame] | 130 | |
Abodunrinwa Toki | 253827f | 2018-04-24 19:19:48 +0100 | [diff] [blame] | 131 | public TextClassifierImpl( |
| 132 | Context context, TextClassificationConstants settings, TextClassifier fallback) { |
Daulet Zhanguzin | e155947 | 2019-12-18 14:17:56 +0000 | [diff] [blame] | 133 | mContext = Objects.requireNonNull(context); |
| 134 | mFallback = Objects.requireNonNull(fallback); |
| 135 | mSettings = Objects.requireNonNull(settings); |
Abodunrinwa Toki | db8fc31 | 2018-02-26 21:37:51 +0000 | [diff] [blame] | 136 | mGenerateLinksLogger = new GenerateLinksLogger(mSettings.getGenerateLinksLogSampleRate()); |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 137 | mAnnotatorModelFileManager = new ModelFileManager( |
| 138 | new ModelFileManager.ModelFileSupplierImpl( |
| 139 | FACTORY_MODEL_DIR, |
| 140 | ANNOTATOR_FACTORY_MODEL_FILENAME_REGEX, |
| 141 | ANNOTATOR_UPDATED_MODEL_FILE, |
| 142 | AnnotatorModel::getVersion, |
| 143 | AnnotatorModel::getLocales)); |
| 144 | mLangIdModelFileManager = new ModelFileManager( |
| 145 | new ModelFileManager.ModelFileSupplierImpl( |
| 146 | FACTORY_MODEL_DIR, |
| 147 | LANG_ID_FACTORY_MODEL_FILENAME_REGEX, |
| 148 | UPDATED_LANG_ID_MODEL_FILE, |
Tony Mak | c5a4612 | 2018-12-05 22:19:22 +0000 | [diff] [blame] | 149 | LangIdModel::getVersion, |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 150 | fd -> ModelFileManager.ModelFile.LANGUAGE_INDEPENDENT)); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 151 | mActionsModelFileManager = new ModelFileManager( |
| 152 | new ModelFileManager.ModelFileSupplierImpl( |
| 153 | FACTORY_MODEL_DIR, |
| 154 | ACTIONS_FACTORY_MODEL_FILENAME_REGEX, |
| 155 | UPDATED_ACTIONS_MODEL, |
| 156 | ActionsSuggestionsModel::getVersion, |
| 157 | ActionsSuggestionsModel::getLocales)); |
Tony Mak | fc039c3 | 2019-01-17 19:32:08 +0000 | [diff] [blame] | 158 | |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 159 | mTemplateIntentFactory = new TemplateIntentFactory(); |
Tony Mak | 8ab9b18 | 2019-03-01 16:44:17 +0000 | [diff] [blame] | 160 | mClassificationIntentFactory = mSettings.isTemplateIntentFactoryEnabled() |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 161 | ? new TemplateClassificationIntentFactory( |
Tony Mak | 8ab9b18 | 2019-03-01 16:44:17 +0000 | [diff] [blame] | 162 | mTemplateIntentFactory, new LegacyClassificationIntentFactory()) |
| 163 | : new LegacyClassificationIntentFactory(); |
Tony Mak | 20fe187 | 2019-03-22 15:35:15 +0000 | [diff] [blame] | 164 | mActionsModelParamsSupplier = new ActionsModelParamsSupplier(mContext, |
| 165 | () -> { |
| 166 | synchronized (mLock) { |
| 167 | // Clear mActionsImpl here, so that we will create a new |
| 168 | // ActionsSuggestionsModel object with the new flag in the next request. |
| 169 | mActionsImpl = null; |
| 170 | mActionModelInUse = null; |
| 171 | } |
| 172 | }); |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 173 | } |
| 174 | |
Abodunrinwa Toki | 253827f | 2018-04-24 19:19:48 +0100 | [diff] [blame] | 175 | public TextClassifierImpl(Context context, TextClassificationConstants settings) { |
| 176 | this(context, settings, TextClassifier.NO_OP); |
| 177 | } |
| 178 | |
Abodunrinwa Toki | d32906c | 2018-01-18 04:34:44 -0800 | [diff] [blame] | 179 | /** @inheritDoc */ |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 180 | @Override |
Abodunrinwa Toki | ad52f4b | 2018-02-06 23:32:41 +0000 | [diff] [blame] | 181 | @WorkerThread |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 182 | public TextSelection suggestSelection(TextSelection.Request request) { |
Daulet Zhanguzin | e155947 | 2019-12-18 14:17:56 +0000 | [diff] [blame] | 183 | Objects.requireNonNull(request); |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 184 | Utils.checkMainThread(); |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 185 | try { |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 186 | final int rangeLength = request.getEndIndex() - request.getStartIndex(); |
| 187 | final String string = request.getText().toString(); |
| 188 | if (string.length() > 0 |
Abodunrinwa Toki | db8fc31 | 2018-02-26 21:37:51 +0000 | [diff] [blame] | 189 | && rangeLength <= mSettings.getSuggestSelectionMaxRangeLength()) { |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 190 | final String localesString = concatenateLocales(request.getDefaultLocales()); |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 191 | final String detectLanguageTags = detectLanguageTagsFromText(request.getText()); |
Jan Althaus | a1652cf | 2018-03-29 17:51:57 +0200 | [diff] [blame] | 192 | final ZonedDateTime refTime = ZonedDateTime.now(); |
Tony Mak | 2a3adb7 | 2019-03-20 17:55:53 +0000 | [diff] [blame] | 193 | final AnnotatorModel annotatorImpl = getAnnotatorImpl(request.getDefaultLocales()); |
Abodunrinwa Toki | 2b6020f | 2017-10-28 02:28:45 +0100 | [diff] [blame] | 194 | final int start; |
| 195 | final int end; |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 196 | if (mSettings.isModelDarkLaunchEnabled() && !request.isDarkLaunchAllowed()) { |
| 197 | start = request.getStartIndex(); |
| 198 | end = request.getEndIndex(); |
Abodunrinwa Toki | 2b6020f | 2017-10-28 02:28:45 +0100 | [diff] [blame] | 199 | } else { |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 200 | final int[] startEnd = annotatorImpl.suggestSelection( |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 201 | string, request.getStartIndex(), request.getEndIndex(), |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 202 | new AnnotatorModel.SelectionOptions(localesString, detectLanguageTags)); |
Abodunrinwa Toki | 2b6020f | 2017-10-28 02:28:45 +0100 | [diff] [blame] | 203 | start = startEnd[0]; |
| 204 | end = startEnd[1]; |
| 205 | } |
Jan Althaus | b7f7d36 | 2018-01-26 13:51:31 +0100 | [diff] [blame] | 206 | if (start < end |
Abodunrinwa Toki | b416297 | 2017-05-05 18:07:17 +0100 | [diff] [blame] | 207 | && start >= 0 && end <= string.length() |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 208 | && start <= request.getStartIndex() && end >= request.getEndIndex()) { |
Abodunrinwa Toki | 692b196 | 2017-08-15 15:05:11 +0100 | [diff] [blame] | 209 | final TextSelection.Builder tsBuilder = new TextSelection.Builder(start, end); |
Tony Mak | 64c4cb2 | 2018-09-25 13:38:28 +0100 | [diff] [blame] | 210 | final AnnotatorModel.ClassificationResult[] results = |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 211 | annotatorImpl.classifyText( |
Abodunrinwa Toki | d2d1399 | 2017-03-24 21:43:13 +0000 | [diff] [blame] | 212 | string, start, end, |
Tony Mak | 64c4cb2 | 2018-09-25 13:38:28 +0100 | [diff] [blame] | 213 | new AnnotatorModel.ClassificationOptions( |
Jan Althaus | a1652cf | 2018-03-29 17:51:57 +0200 | [diff] [blame] | 214 | refTime.toInstant().toEpochMilli(), |
| 215 | refTime.getZone().getId(), |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 216 | localesString, |
| 217 | detectLanguageTags), |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 218 | // Passing null here to suppress intent generation |
| 219 | // TODO: Use an explicit flag to suppress it. |
| 220 | /* appContext */ null, |
| 221 | /* deviceLocales */null); |
Abodunrinwa Toki | a6096f6 | 2017-03-08 17:21:40 +0000 | [diff] [blame] | 222 | final int size = results.length; |
| 223 | for (int i = 0; i < size; i++) { |
Lukas Zilka | f8c36bf | 2018-02-07 20:30:08 +0100 | [diff] [blame] | 224 | tsBuilder.setEntityType(results[i].getCollection(), results[i].getScore()); |
Abodunrinwa Toki | a6096f6 | 2017-03-08 17:21:40 +0000 | [diff] [blame] | 225 | } |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 226 | return tsBuilder.setId(createId( |
| 227 | string, request.getStartIndex(), request.getEndIndex())) |
Abodunrinwa Toki | 692b196 | 2017-08-15 15:05:11 +0100 | [diff] [blame] | 228 | .build(); |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 229 | } else { |
| 230 | // We can not trust the result. Log the issue and ignore the result. |
| 231 | Log.d(LOG_TAG, "Got bad indices for input text. Ignoring result."); |
| 232 | } |
| 233 | } |
| 234 | } catch (Throwable t) { |
| 235 | // Avoid throwing from this method. Log the error. |
| 236 | Log.e(LOG_TAG, |
| 237 | "Error suggesting selection for text. No changes to selection suggested.", |
| 238 | t); |
| 239 | } |
| 240 | // Getting here means something went wrong, return a NO_OP result. |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 241 | return mFallback.suggestSelection(request); |
Abodunrinwa Toki | 2b6020f | 2017-10-28 02:28:45 +0100 | [diff] [blame] | 242 | } |
| 243 | |
Abodunrinwa Toki | d32906c | 2018-01-18 04:34:44 -0800 | [diff] [blame] | 244 | /** @inheritDoc */ |
Abodunrinwa Toki | 2b6020f | 2017-10-28 02:28:45 +0100 | [diff] [blame] | 245 | @Override |
Abodunrinwa Toki | ad52f4b | 2018-02-06 23:32:41 +0000 | [diff] [blame] | 246 | @WorkerThread |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 247 | public TextClassification classifyText(TextClassification.Request request) { |
Daulet Zhanguzin | e155947 | 2019-12-18 14:17:56 +0000 | [diff] [blame] | 248 | Objects.requireNonNull(request); |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 249 | Utils.checkMainThread(); |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 250 | try { |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 251 | final int rangeLength = request.getEndIndex() - request.getStartIndex(); |
| 252 | final String string = request.getText().toString(); |
| 253 | if (string.length() > 0 && rangeLength <= mSettings.getClassifyTextMaxRangeLength()) { |
| 254 | final String localesString = concatenateLocales(request.getDefaultLocales()); |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 255 | final String detectLanguageTags = detectLanguageTagsFromText(request.getText()); |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 256 | final ZonedDateTime refTime = request.getReferenceTime() != null |
| 257 | ? request.getReferenceTime() : ZonedDateTime.now(); |
Tony Mak | 64c4cb2 | 2018-09-25 13:38:28 +0100 | [diff] [blame] | 258 | final AnnotatorModel.ClassificationResult[] results = |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 259 | getAnnotatorImpl(request.getDefaultLocales()) |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 260 | .classifyText( |
| 261 | string, request.getStartIndex(), request.getEndIndex(), |
Tony Mak | 64c4cb2 | 2018-09-25 13:38:28 +0100 | [diff] [blame] | 262 | new AnnotatorModel.ClassificationOptions( |
Jan Althaus | a1652cf | 2018-03-29 17:51:57 +0200 | [diff] [blame] | 263 | refTime.toInstant().toEpochMilli(), |
| 264 | refTime.getZone().getId(), |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 265 | localesString, |
| 266 | detectLanguageTags), |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 267 | mContext, |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 268 | getResourceLocalesString() |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 269 | ); |
Abodunrinwa Toki | a6096f6 | 2017-03-08 17:21:40 +0000 | [diff] [blame] | 270 | if (results.length > 0) { |
Jan Althaus | 705b9e9 | 2018-01-22 18:22:29 +0100 | [diff] [blame] | 271 | return createClassificationResult( |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 272 | results, string, |
| 273 | request.getStartIndex(), request.getEndIndex(), refTime.toInstant()); |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 274 | } |
| 275 | } |
| 276 | } catch (Throwable t) { |
| 277 | // Avoid throwing from this method. Log the error. |
Abodunrinwa Toki | 7861885 | 2017-10-17 15:31:39 +0100 | [diff] [blame] | 278 | Log.e(LOG_TAG, "Error getting text classification info.", t); |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 279 | } |
| 280 | // Getting here means something went wrong, return a NO_OP result. |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 281 | return mFallback.classifyText(request); |
Abodunrinwa Toki | 2b6020f | 2017-10-28 02:28:45 +0100 | [diff] [blame] | 282 | } |
| 283 | |
Abodunrinwa Toki | d32906c | 2018-01-18 04:34:44 -0800 | [diff] [blame] | 284 | /** @inheritDoc */ |
Abodunrinwa Toki | 2b6020f | 2017-10-28 02:28:45 +0100 | [diff] [blame] | 285 | @Override |
Abodunrinwa Toki | ad52f4b | 2018-02-06 23:32:41 +0000 | [diff] [blame] | 286 | @WorkerThread |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 287 | public TextLinks generateLinks(@NonNull TextLinks.Request request) { |
Daulet Zhanguzin | e155947 | 2019-12-18 14:17:56 +0000 | [diff] [blame] | 288 | Objects.requireNonNull(request); |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 289 | Utils.checkMainThread(); |
Tony Mak | c5a7432 | 2020-02-04 17:18:15 +0000 | [diff] [blame] | 290 | if (!Utils.checkTextLength(request.getText(), getMaxGenerateLinksTextLength())) { |
| 291 | return mFallback.generateLinks(request); |
| 292 | } |
Abodunrinwa Toki | 6563833 | 2018-03-16 21:08:50 +0000 | [diff] [blame] | 293 | |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 294 | if (!mSettings.isSmartLinkifyEnabled() && request.isLegacyFallback()) { |
| 295 | return Utils.generateLegacyLinks(request); |
Abodunrinwa Toki | 6563833 | 2018-03-16 21:08:50 +0000 | [diff] [blame] | 296 | } |
| 297 | |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 298 | final String textString = request.getText().toString(); |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 299 | final TextLinks.Builder builder = new TextLinks.Builder(textString); |
Richard Ledley | 9cfa606 | 2018-01-15 13:13:29 +0000 | [diff] [blame] | 300 | |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 301 | try { |
Jan Althaus | 31efdc3 | 2018-02-19 22:23:13 +0100 | [diff] [blame] | 302 | final long startTimeMs = System.currentTimeMillis(); |
Jan Althaus | a1652cf | 2018-03-29 17:51:57 +0200 | [diff] [blame] | 303 | final ZonedDateTime refTime = ZonedDateTime.now(); |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 304 | final Collection<String> entitiesToIdentify = request.getEntityConfig() != null |
| 305 | ? request.getEntityConfig().resolveEntityListModifications( |
Abodunrinwa Toki | 0634af3 | 2019-04-04 13:10:59 +0100 | [diff] [blame] | 306 | getEntitiesForHints(request.getEntityConfig().getHints())) |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 307 | : mSettings.getEntityListDefault(); |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 308 | final String localesString = concatenateLocales(request.getDefaultLocales()); |
| 309 | final String detectLanguageTags = detectLanguageTagsFromText(request.getText()); |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 310 | final AnnotatorModel annotatorImpl = |
| 311 | getAnnotatorImpl(request.getDefaultLocales()); |
Tony Mak | b6afd3c | 2019-04-05 15:45:18 +0100 | [diff] [blame] | 312 | final boolean isSerializedEntityDataEnabled = |
| 313 | ExtrasUtils.isSerializedEntityDataEnabled(request); |
Tony Mak | 64c4cb2 | 2018-09-25 13:38:28 +0100 | [diff] [blame] | 314 | final AnnotatorModel.AnnotatedSpan[] annotations = |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 315 | annotatorImpl.annotate( |
Tony Mak | f99ee17 | 2018-11-23 12:14:39 +0000 | [diff] [blame] | 316 | textString, |
| 317 | new AnnotatorModel.AnnotationOptions( |
| 318 | refTime.toInstant().toEpochMilli(), |
| 319 | refTime.getZone().getId(), |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 320 | localesString, |
Tony Mak | b6afd3c | 2019-04-05 15:45:18 +0100 | [diff] [blame] | 321 | detectLanguageTags, |
| 322 | entitiesToIdentify, |
| 323 | AnnotatorModel.AnnotationUsecase.SMART.getValue(), |
| 324 | isSerializedEntityDataEnabled)); |
Tony Mak | 64c4cb2 | 2018-09-25 13:38:28 +0100 | [diff] [blame] | 325 | for (AnnotatorModel.AnnotatedSpan span : annotations) { |
| 326 | final AnnotatorModel.ClassificationResult[] results = |
Lukas Zilka | f8c36bf | 2018-02-07 20:30:08 +0100 | [diff] [blame] | 327 | span.getClassification(); |
| 328 | if (results.length == 0 |
| 329 | || !entitiesToIdentify.contains(results[0].getCollection())) { |
Richard Ledley | db18a57 | 2017-11-30 17:33:51 +0000 | [diff] [blame] | 330 | continue; |
| 331 | } |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 332 | final Map<String, Float> entityScores = new ArrayMap<>(); |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 333 | for (int i = 0; i < results.length; i++) { |
Lukas Zilka | f8c36bf | 2018-02-07 20:30:08 +0100 | [diff] [blame] | 334 | entityScores.put(results[i].getCollection(), results[i].getScore()); |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 335 | } |
Tony Mak | b6afd3c | 2019-04-05 15:45:18 +0100 | [diff] [blame] | 336 | Bundle extras = new Bundle(); |
| 337 | if (isSerializedEntityDataEnabled) { |
| 338 | ExtrasUtils.putEntities(extras, results); |
| 339 | } |
| 340 | builder.addLink(span.getStartIndex(), span.getEndIndex(), entityScores, extras); |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 341 | } |
Jan Althaus | 31efdc3 | 2018-02-19 22:23:13 +0100 | [diff] [blame] | 342 | final TextLinks links = builder.build(); |
| 343 | final long endTimeMs = System.currentTimeMillis(); |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 344 | final String callingPackageName = request.getCallingPackageName() == null |
| 345 | ? mContext.getPackageName() // local (in process) TC. |
| 346 | : request.getCallingPackageName(); |
Jan Althaus | 31efdc3 | 2018-02-19 22:23:13 +0100 | [diff] [blame] | 347 | mGenerateLinksLogger.logGenerateLinks( |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 348 | request.getText(), links, callingPackageName, endTimeMs - startTimeMs); |
Jan Althaus | 31efdc3 | 2018-02-19 22:23:13 +0100 | [diff] [blame] | 349 | return links; |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 350 | } catch (Throwable t) { |
| 351 | // Avoid throwing from this method. Log the error. |
| 352 | Log.e(LOG_TAG, "Error getting links info.", t); |
| 353 | } |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 354 | return mFallback.generateLinks(request); |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 355 | } |
| 356 | |
Jan Althaus | 108aad3 | 2018-01-30 15:26:55 +0100 | [diff] [blame] | 357 | /** @inheritDoc */ |
| 358 | @Override |
| 359 | public int getMaxGenerateLinksTextLength() { |
Abodunrinwa Toki | db8fc31 | 2018-02-26 21:37:51 +0000 | [diff] [blame] | 360 | return mSettings.getGenerateLinksMaxTextLength(); |
Jan Althaus | 108aad3 | 2018-01-30 15:26:55 +0100 | [diff] [blame] | 361 | } |
| 362 | |
Richard Ledley | 1fc998b | 2018-02-16 15:45:06 +0000 | [diff] [blame] | 363 | private Collection<String> getEntitiesForHints(Collection<String> hints) { |
Jan Althaus | 0aacdb6 | 2018-02-19 11:44:37 +0100 | [diff] [blame] | 364 | final boolean editable = hints.contains(HINT_TEXT_IS_EDITABLE); |
| 365 | final boolean notEditable = hints.contains(HINT_TEXT_IS_NOT_EDITABLE); |
| 366 | |
| 367 | // Use the default if there is no hint, or conflicting ones. |
| 368 | final boolean useDefault = editable == notEditable; |
| 369 | if (useDefault) { |
Abodunrinwa Toki | db8fc31 | 2018-02-26 21:37:51 +0000 | [diff] [blame] | 370 | return mSettings.getEntityListDefault(); |
Jan Althaus | 0aacdb6 | 2018-02-19 11:44:37 +0100 | [diff] [blame] | 371 | } else if (editable) { |
Abodunrinwa Toki | db8fc31 | 2018-02-26 21:37:51 +0000 | [diff] [blame] | 372 | return mSettings.getEntityListEditable(); |
Jan Althaus | 0aacdb6 | 2018-02-19 11:44:37 +0100 | [diff] [blame] | 373 | } else { // notEditable |
Abodunrinwa Toki | db8fc31 | 2018-02-26 21:37:51 +0000 | [diff] [blame] | 374 | return mSettings.getEntityListNotEditable(); |
Jan Althaus | 0aacdb6 | 2018-02-19 11:44:37 +0100 | [diff] [blame] | 375 | } |
Richard Ledley | db18a57 | 2017-11-30 17:33:51 +0000 | [diff] [blame] | 376 | } |
| 377 | |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 378 | /** @inheritDoc */ |
Abodunrinwa Toki | 88be5a6 | 2018-03-23 04:01:28 +0000 | [diff] [blame] | 379 | @Override |
| 380 | public void onSelectionEvent(SelectionEvent event) { |
Tony Mak | 5a5f0d5 | 2019-01-08 11:07:23 +0000 | [diff] [blame] | 381 | mSessionLogger.writeEvent(event); |
Abodunrinwa Toki | 88be5a6 | 2018-03-23 04:01:28 +0000 | [diff] [blame] | 382 | } |
| 383 | |
Abodunrinwa Toki | 37ccedc | 2018-12-11 00:35:11 +0000 | [diff] [blame] | 384 | @Override |
Tony Mak | e94e078 | 2018-12-14 11:57:54 +0800 | [diff] [blame] | 385 | public void onTextClassifierEvent(TextClassifierEvent event) { |
| 386 | if (DEBUG) { |
| 387 | Log.d(DEFAULT_LOG_TAG, "onTextClassifierEvent() called with: event = [" + event + "]"); |
| 388 | } |
Abodunrinwa Toki | 520b2f8 | 2019-01-27 07:48:02 +0000 | [diff] [blame] | 389 | try { |
Abodunrinwa Toki | 5258633 | 2019-05-22 18:43:16 +0100 | [diff] [blame] | 390 | final SelectionEvent selEvent = event.toSelectionEvent(); |
| 391 | if (selEvent != null) { |
| 392 | mSessionLogger.writeEvent(selEvent); |
| 393 | } else { |
| 394 | mTextClassifierEventTronLogger.writeEvent(event); |
| 395 | } |
Abodunrinwa Toki | 520b2f8 | 2019-01-27 07:48:02 +0000 | [diff] [blame] | 396 | } catch (Exception e) { |
| 397 | Log.e(LOG_TAG, "Error writing event", e); |
| 398 | } |
Abodunrinwa Toki | 37ccedc | 2018-12-11 00:35:11 +0000 | [diff] [blame] | 399 | } |
| 400 | |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 401 | /** @inheritDoc */ |
| 402 | @Override |
| 403 | public TextLanguage detectLanguage(@NonNull TextLanguage.Request request) { |
Daulet Zhanguzin | e155947 | 2019-12-18 14:17:56 +0000 | [diff] [blame] | 404 | Objects.requireNonNull(request); |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 405 | Utils.checkMainThread(); |
| 406 | try { |
| 407 | final TextLanguage.Builder builder = new TextLanguage.Builder(); |
| 408 | final LangIdModel.LanguageResult[] langResults = |
| 409 | getLangIdImpl().detectLanguages(request.getText().toString()); |
| 410 | for (int i = 0; i < langResults.length; i++) { |
| 411 | builder.putLocale( |
| 412 | ULocale.forLanguageTag(langResults[i].getLanguage()), |
| 413 | langResults[i].getScore()); |
| 414 | } |
| 415 | return builder.build(); |
| 416 | } catch (Throwable t) { |
| 417 | // Avoid throwing from this method. Log the error. |
| 418 | Log.e(LOG_TAG, "Error detecting text language.", t); |
| 419 | } |
| 420 | return mFallback.detectLanguage(request); |
| 421 | } |
| 422 | |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 423 | @Override |
| 424 | public ConversationActions suggestConversationActions(ConversationActions.Request request) { |
Daulet Zhanguzin | e155947 | 2019-12-18 14:17:56 +0000 | [diff] [blame] | 425 | Objects.requireNonNull(request); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 426 | Utils.checkMainThread(); |
| 427 | try { |
| 428 | ActionsSuggestionsModel actionsImpl = getActionsImpl(); |
| 429 | if (actionsImpl == null) { |
| 430 | // Actions model is optional, fallback if it is not available. |
| 431 | return mFallback.suggestConversationActions(request); |
| 432 | } |
Tony Mak | f99ee17 | 2018-11-23 12:14:39 +0000 | [diff] [blame] | 433 | ActionsSuggestionsModel.ConversationMessage[] nativeMessages = |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 434 | ActionsSuggestionsHelper.toNativeMessages( |
| 435 | request.getConversation(), this::detectLanguageTagsFromText); |
Tony Mak | f99ee17 | 2018-11-23 12:14:39 +0000 | [diff] [blame] | 436 | if (nativeMessages.length == 0) { |
| 437 | return mFallback.suggestConversationActions(request); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 438 | } |
| 439 | ActionsSuggestionsModel.Conversation nativeConversation = |
Tony Mak | f99ee17 | 2018-11-23 12:14:39 +0000 | [diff] [blame] | 440 | new ActionsSuggestionsModel.Conversation(nativeMessages); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 441 | |
| 442 | ActionsSuggestionsModel.ActionSuggestion[] nativeSuggestions = |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 443 | actionsImpl.suggestActionsWithIntents( |
| 444 | nativeConversation, |
| 445 | null, |
| 446 | mContext, |
Tony Mak | 2a3adb7 | 2019-03-20 17:55:53 +0000 | [diff] [blame] | 447 | getResourceLocalesString(), |
| 448 | getAnnotatorImpl(LocaleList.getDefault())); |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 449 | return createConversationActionResult(request, nativeSuggestions); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 450 | } catch (Throwable t) { |
| 451 | // Avoid throwing from this method. Log the error. |
| 452 | Log.e(LOG_TAG, "Error suggesting conversation actions.", t); |
| 453 | } |
| 454 | return mFallback.suggestConversationActions(request); |
| 455 | } |
| 456 | |
Tony Mak | c12035e | 2019-02-26 17:45:34 +0000 | [diff] [blame] | 457 | /** |
| 458 | * Returns the {@link ConversationAction} result, with a non-null extras. |
| 459 | * <p> |
| 460 | * Whenever the RemoteAction is non-null, you can expect its corresponding intent |
| 461 | * with a non-null component name is in the extras. |
| 462 | */ |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 463 | private ConversationActions createConversationActionResult( |
| 464 | ConversationActions.Request request, |
| 465 | ActionsSuggestionsModel.ActionSuggestion[] nativeSuggestions) { |
| 466 | Collection<String> expectedTypes = resolveActionTypesFromRequest(request); |
| 467 | List<ConversationAction> conversationActions = new ArrayList<>(); |
| 468 | for (ActionsSuggestionsModel.ActionSuggestion nativeSuggestion : nativeSuggestions) { |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 469 | String actionType = nativeSuggestion.getActionType(); |
| 470 | if (!expectedTypes.contains(actionType)) { |
| 471 | continue; |
| 472 | } |
Tony Mak | 8ab9b18 | 2019-03-01 16:44:17 +0000 | [diff] [blame] | 473 | LabeledIntent.Result labeledIntentResult = |
| 474 | ActionsSuggestionsHelper.createLabeledIntentResult( |
| 475 | mContext, |
| 476 | mTemplateIntentFactory, |
| 477 | nativeSuggestion); |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 478 | RemoteAction remoteAction = null; |
Tony Mak | 8ab9b18 | 2019-03-01 16:44:17 +0000 | [diff] [blame] | 479 | Bundle extras = new Bundle(); |
| 480 | if (labeledIntentResult != null) { |
| 481 | remoteAction = labeledIntentResult.remoteAction; |
| 482 | ExtrasUtils.putActionIntent(extras, labeledIntentResult.resolvedIntent); |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 483 | } |
Tony Mak | fdb3554 | 2019-03-22 12:01:50 +0000 | [diff] [blame] | 484 | ExtrasUtils.putSerializedEntityData(extras, nativeSuggestion.getSerializedEntityData()); |
Tony Mak | 0921442 | 2019-03-01 18:25:23 +0000 | [diff] [blame] | 485 | ExtrasUtils.putEntitiesExtras( |
| 486 | extras, |
| 487 | TemplateIntentFactory.nameVariantsToBundle(nativeSuggestion.getEntityData())); |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 488 | conversationActions.add( |
| 489 | new ConversationAction.Builder(actionType) |
| 490 | .setConfidenceScore(nativeSuggestion.getScore()) |
| 491 | .setTextReply(nativeSuggestion.getResponseText()) |
| 492 | .setAction(remoteAction) |
Tony Mak | c12035e | 2019-02-26 17:45:34 +0000 | [diff] [blame] | 493 | .setExtras(extras) |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 494 | .build()); |
| 495 | } |
Tony Mak | c12035e | 2019-02-26 17:45:34 +0000 | [diff] [blame] | 496 | conversationActions = |
| 497 | ActionsSuggestionsHelper.removeActionsWithDuplicates(conversationActions); |
Tony Mak | aa496d0 | 2019-04-11 17:38:47 +0100 | [diff] [blame] | 498 | if (request.getMaxSuggestions() >= 0 |
| 499 | && conversationActions.size() > request.getMaxSuggestions()) { |
| 500 | conversationActions = conversationActions.subList(0, request.getMaxSuggestions()); |
| 501 | } |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 502 | String resultId = ActionsSuggestionsHelper.createResultId( |
| 503 | mContext, |
| 504 | request.getConversation(), |
| 505 | mActionModelInUse.getVersion(), |
| 506 | mActionModelInUse.getSupportedLocales()); |
| 507 | return new ConversationActions(conversationActions, resultId); |
| 508 | } |
| 509 | |
Tony Mak | 82fa8d9 | 2018-12-07 17:37:43 +0000 | [diff] [blame] | 510 | @Nullable |
| 511 | private String detectLanguageTagsFromText(CharSequence text) { |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 512 | if (!mSettings.isDetectLanguagesFromTextEnabled()) { |
| 513 | return null; |
| 514 | } |
| 515 | final float threshold = getLangIdThreshold(); |
| 516 | if (threshold < 0 || threshold > 1) { |
| 517 | Log.w(LOG_TAG, |
| 518 | "[detectLanguageTagsFromText] unexpected threshold is found: " + threshold); |
| 519 | return null; |
| 520 | } |
Tony Mak | 82fa8d9 | 2018-12-07 17:37:43 +0000 | [diff] [blame] | 521 | TextLanguage.Request request = new TextLanguage.Request.Builder(text).build(); |
| 522 | TextLanguage textLanguage = detectLanguage(request); |
| 523 | int localeHypothesisCount = textLanguage.getLocaleHypothesisCount(); |
| 524 | List<String> languageTags = new ArrayList<>(); |
Tony Mak | 82fa8d9 | 2018-12-07 17:37:43 +0000 | [diff] [blame] | 525 | for (int i = 0; i < localeHypothesisCount; i++) { |
| 526 | ULocale locale = textLanguage.getLocale(i); |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 527 | if (textLanguage.getConfidenceScore(locale) < threshold) { |
Tony Mak | 82fa8d9 | 2018-12-07 17:37:43 +0000 | [diff] [blame] | 528 | break; |
| 529 | } |
| 530 | languageTags.add(locale.toLanguageTag()); |
| 531 | } |
| 532 | if (languageTags.isEmpty()) { |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 533 | return null; |
Tony Mak | 82fa8d9 | 2018-12-07 17:37:43 +0000 | [diff] [blame] | 534 | } |
| 535 | return String.join(",", languageTags); |
| 536 | } |
| 537 | |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 538 | private Collection<String> resolveActionTypesFromRequest(ConversationActions.Request request) { |
| 539 | List<String> defaultActionTypes = |
Tony Mak | ae85aae | 2019-01-09 15:59:56 +0000 | [diff] [blame] | 540 | request.getHints().contains(ConversationActions.Request.HINT_FOR_NOTIFICATION) |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 541 | ? mSettings.getNotificationConversationActionTypes() |
| 542 | : mSettings.getInAppConversationActionTypes(); |
Tony Mak | ae85aae | 2019-01-09 15:59:56 +0000 | [diff] [blame] | 543 | return request.getTypeConfig().resolveEntityListModifications(defaultActionTypes); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 544 | } |
| 545 | |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 546 | private AnnotatorModel getAnnotatorImpl(LocaleList localeList) |
Lukas Zilka | f8c36bf | 2018-02-07 20:30:08 +0100 | [diff] [blame] | 547 | throws FileNotFoundException { |
Abodunrinwa Toki | d32906c | 2018-01-18 04:34:44 -0800 | [diff] [blame] | 548 | synchronized (mLock) { |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 549 | localeList = localeList == null ? LocaleList.getDefault() : localeList; |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 550 | final ModelFileManager.ModelFile bestModel = |
| 551 | mAnnotatorModelFileManager.findBestModelFile(localeList); |
Jan Althaus | ef0156d | 2018-01-29 19:28:41 +0100 | [diff] [blame] | 552 | if (bestModel == null) { |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 553 | throw new FileNotFoundException( |
| 554 | "No annotator model for " + localeList.toLanguageTags()); |
Abodunrinwa Toki | 146d0d4 | 2017-04-25 01:39:19 +0100 | [diff] [blame] | 555 | } |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 556 | if (mAnnotatorImpl == null || !Objects.equals(mAnnotatorModelInUse, bestModel)) { |
Jan Althaus | ef0156d | 2018-01-29 19:28:41 +0100 | [diff] [blame] | 557 | Log.d(DEFAULT_LOG_TAG, "Loading " + bestModel); |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 558 | final ParcelFileDescriptor pfd = ParcelFileDescriptor.open( |
Jan Althaus | ef0156d | 2018-01-29 19:28:41 +0100 | [diff] [blame] | 559 | new File(bestModel.getPath()), ParcelFileDescriptor.MODE_READ_ONLY); |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 560 | try { |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 561 | if (pfd != null) { |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 562 | // The current annotator model may be still used by another thread / model. |
| 563 | // Do not call close() here, and let the GC to clean it up when no one else |
| 564 | // is using it. |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 565 | mAnnotatorImpl = new AnnotatorModel(pfd.getFd()); |
| 566 | mAnnotatorModelInUse = bestModel; |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 567 | } |
| 568 | } finally { |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 569 | maybeCloseAndLogError(pfd); |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 570 | } |
Abodunrinwa Toki | b89cf02 | 2017-02-06 19:53:22 +0000 | [diff] [blame] | 571 | } |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 572 | return mAnnotatorImpl; |
| 573 | } |
| 574 | } |
| 575 | |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 576 | private LangIdModel getLangIdImpl() throws FileNotFoundException { |
| 577 | synchronized (mLock) { |
Tony Mak | 6fc4318 | 2019-03-07 17:30:33 +0000 | [diff] [blame] | 578 | final ModelFileManager.ModelFile bestModel = |
| 579 | mLangIdModelFileManager.findBestModelFile(null); |
| 580 | if (bestModel == null) { |
| 581 | throw new FileNotFoundException("No LangID model is found"); |
| 582 | } |
| 583 | if (mLangIdImpl == null || !Objects.equals(mLangIdModelInUse, bestModel)) { |
| 584 | Log.d(DEFAULT_LOG_TAG, "Loading " + bestModel); |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 585 | final ParcelFileDescriptor pfd = ParcelFileDescriptor.open( |
| 586 | new File(bestModel.getPath()), ParcelFileDescriptor.MODE_READ_ONLY); |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 587 | try { |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 588 | if (pfd != null) { |
| 589 | mLangIdImpl = new LangIdModel(pfd.getFd()); |
Tony Mak | 6fc4318 | 2019-03-07 17:30:33 +0000 | [diff] [blame] | 590 | mLangIdModelInUse = bestModel; |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 591 | } |
| 592 | } finally { |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 593 | maybeCloseAndLogError(pfd); |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 594 | } |
| 595 | } |
| 596 | return mLangIdImpl; |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 597 | } |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 598 | } |
| 599 | |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 600 | @Nullable |
| 601 | private ActionsSuggestionsModel getActionsImpl() throws FileNotFoundException { |
| 602 | synchronized (mLock) { |
Tony Mak | 6fc4318 | 2019-03-07 17:30:33 +0000 | [diff] [blame] | 603 | // TODO: Use LangID to determine the locale we should use here? |
| 604 | final ModelFileManager.ModelFile bestModel = |
| 605 | mActionsModelFileManager.findBestModelFile(LocaleList.getDefault()); |
| 606 | if (bestModel == null) { |
| 607 | return null; |
| 608 | } |
| 609 | if (mActionsImpl == null || !Objects.equals(mActionModelInUse, bestModel)) { |
| 610 | Log.d(DEFAULT_LOG_TAG, "Loading " + bestModel); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 611 | final ParcelFileDescriptor pfd = ParcelFileDescriptor.open( |
| 612 | new File(bestModel.getPath()), ParcelFileDescriptor.MODE_READ_ONLY); |
| 613 | try { |
Tony Mak | 20fe187 | 2019-03-22 15:35:15 +0000 | [diff] [blame] | 614 | if (pfd == null) { |
| 615 | Log.d(LOG_TAG, "Failed to read the model file: " + bestModel.getPath()); |
| 616 | return null; |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 617 | } |
Tony Mak | 20fe187 | 2019-03-22 15:35:15 +0000 | [diff] [blame] | 618 | ActionsModelParams params = mActionsModelParamsSupplier.get(); |
| 619 | mActionsImpl = new ActionsSuggestionsModel( |
| 620 | pfd.getFd(), params.getSerializedPreconditions(bestModel)); |
| 621 | mActionModelInUse = bestModel; |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 622 | } finally { |
| 623 | maybeCloseAndLogError(pfd); |
| 624 | } |
| 625 | } |
| 626 | return mActionsImpl; |
| 627 | } |
| 628 | } |
| 629 | |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 630 | private String createId(String text, int start, int end) { |
Abodunrinwa Toki | d32906c | 2018-01-18 04:34:44 -0800 | [diff] [blame] | 631 | synchronized (mLock) { |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 632 | return SelectionSessionLogger.createId(text, start, end, mContext, |
| 633 | mAnnotatorModelInUse.getVersion(), |
| 634 | mAnnotatorModelInUse.getSupportedLocales()); |
Abodunrinwa Toki | 146d0d4 | 2017-04-25 01:39:19 +0100 | [diff] [blame] | 635 | } |
| 636 | } |
| 637 | |
Lukas Zilka | f8c36bf | 2018-02-07 20:30:08 +0100 | [diff] [blame] | 638 | private static String concatenateLocales(@Nullable LocaleList locales) { |
| 639 | return (locales == null) ? "" : locales.toLanguageTags(); |
| 640 | } |
| 641 | |
Abodunrinwa Toki | e0b5789 | 2017-04-28 19:59:57 +0100 | [diff] [blame] | 642 | private TextClassification createClassificationResult( |
Tony Mak | 64c4cb2 | 2018-09-25 13:38:28 +0100 | [diff] [blame] | 643 | AnnotatorModel.ClassificationResult[] classifications, |
Jan Althaus | a1652cf | 2018-03-29 17:51:57 +0200 | [diff] [blame] | 644 | String text, int start, int end, @Nullable Instant referenceTime) { |
Abodunrinwa Toki | 008f387 | 2017-11-27 19:32:35 +0000 | [diff] [blame] | 645 | final String classifiedText = text.substring(start, end); |
Abodunrinwa Toki | e0b5789 | 2017-04-28 19:59:57 +0100 | [diff] [blame] | 646 | final TextClassification.Builder builder = new TextClassification.Builder() |
Abodunrinwa Toki | 008f387 | 2017-11-27 19:32:35 +0000 | [diff] [blame] | 647 | .setText(classifiedText); |
Abodunrinwa Toki | 9b4c82a | 2017-02-06 20:29:36 +0000 | [diff] [blame] | 648 | |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 649 | final int typeCount = classifications.length; |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 650 | AnnotatorModel.ClassificationResult highestScoringResult = |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 651 | typeCount > 0 ? classifications[0] : null; |
| 652 | for (int i = 0; i < typeCount; i++) { |
Tony Mak | fdb3554 | 2019-03-22 12:01:50 +0000 | [diff] [blame] | 653 | builder.setEntityType(classifications[i]); |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 654 | if (classifications[i].getScore() > highestScoringResult.getScore()) { |
Jan Althaus | 705b9e9 | 2018-01-22 18:22:29 +0100 | [diff] [blame] | 655 | highestScoringResult = classifications[i]; |
Jan Althaus | 705b9e9 | 2018-01-22 18:22:29 +0100 | [diff] [blame] | 656 | } |
Abodunrinwa Toki | a6096f6 | 2017-03-08 17:21:40 +0000 | [diff] [blame] | 657 | } |
| 658 | |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 659 | final Pair<Bundle, Bundle> languagesBundles = generateLanguageBundles(text, start, end); |
| 660 | final Bundle textLanguagesBundle = languagesBundles.first; |
| 661 | final Bundle foreignLanguageBundle = languagesBundles.second; |
Abodunrinwa Toki | 520b2f8 | 2019-01-27 07:48:02 +0000 | [diff] [blame] | 662 | builder.setForeignLanguageExtra(foreignLanguageBundle); |
| 663 | |
Jan Althaus | 20d346e | 2018-03-23 14:03:52 +0100 | [diff] [blame] | 664 | boolean isPrimaryAction = true; |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 665 | final List<LabeledIntent> labeledIntents = mClassificationIntentFactory.create( |
Tony Mak | fc039c3 | 2019-01-17 19:32:08 +0000 | [diff] [blame] | 666 | mContext, |
| 667 | classifiedText, |
Abodunrinwa Toki | 520b2f8 | 2019-01-27 07:48:02 +0000 | [diff] [blame] | 668 | foreignLanguageBundle != null, |
Tony Mak | fc039c3 | 2019-01-17 19:32:08 +0000 | [diff] [blame] | 669 | referenceTime, |
| 670 | highestScoringResult); |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 671 | final LabeledIntent.TitleChooser titleChooser = |
Tony Mak | ac9b4d8 | 2019-02-15 13:57:38 +0000 | [diff] [blame] | 672 | (labeledIntent, resolveInfo) -> labeledIntent.titleWithoutEntity; |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 673 | |
Tony Mak | fc039c3 | 2019-01-17 19:32:08 +0000 | [diff] [blame] | 674 | for (LabeledIntent labeledIntent : labeledIntents) { |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 675 | final LabeledIntent.Result result = |
| 676 | labeledIntent.resolve(mContext, titleChooser, textLanguagesBundle); |
Tony Mak | ac9b4d8 | 2019-02-15 13:57:38 +0000 | [diff] [blame] | 677 | if (result == null) { |
Abodunrinwa Toki | 253827f | 2018-04-24 19:19:48 +0100 | [diff] [blame] | 678 | continue; |
| 679 | } |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 680 | |
| 681 | final Intent intent = result.resolvedIntent; |
Tony Mak | ac9b4d8 | 2019-02-15 13:57:38 +0000 | [diff] [blame] | 682 | final RemoteAction action = result.remoteAction; |
Jan Althaus | 20d346e | 2018-03-23 14:03:52 +0100 | [diff] [blame] | 683 | if (isPrimaryAction) { |
| 684 | // For O backwards compatibility, the first RemoteAction is also written to the |
| 685 | // legacy API fields. |
| 686 | builder.setIcon(action.getIcon().loadDrawable(mContext)); |
| 687 | builder.setLabel(action.getTitle().toString()); |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 688 | builder.setIntent(intent); |
Jan Althaus | 20d346e | 2018-03-23 14:03:52 +0100 | [diff] [blame] | 689 | builder.setOnClickListener(TextClassification.createIntentOnClickListener( |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 690 | TextClassification.createPendingIntent( |
| 691 | mContext, intent, labeledIntent.requestCode))); |
Jan Althaus | 20d346e | 2018-03-23 14:03:52 +0100 | [diff] [blame] | 692 | isPrimaryAction = false; |
| 693 | } |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 694 | builder.addAction(action, intent); |
Jan Althaus | 20d346e | 2018-03-23 14:03:52 +0100 | [diff] [blame] | 695 | } |
Abodunrinwa Toki | 520b2f8 | 2019-01-27 07:48:02 +0000 | [diff] [blame] | 696 | return builder.setId(createId(text, start, end)).build(); |
Jan Althaus | 92d7683 | 2017-09-27 18:14:35 +0200 | [diff] [blame] | 697 | } |
| 698 | |
Abodunrinwa Toki | 520b2f8 | 2019-01-27 07:48:02 +0000 | [diff] [blame] | 699 | /** |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 700 | * Returns a bundle pair with language detection information for extras. |
| 701 | * <p> |
| 702 | * Pair.first = textLanguagesBundle - A bundle containing information about all detected |
| 703 | * languages in the text. May be null if language detection fails or is disabled. This is |
| 704 | * typically expected to be added to a textClassifier generated remote action intent. |
| 705 | * See {@link ExtrasUtils#putTextLanguagesExtra(Bundle, Bundle)}. |
| 706 | * See {@link ExtrasUtils#getTopLanguage(Intent)}. |
| 707 | * <p> |
| 708 | * Pair.second = foreignLanguageBundle - A bundle with the language and confidence score if the |
| 709 | * system finds the text to be in a foreign language. Otherwise is null. |
| 710 | * See {@link TextClassification.Builder#setForeignLanguageExtra(Bundle)}. |
| 711 | * |
| 712 | * @param context the context of the text to detect languages for |
| 713 | * @param start the start index of the text |
| 714 | * @param end the end index of the text |
Abodunrinwa Toki | 520b2f8 | 2019-01-27 07:48:02 +0000 | [diff] [blame] | 715 | */ |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 716 | // TODO: Revisit this algorithm. |
| 717 | // TODO: Consider making this public API. |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 718 | private Pair<Bundle, Bundle> generateLanguageBundles(String context, int start, int end) { |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 719 | if (!mSettings.isTranslateInClassificationEnabled()) { |
| 720 | return null; |
| 721 | } |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 722 | try { |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 723 | final float threshold = getLangIdThreshold(); |
| 724 | if (threshold < 0 || threshold > 1) { |
| 725 | Log.w(LOG_TAG, |
| 726 | "[detectForeignLanguage] unexpected threshold is found: " + threshold); |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 727 | return Pair.create(null, null); |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 728 | } |
| 729 | |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 730 | final EntityConfidence languageScores = detectLanguages(context, start, end); |
| 731 | if (languageScores.getEntities().isEmpty()) { |
| 732 | return Pair.create(null, null); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 733 | } |
| 734 | |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 735 | final Bundle textLanguagesBundle = new Bundle(); |
| 736 | ExtrasUtils.putTopLanguageScores(textLanguagesBundle, languageScores); |
| 737 | |
| 738 | final String language = languageScores.getEntities().get(0); |
| 739 | final float score = languageScores.getConfidenceScore(language); |
| 740 | if (score < threshold) { |
| 741 | return Pair.create(textLanguagesBundle, null); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 742 | } |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 743 | |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 744 | Log.v(LOG_TAG, String.format( |
| 745 | Locale.US, "Language detected: <%s:%.2f>", language, score)); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 746 | |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 747 | final Locale detected = new Locale(language); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 748 | final LocaleList deviceLocales = LocaleList.getDefault(); |
| 749 | final int size = deviceLocales.size(); |
| 750 | for (int i = 0; i < size; i++) { |
| 751 | if (deviceLocales.get(i).getLanguage().equals(detected.getLanguage())) { |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 752 | return Pair.create(textLanguagesBundle, null); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 753 | } |
| 754 | } |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 755 | final Bundle foreignLanguageBundle = ExtrasUtils.createForeignLanguageExtra( |
| 756 | detected.getLanguage(), score, getLangIdImpl().getVersion()); |
| 757 | return Pair.create(textLanguagesBundle, foreignLanguageBundle); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 758 | } catch (Throwable t) { |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 759 | Log.e(LOG_TAG, "Error generating language bundles.", t); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 760 | } |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 761 | return Pair.create(null, null); |
| 762 | } |
| 763 | |
| 764 | /** |
| 765 | * Detect the language of a piece of text by taking surrounding text into consideration. |
| 766 | * |
| 767 | * @param text text providing context for the text for which its language is to be detected |
| 768 | * @param start the start index of the text to detect its language |
| 769 | * @param end the end index of the text to detect its language |
| 770 | */ |
| 771 | // TODO: Revisit this algorithm. |
| 772 | private EntityConfidence detectLanguages(String text, int start, int end) |
| 773 | throws FileNotFoundException { |
| 774 | Preconditions.checkArgument(start >= 0); |
| 775 | Preconditions.checkArgument(end <= text.length()); |
| 776 | Preconditions.checkArgument(start <= end); |
| 777 | |
| 778 | final float[] langIdContextSettings = mSettings.getLangIdContextSettings(); |
| 779 | // The minimum size of text to prefer for detection. |
| 780 | final int minimumTextSize = (int) langIdContextSettings[0]; |
| 781 | // For reducing the score when text is less than the preferred size. |
| 782 | final float penalizeRatio = langIdContextSettings[1]; |
| 783 | // Original detection score to surrounding text detection score ratios. |
| 784 | final float subjectTextScoreRatio = langIdContextSettings[2]; |
| 785 | final float moreTextScoreRatio = 1f - subjectTextScoreRatio; |
| 786 | Log.v(LOG_TAG, |
| 787 | String.format(Locale.US, "LangIdContextSettings: " |
Abodunrinwa Toki | 0634af3 | 2019-04-04 13:10:59 +0100 | [diff] [blame] | 788 | + "minimumTextSize=%d, penalizeRatio=%.2f, " |
| 789 | + "subjectTextScoreRatio=%.2f, moreTextScoreRatio=%.2f", |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 790 | minimumTextSize, penalizeRatio, subjectTextScoreRatio, moreTextScoreRatio)); |
| 791 | |
| 792 | if (end - start < minimumTextSize && penalizeRatio <= 0) { |
| 793 | return new EntityConfidence(Collections.emptyMap()); |
| 794 | } |
| 795 | |
| 796 | final String subject = text.substring(start, end); |
| 797 | final EntityConfidence scores = detectLanguages(subject); |
| 798 | |
| 799 | if (subject.length() >= minimumTextSize |
| 800 | || subject.length() == text.length() |
| 801 | || subjectTextScoreRatio * penalizeRatio >= 1) { |
| 802 | return scores; |
| 803 | } |
| 804 | |
| 805 | final EntityConfidence moreTextScores; |
| 806 | if (moreTextScoreRatio >= 0) { |
| 807 | // Attempt to grow the detection text to be at least minimumTextSize long. |
| 808 | final String moreText = Utils.getSubString(text, start, end, minimumTextSize); |
| 809 | moreTextScores = detectLanguages(moreText); |
| 810 | } else { |
| 811 | moreTextScores = new EntityConfidence(Collections.emptyMap()); |
| 812 | } |
| 813 | |
| 814 | // Combine the original detection scores with the those returned after including more text. |
| 815 | final Map<String, Float> newScores = new ArrayMap<>(); |
| 816 | final Set<String> languages = new ArraySet<>(); |
| 817 | languages.addAll(scores.getEntities()); |
| 818 | languages.addAll(moreTextScores.getEntities()); |
| 819 | for (String language : languages) { |
| 820 | final float score = (subjectTextScoreRatio * scores.getConfidenceScore(language) |
| 821 | + moreTextScoreRatio * moreTextScores.getConfidenceScore(language)) |
| 822 | * penalizeRatio; |
| 823 | newScores.put(language, score); |
| 824 | } |
| 825 | return new EntityConfidence(newScores); |
| 826 | } |
| 827 | |
| 828 | /** |
| 829 | * Detect languages for the specified text. |
| 830 | */ |
| 831 | private EntityConfidence detectLanguages(String text) throws FileNotFoundException { |
| 832 | final LangIdModel langId = getLangIdImpl(); |
| 833 | final LangIdModel.LanguageResult[] langResults = langId.detectLanguages(text); |
| 834 | final Map<String, Float> languagesMap = new ArrayMap<>(); |
| 835 | for (LanguageResult langResult : langResults) { |
| 836 | languagesMap.put(langResult.getLanguage(), langResult.getScore()); |
| 837 | } |
| 838 | return new EntityConfidence(languagesMap); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 839 | } |
| 840 | |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 841 | private float getLangIdThreshold() { |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 842 | try { |
| 843 | return mSettings.getLangIdThresholdOverride() >= 0 |
| 844 | ? mSettings.getLangIdThresholdOverride() |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 845 | : getLangIdImpl().getLangIdThreshold(); |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 846 | } catch (FileNotFoundException e) { |
| 847 | final float defaultThreshold = 0.5f; |
| 848 | Log.v(LOG_TAG, "Using default foreign language threshold: " + defaultThreshold); |
| 849 | return defaultThreshold; |
| 850 | } |
| 851 | } |
| 852 | |
Tony Mak | f93e9e5 | 2018-07-16 14:46:29 +0200 | [diff] [blame] | 853 | @Override |
| 854 | public void dump(@NonNull IndentingPrintWriter printWriter) { |
| 855 | synchronized (mLock) { |
Tony Mak | f93e9e5 | 2018-07-16 14:46:29 +0200 | [diff] [blame] | 856 | printWriter.println("TextClassifierImpl:"); |
| 857 | printWriter.increaseIndent(); |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 858 | printWriter.println("Annotator model file(s):"); |
Tony Mak | f93e9e5 | 2018-07-16 14:46:29 +0200 | [diff] [blame] | 859 | printWriter.increaseIndent(); |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 860 | for (ModelFileManager.ModelFile modelFile : |
| 861 | mAnnotatorModelFileManager.listModelFiles()) { |
| 862 | printWriter.println(modelFile.toString()); |
| 863 | } |
| 864 | printWriter.decreaseIndent(); |
| 865 | printWriter.println("LangID model file(s):"); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 866 | printWriter.increaseIndent(); |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 867 | for (ModelFileManager.ModelFile modelFile : |
| 868 | mLangIdModelFileManager.listModelFiles()) { |
Tony Mak | f93e9e5 | 2018-07-16 14:46:29 +0200 | [diff] [blame] | 869 | printWriter.println(modelFile.toString()); |
| 870 | } |
| 871 | printWriter.decreaseIndent(); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 872 | printWriter.println("Actions model file(s):"); |
| 873 | printWriter.increaseIndent(); |
| 874 | for (ModelFileManager.ModelFile modelFile : |
| 875 | mActionsModelFileManager.listModelFiles()) { |
| 876 | printWriter.println(modelFile.toString()); |
| 877 | } |
| 878 | printWriter.decreaseIndent(); |
Tony Mak | f93e9e5 | 2018-07-16 14:46:29 +0200 | [diff] [blame] | 879 | printWriter.printPair("mFallback", mFallback); |
| 880 | printWriter.decreaseIndent(); |
| 881 | printWriter.println(); |
| 882 | } |
| 883 | } |
| 884 | |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 885 | /** |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 886 | * Closes the ParcelFileDescriptor, if non-null, and logs any errors that occur. |
Abodunrinwa Toki | 146d0d4 | 2017-04-25 01:39:19 +0100 | [diff] [blame] | 887 | */ |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 888 | private static void maybeCloseAndLogError(@Nullable ParcelFileDescriptor fd) { |
| 889 | if (fd == null) { |
| 890 | return; |
| 891 | } |
| 892 | |
Abodunrinwa Toki | 146d0d4 | 2017-04-25 01:39:19 +0100 | [diff] [blame] | 893 | try { |
| 894 | fd.close(); |
| 895 | } catch (IOException e) { |
| 896 | Log.e(LOG_TAG, "Error closing file.", e); |
| 897 | } |
| 898 | } |
| 899 | |
| 900 | /** |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 901 | * Returns the locales string for the current resources configuration. |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 902 | */ |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 903 | private String getResourceLocalesString() { |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 904 | try { |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 905 | return mContext.getResources().getConfiguration().getLocales().toLanguageTags(); |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 906 | } catch (NullPointerException e) { |
| 907 | // NPE is unexpected. Erring on the side of caution. |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 908 | return LocaleList.getDefault().toLanguageTags(); |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 909 | } |
| 910 | } |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 911 | } |