GithubHelp home page GithubHelp logo

444b / streamlit-analytics2 Goto Github PK

View Code? Open in Web Editor NEW

This project forked from jrieke/streamlit-analytics

21.0 2.0 2.0 2.27 MB

๐Ÿ‘€ Track & visualize user interactions with your streamlit app

License: MIT License

Python 94.15% Shell 5.85%
analytics streamlit visualization streamlit-analytics

streamlit-analytics2's Introduction

streamlit-analytics2 ๐Ÿ‘€

PyPi PyPI - Downloads Build Status

CodeFactor Coverage

Known Vulnerabilities streamlit-analytics2

Enhanced tracking & visualization for your Streamlit apps.

streamlit-analytics2 is a fork and extension of the original streamlit-analytics, aimed at improving and securing the analytics functionality within Streamlit applications. With minimal setup, track user interactions and visualize analytics directly in your browser, akin to Google Analytics but tailored for Streamlit.

This fork was initiated due to the inability to collaborate directly on the upstream project, which currently has several unresolved security issues and bugs. Our intention is to maintain a positive relationship with the original project and its creator, focusing on enhancing the tool's reliability and security for the community.

Note

This fork is confirmed to fix the deprecation st.experimental_get_query_params alerts. Context
It also resolved 25 security issues that exist in the upstream (2 Critical, 11 High, 10 Moderate, 2 Low)

This project is in active development. We welcome contributions and address security concerns on a best-effort basis, with details available in our CONTRIBUTING.md and SECURITY.md respectively.

Installation

pip install streamlit-analytics2

Migration from upstream streamlit-analytics

Only two single characters need to be changed and this has been tested and verified to work.

  1. Change your requirements.txt or other dependency file to use 'streamlit-analytics2'. Just add a '2'
  2. Change your code import to use 'streamlit_analytics2 as streamlit_analytics'. Also, just add a '2'. Seen below.

Important

This project aims to be backwards compatible with the upstream and migration literally just means adding the number 2 and getting the new package.
The above steps should be sufficient but if you need more steps, check out our Migration Guide.

How to Use

Simple integration with any Streamlit app:

import streamlit as st
import streamlit_analytics2 as streamlit_analytics

with streamlit_analytics.track():
    st.write("Hello, World!")
    st.button("Click me")

All interactions are now tracked, supporting all standard Streamlit widgets.

Another way to get the tracking is to call the streamlit_analytics.track() on your main() function:

import streamlit as st
import streamlit_analytics2 as streamlit_analytics

with streamlit_analytics.track():
    main()

def main():
    st.write("Hello, World!")
    st.button("Click me")

Using streamlit_analytics.track() is the recommended method and will become the primary way to initiate streamlit-analytics2 after the upcoming v.1.0.0 release.

Moving Forward

  • TODOs and Feature Requests: We've transitioned our roadmap and feature requests to GitHub Issues. Feel free to contribute ideas or report bugs!
  • Advanced Configuration: Detailed guidance on advanced setup (including password protection and database integration) options are available in our Project Wiki.
  • Improved Performance: We are focused on providing a use of streamlit-analytics2 that doesn't impact the performance of your app.
    All suggestions and inputs are welcome on our forum

Contributing

Your contributions are welcome! Please refer to our CONTRIBUTING.md for guidelines on how to make a difference. The step by step guide will show you how to set up a dev environment, testing standards and how to make a PR.

Security

We prioritize the security of our users' data. For reporting security vulnerabilities or for more information, please review our SECURITY.md.

Acknowledgments

A special thanks to jrieke and all contributors to the original streamlit-analytics project. Your work has inspired continued innovation and community collaboration.

streamlit-analytics2's People

Contributors

jrieke avatar 444b avatar uranium2 avatar alyetama avatar bulletmark avatar pedroprates avatar realisticitem avatar dependabot[bot] avatar

Stargazers

 avatar Aflah avatar  avatar Zifeng avatar  avatar Pranjal Pruthi avatar Doug avatar shuyueW1991 avatar wong mc avatar  avatar  avatar Vikram avatar  avatar Cem Aksoylar avatar Andy Richardson avatar Alexander Rogiers avatar Hadrien avatar  avatar Hansi P. avatar Jan Gieseler avatar Daniel Senff avatar

Watchers

Alon avatar  avatar

streamlit-analytics2's Issues

KeyError when using select_slider

Original issue by upasana-mittal on 2023-02-02 22:13:34+00:00

