import csv
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import streamlit as st
from PIL import Image
import base64
from io import BytesIO
from datetime import datetime # Importing datetime
# Set page title
st.set_page_config(page_title="Corporate 24 Healthcare Dashboard", layout="wide")
st.sidebar.markdown("<h1 style='text-align: center; color: blue; font-size:
40px;'><b>DASHBOARD</b></span>", unsafe_allow_html=True)
# Load the logo image
logo_path = r"C:\Users\PC\Desktop\FB_IMG_17285456011763622.jpg"
logo = Image.open(logo_path)
def convert_image_to_base64(image):
buffered = BytesIO()
image.save(buffered, format="PNG")
return base64.b64encode(buffered.getvalue()).decode()
st.markdown('<div style="position: fixed; bottom: 0; width: 100%; text-align: center;"><p><a
href="https://www.google.com/url?client=internal-element-cse&cx=e644b33a7719ef93e&q=https://
corp24med.com/&sa=U&ved=2ahUKEwiY-
9KogoGKAxWXVKQEHYNyC64QFnoECAsQAQ&usg=AOvVaw2wI4TeGHO7OmicfGawpMoe&fexp=7282150
2,72821501">For More Info, Click here to Visit our Website</a></p></div>', unsafe_allow_html=True)
# Convert logo to base64
logo_base64 = convert_image_to_base64(logo)
# Set sidebar background color and center alignment
st.sidebar.markdown(
"""
<style>
.sidebar .sidebar-content {
background-color: blue; /* Change this to your desired blue color */
text-align: center; /* Center align all items */
.upload-button {
background-color: #d3d3d3; /* Grey background */
color: blue; /* Blue text */
border: none; /* No border */
padding: 10px 20px; /* Padding */
border-radius: 5px; /* Rounded corners */
font-size: 16px; /* Font size */
cursor: pointer; /* Pointer cursor on hover */
display: inline-block; /* Inline block for centering */
margin: 20px auto; /* Center the button */
width: 80%; /* Width for buttons */
</style>
""",
unsafe_allow_html=True
)
# Sidebar with round logo
st.sidebar.markdown(
f"""
<div style="width: 200px; height: 200px; border-radius: 150px; background-color: white; display: flex;
justify-content: center; align-items: center; margin: 0 auto;">
<img src="data:image/png;base64,{logo_base64}" style="border-radius: 150px; width: 100%; height:
100%; object-fit: cover;">
</div>
""",
unsafe_allow_html=True
st.sidebar.markdown("<h1 style='text-align: center; color: red; font-size: 24px;'><b>CORPORATE 24
HEALTHCARE</b></span>", unsafe_allow_html=True)
st.sidebar.markdown("<h1 style='text-align: center; color: green; font-size: 20px;'><b>Upload Dataset
(.CSV)</b></span>", unsafe_allow_html=True)
# Initialize a variable for the dataset
df = None
# Handle file upload
uploaded_file = st.sidebar.file_uploader("Upload Your Dataset", type=["csv"], key="file_uploader",
label_visibility="collapsed")
# Check if a file is uploaded
if uploaded_file is not None:
try:
# Attempt to read the dataset
df = pd.read_csv(uploaded_file)
# Proceed with further processing only if the dataframe is not empty
if df.empty:
st.warning("The uploaded file is empty. Please upload a valid CSV file.")
else:
# Convert 'DATE OF BIRTH' and 'VISIT DATE' to datetime
df['DATE OF BIRTH'] = pd.to_datetime(df['DATE OF BIRTH'], errors='coerce')
df['VISIT DATE'] = pd.to_datetime(df['VISIT DATE'], errors='coerce')
# Extract age for filtering
df['AGE'] = (datetime.now() - df['DATE OF BIRTH']).dt.days // 365
# Centered title for the dataset on the main page
st.markdown("<h2 style='text-align: center;'>PATIENTS DATASET</h2>", unsafe_allow_html=True)
# Display the dataset filling the whole main page
st.dataframe(df, use_container_width=True) # Use container width to fill the page
# Visualization section
st.sidebar.markdown("<h2 style='text-align: center;'>VISUALIZE THE DATA</h2>",
unsafe_allow_html=True)
# Button for visualization
if st.sidebar.button("VISUALIZE THE DATA"):
st.session_state.visualize = True
# Button to visualize the data
if st.button("VISUALIZE", key="visualize_button"):
df['VISIT DATE'] = pd.to_datetime(df['VISIT DATE'], errors='coerce')
# Step 3: Extract year and month from 'VISIT DATE'
df['Year'] = df['VISIT DATE'].dt.year
df['Month'] = df['VISIT DATE'].dt.month
# Step 4: Generate visualizations for all years in a single figure
years = [2020, 2021, 2022, 2023, 2024] # List of years to filter and plot
fig, axes = plt.subplots(nrows=1, ncols=len(years), figsize=(20, 6), sharey=True)
for i, year in enumerate(years):
# Filter data for the specific year
year_data = df[df['Year'] == year]
# Aggregate visits by month
monthly_visits = year_data.groupby('Month').size().reset_index(name='Total Visits')
# Plot the data for the year in a specific subplot
ax = axes[i]
ax.bar(monthly_visits['Month'], monthly_visits['Total Visits'], color='blue')
# Add labels and title
ax.set_title(f'{year}', fontsize=14)
ax.set_xlabel('Month', fontsize=12)
if i == 0:
ax.set_ylabel('Total Visits', fontsize=12)
ax.set_xticks(range(1, 13))
ax.set_xticklabels([
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
])
ax.grid(axis='y', linestyle='--', alpha=0.7)
# Adjust layout to prevent overlap
plt.tight_layout()
plt.suptitle('Total Visits Per Month for Each Year', fontsize=16, y=1.02)
plt.subplots_adjust(top=0.85)
# Save and display the figure
st.pyplot(fig)
# Sidebar filters
st.sidebar.markdown("<h2 style='text-align: center;'>FILTER OPTIONS</h2>",
unsafe_allow_html=True)
# Filter by SEX
sex_filter = st.sidebar.selectbox("Filter by SEX:", options=["All", "Male", "Female"])
if sex_filter != "All":
df = df[df['SEX'] == sex_filter]
# Filter by AGE
age_filter = st.sidebar.slider("Filter by AGE:", min_value=0, max_value=100, value=(0, 100))
df = df[(df['AGE'] >= age_filter[0]) & (df['AGE'] <= age_filter[1])]
# Filter by MEDICAL AID
medical_aid_filter = st.sidebar.multiselect("Filter by MEDICAL AID:", options=df['MEDICAL
AID'].unique())
if medical_aid_filter:
df = df[df['MEDICAL AID'].isin(medical_aid_filter)]
# Display the filtered dataset on the main page
if not df.empty:
# Title for filtered output
st.markdown("<h2 style='text-align: center;'>FILTERED OUTPUT</h2>",
unsafe_allow_html=True)
st.dataframe(df, use_container_width=True) # Display the filtered dataset
else:
st.warning("No patients found matching your filters.")
except pd.errors.EmptyDataError:
st.warning("The uploaded file is empty. Please upload a valid CSV file.")
except pd.errors.ParserError:
st.warning("Error parsing the file. Please ensure it is a valid CSV.")
except Exception as e:
st.error(f"An error occurred: {e}")
else:
st.warning("Please upload a CSV file.")