예제 #1
0
def index():
    max_show = 12  # Maximum of snacks to show
    snacks = Snack.objects
    top_snacks = snacks.order_by("-avg_overall_rating")
    featured_snacks = []
    recommended_snacks = []
    notification_messages = []  # Some useful messages can be registered here
    # Getting snacks that have some image to display
    for snack in top_snacks:
        if snack.photo_files:
            featured_snacks.append(snack)
            if len(featured_snacks) == max_show:
                break
    # Recommends tailored snacks to the user (if logged in)
    if current_user.is_authenticated:
        country = ""
        try:
            country = current_user.last_country
        except:
            print("No last country")
        country = country if country else "Canada"  # Default is canada, if not found
        # Some special user cases for demonstration purposes
        country = "China" if current_user.email == "*****@*****.**" else country
        country = "Mexico" if current_user.email == "*****@*****.**" else country
        country = "Brazil" if current_user.email == "*****@*****.**" else country
        recommended_snacks = recommender.recommend_snacks(
            current_user,
            Review.objects(user_id=current_user.id),
            country,
            num_snacks=12,
            msgs=notification_messages)

    # Use JS Queries later
    # Needs to be a divisor of 12
    interesting_facts = []
    interesting_facts.extend([("Snacks", snacks.count()),
                              ("Reviews", Review.objects.count()),
                              ("Five stars given",
                               Review.objects(overall_rating=5).count())])

    snack_names = sorted(list(set(snacks.all().values_list('snack_name'))))
    snack_brands = sorted(list(set(snacks.all().values_list('snack_brand'))))
    all_countries = generate_unique_countries()
    # This is a rare case if the db has NO countries at all, then we just add 'Canada'
    all_countries = ["Canada"] if not all_countries else all_countries
    context_dict = {
        "title": "Index",
        "featured_snacks": featured_snacks,
        "recommended_snacks": recommended_snacks,
        "notification_messages": notification_messages,
        "top_snacks": snacks.order_by("-avg_overall_rating")[:12],
        "popular_snacks": snacks.order_by("-review_count")[:12],
        "interesting_facts": interesting_facts,
        "user": current_user,
        "snack_names": snack_names,
        "snack_brands": snack_brands,
        "all_countries": all_countries
    }
    return render_template('index.html', **context_dict)
예제 #2
0
    def setUp(self):
        self._db_path = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 'test.db')
        if os.path.exists(self._db_path):
            os.remove(self._db_path)
        self._db = PeerReviewDB('sqlite:///' + self._db_path, echo=False)

        # define test records
        self._test_users = [
            User(id=0, login='******'),
            User(id=1, login='******'),
            User(id=2, login='******'),
        ]

        self._test_tasks = [
            Task(name='task0'),
            Task(name='task1'),
            Task(name='task2'),
        ]

        self._test_user_tasks = [
            UserTask(user=self._test_users[0],
                     task=self._test_tasks[0],
                     url='!',
                     status=TaskStatus.WAITING_REVIEW,
                     timestamp=0),
            UserTask(user=self._test_users[0],
                     task=self._test_tasks[1],
                     url='@',
                     status=TaskStatus.COMPLETE,
                     timestamp=1),
            UserTask(user=self._test_users[1],
                     task=self._test_tasks[0],
                     url='#',
                     status=TaskStatus.IN_WORK,
                     timestamp=0),
            UserTask(user=self._test_users[2],
                     task=self._test_tasks[2],
                     url='^',
                     status=TaskStatus.COMPLETE,
                     timestamp=0),
        ]

        self._test_reviews = [
            Review(reviewer=self._test_users[0],
                   reviewed_task=self._test_user_tasks[2],
                   status=ReviewStatus.IN_WORK,
                   issue_url='$'),
            Review(reviewer=self._test_users[1],
                   reviewed_task=self._test_user_tasks[1],
                   status=ReviewStatus.CLOSED,
                   issue_url='%'),
        ]
