예제 #1
0
def similar_users(context, arg):
    """ displays widget with similar users"""

    more = False
    if not isinstance(arg, User):
        user = User.objects.get(username__iexact=arg)
    else:
        user = arg

    logged_user = context['request'].user
    is_logged = logged_user.username == user.username

    page_size = getattr(settings, "NUMBER_OF_SIMILAR_USERS_ON_TAG", 3)
    recom_helper = RecomHelper()
    filmaster_type = 'all'
    similar_users = recom_helper.get_best_tci_users(user=user, limit=page_size+1, filmaster_type=filmaster_type)

    list_of_users = list(similar_users)
    list_of_shown_users  = list(similar_users[:settings.NUMBER_OF_SIMILAR_USERS_ON_TAG])

    if len(list_of_users) > len(list_of_shown_users):
        more = True

    return {
        'users': similar_users[:settings.NUMBER_OF_SIMILAR_USERS_ON_TAG],
        'more': more,
        'user_checked': user,
        'is_logged': is_logged,
    }
예제 #2
0
파일: views.py 프로젝트: thuvh/filmmaster
    def get_queryset(self):
        is_valid, fake_film_specs_form, film_specs_form = self.get_specs_form()
        self.get_username()
        self.get_type()
        self.get_params()
        self.get_sort_by()

        tags = None
        year_from = None
        year_to = None
        related_director = None
        related_actor = None
        popularity = None
        if is_valid:
            tags = fake_film_specs_form.tags
            year_from = fake_film_specs_form.year_from
            year_to = fake_film_specs_form.year_to
            related_director = fake_film_specs_form.related_director_as_object
            related_actor = fake_film_specs_form.related_actor_as_object
            popularity = fake_film_specs_form.popularity

        recom_helper = RecomHelper()
        ratings = recom_helper.get_all_ratings(
            user_id = self.user.id,
            type = self.type_as_str,
            tags = tags,
            year_from = year_from,
            year_to = year_to,
            related_director = related_director,
            related_actor = related_actor,
            order_by=self.sort_by
        )
        #logger.debug(ratings)
        return ratings
예제 #3
0
파일: views.py 프로젝트: manlan2/filmaster
    def get_queryset(self):
        is_valid, fake_film_specs_form, film_specs_form = self.get_specs_form()
        self.get_username()
        self.get_type()
        self.get_params()
        self.get_sort_by()

        tags = None
        year_from = None
        year_to = None
        related_director = None
        related_actor = None
        popularity = None
        if is_valid:
            tags = fake_film_specs_form.tags
            year_from = fake_film_specs_form.year_from
            year_to = fake_film_specs_form.year_to
            related_director = fake_film_specs_form.related_director_as_object
            related_actor = fake_film_specs_form.related_actor_as_object
            popularity = fake_film_specs_form.popularity

        recom_helper = RecomHelper()
        ratings = recom_helper.get_all_ratings(
            user_id=self.user.id,
            type=self.type_as_str,
            tags=tags,
            year_from=year_from,
            year_to=year_to,
            related_director=related_director,
            related_actor=related_actor,
            order_by=self.sort_by)
        #logger.debug(ratings)
        return ratings
예제 #4
0
def show_films_for_tag(request, tag=None, page_id = "1"):
    """
        Shows a sortable and pageable list of films for a tag
    """

    if tag == None:
        raise Http404

    recom_helper = RecomHelper()
    films_list = recom_helper.get_films_for_tag(tag = tag)

    logger.debug(films_list)

    paginate_by = 75
    paginator = Paginator(films_list, paginate_by)
    paginator._count = len(films_list)

    try:
        films = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        films = paginator.page(paginator.num_pages)        

    context = {
        'tag': tag,
        'films': films,
    }

    return render_to_response(templates['FILMS_FOR_TAG'],
            context,
            context_instance=RequestContext(request))
예제 #5
0
    def get_queryset(self):
        genre = self.get_genre()
        is_valid, fake_film_specs_form, film_specs_form = self.get_specs_form()
        recom_helper = RecomHelper()

        year_from = None
        year_to = None
        related_director = None
        related_actor = None
        popularity = None
        if is_valid:
            year_from = fake_film_specs_form.year_from
            year_to = fake_film_specs_form.year_to
            related_director = fake_film_specs_form.related_director_as_object
            related_actor = fake_film_specs_form.related_actor_as_object
            popularity = fake_film_specs_form.popularity

        films = recom_helper.get_films_for_tag(
            tags=genre,
            year_from=year_from,
            year_to=year_to,
            related_director=related_director,
            related_actor=related_actor,
            popularity=popularity)
        return films
예제 #6
0
파일: views.py 프로젝트: thuvh/filmmaster
    def get_queryset(self):
        is_valid, fake_film_specs_form, film_specs_form = self.get_specs_form()
        genre = self.get_genre()
        type_as_str = self.get_type()
        recom_helper = RecomHelper()

        tags = genre
        ranking = None

        year_from = None
        year_to = None
        related_director = None
        related_actor = None
        popularity = None
        if is_valid:
            year_from = fake_film_specs_form.year_from
            year_to = fake_film_specs_form.year_to
            related_director = fake_film_specs_form.related_director_as_object
            related_actor = fake_film_specs_form.related_actor_as_object
            popularity = fake_film_specs_form.popularity

        ranking = recom_helper.get_ranking(
            type = type_as_str,
            tags = genre,
            year_from = year_from,
            year_to = year_to,
            related_director = related_director,
            related_actor = related_actor,
            popularity = popularity,
        )
        return ranking
예제 #7
0
def show_films_for_tag(request, tag=None, page_id="1"):
    """
        Shows a sortable and pageable list of films for a tag
    """

    if tag == None:
        raise Http404

    recom_helper = RecomHelper()
    films_list = recom_helper.get_films_for_tag(tag=tag)

    logger.debug(films_list)

    paginate_by = 75
    paginator = Paginator(films_list, paginate_by)
    paginator._count = len(films_list)

    try:
        films = paginator.page(page_id)
    except (EmptyPage, InvalidPage):
        films = paginator.page(paginator.num_pages)

    context = {
        'tag': tag,
        'films': films,
    }

    return render_to_response(templates['FILMS_FOR_TAG'],
                              context,
                              context_instance=RequestContext(request))
예제 #8
0
def create_data_set(user):
    film = {}
    data_set = []

    recom_helper = RecomHelper()
    ratings = recom_helper.get_all_ratings(user)
    reviews = UserActivity.objects.reviews_for_user(user)

    for rating in ratings:
        filmid = rating.film.id
        filmname = rating.film.title
        filmlink = permalink_film(rating.film)
        img = get_image_path(rating.film, 50, 71)  # FLM-1267
        score = rating.rating
        quote = get_single_review(reviews, filmid)
        reviewdate = ""
        if rating.last_rated is not None:
            reviewdate = rating.last_rated.strftime("%b %d %Y, %H:%M")

        film = {
            "filmid": filmid,
            "filmname": filmname,
            "filmlink": filmlink,
            "img": img,
            "score": score,
            "quote": quote,
            "reviewdate": reviewdate,
            "tier": score,
        }
        data_set.append(film)
    return data_set
예제 #9
0
    def get_queryset(self):
        genre = self.get_genre()
        is_valid, fake_film_specs_form, film_specs_form = self.get_specs_form()
        recom_helper = RecomHelper()

        year_from = None
        year_to= None
        related_director= None
        related_actor= None
        popularity= None
        if is_valid:
            year_from= fake_film_specs_form.year_from
            year_to= fake_film_specs_form.year_to
            related_director= fake_film_specs_form.related_director_as_object
            related_actor= fake_film_specs_form.related_actor_as_object
            popularity= fake_film_specs_form.popularity

        films = recom_helper.get_films_for_tag(
            tags=genre,
            year_from= year_from,
            year_to= year_to,
            related_director= related_director,
            related_actor= related_actor,
            popularity= popularity
        )
        return films
예제 #10
0
파일: views.py 프로젝트: manlan2/filmaster
 def get_queryset(self):
     self.get_username()
     recom_helper = RecomHelper()
     users = recom_helper.get_best_tci_users(
         user=self.user,
         limit=self.users_limit,
         filmaster_type=self.filmaster_type)
     return users
예제 #11
0
 def test_get_best_tci_users(self):
     """
        Test for query that retrieves top users (based on common taste).
     """
     do_create_comparators()
     recom_helper = RecomHelper()
     result = recom_helper.get_best_tci_users(self.u1)
     self.assertEquals(len(result), 3)
예제 #12
0
    def test_cache_count_ratings(self):
        recom_helper = RecomHelper()
        ratings_count = recom_helper.count_ratings(self.u3.id)
        self.assertEquals(ratings_count, 15)

        save_rating(self.f1, self.u3, 1)
        ratings_count = recom_helper.count_ratings(self.u3.id)
        self.assertEquals(ratings_count, 16)
예제 #13
0
    def test_cache_count_ratings(self):
        recom_helper = RecomHelper()
        ratings_count = recom_helper.count_ratings(self.u3.id)
        self.assertEquals(ratings_count, 15)

        save_rating(self.f1, self.u3, 1)
        ratings_count = recom_helper.count_ratings(self.u3.id)
        self.assertEquals(ratings_count, 16)
예제 #14
0
 def test_get_best_tci_users(self):
     """
        Test for query that retrieves top users (based on common taste).
     """
     do_create_comparators()
     recom_helper = RecomHelper()
     result = recom_helper.get_best_tci_users(self.u1)
     print "result -->", result
     self.assertEquals(len(result), 4)
예제 #15
0
파일: views.py 프로젝트: thuvh/filmmaster
    def get_context_data(self, **kwargs):
        context = super(RatingsListView, self).get_context_data(**kwargs)

        recom_helper = RecomHelper()

        context['ratings_user'] = self.user
        context['rating_type_str'] = rating_helper.get_rating_type_label(self.type_as_str)
        context['type_as_str'] = self.type_as_str
        context['rating_types'] = get_rating_types_to_display()
        context['ratings_count'] = recom_helper.count_ratings(user_id = self.user.id)
        context['ratings_for_user_id'] = self.user.id
        return context
예제 #16
0
파일: views.py 프로젝트: thuvh/filmmaster
    def get_queryset(self):
        tags = None
        year_from = None
        year_to = None
        related_director = None
        related_actor = None
        popularity = None
        tags = self.get_genre()

        is_valid, fake_film_specs_form, film_specs_form = \
                self.get_specs_form()

        if is_valid:
            tags = tags
            year_from = fake_film_specs_form.year_from
            year_to = fake_film_specs_form.year_to
            related_director = \
                    fake_film_specs_form.related_director_as_object
            related_actor = fake_film_specs_form.related_actor_as_object
            popularity = fake_film_specs_form.popularity

        films = None
        if self.request.user.is_authenticated():
            recom_status = self.request.user.get_profile().recommendations_status
        else:
            recom_status = False

        if recom_status:
            recom_helper = RecomHelper()
            films = recom_helper.get_best_psi_films_queryset(
                user_id = self.request.user.id,
                tags = tags,
                year_from = year_from,
                year_to = year_to,
                related_director = related_director,
                related_actor = related_actor,
                popularity = popularity,
            )
        else:
            film_helper = FilmHelper()
            films = film_helper.get_best_films(
                tags = tags,
                year_from = year_from,
                year_to = year_to,
                related_director = related_director,
                related_actor = related_actor,
                popularity = popularity
            )

        films = list(films)
        return films
