def update_weight_database():
    for k, v in {
            WEIGHT_CATEGORY_NAME: WEIGHT_CATEGORY,
            WEIGHT_DESCRIPTION_NAME: WEIGHT_DESCRIPTION_TEXT,
            WEIGHT_WEBSITE_NAME: WEIGHT_WEBSITE_TEXT
    }.items():
        Weight(name=k, weight=v).save()
예제 #2
0
def add_weight():
    data = request.get_json()

    new_weight = Weight(uid=data['user_id'],
                        weight=data['weight'],
                        date=data['date'])

    db.session.add(new_weight)
    db.session.commit()

    return jsonify({
        'message': 'Weight log added successfully!',
        'status': 200
    })
예제 #3
0
파일: app.py 프로젝트: TheRijn/HCI-arris3
def home():
    print(request.form)

    user: User = current_user

    weights = user.weights_dict()
    steps = user.steps_dict()
    today = datetime.today()
    points = []
    message = "You can still log your current weight and steps to gain points, make over 10000 steps to make even more points."
    for weight in weights:
        if (today.strftime("%m/%d/%y") in weight.values()):
            points.append(40)
            message = "Try to make more then 10000 steps tommorow to gain the last 20 points."
            break

    for step in steps:
        if (today.strftime("%m/%d/%y") in step.values()):
            points.append(40)
            message = "Try to make more then 10000 steps tommorow to gain the last 20 points."
            if (step['series'] > 10000):
                points.append(20)
                message = "You've done everything for today. A full one hundred points, be proud!!"
            break

    le_form = LogExerciseForm(prefix='exercise')
    le_form.exercise.choices = [(e.id, e.name) for e in Exercise.query.all()]

    lf_form = LogFoodForm(prefix='food')
    lf_form.ingredient.choices = [(i.id, i.name)
                                  for i in Ingredient.query.all()]

    w_form = AddWeightForm(prefix='weight')

    s_form = AddStepsForm(prefix='steps')

    if lf_form.ingredient.data and lf_form.validate_on_submit():
        food_log = FoodLog(grams=lf_form.grams.data)
        food_log.user = current_user
        food_log.ingredient_id = lf_form.ingredient.data

        db.session.add(food_log)
        db.session.commit()

        flash('Food added!')
        return redirect(url_for('home'))

    if le_form.exercise.data and le_form.validate_on_submit():
        exercise_log = ExerciseLog(amount=le_form.reps.data)
        exercise_log.user = current_user
        exercise_log.exercise_id = le_form.exercise.data

        db.session.add(exercise_log)
        db.session.commit()

        flash('Exercise added!')
        return redirect(url_for('home'))

    if w_form.weight.data and w_form.validate_on_submit():
        weight = Weight(w_form.weight.data)
        weight.user = current_user
        db.session.add(weight)
        db.session.commit()

        flash('Weight added!')
        return redirect(url_for('home'))

    if s_form.steps.data and s_form.validate_on_submit():
        steps = Steps(s_form.steps.data)
        steps.user = current_user
        db.session.add(steps)
        db.session.commit()

        flash('Steps added!')
        return redirect(url_for('home'))

    return render_template('home.html',
                           e_form=le_form,
                           f_form=lf_form,
                           s_form=s_form,
                           w_form=w_form,
                           weights=weights,
                           steps=steps,
                           points=points,
                           message=message)
예제 #4
0
파일: app.py 프로젝트: TheRijn/HCI-arris3
def import_data():
    if Path('db/app.db').exists():
        click.confirm('app.db already exist, want to remove it?', abort=True)
        Path('db/app.db').unlink()

    upgrade()
    user = create_user()

    with open("data/steps.csv", 'r') as f:
        reader = DictReader(f)
        for line in reader:
            steps = Steps(steps=line['steps'])
            steps.date = datetime.fromisoformat(line['datetime'])
            steps.user = user
            db.session.add(steps)
        db.session.commit()

    with open("data/weights.csv", 'r') as f:
        reader = DictReader(f)
        for line in reader:
            weight = Weight(weight=line['weight'])
            weight.date = datetime.fromisoformat(line['datetime'])
            weight.user = user
            db.session.add(weight)
        db.session.commit()

    with open("data/exercises.csv", 'r') as f:
        reader = DictReader(f)
        for line in reader:
            exercise = Exercise(name=line['name'], kcal_per_rep=line['kcal'])
            db.session.add(exercise)
        db.session.commit()

    with open("data/ingredients.csv", 'r') as f:
        reader = DictReader(f)
        for line in reader:
            ingredient = Ingredient(name=line['name'],
                                    kcal_per_100_gram=line['kcal'])
            db.session.add(ingredient)
        db.session.commit()

    with open("data/food_log.csv", 'r') as f:
        reader = DictReader(f)
        for line in reader:
            food_log = FoodLog()
            food_log.user = user
            food_log.ingredient_id = line['ingredient_id']
            food_log.grams = line['grams']
            food_log.timestamp = datetime.fromisoformat(line['datetime'])
            db.session.add(food_log)
        db.session.commit()

    with open("data/exercise_log.csv", 'r') as f:
        reader = DictReader(f)
        for line in reader:
            exercise_log = ExerciseLog()
            exercise_log.user = user
            exercise_log.exercise_id = line['exercise_id']
            exercise_log.amount = line['amount']
            food_log.timestamp = datetime.fromisoformat(line['datetime'])
            db.session.add(exercise_log)
        db.session.commit()