I am getting a key error at st.select slider

start_rating, end_rating = st.select_slider("Select range of CSAT", options=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], value=(2, 4))

KeyError: (2, 4)

Google Analytics integration

Original issue by 444B on 2023-11-23 19:45:13+00:00

Request: To pass your analytics token into an optional function streamlit_analytics.google_analytics('gtag_ID') and allow the site owner to see the analytics use of their website

Additional Request: To enable alternative analytics providers in the same or similar fashion.

I am developing this on my fork for now
The purpose of this issue is to serve as a discussion point around integrations Google Analytics for any interested parties.

track download_button

Original issue by ZA89676 on 2023-02-04 23:11:17+00:00

Tracking does not seem to be enabled for download_button. Would it be possible to add?

TypeError when displaying the tracking analytics

Original issue by BillelBenoudjit on 2023-02-07 10:22:18+00:00

Got this issue when trying to displaying the tracking analytics with ?analytics=on. Any clues to fix this issue?

TypeError: metric() got an unexpected keyword argument 'help'
Traceback:
File "/usr/local/lib/python3.6/dist-packages/streamlit/scriptrunner/script_runner.py", line 554, in _run_script
    exec(code, module.__dict__)
File "/home/ubuntu/SE_github/streamlit_apps/dev_pages/csv_merger.py", line 22, in <module>
    "...and now add `?analytics=on` to the URL to see the analytics dashboard ๐Ÿ‘€"
File "/usr/lib/python3.6/contextlib.py", line 88, in __exit__
    next(self.gen)
File "/usr/local/lib/python3.6/dist-packages/streamlit_analytics/main.py", line 440, in track
    verbose=verbose,
File "/usr/local/lib/python3.6/dist-packages/streamlit_analytics/main.py", line 405, in stop_tracking
    display.show_results(counts, reset_counts, unsafe_password)
File "/usr/local/lib/python3.6/dist-packages/streamlit_analytics/display.py", line 44, in show_results
    help="Every time a user (re-)loads the site.",

Graph visualization sorts by months ignore year

Original issue by Dahie on 2024-01-23 08:35:12+00:00

We run streamlit_analytics since December and collect data successfully. The visualization however doesn't handle the year-switch well. The visualization aparently only sorts by month and ignores the year.

Bildschirmfoto 2024-01-23 um 09 30 39

Expected behaviour would be to start the graph have the graph between November '23 to Jan '24 in one line without wrap-around.

[BUG]

Describe the bug
A clear and concise description of what the bug is.

  • When trying to reset analytics in /?analytics=on, the reset button will not apear after choosing the "I'm absolutely sure that I want to reset the results".

  • I think the root cause is a typo in src/streamlit_analytics2/display.py

  • line 153-160

            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 sure that I want to reset the results":
  • The if statement in 160 has a typo that cannot match the selectbox in 157.

Expected behavior
A clear and concise description of what you expected to happen.

  • The button "Click here to reset" should appear

To Reproduce
Steps to reproduce the behavior:

  1. Go to '/?analytics=on' path > Danger Zone
  2. Click on 'I'm absolutely sure that I want to reset the results'
  3. See error

Software Versions
Please fill in the relevant field:

  • streamlit_analytics2 : 0.7.5
  • streamlit : 1.35.0
  • Python3 : 3.9-slim

Screenshots
If applicable, add screenshots to help explain your problem.

Additional context
Add any other context about the problem here.

streamlit >= 1.12.0 not supporting this package

Original issue by zivshapiraintel on 2022-08-17 05:50:11+00:00

streamlit >= 1.12.0 not supporting this package

When upgrading our working code from streamlit 1.11.1 to 1.12.0, this package breaks

Add support for sliders / tuples in widget interactions

Original issue by eschares on 2021-04-25 19:15:46+00:00

Almost all my widets are setup as double-sided sliders, which return a tuple of values. This produces an error in the widget interactions section of the report as tuples are not supported.

slider

I don't know what it would take to enable this, but I would like to have that functionality available to me.

Timestamp data?

Original issue by nixshal on 2022-02-07 06:19:48+00:00

Hi, I got the JSON output but was wondering if there was a way to get the timestamp data for each input/run too?

[BUG] Checkbox counts are incremented on startup

Describe the bug
The counts for all checkboxes are incremented on startup without user interaction. Counts for checkboxes always start at one instead of zero and are incremented without interaction from the user.

