Example #1
0
def callback_inline(call):
    try:
        if call.message:
            if call.data.startswith('next'):
                recommendation_index = int(call.data.split('-')[1])
                recommend(call.message.chat.id, recommendation_index, bot)
            elif call.data.startswith('rate'):
                anime_id, chat_id = call.data.split('-')[1::]
                add_rating_from_inline(anime_id, chat_id, bot)
            elif call.data.startswith('ban'):
                anime_id, chat_id = call.data.split('-')[1::]
                ban_anime(anime_id, chat_id, bot)
            elif call.data.startswith('remove_rating'):
                user_id = call.data.split('-')[1]
                remove_rating_for(user_id, bot)
            elif call.data.startswith('remove_from_ban_list'):
                user_id = call.data.split('-')[1]
                remove_from_ban_list(user_id, bot)
            elif call.data.startswith('change_rating'):
                user_id = call.data.split('-')[1]
                change_rating(user_id, bot)
            else:
                print(call.data)
    except Exception as error:
        handle_error(error, call.message.chat.id, bot)
    def show_content(self):
        """ Prepares the content list for the user depending on their current choice of content.
            Adds the list of items to the OneLineListItem for display in the 'contentlist' page.
            Transitions to the 'contentlist' page.

        """
        content_dict = dict()
        self.screen.transition.duration = 0
        self.transition('loadingpage', True)
        if self.current_content_choice == "movies":
            if len(self.content_dict_movies) == 0:
                self.content_dict_movies = recommend(self.y_movies_df, self.merged_movies, self.moviemat, self.movie_dict,
                                                    self.movies_rated, self.movies_liked, self.filt_good_movies_rating_count, self.filt_movies_rating_count)
                content_dict = self.content_dict_movies
            else:
                content_dict = self.content_dict_movies
        elif self.current_content_choice == "books":
            if len(self.content_dict_books) == 0:
                self.content_dict_books = recommend(self.y_books_df, self.merged_books, self.bookmat, self.book_dict,
                                                    self.books_rated, self.books_liked, self.filt_good_books_rating_count, self.filt_books_rating_count)
                content_dict = self.content_dict_books
            else:
                content_dict = self.content_dict_books
        else:
            if len(self.content_dict_songs) == 0:
                self.content_dict_songs = recommend(self.y_songs_df, self.merged_songs, self.songmat, self.song_dict,
                                                    self.songs_rated, self.songs_liked, self.filt_good_songs_rating_count, self.filt_songs_rating_count)
                content_dict = self.content_dict_songs
            else:
                content_dict = self.content_dict_songs

        self.make_list_ui(content_dict)

        self.transition('contentlist', True)
Example #3
0
def handle_recs(message: Message):
    try:
        db.check_user(message)
        chat_id = message.chat.id
        recommend(chat_id, 0, bot)
    except Exception as error:
        handle_error(error, message.chat.id, bot)
def test_stability():
    i0 = [random.randint(1, 24)]
    i1 = [random.randint(1, 24)]
    for _ in range(1000):
        # first
        data = {'0': i0, '1': i1}
        r0 = recommender.recommend(data)
        # second
        data = {'0': i0, '1': i1}
        r1 = recommender.recommend(data)
        # test
        assert r0 == r1
def test_order():
    for _ in range(1000):
        i0 = [random.randint(1, 24)]
        i1 = [random.randint(1, 24)]
        n0 = randomword(i0[0])
        n1 = randomword(i1[0])
        print(n0, n1)
        # first
        data = {n0: i0, n1: i1}
        r0 = recommender.recommend(data)
        # second
        data = {n1: i0, n0: i1}
        r1 = recommender.recommend(data)
        # test
        assert r0 == r1
Example #6
0
def recommend():
    watched_movies = request.json
    data = recommender.recommend(watched_movies["movie_ids"])[0:20]

    js = json.dumps(data)
    resp = Response(js, status=200, mimetype='application/json')
    return resp
Example #7
0
def news_handler():
    if request.method == "GET":
        # Get news'

        news = list(app.db['news'].find({}))
        recommended_news = recommender.recommend(current_user.data['name'], news)
        return render_template("news.html", news=recommended_news)
    else:
        title = request.form.get('title', '')
        text = request.form.get('text', '')
        tags = request.form.get('tags', '')
        tags = tags.split(',')
        tags = [tag.strip().lower() for tag in tags]
        # filter empty tags
        # tags = [tag for tag in tags if tag]
        new_tags= []
        for tag in tags:
            if tag:
                new_tags.append(tag)
        tags = new_tags
        tags = list(set(tags))

        new_post = {
            'title': title,
            'text': text,
            'tags': tags,
            'author': current_user.data['name'],
            'time': datetime.datetime.utcnow(),
            'likes': [],
            'dislikes': []
        }
        app.db['news'].insert(new_post)
        return redirect('/')
 def test_recommender(self):
     print "============================="
     print "Recommendations for high sleep high activities"
     print "============================="
     for recommendation in recommender.recommend(fixtures.input):
         if recommendation['severity'] >= 5:
             print recommendation['recommendation']
Example #9
0
def recommend():
  results = recommender.recommend(request.args.get('request'))
  formatted_results = []

  for result in results:
    params = {
      'input': compileAddress(result['address']),
      'key': 'AIzaSyBdrIv-3ggQwhyjuFrLSpjmSR1aj05FeUU',
      'inputtype': 'textquery'
    }
    r = requests.get(url="https://maps.googleapis.com/maps/api/place/findplacefromtext/json", params=params)
    data = r.json()
    
    params2 = {
      'key': 'AIzaSyBdrIv-3ggQwhyjuFrLSpjmSR1aj05FeUU',
      'place_id': data['candidates'][0]['place_id']
    }
    r2 = r = requests.get(url="https://maps.googleapis.com/maps/api/place/details/json", params=params2)
    data2 = r2.json()

    formatted_result = {
      'name': result['name'],
      'formatted_address': data2['result']['formatted_address'],
      'location': {
        'lat': data2['result']['geometry']['location']['lat'],
        'lng': data2['result']['geometry']['location']['lng'],
      },
      'url': data2['result']['url'],
      'icon': data2['result']['icon'],
      'rating': result['rating']
    }

    formatted_results.append(formatted_result)

  return jsonify(formatted_results),200
 def test_condition53(self):
     print "============================="
     print "Recommendations for Low activity"
     print "============================="
     for recommendation in recommender.recommend(fixtures.input53):
         if recommendation['severity'] >= 5:
             print recommendation['recommendation']
 def test_condition9(self):
     print "============================="
     print "Recommendations for Bloodpressure high"
     print "============================="
     for recommendation in recommender.recommend(fixtures.input9):
         if recommendation['severity'] >= 5:
             print recommendation['recommendation']
