コード例 #1
0
def api_member_intake_meal(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"}, status=401)

    if request.method == "POST":
        json_request = json.loads(request.body)

        year = int(json_request["year"])
        month = int(json_request["month"])
        day = int(json_request["day"])
        today = date(year, month, day)

        CalorieIntake.objects.create(
            user=user,
            qty=1,
            meal=Meal.objects.get(id=json_request["id"]),
            eat_time=EatTime.objects.get(id=json_request["category_intake"]),
            created_at=today
        )

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Not Found"}, status=404)
コード例 #2
0
def api_login(request):
    if request.method == "POST":
        json_request = json.loads(request.body)
        input_email = json_request["email"]
        input_password = json_request["password"]

        try:
            user = User.objects.get(email=input_email)
            hashed = user.password.encode("utf-8")

            if bcrypt.checkpw(input_password.encode("utf-8"), hashed):
                return JsonResponse({"results": {
                    "role": user.role.id,
                    "name": user.name,
                    "token": JWT().encode({
                        "id": user.id,
                        "name": user.name,
                        "email": user.email
                    })
                }})

            else:
                return JsonResponse({"message": "Invalid credentials"}, status=400)

        except ObjectDoesNotExist:
            return JsonResponse({"message": "Invalid credentials"}, status=400)

    return JsonResponse({"message": "Not Found"}, status=404)
コード例 #3
0
def api_member_activity_label(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"}, status=401)

    if request.method == "GET":
        status = request.GET.get("status", "new")

        contain = []
        activities = Activity.objects.filter(Q(user=1) | Q(
            user=user.id)).values('label').annotate(
                total=Count('label')).order_by('label')
        for activity in activities:
            contain.append(activity['label'])

        if status == "new":
            labels = ActivityLabel.objects.exclude(id__in=contain).values(
                'id', 'met', 'name')
        else:
            labels = ActivityLabel.objects.filter(id__in=contain).values(
                'id', 'met', 'name')

        return JsonResponse({"results": {"activities": list(labels)}})

    return JsonResponse({"message": "Not Found"}, status=404)
コード例 #4
0
def quote_detail_api(request, quote_id):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "PUT":
        json_request = json.loads(request.body)
        author = json_request["author"]
        desc = json_request["desc"]

        quote = Quote.objects.get(id=quote_id)
        quote.desc = desc
        quote.author = author
        quote.save()

        return JsonResponse({"message": "Success"})

    if request.method == "DELETE":
        quote = Quote.objects.get(id=quote_id)
        quote.deleted_at = datetime.now()
        quote.save()

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Invalid Method"})
コード例 #5
0
def api_member_article_detail(request, article_id):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"}, status=401)

    if request.method == "GET":
        article = Article.objects.get(id=article_id)
        view = ArticleView.objects.filter(article=article)

        ArticleView.objects.create(article=article, user=user)

        return JsonResponse({
            "results": {
                "title": article.title,
                "image": article.image,
                "author": article.author,
                "content": article.content,
                "published_on": article.created_at,
                "view": len(view)
            }
        })

    return JsonResponse({"message": "Not Found"}, status=404)
コード例 #6
0
def calorie_intake_food_api(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "POST":
        json_request = json.loads(request.body)

        qty = json_request["qty"]
        food_id = json_request["food"]
        eat_time_id = json_request["eat_time"]

        food = Food.objects.get(id=food_id)
        eat_time = EatTime.objects.get(id=eat_time_id)
        CalorieIntake.objects.create(
            qty=qty,
            user=user,
            food=food,
            eat_time=eat_time
        )

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Invalid Method"})
コード例 #7
0
def api_member_activity_level_review(request):
    if request.method == "POST":
        bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
        user = JWT().decode(token)

        if user is None:
            return JsonResponse({"message": "Unauthorized"}, status=401)

        today = datetime.now().date()
        last30 = today + timedelta(-30)
        date_start = datetime.combine(last30, time())
        date_end = datetime.combine(today, time())

        calorie_burnt = CalorieBurnt.objects.filter(user=user.id,
                                                    created_at__gte=date_start,
                                                    created_at__lte=date_end,
                                                    deleted_at__isnull=True)

        energy = 0
        for calorie in calorie_burnt:
            energy += (calorie.duration * calorie.activity_label.met)

        activity_factor = energy / 3600 / 24 / 30
        level = clasify_activity_factor(activity_factor)
        bmr = calculate_bmr(user)

        tdee = activity_factor * bmr
        ActivityLevel.objects.create(level=level, tdee=tdee, user=user)

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Not Found"}, status=404)
コード例 #8
0
def api_check(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"}, status=401)

    return JsonResponse({"message": "Success"})
コード例 #9
0
def compare_api(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "POST":
        json_request = json.loads(request.body)

        raw_data = json_request["raw_data"]
        algorithm = json_request["algorithm"].lower()

        train_label = get_train_labels()
        train_feature = get_train_features(user.id)

        data_test = convert_raw_data_to_data_test(raw_data)

        start_training_time = time.time()
        clasification = choose_clasification(train_label, train_feature,
                                             algorithm)
        end_training_time = time.time()

        if clasification is None:
            return JsonResponse({"message": "Invalid Algorithm"})

        start_testing_time = time.time()
        predict = list(clasification.predict(data_test))
        end_testing_time = time.time()

        dict = {}
        predict.sort()
        for i in range(len(predict)):
            key = train_label[int(predict[i])]
            if key in dict:
                dict[key] += 1
            else:
                dict[key] = 1

        keys = list(dict.keys())
        print(keys)
        clasification_results = []
        for i in range(len(keys)):
            clasification_results.append({
                "label": keys[i],
                "value": dict[keys[i]]
            })

        return JsonResponse({
            "results": {
                "training_time": end_training_time - start_training_time,
                "testing_time": end_testing_time - start_testing_time,
                "clasification": clasification_results
            }
        })

    return JsonResponse({"message": "Invalid Method"})
コード例 #10
0
def article_api(request):

    if request.method == "GET":
        title = request.GET.get("title", "").lower()
        page = int(request.GET.get("page", 1))
        offset = (page - 1) * 30
        limit = offset + 30

        articles = Article.objects.all() if title == "" else \
            Article.objects.annotate(lower_title=Lower("title")).filter(lower_title__contains=title)

        total = len(articles)
        pages = ceil(total / 30)
        articles = articles[offset:limit]

        article_results = []
        for article in articles:
            article_results.append({
                "id": article.id,
                "title": article.title,
                "author": article.author,
                "published_on": article.created_at,
                "published_by": article.user.name
            })

        return JsonResponse({"results": {
            "total": total,
            "pages": pages,
            "articles": article_results,
        }})

    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "POST":
        json_request = json.loads(request.body)
        title = json_request["title"]
        author = json_request["author"]
        image = json_request["image"]
        content = json_request["content"]

        Article.objects.create(
            title=title,
            image=image,
            content=content,
            author=author,
            user=user
        )

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Invalid Method"})
コード例 #11
0
def check(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    print(JWT().decode(token))

    decode = JWT().decode(token)

    if decode is None:
        return JsonResponse({"message": "Token expired"})

    return JsonResponse({"message": "wow"})


#
# def register(request):
#
# def block(request):
#
# def update(request):
#
# def delete(request):
コード例 #12
0
def calorie_burnt_detail_api(request, activity_id):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "DELETE":
        CalorieBurnt.objects.get(user=user, id=activity_id).delete()
        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Invalid Method"})
コード例 #13
0
def api_article(request):
    if request.method == "GET":
        title = request.GET.get("title", "").lower()
        page = int(request.GET.get("page", 1))
        offset = (page - 1) * 30
        limit = offset + 30

        articles = Article.objects.all() if title == "" else \
            Article.objects.annotate(lower_title=Lower("title")).filter(lower_title__contains=title.lower())

        total = len(articles)
        pages = ceil(total / 30)
        articles = articles.annotate(published_by=F('user__name'), published_on=F('created_at')) \
            .values('id', 'title', 'author', 'published_on', 'published_by')[offset:limit]

        return JsonResponse({
            "results": {
                "total": total,
                "pages": pages,
                "articles": list(articles),
            }
        })

    if request.method == "POST":
        bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
        user = JWT().decode(token)

        if user is None:
            return JsonResponse({"message": "Unauthorized"}, status=401)

        json_request = json.loads(request.body)
        have_data = Article.objects.annotate(
            lower_title=Lower("title")).filter(
                lower_title__exact=json_request["title"].lower()).values(
                    'id', 'title')

        if len(have_data) > 0:
            return JsonResponse(
                {"message": json_request["title"] + " is already available."},
                status=400)

        Article.objects.create(
            user=user,
            title=json_request["title"],
            image=json_request["image"],
            content=json_request["content"],
            author=json_request["author"],
        )

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Not Found"}, status=404)
コード例 #14
0
def calorie_burnt_api(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "POST":
        json_request = json.loads(request.body)

        raw_data = json_request["raw_data"]
        requested_at = parse_datetime(json_request["requested_at"] + "+0700")

        train_label = get_train_labels()
        train_feature = get_train_features(user.id)

        data_test = convert_raw_data_to_data_test(raw_data)

        labels = train_feature[:, 0]
        features = train_feature[:, 1:]
        clasification = RKELM(train_label.shape[0]).fit(features, labels)
        predict = list(clasification.predict(data_test))

        dict = {}
        predict.sort()
        for i in range(len(predict)):
            key = train_label[int(predict[i])]
            dict[key] = dict[key] + 1 if key in dict else 1

        keys = list(dict.keys())
        results = []

        for i in range(len(keys)):
            label = ActivityLabel.objects.annotate(
                lower_name=Lower('name')).get(lower_name=keys[i])
            if (dict[keys[i]] / 2) > 0:
                CalorieBurnt.objects.create(user=user,
                                            activity_label=label,
                                            start_track=requested_at,
                                            duration=dict[keys[i]] / 2)
                results.append({
                    "label":
                    keys[i],
                    "time":
                    dict[keys[i]] / 2,
                    "burnt":
                    label.calorie * user.weight * (dict[keys[i]] / 2 / 60)
                })

        return JsonResponse({"results": results})

    return JsonResponse({"message": "Invalid Method"})
コード例 #15
0
def api_member_evaluation(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"}, status=401)

    if request.method == "GET":
        today = datetime.now()
        total_calorie = 0

        for i in range(30):
            date_start = datetime.combine(today + timedelta((i + 0) * -1),
                                          time())
            date_end = datetime.combine(today + timedelta((i - 1) * -1),
                                        time())
            calorie_burnt = CalorieBurnt.objects.filter(
                user=user,
                created_at__gte=date_start,
                created_at__lte=date_end,
                deleted_at__isnull=True)

            month_calorie = 0
            total_duration = 0
            for calorie in calorie_burnt:
                month_calorie += calorie.activity_label.met * user.weight * calorie.duration / 3600
                total_duration += calorie.duration

            if total_duration / (24 * 3600) >= 24:
                sitting = ((24 * 3600) - (total_duration /
                                          (24 * 3600))) * user.weight
                total_calorie += sitting

            total_calorie += (month_calorie / 24)

        total_calorie = (total_calorie / 30)

        result = clasify_activity_factor(total_calorie)

        tdee = total_calorie * calculate_bmr(user)
        # ActivityLevel.objects.create(
        #     level=result,
        #     tdee=tdee,
        #     user=user
        # )

        return JsonResponse({"results": clasify_bmi(user)})

    return JsonResponse({"message": "Not Found"}, status=404)
コード例 #16
0
def quote_api(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "GET":
        page = int(request.GET.get("page", 1))
        offset = (page - 1) * 30
        limit = offset + 30

        quotes = Quote.objects.all()
        total = len(quotes)
        pages = ceil(total / 30)
        quotes = quotes[offset:limit]

        quote_results = []
        for quote in quotes:
            quote_results.append({
                "id": quote.id,
                "desc": quote.desc,
                "author": quote.author
            })

        return JsonResponse({
            "results": {
                "total": total,
                "pages": pages,
                "quotes": quote_results,
                "last_date": (list(quotes)[-1]).created_at
            }
        })

    if request.method == "POST":
        json_request = json.loads(request.body)
        author = json_request["author"]
        desc = json_request["desc"]

        Quote.objects.create(
            user=user,
            desc=desc,
            author=author,
        )

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Invalid Method"})
コード例 #17
0
def api_member_recent(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"}, status=401)

    if request.method == "GET":
        calorie_intake = CalorieIntake.objects.filter(user=user).order_by('-created_at')

        list_date = []
        dist_date = {}
        for intake in calorie_intake:
            date = intake.created_at.strftime('%Y-%m-%d')
            if date not in dist_date:
                list_date.append(date)
                dist_date[date] = []

            if intake.food is not None:
                dist_date[date].append({
                    "id": intake.food.id,
                    "name": intake.food.name,
                    "calorie": intake.food.calorie,
                    "qty": intake.qty,
                    "type": "food"
                })

            if intake.meal is not None:
                calorie = 0
                details = MealDetail.objects.filter(meal=intake.meal)
                for detail in details:
                    calorie += (detail.food.calorie * detail.qty)

                dist_date[date].append({
                    "id": intake.meal.id,
                    "name": intake.meal.name,
                    "calorie": calorie,
                    "qty": intake.qty,
                    "type": "meal"
                })

        return JsonResponse({"results": {
            "dates": list_date,
            "foods": dist_date
        }})

    return JsonResponse({"message": "Not Found"}, status=404)
コード例 #18
0
def api_member_intake(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"}, status=401)

    if request.method == "DELETE":
        json_request = json.loads(request.body)
        for data in json_request["data"]:
            intake = CalorieIntake.objects.get(id=data, eat_time=EatTime.objects.get(id=json_request["eat_time"]))
            intake.deleted_at = datetime.now()
            intake.save()

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Not Found"}, status=404)
コード例 #19
0
def api_member_meal_detail(request, meal_id):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"}, status=401)

    if request.method == "GET":
        results = []
        meal = Meal.objects.get(id=meal_id)
        meal_details = MealDetail.objects.filter(meal=meal)

        calories = 0
        fats = 0
        proteins = 0
        carbohydrates = 0
        detail = []

        for meal_detail in meal_details:
            calories += meal_detail.food.calorie
            fats += meal_detail.food.fat
            proteins += meal_detail.food.protein
            carbohydrates += meal_detail.food.carbohydrate
            detail.append({
                "qty": meal_detail.qty,
                "name": meal_detail.food.name,
                "calorie": meal_detail.food.calorie,
                "carbohydrate": meal_detail.food.carbohydrate,
                "protein": meal_detail.food.protein,
                "fat": meal_detail.food.fat
            })

        return JsonResponse({
            "results": {
                "meal": {
                    "id": meal.id,
                    "name": meal.name,
                    "calorie": calories,
                    "fat": fats,
                    "protein": proteins,
                    "carbohydrate": carbohydrates,
                    "meal_detail": detail
                }
            }
        })
コード例 #20
0
def meal_detail_api(request, meal_id):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "GET":
        meal = Meal.objects.get(Q(user=1) | Q(user=user), id=meal_id)
        meal_details = MealDetail.objects.filter(meal=meal)

        fat = 0
        protein = 0
        calorie = 0
        carbohydrate = 0
        foods = []

        for meal_detail in meal_details:
            fat += meal_detail.food.fat
            protein += meal_detail.food.protein
            calorie += meal_detail.food.calorie
            carbohydrate += meal_detail.food.carbohydrate
            foods.append({
                "qty": meal_detail.food.qty,
                "name": meal_detail.food.name,
                "calorie": meal_detail.food.calorie,
            })

        return JsonResponse({
            "results": {
                "id": meal.id,
                "name": meal.name,
                "foods": foods,
                "info": {
                    "fat": fat,
                    "protein": protein,
                    "calorie": calorie,
                    "carbohydrate": carbohydrate,
                }
            }
        })

    return JsonResponse({"message": "Invalid Method"})
コード例 #21
0
def api_confirm_email(request, confirm_email):
    if request.method == "POST":
        try:
            user = User.objects.get(confirm_email=confirm_email)

            return JsonResponse({"results": {
                "role": user.role.id,
                "name": user.name,
                "email": user.email,
                "token": JWT().encode({
                    "id": user.id,
                    "name": user.name,
                    "email": user.email
                })
            }})

        except ObjectDoesNotExist:
            return JsonResponse({"message": "Invalid Email"}, status=400)

    return JsonResponse({"message": "Not Found"}, status=404)
コード例 #22
0
def activity_level_new_api(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "POST":
        json_request = json.loads(request.body)
        level = json_request["level"]

        activity_factor = calculate_activity_factor(user, level)
        bmr = calculate_bmr(user)
        tdee = activity_factor * bmr

        ActivityLevel.objects.create(tdee=tdee, user=user, level=level)

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Invalid Method"})
コード例 #23
0
def api_member_activity_level(request):
    if request.method == "POST":
        bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
        user = JWT().decode(token)

        if user is None:
            return JsonResponse({"message": "Unauthorized"}, status=401)

        json_request = json.loads(request.body)
        activity_factor = calculate_activity_factor(
            user, json_request["activity_level"])
        bmr = calculate_bmr(user)

        tdee = activity_factor * bmr
        ActivityLevel.objects.create(level=json_request["activity_level"],
                                     tdee=tdee,
                                     user=user)

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Not Found"}, status=404)
コード例 #24
0
def meal_api(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "POST":
        json_request = json.loads(request.body)
        name = json_request["name"]
        foods = json_request["foods"]

        meal = Meal.objects.create(Q(user=1) | Q(user=user), name=name)
        for food in foods:
            obj_food = Food.objects.get(id=food["id"])
            MealDetail.objects.create(meal=meal,
                                      food=obj_food,
                                      qty=food["qty"])

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Invalid Method"})
コード例 #25
0
def activity_level_review_api(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "POST":
        last_date_activity = ActivityLevel.objects.filter(
            user=user).latest("created_at")
        current_date = datetime.now()

        activities = CalorieBurnt.objects.filter(user=user, start_track__range=(last_date_activity, current_date)) \
            .values("activity_label__met") \
            .annotate(count_duration=Sum("duration")) \

        pal = 0
        for activity in activities:
            pal += (activity["activity_label__met"] *
                    activity["count_duration"])

        pal = pal / (24 * 30)

        if user.gender.id == 1 and pal < 1.56:
            pal = 1.56
        elif user.gender.id == 2 and pal < 1.55:
            pal = 1.55

        level = clasify_activity_factor(pal)
        bmr = calculate_bmr(user)
        tdee = pal * bmr

        ActivityLevel.objects.create(tdee=tdee, user=user, level=level)

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Invalid Method"})
コード例 #26
0
def app_api(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "GET":
        list_history_search = HistorySearch.objects.filter(
            user=user).order_by("-created_at")[:5]
        results = []

        for history_search in list_history_search:
            results.append(history_search.name)

        return JsonResponse({"results": results})

    if request.method == "POST":
        json_request = json.loads(request.body)
        HistorySearch.objects.create(name=json_request["search"], user=user)

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Invalid Method"})
コード例 #27
0
def api_quote(request):
    if request.method == "GET":
        page = int(request.GET.get("page", 1))
        offset = (page - 1) * 30
        limit = offset + 30

        quotes = Quote.objects.all()
        total = len(quotes)
        pages = ceil(total / 30)
        date = list(quotes)[-1].created_at if total > 0 else ''
        quotes = quotes.values('id', 'desc', 'author')[offset:limit]

        return JsonResponse({ "results": {
            "total": total,
            "pages": pages,
            "date": date,
            "quotes": list(quotes),
        }})

    if request.method == "POST":
        bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
        user = JWT().decode(token)

        if user is None:
            return JsonResponse({"message": "Unauthorized"}, status=401)

        json_request = json.loads(request.body)
        Quote.objects.create(
            user=user,
            desc=json_request["desc"],
            author=json_request["author"],
        )

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Not Found"}, status=404)
コード例 #28
0
def dairy_view(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "GET":
        requested_at = parse_datetime(
            request.GET.get('requested_at', '') + "+0700")

        current_datetime = datetime.now()
        today_min = datetime.combine(requested_at.date(), time.min)
        today_max = datetime.combine(requested_at.date(), time.max)
        activity_level = ActivityLevel.objects.filter(
            user=user).latest("created_at")

        if (current_datetime - activity_level.created_at).days > 30:
            return JsonResponse({"message": "Review"})

        goal_calorie_burnt = activity_level.tdee
        goal_calorie_intake = activity_level.tdee + additional_goal_calorie_intake(
            user)

        list_calorie_burnt = CalorieBurnt.objects.filter(
            user=user, start_track__range=(today_min, today_max))
        list_calorie_intake = CalorieIntake.objects.filter(
            user=user, created_at__range=(today_min, today_max))

        total_calorie_burnt = 0
        total_calorie_intake = 0
        total_carbohydrate = 0
        total_protein = 0
        total_fat = 0

        list_activity = []

        for calorie_burnt in list_calorie_burnt:
            calorie = calorie_burnt.activity_label.met * user.weight * (
                calorie_burnt.duration / 3600)
            total_calorie_burnt += calorie

            list_activity.append({
                "id": calorie_burnt.id,
                "calorie": calorie,
                "duration": calorie_burnt.duration,
                "start_track": calorie_burnt.start_track,
                "label": calorie_burnt.activity_label.name,
            })

        dict_food = {}
        for calorie_intake in list_calorie_intake:
            calorie = 0
            label = ""

            if calorie_intake.food is not None:
                label = calorie_intake.food.name
                calorie += calorie_intake.food.calorie * calorie_intake.qty
                total_carbohydrate += calorie_intake.food.carbohydrate
                total_protein += calorie_intake.food.protein
                total_fat += calorie_intake.food.fat

            elif calorie_intake.meal is not None:
                label = calorie_intake.meal.name
                meal_details = MealDetail.objects.filter(
                    meal=calorie_intake.meal)
                for meal_detail in meal_details:
                    calorie += meal_detail.food.calorie * meal_detail.qty
                    total_carbohydrate += meal_detail.food.carbohydrate
                    total_protein += meal_detail.food.protein
                    total_fat += meal_detail.food.fat

            total_calorie_intake += calorie

            if calorie_intake.eat_time.name not in dict_food:
                dict_food[calorie_intake.eat_time.name] = {
                    "total":
                    goal_calorie_intake * calorie_intake.eat_time.percentage /
                    100,
                    "list": []
                }

            dict_food[calorie_intake.eat_time.name]["list"].append({
                "id":
                calorie_intake.id,
                "label":
                label,
                "calorie":
                calorie,
                "qty":
                calorie_intake.qty,
            })

        percentage_fat = total_fat / (0.25 * activity_level.tdee / 9)
        percentage_protein = total_protein / (0.15 * activity_level.tdee / 4)
        percentage_carbohydrate = total_carbohydrate / (
            0.6 * activity_level.tdee / 4)

        return JsonResponse({
            "results": {
                "calorie_burnt": {
                    "goal": goal_calorie_burnt,
                    "total": total_calorie_burnt
                },
                "calorie_intake": {
                    "goal": goal_calorie_intake,
                    "total": total_calorie_intake
                },
                "nutrient": {
                    "fat": percentage_fat,
                    "protein": percentage_protein,
                    "carbohydrate": percentage_carbohydrate
                },
                "food": dict_food,
                "exercise": list_activity
            }
        })

    return JsonResponse({"message": "Invalid Method"})
コード例 #29
0
def api_member_burnt(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"})

    if request.method == "POST":
        json_request = json.loads(request.body)

        raw_data = json_request["raw_data"]
        requested_at = datetime.now()

        train_label = get_train_labels()
        train_feature = get_train_features(user.id)

        data_test = convert_raw_data_to_data_test(raw_data)

        labels = train_feature[:, 0]
        features = train_feature[:, 1:]
        clasification = RKELM(train_label.shape[0]).fit(features, labels)
        predict = list(clasification.predict(data_test))

        dict = {}
        predict.sort()
        for i in range(len(predict)):
            key = train_label[int(predict[i])]
            dict[key] = dict[key] + 1 if key in dict else 1

        keys = list(dict.keys())
        results = []

        for i in range(len(keys)):
            label = ActivityLabel.objects.annotate(
                lower_name=Lower('name')).get(lower_name=keys[i])
            if (dict[keys[i]] / 2) >= 1:
                CalorieBurnt.objects.create(user=user,
                                            activity_label=label,
                                            start_track=requested_at,
                                            duration=int(dict[keys[i]] / 2))
                results.append({
                    "label":
                    keys[i],
                    "time":
                    dict[keys[i]] / 2,
                    "burnt":
                    label.met * user.weight * (int(dict[keys[i]] / 2) / 3600)
                })

        return JsonResponse({
            "results": results,
            "keys": keys,
            "predict": predict,
            "len_1": len(data_test),
            "len_2": len(predict)
        })

    if request.method == "DELETE":
        json_request = json.loads(request.body)
        for data in json_request["data"]:
            burnt = CalorieBurnt.objects.get(id=data)
            burnt.deleted_at = datetime.now()
            burnt.save()

        return JsonResponse({"message": "Success"})

    return JsonResponse({"message": "Invalid Method"})
コード例 #30
0
def api_member_diary(request):
    bearer, token = request.META.get('HTTP_AUTHORIZATION').split()
    user = JWT().decode(token)

    if user is None:
        return JsonResponse({"message": "Unauthorized"}, status=401)

    if request.method == "GET":
        year = int(request.GET.get("year"))
        month = int(request.GET.get("month"))
        day = int(request.GET.get("day"))
        today = date(year, month, day)
        tomorrow = today + timedelta(+1)
        date_start = datetime.combine(today, time())
        date_end = datetime.combine(tomorrow, time())

        calorie_intake = CalorieIntake.objects.filter(user=user.id,
                                                      created_at__gte=today,
                                                      created_at__lt=tomorrow)
        calorie_burnt = CalorieBurnt.objects.filter(user=user.id,
                                                    created_at__gte=date_start,
                                                    created_at__lt=date_end,
                                                    deleted_at__isnull=True)

        dict_activity = {}
        burnt = []
        total_calorie_burnt = 0
        for calorie in calorie_burnt:
            if calorie.activity_label.name not in dict_activity:
                dict_activity[calorie.activity_label.name] = {
                    "id": [],
                    "duration": 0,
                    "calorie": 0
                }
            dict_activity[calorie.activity_label.name]["id"].append(calorie.id)
            dict_activity[
                calorie.activity_label.name]["duration"] += calorie.duration
            dict_activity[calorie.activity_label.name][
                "calorie"] += calorie.activity_label.met * user.weight * (
                    calorie.duration / 3600)
            total_calorie_burnt += calorie.activity_label.met * user.weight * (
                calorie.duration / 3600)

        for key, value in dict_activity.items():
            burnt.append({
                "label": key,
                "id": dict_activity[key]["id"],
                "duration": dict_activity[key]["duration"],
                "calorie": dict_activity[key]["calorie"]
            })

        intake = {"breakfast": [], "lunch": [], "dinner": [], "snack": []}
        nutrient = {
            "fat": 0,
            "protein": 0,
            "carbohydrate": 0,
            "total_fat": 0,
            "total_protein": 0,
            "total_carbohydrate": 0
        }

        total_calorie_intake = 0
        total_breakfast = 0
        total_lunch = 0
        total_dinner = 0
        total_snack = 0
        for calorie in calorie_intake:
            total_calorie = 0
            if calorie.meal is not None:
                details = MealDetail.objects.filter(meal=calorie.meal)
                for detail in details:
                    total_calorie += (detail.food.calorie * detail.qty)
                    nutrient["fat"] += (detail.food.fat * detail.qty *
                                        calorie.qty)
                    nutrient["protein"] += (detail.food.protein * detail.qty *
                                            calorie.qty)
                    nutrient["carbohydrate"] += (detail.food.carbohydrate *
                                                 detail.qty * calorie.qty)

            elif calorie.food is not None:
                total_calorie = calorie.food.calorie
                nutrient["fat"] += calorie.food.fat * calorie.qty
                nutrient["protein"] += calorie.food.protein * calorie.qty
                nutrient[
                    "carbohydrate"] += calorie.food.carbohydrate * calorie.qty

            data = {
                "id":
                calorie.id,
                "qty":
                calorie.qty,
                "name":
                calorie.food.name
                if calorie.food is not None else calorie.meal.name,
                "calorie":
                total_calorie
            }

            if calorie.eat_time.id == 1:
                intake["breakfast"].append(data)
                total_breakfast += (total_calorie * calorie.qty)
            elif calorie.eat_time.id == 2:
                intake["lunch"].append(data)
                total_lunch += (total_calorie * calorie.qty)
            elif calorie.eat_time.id == 3:
                intake["dinner"].append(data)
                total_dinner += (total_calorie * calorie.qty)
            elif calorie.eat_time.id == 4:
                intake["snack"].append(data)
                total_snack += (total_calorie * calorie.qty)

            total_calorie_intake += (total_calorie * calorie.qty)

        activity_level = list(
            ActivityLevel.objects.filter(user=user).order_by("-created_at"))[0]
        eat_time = list(EatTime.objects.all())

        recommendation_calorie = {
            "breakfast": activity_level.tdee * eat_time[0].percentage / 100,
            "lunch": activity_level.tdee * eat_time[1].percentage / 100,
            "dinner": activity_level.tdee * eat_time[2].percentage / 100,
            "snack": activity_level.tdee * eat_time[3].percentage / 100
        }

        recommendation_activity = {
            "breakfast": {
                "running": 0,
                "walking": 0,
                "stair": 0
            },
            "lunch": {
                "running": 0,
                "walking": 0,
                "stair": 0
            },
            "dinner": {
                "running": 0,
                "walking": 0,
                "stair": 0
            },
            "snack": {
                "running": 0,
                "walking": 0,
                "stair": 0
            }
        }

        met = []
        activities = ActivityLabel.objects.filter(id__in=[2, 3, 4])
        for activity in activities:
            met.append(activity.met)

        if recommendation_calorie["breakfast"] < total_breakfast:
            diff = total_breakfast - recommendation_calorie["breakfast"]
            recommendation_activity["breakfast"]["walking"] = int(
                diff * 3600) / (met[0] * user.weight)
            recommendation_activity["breakfast"]["running"] = int(
                diff * 3600) / (met[1] * user.weight)
            recommendation_activity["breakfast"]["stair"] = int(
                diff * 3600) / (met[2] * user.weight)

        if recommendation_calorie["lunch"] < total_lunch:
            diff = total_lunch - recommendation_calorie["lunch"]
            recommendation_activity["lunch"]["walking"] = int(
                diff * 3600) / (met[0] * user.weight)
            recommendation_activity["lunch"]["running"] = int(
                diff * 3600) / (met[1] * user.weight)
            recommendation_activity["lunch"]["stair"] = int(
                diff * 3600) / (met[2] * user.weight)

        if recommendation_calorie["dinner"] < total_dinner:
            diff = total_dinner - recommendation_calorie["dinner"]
            recommendation_activity["dinner"]["walking"] = int(
                diff * 3600) / (met[0] * user.weight)
            recommendation_activity["dinner"]["running"] = int(
                diff * 3600) / (met[1] * user.weight)
            recommendation_activity["dinner"]["stair"] = int(
                diff * 3600) / (met[2] * user.weight)

        if recommendation_calorie["snack"] < total_snack:
            diff = total_snack - recommendation_calorie["snack"]
            recommendation_activity["snack"]["walking"] = int(
                diff * 3600) / (met[0] * user.weight)
            recommendation_activity["snack"]["running"] = int(
                diff * 3600) / (met[1] * user.weight)
            recommendation_activity["snack"]["stair"] = int(
                diff * 3600) / (met[2] * user.weight)

        bmi = calculate_bmi(user)
        calorie = {
            "intake": total_calorie_intake,
            "total_intake": activity_level.tdee,
            "burnt": total_calorie_burnt,
            "total_burnt": activity_level.tdee,
        }

        if bmi < 18.5:
            calorie["total_intake"] += 500
        elif bmi >= 25.0:
            calorie["total_intake"] -= 500

        nutrient["total_fat"] = 0.25 * activity_level.tdee / 9
        nutrient["total_protein"] = 0.15 * activity_level.tdee / 4
        nutrient["total_carbohydrate"] = 0.6 * activity_level.tdee / 4

        activity_1 = Activity.objects.filter(
            user=user, label=ActivityLabel.objects.get(id=2)).values('id')
        activity_2 = Activity.objects.filter(
            user=user, label=ActivityLabel.objects.get(id=3)).values('id')
        activity_3 = Activity.objects.filter(
            user=user, label=ActivityLabel.objects.get(id=4)).values('id')

        return JsonResponse({
            "results": {
                "calorie":
                calorie,
                "intake":
                intake,
                "burnt":
                burnt,
                "nutrient":
                nutrient,
                "recommendation_calorie":
                recommendation_calorie,
                "recommendation_activity":
                recommendation_activity,
                "activity": [
                    len(list(activity_1)),
                    len(list(activity_2)),
                    len(list(activity_3))
                ],
                "tanggal": {
                    "today": today,
                    "date_start": date_start,
                    "date_end": date_end,
                    "sql": calorie_intake.query.__str__()
                }
            }
        })

    return JsonResponse({"message": "Not Found"}, status=404)