Expected behavior
I would expect the counts for all widgets to start at zero the first time the app is run. Once a user checks or unchecks a checkbox, the count for that checkbox should increment by one. Checkboxes that are untouched should remain at count 0.

To Reproduce

  1. Make a Streamlit app with at least one checkbox (and which stores the counts in, e.g., a JSON file).
  2. Run the app.
  3. See that the count for all checboxes start at 1 instead of 0 by examining the JSON file.
  4. Stop and re-start the app.
  5. See that the count for all checkboxes have been incremented by 1 without user interaction.

Software Vesions

  • streamlit_analytics2 : v0.7.7

Additional context
The original streamlit-analytics repo by jrieke also has this bug.

Suggested fix:
We should not increment the count the first time the script is run, only after a user has interacted with the checkbox. The following code attempts to solve this issue:

def _wrap_checkbox(func):
    """
    Wrap st.checkbox.
    """

    def new_func(label, *args, **kwargs):
        checked = func(label, *args, **kwargs)
        label = replace_empty(label)
        if label not in counts["widgets"]:
            counts["widgets"][label] = 0

        # we only increment the count if the user has interacted with the checbox
        if label in st.session_state.state_dict and checked != st.session_state.state_dict[label]:
            counts["widgets"][label] += 1

        st.session_state.state_dict[label] = checked
        return checked

    return new_func

The code and comments here are just suggestions.

[FEATURE] Provide ability to "export" to various backend services

Is your feature request related to a problem? Please describe.
I would like to be able to export analytics data to other backends e.g. MotherDuck

Describe the solution you'd like
Make it easy for the use with documented API to access analytics data to be able to push to other backends and/or support other backends.

Describe alternatives you've considered
Firestore backend already exists.

Additional context
I use DuckDB for ETL of data and for analytics (which it is designed for) - MotherDuck provides a SaaS version of DuckDB which is persistent and easily shareable.

p.s. Nice work on project - I'd also like multipage app tracking support e.g. with latest st.Page() features.

error with enqueue?

Original issue by nixshal on 2022-01-27 17:24:53+00:00

I packaged your 'minimal' example into a app() function (so I can run it as a page in a multi-page streamlit app). Similar to what's being done here.

import streamlit as st
import datetime

try:
    import streamlit_analytics
except ImportError:
    import subprocess, sys # Install streamlit-analytics on first run (not included in requirements.txt).
    subprocess.check_call([sys.executable, "-m", "pip", "install", "streamlit_analytics"])
    import streamlit_analytics

def app():
  with streamlit_analytics.track(verbose=True):
    st.text_input("Write your name")
    st.selectbox("Select your favorite", ["cat", "dog", "flower"])
    st.button("Click me")

However, I got the following error using streamlit 1.4