예제 #17
0
    def get_queryset(self):
        tags = None
        year_from = None
        year_to = None
        related_director = None
        related_actor = None
        popularity = None
        tags = self.get_genre()

        is_valid, fake_film_specs_form, film_specs_form = \
                self.get_specs_form()

        if is_valid:
            tags = tags
            year_from = fake_film_specs_form.year_from
            year_to = fake_film_specs_form.year_to
            related_director = \
                    fake_film_specs_form.related_director_as_object
            related_actor = fake_film_specs_form.related_actor_as_object
            popularity = fake_film_specs_form.popularity

        films = None
        if self.request.user.is_authenticated():
            recom_status = self.request.user.get_profile(
            ).recommendations_status
        else:
            recom_status = False

        if recom_status:
            recom_helper = RecomHelper()
            films = recom_helper.get_best_psi_films_queryset(
                self.request.user,
                tags=tags,
                year_from=year_from,
                year_to=year_to,
                related_director=related_director,
                related_actor=related_actor,
                popularity=popularity,
            )
        else:
            film_helper = FilmHelper()
            films = film_helper.get_best_films(
                tags=tags,
                year_from=year_from,
                year_to=year_to,
                related_director=related_director,
                related_actor=related_actor,
                popularity=popularity)

        return films
예제 #18
0
파일: views.py 프로젝트: manlan2/filmaster
    def get_context_data(self, **kwargs):
        context = super(RatingsListView, self).get_context_data(**kwargs)

        recom_helper = RecomHelper()

        context['ratings_user'] = self.user
        context['rating_type_str'] = rating_helper.get_rating_type_label(
            self.type_as_str)
        context['type_as_str'] = self.type_as_str
        context['rating_types'] = get_rating_types_to_display()
        context['ratings_count'] = recom_helper.count_ratings(
            user_id=self.user.id)
        context['ratings_for_user_id'] = self.user.id
        return context
예제 #19
0
    def test_get_all_ratings(self):
        recom_helper = RecomHelper()
        film_helper = FilmHelper()

        film_with_director_and_actor = Film.objects.filter(
            title__startswith="Added film part 2")
        related_directors = film_helper.get_film_directors(
            film_with_director_and_actor[0])
        related_characters = film_helper.get_film_actors(
            film_with_director_and_actor[0])
        related_actors = []
        for character in related_characters:
            actor = character.person
            related_actors.append(actor)

        non_rated_films = Film.objects.filter(rating__isnull=True,
                                              title__startswith="Added")

        POST = {}
        #POST['form_id'] = '1'
        POST['rating'] = '6'
        POST['object_id'] = str(non_rated_films[1].parent.id)
        POST['form_type'] = str(Rating.TYPE_FILM)
        POST['cancel_rating'] = '0'
        rating_form = RatingForm(POST)
        if rating_form.is_valid():
            rating_helper.add_edit_rating(rating_form, self.u1)
        else:
            print "RATING FORM INVALID!"

        all_ratings = recom_helper.get_all_ratings(self.u1.id)
        self.assertEquals(len(all_ratings), 31)

        director_ratings = recom_helper.get_all_ratings(
            self.u1.id, related_director=related_directors)
        self.assertEquals(len(director_ratings), 1)

        actor_ratings = recom_helper.get_all_ratings(
            self.u1.id, related_actor=related_actors)
        self.assertEquals(len(actor_ratings), 1)

        from_ratings = recom_helper.get_all_ratings(self.u1.id, year_from=1990)
        self.assertEquals(len(from_ratings), 23)

        to_ratings = recom_helper.get_all_ratings(self.u1.id, year_to=2000)
        self.assertEquals(len(to_ratings), 22)

        popularity_ratings = recom_helper.get_all_ratings(self.u1.id,
                                                          popularity=5)
        self.assertEquals(len(popularity_ratings), 8)

        tag_ratings = recom_helper.get_all_ratings(self.u1.id, tags='comedy')
        self.assertEquals(len(tag_ratings), 5)
예제 #20
0
def compute_fast_recommendations_phase2(user_id, send_notice):
    from recom_helper import RecomHelper
    from film20.core.models import Recommendation
    from film20.showtimes.showtimes_helper import get_films
    from film20.showtimes.models import Channel
    from film20.showtimes.utils import get_today
    from itertools import chain
    import pytz

    helper = RecomHelper()
    
    user = User.objects.get(pk=user_id)
    profile = user.get_profile()

    if profile.country in settings.COUNTRIES_WITH_SHOWTIMES:
        if profile.timezone_id:
            timezone = pytz.timezone(profile.timezone_id)
        else:
            timezone = pytz.utc
            logger.warning("user %r has no timezone, using utc", user)
        
        today = get_today(timezone)

        theaters = Channel.objects.selected_by(user, Channel.TYPE_CINEMA)
        tv_channels = Channel.objects.selected_by(user, Channel.TYPE_TV_CHANNEL)
        for i in range(3):
            date = today + timedelta(days=i)
            for channels in (theaters, tv_channels):
                for film in get_films(date, channels):
                    count_guessed_rate(user, film)
    
    if send_notice:
        notification.send([user], 'recommendations_fast_calculated', {})
예제 #21
0
    def test_get_best_psi_films_queryset_alg2(self):
        """
           Test for query that retrieves top recommendations.
           First it should return all films, then we rate one and in the second call
           it should only retrieve the other film.
        """

        recom_helper = RecomHelper()
        film_helper = FilmHelper()

        # no recommendations yet, the result should be 0
        result = recom_helper.get_best_psi_films_queryset_alg2(self.u4.id)
        self.assertEquals(len(result), 0)

        # simulate generating recommendations (for all films) and test again, it should retrieve all films
        r1 = Recommendation()
        r1.guess_rating_alg2 = 7
        r1.film = self.f19
        r1.user = self.u4
        r1.save()
        r2 = Recommendation()
        r2.guess_rating_alg2 = 8
        r2.film = self.f20
        r2.user = self.u4
        r2.save()
        result = recom_helper.get_best_psi_films_queryset_alg2(self.u4.id)
        self.assertEquals(len(result), 2)

        # rate one film, it should be removed from the list
        POST = {}
        # TODO check why it starts breaking (form invalid) when form_id is set
        # POST['form_id'] = '1'
        POST["rating"] = "6"
        POST["object_id"] = str(self.f20.parent.id)
        POST["form_type"] = str(Rating.TYPE_FILM)
        POST["cancel_rating"] = "0"
        rating_form = RatingForm(POST)
        if rating_form.is_valid():
            rating_helper.add_edit_rating(rating_form, self.u4)
        else:
            print "RATING FORM INVALID!"

        result = recom_helper.get_recently_popular_films_query(self.u4.id)
        self.assertEquals(len(result), 21)
예제 #22
0
def get_next_film(request):
    """
        Gets next film from session. If list of films to be rated doesn't exist in session, or if there are no 
        more movies to rate, retrieves the list first and then gets next film to rate

    """
    recom_helper = RecomHelper()
    films_to_be_rated = get_movies_to_be_rated_from_session(request)
  
    # hack for not-logged-in users 
    if request.user.is_authenticated() == False:
        user_id = 1
    else:
        user_id = request.user.id

    # logger.debug(films_to_be_rated)
    # just to check if it's session that's causing problems
    # films_to_be_rated = None
    
    # no films to be rated yet
    if films_to_be_rated == None:
        logger.debug("No list of films to be rated found in session, retrieving a new list")
        films_to_be_rated = recom_helper.prepare_films_to_rate(user_id, get_rated_movies_from_session(request))            
        store_movies_to_be_rated_in_session(request, films_to_be_rated)
    # all films rated already
    else:
        len_films = len(films_to_be_rated)
        logger.debug("Film to be rated:" + unicode(len_films))
        if len_films==0:
            logger.debug("All films already rated, retrieving a new list")
            films_to_be_rated = recom_helper.prepare_films_to_rate(user_id, get_rated_movies_from_session(request))            
            store_movies_to_be_rated_in_session(request, films_to_be_rated)
        else:
            logger.debug("Getting next object to rate from session")

    if not films_to_be_rated:
        return None        
    # pop first item from the list
    the_film = films_to_be_rated.pop(0)
    # update the list in session
    store_movies_to_be_rated_in_session(request, films_to_be_rated)
    update_rating_last_displayed(request.user, the_film)
    
    return the_film
예제 #23
0
    def get_queryset(self):
        is_valid, fake_film_specs_form, film_specs_form = self.get_specs_form()
        genre = self.get_genre()
        type_as_str = self.get_type()
        recom_helper = RecomHelper()

        tags = genre
        ranking = None

        year_from = None
        year_to = None
        related_director = None
        related_actor = None
        popularity = None
        if is_valid:
            year_from = fake_film_specs_form.year_from
            year_to = fake_film_specs_form.year_to
            related_director = fake_film_specs_form.related_director_as_object
            related_actor = fake_film_specs_form.related_actor_as_object
            popularity = fake_film_specs_form.popularity

        ranking = recom_helper.get_ranking(
            type=type_as_str,
            tags=genre,
            year_from=year_from,
            year_to=year_to,
            related_director=related_director,
            related_actor=related_actor,
            popularity=popularity,
            festival=self.festival,
            tv_series=self.kwargs.get('tv_series', False),
        )

        from film20.utils.misc import ListWrapper

        class RankingWrapper(ListWrapper):
            def wrap(self, items):
                for item in items:
                    item.film._average_score = item.average_score
                    item.film._number_of_ratings = item.number_of_votes
                    yield item

        return RankingWrapper(ranking)
예제 #24
0
    def get_queryset(self):
        is_valid, fake_film_specs_form, film_specs_form = self.get_specs_form()
        genre = self.get_genre()
        type_as_str = self.get_type()
        recom_helper = RecomHelper()

        tags = genre
        ranking = None

        year_from = None
        year_to = None
        related_director = None
        related_actor = None
        popularity = None
        if is_valid:
            year_from = fake_film_specs_form.year_from
            year_to = fake_film_specs_form.year_to
            related_director = fake_film_specs_form.related_director_as_object
            related_actor = fake_film_specs_form.related_actor_as_object
            popularity = fake_film_specs_form.popularity

        ranking = recom_helper.get_ranking(
            type = type_as_str,
            tags = genre,
            year_from = year_from,
            year_to = year_to,
            related_director = related_director,
            related_actor = related_actor,
            popularity = popularity,
            festival = self.festival,
            tv_series = self.kwargs.get('tv_series', False),
        )

        from film20.utils.misc import ListWrapper
        class RankingWrapper(ListWrapper):
            def wrap(self, items):
                for item in items:
                    item.film._average_score = item.average_score
                    item.film._number_of_ratings = item.number_of_votes
                    yield item
        
        return RankingWrapper(ranking)
