On this weblog, we are going to create a hydration reminder utility that predicts your day by day water consumption based mostly in your exercise stage, present temperature, and former water consumption. The app will ship you reminders to drink water and can help you acknowledge every reminder, updating your consumption standing in real-time. We’ll use Streamlit for the UI, TensorFlow for the AI mannequin, Twilio for SMS notifications, OpenAI for customized recommendation, and OpenWeatherMap for climate knowledge.
pip set up tensorflow twilio requests streamlit openai python-dotenv
Create a .env
file in your venture listing to retailer your delicate info like API keys and credentials.
# .env
OPENAI_API_KEY=your_openai_api_key
WEATHER_API_KEY=your_openweathermap_api_key
TWILIO_ACCOUNT_SID=your_twilio_account_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_PHONE_NUMBER=your_twilio_phone_number
We’ll practice a easy neural community to foretell day by day water consumption. Save the next code in a file named hydration_model.py
.
import numpy as np
import tensorflow as tf# Pattern knowledge (consumer exercise in steps, temperature in °C, earlier consumption in liters)
knowledge = np.array([
[1000, 30, 1.5],
[2000, 35, 2.0],
[1500, 32, 1.8],
[1700, 31, 1.7],
[1300, 29, 1.6]
])
labels = np.array([2.0, 2.5, 2.2, 2.3, 1.9]) # Corresponding water consumption in liters
# Normalize knowledge
knowledge[:, 0] = knowledge[:, 0] / 10000 # Normalize steps to [0, 3]
knowledge[:, 1] = knowledge[:, 1] / 40 # Normalize temperature to [0, 1]
knowledge[:, 2] = knowledge[:, 2] / 5 # Normalize consumption to [0, 1]
# Outline a easy neural community mannequin
mannequin = tf.keras.fashions.Sequential([
tf.keras.layers.Dense(10, activation='relu', input_shape=(3,)),
tf.keras.layers.Dense(1)
])
# Compile the mannequin
mannequin.compile(optimizer='adam', loss='mean_squared_error')
# Prepare the mannequin
mannequin.match(knowledge, labels, epochs=100)
# Save the mannequin
mannequin.save('hydration_model.h5')
Run the script to coach and save the mannequin:
python hydration_model.py
Create a file named notification_system.py
for sending SMS reminders utilizing Twilio.
from twilio.relaxation import Consumer
import os
from dotenv import load_dotenv# Load atmosphere variables from .env file
load_dotenv()
# Twilio configuration
account_sid = os.getenv('TWILIO_ACCOUNT_SID')
auth_token = os.getenv('TWILIO_AUTH_TOKEN')
twilio_phone_number = os.getenv('TWILIO_PHONE_NUMBER')
shopper = Consumer(account_sid, auth_token)
def send_reminder(phone_number, message):
shopper.messages.create(
physique=message,
from_=twilio_phone_number, # Your Twilio quantity
to=phone_number
)
Create a file named app.py
for the Streamlit utility.
import streamlit as st
import numpy as np
import tensorflow as tf
import requests
import os
from dotenv import load_dotenv
from notification_system import send_reminder
import openai# Load atmosphere variables from .env file
load_dotenv()
# Initialize OpenAI shopper
openai.api_key = os.getenv('OPENAI_API_KEY')
# Load the educated mannequin
mannequin = tf.keras.fashions.load_model('hydration_model.h5', compile=False)
mannequin.compile(optimizer='adam', loss='mean_squared_error')
# Climate API configuration
weather_api_key = os.getenv('WEATHER_API_KEY')
weather_api_url = 'http://api.openweathermap.org/knowledge/2.5/climate'
st.title('Keep Hydrated: AI-Powered Hydration Reminder')
# Initialize session state for water consumption monitoring
if 'total_intake' not in st.session_state:
st.session_state.total_intake = 0
# Person enter for exercise, location, and former water consumption
exercise = st.slider('Each day Exercise (steps)', min_value=0, max_value=30000, worth=5000, step=500)
location = st.text_input('Location (metropolis title)', 'Los Angeles')
previous_intake = st.slider('Earlier Water Consumption (liters)', min_value=0.0, max_value=5.0, worth=1.0, step=0.1)
phone_number = st.text_input('Cellphone Quantity', '+1234567890')
if st.button('Get Hydration Advice'):
# Get present temperature from climate API
weather_response = requests.get(weather_api_url, params={
'q': location,
'appid': weather_api_key,
'items': 'metric'
})
if weather_response.status_code == 200:
weather_data = weather_response.json()
if 'essential' in weather_data:
temperature = weather_data['main']['temp']
# Normalize inputs much like coaching knowledge
normalized_activity = exercise / 10000
normalized_temperature = temperature / 40
normalized_intake = previous_intake / 5
# Predict water consumption
input_data = np.array([[normalized_activity, normalized_temperature, normalized_intake]])
predicted_intake = mannequin.predict(input_data)[0][0]
# Clamp the prediction to an inexpensive vary
predicted_intake = max(0, min(predicted_intake, 2.5))
# Show advice
st.write(f'You need to drink {predicted_intake:.2f} liters of water right now!')
# Ship notification
send_reminder(phone_number, f'You need to drink {predicted_intake:.2f} liters of water right now!')
st.success('Reminder despatched efficiently!')
else:
st.error('Couldn't retrieve temperature knowledge. Please examine town title and check out once more.')
else:
st.error('Did not get climate knowledge. Please examine your API key and metropolis title.')
# Acknowledgment button to replace water consumption
if st.button('Acknowledge and Replace Water Consumption'):
st.session_state.total_intake += 0.25 # Assume every acknowledgment is 0.25 liters (one glass)
st.write(f'Complete water consumption up to date: {st.session_state.total_intake:.2f} liters')
# LLM integration for customized ideas and recommendation
st.header('Personalised Hydration Recommendation')
user_question = st.text_area('Ask something about hydration:')
if st.button('Get Recommendation'):
response = openai.ChatCompletion.create(
mannequin="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": user_question}
]
)
st.write(response['choices'][0]['message']['content'].strip())
To run the Streamlit app, open your terminal and execute:
streamlit run app.py
On this information, we constructed an entire hydration reminder utility utilizing fashionable AI and internet applied sciences. The app predicts your day by day water consumption, sends reminders through SMS, and lets you observe your consumption in real-time. Moreover, it offers customized hydration recommendation utilizing OpenAI’s GPT-3.5-turbo.
By following these steps, you’ll be able to improve your well being and hydration habits with the facility of AI. Be happy to customise the appliance additional and share your enhancements.
Glad coding and keep hydrated!