def index():
    if current_user.is_authenticated:
        print("ok")
    max_show = 5  # Maximum of snacks to show
    snacks = Snack.objects
    popular_snacks = snacks.order_by("-review_count")[:max_show]
    top_snacks = snacks.order_by("-avg_overall_rating")
    featured_snacks = []
    # Getting snacks that have some image to display
    for snack in top_snacks:
        if snack.photo_files:
            featured_snacks.append(snack)
            if len(featured_snacks) == max_show:
                break
    # TODO: Recommend snacks tailored to user
    # featured_snacks = top_snacks

    # Use JS Queries later
    # Needs to be a divisor of 12
    interesting_facts = []
    interesting_facts.append(("Snacks", snacks.count()))
    interesting_facts.append(("Reviews", Review.objects.count()))
    interesting_facts.append(
        ("Five stars given", Review.objects(overall_rating=5).count()))

    context_dict = {
        "title": "Index",
        "featured_snacks": featured_snacks,
        "top_snacks": snacks.order_by("-avg_overall_rating")[:5],
        "popular_snacks": snacks.order_by("-review_count")[:5],
        "interesting_facts": interesting_facts,
        "user": current_user
    }
    return render_template('index.html', **context_dict)
def commit_normal_review_database(user, snack, geoloc="Canada", rating=1):
    user_id = user.id
    snack_id = snack.id
    try:
        new_review = Review(user_id=user_id,
                            snack_id=snack_id,
                            geolocation=geoloc,
                            overall_rating=rating)
        new_review.save()

        avg_overall_rating = Review.objects.filter(
            snack_id=snack_id).average('overall_rating')

        snack.update(set__avg_overall_rating=avg_overall_rating)

        review_count = snack.review_count + 1
        snack.update(set__review_count=review_count)
        if review_count > 10:
            snack.update(set__is_verified=True)
        snack.update(add_to_set__available_at_locations=geoloc)

    except:
        print(f" Couldn't add review {new_review}")
예제 #5
0
파일: review.py 프로젝트: yogurtkun/Sponge
def addReview(reviewer, reviewee, rating, content, orderId):
    time = datetime.datetime.now(pytz.timezone('US/Eastern'))
    review = Review(reviewer=reviewer,
                    reviewee=reviewee,
                    rating=rating,
                    content=content,
                    orderId=orderId,
                    time=time)
    try:
        db.session.add(review)
        db.session.commit()
        if not account.updateRating(reviewee, rating):
            return None
        return from_sql(review)
    except Exception as e:
        print e
        db.session.rollback()
        return None
def hello_world():
    snacks = Snack.objects
    popular_snacks = snacks.order_by("-review_count")[:5]
    top_snacks = snacks.order_by("-avg_overall_rating")[:5]
    # TODO: Recommend snacks tailored to user
    featured_snacks = top_snacks

    # Use JS Queries later
    # Needs to be a divisor of 12
    interesting_facts = []
    interesting_facts.append(("Snacks", Snack.objects.count()))
    interesting_facts.append(("Reviews", Review.objects.count()))
    interesting_facts.append(
        ("Five stars given", Review.objects(overall_rating=5).count()))

    context_dict = {
        "title": "Index",
        "featured_snacks": snacks.order_by("-avg_overall_rating")[:5],
        "top_snacks": snacks.order_by("-avg_overall_rating")[:5],
        "popular_snacks": snacks.order_by("-review_count")[:5],
        "interesting_facts": interesting_facts,
        "user": current_user
    }
    return render_template('index.html', **context_dict)
예제 #7
0
                f"The model file does not exists ({self.model_filename}). Please refer to the README.md for instructions about how to download the trained ML model!"
            )
        # Update current model attributes from the file
        with open(self.model_filename, 'rb') as f:
            self.model = pickle.load(f)
            self.recc = self.model["model"]
            self.snackID_to_index = self.model["snackID_to_index"]
            self.index_to_snackID = self.model["index_to_snackID"]
            self.index_snack = self.model["index_snack"]
            self.userID_to_index = self.model["userID_to_index"]
            self.index_to_userID = self.model["index_to_userID"]
            self.index_user = self.model["index_user"]


if __name__ == "__main__":
    # TESTING with:
    # Salty user Katrina beck, ID: 5bfcc6e767afee10a880f8f5
    mongo = prepare_mongodb(
        mongo_uri=
        "mongodb+srv://Jayde:[email protected]/test?retryWrites=true"
    )
    salty_user_id = "5bfcc6e767afee10a880f8f5"
    katrina = User.objects(id=salty_user_id)[0]
    country_katrina = "Vietnam"
    review_from_katrina = Review.objects(user_id=salty_user_id)
    print(katrina)
    print(f"Katrina has done {len(review_from_katrina)} reviews!!")
    # Create a new recommender
    rec = Recommender()
    print(rec.recommend_snacks(katrina, review_from_katrina, country_katrina))