예제 #25
0
def compute_fast_recommendations(user_id, send_notice=True):
    from recom_helper import RecomHelper
    from film20.core.models import Recommendation
    from film20.showtimes.showtimes_helper import get_films
    from film20.showtimes.models import Channel
    from film20.showtimes.utils import get_today
    from itertools import chain
    import pytz

    helper = RecomHelper()
    
    user = User.objects.get(pk=user_id)
    profile = user.get_profile()

    Recommendation.objects.filter(user=user).delete()

    if profile.country in settings.COUNTRIES_WITH_SHOWTIMES:
        if profile.timezone_id:
            timezone = pytz.timezone(profile.timezone_id)
        else:
            timezone = pytz.utc
            logger.warning("user %r has no timezone, using utc", user)
        
        today = get_today(timezone)

        theaters = Channel.objects.selected_by(user, Channel.TYPE_CINEMA)
        tv_channels = Channel.objects.selected_by(user, Channel.TYPE_TV_CHANNEL)
        for i in range(3):
            date = today + timedelta(days=i)
            for channels in (theaters, tv_channels):
                for film in get_films(date, channels):
                    count_guessed_rate(user, film)
    
    for r in helper.get_ranking()[0:200]:
        count_guessed_rate(user, r.film)

    profile.recommendations_status = profile.FAST_RECOMMENDATIONS
    profile.save()

    if send_notice:
        notification.send([user], 'recommendations_fast_calculated', {})
예제 #26
0
    def get_recommended_films(self, user_id):
        """ 
        Fetch recommended films for a user (with caching enabled)
        """

        # try to retrieve from cache
        result = get_cache(CACHE_RECOMMENDED_FILMS_HOME_PAGE, user_id)
        if result!=None:
            return result

        logger.debug("user_id: " + unicode(user_id))
        recom_helper = RecomHelper()        
        recommended_films = recom_helper.get_best_psi_films(
            limit = NUMBER_OF_RECOMMENDED_FILMS_FRONT_PAGE, 
            user_id = user_id, 
            rated_films = None)

        # store in cache
        set_cache(CACHE_RECOMMENDED_FILMS_HOME_PAGE, user_id, recommended_films)

        return recommended_films
예제 #27
0
def compute_fast_recommendations(user_id, send_notice=True):
    from recom_helper import RecomHelper
    from film20.core.models import Recommendation
    from film20.showtimes.showtimes_helper import get_films
    from film20.showtimes.models import Channel
    from film20.showtimes.utils import get_today
    from itertools import chain
    import pytz

    helper = RecomHelper()
    
    user = User.objects.get(pk=user_id)
    profile = user.get_profile()

    for r in helper.get_ranking()[:settings.FAST_RECOMMENDATIONS_NUMBER_OF_TOP_FILMS]:
        count_guessed_rate(user, r.film)

    profile.recommendations_status = profile.FAST_RECOMMENDATIONS
    profile.save()

    from film20.core.deferred import defer
    defer(compute_fast_recommendations_phase2, user_id, send_notice)
예제 #28
0
파일: movie.py 프로젝트: manlan2/filmaster
def show_movies_slider_widget(limit=settings.NUMBER_OF_MOVIES_FOR_WIDGET):
    CACHE_RANDOM_FILMS = 'random_films_for_tag'
    CACHE_FILMS_FOR_TAG = 'films_for_tag'
    CACHE_LINKS_FOR_GENRE = 'links_for_genre'

    tags = Film.get_top_tags()
    key = 'tag'
    key += "_".join(str(tag.id) for tag in tags)

    films_for_tags = cache.get_cache(CACHE_FILMS_FOR_TAG, key)
    films_list = cache.get_cache(CACHE_RANDOM_FILMS, films_for_tags)
    if not films_list:
        films_list = []
        if not films_for_tags:
            films_for_tags = []
            for tag in tags:
                rh = RecomHelper()
                films = rh.get_films_for_tag(str(tag), order_by="-popularity")
                films = films.filter(image__isnull=False)
                films_for_tags.append(films[:100])
            cache.set_cache(CACHE_FILMS_FOR_TAG, key, films_for_tags)

        for films in films_for_tags:
            films = list(films)
            random.shuffle(films)
            films = films[:limit]
            films_list += films
        cache.set_cache(CACHE_RANDOM_FILMS, films_for_tags, films_list,
                        CACHE_HOUR)

    links_list = cache.get_cache(CACHE_LINKS_FOR_GENRE, key)
    if not links_list:
        links_list = []
        for tag in tags:
            links = reverse('movies_menu', args=(tag.name, ))
            links_list.append(links)
        cache.set_cache(CACHE_LINKS_FOR_GENRE, key, links_list)

    return {'films': films_list, 'tags': tags, 'links': links_list}
예제 #29
0
파일: movie.py 프로젝트: manlan2/filmaster
def top_recommendations_all(context, films_number=4):
    """
        Displays user's top recommended movies
        (most popular for not logged in).
    """
    POPULAR_FILMS_NUMBER_ALL = getattr(settings,
                                       'POPULAR_FILMS_MAIN_PAGE_NUMBER_ALL')

    user = context.get('recommendations_user', context['request'].user)
    key = cache.Key("popular_films_main_page", user)

    films = cache.get(key)
    if (not films) or len(films) < films_number:

        key_all = cache.Key("popular_films_main_page_all", user)
        all_films = cache.get(key_all)
        if not all_films:
            has_recommendations = user.is_authenticated() and \
                    user.get_profile().recommendations_status
            if has_recommendations:
                recom_helper = RecomHelper()
                all_films = list(
                    recom_helper.get_best_psi_films_queryset(user)
                    [:POPULAR_FILMS_NUMBER_ALL])
            else:
                fhelper = FilmHelper()
                all_films = list(
                    fhelper.get_popular_films(
                        number_of_films=POPULAR_FILMS_NUMBER_ALL,
                        exclude_nonEnglish=True))

            cache.set(key_all, all_films, cache.A_MONTH)

        # Select random few films
        random.shuffle(all_films)
        films = all_films[:films_number]
        cache.set(key, films, cache.A_QUARTER)

    return films[:films_number]
예제 #30
0
파일: movie.py 프로젝트: thuvh/filmmaster
def top_recommendations_all(context, films_number=4):
    """
        Displays user's top recommended movies
        (most popular for not logged in).
    """
    POPULAR_FILMS_NUMBER_ALL = getattr(settings,
            'POPULAR_FILMS_MAIN_PAGE_NUMBER_ALL')

    user = context['request'].user
    key = cache.Key("popular_films_main_page", user)

    films = cache.get(key)
    if (not films) or len(films) < films_number:

        key_all = cache.Key("popular_films_main_page_all", user)
        all_films = cache.get(key_all)
        if not all_films:
            has_recommendations = user.is_authenticated() and \
                    user.get_profile().recommendations_status
            if has_recommendations:
                recom_helper = RecomHelper()
                all_films = list(recom_helper.get_best_psi_films_queryset(
                    user_id = user.id, offset=0,
                    limit=POPULAR_FILMS_NUMBER_ALL))
            else:
                fhelper = FilmHelper()
                all_films = list(fhelper.get_popular_films(
                        number_of_films=POPULAR_FILMS_NUMBER_ALL,
                        exclude_nonEnglish=True))

            cache.set(key_all, all_films, cache.A_MONTH)

        # Select random few films
        random.shuffle(all_films)
        films = all_films[:films_number]
        cache.set(key, films, cache.A_QUARTER)

    return films[:films_number]
예제 #31
0
파일: movie.py 프로젝트: thuvh/filmmaster
def show_movies_slider_widget(limit=settings.NUMBER_OF_MOVIES_FOR_WIDGET):
    CACHE_RANDOM_FILMS = 'random_films_for_tag'
    CACHE_FILMS_FOR_TAG = 'films_for_tag'
    CACHE_LINKS_FOR_GENRE = 'links_for_genre'

    tags = Film.get_top_tags()
    key = 'tag'
    key += "_".join(str(tag.id) for tag in tags)

    films_for_tags = cache.get_cache(CACHE_FILMS_FOR_TAG, key)
    films_list = cache.get_cache(CACHE_RANDOM_FILMS, films_for_tags)
    if not films_list:
        films_list = []
        if not films_for_tags:
            films_for_tags = []
            for tag in tags:
                rh = RecomHelper()
                films = rh.get_films_for_tag(str(tag), order_by="-popularity")
                films = films.filter(image__isnull = False)
                films_for_tags.append(films[:100])
            cache.set_cache(CACHE_FILMS_FOR_TAG, key, films_for_tags)

        for films in films_for_tags:
            films = list(films)
            random.shuffle(films)
            films = films[:limit]
            films_list += films
        cache.set_cache(CACHE_RANDOM_FILMS, films_for_tags, films_list, CACHE_HOUR)

    links_list = cache.get_cache(CACHE_LINKS_FOR_GENRE, key)
    if not links_list:
        links_list = []
        for tag in tags:
            links = reverse('movies_menu', args=(tag.name,))
            links_list.append(links)
        cache.set_cache(CACHE_LINKS_FOR_GENRE, key, links_list)

    return {'films':films_list, 'tags': tags, 'links': links_list}
예제 #32
0
def compute_fast_recommendations(user_id, send_notice=True):
    from recom_helper import RecomHelper
    from film20.core.models import Recommendation
    from film20.showtimes.showtimes_helper import get_films
    from film20.showtimes.models import Channel
    from film20.showtimes.utils import get_today
    from itertools import chain
    import pytz

    helper = RecomHelper()

    user = User.objects.get(pk=user_id)
    profile = user.get_profile()

    for r in helper.get_ranking()[: settings.FAST_RECOMMENDATIONS_NUMBER_OF_TOP_FILMS]:
        count_guessed_rate(user, r.film)

    profile.recommendations_status = profile.FAST_RECOMMENDATIONS
    profile.save()

    from film20.core.deferred import defer

    defer(compute_fast_recommendations_phase2, user_id, send_notice)
예제 #33
0
    def test_enrich_query_with_tags(self):
        print "Test enrich query with tags"
        recom_helper = RecomHelper()
        film_helper = FilmHelper()

        comedies = recom_helper.get_films_for_tag('comedy')
        scifis = recom_helper.get_films_for_tag('sci-fi')
        horrors = recom_helper.get_films_for_tag('horror')
        thrillers = recom_helper.get_films_for_tag('thriller')
        dramas = recom_helper.get_films_for_tag('drama')
        fantasies = recom_helper.get_films_for_tag('fantasy')
        mysteries = recom_helper.get_films_for_tag('mystery')
        animations = recom_helper.get_films_for_tag('animation')
        series = recom_helper.get_films_for_tag('series')

        self.assertEquals(len(comedies), 5)
        self.assertEquals(len(scifis), 6)
        self.assertEquals(len(horrors), 3)
        self.assertEquals(len(thrillers), 4)
        self.assertEquals(len(dramas), 4)
        self.assertEquals(len(fantasies), 3)
        self.assertEquals(len(mysteries), 2)
        self.assertEquals(len(animations), 3)
        self.assertEquals(len(series), 4)