예제 #5
0
 def weight(self, weight_data):
     newWeight = Weight(created=weight_data.date.data,
                        weight=weight_data.weight.data,
                        user_id=session['user_id'])
     db_session.add(newWeight)
     db_session.commit()
예제 #6
0
def profile():
    if 'email' not in session:
        return redirect(url_for('index'))
    groupnameList = []
    grouplist = []
    user = User.query.filter_by(email = session['email']).first()
    nickname = user.nickname
    if user is None:
        return redirect(url_for('index'))
    else:
        groupInfo = Group.query.filter_by(owner=session['email']).all()
        if groupInfo is not None:
            for ele in groupInfo:
                groupnameList.append(ele.groupname)
        if user.grouplist != "":
            grouplist = user.grouplist.split(",")

    number = [""]

    def makePicture(length):
        weight = Weight.query.filter_by(email = session['email']).first()
        if weight is not None:
            daysFromLast = (datetime.now(pytz.timezone(weight.timezone)).date() - weight.lastupdated).days
            weightarray = weight.weight.split(",")
            recordarray = []
            day = []
            labels = []
            reduce = (length / 30) + 1
            plt.figure(figsize=(12, 4))
            if length - daysFromLast > 1:
                for i in range(0, daysFromLast):
                    recordarray.append(None)
                for i in range(0, length - daysFromLast):
                    if len(weightarray) > 0:
                        recordarray.append(float(weightarray.pop()))
                    else:
                        recordarray.append(None)
                recordarray.reverse()
                
                def getfirst(array):
                    for ele in array:
                        if ele != None:
                            return ele
                def getlast(array):
                    array.reverse()
                    return getfirst(array)
                
                number[1] = getfirst(recordarray)
                number[2] = getlast(recordarray)
                recordarray.reverse()
                for i in range(0, length):
                    
                    day.append(i)
                    if reduce == 0 or i%reduce == 0:
                        labels.append(str(datetime.now(pytz.timezone(weight.timezone)).date() - timedelta(i)))
                labels.reverse()
                for i in range(0, length):
                    plt.plot(day[i],recordarray[i], linestyle="None",marker = "o", markersize = 8, color = "green")
                    #zhfont1 = matplotlib.font_manager.FontProperties(fname='/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc')
	            plt.plot(day, recordarray, linestyle="solid",color="#2BCE48",linewidth=3,label=unicode(weight.nickname) if i ==0 else "")
                plt.legend(loc='best',prop=prop)
                file = "/var/www/weight_overflow/files/static/weightgram/users/" + nickname
                plt.xticks(day, labels, rotation=45)
                plt.subplots_adjust(bottom=0.30)
                if reduce != 0:
                    plt.xticks(np.arange(min(day), max(day)+1, reduce))
                if os.path.exists(file):
                    filenumber = int(os.listdir(file)[0].split(".")[0][1:])
                    filenumber += 1
                    number[0] = str(filenumber)
                    os.remove(file + "/w" + str(filenumber - 1) + ".png")
                    plt.savefig(file + "/w" + str(filenumber) + ".png")
                else:
                    os.mkdir(file)
                    plt.savefig(file + "/w0.png")
                    number[0] = "0"
                plt.clf()
                return True
            else:
                return False
        return False

    warn = ""
    form = EditForm(prefix = "form")
    form1 = WeightForm(prefix = "form1")
    form2 = UserProgressForm(prefix = "form2")
    newuser = False
    timezoneRecorded = False
    message = ""
    weight = Weight.query.filter_by(email = session['email']).first()
    if weight != None:
        if len(weight.weight.split(",")) == 1:
            newuser = True
    else:
        newuser = True
    if user.timezone != None:
        timezoneRecorded = True


    if request.method == 'POST':
                #for weight form

        if form1.submit.data and form1.validate():

            user = Weight.query.filter_by(email = session['email']).first()
            
            if user == None:
                currentUser = User.query.filter_by(email = session['email']).first()
                grouplist = User.query.filter_by(email = session['email']).first().grouplist
                newWeight = Weight(session['email'],form1.todaysweight.data,datetime.now(pytz.timezone(currentUser.timezone)).date(),datetime.now(pytz.timezone(currentUser.timezone)).date(),grouplist, nickname, currentUser.timezone, currentUser.target)
                db.session.add(newWeight)
                db.session.commit()
            
            if user != None:
                if (datetime.now(pytz.timezone(user.timezone)).date() - user.lastupdated).days == -1:
                    
                    weight = Weight.query.filter_by(email = session['email']).first()
                    if user.begindate == user.lastupdated:
                        weight.begindate = datetime.now(pytz.timezone(user.timezone)).date()
                        weight.weight = form1.todaysweight.data
                    else:
                        temp = weight.weight.split(",")
                        temp[-2] = form1.todaysweight.data
                        temp.pop()
                        weight.weight = ','.join(temp)
                        weight.daysAbsent = weight.daysAbsent - 1
                    
                    weight.lastupdated = datetime.now(pytz.timezone(user.timezone)).date()
                    db.session.commit()
                else:
                
                
                
                
                
                
                    #first day recording, if it's not the first day, go to else
                    temp = (datetime.now(pytz.timezone(user.timezone)).date() - user.lastupdated).days
                    if temp > 0:
                        user.daysAbsent = temp
                    if user.daysAbsent == 0:
                        user.weight = "%.2f"%(float(form1.todaysweight.data))
                    #after first day
                    else:
                        #days that this ppl is not recording the weight info, this will remain the same if
                        #ppl try to modify today's weight.
                        #check if user have already entered today's weight
                        exist = False
                        if user.lastupdated == datetime.now(pytz.timezone(user.timezone)).date():
                            exist = True
                        else:
                            user.lastupdated = datetime.now(pytz.timezone(user.timezone)).date()
                        #delete data back to last recorded time
                        if exist:
                            temp = user.weight.split(',')
                            for i in range(0,user.daysAbsent):
                                temp.pop()
                            user.weight = ','.join(temp)
                        #add data back to database
                        last = float(user.weight.split(",")[-1])
                        now = float(form1.todaysweight.data)
                        differenceEachDay = (now - last)/user.daysAbsent
                        for i in range(1,user.daysAbsent):
                            user.weight += "," + "%.2f"%(i * differenceEachDay + last)
                        user.weight += "," + "%.2f"%(float(form1.todaysweight.data))
                db.session.commit()
            #put user's information into achieve table if they achieve their target weight
            user = Weight.query.filter_by(email = session['email']).first()
            if user.target is not None:
                achieved = Achieved.query.filter_by(email = session['email']).first()
                begin = float(user.weight.split(",")[0])
                target = float(user.target)
                #requirement to be recorded: not in the least, reached the target, loss more than 10% of ur body weight
            if float(user.weight.split(",")[-1]) <= target and achieved == None and begin - target >= begin * 0.1:
                grats = Achieved(user.email, user.nickname, user.begindate,user.lastupdated,user.weight.split(",")[0],user.target)
                db.session.add(grats)
                db.session.commit()
            return redirect(url_for('profile'))

        #for edit form
        if form.submit.data and form.validate():
            weight = Weight.query.filter_by(email = session['email']).first()
            user = User.query.filter_by(email = session['email']).first()
            if form.nickname.data != '':
                if weight is not None:
                    weight.nickname = form.nickname.data
                user.nickname = form.nickname.data
            try:
                float(form.target.data)
                if weight is not None:
                    weight.target = form.target.data
                user.target = form.target.data
            except ValueError:
                pass
            if form.timezone.data != "default":
                user.timezone = form.timezone.data
                if weight is not None:
                    weight.timezone = form.timezone.data
            db.session.commit()
            return redirect(url_for('profile'))


        #for user process tracking form

        if form2.submit.data and form2.validate():
            
            number = ["filenumber","startweight","finishweight"]
            if form2.days.data in ["7","30"]:
                
                if makePicture(int(form2.days.data)) == True:

                    loss = number[1] - number[2]
                    if loss < 0:
                        message = "Seriously? are you really try to lose weight?"
                    else:
                        message = "You lose " + "%.2f"%(loss) + " Kg in " + form2.days.data + " days"

                    number = number[0]
                else:
                    number = [""]
                    warn = "Did you at least record twice during those days?"
            elif form2.days.data == "max":
                weight = Weight.query.filter_by(email = session['email']).first()
                days = (datetime.now(pytz.timezone(weight.timezone)).date() - weight.begindate).days + 1
                makePicture(days)
                
                loss = number[1] - number[2]
                if loss < 0:
                    message = "Seriously? are you really try to lose weight?"
                else:
                    
                    message = "You lose " + "%.2f"%(loss) + " Kg in " + str(len((Weight.query.filter_by(email = session['email']).first()).weight.split(","))) + " days"
                number = number[0]

    return render_template('profile.html',nickname = user.nickname,email = user.email,groupnameList = groupnameList, grouplist=grouplist, form = form, form1 = form1, form2 = form2, number = number, newuser = newuser, timezoneRecorded = timezoneRecorded, message = message, warn = warn)