Skip to content

Commit

Permalink
able to capture analytics through new interface but issue in bringing…
Browse files Browse the repository at this point in the history
… up interface
  • Loading branch information
444B committed Mar 4, 2024
1 parent a37595c commit 3e28a80
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 161 deletions.
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ streamlit = ">=1.31"
altair = "*"
pandas = "*"
google-cloud-firestore = "*"
bcrypt = "*"
streamlit-analytics2 = {editable = true, path = "."}

[dev-packages]
Expand Down
File renamed without changes.
16 changes: 9 additions & 7 deletions examples/minimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,26 @@
# Get the software versions
python_version = platform.python_version()
streamlit_version = st.__version__
# streamlit_analytics_version = streamlit_analytics.__version__
# streamlit_analytics2_version = streamlit_analytics.__version__

# Print the versions
st.write(f"Python version: {python_version}")
st.write(f"Streamlit version: {streamlit_version}")
# st.write(f"streamlit_analytics version: {streamlit_analytics_version}")
# st.write(f"streamlit_analytics2 version: {streamlit_analytics2_version}")

st.markdown("---")

# with streamlit_analytics.track():

streamlit_analytics.start_tracking()
st.text_input("Write your name")
st.selectbox("Select your favorite", ["cat", "dog", "flower"])
st.button("Click me")

streamlit_analytics.start_tracking()

st.header("minimal.py loaded")
st.text_input("Write your name")

st.button("Click me")
st.title("A [link]()")

counts = streamlit_analytics.get_counts()
st.write(counts)

streamlit_analytics.stop_tracking()
File renamed without changes.
2 changes: 1 addition & 1 deletion src/streamlit_analytics2/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .analytics.tracker import get_counts, track, start_tracking, stop_tracking

from .main import *

__version__ = "0.6.0"
141 changes: 8 additions & 133 deletions src/streamlit_analytics2/display/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,142 +6,17 @@


def show_settings(app_config):
st.title("Settings")
st.write(
"Here you can configure the settings for streamlit-analytics."
)
st.markdown(
"""
**Note:** Changes to the settings will be saved to `app_config.json` in the
current working directory.
"""
)
st.header("settings()")
# Get the current settings
settings = app_config.get_settings()
st.write(settings)


# Show password protection settings.
st.header("Password protection")
hashed_password = app_config.get_setting("hashed_password")
if hashed_password:
st.write("Password is set.")
if st.button("Remove password"):
app_config.update_setting("hashed_password", "")
else:
st.write("No password set.")
new_password = st.text_input("Set new password", type="password")
if new_password:
app_config.update_setting("hashed_password", hash_password(new_password))

def show_results():
from streamlit_analytics2.analytics.tracker import get_counts
"""Show analytics results in streamlit, asking for password if given."""
"""Show analytics results in streamlit"""
counts = get_counts()
# Show header.
st.title("Analytics Dashboard")
st.markdown(
"""
Psst! 👀 You found a secret section generated by
[streamlit-analytics](https://github.com/444B/streamlit-analytics2).
If you didn't mean to go here, remove `?analytics=on` from the URL.
"""
)

# Show traffic.
st.header("Traffic")
st.write(f"since {counts['start_time']}")
col1, col2, col3 = st.columns(3)
col1.metric(
"Pageviews",
counts["total_pageviews"],
help="Every time a user (re-)loads the site.",
)
col2.metric(
"Script runs",
counts["total_script_runs"],
help="Every time Streamlit reruns upon changes or interactions.",
)
col3.metric(
"Time spent",
format_seconds(counts["total_time_seconds"]),
help="Time from initial page load to last widget interaction, summed over all users.",
)
st.write("")