Example #12
0
def business(city, id):
    """Business page, shows the business, reviews and 10 recommendations."""
    # Get current user if logged in
    user = session.get("user")
    user_id = user["user_id"] if user else None

    # Get business by city and business_id
    business = data.get_business(city.lower(), id)

    # Grab reviews
    reviews = data.get_reviews(city=business["city"].lower(),
                               business_id=business["business_id"])

    # Get 10 recommendations
    recommendations = recommender.recommend(user=user,
                                            business_id=id,
                                            city=business["city"].lower(),
                                            n=10)

    # Render
    return render_template("business.html",
                           business=business,
                           recommendations=recommendations,
                           reviews=reviews,
                           user=user)
Example #13
0
def results():
    # Get request arguments
    region = request.args['region']
    summoner_name = request.args['summoner_name']

    if request.args['champion'] == "any_champion":
        champion = 'any_champion'
    elif request.args['champion'] == "my_champion":
        champion = "my_champion"
    elif request.args['champion'] == "specific_champion":
        champion = request.args['specific_champion']

    if request.args['role'] == "any_role":
        role = 'any_role'
    elif request.args['role'] == "my_role":
        role = "my_role"
    elif request.args['role'] == "specific_role":
        role = request.args['specific_role']

    filter_options = {'champion': champion, 'role': role}

    summoner_account = riot.get_summoner_by_name(
        config.region_base_url_dict[region], summoner_name)

    if summoner_account.status_code != 200:
        return "<html><body><p>Sorry, we couldn't find this summoner. Please try re-entering your information.</p></body></html>"

    player_data = riot.process(summoner_account.json(), region)

    recommendations = rec.recommend(player_data, filter_options)

    return render_template('results_page.html',
                           recommendations=recommendations)
 def test_condition72(self):
     print "============================="
     print "Recommendations for Too much sleep"
     print "============================="
     
     for recommendation in recommender.recommend(fixtures.input72):
         if recommendation['severity'] >= 5:
             print recommendation['recommendation']
Example #15
0
def recommend():

     try:
         inputs = json.loads(request.data)
     except ValueError:
         return "Unable to parse input data", 400
          
     response = recommender.recommend(inputs)
     return json.dumps(response), 201
    def mood_filter(self, mood):
        """ Filters content according to the mood of the user.
            Transitions to the 'contentlist' page to display the filtered content.

        Parameters:
        mood (str): Name of the mood of the user.

        """
        self.create_dialogue_box_mood(mood)
        content_dict = dict()
        self.screen.transition.duration = 0
        self.transition('loadingpage', True)
        if self.current_content_choice == "movies":
            if len(self.content_dict_movies) == 0:
                self.content_dict_movies = recommend(self.y_movies_df, self.merged_movies, self.moviemat, self.movie_dict,
                                                    self.movies_rated, self.movies_liked, self.filt_good_movies_rating_count, self.filt_movies_rating_count)
                content_dict = self.content_dict_movies
                content_dict = filter_content_movies(mood, content_dict)
            else:
                content_dict = self.content_dict_movies
                content_dict = filter_content_movies(mood, content_dict)
        elif self.current_content_choice == "books":
            if len(self.content_dict_books) == 0:
                self.content_dict_books = recommend(self.y_books_df, self.merged_books, self.bookmat, self.book_dict,
                                                    self.books_rated, self.books_liked, self.filt_good_books_rating_count, self.filt_books_rating_count)
                content_dict = self.content_dict_books
                content_dict = filter_content_books(mood, content_dict)
            else:
                content_dict = self.content_dict_books
                content_dict = filter_content_books(mood, content_dict)
        else:
            if len(self.content_dict_songs) == 0:
                self.content_dict_songs = recommend(self.y_songs_df, self.merged_songs, self.songmat, self.song_dict,
                                                    self.songs_rated, self.songs_liked, self.filt_good_songs_rating_count, self.filt_songs_rating_count)
                content_dict = self.content_dict_songs
                content_dict = filter_content_songs(mood, content_dict)
            else:
                content_dict = self.content_dict_songs
                content_dict = filter_content_songs(mood, content_dict)

        self.make_list_ui(content_dict)

        self.transition('contentlist', True)
Example #17
0
def get_recommendation():
    #TODO: put it here!
    global files_by_genre_dict,user_prefs
    sort_user_prefs()
    recommendation_tuples = list(recommender.recommend(user_prefs, amount=5).items())
    recommendations = []
    for (genre,amount) in recommendation_tuples:
        part, files_by_genre_dict[genre] = \
            get_n_in_genre(files_by_genre_dict,genre, amount)
        recommendations.extend(part)
    return recommendations
Example #18
0
def index():
    """Landing page, shows 10 recommendations."""
    # Get current user if logged in
    user = session.get("user")
    user_id = user["user_id"] if user else None

    # Get 10 recommendations
    recommendations = recommender.recommend(user_id=user_id, n=10)

    # Render
    return render_template("index.html", recommendations=recommendations, user=session.get("user"))
def reco():
    lista = rec.recommend(perfilUsuario, df)
    cont = 0
    for i in lista:
        if cont <= 3:
            toList = list(i)
            torec = toList[1]
            lista_conteudo.append(torec[:3])
            cont +=1
        else:
            pass
Example #20
0
 def getrecommend():
     answer = []
     y = 1
     #Acquires response from general responses
     answer.append(traditionalresponse('recommendconfirm'))
     #Appends the hotel recommendation based on features found in memory
     for x in recommend(featureget()):
         answer.append("Number " + str(y) + ": " + x)
         y += 1
     featureclear()
     return answer
Example #21
0
File: App.py Project: 2rd/Thesis
def get_recommendations():
    '''
    Takes a string in json format of interactions {movieId:"x", rating:x}
    and returns recommendations in json format.
    '''

    interactions = request.args['interactions']

    try:
        return jsonify({'results': rec.recommend(interactions)})

    except KeyError:
        return f'invalid input'
Example #22
0
def handle_any_message(message: Message):
    try:
        db.check_user(message)

        if message.text == 'Rate anime':
            add_anime(message, bot)
        elif message.text == 'Get recommendations':
            chat_id = message.chat.id
            recommend(chat_id, 0, bot)
        elif message.text == 'Account':
            show_account(message, bot)
        elif message.text == 'Get info':
            get_info(message, bot)
        elif message.text == 'Easter egg':
            bot.send_sticker(message.chat.id, variables.APPROVAL_STICKER_ID)
            bot.send_message(message.chat.id, "Damn, u good")
        else:
            bot.send_sticker(message.chat.id, variables.FLEX_STICKER_ID)
            bot.send_message(message.chat.id, "I don't understand you")
            print(f'{message.from_user.id}: {message.text}')
    except Exception as error:
        handle_error(error, message.chat.id, bot)
