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) { |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 133 | mContext = Preconditions.checkNotNull(context); |
Abodunrinwa Toki | 253827f | 2018-04-24 19:19:48 +0100 | [diff] [blame] | 134 | mFallback = Preconditions.checkNotNull(fallback); |
Abodunrinwa Toki | db8fc31 | 2018-02-26 21:37:51 +0000 | [diff] [blame] | 135 | mSettings = Preconditions.checkNotNull(settings); |
| 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) { |
| 183 | Preconditions.checkNotNull(request); |
| 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) { |
| 248 | Preconditions.checkNotNull(request); |
| 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) { |
| 288 | Preconditions.checkNotNull(request); |
| 289 | Utils.checkTextLength(request.getText(), getMaxGenerateLinksTextLength()); |
| 290 | Utils.checkMainThread(); |
Abodunrinwa Toki | 6563833 | 2018-03-16 21:08:50 +0000 | [diff] [blame] | 291 | |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 292 | if (!mSettings.isSmartLinkifyEnabled() && request.isLegacyFallback()) { |
| 293 | return Utils.generateLegacyLinks(request); |
Abodunrinwa Toki | 6563833 | 2018-03-16 21:08:50 +0000 | [diff] [blame] | 294 | } |
| 295 | |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 296 | final String textString = request.getText().toString(); |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 297 | final TextLinks.Builder builder = new TextLinks.Builder(textString); |
Richard Ledley | 9cfa606 | 2018-01-15 13:13:29 +0000 | [diff] [blame] | 298 | |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 299 | try { |
Jan Althaus | 31efdc3 | 2018-02-19 22:23:13 +0100 | [diff] [blame] | 300 | final long startTimeMs = System.currentTimeMillis(); |
Jan Althaus | a1652cf | 2018-03-29 17:51:57 +0200 | [diff] [blame] | 301 | final ZonedDateTime refTime = ZonedDateTime.now(); |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 302 | final Collection<String> entitiesToIdentify = request.getEntityConfig() != null |
| 303 | ? request.getEntityConfig().resolveEntityListModifications( |
Abodunrinwa Toki | 0634af3 | 2019-04-04 13:10:59 +0100 | [diff] [blame^] | 304 | getEntitiesForHints(request.getEntityConfig().getHints())) |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 305 | : mSettings.getEntityListDefault(); |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 306 | final String localesString = concatenateLocales(request.getDefaultLocales()); |
| 307 | final String detectLanguageTags = detectLanguageTagsFromText(request.getText()); |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 308 | final AnnotatorModel annotatorImpl = |
| 309 | getAnnotatorImpl(request.getDefaultLocales()); |
Tony Mak | b6afd3c | 2019-04-05 15:45:18 +0100 | [diff] [blame] | 310 | final boolean isSerializedEntityDataEnabled = |
| 311 | ExtrasUtils.isSerializedEntityDataEnabled(request); |
Tony Mak | 64c4cb2 | 2018-09-25 13:38:28 +0100 | [diff] [blame] | 312 | final AnnotatorModel.AnnotatedSpan[] annotations = |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 313 | annotatorImpl.annotate( |
Tony Mak | f99ee17 | 2018-11-23 12:14:39 +0000 | [diff] [blame] | 314 | textString, |
| 315 | new AnnotatorModel.AnnotationOptions( |
| 316 | refTime.toInstant().toEpochMilli(), |
| 317 | refTime.getZone().getId(), |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 318 | localesString, |
Tony Mak | b6afd3c | 2019-04-05 15:45:18 +0100 | [diff] [blame] | 319 | detectLanguageTags, |
| 320 | entitiesToIdentify, |
| 321 | AnnotatorModel.AnnotationUsecase.SMART.getValue(), |
| 322 | isSerializedEntityDataEnabled)); |
Tony Mak | 64c4cb2 | 2018-09-25 13:38:28 +0100 | [diff] [blame] | 323 | for (AnnotatorModel.AnnotatedSpan span : annotations) { |
| 324 | final AnnotatorModel.ClassificationResult[] results = |
Lukas Zilka | f8c36bf | 2018-02-07 20:30:08 +0100 | [diff] [blame] | 325 | span.getClassification(); |
| 326 | if (results.length == 0 |
| 327 | || !entitiesToIdentify.contains(results[0].getCollection())) { |
Richard Ledley | db18a57 | 2017-11-30 17:33:51 +0000 | [diff] [blame] | 328 | continue; |
| 329 | } |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 330 | final Map<String, Float> entityScores = new ArrayMap<>(); |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 331 | for (int i = 0; i < results.length; i++) { |
Lukas Zilka | f8c36bf | 2018-02-07 20:30:08 +0100 | [diff] [blame] | 332 | entityScores.put(results[i].getCollection(), results[i].getScore()); |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 333 | } |
Tony Mak | b6afd3c | 2019-04-05 15:45:18 +0100 | [diff] [blame] | 334 | Bundle extras = new Bundle(); |
| 335 | if (isSerializedEntityDataEnabled) { |
| 336 | ExtrasUtils.putEntities(extras, results); |
| 337 | } |
| 338 | builder.addLink(span.getStartIndex(), span.getEndIndex(), entityScores, extras); |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 339 | } |
Jan Althaus | 31efdc3 | 2018-02-19 22:23:13 +0100 | [diff] [blame] | 340 | final TextLinks links = builder.build(); |
| 341 | final long endTimeMs = System.currentTimeMillis(); |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 342 | final String callingPackageName = request.getCallingPackageName() == null |
| 343 | ? mContext.getPackageName() // local (in process) TC. |
| 344 | : request.getCallingPackageName(); |
Jan Althaus | 31efdc3 | 2018-02-19 22:23:13 +0100 | [diff] [blame] | 345 | mGenerateLinksLogger.logGenerateLinks( |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 346 | request.getText(), links, callingPackageName, endTimeMs - startTimeMs); |
Jan Althaus | 31efdc3 | 2018-02-19 22:23:13 +0100 | [diff] [blame] | 347 | return links; |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 348 | } catch (Throwable t) { |
| 349 | // Avoid throwing from this method. Log the error. |
| 350 | Log.e(LOG_TAG, "Error getting links info.", t); |
| 351 | } |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 352 | return mFallback.generateLinks(request); |
Richard Ledley | 68d9452 | 2017-10-05 10:52:19 +0100 | [diff] [blame] | 353 | } |
| 354 | |
Jan Althaus | 108aad3 | 2018-01-30 15:26:55 +0100 | [diff] [blame] | 355 | /** @inheritDoc */ |
| 356 | @Override |
| 357 | public int getMaxGenerateLinksTextLength() { |
Abodunrinwa Toki | db8fc31 | 2018-02-26 21:37:51 +0000 | [diff] [blame] | 358 | return mSettings.getGenerateLinksMaxTextLength(); |
Jan Althaus | 108aad3 | 2018-01-30 15:26:55 +0100 | [diff] [blame] | 359 | } |
| 360 | |
Richard Ledley | 1fc998b | 2018-02-16 15:45:06 +0000 | [diff] [blame] | 361 | private Collection<String> getEntitiesForHints(Collection<String> hints) { |
Jan Althaus | 0aacdb6 | 2018-02-19 11:44:37 +0100 | [diff] [blame] | 362 | final boolean editable = hints.contains(HINT_TEXT_IS_EDITABLE); |
| 363 | final boolean notEditable = hints.contains(HINT_TEXT_IS_NOT_EDITABLE); |
| 364 | |
| 365 | // Use the default if there is no hint, or conflicting ones. |
| 366 | final boolean useDefault = editable == notEditable; |
| 367 | if (useDefault) { |
Abodunrinwa Toki | db8fc31 | 2018-02-26 21:37:51 +0000 | [diff] [blame] | 368 | return mSettings.getEntityListDefault(); |
Jan Althaus | 0aacdb6 | 2018-02-19 11:44:37 +0100 | [diff] [blame] | 369 | } else if (editable) { |
Abodunrinwa Toki | db8fc31 | 2018-02-26 21:37:51 +0000 | [diff] [blame] | 370 | return mSettings.getEntityListEditable(); |
Jan Althaus | 0aacdb6 | 2018-02-19 11:44:37 +0100 | [diff] [blame] | 371 | } else { // notEditable |
Abodunrinwa Toki | db8fc31 | 2018-02-26 21:37:51 +0000 | [diff] [blame] | 372 | return mSettings.getEntityListNotEditable(); |
Jan Althaus | 0aacdb6 | 2018-02-19 11:44:37 +0100 | [diff] [blame] | 373 | } |
Richard Ledley | db18a57 | 2017-11-30 17:33:51 +0000 | [diff] [blame] | 374 | } |
| 375 | |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 376 | /** @inheritDoc */ |
Abodunrinwa Toki | 88be5a6 | 2018-03-23 04:01:28 +0000 | [diff] [blame] | 377 | @Override |
| 378 | public void onSelectionEvent(SelectionEvent event) { |
| 379 | Preconditions.checkNotNull(event); |
Tony Mak | 5a5f0d5 | 2019-01-08 11:07:23 +0000 | [diff] [blame] | 380 | mSessionLogger.writeEvent(event); |
Abodunrinwa Toki | 88be5a6 | 2018-03-23 04:01:28 +0000 | [diff] [blame] | 381 | } |
| 382 | |
Abodunrinwa Toki | 37ccedc | 2018-12-11 00:35:11 +0000 | [diff] [blame] | 383 | @Override |
Tony Mak | e94e078 | 2018-12-14 11:57:54 +0800 | [diff] [blame] | 384 | public void onTextClassifierEvent(TextClassifierEvent event) { |
| 385 | if (DEBUG) { |
| 386 | Log.d(DEFAULT_LOG_TAG, "onTextClassifierEvent() called with: event = [" + event + "]"); |
| 387 | } |
Abodunrinwa Toki | 520b2f8 | 2019-01-27 07:48:02 +0000 | [diff] [blame] | 388 | try { |
| 389 | mTextClassifierEventTronLogger.writeEvent(event); |
| 390 | } catch (Exception e) { |
| 391 | Log.e(LOG_TAG, "Error writing event", e); |
| 392 | } |
Abodunrinwa Toki | 37ccedc | 2018-12-11 00:35:11 +0000 | [diff] [blame] | 393 | } |
| 394 | |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 395 | /** @inheritDoc */ |
| 396 | @Override |
| 397 | public TextLanguage detectLanguage(@NonNull TextLanguage.Request request) { |
| 398 | Preconditions.checkNotNull(request); |
| 399 | Utils.checkMainThread(); |
| 400 | try { |
| 401 | final TextLanguage.Builder builder = new TextLanguage.Builder(); |
| 402 | final LangIdModel.LanguageResult[] langResults = |
| 403 | getLangIdImpl().detectLanguages(request.getText().toString()); |
| 404 | for (int i = 0; i < langResults.length; i++) { |
| 405 | builder.putLocale( |
| 406 | ULocale.forLanguageTag(langResults[i].getLanguage()), |
| 407 | langResults[i].getScore()); |
| 408 | } |
| 409 | return builder.build(); |
| 410 | } catch (Throwable t) { |
| 411 | // Avoid throwing from this method. Log the error. |
| 412 | Log.e(LOG_TAG, "Error detecting text language.", t); |
| 413 | } |
| 414 | return mFallback.detectLanguage(request); |
| 415 | } |
| 416 | |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 417 | @Override |
| 418 | public ConversationActions suggestConversationActions(ConversationActions.Request request) { |
| 419 | Preconditions.checkNotNull(request); |
| 420 | Utils.checkMainThread(); |
| 421 | try { |
| 422 | ActionsSuggestionsModel actionsImpl = getActionsImpl(); |
| 423 | if (actionsImpl == null) { |
| 424 | // Actions model is optional, fallback if it is not available. |
| 425 | return mFallback.suggestConversationActions(request); |
| 426 | } |
Tony Mak | f99ee17 | 2018-11-23 12:14:39 +0000 | [diff] [blame] | 427 | ActionsSuggestionsModel.ConversationMessage[] nativeMessages = |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 428 | ActionsSuggestionsHelper.toNativeMessages( |
| 429 | request.getConversation(), this::detectLanguageTagsFromText); |
Tony Mak | f99ee17 | 2018-11-23 12:14:39 +0000 | [diff] [blame] | 430 | if (nativeMessages.length == 0) { |
| 431 | return mFallback.suggestConversationActions(request); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 432 | } |
| 433 | ActionsSuggestionsModel.Conversation nativeConversation = |
Tony Mak | f99ee17 | 2018-11-23 12:14:39 +0000 | [diff] [blame] | 434 | new ActionsSuggestionsModel.Conversation(nativeMessages); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 435 | |
| 436 | ActionsSuggestionsModel.ActionSuggestion[] nativeSuggestions = |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 437 | actionsImpl.suggestActionsWithIntents( |
| 438 | nativeConversation, |
| 439 | null, |
| 440 | mContext, |
Tony Mak | 2a3adb7 | 2019-03-20 17:55:53 +0000 | [diff] [blame] | 441 | getResourceLocalesString(), |
| 442 | getAnnotatorImpl(LocaleList.getDefault())); |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 443 | return createConversationActionResult(request, nativeSuggestions); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 444 | } catch (Throwable t) { |
| 445 | // Avoid throwing from this method. Log the error. |
| 446 | Log.e(LOG_TAG, "Error suggesting conversation actions.", t); |
| 447 | } |
| 448 | return mFallback.suggestConversationActions(request); |
| 449 | } |
| 450 | |
Tony Mak | c12035e | 2019-02-26 17:45:34 +0000 | [diff] [blame] | 451 | /** |
| 452 | * Returns the {@link ConversationAction} result, with a non-null extras. |
| 453 | * <p> |
| 454 | * Whenever the RemoteAction is non-null, you can expect its corresponding intent |
| 455 | * with a non-null component name is in the extras. |
| 456 | */ |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 457 | private ConversationActions createConversationActionResult( |
| 458 | ConversationActions.Request request, |
| 459 | ActionsSuggestionsModel.ActionSuggestion[] nativeSuggestions) { |
| 460 | Collection<String> expectedTypes = resolveActionTypesFromRequest(request); |
| 461 | List<ConversationAction> conversationActions = new ArrayList<>(); |
| 462 | for (ActionsSuggestionsModel.ActionSuggestion nativeSuggestion : nativeSuggestions) { |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 463 | String actionType = nativeSuggestion.getActionType(); |
| 464 | if (!expectedTypes.contains(actionType)) { |
| 465 | continue; |
| 466 | } |
Tony Mak | 8ab9b18 | 2019-03-01 16:44:17 +0000 | [diff] [blame] | 467 | LabeledIntent.Result labeledIntentResult = |
| 468 | ActionsSuggestionsHelper.createLabeledIntentResult( |
| 469 | mContext, |
| 470 | mTemplateIntentFactory, |
| 471 | nativeSuggestion); |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 472 | RemoteAction remoteAction = null; |
Tony Mak | 8ab9b18 | 2019-03-01 16:44:17 +0000 | [diff] [blame] | 473 | Bundle extras = new Bundle(); |
| 474 | if (labeledIntentResult != null) { |
| 475 | remoteAction = labeledIntentResult.remoteAction; |
| 476 | ExtrasUtils.putActionIntent(extras, labeledIntentResult.resolvedIntent); |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 477 | } |
Tony Mak | fdb3554 | 2019-03-22 12:01:50 +0000 | [diff] [blame] | 478 | ExtrasUtils.putSerializedEntityData(extras, nativeSuggestion.getSerializedEntityData()); |
Tony Mak | 0921442 | 2019-03-01 18:25:23 +0000 | [diff] [blame] | 479 | ExtrasUtils.putEntitiesExtras( |
| 480 | extras, |
| 481 | TemplateIntentFactory.nameVariantsToBundle(nativeSuggestion.getEntityData())); |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 482 | conversationActions.add( |
| 483 | new ConversationAction.Builder(actionType) |
| 484 | .setConfidenceScore(nativeSuggestion.getScore()) |
| 485 | .setTextReply(nativeSuggestion.getResponseText()) |
| 486 | .setAction(remoteAction) |
Tony Mak | c12035e | 2019-02-26 17:45:34 +0000 | [diff] [blame] | 487 | .setExtras(extras) |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 488 | .build()); |
| 489 | } |
Tony Mak | c12035e | 2019-02-26 17:45:34 +0000 | [diff] [blame] | 490 | conversationActions = |
| 491 | ActionsSuggestionsHelper.removeActionsWithDuplicates(conversationActions); |
Tony Mak | aa496d0 | 2019-04-11 17:38:47 +0100 | [diff] [blame] | 492 | if (request.getMaxSuggestions() >= 0 |
| 493 | && conversationActions.size() > request.getMaxSuggestions()) { |
| 494 | conversationActions = conversationActions.subList(0, request.getMaxSuggestions()); |
| 495 | } |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 496 | String resultId = ActionsSuggestionsHelper.createResultId( |
| 497 | mContext, |
| 498 | request.getConversation(), |
| 499 | mActionModelInUse.getVersion(), |
| 500 | mActionModelInUse.getSupportedLocales()); |
| 501 | return new ConversationActions(conversationActions, resultId); |
| 502 | } |
| 503 | |
Tony Mak | 82fa8d9 | 2018-12-07 17:37:43 +0000 | [diff] [blame] | 504 | @Nullable |
| 505 | private String detectLanguageTagsFromText(CharSequence text) { |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 506 | if (!mSettings.isDetectLanguagesFromTextEnabled()) { |
| 507 | return null; |
| 508 | } |
| 509 | final float threshold = getLangIdThreshold(); |
| 510 | if (threshold < 0 || threshold > 1) { |
| 511 | Log.w(LOG_TAG, |
| 512 | "[detectLanguageTagsFromText] unexpected threshold is found: " + threshold); |
| 513 | return null; |
| 514 | } |
Tony Mak | 82fa8d9 | 2018-12-07 17:37:43 +0000 | [diff] [blame] | 515 | TextLanguage.Request request = new TextLanguage.Request.Builder(text).build(); |
| 516 | TextLanguage textLanguage = detectLanguage(request); |
| 517 | int localeHypothesisCount = textLanguage.getLocaleHypothesisCount(); |
| 518 | List<String> languageTags = new ArrayList<>(); |
Tony Mak | 82fa8d9 | 2018-12-07 17:37:43 +0000 | [diff] [blame] | 519 | for (int i = 0; i < localeHypothesisCount; i++) { |
| 520 | ULocale locale = textLanguage.getLocale(i); |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 521 | if (textLanguage.getConfidenceScore(locale) < threshold) { |
Tony Mak | 82fa8d9 | 2018-12-07 17:37:43 +0000 | [diff] [blame] | 522 | break; |
| 523 | } |
| 524 | languageTags.add(locale.toLanguageTag()); |
| 525 | } |
| 526 | if (languageTags.isEmpty()) { |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 527 | return null; |
Tony Mak | 82fa8d9 | 2018-12-07 17:37:43 +0000 | [diff] [blame] | 528 | } |
| 529 | return String.join(",", languageTags); |
| 530 | } |
| 531 | |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 532 | private Collection<String> resolveActionTypesFromRequest(ConversationActions.Request request) { |
| 533 | List<String> defaultActionTypes = |
Tony Mak | ae85aae | 2019-01-09 15:59:56 +0000 | [diff] [blame] | 534 | request.getHints().contains(ConversationActions.Request.HINT_FOR_NOTIFICATION) |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 535 | ? mSettings.getNotificationConversationActionTypes() |
| 536 | : mSettings.getInAppConversationActionTypes(); |
Tony Mak | ae85aae | 2019-01-09 15:59:56 +0000 | [diff] [blame] | 537 | return request.getTypeConfig().resolveEntityListModifications(defaultActionTypes); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 538 | } |
| 539 | |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 540 | private AnnotatorModel getAnnotatorImpl(LocaleList localeList) |
Lukas Zilka | f8c36bf | 2018-02-07 20:30:08 +0100 | [diff] [blame] | 541 | throws FileNotFoundException { |
Abodunrinwa Toki | d32906c | 2018-01-18 04:34:44 -0800 | [diff] [blame] | 542 | synchronized (mLock) { |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 543 | localeList = localeList == null ? LocaleList.getDefault() : localeList; |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 544 | final ModelFileManager.ModelFile bestModel = |
| 545 | mAnnotatorModelFileManager.findBestModelFile(localeList); |
Jan Althaus | ef0156d | 2018-01-29 19:28:41 +0100 | [diff] [blame] | 546 | if (bestModel == null) { |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 547 | throw new FileNotFoundException( |
| 548 | "No annotator model for " + localeList.toLanguageTags()); |
Abodunrinwa Toki | 146d0d4 | 2017-04-25 01:39:19 +0100 | [diff] [blame] | 549 | } |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 550 | if (mAnnotatorImpl == null || !Objects.equals(mAnnotatorModelInUse, bestModel)) { |
Jan Althaus | ef0156d | 2018-01-29 19:28:41 +0100 | [diff] [blame] | 551 | Log.d(DEFAULT_LOG_TAG, "Loading " + bestModel); |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 552 | final ParcelFileDescriptor pfd = ParcelFileDescriptor.open( |
Jan Althaus | ef0156d | 2018-01-29 19:28:41 +0100 | [diff] [blame] | 553 | new File(bestModel.getPath()), ParcelFileDescriptor.MODE_READ_ONLY); |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 554 | try { |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 555 | if (pfd != null) { |
Tony Mak | ae33c3b | 2019-01-31 14:29:19 +0000 | [diff] [blame] | 556 | // The current annotator model may be still used by another thread / model. |
| 557 | // Do not call close() here, and let the GC to clean it up when no one else |
| 558 | // is using it. |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 559 | mAnnotatorImpl = new AnnotatorModel(pfd.getFd()); |
| 560 | mAnnotatorModelInUse = bestModel; |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 561 | } |
| 562 | } finally { |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 563 | maybeCloseAndLogError(pfd); |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 564 | } |
Abodunrinwa Toki | b89cf02 | 2017-02-06 19:53:22 +0000 | [diff] [blame] | 565 | } |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 566 | return mAnnotatorImpl; |
| 567 | } |
| 568 | } |
| 569 | |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 570 | private LangIdModel getLangIdImpl() throws FileNotFoundException { |
| 571 | synchronized (mLock) { |
Tony Mak | 6fc4318 | 2019-03-07 17:30:33 +0000 | [diff] [blame] | 572 | final ModelFileManager.ModelFile bestModel = |
| 573 | mLangIdModelFileManager.findBestModelFile(null); |
| 574 | if (bestModel == null) { |
| 575 | throw new FileNotFoundException("No LangID model is found"); |
| 576 | } |
| 577 | if (mLangIdImpl == null || !Objects.equals(mLangIdModelInUse, bestModel)) { |
| 578 | Log.d(DEFAULT_LOG_TAG, "Loading " + bestModel); |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 579 | final ParcelFileDescriptor pfd = ParcelFileDescriptor.open( |
| 580 | new File(bestModel.getPath()), ParcelFileDescriptor.MODE_READ_ONLY); |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 581 | try { |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 582 | if (pfd != null) { |
| 583 | mLangIdImpl = new LangIdModel(pfd.getFd()); |
Tony Mak | 6fc4318 | 2019-03-07 17:30:33 +0000 | [diff] [blame] | 584 | mLangIdModelInUse = bestModel; |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 585 | } |
| 586 | } finally { |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 587 | maybeCloseAndLogError(pfd); |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 588 | } |
| 589 | } |
| 590 | return mLangIdImpl; |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 591 | } |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 592 | } |
| 593 | |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 594 | @Nullable |
| 595 | private ActionsSuggestionsModel getActionsImpl() throws FileNotFoundException { |
| 596 | synchronized (mLock) { |
Tony Mak | 6fc4318 | 2019-03-07 17:30:33 +0000 | [diff] [blame] | 597 | // TODO: Use LangID to determine the locale we should use here? |
| 598 | final ModelFileManager.ModelFile bestModel = |
| 599 | mActionsModelFileManager.findBestModelFile(LocaleList.getDefault()); |
| 600 | if (bestModel == null) { |
| 601 | return null; |
| 602 | } |
| 603 | if (mActionsImpl == null || !Objects.equals(mActionModelInUse, bestModel)) { |
| 604 | Log.d(DEFAULT_LOG_TAG, "Loading " + bestModel); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 605 | final ParcelFileDescriptor pfd = ParcelFileDescriptor.open( |
| 606 | new File(bestModel.getPath()), ParcelFileDescriptor.MODE_READ_ONLY); |
| 607 | try { |
Tony Mak | 20fe187 | 2019-03-22 15:35:15 +0000 | [diff] [blame] | 608 | if (pfd == null) { |
| 609 | Log.d(LOG_TAG, "Failed to read the model file: " + bestModel.getPath()); |
| 610 | return null; |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 611 | } |
Tony Mak | 20fe187 | 2019-03-22 15:35:15 +0000 | [diff] [blame] | 612 | ActionsModelParams params = mActionsModelParamsSupplier.get(); |
| 613 | mActionsImpl = new ActionsSuggestionsModel( |
| 614 | pfd.getFd(), params.getSerializedPreconditions(bestModel)); |
| 615 | mActionModelInUse = bestModel; |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 616 | } finally { |
| 617 | maybeCloseAndLogError(pfd); |
| 618 | } |
| 619 | } |
| 620 | return mActionsImpl; |
| 621 | } |
| 622 | } |
| 623 | |
Abodunrinwa Toki | 080c854 | 2018-03-27 00:04:06 +0100 | [diff] [blame] | 624 | private String createId(String text, int start, int end) { |
Abodunrinwa Toki | d32906c | 2018-01-18 04:34:44 -0800 | [diff] [blame] | 625 | synchronized (mLock) { |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 626 | return SelectionSessionLogger.createId(text, start, end, mContext, |
| 627 | mAnnotatorModelInUse.getVersion(), |
| 628 | mAnnotatorModelInUse.getSupportedLocales()); |
Abodunrinwa Toki | 146d0d4 | 2017-04-25 01:39:19 +0100 | [diff] [blame] | 629 | } |
| 630 | } |
| 631 | |
Lukas Zilka | f8c36bf | 2018-02-07 20:30:08 +0100 | [diff] [blame] | 632 | private static String concatenateLocales(@Nullable LocaleList locales) { |
| 633 | return (locales == null) ? "" : locales.toLanguageTags(); |
| 634 | } |
| 635 | |
Abodunrinwa Toki | e0b5789 | 2017-04-28 19:59:57 +0100 | [diff] [blame] | 636 | private TextClassification createClassificationResult( |
Tony Mak | 64c4cb2 | 2018-09-25 13:38:28 +0100 | [diff] [blame] | 637 | AnnotatorModel.ClassificationResult[] classifications, |
Jan Althaus | a1652cf | 2018-03-29 17:51:57 +0200 | [diff] [blame] | 638 | String text, int start, int end, @Nullable Instant referenceTime) { |
Abodunrinwa Toki | 008f387 | 2017-11-27 19:32:35 +0000 | [diff] [blame] | 639 | final String classifiedText = text.substring(start, end); |
Abodunrinwa Toki | e0b5789 | 2017-04-28 19:59:57 +0100 | [diff] [blame] | 640 | final TextClassification.Builder builder = new TextClassification.Builder() |
Abodunrinwa Toki | 008f387 | 2017-11-27 19:32:35 +0000 | [diff] [blame] | 641 | .setText(classifiedText); |
Abodunrinwa Toki | 9b4c82a | 2017-02-06 20:29:36 +0000 | [diff] [blame] | 642 | |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 643 | final int typeCount = classifications.length; |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 644 | AnnotatorModel.ClassificationResult highestScoringResult = |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 645 | typeCount > 0 ? classifications[0] : null; |
| 646 | for (int i = 0; i < typeCount; i++) { |
Tony Mak | fdb3554 | 2019-03-22 12:01:50 +0000 | [diff] [blame] | 647 | builder.setEntityType(classifications[i]); |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 648 | if (classifications[i].getScore() > highestScoringResult.getScore()) { |
Jan Althaus | 705b9e9 | 2018-01-22 18:22:29 +0100 | [diff] [blame] | 649 | highestScoringResult = classifications[i]; |
Jan Althaus | 705b9e9 | 2018-01-22 18:22:29 +0100 | [diff] [blame] | 650 | } |
Abodunrinwa Toki | a6096f6 | 2017-03-08 17:21:40 +0000 | [diff] [blame] | 651 | } |
| 652 | |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 653 | final Pair<Bundle, Bundle> languagesBundles = generateLanguageBundles(text, start, end); |
| 654 | final Bundle textLanguagesBundle = languagesBundles.first; |
| 655 | final Bundle foreignLanguageBundle = languagesBundles.second; |
Abodunrinwa Toki | 520b2f8 | 2019-01-27 07:48:02 +0000 | [diff] [blame] | 656 | builder.setForeignLanguageExtra(foreignLanguageBundle); |
| 657 | |
Jan Althaus | 20d346e | 2018-03-23 14:03:52 +0100 | [diff] [blame] | 658 | boolean isPrimaryAction = true; |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 659 | final List<LabeledIntent> labeledIntents = mClassificationIntentFactory.create( |
Tony Mak | fc039c3 | 2019-01-17 19:32:08 +0000 | [diff] [blame] | 660 | mContext, |
| 661 | classifiedText, |
Abodunrinwa Toki | 520b2f8 | 2019-01-27 07:48:02 +0000 | [diff] [blame] | 662 | foreignLanguageBundle != null, |
Tony Mak | fc039c3 | 2019-01-17 19:32:08 +0000 | [diff] [blame] | 663 | referenceTime, |
| 664 | highestScoringResult); |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 665 | final LabeledIntent.TitleChooser titleChooser = |
Tony Mak | ac9b4d8 | 2019-02-15 13:57:38 +0000 | [diff] [blame] | 666 | (labeledIntent, resolveInfo) -> labeledIntent.titleWithoutEntity; |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 667 | |
Tony Mak | fc039c3 | 2019-01-17 19:32:08 +0000 | [diff] [blame] | 668 | for (LabeledIntent labeledIntent : labeledIntents) { |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 669 | final LabeledIntent.Result result = |
| 670 | labeledIntent.resolve(mContext, titleChooser, textLanguagesBundle); |
Tony Mak | ac9b4d8 | 2019-02-15 13:57:38 +0000 | [diff] [blame] | 671 | if (result == null) { |
Abodunrinwa Toki | 253827f | 2018-04-24 19:19:48 +0100 | [diff] [blame] | 672 | continue; |
| 673 | } |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 674 | |
| 675 | final Intent intent = result.resolvedIntent; |
Tony Mak | ac9b4d8 | 2019-02-15 13:57:38 +0000 | [diff] [blame] | 676 | final RemoteAction action = result.remoteAction; |
Jan Althaus | 20d346e | 2018-03-23 14:03:52 +0100 | [diff] [blame] | 677 | if (isPrimaryAction) { |
| 678 | // For O backwards compatibility, the first RemoteAction is also written to the |
| 679 | // legacy API fields. |
| 680 | builder.setIcon(action.getIcon().loadDrawable(mContext)); |
| 681 | builder.setLabel(action.getTitle().toString()); |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 682 | builder.setIntent(intent); |
Jan Althaus | 20d346e | 2018-03-23 14:03:52 +0100 | [diff] [blame] | 683 | builder.setOnClickListener(TextClassification.createIntentOnClickListener( |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 684 | TextClassification.createPendingIntent( |
| 685 | mContext, intent, labeledIntent.requestCode))); |
Jan Althaus | 20d346e | 2018-03-23 14:03:52 +0100 | [diff] [blame] | 686 | isPrimaryAction = false; |
| 687 | } |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 688 | builder.addAction(action, intent); |
Jan Althaus | 20d346e | 2018-03-23 14:03:52 +0100 | [diff] [blame] | 689 | } |
Abodunrinwa Toki | 520b2f8 | 2019-01-27 07:48:02 +0000 | [diff] [blame] | 690 | return builder.setId(createId(text, start, end)).build(); |
Jan Althaus | 92d7683 | 2017-09-27 18:14:35 +0200 | [diff] [blame] | 691 | } |
| 692 | |
Abodunrinwa Toki | 520b2f8 | 2019-01-27 07:48:02 +0000 | [diff] [blame] | 693 | /** |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 694 | * Returns a bundle pair with language detection information for extras. |
| 695 | * <p> |
| 696 | * Pair.first = textLanguagesBundle - A bundle containing information about all detected |
| 697 | * languages in the text. May be null if language detection fails or is disabled. This is |
| 698 | * typically expected to be added to a textClassifier generated remote action intent. |
| 699 | * See {@link ExtrasUtils#putTextLanguagesExtra(Bundle, Bundle)}. |
| 700 | * See {@link ExtrasUtils#getTopLanguage(Intent)}. |
| 701 | * <p> |
| 702 | * Pair.second = foreignLanguageBundle - A bundle with the language and confidence score if the |
| 703 | * system finds the text to be in a foreign language. Otherwise is null. |
| 704 | * See {@link TextClassification.Builder#setForeignLanguageExtra(Bundle)}. |
| 705 | * |
| 706 | * @param context the context of the text to detect languages for |
| 707 | * @param start the start index of the text |
| 708 | * @param end the end index of the text |
Abodunrinwa Toki | 520b2f8 | 2019-01-27 07:48:02 +0000 | [diff] [blame] | 709 | */ |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 710 | // TODO: Revisit this algorithm. |
| 711 | // TODO: Consider making this public API. |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 712 | private Pair<Bundle, Bundle> generateLanguageBundles(String context, int start, int end) { |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 713 | if (!mSettings.isTranslateInClassificationEnabled()) { |
| 714 | return null; |
| 715 | } |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 716 | try { |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 717 | final float threshold = getLangIdThreshold(); |
| 718 | if (threshold < 0 || threshold > 1) { |
| 719 | Log.w(LOG_TAG, |
| 720 | "[detectForeignLanguage] unexpected threshold is found: " + threshold); |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 721 | return Pair.create(null, null); |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 722 | } |
| 723 | |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 724 | final EntityConfidence languageScores = detectLanguages(context, start, end); |
| 725 | if (languageScores.getEntities().isEmpty()) { |
| 726 | return Pair.create(null, null); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 727 | } |
| 728 | |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 729 | final Bundle textLanguagesBundle = new Bundle(); |
| 730 | ExtrasUtils.putTopLanguageScores(textLanguagesBundle, languageScores); |
| 731 | |
| 732 | final String language = languageScores.getEntities().get(0); |
| 733 | final float score = languageScores.getConfidenceScore(language); |
| 734 | if (score < threshold) { |
| 735 | return Pair.create(textLanguagesBundle, null); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 736 | } |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 737 | |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 738 | Log.v(LOG_TAG, String.format( |
| 739 | Locale.US, "Language detected: <%s:%.2f>", language, score)); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 740 | |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 741 | final Locale detected = new Locale(language); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 742 | final LocaleList deviceLocales = LocaleList.getDefault(); |
| 743 | final int size = deviceLocales.size(); |
| 744 | for (int i = 0; i < size; i++) { |
| 745 | if (deviceLocales.get(i).getLanguage().equals(detected.getLanguage())) { |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 746 | return Pair.create(textLanguagesBundle, null); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 747 | } |
| 748 | } |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 749 | final Bundle foreignLanguageBundle = ExtrasUtils.createForeignLanguageExtra( |
| 750 | detected.getLanguage(), score, getLangIdImpl().getVersion()); |
| 751 | return Pair.create(textLanguagesBundle, foreignLanguageBundle); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 752 | } catch (Throwable t) { |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 753 | Log.e(LOG_TAG, "Error generating language bundles.", t); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 754 | } |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 755 | return Pair.create(null, null); |
| 756 | } |
| 757 | |
| 758 | /** |
| 759 | * Detect the language of a piece of text by taking surrounding text into consideration. |
| 760 | * |
| 761 | * @param text text providing context for the text for which its language is to be detected |
| 762 | * @param start the start index of the text to detect its language |
| 763 | * @param end the end index of the text to detect its language |
| 764 | */ |
| 765 | // TODO: Revisit this algorithm. |
| 766 | private EntityConfidence detectLanguages(String text, int start, int end) |
| 767 | throws FileNotFoundException { |
| 768 | Preconditions.checkArgument(start >= 0); |
| 769 | Preconditions.checkArgument(end <= text.length()); |
| 770 | Preconditions.checkArgument(start <= end); |
| 771 | |
| 772 | final float[] langIdContextSettings = mSettings.getLangIdContextSettings(); |
| 773 | // The minimum size of text to prefer for detection. |
| 774 | final int minimumTextSize = (int) langIdContextSettings[0]; |
| 775 | // For reducing the score when text is less than the preferred size. |
| 776 | final float penalizeRatio = langIdContextSettings[1]; |
| 777 | // Original detection score to surrounding text detection score ratios. |
| 778 | final float subjectTextScoreRatio = langIdContextSettings[2]; |
| 779 | final float moreTextScoreRatio = 1f - subjectTextScoreRatio; |
| 780 | Log.v(LOG_TAG, |
| 781 | String.format(Locale.US, "LangIdContextSettings: " |
Abodunrinwa Toki | 0634af3 | 2019-04-04 13:10:59 +0100 | [diff] [blame^] | 782 | + "minimumTextSize=%d, penalizeRatio=%.2f, " |
| 783 | + "subjectTextScoreRatio=%.2f, moreTextScoreRatio=%.2f", |
Tony Mak | 72e1797 | 2019-03-16 10:28:42 +0000 | [diff] [blame] | 784 | minimumTextSize, penalizeRatio, subjectTextScoreRatio, moreTextScoreRatio)); |
| 785 | |
| 786 | if (end - start < minimumTextSize && penalizeRatio <= 0) { |
| 787 | return new EntityConfidence(Collections.emptyMap()); |
| 788 | } |
| 789 | |
| 790 | final String subject = text.substring(start, end); |
| 791 | final EntityConfidence scores = detectLanguages(subject); |
| 792 | |
| 793 | if (subject.length() >= minimumTextSize |
| 794 | || subject.length() == text.length() |
| 795 | || subjectTextScoreRatio * penalizeRatio >= 1) { |
| 796 | return scores; |
| 797 | } |
| 798 | |
| 799 | final EntityConfidence moreTextScores; |
| 800 | if (moreTextScoreRatio >= 0) { |
| 801 | // Attempt to grow the detection text to be at least minimumTextSize long. |
| 802 | final String moreText = Utils.getSubString(text, start, end, minimumTextSize); |
| 803 | moreTextScores = detectLanguages(moreText); |
| 804 | } else { |
| 805 | moreTextScores = new EntityConfidence(Collections.emptyMap()); |
| 806 | } |
| 807 | |
| 808 | // Combine the original detection scores with the those returned after including more text. |
| 809 | final Map<String, Float> newScores = new ArrayMap<>(); |
| 810 | final Set<String> languages = new ArraySet<>(); |
| 811 | languages.addAll(scores.getEntities()); |
| 812 | languages.addAll(moreTextScores.getEntities()); |
| 813 | for (String language : languages) { |
| 814 | final float score = (subjectTextScoreRatio * scores.getConfidenceScore(language) |
| 815 | + moreTextScoreRatio * moreTextScores.getConfidenceScore(language)) |
| 816 | * penalizeRatio; |
| 817 | newScores.put(language, score); |
| 818 | } |
| 819 | return new EntityConfidence(newScores); |
| 820 | } |
| 821 | |
| 822 | /** |
| 823 | * Detect languages for the specified text. |
| 824 | */ |
| 825 | private EntityConfidence detectLanguages(String text) throws FileNotFoundException { |
| 826 | final LangIdModel langId = getLangIdImpl(); |
| 827 | final LangIdModel.LanguageResult[] langResults = langId.detectLanguages(text); |
| 828 | final Map<String, Float> languagesMap = new ArrayMap<>(); |
| 829 | for (LanguageResult langResult : langResults) { |
| 830 | languagesMap.put(langResult.getLanguage(), langResult.getScore()); |
| 831 | } |
| 832 | return new EntityConfidence(languagesMap); |
Abodunrinwa Toki | 4bad09c | 2018-10-25 18:12:28 +0100 | [diff] [blame] | 833 | } |
| 834 | |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 835 | private float getLangIdThreshold() { |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 836 | try { |
| 837 | return mSettings.getLangIdThresholdOverride() >= 0 |
| 838 | ? mSettings.getLangIdThresholdOverride() |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 839 | : getLangIdImpl().getLangIdThreshold(); |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 840 | } catch (FileNotFoundException e) { |
| 841 | final float defaultThreshold = 0.5f; |
| 842 | Log.v(LOG_TAG, "Using default foreign language threshold: " + defaultThreshold); |
| 843 | return defaultThreshold; |
| 844 | } |
| 845 | } |
| 846 | |
Tony Mak | f93e9e5 | 2018-07-16 14:46:29 +0200 | [diff] [blame] | 847 | @Override |
| 848 | public void dump(@NonNull IndentingPrintWriter printWriter) { |
| 849 | synchronized (mLock) { |
Tony Mak | f93e9e5 | 2018-07-16 14:46:29 +0200 | [diff] [blame] | 850 | printWriter.println("TextClassifierImpl:"); |
| 851 | printWriter.increaseIndent(); |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 852 | printWriter.println("Annotator model file(s):"); |
Tony Mak | f93e9e5 | 2018-07-16 14:46:29 +0200 | [diff] [blame] | 853 | printWriter.increaseIndent(); |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 854 | for (ModelFileManager.ModelFile modelFile : |
| 855 | mAnnotatorModelFileManager.listModelFiles()) { |
| 856 | printWriter.println(modelFile.toString()); |
| 857 | } |
| 858 | printWriter.decreaseIndent(); |
| 859 | printWriter.println("LangID model file(s):"); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 860 | printWriter.increaseIndent(); |
Tony Mak | ba22842 | 2018-10-25 21:30:40 +0100 | [diff] [blame] | 861 | for (ModelFileManager.ModelFile modelFile : |
| 862 | mLangIdModelFileManager.listModelFiles()) { |
Tony Mak | f93e9e5 | 2018-07-16 14:46:29 +0200 | [diff] [blame] | 863 | printWriter.println(modelFile.toString()); |
| 864 | } |
| 865 | printWriter.decreaseIndent(); |
Tony Mak | adbebcc | 2018-10-30 18:59:06 +0000 | [diff] [blame] | 866 | printWriter.println("Actions model file(s):"); |
| 867 | printWriter.increaseIndent(); |
| 868 | for (ModelFileManager.ModelFile modelFile : |
| 869 | mActionsModelFileManager.listModelFiles()) { |
| 870 | printWriter.println(modelFile.toString()); |
| 871 | } |
| 872 | printWriter.decreaseIndent(); |
Tony Mak | f93e9e5 | 2018-07-16 14:46:29 +0200 | [diff] [blame] | 873 | printWriter.printPair("mFallback", mFallback); |
| 874 | printWriter.decreaseIndent(); |
| 875 | printWriter.println(); |
| 876 | } |
| 877 | } |
| 878 | |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 879 | /** |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 880 | * Closes the ParcelFileDescriptor, if non-null, and logs any errors that occur. |
Abodunrinwa Toki | 146d0d4 | 2017-04-25 01:39:19 +0100 | [diff] [blame] | 881 | */ |
Abodunrinwa Toki | ee3a48e | 2018-10-19 20:58:26 +0100 | [diff] [blame] | 882 | private static void maybeCloseAndLogError(@Nullable ParcelFileDescriptor fd) { |
| 883 | if (fd == null) { |
| 884 | return; |
| 885 | } |
| 886 | |
Abodunrinwa Toki | 146d0d4 | 2017-04-25 01:39:19 +0100 | [diff] [blame] | 887 | try { |
| 888 | fd.close(); |
| 889 | } catch (IOException e) { |
| 890 | Log.e(LOG_TAG, "Error closing file.", e); |
| 891 | } |
| 892 | } |
| 893 | |
| 894 | /** |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 895 | * Returns the locales string for the current resources configuration. |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 896 | */ |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 897 | private String getResourceLocalesString() { |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 898 | try { |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 899 | return mContext.getResources().getConfiguration().getLocales().toLanguageTags(); |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 900 | } catch (NullPointerException e) { |
| 901 | // NPE is unexpected. Erring on the side of caution. |
Tony Mak | 159f028 | 2019-03-01 14:03:25 +0000 | [diff] [blame] | 902 | return LocaleList.getDefault().toLanguageTags(); |
Abodunrinwa Toki | 25f7fdc | 2019-02-19 23:42:30 +0000 | [diff] [blame] | 903 | } |
| 904 | } |
Abodunrinwa Toki | 43e0350 | 2017-01-13 13:46:33 -0800 | [diff] [blame] | 905 | } |