예제 #34
0
    def test_get_all_ratings(self):
        recom_helper = RecomHelper()
        film_helper = FilmHelper()

        film_with_director_and_actor = Film.objects.filter(title__startswith="Added film part 2")
        related_directors = film_helper.get_film_directors(film_with_director_and_actor[0])
        related_characters = film_helper.get_film_actors(film_with_director_and_actor[0])
        related_actors = []
        for character in related_characters:
            actor = character.person
            related_actors.append(actor)

        non_rated_films = Film.objects.filter(rating__isnull=True, title__startswith="Added")

        POST = {}
        # POST['form_id'] = '1'
        POST["rating"] = "6"
        POST["object_id"] = str(non_rated_films[1].parent.id)
        POST["form_type"] = str(Rating.TYPE_FILM)
        POST["cancel_rating"] = "0"
        rating_form = RatingForm(POST)
        if rating_form.is_valid():
            rating_helper.add_edit_rating(rating_form, self.u1)
        else:
            print "RATING FORM INVALID!"

        all_ratings = recom_helper.get_all_ratings(self.u1.id)
        self.assertEquals(len(all_ratings), 31)

        director_ratings = recom_helper.get_all_ratings(self.u1.id, related_director=related_directors)
        self.assertEquals(len(director_ratings), 1)

        actor_ratings = recom_helper.get_all_ratings(self.u1.id, related_actor=related_actors)
        self.assertEquals(len(actor_ratings), 1)

        from_ratings = recom_helper.get_all_ratings(self.u1.id, year_from=1990)
        self.assertEquals(len(from_ratings), 23)

        to_ratings = recom_helper.get_all_ratings(self.u1.id, year_to=2000)
        self.assertEquals(len(to_ratings), 22)

        popularity_ratings = recom_helper.get_all_ratings(self.u1.id, popularity=5)
        self.assertEquals(len(popularity_ratings), 8)

        tag_ratings = recom_helper.get_all_ratings(self.u1.id, tags="comedy")
        self.assertEquals(len(tag_ratings), 5)
예제 #35
0
    def get_context_data(self, **kwargs):
        context = super(FilterSpecsForm, self).get_context_data(**kwargs)

        genre = self.get_genre()
        default_filter = None
        recom_helper = RecomHelper()
        is_valid, fake_film_specs_form, film_specs_form = self.get_specs_form()

        if is_valid:
            default_filter = fake_film_specs_form.is_empty_form()

        context['film_specs_form'] = film_specs_form
        context['fake_film_specs_form'] = fake_film_specs_form
        context['default_filter'] = default_filter
        context['genre'] = genre
        context['tv_series'] = self.kwargs.get('tv_series')
        return context
예제 #36
0
    def test_enrich_query_with_tags(self):
        print "Test enrich query with tags"
        recom_helper = RecomHelper()
        film_helper = FilmHelper()

        comedies = recom_helper.get_films_for_tag("comedy")
        scifis = recom_helper.get_films_for_tag("sci-fi")
        horrors = recom_helper.get_films_for_tag("horror")
        thrillers = recom_helper.get_films_for_tag("thriller")
        dramas = recom_helper.get_films_for_tag("drama")
        fantasies = recom_helper.get_films_for_tag("fantasy")
        mysteries = recom_helper.get_films_for_tag("mystery")
        animations = recom_helper.get_films_for_tag("animation")
        series = recom_helper.get_films_for_tag("series")

        self.assertEquals(len(comedies), 5)
        self.assertEquals(len(scifis), 6)
        self.assertEquals(len(horrors), 3)
        self.assertEquals(len(thrillers), 4)
        self.assertEquals(len(dramas), 4)
        self.assertEquals(len(fantasies), 3)
        self.assertEquals(len(mysteries), 2)
        self.assertEquals(len(animations), 3)
        self.assertEquals(len(series), 4)
예제 #37
0
    def test_enrich_query_with_tags(self):
        print "Test enrich query with tags"
        recom_helper = RecomHelper()
        film_helper = FilmHelper()

        comedies = recom_helper.get_films_for_tag('comedy')
        scifis = recom_helper.get_films_for_tag('sci-fi')
        horrors = recom_helper.get_films_for_tag('horror')
        thrillers = recom_helper.get_films_for_tag('thriller')
        dramas = recom_helper.get_films_for_tag('drama')
        fantasies = recom_helper.get_films_for_tag('fantasy')
        mysteries = recom_helper.get_films_for_tag('mystery')
        animations = recom_helper.get_films_for_tag('animation')
        series = recom_helper.get_films_for_tag('series')

        self.assertEquals(len(comedies), 5)
        self.assertEquals(len(scifis), 6)
        self.assertEquals(len(horrors), 3)
        self.assertEquals(len(thrillers), 4)
        self.assertEquals(len(dramas), 4)
        self.assertEquals(len(fantasies), 3)
        self.assertEquals(len(mysteries), 2)
        self.assertEquals(len(animations), 3)
        self.assertEquals(len(series), 4)
예제 #38
0
파일: movie.py 프로젝트: manlan2/filmaster
def short_reviews(context, limit=10, param=None, argument=None):
    """
        Configurable widget displaying short reviews
        Takes te following arguments:
        - list of films (can be none), param is "films" and argument is a
        list of film objects
        - film genre (can be none), param is genre and argument is a
        string with film genre
        - if both are none it displays recent last month hand-selected reviews
    """
    request = context['request']
    key = "short_reviews"
    key_params = "short_reviews_params"
    key_films = "films_for_tag"

    if param == "films":
        if argument:
            key += "_".join(film.permalink for film in argument
                            if film and film.pk)

    films = cache.get_cache(CACHE_ACTIVITIES, key_films)
    if param == 'genre':
        if not films:
            rh = RecomHelper()
            films = rh.get_films_for_tag(argument,
                                         limit=500,
                                         order_by="-popularity")
            key_films += "_".join(film.permalink for film in films
                                  if film and film.pk)
            cache.set_cache(CACHE_ACTIVITIES, key_films, films)

    # -- check if path contains tags --
    request_tags = request.GET.get("tags", "")
    request_path = request.META.get("PATH_INFO", "")

    if urls['TAG'] in request_path.lower():
        request_path = request_path.strip(urls['TAG'])
    else:
        request_path = ""

    if param == "genre":
        if request_tags:
            argument = request_tags
        if request_path:
            argument = request_path
        key += "_%s" % argument

    query = cache.get_cache(CACHE_ACTIVITIES, key)
    params = cache.get_cache(CACHE_ACTIVITIES, query)

    if not query:
        params = True
        if param == "films":
            query = UserActivity.objects.select_related(
                'user', 'film', 'short_review').filter(
                    activity_type=UserActivity.TYPE_SHORT_REVIEW,
                    film__in=argument,
                    #featured = True,
                ).order_by("-created_at")[:limit]

        if param == "genre":
            query = UserActivity.objects.select_related(
                'user', 'film', 'short_review').filter(
                    activity_type=UserActivity.TYPE_SHORT_REVIEW,
                    film__in=films,
                    #featured = True,
                ).order_by("-created_at")[:limit]

        if not query:
            params = False
            query = UserActivity.objects.select_related(
                'user', 'film', 'short_review').filter(
                    activity_type=UserActivity.TYPE_SHORT_REVIEW,
                    #featured = True,
                ).order_by("-created_at")[:limit]

        query = list(query)
        random.shuffle(query)
        cache.set_cache(CACHE_ACTIVITIES, key, query, CACHE_HOUR * 3)
        cache.set_cache(CACHE_ACTIVITIES, query, params, CACHE_HOUR * 3)

    return {'activities': query, 'params': params}
예제 #39
0
파일: views.py 프로젝트: manlan2/filmaster
def show_blog_post(request, permalink, user_name):
    profile = None
    user_comparator = None
    author_ratings = None

    logger.debug(user_name)
    logger.debug(request.build_absolute_uri())
    try:
        user = User.objects.get(username__iexact=user_name)
        username = user.username
        other_user = user
        profile = user.get_profile()               
    except:
        raise Http404

    if request.user == other_user:
        is_me = True
    else:
        is_me = False

    if _("preview") in request.GET and request.user==user:
        posts = Post.objects.filter(user__username__iexact=user_name, permalink = permalink).exclude(status=Post.DELETED_STATUS)
        logger.debug(posts)
        if len(posts)==0:
            raise Http404
        else:
            post = posts[0]    
    else:
        try:
            post = Post.objects.select_related().get(user__username__iexact=user_name,
                                                     permalink = permalink, status=Post.PUBLIC_STATUS)
        except:
            raise Http404
            
    #profile = post.author.user.get_profile()
    related_films = None
    related_people = None
    other_user_posts = Post.objects.select_related().filter(user=user, status=Post.PUBLIC_STATUS)\
                                                    .exclude(id=post.id)[:MAX_RELATED_REVIEWS]
    other_posts_for_film = None
    related_films = post.related_film.select_related()
    
    the_film = None # to be used for ratings
    for related_film in related_films:
        the_film = related_film       
        related_posts = Post.objects.select_related().filter(related_film=related_film,\
                                                             status=Post.PUBLIC_STATUS)\
                                                      .exclude(id=post.id)[:MAX_RELATED_REVIEWS]
        if related_posts != None:
            if len(related_posts)>0:
                other_posts = [related_film, related_posts]
                if other_posts_for_film == None:
                    other_posts_for_film = []
                other_posts_for_film.append(other_posts)
        
    related_people = post.related_person.select_related()
    
    if (len(related_films) == 1) & (the_film != None):
        from film20.core import rating_helper
        author_ratings = rating_helper.get_ratings_for_user_and_film(user, the_film)


    # get the comparator
    if request.user.is_authenticated():      
        recom_helper = RecomHelper()      
        rating_comparator = recom_helper.get_rating_comparator_for_user(request.user, user)
        if rating_comparator!= None:
            user_comparator = UserComparator(rating_comparator.score)

    from film20.useractivity.watching_helper import WatchingHelper
    subscribe_form = None
    subscribe_action = None
    # subscription form
    if request.user.is_authenticated():     
        watching_helper = WatchingHelper()
        subscribe_action = watching_helper.get_subscribe_action(request.user, post)
        subscribe_form = watching_helper.get_subscribe_form(post, subscribe_action)
    
    data = {
        'post' : post, 
        'related_films' : related_films, 
        'related_people' : related_people,
        'profile':profile,
        'other_user_posts':other_user_posts,
        'other_posts_for_film':other_posts_for_film, 
        'author_ratings' : author_ratings,
        'user_comparator': user_comparator,

        'subscribe_form': subscribe_form,
        'subscribe_action': subscribe_action,
        
        # friendship
        "is_me": is_me,
        "is_friend": None,
        "invite_form": None,
        "other_friends": None,
        "other_user": other_user,
        "previous_invitations_to": None,
        "previous_invitations_from": None,
    }

    return render_to_response(templates['SHOW_NOTE'],
        data, 
        context_instance=RequestContext(request))