def make_recommendation(random_forest=False,
                        rec_amount=10,
                        entered_songs=None,
                        entered_amount=1):
    '''
    Main function that's called when a user enters the page. Prints a
    recommendation of rec_amount songs for the entered songs.

    random_forest: If False (default), recommendation is done via
    kmeans++ clustering. If True, it's done via random forest.

    rec_amount: The amount of songs to recommend.

    entered_songs: List of song ids the user has entered. If none is
    provided, a random list will be created. Note that if you want to
    use random forest, only enter song ids that at least one user has
    in his good category.

    entered_amount: the amount of songs the randomly created list of
    entered songs shall contain. Only relevant if no list of entered
    songs is provided.
    '''
    req_rf = request.args.get('rf')
    if req_rf == 'True' or req_rf == 'true':
        random_forest = True
    req_ra = request.args.get('recamount')
    if req_ra is not None:
        rec_amount = int(req_ra)
    req_ea = request.args.get('entamount')
    if req_ea is not None:
        entered_amount = int(req_ea)
    if request.args.get('ent1') is not None:
        entered_songs = build_entered_list(request)

# song_dict = read_song_dict_w_labels()
    if random_forest:
        if entered_songs is None:
            entered_songs = get_rnd_good_songs(song_dict, entered_amount)
        return jsonify(
            recommend_w_rf(song_dict, entered_songs, rec_amount,
                           global_clusters))
    else:
        if entered_songs is None:
            entered_songs = get_rnd_entered_songs(song_dict, entered_amount)
        return jsonify(
            recommend(song_dict, entered_songs, rec_amount, global_clusters))
Example #24
0
def get_recommendations(section):
    section_mode_map = {
        'hot-questions': ('questions', 'interests'),
        'useful-questions': ('questions', 'interests'),
        'awaiting-answer': ('questions', 'expertise'),
        'popular-unanswered': ('questions', 'expertise'),
        'highly-discussed-qs': ('questions', 'both'),
        'highly-discussed-as': ('answers', 'both'),
        'interesting-answers': ('answers', 'both'),
    }
    if section not in section_mode_map.keys():
        return flask.abort(404)

    try:
        args = flask.request.args
        user_id = int(args['user_id'])
        frequency = args['frequency']
        duplicates = json.loads(args.get('duplicates', '{}'))
    except ValueError or KeyError:
        return flask.abort(400)

    app.logger.info('GET recommendations - user: %s, section: %s, freq: %s',
                    user_id, section, frequency)

    # Choose recommender in A/B test based on date
    _, week, day = datetime.now().isocalendar()
    week_even = week % 2 == 0
    if (week_even and day > 3) or (not week_even and day <= 3):
        rec_type = 'diverse'
    else:
        rec_type = 'personalized'

    rec_mode = section_mode_map[section]
    results = recommender.recommend(rec_type,
                                    section,
                                    rec_mode,
                                    frequency,
                                    user_id,
                                    duplicates,
                                    logger=app.logger)

    app.logger.info('Returned %d results.', len(results))
    return json_response(results)
Example #25
0
    def get(self):
        parsed_args = parser.parse_args()
        restaurant_name = parsed_args['restaurant_name']
        dishes = session.query(Dish).filter(
            Dish.restaurant_name == restaurant_name).all()

        # return recommended dish's back if:
        #       a user is specified
        #       AND they have atleast one review
        #       AND the restaurant contains atleast one dish
        username = parsed_args['username']
        if (username != 'None' and dishes):
            reviewed_dishes = session.query(
                Dish,
                Review).join(Review).filter(Review.username == username).all()
            if reviewed_dishes:
                dishes = recommend(dishes, reviewed_dishes)

        return dishes
Example #26
0
def process_recommendation(drug):
	"""Pulls drug recommendation stats from recommender.py, formats.

	ARGS:
		drug: string.
			generic name of drug.

	RETURNS:
		data: tuple.
			tuple of (stayed_frac,better_frac,best_frac,drugname)
	"""
	stayed_on_drug,switched_drug,switched_drug_better,best_drug = r.recommend(drug)

	total = stayed_on_drug + switched_drug
	stayed_frac = float(stayed_on_drug)/total
	better_frac = float(switched_drug_better)/switched_drug
	best_frac = float(best_drug[1])/switched_drug_better
	bdrug = best_drug[0]

	drugname,gen = drugnames(bdrug)

	data = (stayed_frac,better_frac,best_frac,drugname)
	return data
Example #27
0
def recommend_books():
    name = request.json['name']
    books_list = recommender.recommend(name)
    print(books_list)
    cur = mysql.connection.cursor()
    return_data = []
    for book in books_list:
        if (book != name):
            book = book.replace("'", "\'")
            cur.execute(
                "select original_title, authors, image_url, original_publication_year, average_rating from books where original_title="
                + "\"" + book + "\"")
            data = cur.fetchall()
            print(data)
            tmp = {
                "title": data[0][0],
                "author": data[0][1],
                "url": data[0][2],
                "published": data[0][3],
                "rating": str(data[0][4])
            }
            return_data.append(tmp)
    print(return_data)
    return jsonify({"data": return_data}), 200
