1 from collections
import defaultdict
, namedtuple
, Counter
2 from operator
import itemgetter
3 from datetime
import datetime
4 from random
import choice
5 from itertools
import chain
7 from mygpo
.decorators
import query_if_required
, repeat_on_conflict
8 from mygpo
.core
.proxy
import proxy_object
9 from mygpo
.directory
.models
import Category
10 from mygpo
.db
.couchdb
.directory
import top_categories
, save_category
, \
11 category_for_tag_uncached
16 def __init__(self
, total
=100, num_cat
=10, podcasts_per_cat
=10):
18 self
.num_cat
= num_cat
19 self
.podcasts_per_cat
= podcasts_per_cat
20 self
._categories
= None
24 def _needs_query(self
):
25 return self
._categories
is None
31 self
._categories
= top_categories(0, self
.num_cat
, True)
34 if self
.total
-self
.num_cat
> 0:
35 self
._tagcloud
= top_categories(self
.num_cat
, self
.total
-self
.num_cat
, False)
41 self
._tagcloud
.sort(key
= lambda x
: x
.label
.lower())
47 return max([e
.get_weight() for e
in self
.tagcloud
] + [0])
51 return min([e
.get_weight() for e
in self
.tagcloud
])
57 return self
._categories
60 def _prepare_category(self
, resp
):
61 category
= Category
.wrap(resp
['doc'])
62 category
= proxy_object(category
)
63 category
.podcasts
= category
.get_podcasts(0, self
.podcasts_per_cat
)
69 def update_category(podcast
):
70 all_tags
= list(chain
.from_iterable(s
for s
in podcast
.tags
.values()))
75 random_tag
= choice(all_tags
)
77 category
= category_for_tag_uncached(random_tag
)
79 category
= Category(label
=random_tag
)
81 category
.updated
= datetime
.utcnow()
83 category
.podcasts
= category
.podcasts
[:999]
85 # we don't need to CategoryEntry wrapper anymore
86 if any(isinstance(x
, dict) for x
in category
.podcasts
):
87 category
.podcasts
= filter(lambda x
: isinstance(x
, dict), category
.podcasts
)
88 category
.podcasts
= [e
['podcast'] for e
in category
.podcasts
]
90 if podcast
.get_id() in category
.podcasts
:
91 category
.podcasts
.remove(podcast
.get_id())
93 category
.podcasts
.insert(0, podcast
.get_id())
94 category
.label
= category
.label
.strip()
96 save_category(category
)