aboutsummaryrefslogtreecommitdiff
path: root/src/com/android/tv/recommendation/Recommender.java
blob: 82c2893d5c863517d3a171567c0d2ac1d70b1452 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
 * Copyright (C) 2015 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.tv.recommendation;

import android.content.Context;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import android.util.Pair;

import com.android.tv.data.Channel;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class Recommender implements RecommendationDataManager.Listener {
    private static final String TAG = "Recommender";

    @VisibleForTesting
    static final String INVALID_CHANNEL_SORT_KEY = "INVALID";
    private static final long MINIMUM_RECOMMENDATION_UPDATE_PERIOD = TimeUnit.MINUTES.toMillis(5);
    private static final Comparator<Pair<Channel, Double>> mChannelScoreComparator =
            new Comparator<Pair<Channel, Double>>() {
                @Override
                public int compare(Pair<Channel, Double> lhs, Pair<Channel, Double> rhs) {
                    // Sort the scores with descending order.
                    return rhs.second.compareTo(lhs.second);
                }
            };

    private final List<EvaluatorWrapper> mEvaluators = new ArrayList<>();
    private final boolean mIncludeRecommendedOnly;
    private final Listener mListener;

    private final Map<Long, String> mChannelSortKey = new HashMap<>();
    private final RecommendationDataManager mDataManager;
    private List<Channel> mPreviousRecommendedChannels = new ArrayList<>();
    private long mLastRecommendationUpdatedTimeUtcMillis;
    private boolean mChannelRecordLoaded;

    /**
     * Create a recommender object.
     *
     * @param includeRecommendedOnly true to include only recommended results, or false.
     */
    public Recommender(Context context, Listener listener, boolean includeRecommendedOnly) {
        mListener = listener;
        mIncludeRecommendedOnly = includeRecommendedOnly;
        mDataManager = RecommendationDataManager.acquireManager(context, this);
    }

    @VisibleForTesting
    Recommender(Listener listener, boolean includeRecommendedOnly,
            RecommendationDataManager dataManager) {
        mListener = listener;
        mIncludeRecommendedOnly = includeRecommendedOnly;
        mDataManager = dataManager;
    }

    public boolean isReady() {
        return mChannelRecordLoaded;
    }

    public void release() {
        mDataManager.release(this);
    }

    public void registerEvaluator(Evaluator evaluator) {
        registerEvaluator(evaluator,
                EvaluatorWrapper.DEFAULT_BASE_SCORE, EvaluatorWrapper.DEFAULT_WEIGHT);
    }

    /**
     * Register the evaluator used in recommendation.
     *
     * The range of evaluated scores by this evaluator will be between {@code baseScore} and
     * {@code baseScore} + {@code weight} (inclusive).

     * @param evaluator The evaluator to register inside this recommender.
     * @param baseScore Base(Minimum) score of the score evaluated by {@code evaluator}.
     * @param weight Weight value to rearrange the score evaluated by {@code evaluator}.
     */
    public void registerEvaluator(Evaluator evaluator, double baseScore, double weight) {
        mEvaluators.add(new EvaluatorWrapper(this, evaluator, baseScore, weight));
    }

    public List<Channel> recommendChannels() {
        return recommendChannels(mDataManager.getChannelRecordCount());
    }

    /**
     * Return the channel list of recommendation up to {@code n} or the number of channels.
     * During the evaluation, this method updates the channel sort key of recommended channels.
     *
     * @param size The number of channels that might be recommended.
     * @return Top {@code size} channels recommended sorted by score in descending order. If
     *         {@code size} is bigger than the number of channels, the number of results could
     *         be less than {@code size}.
     */
    public List<Channel> recommendChannels(int size) {
        List<Pair<Channel, Double>> records = new ArrayList<>();
        Collection<ChannelRecord> channelRecordList = mDataManager.getChannelRecords();
        for (ChannelRecord cr : channelRecordList) {
            double maxScore = Evaluator.NOT_RECOMMENDED;
            for (EvaluatorWrapper evaluator : mEvaluators) {
                double score = evaluator.getScaledEvaluatorScore(cr.getChannel().getId());
                if (score > maxScore) {
                    maxScore = score;
                }
            }
            if (!mIncludeRecommendedOnly || maxScore != Evaluator.NOT_RECOMMENDED) {
                records.add(new Pair<>(cr.getChannel(), maxScore));
            }
        }
        if (size > records.size()) {
            size = records.size();
        }
        Collections.sort(records, mChannelScoreComparator);

        List<Channel> results = new ArrayList<>();

        mChannelSortKey.clear();
        String sortKeyFormat = "%0" + String.valueOf(size).length() + "d";
        for (int i = 0; i < size; ++i) {
            // Channel with smaller sort key has higher priority.
            mChannelSortKey.put(records.get(i).first.getId(), String.format(sortKeyFormat, i));
            results.add(records.get(i).first);
        }
        return results;
    }

    /**
     * Returns the {@link Channel} object for a given channel ID from the channel pool that this
     * recommendation engine has.
     *
     * @param channelId The channel ID to retrieve the {@link Channel} object for.
     * @return the {@link Channel} object for the given channel ID, {@code null} if such a channel
     *         is not found.
     */
    public Channel getChannel(long channelId) {
        ChannelRecord record = mDataManager.getChannelRecord(channelId);
        return record == null ? null : record.getChannel();
    }

    /**
     * Returns the {@link ChannelRecord} object for a given channel ID.
     *
     * @param channelId The channel ID to receive the {@link ChannelRecord} object for.
     * @return the {@link ChannelRecord} object for the given channel ID.
     */
    public ChannelRecord getChannelRecord(long channelId) {
        return mDataManager.getChannelRecord(channelId);
    }

    /**
     * Returns the sort key of a given channel Id. Sort key is determined in
     * {@link #recommendChannels()} and getChannelSortKey must be called after that.
     *
     * If getChannelSortKey was called before evaluating the channels or trying to get sort key
     * of non-recommended channel, it returns {@link #INVALID_CHANNEL_SORT_KEY}.
     */
    public String getChannelSortKey(long channelId) {
        String key = mChannelSortKey.get(channelId);
        return key == null ? INVALID_CHANNEL_SORT_KEY : key;
    }

    @Override
    public void onChannelRecordLoaded() {
        mChannelRecordLoaded = true;
        mListener.onRecommenderReady();
        List<ChannelRecord> channels = new ArrayList<>(mDataManager.getChannelRecords());
        for (EvaluatorWrapper evaluator : mEvaluators) {
            evaluator.onChannelListChanged(Collections.unmodifiableList(channels));
        }
    }

    @Override
    public void onNewWatchLog(ChannelRecord channelRecord) {
        for (EvaluatorWrapper evaluator : mEvaluators) {
            evaluator.onNewWatchLog(channelRecord);
        }
        checkRecommendationChanged();
    }

    @Override
    public void onChannelRecordChanged() {
        if (mChannelRecordLoaded) {
            List<ChannelRecord> channels = new ArrayList<>(mDataManager.getChannelRecords());
            for (EvaluatorWrapper evaluator : mEvaluators) {
                evaluator.onChannelListChanged(Collections.unmodifiableList(channels));
            }
        }
        checkRecommendationChanged();
    }

    private void checkRecommendationChanged() {
        long currentTimeUtcMillis = System.currentTimeMillis();
        if (currentTimeUtcMillis - mLastRecommendationUpdatedTimeUtcMillis
                < MINIMUM_RECOMMENDATION_UPDATE_PERIOD) {
            return;
        }
        mLastRecommendationUpdatedTimeUtcMillis = currentTimeUtcMillis;
        List<Channel> recommendedChannels = recommendChannels();
        if (!recommendedChannels.equals(mPreviousRecommendedChannels)) {
            mPreviousRecommendedChannels = recommendedChannels;
            mListener.onRecommendationChanged();
        }
    }

    @VisibleForTesting
    void setLastRecommendationUpdatedTimeUtcMs(long newUpdatedTimeMs) {
        mLastRecommendationUpdatedTimeUtcMillis = newUpdatedTimeMs;
    }

    public static abstract class Evaluator {
        public static final double NOT_RECOMMENDED = -1.0;
        private Recommender mRecommender;

        protected Evaluator() {}

        protected void onChannelRecordListChanged(List<ChannelRecord> channelRecords) {
        }

        /**
         * This will be called when a new watch log comes into WatchedPrograms table.
         *
         * @param channelRecord The channel record corresponds to the new watch log.
         */
        protected void onNewWatchLog(ChannelRecord channelRecord) {
        }

        /**
         * The implementation should return the recommendation score for the given channel ID.
         * The return value should be in the range of [0.0, 1.0] or NOT_RECOMMENDED for denoting
         * that it gives up to calculate the score for the channel.
         *
         * @param channelId The channel ID which will be evaluated by this recommender.
         * @return The recommendation score
         */
        protected abstract double evaluateChannel(final long channelId);

        protected void setRecommender(Recommender recommender) {
            mRecommender = recommender;
        }

        protected Recommender getRecommender() {
            return mRecommender;
        }
    }

    private static class EvaluatorWrapper {
        private static final double DEFAULT_BASE_SCORE = 0.0;
        private static final double DEFAULT_WEIGHT = 1.0;

        private final Evaluator mEvaluator;
        // The minimum score of the Recommender unless it gives up to provide the score.
        private final double mBaseScore;
        // The weight of the recommender. The return-value of getScore() will be multiplied by
        // this value.
        private final double mWeight;

        public EvaluatorWrapper(Recommender recommender, Evaluator evaluator,
                double baseScore, double weight) {
            mEvaluator = evaluator;
            evaluator.setRecommender(recommender);
            mBaseScore = baseScore;
            mWeight = weight;
        }

        /**
         * This returns the scaled score for the given channel ID based on the returned value
         * of evaluateChannel().
         *
         * @param channelId The channel ID which will be evaluated by the recommender.
         * @return Returns the scaled score (mBaseScore + score * mWeight) when evaluateChannel() is
         *         in the range of [0.0, 1.0]. If evaluateChannel() returns NOT_RECOMMENDED or any
         *         negative numbers, it returns NOT_RECOMMENDED. If calculateScore() returns more
         *         than 1.0, it returns (mBaseScore + mWeight).
         */
        private double getScaledEvaluatorScore(long channelId) {
            double score = mEvaluator.evaluateChannel(channelId);
            if (score < 0.0) {
                if (score != Evaluator.NOT_RECOMMENDED) {
                    Log.w(TAG, "Unexpected score (" + score + ") from the recommender"
                            + mEvaluator);
                }
                // If the recommender gives up to calculate the score, return 0.0
                return Evaluator.NOT_RECOMMENDED;
            } else if (score > 1.0) {
                Log.w(TAG, "Unexpected score (" + score + ") from the recommender"
                        + mEvaluator);
                score = 1.0;
            }
            return mBaseScore + score * mWeight;
        }

        public void onNewWatchLog(ChannelRecord channelRecord) {
            mEvaluator.onNewWatchLog(channelRecord);
        }

        public void onChannelListChanged(List<ChannelRecord> channelRecords) {
            mEvaluator.onChannelRecordListChanged(channelRecords);
        }
    }

    public interface Listener {
        /**
         * Called after channel record map is loaded.
         */
        void onRecommenderReady();

        /**
         * Called when the recommendation changes.
         */
        void onRecommendationChanged();
    }
}