Example #28
0
def Recommend():
    _movie1 = str(request.form['movie1'])
    _movie2 = str(request.form['movie2'])
    _movie3 = str(request.form['movie3'])
    _movie4 = str(request.form['movie4'])
    _movie5 = str(request.form['movie5'])
    _rate1 = int(request.form['rate1'])
    _rate2 = int(request.form['rate2'])
    _rate3 = int(request.form['rate3'])
    _rate3 = int(request.form['rate4'])
    _rate3 = int(request.form['rate5'])

    # keywords to ASIN
    # api = API("AKIAJGEEABW2F4H7ZB4Q", "6+ShIy2suLuPzWOdhEbzA8y4Cd3QDdfzokAbILB1","us","yueyingteng-20")
   
    api = API("AKIAIKFQCWRMAQBAIGDQ","V3URxyjcNbnRgak1CnWSoNqze2OFo2xkzxhYgYbg","us","chenlji-20")


    print(1)

    ASIN = {}
    print("1.1")
    keywords = [_movie1, _movie2, _movie3, _movie4, _movie5]
    print("1.2")
    for keyword in keywords:
        ASIN[keyword] = []
        results = api.item_search('DVD', Title = keyword)
        print("1.3")
        for item in results:
            item =  item.ASIN
            ASIN[keyword].append(item)
    
    print(2)

    # ASIN = {}
    # keywords = ['little miss sunshine']
    # ASIN['little miss sunshine'] = ['B000K7VHQE', 'B000MR1V22', 'B001JNNDDI', 'B000JU9OJ4']
    

    #from recommender import create_new_user_data
    # def create_new_user_data(username, keywords, ratings):
    #     print(a)
    #     empty_dict = {}
    #     print(b)
    #     for i in range(len(keywords)):
    #         print(c)
    #     # if there are no ASINs in common between the Amazon API results and our data, do not create an entry
    #         if len(set(ASIN[keywords[i]]) & set(movies_list)) == 0:
    #             print(d)
    #             continue
    #         else:
    #             print(e)
    #         # get the first entry from the intersection of the Amazon API results and the ASINs in our data
    #             empty_dict[list(set(ASIN[keywords[i]]) & set(movies_list))[0]] = ratings[i]
    #     users_data[username] = empty_dict

    # print(keywords[0])
    # print(ASIN[keywords[0]])
    # print(set(ASIN[keywords[0]]))
    # a = [filter(lambda x: x in ASIN[keywords[0]], sublist) for sublist in movies_list]
    # print("a")
    
    def create_new_user_data(username, keywords, ratings):
        userids[len(userids)] = 'newuser1'
        print("a")
        empty_dict = {}
        print("b")
        for i in range(len(keywords)):
            print("c")
            if len(set(ASIN[keywords[i]]) & set(movies_list)) == 0:
                print("d")
                continue
            else:
                empty_dict[list(set(ASIN[keywords[i]]) & set(movies_list))[0]] = ratings[i]
                print("e")
        users_data[username] = empty_dict


    print(3)
    

    create_new_user_data('newuser1', keywords, [_rate1, _rate2, _rate3, _rate2, _rate1])
    print(users_data['newuser1'])

    

    testrun = recommend('newuser1', userids, users_data)

    print(testrun)

    movies = {}
    for movie in testrun:
        movies[movie] = []
        #result = api.item_lookup(str(movie))
        for item in api.item_lookup(str(movie)).Items.Item:
            title = item.ItemAttributes.Title 
            URL = item.ItemLinks.ItemLink.URL
            movies[movie].append(str(title))
            movies[movie].append(str(URL))
        #result2 = api.item_lookup(str(movie), ResponseGroup='Images')
        for items in api.item_lookup(str(movie), ResponseGroup='Images').Items.Item:
            imageURL = items.ImageSets.ImageSet.LargeImage.URL
            movies[movie].append(str(imageURL))


    
    # # movies2 = {'B004L9GLKE': ['Departed', 'http://www.amazon.com/Departed-Leonardo-DiCaprio/dp/tech-data/B004L9GLKE%3FSubscriptionId%3DAKIAJGEEABW2F4H7ZB4Q%26tag%3Dyueyingteng-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB004L9GLKE', 'http://ecx.images-amazon.com/images/I/51CN2a6OGvL.jpg'], 'B000S0DDG0': ['Dreamgirls', 'http://www.amazon.com/Dreamgirls-Jamie-Foxx/dp/tech-data/B000S0DDG0%3FSubscriptionId%3DAKIAJGEEABW2F4H7ZB4Q%26tag%3Dyueyingteng-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB000S0DDG0', 'http://ecx.images-amazon.com/images/I/51NsSmJiUxL.jpg'], '6300267881': ['The Exorcist [VHS]', 'http://www.amazon.com/The-Exorcist-VHS-Ellen-Burstyn/dp/tech-data/6300267881%3FSubscriptionId%3DAKIAJGEEABW2F4H7ZB4Q%26tag%3Dyueyingteng-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D6300267881', 'http://ecx.images-amazon.com/images/I/21HWKZ0WSNL.jpg']}
    print(movies[testrun[0]][0])
    print(movies[testrun[0]][1])
    print(movies[testrun[0]][2])
    # print(movies2[testrun[0]][0])
    # print(movies2[testrun[0]][1])
    # print(movies2[testrun[0]][2])


    data = [{"title1" : movies[testrun[0]][0], "url1" : movies[testrun[0]][1], "imgUrl1" : movies[testrun[0]][2],
    "title2" : movies[testrun[1]][0], "url2" : movies[testrun[1]][1], "imgUrl2" : movies[testrun[1]][2],
    "title3" : movies[testrun[2]][0], "url3" : movies[testrun[2]][1], "imgUrl3" : movies[testrun[2]][2]}]
    # Writing JSON data
    
    #data = [{'title1': 'The Exorcist [VHS]', 'title2': 'Departed', 'title3': 'Dreamgirls', 'url1': 'http://www.amazon.com/The-Exorcist-VHS-Ellen-Burstyn/dp/tech-data/6300267881%3FSubscriptionId%3DAKIAJGEEABW2F4H7ZB4Q%26tag%3Dyueyingteng-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D6300267881', 'url3': 'http://www.amazon.com/Dreamgirls-Jamie-Foxx/dp/tech-data/B000S0DDG0%3FSubscriptionId%3DAKIAJGEEABW2F4H7ZB4Q%26tag%3Dyueyingteng-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB000S0DDG0', 'url2': 'http://www.amazon.com/Departed-Leonardo-DiCaprio/dp/tech-data/B004L9GLKE%3FSubscriptionId%3DAKIAJGEEABW2F4H7ZB4Q%26tag%3Dyueyingteng-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB004L9GLKE', 'imgUrl3': 'http://ecx.images-amazon.com/images/I/51NsSmJiUxL.jpg', 'imgUrl2': 'http://ecx.images-amazon.com/images/I/51CN2a6OGvL.jpg', 'imgUrl1': 'http://ecx.images-amazon.com/images/I/21HWKZ0WSNL.jpg'}]

    print(data)
    with open('static/js/data.json', 'w') as f:
      json.dump(data,f, ensure_ascii = False, encoding = 'utf-8')

    return render_template('index.html')
            print("Carro ja selecionado")
        else:
            selected.append(list(training_dataset.iloc[entrada]))
            IDS.append(entrada)

tam = df.shape[0]
user_selected = []
for car in selected: #Vai preencher uma lista com os carros selecionados junto dos respectivos atributos
   #print(car)
    for i in range(tam - 1):
        carro = df.iloc[i]
        if ((list(carro)[:11])[1] == car[1]):
            user_selected.append(list(carro))

selected_numbers = len(selected)
print(selected_numbers)

# RETORNA A LISTA "user_selected"

#//////////////////////////////////////////////////////RACIOCINIO BASEADO EM CASOS///////////////////////////////////////////////////////////////////////////

#No pacote CaseBased.py

#///////////////////////////////////////////////////////  MAIN  /////////////////////////////////////////////////////////////////////////////////////////////

preencheperfil()

rec.recommend(perfilUsuario, df)
ava.avaliar(selected_numbers)
#print(ava.avaliasistema())
        user_choice = int(input('Enter Choice : '))

        if user_choice == 1:
            movieBase.DisplayMovies()

        elif user_choice == 2:
            movieid = int(
                input('Enter the id of movie which you want to lend : '))
            moviename = input(
                'Enter the name of movie which you want to lend : ')

            user = input('Enter your Name : ')
            movieBase.LendMovie(movieid, moviename, user)
            print("\nYou may also like : ")
            recommend(moviename, movieid)

        elif user_choice == 3:
            movieid = int(
                input('Enter the movie-id which you want to return : '))
            movieBase.ReturnMovie(movieid)
        else:
            print('INVALID OPERATION')

        user_choice2 = ''

        while (user_choice2 != 'q' and user_choice2 != 'c'):
            print('\nEnter q to quit and c to continue...')
            user_choice2 = input()
            if user_choice2 == 'q':
                exit()
