On this weblog, we’re going to create a hydration reminder utility that predicts your daily water consumption primarily based in your train stage, current temperature, and former water consumption. The app will ship you reminders to drink water and may help you acknowledge each reminder, updating your consumption standing in real-time. We’ll use Streamlit for the UI, TensorFlow for the AI model, Twilio for SMS notifications, OpenAI for custom-made advice, and OpenWeatherMap for local weather data.
pip arrange tensorflow twilio requests streamlit openai python-dotenv
Create a .env
file in your enterprise itemizing to retailer your delicate data 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 follow a straightforward neural group to predict daily water consumption. Save the following code in a file named hydration_model.py
.
import numpy as np
import tensorflow as tf# Sample data (client train in steps, temperature in °C, earlier consumption in liters)
data = 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 data
data[:, 0] = data[:, 0] / 10000 # Normalize steps to [0, 3]
data[:, 1] = data[:, 1] / 40 # Normalize temperature to [0, 1]
data[:, 2] = data[:, 2] / 5 # Normalize consumption to [0, 1]
# Define a straightforward neural group model
model = tf.keras.fashions.Sequential([
tf.keras.layers.Dense(10, activation='relu', input_shape=(3,)),
tf.keras.layers.Dense(1)
])
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# Put together the model
model.match(data, labels, epochs=100)
# Save the model
model.save('hydration_model.h5')
Run the script to teach and save the model:
python hydration_model.py
Create a file named notification_system.py
for sending SMS reminders using Twilio.
from twilio.rest import Client
import os
from dotenv import load_dotenv# Load environment 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 = Client(account_sid, auth_token)
def send_reminder(phone_number, message):
shopper.messages.create(
physique=message,
from_=twilio_phone_number, # Your Twilio amount
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 environment variables from .env file
load_dotenv()
# Initialize OpenAI shopper
openai.api_key = os.getenv('OPENAI_API_KEY')
# Load the educated model
model = tf.keras.fashions.load_model('hydration_model.h5', compile=False)
model.compile(optimizer='adam', loss='mean_squared_error')
# Local weather API configuration
weather_api_key = os.getenv('WEATHER_API_KEY')
weather_api_url = 'http://api.openweathermap.org/data/2.5/local weather'
st.title('Maintain 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
# Particular person enter for train, location, and former water consumption
train = st.slider('Every day Train (steps)', min_value=0, max_value=30000, value=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, value=1.0, step=0.1)
phone_number = st.text_input('Cellphone Amount', '+1234567890')
if st.button('Get Hydration Recommendation'):
# Get current temperature from local weather API
weather_response = requests.get(weather_api_url, params={
'q': location,
'appid': weather_api_key,
'objects': 'metric'
})
if weather_response.status_code == 200:
weather_data = weather_response.json()
if 'important' in weather_data:
temperature = weather_data['main']['temp']
# Normalize inputs very like teaching data
normalized_activity = train / 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 = model.predict(input_data)[0][0]
# Clamp the prediction to a cheap differ
predicted_intake = max(0, min(predicted_intake, 2.5))
# Present recommendation
st.write(f'It is advisable to drink {predicted_intake:.2f} liters of water proper now!')
# Ship notification
send_reminder(phone_number, f'It is advisable to drink {predicted_intake:.2f} liters of water proper now!')
st.success('Reminder despatched effectively!')
else:
st.error('Could not retrieve temperature data. Please study city title and take a look at as soon as extra.')
else:
st.error('Didn't get local weather data. Please study your API key and metropolis title.')
# Acknowledgment button to switch water consumption
if st.button('Acknowledge and Change Water Consumption'):
st.session_state.total_intake += 0.25 # Assume each acknowledgment is 0.25 liters (one glass)
st.write(f'Full water consumption updated: {st.session_state.total_intake:.2f} liters')
# LLM integration for custom-made concepts and advice
st.header('Personalised Hydration Advice')
user_question = st.text_area('Ask one thing about hydration:')
if st.button('Get Advice'):
response = openai.ChatCompletion.create(
model="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 info, we constructed a complete hydration reminder utility using trendy AI and web utilized sciences. The app predicts your daily water consumption, sends reminders by SMS, and allows you to observe your consumption in real-time. Furthermore, it provides custom-made hydration advice using OpenAI’s GPT-3.5-turbo.
By following these steps, you’ll enhance your properly being and hydration habits with the power of AI. Be completely happy to customize the equipment extra and share your enhancements.
Glad coding and preserve hydrated!