Skip to content

Commit

Permalink
Merge pull request #127 from 444B/config-screen
Browse files Browse the repository at this point in the history
Config screen
  • Loading branch information
444B authored Jan 12, 2025
2 parents f0a050d + 695911b commit a90abe5
Show file tree
Hide file tree
Showing 16 changed files with 1,027 additions and 523 deletions.
24 changes: 24 additions & 0 deletions .streamlit/analytics.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[streamlit_analytics2]
enabled = true

[storage]
save = false
type = "json"
save_to_json = "path/to/file.json"
load_from_json = "path/to/file.json"

[logs]
verbose = false

[access]
unsafe_password = "hunter2"

[firestore]
enabled = false
firestore_key_file = "firebase-key.json"
firestore_project_name = ""
firestore_collection_name = "data"
streamlit_secrets_firestore_key = ""

[session]
session_id = ""
24 changes: 24 additions & 0 deletions analytics.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[streamlit_analytics2]
enabled = "true"

[storage]
save = "false"
type = "json"
save_to_json = "path/to/file.json"
load_from_json = "path/to/file.json"

[logs]
verbose = "false"

[access]
unsafe_password = "test123"

[firestore]
enabled = "false"
firestore_key_file = "firebase-key.json"
firestore_project_name= ""
firestore_collection_name = "data"
streamlit_secrets_firestore_key = ""

[session]
session_id = ""
25 changes: 25 additions & 0 deletions examples/.streamlit/analytics.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[streamlit_analytics2]
enabled = true

[storage]
save = false
type = "json"
save_to_json = "path/to/file.json"
load_from_json = "path/to/file.json"

[logs]
verbose = false

[access]
unsafe_password = "hunter2"

[firestore]
enabled = false
firestore_key_file = "firebase-key.json"
firestore_project_name = ""
firestore_collection_name = "streamlit_analytics2"
firestore_document_name = "data"
streamlit_secrets_firestore_key = ""

[session]
session_id = ""
1 change: 1 addition & 0 deletions examples/minimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,4 @@
st.text_input("Write your name")
st.selectbox("Select your favorite", ["cat", "dog", "flower"])
st.button("Click me")
streamlit_analytics.data
38 changes: 38 additions & 0 deletions examples/pages/firebase_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import streamlit as st

import streamlit_analytics2 as streamlit_analytics

tab1, tab2 = st.tabs(["Classic", "Advanced"])


# classic firestore load
with tab1:
st.header("Classic")

if st.button("Test Classic"):

with streamlit_analytics.track(
firestore_document_name="datalyttics",
firestore_key_file="pages/firebase-key.json",
firestore_collection_name="no_doc_name3",
firestore_project_name="streamlit-analtyics2",
verbose=True,
):

st.text_input("Write something")
st.button("Click me")


# Advanced storing of key in secrets.toml
with tab2:
st.header("Advanced")
# if st.button("Test Advanced"):

# with streamlit_analytics.track(
# firestore_collection_name="counts",
# streamlit_secrets_firestore_key="firebase",
# firestore_project_name="firestore_project_name",
# verbose=True):