# Plot altair chart with pageviews and script runs.
try:
alt.themes.enable("streamlit")
except:
pass # probably old Streamlit version
df = pd.DataFrame(counts["per_day"])
base = alt.Chart(df).encode(
x=alt.X("monthdate(days):O", axis=alt.Axis(title="", grid=True))
)
line1 = base.mark_line(point=True, stroke="#5276A7").encode(
alt.Y(
"pageviews:Q",
axis=alt.Axis(
titleColor="#5276A7",
tickColor="#5276A7",
labelColor="#5276A7",
format=".0f",
tickMinStep=1,
),
scale=alt.Scale(domain=(0, df["pageviews"].max() + 1)),
)
)
line2 = base.mark_line(point=True, stroke="#57A44C").encode(
alt.Y(
"script_runs:Q",
axis=alt.Axis(
title="script runs",
titleColor="#57A44C",
tickColor="#57A44C",
labelColor="#57A44C",
format=".0f",
tickMinStep=1,
),
)
)
layer = (
alt.layer(line1, line2)
.resolve_scale(y="independent")
.configure_axis(titleFontSize=15, labelFontSize=12, titlePadding=10)
)
st.altair_chart(layer, use_container_width=True)

# Show widget interactions.
st.header("Widget interactions")
st.markdown(
"""
Find out how users interacted with your app!
<br>
Numbers indicate how often a button was clicked, how often a specific text
input was given, ...
<br>
<sub>Note: Numbers only increase if the state of the widget
changes, not every time streamlit runs the script.</sub>
""",
unsafe_allow_html=True,
)
st.write(counts["widgets"])

# Show button to reset analytics.
st.header("Danger zone")
with st.expander("Here be dragons 🐲🔥"):
st.write(
"""
Here you can reset all analytics results.
**This will erase everything tracked so far. You will not be able to
retrieve it. This will also overwrite any results synced to Firestore.**
"""
)
reset_prompt = st.selectbox(
"Continue?",
[
"No idea what I'm doing here",
"I'm absolutely sure that I want to reset the results",
],
)
if reset_prompt == "I'm absolutely sure that I want to reset the results":
reset_clicked = st.button("Click here to reset")
if reset_clicked:
st.write("Done! Please refresh the page.")
st.header("show_results()")
st.write(counts)
43 changes: 23 additions & 20 deletions src/streamlit_analytics2/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,28 +48,31 @@ def analytics_navigation():
elif page == 'Settings':
show_settings(app_config)

def main():
# Check for the analytics=on query parameter before showing sidebar content
query_params = st.query_params
analytics_enabled = "analytics" in query_params and "on" in query_params["analytics"]
# def main():
# Check for the analytics=on query parameter before showing sidebar content
query_params = st.query_params
analytics_enabled = "analytics" in query_params and "on" in query_params["analytics"]

if analytics_enabled:
# analytics_tracker.start_tracking() # Start tracking within context
password_hash = app_config.get_setting('hashed_password')
if analytics_enabled:
st.write("this thing works (kinda)")
# analytics_tracker.start_tracking() # Start tracking within context
password_hash = app_config.get_setting('hashed_password')

if not password_hash:
set_admin_password()
elif not st.session_state.get('authenticated', False):
login_field(password_hash)
reset_password_and_data()
if not password_hash:
set_admin_password()
elif not st.session_state.get('authenticated', False):
login_field(password_hash)
reset_password_and_data()

if st.session_state.get('authenticated', False):
analytics_navigation()
if st.session_state.get('authenticated', False):
analytics_navigation()

# analytics_tracker.stop_tracking() # Ensure tracking stops appropriately
else:
st.write("Welcome to the app! Append '?analytics=on' to the URL to access the analytics dashboard.")
st.button("Click me")
# analytics_tracker.stop_tracking() # Ensure tracking stops appropriately
else:
st.header("main.py loaded")
st.write("Welcome to the app! Append '?analytics=on' to the URL to access the analytics dashboard.")
st.button("Click me")
show_results()

if __name__ == "__main__":
main()
# if __name__ == "__main__":
# main()

0 comments on commit 3e28a80

Please sign in to comment.