1 from collections
import defaultdict
, namedtuple
2 from operator
import itemgetter
3 from datetime
import datetime
4 from random
import choice
5 from itertools
import chain
7 from mygpo
.core
.models
import Podcast
8 from mygpo
.decorators
import query_if_required
9 from mygpo
.counter
import Counter
10 from mygpo
.core
.proxy
import proxy_object
11 from mygpo
.directory
.models
import Category
12 from mygpo
.db
.couchdb
.podcast
import podcasts_for_tag
13 from mygpo
.db
.couchdb
.directory
import top_categories
, category_for_tag
18 def __init__(self
, tag
):
22 def get_podcasts(self
):
23 """ Returns the podcasts with the current tag.
25 Some podcasts might be returned twice """
27 return podcasts_for_tag(self
.tag
)
31 TagCloudEntry
= namedtuple('TagCloudEntry', 'label weight')
36 def __init__(self
, total
=100, num_cat
=10, podcasts_per_cat
=10):
38 self
.num_cat
= num_cat
39 self
.podcasts_per_cat
= podcasts_per_cat
40 self
._categories
= None
44 def _needs_query(self
):
45 return self
._categories
is None
51 self
._categories
= top_categories(0, self
.num_cat
, True)
54 if self
.total
-self
.num_cat
> 0:
55 self
._tagcloud
= top_categories(self
.num_cat
, self
.total
-self
.num_cat
, False)
61 self
._tagcloud
.sort(key
= lambda x
: x
.label
.lower())
67 return max([e
.get_weight() for e
in self
.tagcloud
] + [0])
71 return min([e
.get_weight() for e
in self
.tagcloud
])
77 return self
._categories
80 def _prepare_category(self
, resp
):
81 category
= Category
.wrap(resp
['doc'])
82 category
= proxy_object(category
)
83 category
.podcasts
= category
.get_podcasts(0, self
.podcasts_per_cat
)
88 def update_category(podcast
):
89 all_tags
= list(chain
.from_iterable(s
for s
in podcast
.tags
.values()))
94 random_tag
= choice(all_tags
)
96 category
= category_for_tag(random_tag
)
98 category
= Category(label
=random_tag
)
100 category
.updated
= datetime
.utcnow()
102 category
.podcasts
= category
.podcasts
[:999]
104 # we don't need to CategoryEntry wrapper anymore
105 if any(isinstance(x
, dict) for x
in category
.podcasts
):
106 category
.podcasts
= filter(lambda x
: isinstance(x
, dict), category
.podcasts
)
107 category
.podcasts
= [e
['podcast'] for e
in category
.podcasts
]
109 if podcast
.get_id() in category
.podcasts
:
110 category
.podcasts
.remove(podcast
.get_id())
112 category
.podcasts
.insert(0, podcast
.get_id())
113 category
.label
= category
.label
.strip()