예제 #40
0
    def test_planet_tag(self):
        # --- Initialize ---
        self.initialize()
        helper_without_tags = PlanetTagHelper()
        helper_with_tags = PlanetTagHelper(tag='comedy')
        recom_helper = RecomHelper()
        user_activity_helper = UserActivityHelper()

        # --- setup followers ---
        self.u1.followers.follow(self.u2)
        self.u1.followers.follow(self.u3)
        self.u1.followers.follow(self.u4)

        # similar users
        from film20.recommendations.bot_helper import do_create_comparators
        self.films_for_comparator()
        do_create_comparators()

        friends_list = recom_helper.get_following_ids_as_list(self.u1)
        friends_without_activities = helper_without_tags.planet_tag_friends(friends_list)
        self.assertEquals(len(friends_without_activities), 0)
        
        similar_users_list = user_activity_helper.get_similar_users_list(request)
        similar_users_without_tags = helper_without_tags.planet_tag_similar_users(similar_users_list)
        self.assertEquals(len(similar_users_without_tags), 0)

        notes_without_tags = helper_without_tags.planet_tag_notes()
        self.assertEquals(len(notes_without_tags), 0)

        all_planet_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_planet_activities), 0)

        # --- setup User activities ---
        post = Post()
        post.title = "Lorem ipsum"
        post.permalink = "lorem-ipsum"
        post.body = "siala lala tralala"
        post.user = self.u1
        post.status = Object.PUBLIC_STATUS
        post.type = Object.TYPE_POST
        post.save()
        post.related_film.add(self.film)
        post.save()
        
        all_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_activities), 1)
        
        post = Post()
        post.title = "Lorem ipsum"
        post.permalink = "lorem-ipsum"
        post.body = "siala lala tralala"
        post.user = self.u1
        post.status = Object.PUBLIC_STATUS
        post.type = Object.TYPE_POST
        post.save()
        post.related_film.add(self.film1)
        post.save()
        
        all_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_activities), 2)
                
        obj = Object.objects.get(id=self.film2.id)
        shortreview = ShortReview()
        shortreview.user = self.u1
        shortreview.review_text = "sialala bumcyk cyk"
        shortreview.status = Object.PUBLIC_STATUS
        shortreview.type = Object.TYPE_SHORT_REVIEW
        shortreview.object = obj
        shortreview.kind = ShortReview.REVIEW
        shortreview.save()

        all_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_activities), 3)
        
        # Activities with 'comedy' tag
        all_activities_with_tags = helper_with_tags.planet_tag_all()
        self.assertEquals(len(all_activities_with_tags), 1)

        # --- setup followers activities ---
        post = Post()
        post.title = "#1 Lorem ipsum"
        post.permalink = "lorem-ipsum"
        post.body = "siala lala tralala"
        post.user = self.u2
        post.status = Object.PUBLIC_STATUS
        post.type = Object.TYPE_POST
        post.save()
        post.related_film.add(self.film)
        post.save()

        all_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_activities), 4)

        post = Post()
        post.title = "#2 Lorem ipsum"
        post.permalink = "lorem-ipsum"
        post.body = "siala lala tralala"
        post.user = self.u3
        post.status = Object.PUBLIC_STATUS
        post.type = Object.TYPE_POST
        post.save()
        post.related_film.add(self.film1)
        post.save()

        all_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_activities), 5)

        obj = Object.objects.get(id=self.film2.id)
        shortreview = ShortReview()
        shortreview.user = self.u4
        shortreview.review_text = "sialala bumcyk cyk"
        shortreview.status = Object.PUBLIC_STATUS
        shortreview.type = Object.TYPE_SHORT_REVIEW
        shortreview.object = obj
        shortreview.kind = ShortReview.REVIEW
        shortreview.save()

        all_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_activities), 6)

        activities_with_tags = helper_with_tags.planet_tag_all()
        self.assertEquals(len(activities_with_tags), 2)

        all_friends_activities = helper_without_tags.planet_tag_friends(friends_list)
        self.assertEquals(len(all_friends_activities), 3)
        friends_activities_with_tag = helper_with_tags.planet_tag_friends(friends_list)
        self.assertEquals(len(friends_activities_with_tag), 1)

        # --- Check notes ---
        all_planet_notes = helper_without_tags.planet_tag_notes()
        self.assertEquals(len(all_planet_notes), 4)

        # Post notes with 'comedy' tag
        notes_activities_with_tag = helper_with_tags.planet_tag_notes()
        self.assertEquals(len(notes_activities_with_tag), 2)

        similar_users_activities = helper_without_tags.planet_tag_similar_users(similar_users_list)
        self.assertEquals(len(similar_users_activities), 2)

        users_with_tags = helper_with_tags.planet_tag_similar_users(similar_users_list)
        self.assertEquals(len(users_with_tags), 1)
        
        activities = UserActivity.objects.all() 
예제 #41
0
    def test_get_recently_popular_films_query(self):
        print "Test get recently popular films query"
        """
           Test for query which gets the most popular films for the rating machine.
           First it should return all films, then we rate one and in the second call
           it should only retrieve the other film.
        """

        recom_helper = RecomHelper()
        film_helper = FilmHelper()

        u1_result = recom_helper.get_recently_popular_films_query(self.u1.id)
        self.assertEquals(len(u1_result), 2)

        u2_result = recom_helper.get_recently_popular_films_query(self.u2.id)
        self.assertEquals(len(u2_result), 12)

        film_with_director_and_actor = Film.objects.filter(title__startswith="Added film part 1")
        related_directors = film_helper.get_film_directors(film_with_director_and_actor[0])
        related_characters = film_helper.get_film_actors(film_with_director_and_actor[0])
        related_actors = []
        for character in related_characters:
            actor = character.person
            related_actors.append(actor)

        POST = {}
        # TODO check why it starts breaking (form invalid) when form_id is set
        # POST['form_id'] = '1'
        POST["rating"] = "6"
        POST["object_id"] = str(self.f12.parent.id)
        POST["form_type"] = str(Rating.TYPE_FILM)
        POST["cancel_rating"] = "0"
        rating_form = RatingForm(POST)
        if rating_form.is_valid():
            rating_helper.add_edit_rating(rating_form, self.u2)
        else:
            print "RATING FORM INVALID!"

        result = recom_helper.get_recently_popular_films_query(self.u2.id)
        self.assertEquals(len(result), 11)

        # test filtering
        result = recom_helper.get_recently_popular_films_query(self.u5.id)
        self.assertEquals(len(result), 32)

        result = recom_helper.get_recently_popular_films_query(self.u5.id, year_from="1990")
        self.assertEquals(len(result), 24)

        result = recom_helper.get_recently_popular_films_query(self.u5.id, year_to="2000")
        self.assertEquals(len(result), 22)

        result = recom_helper.get_recently_popular_films_query(self.u5.id, year_from="1990", year_to="2000")
        self.assertEquals(len(result), 14)

        result = recom_helper.get_recently_popular_films_query(self.u5.id, popularity="10")
        self.assertEquals(len(result), 8)

        result = recom_helper.get_recently_popular_films_query(
            self.u5.id, year_from="1990", year_to="2000", popularity="10"
        )
        self.assertEquals(len(result), 4)

        rated_films = [self.f1.id, self.f3.id, self.f5.id, self.f7.id, self.f9.id]
        result = recom_helper.get_recently_popular_films_query(self.u5.id, rated_films=rated_films)
        self.assertEquals(len(result), 27)

        result = recom_helper.get_recently_popular_films_query(
            self.u5.id, year_from="1990", year_to="2000", rated_films=rated_films, popularity="10"
        )
        self.assertEquals(len(result), 2)

        result = recom_helper.get_recently_popular_films_query(self.u5.id, related_director=related_directors)
        self.assertEquals(len(result), 1)

        result = recom_helper.get_recently_popular_films_query(self.u5.id, related_actor=related_actors)
        self.assertEquals(len(result), 2)

        result = recom_helper.get_recently_popular_films_query(
            self.u5.id, related_director=related_directors, related_actor=related_actors
        )
        self.assertEquals(len(result), 1)

        result = recom_helper.get_recently_popular_films_query(
            self.u5.id,
            year_from="1990",
            year_to="2011",
            related_director=related_directors,
            related_actor=related_actors,
        )
        self.assertEquals(len(result), 1)
