Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
350 changes: 143 additions & 207 deletions python/api-examples-source/hello/hello.py
Original file line number Diff line number Diff line change
@@ -1,235 +1,171 @@
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime

# ====== PAGE SETTINGS ======
st.set_page_config(
page_title="MindGuard AI",
page_icon="🧠",
layout="centered"
)

# ====== CUSTOM UI ======
st.markdown("""
<style>

.stApp {
background: linear-gradient(to bottom, #0f172a, #1e293b);
color: white;
}

h1 {
color: #38bdf8;
text-align: center;
font-size: 50px;
}

h2, h3 {
color: white;
}

def intro():
import streamlit as st
.stButton>button {
background-color: #38bdf8;
color: black;
border-radius: 12px;
height: 50px;
width: 100%;
font-size: 18px;
font-weight: bold;
}

div.stSlider {
padding-top: 20px;
padding-bottom: 20px;
}

st.write("# Welcome to Streamlit! 👋")
st.sidebar.success("Select a demo above.")
</style>
""", unsafe_allow_html=True)

st.markdown(
"""
Streamlit is an open-source app framework built specifically for
Machine Learning and Data Science projects.
# ====== TITLE ======
st.title("🧠 MindGuard AI")
st.subheader("Early Mental Health Monitoring System")

**👈 Select a demo from the dropdown on the left** to see some examples
of what Streamlit can do!
# ====== SESSION STORAGE ======
if "data" not in st.session_state:
st.session_state.data = pd.DataFrame(columns=["date", "mood"])

### Want to learn more?
# ====== MOOD INPUT ======
st.markdown("## 🎯 Daily Mood Check")

- Check out [streamlit.io](https://streamlit.io)
- Jump into our [documentation](https://docs.streamlit.io)
- Ask a question in our [community
forums](https://discuss.streamlit.io)
mood = st.slider(
"How do you feel today? (1 = worst, 5 = best)",
1,
5
)

### See more complex demos
# ====== SAVE BUTTON ======
if st.button("Save Mood"):

- Use a neural net to [analyze the Udacity Self-driving Car Image
Dataset](https://github.com/streamlit/demo-self-driving)
- Explore a [New York City rideshare dataset](https://github.com/streamlit/demo-uber-nyc-pickups)
"""
new_data = pd.DataFrame({
"date": [datetime.now()],
"mood": [mood]
})

st.session_state.data = pd.concat(
[st.session_state.data, new_data],
ignore_index=True
)

st.success("✅ Mood saved successfully!")

def mapping_demo():
from urllib.error import URLError
# ====== MOOD RESPONSES ======

import pandas as pd
import pydeck as pdk
import streamlit as st
if mood == 1:

st.markdown(f"# {list(page_names_to_funcs.keys())[2]}")
st.write(
"""
This demo shows how to use
[`st.pydeck_chart`](https://docs.streamlit.io/develop/api-reference/charts/st.pydeck_chart)
to display geospatial data.
"""
)
st.error("""
⚠️ Very low mood detected.

@st.cache_data
def from_data_file(filename):
url = (
"https://raw.githubusercontent.com/streamlit/"
"example-data/master/hello/v1/%s" % filename
)
return pd.read_json(url)

try:
ALL_LAYERS = {
"Bike Rentals": pdk.Layer(
"HexagonLayer",
data=from_data_file("bike_rental_stats.json"),
get_position=["lon", "lat"],
radius=200,
elevation_scale=4,
elevation_range=[0, 1000],
extruded=True,
),
"Bart Stop Exits": pdk.Layer(
"ScatterplotLayer",
data=from_data_file("bart_stop_stats.json"),
get_position=["lon", "lat"],
get_color=[200, 30, 0, 160],
get_radius="[exits]",
radius_scale=0.05,
),
"Bart Stop Names": pdk.Layer(
"TextLayer",
data=from_data_file("bart_stop_stats.json"),
get_position=["lon", "lat"],
get_text="name",
get_color=[0, 0, 0, 200],
get_size=15,
get_alignment_baseline="'bottom'",
),
"Outbound Flow": pdk.Layer(
"ArcLayer",
data=from_data_file("bart_path_stats.json"),
get_source_position=["lon", "lat"],
get_target_position=["lon2", "lat2"],
get_source_color=[200, 30, 0, 160],
get_target_color=[200, 30, 0, 160],
auto_highlight=True,
width_scale=0.0001,
get_width="outbound",
width_min_pixels=3,
width_max_pixels=30,
),
}
st.sidebar.markdown("### Map Layers")
selected_layers = [
layer
for layer_name, layer in ALL_LAYERS.items()
if st.sidebar.checkbox(layer_name, True)
]
if selected_layers:
st.pydeck_chart(
pdk.Deck(
map_style="mapbox://styles/mapbox/light-v9",
initial_view_state={
"latitude": 37.76,
"longitude": -122.4,
"zoom": 11,
"pitch": 50,
},
layers=selected_layers,
)
)
else:
st.error("Please choose at least one layer above.")
except URLError as e:
st.error(
"""
**This demo requires internet access.**

Connection error: %s
"""
% e.reason
)


def plotting_demo():
import time

import numpy as np
import streamlit as st

st.markdown(f"# {list(page_names_to_funcs.keys())[1]}")
st.write(
"""
This demo illustrates a combination of plotting and animation with
Streamlit. We're generating a bunch of random numbers in a loop for around
5 seconds. Enjoy!
"""
)
Please avoid isolating yourself.
Try speaking with someone you trust or seeking professional support.

Remember:
bad days do not last forever.
""")

elif mood == 2:

st.warning("""
😔 Low emotional state detected.

progress_bar = st.sidebar.progress(0)
status_text = st.sidebar.empty()
last_rows = np.random.randn(1, 1)
chart = st.line_chart(last_rows)
Try:
• Taking a break
• Listening to calming sounds
• Avoiding pressure
• Going outside for fresh air
""")

for i in range(1, 101):
new_rows = last_rows[-1, :] + np.random.randn(5, 1).cumsum(axis=0)
status_text.text("%i%% Complete" % i)
chart.add_rows(new_rows)
progress_bar.progress(i)
last_rows = new_rows
time.sleep(0.05)
elif mood == 3:

progress_bar.empty()
st.info("""
🙂 Neutral emotional state.

# Streamlit widgets automatically run the script from top to bottom. Since
# this button is not connected to any other logic, it just causes a plain
# rerun.
st.button("Re-run")
Maintain healthy routines and rest properly.
""")

elif mood == 4:

def data_frame_demo():
from urllib.error import URLError
st.success("""
😊 Positive emotional state detected.

import altair as alt
import pandas as pd
import streamlit as st
Keep maintaining:
• Healthy habits
• Social connection
• Balanced routines
""")

st.markdown(f"# {list(page_names_to_funcs.keys())[3]}")
st.write(
"""
This demo shows how to use `st.write` to visualize Pandas DataFrames.
elif mood == 5:

(Data courtesy of the [UN Data Explorer](http://data.un.org/Explorer.aspx).)
"""
st.balloons()

st.success("""
🔥 Excellent emotional condition detected!

Keep the momentum going!
""")

# ====== CHART ======
if not st.session_state.data.empty:

df = st.session_state.data

st.markdown("## 📊 Mood History")

fig, ax = plt.subplots(figsize=(8, 4))

ax.plot(
df["date"],
df["mood"],
marker="o",
linewidth=3
)

@st.cache_data
def get_UN_data():
AWS_BUCKET_URL = "https://streamlit-demo-data.s3-us-west-2.amazonaws.com"
df = pd.read_csv(AWS_BUCKET_URL + "/agri.csv.gz")
return df.set_index("Region")

try:
df = get_UN_data()
countries = st.multiselect(
"Choose countries", list(df.index), ["China", "United States of America"]
)
if not countries:
st.error("Please select at least one country.")
else:
data = df.loc[countries]
data /= 1000000.0
st.write("### Gross Agricultural Production ($B)", data.sort_index())

data = data.T.reset_index()
data = pd.melt(data, id_vars=["index"]).rename(
columns={"index": "year", "value": "Gross Agricultural Product ($B)"}
)
chart = (
alt.Chart(data)
.mark_area(opacity=0.3)
.encode(
x="year:T",
y=alt.Y("Gross Agricultural Product ($B):Q", stack=None),
color="Region:N",
)
)
st.altair_chart(chart, use_container_width=True)
except URLError as e:
st.error(
"""
**This demo requires internet access.**

Connection error: %s
"""
% e.reason
)


page_names_to_funcs = {
"—": intro,
"Plotting Demo": plotting_demo,
"Mapping Demo": mapping_demo,
"DataFrame Demo": data_frame_demo,
}
ax.set_xlabel("Time")
ax.set_ylabel("Mood Level")

st.pyplot(fig)

# ====== AVERAGE ======
average_mood = round(df["mood"].mean(), 2)

st.markdown(f"## 📌 Average Mood: {average_mood}")

# ====== EXTRA INSIGHT ======
if average_mood <= 2:
st.error("⚠️ Emotional trend is concerning over time.")

elif average_mood >= 4:
st.success("🌟 Emotional trend is very positive.")

demo_name = st.sidebar.selectbox("Choose a demo", page_names_to_funcs.keys())
page_names_to_funcs[demo_name]()
else:
st.info("📈 Emotional trend is generally stable.")