Example #31
0
def respond(sentence):
    # Parses the user's statement and identify POS to construct response
    #Cleans sentences for processing
    cleaned = preprocess_text(sentence)
    #parsed = TextBlob(cleaned)

    #Extracts the POS and clearly marks proper nouns in sentences
    pos, markeddata = postag(cleaned)
    #print(pos)

    data = sentencedata(markeddata)
    #print(data.sentence())

    #Does a general clssification
    sentclass = generalclassify(data)

    #Does action according to classification map
    mapping = getmapping()

    for k, v in mapping.items():
        if sentclass == k:
            sentclass = v
            break

    #sentclass = classifysent(cleaned)
    #print(sentclass)
    def getrecommend():
        answer = []
        y = 1
        #Acquires response from general responses
        answer.append(traditionalresponse('recommendconfirm'))
        #Appends the hotel recommendation based on features found in memory
        for x in recommend(featureget()):
            answer.append("Number " + str(y) + ": " + x)
            y += 1
        featureclear()
        return answer

    # Contains actions performed during specific classification of sentences
    #If the classifier sees the statement as informational (Informational)
    if sentclass == 'IN':
        answer = responseinfo(find_features(pos))
        featureadd(find_features(pos))
        if featurelimit() == True:
            addon = "We have enough information for a recommendation. Would you like to me to recommend you a hotel now?"
            memoryadd("confirmrecommend")
            answer.append(addon)

    #If the sentence is a question about a hotel for its features (Question on Features)
    elif sentclass == 'QF' or sentclass == 'moredetails':
        #answer = responseqf(find_features(pos))
        locationname = find_names(pos)
        locstring = ' '.join(locationname)
        if locstring == '':
            answer = "Sorry, but there's no hotel with that name. How about just telling me about things you'd want in your hotel?"
        else:
            if not recommendwname(locstring):
                answer = "Sorry, but there's no hotel with that address. How about just telling me about things you'd want in your hotel?"
            else:
                name, features = recommendwname(locstring)
                completesent = []
                completesent.append('The hotel ')
                completesent.append(name)
                completesent.append(' has ')
                things = ', '.join(features)
                completesent.append(things)
                answer = ''.join(completesent)

    #If the user is responeding with a confirmation or denial of last asked question
    elif sentclass == 'confirm':
        #Checks if memoryget() has any variables
        try:
            x = memoryget()[-1]
        except IndexError:
            x = "Nothing"

        if x == "confirmrecommend":
            answer = getrecommend()
            memoryclear()
        else:
            if memoryget() == []:
                answer = traditionalresponse(sentclass)
            else:
                mem = memoryget()
                sentclass = 'confirm' + mem[0]
                answer = traditionalresponse(sentclass)
                memoryclear()
    elif sentclass == 'deny':
        #Checks if memoryget() has any variables
        try:
            x = memoryget()[-1]
        except IndexError:
            x = "Nothing"

        if x == "confirmrecommend":
            answer = "Okay, please tell me more about what you'd like to see in your hotel"
            memoryclear()
        else:
            if memoryget() == []:
                answer = traditionalresponse(sentclass)
            else:
                sentclass = sentclass + 'help'
                answer = traditionalresponse(sentclass)
                memoryclear()

    #If the user is getting a recommendation now
    elif sentclass == 'recommendconfirm':
        answer = []
        y = 1
        #Acquires response from general responses
        answer.append(traditionalresponse(sentclass))
        #Appends the hotel recommendation based on features found in memory
        for x in recommend(featureget()):
            answer.append("Number " + str(y) + ": " + x)
            y += 1
        featureclear()
        memoryclear()

    elif sentclass == 'infolocation' or sentclass == 'location':
        #answer = traditionalresponse(sentclass)
        locationname = find_names(pos)
        locstring = ' '.join(locationname)
        locset = [locstring]
        #print(locset)
        if not recommendwlocation(locset):
            answer = "Sorry, but there's no hotel with that name. How about just telling me about things you'd want in your hotel?"
        else:
            completesent = []
            completesent.append(
                'The following hotels are near that location: ')
            things = ', '.join(x for x in recommendwlocation(locset))
            completesent.append(things)
            answer = ''.join(completesent)

    #If the statement can handle a general response
    elif bool(sentclass) == True:
        answer = traditionalresponse(sentclass)
        memoryadd(sentclass)
        #print("YOU HAVE CLASSIFIED THIS AS ", sentclass)

    #If the statement is truly not understood
    else:
        return "Sorry, but I don't understand you"
        #print(sentclass)

    #answer.append(addon)
    return answer
Example #32
0
 def test_recommender(self):
     print recommender.recommend(fixtures.input)