File "/home/appuser/venv/lib/python3.7/site-packages/streamlit/script_runner.py", line 379, in _run_script
    """
File "/app/k_internal_tools/app.py", line 23, in <module>
    apps.run()
File "/app/k_internal_tools/multiapp.py", line 64, in run
    functions[titles.index(title)]()
File "/app/k_internal_tools/apps/tracking.py", line 12, in app
    with streamlit_analytics.track(verbose=True):
File "/usr/local/lib/python3.7/contextlib.py", line 112, in __enter__
    return next(self.gen)
File "/home/appuser/venv/lib/python3.7/site-packages/streamlit_analytics/main.py", line 443, in track
    load_from_json=load_from_json,
File "/home/appuser/venv/lib/python3.7/site-packages/streamlit_analytics/main.py", line 282, in start_tracking
    last_time=datetime.datetime.now(),
File "/home/appuser/venv/lib/python3.7/site-packages/streamlit_analytics/session_state.py", line 92, in get
    (not hasattr(s, "_main_dg") and s.enqueue == ctx.enqueue)

Any ideas?

Option to load firestore key from dict

Original issue by alizahidraja on 2023-02-28 20:52:22+00:00

I am trying to deploy an app & I do not want to publicly show my firebase key

For this I use st.secrets to make a dict object, but there is no option to pass it to the track function

[BUG] Graph does not display

Describe the bug
I integrated streamlit-analytics2 in my streamlit app, open the app in my browser with the parameter analytics=on, but the graphs are not displayed.

To Reproduce
You can use this boilerplate, to simulate: https://github.com/WhatAVenture/wav-streamlit-boilerplate

  1. Run the app
  2. Open http://localhost:8501?analytics=on
  3. It opens the page, but without showing the analytics summary and timeline.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: MacOS
  • Browser Firefox
  • Version 123.0.1

Additional context
I have the same issue in a different project, but the boilerplate shows it clearest.

[BUG] Cannot store multipage analytics in Firestore: `ValueError: One or more components is not a string or is empty.`

Describe the bug
I have a deployed multipage Streamlit app and am trying to store the results of streamlit-analytics2 in Google Firestore, so that they persist when the app is re-deployed. I added this line on one of the pages of the multipage app:

with streamlit_analytics.track(
    firestore_key_file="...",
    firestore_collection_name="..."
):

After adding this line, when accessing the page http://localhost:8501/<PAGE_NAME>?analytics=on, where the analytics should be, I instead get this traceback:

ValueError: One or more components is not a string or is empty.
Traceback:

File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 541, in _run_script
    prep_time = timer() - start_time
File "/Users/<USER_NAME>/Work/<COMPANY_NAME>/<PROJECT_NAME>/pages/<PAGE_NAME>.py", line 14, in <module>
    with streamlit_analytics.track(
File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/contextlib.py", line 142, in __exit__
    next(self.gen)
File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/site-packages/streamlit_analytics2/main.py", line 517, in track
    stop_tracking(
File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/site-packages/streamlit_analytics2/main.py", line 463, in stop_tracking
    firestore.save(counts, firestore_key_file, firestore_collection_name)
File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/site-packages/streamlit_analytics2/firestore.py", line 24, in save
    doc.set(counts)  # creates if doesn't exist
File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/site-packages/google/cloud/firestore_v1/document.py", line 166, in set
    batch, kwargs = self._prep_set(document_data, merge, retry, timeout)
File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/site-packages/google/cloud/firestore_v1/base_document.py", line 217, in _prep_set
    batch.set(self, document_data, merge=merge)
File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/site-packages/google/cloud/firestore_v1/base_batch.py", line 111, in set
    write_pbs = _helpers.pbs_for_set_no_merge(
File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/site-packages/google/cloud/firestore_v1/_helpers.py", line 702, in pbs_for_set_no_merge
    extractor = DocumentExtractor(document_data)
File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/site-packages/google/cloud/firestore_v1/_helpers.py", line 504, in __init__
    for field_path, value in iterator:
File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/site-packages/google/cloud/firestore_v1/_helpers.py", line 451, in extract_fields
    for s_path, s_value in extract_fields(value, field_path):
File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/site-packages/google/cloud/firestore_v1/_helpers.py", line 451, in extract_fields
    for s_path, s_value in extract_fields(value, field_path):
File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/site-packages/google/cloud/firestore_v1/_helpers.py", line 446, in extract_fields
    sub_key = FieldPath(key)
File "/opt/anaconda3/envs/<ENV_NAME>/lib/python3.10/site-packages/google/cloud/firestore_v1/field_path.py", line 272, in __init__
    raise ValueError(error)

If I just use with streamlit_analytics.track(), without using Firestore as a backend, the analytics work correctly.

Expected behavior

I expected the Streamlit app to show analytics as usual, and expected to see some data in the Firestore database.

To Reproduce
Steps to reproduce the behavior:

  1. Create a simple multipage app
  2. Add the line with streamlit_analytics.track(firestore_key_file="...", firestore_collection_name="..."): in one of the pages
  3. Access localhost:8501 and browse to the page with the line from step 2
  4. See error

Software Vesions
Please fill in the relevant field:

  • streamlit_analytics2 : 0.6.4
  • streamlit : 1.32.2
  • Python3 : 3.10.10

Screenshots
image

Tracking all select/multiselect options can consume too much memory

Original issue by mateusccoelho on 2023-09-02 14:10:28+00:00

Currently this package tracks all select/multiselect options, even if they are not selected. This maybe is a good feature because the option list can change during the app utilization. Still, we can't track which option were available to each user.

On the other hand, this can be problematic when using more than, say, 3000 options. Or when the label changes in execution time. The visualization in the analytics section becomes too large and this has the potential of using a lot of memory, since counts are stored in session state. That is, it's necessary to allocate a dict with 3000 string keys.

Example:

import streamlit as st
import streamlit_analytics as st_analytics

with st_analytics.track():
    val = st.multiselect('abc', list(range(5000)))

One thing that's supposed to be desirable with this package is to interfere as little as possible with the server's resources or with the user's code. So I propose to create a parameter in start_tracking so the user can choose to track all options. But it should be False by default, in which case _wrap_select and _wrap_multiselect should behave like _wrap_value.

[BUG] `state_dict` is reset every time `start_tracking()` is called

Description
There is a typo in the start_tracking function where the state_dict is incorrectly checked as state_dic, causing the state_dict to be reset every time start_tracking is called.

Expected behavior
The state_dict should be stored in the session state for the duration of the session without being reset. This will ensure counts are correctly updated.

To Reproduce

  • Run a streamlit app which uses the streamlit-analytics2 package.
  • Monitor how counts are updated. You may see that the counts are not accurately captured due to the state_dict being reset.

Additional context
This bug is also present in the original streamlit-analytics repo by jrieke.

Suggested fix

# Current incorrect code
if "state_dic" not in st.session_state:
    st.session_state.state_dict = {}

# Suggested fix
if "state_dict" not in st.session_state:
    st.session_state.state_dict = {}

Tracking buttons with the same name

Original issue by amirmk89 on 2023-01-12 15:10:09+00:00

Hi, awesome tool!

I have a use case where several buttons have the same text, and currently the analytics tool tracks all of them as a single button. Each of the buttons has a unique key, and I thought it could be useful to support key based indexing instead of, e.g., button label based.
Is this possible in streamlit-analytics?

Thanks!

New widget support

Original issue by spotglenn on 2023-07-16 14:25:14+00:00

Just wanted to say this module works so well and is exactly what I was looking for.

Just wondering if you plan to include tracking support for newer widgets (e.g st.chat_input) somewhere down the line?

None Selected

Original issue by hansipie on 2024-02-02 18:22:02+00:00

Hello,

Defining a selectbox like this :
select = st.selectbox("title", ("A", "B"), index=None)
... I get a KeyError exception at main.py:162
This is caused by the default "None" value. It is changed into an empty space by "replace_empty(...)", but
if selected != st.session_state.state_dict.get(label, None): goes into the "true" statement, and causes an exception.

The fix at main.py:161:
if selected != st.session_state.state_dict.get(label, " "):

I make a PR or let you fix ...

[FEATURE] - add new input widgets

Issue description

Since the last release of the upstream of streamlit-analytics, there have been a few new input widgets released. Namely:

  • st.download_button
  • st.link_button
  • st.page_link
  • st.toggle
  • st.camera_input

There are no wrappers for some of them and they are require testing for both the standard widget and within the sidebar.

Fix:

Implement wrapper and tests:

standard functions

  • st.download_button
  • st.link_button
  • st.page_link
  • st.toggle
  • st.camera_input

sidebar functions

  • st.sidebar.download_button
  • st.sidebar.link_button
  • st.sidebar.page_link
  • st.sidebar.toggle
  • st.sidebar.camera_input

Chat Inputs

Depreciation warning popup and message about st.experimental_dialog since streamlit 1.37.0

Since streamlit version 1.37.0, we get a display popup at app start and a message on stdout saying:

2024-08-06 15:46:39.661 Please replace `st.experimental_dialog` with `st.dialog`.

`st.experimental_dialog` will be removed after 2025-01-01.

See streamlit 1.37.0 release notes.

src/streamlit_analytics2/display.py line 11 needs update. Was going to add a PR but wasn't sure if best to add a runtime check on streamlit version (for backwards compatibility), or just up the minimum version in pyproject.toml.

This is using streamlit_analytics2 version 0.8.1.

Create full path for tracking file

Original issue by Nickelza on 2023-02-06 00:51:59+00:00

When given a file.json to store data, it'd be nice if the path to the file is created if it doesn't exist

[BUG] Logging basicConfig may be imported and overwriting logging for user modules

Describe the bug
A clear and concise description of what the bug is.

  • While using SA2 for a custom project, I realized there was logging taking place into standard output when this was not intended
  • This was being attributed to SA2:
  • streamlit-analytics2: INFO: HTTP Request: POST https://api.openai.com/v1/embeddings "HTTP/1.1 200 OK"
  • However I can rule out without a single doubt that this was not intended behavior
  • As a result of this knowledge, I can not allow such unintended behavior for the other users of SA2 (currently around 350 downloads a month)

Expected behavior
A clear and concise description of what you expected to happen.

  • Logging should only be invoked if "verbose" is passed as an argument to track() or an alternative function

Software Vesions
Please fill in the relevant field:

  • streamlit_analytics2 : 0.7.2
  • streamlit : 1.33.0
  • Python3 : 3.10.12

[BUG] - streamlit crashed when running from python directly

Describe the bug
When running streamlit run main.py the files runs without issue
However, when running python3 main.py it will crash and attribute it to streamlit-analytics2

To Reproduce
Steps to reproduce the behavior:

  1. write boilerplate streamlit file as main.py
  2. install streamlit and streamlit-analytics2
  3. enter python3 main.py

Expected behavior
streamlit should run as expected, as seen with streamlit run main.py
Confirmed that this has no correlation to the streamlit-analytics2 migration as it appears on the upstream as well

Error text

python3 main.py 
2024-03-02 08:46:19.021 WARNING streamlit.runtime.state.session_state_proxy: Session state does not function when running a script without `streamlit run`
Traceback (most recent call last):
  File "/home/codespace/.python/current/lib/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 398, in __getitem__
    return self._getitem(widget_id, key)
  File "/home/codespace/.python/current/lib/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 443, in _getitem
    raise KeyError
KeyError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/codespace/.python/current/lib/python3.10/site-packages/streamlit/runtime/state/session_state_proxy.py", line 119, in __getattr__
    return self[key]
  File "/home/codespace/.python/current/lib/python3.10/site-packages/streamlit/runtime/state/session_state_proxy.py", line 90, in __getitem__
    return get_session_state()[key]
  File "/home/codespace/.python/current/lib/python3.10/site-packages/streamlit/runtime/state/safe_session_state.py", line 91, in __getitem__
    return self._state[key]
  File "/home/codespace/.python/current/lib/python3.10/site-packages/streamlit/runtime/state/session_state.py", line 400, in __getitem__
    raise KeyError(_missing_key_error_message(key))
KeyError: 'st.session_state has no key "last_time". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/workspaces/codespaces-blank/main.py", line 4, in <module>
    with streamlit_analytics.track():
  File "/home/codespace/.python/current/lib/python3.10/contextlib.py", line 135, in __enter__
    return next(self.gen)
  File "/home/codespace/.python/current/lib/python3.10/site-packages/streamlit_analytics2/main.py", line 425, in track
    start_tracking(
  File "/home/codespace/.python/current/lib/python3.10/site-packages/streamlit_analytics2/main.py", line 276, in start_tracking
    _track_user()
  File "/home/codespace/.python/current/lib/python3.10/site-packages/streamlit_analytics2/main.py", line 78, in _track_user
    counts["total_time_seconds"] += (now - st.session_state.last_time).total_seconds()
  File "/home/codespace/.python/current/lib/python3.10/site-packages/streamlit/runtime/state/session_state_proxy.py", line 121, in __getattr__
    raise AttributeError(_missing_attr_error_message(key))
AttributeError: st.session_state has no attribute "last_time". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization

support for multipage - fork / wrap st.title?

Original issue by fredzannarbor on 2022-08-12 06:15:42+00:00

Hi,

I want to have some analytics for my multipage app. I forked @franasol's fork and took a look. It seems as if the way to proceed is to create wrapper functions for the page filename and st.title, then feed the results into a new object that is compatible with the other counting objects. Is that more or less correct? Any gotchas?

Load Json to persist data between deployments

Original issue by Uranium2 on 2021-10-06 12:54:43+00:00

Hello,

I see you used firebase to do persist data between deployments, would it be possible to add this feature with json?

Context:

In my case the streamlit app is deployed on a docker and we have no persistence of volume (security constraint), so I was thinking about uploading the json on a server at fixed frequency rate. For example a task that will upload the json file each 30 seconds.

Then if the docker dies, we could fetch this json and load it in your tracker to persist the data.

Firestore not playing nice with file_uploader

Original issue by jucor on 2021-04-20 20:31:21+00:00

When one of the widgets is a file_uploader and Firestore is enabled, an error is thrown at stop_tracking complaining about something something not being a string something something.
(sorry, did not save the exact error anymore, I worked around it, see below).

This error does not appear when Firestore is not enabled.

I suspect this is because the return value of a file uploader is sometimes None and sometimes an instance of class UploadedFile, which is not a string. That causes a problem at seralization time into Firestore.

Workaround: I only call start_tracking() after having instanciated my file_uploader widget, meaning I cannot track any widget that comes before it. Sad, but the only way to make it work so far.

Alternative: adding a conditional to automatically convert the value of file_uploader into a string (containing maybe just the filename, not the whole uploaded file).

streamlit-analytics does not load on deploy to share.streamlit.io

Original issue by eschares on 2021-04-25 19:11:38+00:00

I really like the idea for this, as logging usage stats is one thing Streamlit is sorely lacking. Adding streamlit-analytics to my app works on my local machine

import streamlit_analytics

streamlit_analytics.start_tracking()
---code---
streamlit_analytics.stop_tracking()

but when copying to GitHub and deploying, the Streamlit share crashes and does not find the module streamlit_analytics. Is there something else I need to do to tell share.streamlit.io that I'm using this package? Your Live Demo is up, so it must be possible to deploy there.

ReportThread - ModuleNotFoundError

Original issue by trsavi on 2022-02-01 12:57:20+00:00

ReportThread seems to not be working with new version of streamlit (1.5.0.), I got ModuleNotFoundError. When I changed the source code in session_state.py and commented lines for importing report_thread and also disregarded ctx (ctx = ReportThread.get_report_ctx()) variable throughout the script I avoided error on local machine and everything worked fine (I could see basic statistics) but when I deploy it onto streamlit share framework error appeared once again.
Any thoughts on this?

Error using your module

Original issue by KassiusKlay on 2021-04-27 12:42:15+00:00

Screenshot 2021-04-27 at 13 38 48

I have this error when using your code, I had my own SessionState before but this error is after completely removing my call on session state.

Screenshot 2021-04-27 at 13 41 48

Any idea.
Thanks

track with conditions

Original issue by abobafett-dev on 2022-11-17 12:38:49+00:00

Hello, I have student project where I use your package. And I want to track information in if construction with elements which I create before that. Can I track information in same elements which I track information before use if or custom element.

Something like:
in code:

with streamlit_analytics.track():
    options = streamlit.multiselect(
        'Choose your color:',
        [
            '๐Ÿ”ด',
            '๐ŸŸก',
            '๐Ÿ”ต',
            '๐ŸŸข',
            '๐ŸŸฃ'
        ],
    button = streamlit.button('activate_button')
if button:
    streamlit_analytics.custom_track(name_of_element='activate_button')
    streamlit_analytics.custom_track(name_of_element='count_of_using_main_feature')

current result after choose ๐Ÿ”ด and ๐ŸŸก colors and click on button:

{
    'Choose your color:'
    {
        '๐Ÿ”ด': 3
        '๐ŸŸก': 2
        '๐Ÿ”ต': 0
        '๐ŸŸข': 0
        '๐ŸŸฃ': 0
    }
    'activate_button': 1
}

what I want to see:

{
    'Choose your color:'
    {
        '๐Ÿ”ด': 3
        '๐ŸŸก': 2
        '๐Ÿ”ต': 0
        '๐ŸŸข': 0
        '๐ŸŸฃ': 0
    }
    'activate_button': 2
    'count_of_using_main_feature': 1
}

Can you help me with that?

By the way, there is another point here. I think that bad if the checkbox has the value False, then it is tracking. And the fact that if I select elements in multiselect, it's all tracking sequentially as in the example above.

AttributeError: st.session_state has no attribute "last_time".

Original issue by rawmean on 2023-05-12 02:08:34+00:00

I get the following error:

AttributeError: st.session_state has no attribute "last_time". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization

It comes from this line. The fix seems to be easy (avoid using the dot notation when the key doesn't exist)

    if "last_time" not in st.session_state:
        st.session_state.last_time = datetime.datetime.now()
    _track_user()

Saving to Firestore fails for `None` values

Original issue by jucor on 2021-04-20 19:53:05+00:00

Hi!
Quite excited at the prospect of using streamlit-analytics, but with streamlit-analytics 0.2.2 I get a bad error when calling

sa.stop_tracking(firestore_key_file="firestore-key.json", firestore_collection_name="counts") 

The following error gets displayed in my app:

TypeError: '<' not supported between instances of 'str' and 'NoneType'
Traceback:
File "/opt/conda/lib/python3.6/site-packages/streamlit/script_runner.py", line 337, in _run_script
    exec(code, module.__dict__)
File "/root/xray/web_demo_streamlit.py", line 244, in <module>
    firestore_collection_name="counts")
File "/opt/conda/lib/python3.6/site-packages/streamlit_analytics/main.py", line 381, in stop_tracking
    firestore.save(counts, firestore_key_file, firestore_collection_name)
File "/opt/conda/lib/python3.6/site-packages/streamlit_analytics/firestore.py", line 24, in save
    doc.set(counts)  # creates if doesn't exist
File "/opt/conda/lib/python3.6/site-packages/google/cloud/firestore_v1/document.py", line 166, in set
    batch, kwargs = self._prep_set(document_data, merge, retry, timeout)
File "/opt/conda/lib/python3.6/site-packages/google/cloud/firestore_v1/base_document.py", line 211, in _prep_set
    batch.set(self, document_data, merge=merge)
File "/opt/conda/lib/python3.6/site-packages/google/cloud/firestore_v1/base_batch.py", line 98, in set
    reference._document_path, document_data
File "/opt/conda/lib/python3.6/site-packages/google/cloud/firestore_v1/_helpers.py", line 697, in pbs_for_set_no_merge
    extractor = DocumentExtractor(document_data)
File "/opt/conda/lib/python3.6/site-packages/google/cloud/firestore_v1/_helpers.py", line 497, in __init__
    for field_path, value in iterator:
File "/opt/conda/lib/python3.6/site-packages/google/cloud/firestore_v1/_helpers.py", line 444, in extract_fields
    for s_path, s_value in extract_fields(value, field_path):
File "/opt/conda/lib/python3.6/site-packages/google/cloud/firestore_v1/_helpers.py", line 444, in extract_fields
    for s_path, s_value in extract_fields(value, field_path):
File "/opt/conda/lib/python3.6/site-packages/google/cloud/firestore_v1/_helpers.py", line 434, in extract_fields
    for key, value in sorted(document_data.items()):

Any idea what I'm missing, please?

Reset analytics

Original issue by robsannaa on 2021-01-22 12:59:28+00:00

Hello! First of all thanks for this. It is really great to have something like built for Streamlit!

I have tried saving the analytics as JSON, and I have noticed that if I delete the .json file, once I run the app again I will still get my "old" analytics files. Is there a wy to reset the tracking and start from zero at some point?

Traffic plot improvement

Original issue by mateusccoelho on 2023-08-27 03:27:32+00:00

  1. Initialize the traffic counts with yesterday is not right because it's misleading. If one doesn't know how the package works, he/she will think that the first day had no visitors.
  2. If the computer running the Streamlit server is in a negative timezone, altair/javascript will parse dates wrong and "shift" dates by -1 day. This Stack Overflow thread explains the issue.

See plot below to visualize the two problems:

image

Notice the first day is 0 and that the counting started in 27th august, but there are no pageviews in this day.

Issues with Session State

Original issue by oltipreka on 2021-01-09 10:41:16+00:00

Hi guys,
First, congratulations for the great idea of creating an analytics tool for Streamlit.

I am having an issue when using Streamlit_analytics with a Login class for single user given as an argument within get_session_state

Is there any rule where to precisely include insert .start_tracking() and .stop_tracking() within a Streamlit app?

[BUG] streamlit-analytics cannot track multi-page separately

I have 2 pages in my application, and I'm tracking both the page views and st.sidebar.file_uploader for each page. On page1, the number of page_view and the number of uploaded_file is only for page 1, which is as expected. However for page2, the number of page_view and the number of uploaded_file are not only of page2, but also combined with these two metrics of page1. Any idea why that maybe happening? Thank you.

Error on show_results

Original issue by tiagocampo on 2022-11-21 19:29:39+00:00

Hello, I'm trying to use your implementation and saving the results to a json file. It works fine when running on my local machine, but when deploying on a server I keep getting:
streamlit_analytics.stop_tracking(save_to_json='path', unsafe_password='somepass')
display.show_results(counts, reset_counts, unsafe_password)
metric() got an unexpected keyword argument 'help'.

I'm running on python 3.7, streamlit 1.9 and analytics 0.4.1.

Thanks for your time and attention.

[FEATURE] - v1.0.0 Settings Page + Refactor + GA4

Issue description

Currently, there is a growing need to allow developers to customize streamlit. Some existing features are:

  • password protection
  • firestore as storage for logs
  • save location of local json for logs

However, there are a few requests for new features, outlined below.

Suggested fix

Primary

  • #57
  • #54
  • Separate between application and tracking logic
  • settings page for configuration

Added features: - (dependent on Primary)

  • More granular timestamps - #31
  • GA4 support - #16
  • track all new widgets - #46

Refactor - (dependent on Primary)

  • multi-page tracking - #47
  • track inputs with same name - #26
  • traffic plot improvement (originally # 18)
  • efficient tracking of multiselect (originally # 17)
  • Add streamlits AppTest framework for pytest coverage

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.