예제 #42
0
class PlanetTagHelper(UserActivityHelper):

    tag = None
    recom_helper = None

    def __init__(self, limit=None, tag=None):
        self.limit = limit
        self.tag = tag
        self.recom_helper = RecomHelper()

    def __perform_queries(self, query_with_tags):
        select_query = query_with_tags['select'] if query_with_tags['select'] is not None else ''
        from_query = query_with_tags['from'] if query_with_tags['from'] is not None else ''
        join_query = query_with_tags['join'] if query_with_tags['join'] is not None else ''
        where_query = query_with_tags['where'] if query_with_tags['where'] is not None else ''
        order_by = query_with_tags['order_by'] if query_with_tags['order_by'] is not None else ''

        query = select_query + from_query + join_query + where_query + order_by
        params = query_with_tags['params']
        return query, params

    def __execute_queries(self, query, params):
        activities = UserActivity.objects.raw(query, params)
        query = list(activities)[:self.limit]
        return query

    def planet_tag_friends(self, friends_list):
        
        if len(friends_list) == 0:
            friends_list = [0]
        
        select_query = 'SELECT DISTINCT "useractivity_useractivity".* '
        from_query = ' FROM "useractivity_useractivity" '
        join_query = ''' LEFT OUTER JOIN "blog_post" ON ("useractivity_useractivity"."post_id" = "blog_post"."parent_id")
         LEFT OUTER JOIN "core_object" ON ("blog_post"."parent_id" = "core_object"."id") '''
        where_query = ' WHERE ("useractivity_useractivity"."LANG" = %(lang)s AND '
        where_query += ' "useractivity_useractivity"."user_id" IN (%s) ' %str(friends_list)[1:-1]
        where_query += ' AND (("core_object"."status" = %(public_status)s  AND "useractivity_useractivity"."activity_type" = %(type_post)s ) OR "useractivity_useractivity"."activity_type" = %(type_short_review)s  OR "useractivity_useractivity"."activity_type" = %(type_comment)s ))'
        order_by = ' ORDER BY created_at DESC'
        params = {'lang':str(LANGUAGE_CODE), 'public_status': str(Post.PUBLIC_STATUS), 'type_post': str(UserActivity.TYPE_POST), 'type_short_review': str(UserActivity.TYPE_SHORT_REVIEW), 'type_comment': str(UserActivity.TYPE_COMMENT)}

        query_planet_tag_friends = {
            'select': select_query,
            'from': from_query,
            'join': join_query,
            'where': where_query,
            'order_by': order_by,
            'limit_and_offset': None,
            'params': params
        }
        query_with_tags = self.recom_helper.enrich_query_with_tags(query_planet_tag_friends, self.tag, film_id_string="useractivity_useractivity.film_id")
        query, params = self.__perform_queries(query_with_tags)
        activities = self.__execute_queries(query, params)
        return activities

    def planet_tag_similar_users(self, similar_users):
        
        similar_users_list = []
        for user in similar_users:
            similar_users_list.append(user.id)
        
        if len(similar_users_list) == 0:
            similar_users_list = [0]
        
        select_query = 'SELECT DISTINCT "useractivity_useractivity".* '
        from_query = ' FROM "useractivity_useractivity" '
        join_query = ''' LEFT OUTER JOIN "blog_post" ON ("useractivity_useractivity"."post_id" = "blog_post"."parent_id")
         LEFT OUTER JOIN "core_object" ON ("blog_post"."parent_id" = "core_object"."id") '''
        where_query = ' WHERE ("useractivity_useractivity"."LANG" = %(lang)s '
        where_query += ' AND "useractivity_useractivity"."user_id" IN ( %s ) ' % str(similar_users_list)[1:-1]
        where_query += ' AND (("core_object"."status" = %(public_status)s  AND "useractivity_useractivity"."activity_type" = %(type_post)s ) OR "useractivity_useractivity"."activity_type" = %(type_short_review)s  OR "useractivity_useractivity"."activity_type" = %(type_comment)s )) '
        order_by = ' ORDER BY "useractivity_useractivity"."created_at" DESC'
        params = {'lang': str(LANGUAGE_CODE), 'public_status': str(Post.PUBLIC_STATUS), 'type_post': str(UserActivity.TYPE_POST), 'type_short_review': str(UserActivity.TYPE_SHORT_REVIEW), 'type_comment': str(UserActivity.TYPE_COMMENT)}

        query_planet_tag_similar_users = {
            'select': select_query,
            'from': from_query,
            'join': join_query,
            'where': where_query,
            'order_by': order_by,
            'limit_and_offset': None,
            'params': params
        }

        query_with_tags = self.recom_helper.enrich_query_with_tags(query_planet_tag_similar_users, self.tag, film_id_string="useractivity_useractivity.film_id")
        query, params = self.__perform_queries(query_planet_tag_similar_users)
        activities = self.__execute_queries(query, params)
        return activities

    def planet_tag_reviews(self):
        select_query = 'SELECT "useractivity_useractivity".* '
        from_query = ' FROM "useractivity_useractivity" '
        join_query = ''
        where_query = ' WHERE ("useractivity_useractivity"."LANG" = %(lang)s AND "useractivity_useractivity"."activity_type" = %(activity_type)s) '
        order_by = ' ORDER BY "created_at" DESC'
        params = {'lang':str(LANGUAGE_CODE), 'activity_type':str(UserActivity.TYPE_SHORT_REVIEW)}

        query_planet_tag_reviews = {
            'select': select_query,
            'from': from_query,
            'join': join_query,
            'where': where_query,
            'order_by': order_by,
            'limit_and_offset': None,
            'params': params
        }

        query_with_tags = self.recom_helper.enrich_query_with_tags(query_planet_tag_reviews, self.tag, film_id_string="useractivity_useractivity.film_id")
        query, params = self.__perform_queries(query_with_tags)
        activities = self.__execute_queries(query, params)
        return activities

    def planet_tag_notes(self):
        select_query = 'SELECT DISTINCT "useractivity_useractivity".* '
        from_query = ' FROM "useractivity_useractivity" '
        join_query = ''' LEFT OUTER JOIN "blog_post" ON ("useractivity_useractivity"."post_id" = "blog_post"."parent_id")
             LEFT OUTER JOIN "core_object" ON ("blog_post"."parent_id" = "core_object"."id")
             INNER JOIN "blog_post_related_film" ON ("blog_post"."parent_id" = "blog_post_related_film"."post_id")
             INNER JOIN "core_film" ON ("blog_post_related_film"."film_id" = "core_film"."parent_id")
             INNER JOIN "core_object" T6 ON ("core_film"."parent_id" = T6."id") '''
        where_query = ' WHERE ("useractivity_useractivity"."LANG" = %(lang)s AND "core_object"."status" = 1  AND T6."status" = 1  AND "useractivity_useractivity"."activity_type" = 1  AND NOT (("core_object"."status" = 2  AND NOT ("blog_post"."parent_id" IS NULL))) AND NOT (("core_object"."status" = 3  AND NOT ("blog_post"."parent_id" IS NULL)))) '
        order_by = ' ORDER BY "created_at" DESC'
        params = {'lang':str(settings.LANGUAGE_CODE), 'draft_status':str(Post.DRAFT_STATUS), 'deleted_status':str(Post.DELETED_STATUS), 'activity_type': str(UserActivity.TYPE_SHORT_REVIEW)}

        query_planet_tag_notes = {
            'select': select_query,
            'from': from_query,
            'join': join_query,
            'where': where_query,
            'order_by': order_by,
            'limit_and_offset': None,
            'params': params
        }

        query_with_tags = self.recom_helper.enrich_query_with_tags(query_planet_tag_notes, self.tag, film_id_string="blog_post_related_film.film_id" )
        query, params = self.__perform_queries(query_with_tags)
        activities = self.__execute_queries(query, params)
        return activities

    def planet_tag_comments(self):
        select_query = 'SELECT "useractivity_useractivity".* '
        from_query = ' FROM "useractivity_useractivity" '
        join_query = ''
        where_query = ' WHERE ("useractivity_useractivity"."LANG" = %(lang)s  AND "useractivity_useractivity"."activity_type" = %(activity_type)s) '
        order_by = ' ORDER BY "created_at" DESC'
        params = {'lang':str(LANGUAGE_CODE), 'activity_type':str(UserActivity.TYPE_COMMENT)}

        query_planet_tag_comments = {
            'select': select_query,
            'from': from_query,
            'join': join_query,
            'where': where_query,
            'order_by': order_by,
            'limit_and_offset': None,
            'params': params
        }

        query_with_tags = self.recom_helper.enrich_query_with_tags(query_planet_tag_comments, self.tag, film_id_string="useractivity_useractivity.film_id" )
        query, params = self.__perform_queries(query_with_tags)
        activities = self.__execute_queries(query, params)
        return activities

    def planet_tag_all(self):
        select_query = 'SELECT DISTINCT "useractivity_useractivity".* '
        from_query = ' FROM "useractivity_useractivity" '
        join_query = ''' LEFT OUTER JOIN "blog_post" ON ("useractivity_useractivity"."post_id" = "blog_post"."parent_id")
         LEFT OUTER JOIN "core_object" ON ("blog_post"."parent_id" = "core_object"."id")
         LEFT OUTER JOIN "blog_post_related_film" ON ("blog_post"."parent_id" = "blog_post_related_film"."post_id")
         LEFT OUTER JOIN "core_film" ON ("blog_post_related_film"."film_id" = "core_film"."parent_id")
         LEFT OUTER JOIN "core_object" T6 ON ("core_film"."parent_id" = T6."id") '''
        where_query = ' WHERE ("useractivity_useractivity"."LANG" = %(lang)s  AND (("core_object"."status" = 1  AND T6."status" = 1  AND "useractivity_useractivity"."activity_type" = 1 ) OR "useractivity_useractivity"."activity_type" = 2  OR "useractivity_useractivity"."activity_type" = 3 )) '
        order_by = ' ORDER BY "created_at" DESC'
        params = {'lang':str(LANGUAGE_CODE)}

        query_planet_tag_all = {
            'select': select_query,
            'from': from_query,
            'join': join_query,
            'where': where_query,
            'order_by': order_by,
            'limit_and_offset': None,
            'params': params
        }

        query_with_tags = self.recom_helper.enrich_query_with_tags(query_planet_tag_all, self.tag, film_id_string="useractivity_useractivity.film_id" )
        query, params = self.__perform_queries(query_with_tags)
        activities = self.__execute_queries(query, params)
        return activities

    def planet_tag_favourites(self, request):
        # Removed in http://jira.filmaster.org/browse/FLM-1079
        return None
예제 #43
0
    def test_get_recently_popular_films_query(self):
        print "Test get recently popular films query"
        """
           Test for query which gets the most popular films for the rating machine.
           First it should return all films, then we rate one and in the second call
           it should only retrieve the other film.
        """

        recom_helper = RecomHelper()
        film_helper = FilmHelper()

        u1_result = recom_helper.get_recently_popular_films_query(self.u1.id)
        self.assertEquals(len(u1_result), 2)

        u2_result = recom_helper.get_recently_popular_films_query(self.u2.id)
        self.assertEquals(len(u2_result), 12)

        film_with_director_and_actor = Film.objects.filter(
            title__startswith="Added film part 1")
        related_directors = film_helper.get_film_directors(
            film_with_director_and_actor[0])
        related_characters = film_helper.get_film_actors(
            film_with_director_and_actor[0])
        related_actors = []
        for character in related_characters:
            actor = character.person
            related_actors.append(actor)

        POST = {}
        # TODO check why it starts breaking (form invalid) when form_id is set
        #POST['form_id'] = '1'
        POST['rating'] = '6'
        POST['object_id'] = str(self.f12.parent.id)
        POST['form_type'] = str(Rating.TYPE_FILM)
        POST['cancel_rating'] = '0'
        rating_form = RatingForm(POST)
        if rating_form.is_valid():
            rating_helper.add_edit_rating(rating_form, self.u2)
        else:
            print "RATING FORM INVALID!"

        result = recom_helper.get_recently_popular_films_query(self.u2.id)
        self.assertEquals(len(result), 11)

        # test filtering
        result = recom_helper.get_recently_popular_films_query(self.u5.id)
        self.assertEquals(len(result), 32)

        result = recom_helper.get_recently_popular_films_query(
            self.u5.id, year_from='1990')
        self.assertEquals(len(result), 24)

        result = recom_helper.get_recently_popular_films_query(self.u5.id,
                                                               year_to='2000')
        self.assertEquals(len(result), 22)

        result = recom_helper.get_recently_popular_films_query(
            self.u5.id, year_from='1990', year_to='2000')
        self.assertEquals(len(result), 14)

        result = recom_helper.get_recently_popular_films_query(self.u5.id,
                                                               popularity='10')
        self.assertEquals(len(result), 8)

        result = recom_helper.get_recently_popular_films_query(
            self.u5.id, year_from='1990', year_to='2000', popularity='10')
        self.assertEquals(len(result), 4)

        rated_films = [
            self.f1.id, self.f3.id, self.f5.id, self.f7.id, self.f9.id
        ]
        result = recom_helper.get_recently_popular_films_query(
            self.u5.id, rated_films=rated_films)
        self.assertEquals(len(result), 27)

        result = recom_helper.get_recently_popular_films_query(
            self.u5.id,
            year_from='1990',
            year_to='2000',
            rated_films=rated_films,
            popularity='10')
        self.assertEquals(len(result), 2)

        result = recom_helper.get_recently_popular_films_query(
            self.u5.id, related_director=related_directors)
        self.assertEquals(len(result), 1)

        result = recom_helper.get_recently_popular_films_query(
            self.u5.id, related_actor=related_actors)
        self.assertEquals(len(result), 2)

        result = recom_helper.get_recently_popular_films_query(
            self.u5.id,
            related_director=related_directors,
            related_actor=related_actors)
        self.assertEquals(len(result), 1)

        result = recom_helper.get_recently_popular_films_query(
            self.u5.id,
            year_from='1990',
            year_to='2011',
            related_director=related_directors,
            related_actor=related_actors)
        self.assertEquals(len(result), 1)