Example #33
0
def Recommend():
    _movie1 = str(request.form['movie1'])
    _movie2 = str(request.form['movie2'])
    _movie3 = str(request.form['movie3'])
    _movie4 = str(request.form['movie4'])
    _movie5 = str(request.form['movie5'])
    _rate1 = int(request.form['rate1'])
    _rate2 = int(request.form['rate2'])
    _rate3 = int(request.form['rate3'])
    _rate3 = int(request.form['rate4'])
    _rate3 = int(request.form['rate5'])

    # keywords to ASIN
       
    api = API(aws credentials) # you need to buy your own aws credentials


    # print(1)

    ASIN = {}
    print("1.1")
    keywords = [_movie1, _movie2, _movie3, _movie4, _movie5]
    print("1.2")
    for keyword in keywords:
        ASIN[str(keyword)] = []
        results = api.item_search('DVD', Title = str(keyword))
        print("1.3")
        for item in results:
            item =  item.ASIN
            ASIN[str(keyword)].append(str(item))
    
    print(2)

    # ASIN = {}
    # keywords = ['little miss sunshine']
    # ASIN['little miss sunshine'] = ['B000K7VHQE', 'B000MR1V22', 'B001JNNDDI', 'B000JU9OJ4']
    

    # from recommender import create_new_user_data
    # def create_new_user_data(username, keywords, ratings):
    #     print(a)
    #     empty_dict = {}
    #     print(b)
    #     for i in range(len(keywords)):
    #         print(c)
    #     # if there are no ASINs in common between the Amazon API results and our data, do not create an entry
    #         if len(set(ASIN[keywords[i]]) & set(movies_list)) == 0:
    #             print(d)
    #             continue
    #         else:
    #             print(e)
    #         # get the first entry from the intersection of the Amazon API results and the ASINs in our data
    #             empty_dict[list(set(ASIN[keywords[i]]) & set(movies_list))[0]] = ratings[i]
    #     users_data[username] = empty_dict

    print(keywords[0])
    print(ASIN[keywords[0]])
    print(list(ASIN[keywords[0]]))
    print(set(ASIN[str(keywords[0])]))
    print(set(list(ASIN[keywords[0]])))
    #print(set(list(movies_list)))
    #a = [filter(lambda x: x in ASIN[keywords[0]], sublist) for sublist in movies_list]
    #print(a)
    
    def create_new_user_data(username, keywords, ratings, ASIN):
        userids[len(userids)] = 'newuser1'
        print("a")
        empty_dict = {}
        print("b")
        for i in range(len(keywords)):
            print("c")
            a = set(list(ASIN[keywords[i]]))
            print(a)
            b = set(list(movies_list))
            print(b)
            c = list(a & b)
            print(c)
            if len(list(c)) == 0:
                print("d")
                continue
            else:
                #empty_dict[list(c)] = ratings[i]
                empty_dict[c[0]] = ratings[i]
                print("e")
        users_data[username] = empty_dict


    print(3)
    

    create_new_user_data('newuser1', keywords, [_rate1, _rate2, _rate3, _rate2, _rate1], ASIN)
    print(users_data['newuser1'])

    

    testrun = recommend('newuser1', userids, users_data)

    print(testrun)

    movies = {}
    for movie in testrun:
        movies[movie] = []
        #result = api.item_lookup(str(movie))
        for item in api.item_lookup(str(movie)).Items.Item:
            title = item.ItemAttributes.Title 
            URL = item.ItemLinks.ItemLink.URL
            movies[movie].append(str(title))
            movies[movie].append(str(URL))
        #result2 = api.item_lookup(str(movie), ResponseGroup='Images')
        for items in api.item_lookup(str(movie), ResponseGroup='Images').Items.Item:
            imageURL = items.ImageSets.ImageSet.LargeImage.URL
            movies[movie].append(str(imageURL))


    
    # # movies2 = {'B004L9GLKE': ['Departed', 'http://www.amazon.com/Departed-Leonardo-DiCaprio/dp/tech-data/B004L9GLKE%3FSubscriptionId%3DAKIAJGEEABW2F4H7ZB4Q%26tag%3Dyueyingteng-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB004L9GLKE', 'http://ecx.images-amazon.com/images/I/51CN2a6OGvL.jpg'], 'B000S0DDG0': ['Dreamgirls', 'http://www.amazon.com/Dreamgirls-Jamie-Foxx/dp/tech-data/B000S0DDG0%3FSubscriptionId%3DAKIAJGEEABW2F4H7ZB4Q%26tag%3Dyueyingteng-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB000S0DDG0', 'http://ecx.images-amazon.com/images/I/51NsSmJiUxL.jpg'], '6300267881': ['The Exorcist [VHS]', 'http://www.amazon.com/The-Exorcist-VHS-Ellen-Burstyn/dp/tech-data/6300267881%3FSubscriptionId%3DAKIAJGEEABW2F4H7ZB4Q%26tag%3Dyueyingteng-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D6300267881', 'http://ecx.images-amazon.com/images/I/21HWKZ0WSNL.jpg']}
    print(movies[testrun[0]][0])
    print(movies[testrun[0]][1])
    print(movies[testrun[0]][2])
    # print(movies2[testrun[0]][0])
    # print(movies2[testrun[0]][1])
    # print(movies2[testrun[0]][2])


    data = [{"title1" : movies[testrun[0]][0], "url1" : movies[testrun[0]][1], "imgUrl1" : movies[testrun[0]][2],
    "title2" : movies[testrun[1]][0], "url2" : movies[testrun[1]][1], "imgUrl2" : movies[testrun[1]][2],
    "title3" : movies[testrun[2]][0], "url3" : movies[testrun[2]][1], "imgUrl3" : movies[testrun[2]][2]}]
    # Writing JSON data
    
    #data = [{'title1': 'The Exorcist [VHS]', 'title2': 'Departed', 'title3': 'Dreamgirls', 'url1': 'http://www.amazon.com/The-Exorcist-VHS-Ellen-Burstyn/dp/tech-data/6300267881%3FSubscriptionId%3DAKIAJGEEABW2F4H7ZB4Q%26tag%3Dyueyingteng-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3D6300267881', 'url3': 'http://www.amazon.com/Dreamgirls-Jamie-Foxx/dp/tech-data/B000S0DDG0%3FSubscriptionId%3DAKIAJGEEABW2F4H7ZB4Q%26tag%3Dyueyingteng-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB000S0DDG0', 'url2': 'http://www.amazon.com/Departed-Leonardo-DiCaprio/dp/tech-data/B004L9GLKE%3FSubscriptionId%3DAKIAJGEEABW2F4H7ZB4Q%26tag%3Dyueyingteng-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB004L9GLKE', 'imgUrl3': 'http://ecx.images-amazon.com/images/I/51NsSmJiUxL.jpg', 'imgUrl2': 'http://ecx.images-amazon.com/images/I/51CN2a6OGvL.jpg', 'imgUrl1': 'http://ecx.images-amazon.com/images/I/21HWKZ0WSNL.jpg'}]

    print(data)
    with open('static/js/data.json', 'w') as f:
      json.dump(data,f, ensure_ascii = False, encoding = 'utf-8')

    return render_template('index.html')
    compare = list(UserCase.values())
    for i in range(tam):
        caso = casos.iloc[i]
        similarity = calcSimi(list(UserCase), list(caso)[:1])
        distances.append((similarity, list(carro)[1:]))
    distances.sort()
    distances.reverse()  # ---- Pearson and Cosseno

    print(distances[:3])
    return distances


#/////////////////////////////////////Aprendizado Inicial///////////////////////////////////

#///////////////////////////////////////MAIN////////////////////////////////////////////////

Usuario = {
    "Carroceria": 1.5,
    "NumLugares": 5,
    "NumeroDePortas": 3,
    "Finalidade": 1,
    "Combustivel": 2,
    "Valor": 4,
    "Conforto": 2,
    "Seguranca": 2,
    "GastosFixos": 1,
    "Desempenho": 1
}

rec.recommend(Usuario, df)
Example #35
0
def upload_file():
    if request.method == 'POST':
        global previous_upload_dir
        global previous_filenames
        use_previous_path = False

        # Create directory with unique name for uploaded files
        timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
        directory = os.path.join(app.config['UPLOAD_FOLDER'], timestamp)
        try:
            os.makedirs(directory)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise OSError('Error creating directory for uploaded files')

        if request.form['input-method'] == 'mic':
            d, f = os.path.split(sound_recording.record(directory)) # Record audio and get path components
            # Retrieve form info
            filenames = [f]
            mode = request.form['mode']
            vector_type = request.form['features']
            # Update arguments and previous upload information to current upload
            args = [directory, mode, vector_type, data]
            previous_upload_dir = directory
            previous_filenames = filenames
            recommendations, predictions, warning = recommender.recommend(args=args)  # Perform recommendation
            # Return the template with the included information from the recommendation process
            return render_template("index.html", current_song=filenames, recommendations=recommendations, predicted=make_string(predictions), scroll="app", error=None, warning=warning)
        elif request.form['input-method'] == 'file':
            # Check if post request has file part
            if 'file[]' not in request.files:
                use_previous_path = True
            if use_previous_path:
                # If there are no previous songs to use, then return error as no files have been selected, otherwise continue and use previous songs
                if previous_upload_dir is None or previous_filenames is None:
                    return render_template("index.html", current_song=None, recommendations=None, predicted=None, scroll="app", error="No file selected", warning=None)
            # Retrieve files from request
            file_list = request.files.getlist("file[]")
            for f in file_list:
                # Check uploaded files are valid - if empty use previous songs or return invalid filename error
                if f.filename == '':
                    use_previous_path = True
                    if previous_upload_dir is None or previous_filenames is None:
                        return render_template("index.html", current_song=None, recommendations=None, predicted=None, scroll="app", error="Invalid filename", warning=None)
            # Retrieve other information from request
            mode = request.form['mode']
            vector_type = request.form['features']
            # If set to use previous path/songs due to request with no file part or empty filename, then use the stored directory
            if use_previous_path:
                args = [previous_upload_dir, mode, vector_type, data]
                recommendations, predictions, warning = recommender.recommend(args=args)
                return render_template("index.html", current_song=previous_filenames, recommendations=recommendations, predicted=make_string(predictions), scroll="app", error=None, warning=warning)
            elif mode and all(allowed_file(f.filename) for f in file_list) and all(f for f in file_list):
                # Ensure filenames are secure and save the uploaded files
                filenames = []
                for f in file_list:
                    filename = secure_filename(f.filename)
                    path = os.path.join(directory, filename)
                    f.save(path)
                    filenames.append(filename)
                # Update arguments and previous upload information to current upload
                args = [directory, mode, vector_type, data]
                previous_upload_dir = directory
                previous_filenames = filenames
                recommendations, predictions, warning = recommender.recommend(args=args)  # Perform recommendation
                # Return the template with the included information from the recommendation process
                return render_template("index.html", current_song=filenames, recommendations=recommendations, predicted=make_string(predictions), scroll="app", error=None, warning=warning)
    return render_template("index.html", current_song=None, recommendations=None, predicted=None, scroll="app", error=None, warning=None)
