Skip to content

Commit

Permalink
Merge pull request #33 from rishi2019194/email_bmi_1
Browse files Browse the repository at this point in the history
beautify email; add avg bmi by country
  • Loading branch information
rishi2019194 authored Nov 25, 2023
2 parents cb17a83 + 0c038c3 commit 31521e4
Show file tree
Hide file tree
Showing 6 changed files with 1,052 additions and 334 deletions.
138 changes: 123 additions & 15 deletions application.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
# from apps import App
from flask import json
# from utilities import Utilities
from flask import render_template, session, url_for, flash, redirect, request, Flask
from flask import render_template, session, url_for, flash, redirect, request, Flask, jsonify
from flask_mail import Mail
from flask_pymongo import PyMongo
from tabulate import tabulate
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from forms import HistoryForm, RegistrationForm, LoginForm, CalorieForm, UserProfileForm, EnrollForm, WorkoutForm
import openai
import os
Expand Down Expand Up @@ -499,35 +501,104 @@ def refresh():

@app.route("/send_email", methods=['GET', 'POST'])
def send_email():
# ############################
# send_email() function shares Calorie History with friend's email
# route "/send_email" will redirect to send_email() function which redirects to friends.html page.
# Input: Email
# Output: Calorie History Received on specified email
# ##########################
'''
send_email() function shares Calorie History with friend's email
route "/send_email" will redirect to send_email() function which redirects to friends.html page.
Input: Email
Output: Latest Week Calorie History received on specified email
''' # ##########################'''
email = session.get('email')
data = list(
mongo.db.calories.find({'email': email},
{'date', 'email', 'calories'}))
data = list(mongo.db.calories.find({'email': email}, {'date', 'email', 'calories'}))
workout_data = list(mongo.db.workout.find({'email': email}, {'date', 'email', 'burnout'}))
print(data, workout_data)

one_week_ago = datetime.now() - timedelta(days=7)

filtered_data = [a for a in data if datetime.strptime(a['date'], '%Y-%m-%d') >= one_week_ago]
filtered_workout_data = [a for a in workout_data if datetime.strptime(a['date'], '%Y-%m-%d') >= one_week_ago]

table = [['Date', 'Email ID', 'Calories']]
for a in data:

for a in filtered_data:
tmp = [a['date'], a['email'], a['calories']]
table.append(tmp)
for a in filtered_workout_data:
tmp = [a['date'], a['email'], int(a['burnout'])*(-1)]
table.append(tmp)

friend_email = str(request.form.get('share')).strip()
friend_email = str(friend_email).split(',')
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)

#Storing sender's email address and password
sender_email = "[email protected]"
sender_password = c.email_password
sharing_email = table[1][1]

positive_calories = [row for row in table[1:] if int(row[2]) > 0]
negative_calories = [row for row in table[1:] if int(row[2]) < 0]

net_calories = sum(int(row[2]) for row in table[1:])

html_table = """
<html>
<head></head>
<body>
<p>Your friend with email {} wants to share their past week's calorie history with you!</p>
<!-- Positive Calories Table -->
<h3>Calories Gained</h3>
<table style="font-family: Arial, sans-serif; border-collapse: collapse; width: 100%; max-width: 600px;">
<tr style="background-color: #f2f2f2;">
<th style="border: 1px solid #dddddd; text-align: left; padding: 8px;">Date</th>
<th style="border: 1px solid #dddddd; text-align: left; padding: 8px;">Calories</th>
</tr>
{}
</table>
<!-- Negative Calories Table -->
<h3>Calories Lost</h3>
<table style="font-family: Arial, sans-serif; border-collapse: collapse; width: 100%; max-width: 600px;">
<tr style="background-color: #f2f2f2;">
<th style="border: 1px solid #dddddd; text-align: left; padding: 8px;">Date</th>
<th style="border: 1px solid #dddddd; text-align: left; padding: 8px;">Calories</th>
</tr>
{}
</table>
<!-- Net Calories -->
<h3>Net Calories: {}</h3>
</body>
</html>
"""