예제 #8
0
def create_review(snack):
    # check authenticated
    if not current_user.is_authenticated:
        return redirect(url_for('index'))

    print(f"is_authenticated\n", file=sys.stdout)

    review_form = CreateReviewForm(request.form)

    # post to db
    if request.method == "POST":
        user_id = current_user.id
        snack_id = snack.split('=')[1]
        snackObject = Snack.objects(id=snack_id)

        saltiness_review = request.form['saltiness']
        sweetness_review = request.form['sweetness']
        spiciness_review = request.form['spiciness']
        bitterness_review = request.form['bitterness']
        sourness_review = request.form['sourness']
        overall_rating_review = request.form['overall_rating']

        # check if metric review
        if saltiness_review == 0 and sourness_review == 0 and spiciness_review == 0 \
            and bitterness_review == 0 and sweetness_review == 0:

            try:
                # user_id comes from current_user
                # snack_id should come from request sent by frontend
                # geolocation is found by request
                new_review = Review(user_id=user_id,
                                    snack_id=snack_id,
                                    description=request.form['description'],
                                    geolocation=request.form['review_country'],
                                    overall_rating=overall_rating_review)
                new_review.save()

                avg_overall_rating = Review.objects.filter(
                    snack_id=snack_id).average('overall_rating')

                snackObject.update(set__avg_overall_rating=avg_overall_rating)

                review_count = snackObject[0].review_count + 1
                snackObject.update(set__review_count=review_count)
                if review_count > 10:
                    snackObject.update(set__is_verified=True)
                snackObject.update(add_to_set__available_at_locations=request.
                                   form['review_country'])

            except Exception as e:
                raise Exception(
                    f"Error {e}. \n Couldn't add review {new_review},\n with following review form: {review_form}"
                )

            print(f"A new user submitted the review form: {user_id}",
                  file=sys.stdout)
            return redirect(url_for('find_reviews_for_snack', filters=snack))

        else:
            try:
                # user_id comes from current_user
                # snack_id should come from request sent by frontend
                # geolocation is found by request
                snack_metric_review = MetricReview(
                    user_id=user_id,
                    snack_id=snack_id,
                    description=request.form['description'],
                    geolocation=request.form['review_country'],
                    overall_rating=overall_rating_review,
                    sourness=sourness_review,
                    spiciness=spiciness_review,
                    saltiness=saltiness_review,
                    bitterness=bitterness_review,
                    sweetness=sweetness_review)
                snack_metric_review.save()

                avg_overall_rating = Review.objects.filter(
                    snack_id=snack_id).average('overall_rating')
                avg_sourness = Review.objects.filter \
                    (Q(snack_id=snack_id) & Q(sourness__exists=True)).average("sourness")
                avg_spiciness = Review.objects.filter \
                    (Q(snack_id=snack_id) & Q(spiciness__exists=True)).average("spiciness")
                avg_bitterness = Review.objects.filter \
                    (Q(snack_id=snack_id) & Q(bitterness__exists=True)).average("bitterness")
                avg_sweetness = Review.objects.filter \
                    (Q(snack_id=snack_id) & Q(sweetness__exists=True)).average("sweetness")
                avg_saltiness = Review.objects.filter \
                    (Q(snack_id=snack_id) & Q(saltiness__exists=True)).average("saltiness")

                snackObject.update(set__avg_overall_rating=avg_overall_rating)
                snackObject.update(set__avg_sourness=avg_sourness)
                snackObject.update(set__avg_spiciness=avg_spiciness)
                snackObject.update(set__avg_bitterness=avg_bitterness)
                snackObject.update(set__avg_sweetness=avg_sweetness)
                snackObject.update(set__avg_saltiness=avg_saltiness)

                review_count = snackObject[0].review_count + 1
                snackObject.update(set__review_count=review_count)
                if review_count > 10:
                    snackObject.update(set__is_verified=True)
                snackObject.update(add_to_set__available_at_locations=request.
                                   form['review_country'])

            except Exception as e:
                raise Exception(
                    f"Error {e}. \n Couldn't add metric review {snack_metric_review},\n with following review form: {review_form}"
                )

            print(f"A new user submitted the review form: {user_id}",
                  file=sys.stdout)
            return redirect(url_for('find_reviews_for_snack', filters=snack))

    context_dict = {
        "title": "Create Review",
        "form": review_form,
        "user": current_user
    }
    # frontend stuff
    return render_template("reviews_for_snack.html", **context_dict)