Example #36
0
def main():
    # Command-line parsing
    parser = OptionParser()
    parser.add_option("-f", "--test_full",
                      action="store_true", dest="full_training_set",
                      help="test the recommender on the full training dataset.")
    parser.add_option("-l", "--test_local",
                      action="store_false", dest="full_training_set", default=False,
                      help="test the recommender on the local training dataset (default behavior).")
    parser.add_option("-s", "--split-datasets",
                      action="store_true", dest="split", default=False,
                      help="takes the full dataset file has specified in the constants and split "+
                            "it into a reasonable couple of test-training datasets")


    (options, args) = parser.parse_args()

    # Split the dataset (una-tantum)
    if options.split:
        print("CAREFUL HERE! Save your datasets somewhere before proceeding!")
        return
        
        print(" # Loading interactions full dataset ({})...".format(TRAINING_FULL_SET))
        #interactions_map = sp.genfromtxt("{}{}".format(ROOT, TRAINING_FULL_SET), dtype='int64', delimiter="\t", names=["users", "items", "inter", "date"])[1:]
        interactions_map =  pd.read_csv("{}{}".format(ROOT, TRAINING_FULL_SET), sep="\t")
        print("   -> got {} rows".format(interactions_map.shape[0]))
        print(" # Loading target users' table ...")
        #target_users = sp.genfromtxt("{}target_users.csv".format(ROOT), dtype='int64', delimiter="\t")[1:]
        target_users =  pd.read_csv("{}target_users.csv".format(ROOT), sep="\t")
        print("   -> got {} rows".format(target_users.shape[0]))
        
        import splitter2 as s
        print(" # Splitting datasets...")
        start = time.time()
        s.split(interactions_map, target_users)
        end = time.time()
        print(" # Done in {:3f} sec!".format(end-start))
        return

    if options.full_training_set:
        training_set = TRAINING_FULL_SET
        print("\n # FULL dataset chosen for training")
    else:
        training_set = TRAINING_LOCAL_SET
        print("\n # LOCAL dataset chosen for training")
        
        

        
        

    ######## LOADING DATASETS ########

    print("\n-----------------------------------------------------------------")
    print("---------- LOADING DATASETS -------------------------------------\n")

    start = time.time()

    #### Interactions' structure
    #
    # user_id : ID of the user who performed the interaction 
    #            (points to users.id)
    # item_id : ID of the item on which the interaction was 
    #           performed (points to items.id)
    # interaction_type : the type of interaction that was performed 
    #                    on the item:
    #     1 = the user clicked on the item
    #     2 = the user bookmarked the item
    #     3 = the user clicked on the reply button or application 
    #         form button that is shown on some job postings
    # created_at : a unix time stamp timestamp representing the 
    #              time when the interaction got created
    print(" # Loading interactions' dataset...")
    int_training_map =  pd.read_csv("{}{}".format(ROOT, training_set), sep="\t")
    print("   -> got {} rows".format(int_training_map.shape[0]))
    
    # Load the test set only if I'm training on the local set
    int_test_map = []
    if training_set == TRAINING_LOCAL_SET:  
        print(" # Loading test dataset ({})...".format(TEST_SET))
        int_test_map = pd.read_csv("{}{}".format(ROOT, TEST_SET), sep="\t")
        print("   -> got {} rows".format(int_test_map.shape[0]))
        
    ### Item Profiles' structure
    #
    # id : anonymized ID of the item (item_id in interaction dataset)
    # title : concepts that have been extracted from the job title 
    #         of the job posting (numeric IDs)
    # career_level : career level ID (e.g. beginner, experienced, manager):
    #    0 = unknown
    #    1 = Student/Intern
    #    2 = Entry Level (Beginner)
    #    3 = Professional/Experienced
    #    4 = Manager (Manager/Supervisor)
    #    5 = Executive (VP, SVP, etc.)
    #    6 = Senior Executive (CEO, CFO, President)
    # discipline_id : anonymized IDs represent disciplines
    # industry_id : anonymized IDs represent industries
    # country : code of the country in which the job is offered
    # region : is specified for some users who have as country de.
    #           0 means not specified
    # latitude : latitude information (rounded to ca. 10km)
    # longitude : longitude information (rounded to ca. 10km)
    # employment : the type of employment:
    #    0 = unknown
    #    1 = full-time
    #    2 = part-time
    #    3 = freelancer
    #    4 = intern
    #    5 = voluntary
    # tags : concepts that have been extracted from the tags, skills 
    #        or company name
    # created_at : a Unix time stamp timestamp representing the time 
    #              when the interaction happened
    # active_during_test : is 1 if the item (job) is still active 
    #                      (= recommendable) during the test period and
    #                      0 if the item is not active anymore in the 
    #                      test period (= not recommendable)
    print(" # Loading item profiles' dataset...")
    item_profiles =  pd.read_csv("{}item_profile.csv".format(ROOT), sep="\t")
    print("   -> got {} rows".format(item_profiles.shape[0]))


    #### User Profiles' structure
    #
    # id : anonymized ID of the user (referenced as user_id in 
    #      the interaction dataset)
    # jobroles : comma-separated list of job role terms (numeric IDs)
    #            that were extracted from the user’s current job title. 
    #            0 means that there was no known jobrole detected for 
    #            the user.
    # career_level : career level ID (e.g. beginner, experienced, manager):
    #    0 = unknown
    #    1 = Student/Intern
    #    2 = Entry Level (Beginner)
    #    3 = Professional/Experienced
    #    4 = Manager (Manager/Supervisor)
    #    5 = Executive (VP, SVP, etc.)
    #    6 = Senior Executive (CEO, CFO, President)
    # discipline_id : anonymized IDs represent disciplines
    # industry_id : anonymized IDs represent industries
    # country : describes the country in which the user is now working:
    #    de = Germany
    #    at = Austria
    #    ch = Switzerland
    #    non_dach = non of the above countries
    # region : is specified for some users who have as country de. 
    #          0 means Not Specified
    # experience_n_entries_class : identifies the number of CV entries
    #                              the user has listed as work experiences:
    #    0 = no entries
    #    1 = 1-2 entries
    #    2 = 3-4 entries
    #    3 = 5 or more entries
    # experience_years_experience : number of years of work experience 
    #                               the user has:
    #    0 = unknown
    #    1 = less than 1 year
    #    2 = 1-3 years
    #    3 = 3-5 years
    #    4 = 5-10 years
    #    5 = 10-15 years
    #    6 = 16-20
    #    7 = more than 20 years
    # experience_years_in_current : number of years that the user is 
    #                               already working in her current job. 
    #           Meaning of numbers: same as experience_years_experience
    # edu_degree : university degree of the user:
    #    0 or NULL = unknown
    #    1 = bachelor
    #    2 = master
    #    3 = phd
    # edu_fieldofstudies : comma-separated fields of studies (anonymized
    #                      ids) that the user studied. 0 means “unknown”
    #                      and edu_fieldofstudies > 0 entries refer to 
    #                      broad field of studies
    print(" # Loading user profiles' dataset...")
    user_profiles = pd.read_csv("{}user_profile.csv".format(ROOT), sep="\t")
    print("   -> got {} rows".format(user_profiles.shape[0]))

    # Target users' structure
    # user_id
    print(" # Loading target users' dataset...")
    target_users = pd.read_csv("{}target_users.csv".format(ROOT), sep="\t")
    print("   -> got {} rows".format(target_users.shape[0]))

    end = time.time()

    print("\n---------- DATASETS LOADED IN {:.3f} sec -------------------------------------".format(end-start))
    print("------------------------------------------------------------------------------\n")



    ########  RUNNING LOOP ##################

    loaded = False
    while not loaded:
        try:
            import recommender as r
            import map_evaluator as e
            loaded = True
        except SyntaxError:
            print(traceback.format_exc())
            user_input = input("----> Press any key to retry...")
            
        
    exec_number = 0
    while True:
        user_input = input("\n # Press X to exit, F to load full datasets, L to load local datasets\n   or any other key to re-execute the recommender algorithm.\n")
        if user_input=="X" or user_input=="x":
            break
        if user_input=="F" or user_input=="f":
            training_set = TRAINING_FULL_SET
            int_training_map = pd.read_csv("{}{}".format(ROOT, training_set), sep="\t")
            continue
        if user_input=="L" or user_input=="l":
            training_set = TRAINING_LOCAL_SET
            int_training_map = pd.read_csv("{}{}".format(ROOT, training_set), sep="\t")
            continue
        
        try:
            il.reload(r)
            il.reload(e)
        except SyntaxError:
            print(traceback.format_exc())
            continue
        
        exec_number += 1
        start = 0
        end = 0
        print("\n--------------------------------------------------------------------".format(end-start))
        print("---------- START EXECUTION {} -------------------------------------\n".format(exec_number))
        try:
            start = time.time()
            user_ratings = r.recommend(int_training_map, item_profiles, user_profiles, target_users)
            end = time.time()
            
        # except Exception: CtrlC kills the runner too
        # except: CtrlC does NOT kill the runner at this stage
        except Exception:
            print("\n\n---> EXECUTION KILLED by an Exception:")
            print(traceback.format_exc())
            print("\n---------- EXECUTION COMPLETED WITH AN EXCEPTION ------------------".format(exec_number, end-start))
        except:
            end = time.time()
            print("\n\n---> EXECUTION KILLED (not by an Exception)")
            print("\n---------- EXECUTION INTERRUPTED at sec {:.3f} ------------------".format(end-start))
            end = 0
            
        if end != 0:
            print("\n---------- EXECUTION {} COMPLETED in {:.3f} sec --------------------".format(exec_number, end-start))

            # Do evaluate if I have a test_set to evaluate on
            if training_set == TRAINING_LOCAL_SET:  
                print("---> Evaluation:")
                try:
                    e.evaluate(int_test_map, user_ratings)
                    
                except Exception:
                    print(traceback.format_exc())
                    print("\n-----> Evaluation gave exception")
            else:
                print("---> Writing Submission File")
                r.writecsv(user_ratings, target_users)
            
        print("--------------------------------------------------------------------\n\n")
        

    print("\nThe runner's exiting. Bye bye!")