positive_rows = ""
for row in positive_calories:
positive_rows += "<tr>"
for item in [row[0]] + [row[2]]:
positive_rows += "<td style='border: 1px solid #dddddd; text-align: left; padding: 8px;'>{}</td>".format(item)
positive_rows += "</tr>"

negative_rows = ""
for row in negative_calories:
negative_rows += "<tr>"
for item in [row[0]] + [row[2]]:
negative_rows += "<td style='border: 1px solid #dddddd; text-align: left; padding: 8px;'>{}</td>".format(item)
negative_rows += "</tr>"

formatted_html = html_table.format(sharing_email, positive_rows, negative_rows, net_calories)

#Logging in with sender details
server.login(sender_email, sender_password)
message = 'Subject: Calorie History\n\n Your Friend wants to share their calorie history with you!\n {}'.format(
tabulate(table))
message = MIMEMultipart()
message["Subject"] = "Calorie History"
message["From"] = sender_email

html_content = MIMEText(formatted_html, "html")
message.attach(html_content)
for e in friend_email:
print(e)
server.sendmail(sender_email, e, message)
server.sendmail(sender_email, e, message.as_string())

server.quit()

Expand Down Expand Up @@ -901,6 +972,43 @@ def hrx():
return redirect(url_for('dashboard'))
return render_template('hrx.html', title='HRX', form=form)

@app.route('/get_countries', methods=['GET'])
def get_countries():
'''
Populate countries in the bmi_cal.html dropdown from mongodb
'''
countries = [country['country_name'] for country in mongo.db.obesity.find({}, {'country_name': 1, '_id': 0})]
return jsonify({'countries': countries})

@app.route('/get_average_bmi', methods=['GET'])
def get_average_bmi():
'''
Fetch the average bmi values from database
'''
country = request.args.get('country')
gender = request.args.get('gender')

bmi_data_for_country = list(mongo.db.obesity.find({'country_name': country}))

# Get the keys for both sexes, male, and female
gender_keys = ['both_sexes', 'male', 'female']

# Dictionary to store average BMI values
average_bmi_data = {}

# Calculate average BMI for both sexes
both_sexes_data = [entry[key] for entry in bmi_data_for_country for key in gender_keys if key in entry]
total_both_sexes = sum(both_sexes_data)
average_bmi_data['both_sexes'] = total_both_sexes / len(both_sexes_data)

# Calculate average BMI for the selected gender
if gender in gender_keys:
selected_gender_data = [entry[gender] for entry in bmi_data_for_country if gender in entry]
total_selected_gender = sum(selected_gender_data)
average_bmi_data[gender] = total_selected_gender / len(selected_gender_data)
else:
return jsonify({'error': 'Invalid gender parameter'}), 400
return jsonify(average_bmi_data)

# @app.route("/ajaxdashboard", methods=['POST'])
# def ajaxdashboard():
Expand All @@ -925,4 +1033,4 @@ def hrx():
# 'ContentType': 'application/json'}

if __name__ == '__main__':
app.run(debug=True)
app.run(debug=True)
38 changes: 38 additions & 0 deletions insert_food_bmi_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from apps import App
import pandas as pd

app = App()
mongo = app.mongo

# Clear existing data in the 'food' and 'obesity' collections
mongo.db.food.delete_many({})
mongo.db.obesity.delete_many({})

# Food Data
f = open('food_data/calories.csv', 'r', encoding="ISO-8859-1")
l = f.readlines()

for i in range(1, len(l)):
l[i] = l[i][1:len(l[i]) - 2]

for i in range(1, len(l)):
temp = l[i].split(",")
mongo.db.food.insert_one({'food': temp[0], 'calories': temp[1]})

# BMI data
df = pd.read_csv('model/WHO_obesityByCountry_2016.csv')

for index, row in df.iterrows():
country_name = row['Country']
both_sexes = row['Both.sexes']
male = row['Male']
female = row['Female']

mongo.db.obesity.insert_one({
'country_name': country_name,
'both_sexes': both_sexes,
'male': male,
'female': female
})

print("Data inserted into MongoDB.")
14 changes: 0 additions & 14 deletions insert_food_data.py

This file was deleted.

Loading

0 comments on commit 31521e4

Please sign in to comment.