예제 #44
0
def show_tag_page(request, tag, festival=None):
    """
        Shows a tag page with a list of recent activities for movies tagged with the
        selected tag, its ranking and film recommendations for the tag (for logged in users)
        This is also used for film festival sites as festivals use tags to group films 
        (show_tag_page caled from festivals.views.show_festival)
    """

    if tag == None:
        raise Http404

    recom_helper = RecomHelper()
    ranking = recom_helper.get_ranking(
        type=Rating.TYPE_FILM,
        tags=tag,
        limit=25,  # TODO: customize
        offset=0,
        festival=festival,
    )

    recommended_films = None
    if request.user.is_authenticated():
        logger.debug("User authenticated, getting recommendations")
        recommended_films = recom_helper.get_best_psi_films_queryset(
            request.user,
            tags=tag,
            limit=25,  # TODO: customize
            offset=0,
        )
    else:
        logger.debug("User not authenticated, skipping recommendations")

    from django.db.models import Q
    from film20.useractivity.models import UserActivity
    from film20.blog.models import Post

    select_query = 'SELECT DISTINCT "useractivity_useractivity".* '
    from_query = ' FROM "useractivity_useractivity" '
    join_query = ' LEFT OUTER JOIN "blog_post" ON ("useractivity_useractivity"."post_id" = "blog_post"."parent_id") LEFT OUTER JOIN "core_object" ON ("blog_post"."parent_id" = "core_object"."id") '
    where_query = ' WHERE "useractivity_useractivity"."LANG" = %(language_code)s  AND (("core_object"."status" = %(post_status)s  AND "useractivity_useractivity"."activity_type" = %(useractivity_type_post)s) OR "useractivity_useractivity"."activity_type" = %(useractivity_type_short_review)s  OR "useractivity_useractivity"."activity_type" = %(useractivity_type_comment)s ) '
    order_by = ' ORDER BY "useractivity_useractivity"."created_at" DESC '
    params = {
        'language_code': LANGUAGE_CODE,
        'post_status': Post.PUBLIC_STATUS,
        'useractivity_type_post': UserActivity.TYPE_POST,
        'useractivity_type_short_review': UserActivity.TYPE_SHORT_REVIEW,
        'useractivity_type_comment': UserActivity.TYPE_COMMENT
    }

    activities = {
        'select': select_query,
        'from': from_query,
        'join': join_query,
        'where': where_query,
        'order_by': order_by,
        'params': params
    }

    activities = recom_helper.enrich_query_with_tags(
        activities, tag, film_id_string="useractivity_useractivity.film_id")
    query, params = recom_helper._perform_queries(activities)
    activities = UserActivity.objects.raw(query, params)
    activities = activities[:5]

    # TODO refactor together with same query from core/views/show_main
    select_query = 'SELECT DISTINCT "blog_post".* '
    from_query = ' FROM "blog_post" '
    join_query = ' INNER JOIN "core_object" ON ("blog_post"."parent_id" = "core_object"."id") INNER JOIN "blog_post_related_film" ON ("blog_post"."parent_id" = "blog_post_related_film"."post_id") INNER JOIN "auth_user" ON ("blog_post"."user_id" = "auth_user"."id") '
    where_query = ' WHERE "blog_post"."LANG" = %(language_code)s  AND "core_object"."status" = %(post_status)s  AND "blog_post_related_film"."film_id" IS NOT NULL AND "blog_post"."featured_note" = false  AND "blog_post"."is_published" = true  AND NOT ("blog_post"."featured_note" = true ) '
    order_by = ' ORDER BY "blog_post"."publish" DESC '
    featured_reviews = {
        'select': select_query,
        'from': from_query,
        'join': join_query,
        'where': where_query,
        'order_by': order_by,
        'params': params
    }

    featured_reviews = recom_helper.enrich_query_with_tags(
        featured_reviews, tag, "blog_post_related_film.film_id")
    query, params = recom_helper._perform_queries(featured_reviews)
    featured_reviews = Post.objects.raw(query, params)
    featured_reviews = featured_reviews[:settings.NUMBER_OF_REVIEWS_TAG_PAGE]

    context = {
        'ranking': ranking,
        'recommendations': recommended_films,
        'page': 1,
        'tag': tag,
        'activities': activities,
        'featured_reviews': featured_reviews,
        'festival': festival,
    }

    return render_to_response(templates['SHOW_TAG_PAGE'],
                              context,
                              context_instance=RequestContext(request))
예제 #45
0
def top_users(request, page_id="1", type=None):
    """
        Lists users with the most common taste, or depending
        on the filtering / sorting criteria, in any other order
    """

    form = None
    # boring defaults
    min_common_films = 15
    filmaster_type = FILMASTERS_ALL
    sort_by = FILMASTERS_SORT_COMMON_TASTE

    if type == urls['FOLLOWED']:
        followed_page = True
    else:
        followed_page = False

    if request.user.is_authenticated():
        this_user = request.user
    else:
        this_user = None

    if request.method == "POST":
        # parse the form
        if followed_page:
            logger.debug("Validating FilmastersForm")
            form = FilmastersForm(request.POST)
        else:
            logger.debug("Validating TopUsersForm")
            form = TopUsersForm(request.POST)
        if form.is_valid():
            logger.debug("TopUsersForm valid")
            min_common_films = form.cleaned_data['min_common_films']
            if not followed_page:
                filmaster_type = form.cleaned_data['filmaster_type']
            sort_by = form.cleaned_data['sort_by']
            # reset page ID
            page_id = "1"
            # and store results into session
            request.session["TopUsersForm"] = True
            request.session[
                "TopUsersForm__min_common_films"] = min_common_films
            if type != urls['FOLLOWED']:
                request.session[
                    "TopUsersForm__filmaster_type"] = filmaster_type
            request.session["TopUsersForm__sort_by"] = sort_by
        else:
            logger.error("TopUsersForm invalid")
    elif "TopUsersForm" in request.session:
        # get from session if no form
        try:
            min_common_films = request.session[
                "TopUsersForm__min_common_films"]
            if not followed_page:
                filmaster_type = request.session[
                    "TopUsersForm__filmaster_type"]
            sort_by = request.session["TopUsersForm__sort_by"]
        except KeyError:
            # something went wrong (e.g. we updated code to add new variables), reset vars
            request.session["TopUsersForm"] = None
            request.session["TopUsersForm__min_common_films"] = None
            if type != urls['FOLLOWED']:
                request.session["TopUsersForm__filmaster_type"] = None
            request.session["TopUsersForm__sort_by"] = None

    if form == None:
        logger.debug("Creating a new form with defaults...")

        if followed_page:
            logger.debug("Creating new FilmastersForm")
            form = FilmastersForm(initial={
                'min_common_films': min_common_films,
                'sort_by': sort_by,
            }, )
        else:
            logger.debug("Creating new TopUsersForm")
            form = TopUsersForm(initial={
                'min_common_films': min_common_films,
                'filmaster_type': filmaster_type,
                'sort_by': sort_by,
            }, )

    if followed_page:
        filmaster_type = FOLLOWING_ONLY

    recom_helper = RecomHelper()
    best_tci_users = recom_helper.get_best_tci_users(
        user=this_user,
        min_common_films=min_common_films,
        filmaster_type=filmaster_type,
        sort_by=sort_by,
    )

    logger.debug(form)
    context = {
        "object_list": best_tci_users,
        "form": form,
        "followed_page": followed_page,
    }

    return render_to_response(templates['TOP_USERS'],
                              context,
                              context_instance=RequestContext(request))
예제 #46
0
def show_tag_page(request, tag, festival = None):
    """
        Shows a tag page with a list of recent activities for movies tagged with the
        selected tag, its ranking and film recommendations for the tag (for logged in users)
        This is also used for film festival sites as festivals use tags to group films 
        (show_tag_page caled from festivals.views.show_festival)
    """
       
    if tag == None:
        raise Http404

    recom_helper = RecomHelper()
    ranking = recom_helper.get_ranking(
        type = Rating.TYPE_FILM,
        tags = tag,
        limit = 25, # TODO: customize
        offset = 0,
        festival = festival,
    )

    recommended_films = None
    if request.user.is_authenticated():
        logger.debug("User authenticated, getting recommendations")
        recommended_films = recom_helper.get_best_psi_films_queryset(
            request.user,
            tags = tag,
            limit = 25, # TODO: customize
            offset = 0,
        )
    else:
        logger.debug("User not authenticated, skipping recommendations")

    from django.db.models import Q
    from film20.useractivity.models import UserActivity
    from film20.blog.models import Post

    select_query = 'SELECT DISTINCT "useractivity_useractivity".* '
    from_query = ' FROM "useractivity_useractivity" '
    join_query = ' LEFT OUTER JOIN "blog_post" ON ("useractivity_useractivity"."post_id" = "blog_post"."parent_id") LEFT OUTER JOIN "core_object" ON ("blog_post"."parent_id" = "core_object"."id") '
    where_query = ' WHERE "useractivity_useractivity"."LANG" = %(language_code)s  AND (("core_object"."status" = %(post_status)s  AND "useractivity_useractivity"."activity_type" = %(useractivity_type_post)s) OR "useractivity_useractivity"."activity_type" = %(useractivity_type_short_review)s  OR "useractivity_useractivity"."activity_type" = %(useractivity_type_comment)s ) '
    order_by = ' ORDER BY "useractivity_useractivity"."created_at" DESC '
    params = {'language_code': LANGUAGE_CODE, 'post_status': Post.PUBLIC_STATUS, 'useractivity_type_post': UserActivity.TYPE_POST, 'useractivity_type_short_review': UserActivity.TYPE_SHORT_REVIEW, 'useractivity_type_comment': UserActivity.TYPE_COMMENT}

    activities = {
        'select': select_query,
        'from' : from_query,
        'join' : join_query,
        'where': where_query,
        'order_by': order_by,
        'params': params
    }

    activities = recom_helper.enrich_query_with_tags(activities, tag, film_id_string="useractivity_useractivity.film_id" )
    query, params = recom_helper._perform_queries(activities)
    activities = UserActivity.objects.raw(query, params)
    activities = activities[:5]

    # TODO refactor together with same query from core/views/show_main
    select_query = 'SELECT DISTINCT "blog_post".* '
    from_query = ' FROM "blog_post" '
    join_query = ' INNER JOIN "core_object" ON ("blog_post"."parent_id" = "core_object"."id") INNER JOIN "blog_post_related_film" ON ("blog_post"."parent_id" = "blog_post_related_film"."post_id") INNER JOIN "auth_user" ON ("blog_post"."user_id" = "auth_user"."id") '
    where_query = ' WHERE "blog_post"."LANG" = %(language_code)s  AND "core_object"."status" = %(post_status)s  AND "blog_post_related_film"."film_id" IS NOT NULL AND "blog_post"."featured_note" = false  AND "blog_post"."is_published" = true  AND NOT ("blog_post"."featured_note" = true ) '
    order_by = ' ORDER BY "blog_post"."publish" DESC '
    featured_reviews = {
        'select': select_query,
        'from' : from_query,
        'join' : join_query,
        'where': where_query,
        'order_by': order_by,
        'params': params
    }

    featured_reviews = recom_helper.enrich_query_with_tags(featured_reviews, tag,  "blog_post_related_film.film_id")
    query, params = recom_helper._perform_queries(featured_reviews)
    featured_reviews = Post.objects.raw(query, params)
    featured_reviews = featured_reviews[:settings.NUMBER_OF_REVIEWS_TAG_PAGE]
    
    context = {
        'ranking': ranking,
        'recommendations': recommended_films,
        'page': 1,
        'tag': tag,
        'activities': activities,
        'featured_reviews': featured_reviews,
        'festival': festival,
    }


    return render_to_response(
		templates['SHOW_TAG_PAGE'],
        context, 
        context_instance = RequestContext(request))