Example #37
0
def reco(request):
	if 'userid' in request.session:
		onlyonce=0
		reco=[]
		disjoint_movies = []

		glob_userid = request.session['userid']
		print "userid",glob_userid

		dat = Movie.objects.all().order_by("-movieid")



		val = Ratings.objects.filter(userid=glob_userid)
		uniq_rated_movieids = set(x.movieid for x in val)
		disjoint_movies=[x for x in dat if x.movieid not in uniq_rated_movieids]
		paginator = Paginator(disjoint_movies, 9)
		page = request.GET.get('page')
		try:
			contacts = paginator.page(page)
		except PageNotAnInteger:
		    # If page is not an integer, deliver first page.
		    contacts = paginator.page(1)
		except EmptyPage:
		    # If page is out of range (e.g. 9999), deliver last page of results.
		    contacts = paginator.page(paginator.num_pages)
		print "enterd reco"
		if request.method=='POST':
			name = request.POST['id']
			rating = request.POST['rat']
			print request.session['userid'],name,rating
			if int(rating)<=5:
				rat = Ratings.objects.filter(userid=glob_userid,movieid=int(name))
				if not rat:
					rate = Ratings(userid=glob_userid,movieid=int(name),rating=int(rating))
					rate.save()
					recomended = recommend(glob_userid)
					for x in recomended:
						reco.append(x['movieid'])
					recdat = Movie.objects.filter(movieid__in=reco)
			context = {'mov':contacts,'rating':rating,'id':int(name),'username':request.session['uname'],'userid':glob_userid,'contacts':contacts,'recommended':recdat}
			print "enterd if"
			return render(request,"movieapp/recommendation.html",context)
		else:
			print "enterd else"
			if onlyonce == 1:
				recomended = recommend(glob_userid)
				for x in recomended:
					reco.append(x['movieid'])
			else:
				recomended = loadmodel(glob_userid)
				for x in recomended:
					reco.append(x['movieid'])
			recdat = Movie.objects.filter(movieid__in=reco)
			print recdat
			for x in contacts:
				print x.moviename

			context = {'contacts':contacts,'mov':contacts,'username':request.session['uname'],'userid':glob_userid,'recommended':recdat}
			return render(request,"movieapp/recommendation.html",context)
	else:
		return redirect('login')