# st.text_input("Write something")
# st.button("Click me")
5 changes: 5 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,8 @@ exclude_lines = [
[tool.bandit]
exclude_dirs = ["tests", "docs"]
skips = ["B311"]

[dependency-groups]
dev = [
"types-toml>=0.10.8.20240310",
]
5 changes: 3 additions & 2 deletions src/streamlit_analytics2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
Track & visualize user interactions with your streamlit app.
"""

from .main import counts, start_tracking, stop_tracking, track # noqa: F401
from .main import start_tracking, stop_tracking, track # noqa: F401
from .state import data # noqa: F401

__version__ = "0.9.1"
__version__ = "0.10.0"
__name__ = "streamlit_analytics2"
199 changes: 199 additions & 0 deletions src/streamlit_analytics2/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import os
from pathlib import Path

import streamlit as st
import toml

# import logging

# Set up logging
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)

# Default configuration
DEFAULT_CONFIG = {
"streamlit_analytics2": {"enabled": True},
"storage": {
"save": False,
"type": "json",
"save_to_json": "path/to/file.json",
"load_from_json": "path/to/file.json",
},
"logs": {"verbose": False},
"access": {"unsafe_password": "hunter2"},
"firestore": {
"enabled": False,
"firestore_key_file": "firebase-key.json",
"firestore_project_name": "",
"firestore_collection_name": "streamlit_analytics2",
"firestore_document_name": "data",
"streamlit_secrets_firestore_key": "",
},
"session": {"session_id": ""},
}


def ensure_streamlit_dir():
"""Ensure .streamlit directory exists"""
Path(".streamlit").mkdir(exist_ok=True)


def load_analytics_config():
"""Load analytics configuration with fallback to defaults"""
path = os.path.join(os.getcwd(), ".streamlit/analytics.toml")
# logger.info(f"Loading configuration from: {path}")

try:
if not os.path.exists(path):
# logger.warning("Configuration file not found. Creating with defaults.")
ensure_streamlit_dir()
save_config(DEFAULT_CONFIG)
return DEFAULT_CONFIG.copy()

with open(path, "r") as file:
config = toml.load(file)

# Check if file is empty or missing required sections
if not config or "streamlit_analytics2" not in config:
# logger.warning("Invalid configuration found. Resetting to defaults.")
save_config(DEFAULT_CONFIG)
return DEFAULT_CONFIG.copy()

return config

except Exception as e: # noqa: F841
# logger.error(f"Error loading configuration: {str(e)}")
st.error("Error loading configuration. Using defaults.")
return DEFAULT_CONFIG.copy()


def save_config(config):
"""Save configuration to file"""
path = os.path.join(os.getcwd(), ".streamlit/analytics.toml")
try:
ensure_streamlit_dir()
with open(path, "w") as file:
toml.dump(config, file)
new_config = config # noqa: F841
# logger.info("Configuration saved successfully")
except Exception as e: # noqa: F841
# logger.error(f"Error saving configuration: {str(e)}")
st.error("Failed to save configuration")
raise


def show_config():
"""Display and manage configuration"""
st.title("Analytics Configuration")
st.markdown(
"""
This config page serves as a proof of concept for all SA2 existing features
and some that dont exist yet (like CSV)\
The Buttons do not currently do anything - please make a PR to help
implement them.\
To learn how to use all these features, please visit the [Wiki](https://github.com/444B/streamlit-analytics2/wiki) which could also do with some love
> This will create a .streamlit/analytics.toml in the directory that you ran streamlit\
> You can edit the values in the text file directly if its easier
"""
)

# Load current config
config = load_analytics_config()

# Configuration inputs for streamlit_analytics2
enabled = st.checkbox(
"Enable Streamlit_Analytics2", value=config["streamlit_analytics2"]["enabled"]
)
st.divider()
storage_save = st.checkbox("Store Data", value=config["storage"]["save"])
storage_type = st.radio(
"Storage type",
["json", "CSV"],
horizontal=True,
index=0 if config["storage"]["type"] == "json" else 1,
)
save_path = st.text_input("Save File Path", value=config["storage"]["save_to_json"])
load_path = st.text_input(
"Load File Path", value=config["storage"]["load_from_json"]
)
st.divider()
verbose_logging = st.checkbox("Verbose Logging", value=config["logs"]["verbose"])
st.divider()
password = st.text_input(
"Access Password", value=config["access"]["unsafe_password"], type="password"
)
st.divider()
firestore_enabled = st.checkbox(
"Enable Firestore", value=config["firestore"]["enabled"]
)
firestore_key_file = st.text_input(
"Firestore Key File Path", value=config["firestore"]["firestore_key_file"]
)
firestore_project = st.text_input(
"Firestore Project Name", value=config["firestore"]["firestore_project_name"]
)
firestore_collection = st.text_input(
"Firestore Collection Name",
value=config["firestore"]["firestore_collection_name"],
)
firestore_document = st.text_input(
"Firestore Document Name",
value=config["firestore"]["firestore_document_name"],
)
firestore_secret_key = st.text_input(
"Firestore Secret Key",
value=config["firestore"]["streamlit_secrets_firestore_key"],
type="password",
)
st.divider()
session_id = st.text_input("Session ID", value=config["session"]["session_id"])
st.divider()

# Create new config from inputs
new_config = {
"streamlit_analytics2": {"enabled": enabled},
"storage": {
"save": storage_save,
"type": storage_type,
"save_to_json": save_path,
"load_from_json": load_path,
},
"logs": {"verbose": verbose_logging},
"access": {"unsafe_password": password},
"firestore": {
"enabled": firestore_enabled,
"firestore_key_file": firestore_key_file,
"firestore_project_name": firestore_project,
"firestore_collection_name": firestore_collection,
"firestore_document_name": firestore_document,
"streamlit_secrets_firestore_key": firestore_secret_key,
},
"session": {"session_id": session_id},
}

st.subheader("Current Configuration")
st.write(
"This is the final JSON that will get parsed to TOML in .streamlit/analytics.toml"
)
st.json(new_config)

col1, col2 = st.columns(2)

with col1:
# Save button
if st.button("Save Configuration", type="primary"):
try:
save_config(new_config)
st.success("Configuration saved!")
except Exception:
st.error("Failed to save configuration. Please check logs.")

with col2:
# Reset to defaults button
if st.button("↻ Reset to Defaults"):
save_config(DEFAULT_CONFIG)
st.success("Configuration reset to defaults!")
new_config = DEFAULT_CONFIG
st.rerun()
Loading

0 comments on commit a90abe5

Please sign in to comment.