예제 #47
0
def top_users(request, page_id = "1", type=None):
    """
        Lists users with the most common taste, or depending
        on the filtering / sorting criteria, in any other order
    """
            
    form = None
    # boring defaults
    min_common_films = 15
    filmaster_type = FILMASTERS_ALL
    sort_by = FILMASTERS_SORT_COMMON_TASTE
    
    if type == urls['FOLLOWED']:
        followed_page = True
    else:
        followed_page = False
    
    if request.user.is_authenticated():
        this_user = request.user
    else:
        this_user = None
    
    if request.method == "POST":
        # parse the form        
        if followed_page:
            logger.debug("Validating FilmastersForm")
            form = FilmastersForm(request.POST)
        else:
            logger.debug("Validating TopUsersForm")
            form = TopUsersForm(request.POST)
        if form.is_valid():
            logger.debug("TopUsersForm valid")
            min_common_films = form.cleaned_data['min_common_films']
            if not followed_page:
                filmaster_type = form.cleaned_data['filmaster_type']
            sort_by = form.cleaned_data['sort_by']
            # reset page ID
            page_id = "1"
            # and store results into session
            request.session["TopUsersForm"] = True
            request.session["TopUsersForm__min_common_films"] = min_common_films
            if type != urls['FOLLOWED']:
                request.session["TopUsersForm__filmaster_type"] = filmaster_type
            request.session["TopUsersForm__sort_by"] = sort_by
        else:
            logger.error("TopUsersForm invalid")
    elif "TopUsersForm" in request.session:
        # get from session if no form
        try:
            min_common_films = request.session["TopUsersForm__min_common_films"]
            if not followed_page:
                filmaster_type = request.session["TopUsersForm__filmaster_type"]
            sort_by = request.session["TopUsersForm__sort_by"]
        except KeyError:
            # something went wrong (e.g. we updated code to add new variables), reset vars
            request.session["TopUsersForm"] = None
            request.session["TopUsersForm__min_common_films"] = None
            if type != urls['FOLLOWED']:
                request.session["TopUsersForm__filmaster_type"] = None
            request.session["TopUsersForm__sort_by"] = None
        
    
    if form == None:
        logger.debug("Creating a new form with defaults...")
        
        if followed_page:
            logger.debug("Creating new FilmastersForm")
            form = FilmastersForm(
                initial = {
                    'min_common_films': min_common_films,
                    'sort_by': sort_by,
                },
            )
        else:
            logger.debug("Creating new TopUsersForm")
            form = TopUsersForm(
                initial = {
                    'min_common_films': min_common_films,
                    'filmaster_type': filmaster_type,
                    'sort_by': sort_by,
                },
            )
            
    if followed_page:
        filmaster_type = FOLLOWING_ONLY
    
    recom_helper = RecomHelper()        
    best_tci_users = recom_helper.get_best_tci_users(          
        user = this_user, 
        min_common_films = min_common_films,
        filmaster_type = filmaster_type,
        sort_by = sort_by,
    )

    logger.debug(form)
    context = {
        "object_list" : best_tci_users,
        "form": form,
        "followed_page": followed_page,
    }

    return render_to_response(templates['TOP_USERS'],
            context,
            context_instance=RequestContext(request))    
예제 #48
0
파일: views.py 프로젝트: thuvh/filmmaster
 def get_queryset(self):
     self.get_username()
     recom_helper = RecomHelper()
     users = recom_helper.get_best_tci_users(user=self.user, limit=self.users_limit, filmaster_type= self.filmaster_type)
     return users
예제 #49
0
파일: movie.py 프로젝트: thuvh/filmmaster
def short_reviews(context, limit=10, param=None, argument=None):
    """
        Configurable widget displaying short reviews
        Takes te following arguments:
        - list of films (can be none), param is "films" and argument is a
        list of film objects
        - film genre (can be none), param is genre and argument is a
        string with film genre
        - if both are none it displays recent last month hand-selected reviews
    """
    request = context['request']
    key = "short_reviews"
    key_params = "short_reviews_params"
    key_films = "films_for_tag"

    if param == "films":
        if argument:
            key += "_".join(film.permalink for film in argument if film and film.pk)

    films = cache.get_cache(CACHE_ACTIVITIES, key_films)
    if param == 'genre':
        if not films:
            rh = RecomHelper()
            films = rh.get_films_for_tag(argument, limit=500, order_by="-popularity")
            key_films += "_".join(film.permalink for film in films if film and film.pk)
            cache.set_cache(CACHE_ACTIVITIES, key_films, films)


    # -- check if path contains tags --
    request_tags = request.GET.get("tags", "")
    request_path = request.META.get("PATH_INFO", "")

    if urls['TAG'] in request_path.lower():
        request_path = request_path.strip(urls['TAG'])
    else:
        request_path = ""

    if param == "genre":
        if request_tags:
            argument = request_tags
        if request_path:
            argument = request_path
        key += "_%s" % argument

    query = cache.get_cache(CACHE_ACTIVITIES, key)
    params = cache.get_cache(CACHE_ACTIVITIES, query)

    if not query:
        params = True
        if param == "films":
            query = UserActivity.objects.select_related('user', 'film', 'short_review').filter(
                activity_type = UserActivity.TYPE_SHORT_REVIEW,
                film__in = argument,
                #featured = True,
                ).order_by("-created_at")[:limit]

        if param == "genre":
            query = UserActivity.objects.select_related('user', 'film', 'short_review').filter(
                activity_type = UserActivity.TYPE_SHORT_REVIEW,
                film__in = films,
                #featured = True,
                ).order_by("-created_at")[:limit]

        if not query:
            params = False
            query = UserActivity.objects.select_related('user', 'film', 'short_review').filter(
                activity_type = UserActivity.TYPE_SHORT_REVIEW,
                #featured = True,
                ).order_by("-created_at")[:limit]

        query = list(query)
        random.shuffle(query)
        cache.set_cache(CACHE_ACTIVITIES, key, query, CACHE_HOUR * 3)
        cache.set_cache(CACHE_ACTIVITIES, query, params, CACHE_HOUR * 3)

    return {'activities': query, 'params': params}
예제 #50
0
 def __init__(self, limit=None, tag=None):
     self.limit = limit
     self.tag = tag
     self.recom_helper = RecomHelper()
예제 #51
0
    def test_planet_tag(self):
        # --- Initialize ---
        self.initialize()
        helper_without_tags = PlanetTagHelper()
        helper_with_tags = PlanetTagHelper(tag='comedy')
        recom_helper = RecomHelper()
        user_activity_helper = UserActivityHelper()

        # --- setup followers ---
        self.u1.followers.follow(self.u2)
        self.u1.followers.follow(self.u3)
        self.u1.followers.follow(self.u4)

        # similar users
        from film20.recommendations.bot_helper import do_create_comparators
        self.films_for_comparator()
        do_create_comparators()

        friends_list = recom_helper.get_following_ids_as_list(self.u1)
        friends_without_activities = helper_without_tags.planet_tag_friends(
            friends_list)
        self.assertEquals(len(friends_without_activities), 0)

        similar_users_list = user_activity_helper.get_similar_users_list(
            request)
        similar_users_without_tags = helper_without_tags.planet_tag_similar_users(
            similar_users_list)
        self.assertEquals(len(similar_users_without_tags), 0)

        notes_without_tags = helper_without_tags.planet_tag_notes()
        self.assertEquals(len(notes_without_tags), 0)

        all_planet_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_planet_activities), 0)

        # --- setup User activities ---
        post = Post()
        post.title = "Lorem ipsum"
        post.permalink = "lorem-ipsum"
        post.body = "siala lala tralala"
        post.user = self.u1
        post.status = Object.PUBLIC_STATUS
        post.type = Object.TYPE_POST
        post.save()
        post.related_film.add(self.film)
        post.save()

        all_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_activities), 1)

        post = Post()
        post.title = "Lorem ipsum"
        post.permalink = "lorem-ipsum"
        post.body = "siala lala tralala"
        post.user = self.u1
        post.status = Object.PUBLIC_STATUS
        post.type = Object.TYPE_POST
        post.save()
        post.related_film.add(self.film1)
        post.save()

        all_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_activities), 2)

        obj = Object.objects.get(id=self.film2.id)
        shortreview = ShortReview()
        shortreview.user = self.u1
        shortreview.review_text = "sialala bumcyk cyk"
        shortreview.status = Object.PUBLIC_STATUS
        shortreview.type = Object.TYPE_SHORT_REVIEW
        shortreview.object = obj
        shortreview.kind = ShortReview.REVIEW
        shortreview.save()

        all_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_activities), 3)

        # Activities with 'comedy' tag
        all_activities_with_tags = helper_with_tags.planet_tag_all()
        self.assertEquals(len(all_activities_with_tags), 1)

        # --- setup followers activities ---
        post = Post()
        post.title = "#1 Lorem ipsum"
        post.permalink = "lorem-ipsum"
        post.body = "siala lala tralala"
        post.user = self.u2
        post.status = Object.PUBLIC_STATUS
        post.type = Object.TYPE_POST
        post.save()
        post.related_film.add(self.film)
        post.save()

        all_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_activities), 4)

        post = Post()
        post.title = "#2 Lorem ipsum"
        post.permalink = "lorem-ipsum"
        post.body = "siala lala tralala"
        post.user = self.u3
        post.status = Object.PUBLIC_STATUS
        post.type = Object.TYPE_POST
        post.save()
        post.related_film.add(self.film1)
        post.save()

        all_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_activities), 5)

        obj = Object.objects.get(id=self.film2.id)
        shortreview = ShortReview()
        shortreview.user = self.u4
        shortreview.review_text = "sialala bumcyk cyk"
        shortreview.status = Object.PUBLIC_STATUS
        shortreview.type = Object.TYPE_SHORT_REVIEW
        shortreview.object = obj
        shortreview.kind = ShortReview.REVIEW
        shortreview.save()

        all_activities = helper_without_tags.planet_tag_all()
        self.assertEquals(len(all_activities), 6)

        activities_with_tags = helper_with_tags.planet_tag_all()
        self.assertEquals(len(activities_with_tags), 2)

        all_friends_activities = helper_without_tags.planet_tag_friends(
            friends_list)
        self.assertEquals(len(all_friends_activities), 3)
        friends_activities_with_tag = helper_with_tags.planet_tag_friends(
            friends_list)
        self.assertEquals(len(friends_activities_with_tag), 1)

        # --- Check notes ---
        all_planet_notes = helper_without_tags.planet_tag_notes()
        self.assertEquals(len(all_planet_notes), 4)

        # Post notes with 'comedy' tag
        notes_activities_with_tag = helper_with_tags.planet_tag_notes()
        self.assertEquals(len(notes_activities_with_tag), 2)

        similar_users_activities = helper_without_tags.planet_tag_similar_users(
            similar_users_list)
        self.assertEquals(len(similar_users_activities), 2)

        users_with_tags = helper_with_tags.planet_tag_similar_users(
            similar_users_list)
        self.assertEquals(len(users_with_tags), 1)

        activities = UserActivity.objects.all()