summaryrefslogtreecommitdiff
path: root/adservices/service-core/java/com/android/adservices/service/topics/classifier/ClassifierManager.java
blob: 55809cb97481c630d9c069f99b5177da4a69d6fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.adservices.service.topics.classifier;

import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;

import android.annotation.NonNull;
import android.content.Context;

import com.android.adservices.data.topics.Topic;
import com.android.adservices.service.Flags;
import com.android.adservices.service.Flags.ClassifierType;
import com.android.adservices.service.FlagsFactory;
import com.android.adservices.service.topics.PackageManagerUtil;
import com.android.internal.annotations.VisibleForTesting;

import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.stream.Stream;

/**
 * Manager class to control the classifier behaviour between available types of classifier based on
 * classifier flags.
 */
public class ClassifierManager implements Classifier {
    private static ClassifierManager sSingleton;

    private Supplier<OnDeviceClassifier> mOnDeviceClassifier;
    private Supplier<PrecomputedClassifier> mPrecomputedClassifier;

    @VisibleForTesting
    ClassifierManager(
            @NonNull Supplier<OnDeviceClassifier> onDeviceClassifier,
            @NonNull Supplier<PrecomputedClassifier> precomputedClassifier) {
        mOnDeviceClassifier = onDeviceClassifier;
        mPrecomputedClassifier = precomputedClassifier;
    }

    /** Returns the singleton instance of the {@link ClassifierManager} given a context. */
    @NonNull
    public static ClassifierManager getInstance(@NonNull Context context) {
        synchronized (ClassifierManager.class) {
            if (sSingleton == null) {
                // Note: we need to have a singleton ModelManager shared by both Classifiers.
                sSingleton =
                        new ClassifierManager(
                                Suppliers.memoize(
                                        () ->
                                                new OnDeviceClassifier(
                                                        new Preprocessor(context),
                                                        new PackageManagerUtil(context),
                                                        new Random(),
                                                        ModelManager.getInstance(context))),
                                Suppliers.memoize(
                                        () ->
                                                new PrecomputedClassifier(
                                                        ModelManager.getInstance(context))));
            }
        }
        return sSingleton;
    }

    /**
     * {@inheritDoc}
     *
     * <p>Invokes a particular {@link Classifier} instance based on the classifier type flag values.
     */
    @Override
    public Map<String, List<Topic>> classify(Set<String> apps) {
        @ClassifierType int classifierTypeFlag = FlagsFactory.getFlags().getClassifierType();
        if (classifierTypeFlag == Flags.PRECOMPUTED_CLASSIFIER) {
            return mPrecomputedClassifier.get().classify(apps);
        } else if (classifierTypeFlag == Flags.ON_DEVICE_CLASSIFIER) {
            return mOnDeviceClassifier.get().classify(apps);
        } else {
            // PRECOMPUTED_THEN_ON_DEVICE
            // Default if classifierTypeFlag value is not set/invalid.
            // precomputedClassifications expects non-empty values.
            Map<String, List<Topic>> precomputedClassifications =
                    mPrecomputedClassifier.get().classify(apps);
            // Collect package names that do not have any topics in the precomputed list.
            Set<String> remainingApps =
                    apps.stream()
                            .filter(
                                    packageName ->
                                            !isValidValue(packageName, precomputedClassifications))
                            .collect(toSet());
            Map<String, List<Topic>> onDeviceClassifications =
                    mOnDeviceClassifier.get().classify(remainingApps);

            // Combine classification values. On device classifications are used for values that
            // do not have valid precomputed classifications.
            Map<String, List<Topic>> combinedClassifications =
                    Stream.concat(
                                    onDeviceClassifications.entrySet().stream(),
                                    precomputedClassifications.entrySet().stream())
                            .collect(
                                    toMap(
                                            Entry::getKey,
                                            Entry::getValue,
                                            ClassifierManager::combineTopics));
            return combinedClassifications;
        }
    }

    /**
     * {@inheritDoc}
     *
     * <p>Invokes a particular {@link Classifier} instance based on the classifier type flag values.
     */
    @Override
    public List<Topic> getTopTopics(
            Map<String, List<Topic>> appTopics, int numberOfTopTopics, int numberOfRandomTopics) {
        @ClassifierType int classifierTypeFlag = FlagsFactory.getFlags().getClassifierType();
        // getTopTopics has the same implementation.
        // If the loaded assets are same, the output will be same.
        // TODO(b/240478024): Unify asset loading for Classifiers to ensure same assets are used.
        if (classifierTypeFlag == Flags.ON_DEVICE_CLASSIFIER) {
            return mOnDeviceClassifier
                    .get()
                    .getTopTopics(appTopics, numberOfTopTopics, numberOfRandomTopics);
        } else {
            // Use getTopics from PrecomputedClassifier as default.
            // TODO(b/240478024): Unify asset loading for Classifiers to ensure same assets are
            //  used.
            return mPrecomputedClassifier
                    .get()
                    .getTopTopics(appTopics, numberOfTopTopics, numberOfRandomTopics);
        }
    }

    // Prefer precomputed values for topics if the list is not empty.
    private static List<Topic> combineTopics(
            List<Topic> onDeviceValue, List<Topic> precomputedValue) {
        if (!precomputedValue.isEmpty()) {
            return precomputedValue;
        }
        return onDeviceValue;
    }

    // Return true if package name has non-empty list of topics in the classifications.
    private boolean isValidValue(String packageName, Map<String, List<Topic>> classifications) {
        if (classifications.containsKey(packageName)
                && !classifications.get(packageName).isEmpty()) {
            return true;
        }
        return false;
    }
}