This repository was archived by the owner on Feb 20, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathlocale_recommender.py
76 lines (56 loc) · 2.55 KB
/
locale_recommender.py
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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from taar.interfaces import IMozLogging, ITAARCache
from .base_recommender import AbstractRecommender
class LocaleRecommender(AbstractRecommender):
""" A recommender class that returns top N addons based on the client geo-locale.
This will load a json file containing updated top n addons in use per geo locale
updated periodically by a separate process on airflow using Longitdudinal Telemetry
data.
This recommender may provide useful recommendations when collaborative_recommender
may not work.
"""
def __init__(self, ctx):
self._ctx = ctx
self.logger = self._ctx[IMozLogging].get_logger("taar")
self._cache = self._ctx[ITAARCache]
def _get_cache(self, extra_data):
tmp = extra_data.get("cache", None)
if tmp is None:
tmp = self._cache.cache_context()
return tmp
def can_recommend(self, client_data, extra_data={}):
cache = self._get_cache(extra_data)
# We can't recommend if we don't have our data files.
if cache["top_addons_per_locale"] is None:
return False
# If we have data coming from other sources, we can use that for
# recommending.
client_locale = client_data.get("locale", None) or extra_data.get(
"locale", None
)
if not isinstance(client_locale, str):
return False
if client_locale not in cache["top_addons_per_locale"]:
return False
if not cache["top_addons_per_locale"].get(client_locale):
return False
return True
def recommend(self, client_data, limit, extra_data={}):
cache = self._get_cache(extra_data)
# If we have data coming from multiple sourecs, prefer the one
# from 'client_data'.
client_locale = client_data.get("locale") or extra_data.get("locale", None)
result_list = cache["top_addons_per_locale"].get(client_locale, [])[:limit]
if "locale" not in client_data:
try:
client_data["locale"] = extra_data["locale"]
except KeyError:
client_data["locale"] = None
log_data = (client_data["locale"], str([r[0] for r in result_list]))
self.logger.debug(
"locale_recommender_triggered, "
"client_locale: [%s], guids: [%s]" % log_data
)
return result_list