Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +130 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,132 @@
|
|
| 1 |
-
import altair as alt
|
| 2 |
-
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
""
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
|
| 10 |
-
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
|
| 11 |
-
forums](https://discuss.streamlit.io).
|
| 12 |
-
|
| 13 |
-
In the meantime, below is an example of what you can do with just a few lines of code:
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
|
| 17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
# Try to import from your uploaded files.
|
| 6 |
+
# If they are missing, we will show a helpful error in the app.
|
| 7 |
+
try:
|
| 8 |
+
from demo import run_checks, format_console_output
|
| 9 |
+
from llm_utils import generate_summary
|
| 10 |
+
except ImportError as e:
|
| 11 |
+
st.error(f"❌ Could not import modules: {e}")
|
| 12 |
+
st.info("Make sure you have uploaded 'demo.py' and 'llm_utils.py' to your Space!")
|
| 13 |
+
st.stop()
|
| 14 |
+
|
| 15 |
+
# ---------------------------------------------------------------------------
|
| 16 |
+
# Configuration & Setup
|
| 17 |
+
# ---------------------------------------------------------------------------
|
| 18 |
+
st.set_page_config(
|
| 19 |
+
page_title="Analytics Validation Demo",
|
| 20 |
+
page_icon="📊",
|
| 21 |
+
layout="wide"
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
# ---------------------------------------------------------------------------
|
| 25 |
+
# Data Loading Helper
|
| 26 |
+
# ---------------------------------------------------------------------------
|
| 27 |
+
@st.cache_data
|
| 28 |
+
def load_data_cached(filepath):
|
| 29 |
+
# We copy the load_data logic here or import it if compatible
|
| 30 |
+
# Importing is better to keep logic in one place
|
| 31 |
+
from demo import load_data
|
| 32 |
+
return load_data(filepath)
|
| 33 |
+
|
| 34 |
+
# ---------------------------------------------------------------------------
|
| 35 |
+
# UI Helpers
|
| 36 |
+
# ---------------------------------------------------------------------------
|
| 37 |
+
def display_issues(issues):
|
| 38 |
+
"""Render list of issues as Streamlit alerts."""
|
| 39 |
+
if not issues:
|
| 40 |
+
st.success("✅ No issues detected. Data appears clean.")
|
| 41 |
+
return
|
| 42 |
+
|
| 43 |
+
st.warning(f"⚠️ Found {len(issues)} issues")
|
| 44 |
+
|
| 45 |
+
for issue in issues:
|
| 46 |
+
severity_icon = "🔴" if issue["severity"] == "ERROR" else "⚠️"
|
| 47 |
+
with st.expander(f"{severity_icon} [{issue['severity']}] {issue['type']} in {issue.get('column', 'General')}"):
|
| 48 |
+
st.write(f"**Detail:** {issue['detail']}")
|
| 49 |
+
if issue.get("dates"):
|
| 50 |
+
st.write(f"**Affected Dates:** {', '.join(issue['dates'])}")
|
| 51 |
+
|
| 52 |
+
def display_metrics(stats):
|
| 53 |
+
"""Render Key Metrics in columns."""
|
| 54 |
+
st.subheader("Key Metrics")
|
| 55 |
+
col1, col2 = st.columns(2)
|
| 56 |
+
|
| 57 |
+
with col1:
|
| 58 |
+
rev = stats["revenue"]
|
| 59 |
+
st.metric("Total Revenue", f"${rev['total']:,.2f}")
|
| 60 |
+
st.caption(f"Mean: ${rev['mean']:,.2f} | Missing: {rev['missing_count']}")
|
| 61 |
+
|
| 62 |
+
with col2:
|
| 63 |
+
ord_ = stats["orders"]
|
| 64 |
+
st.metric("Total Orders", f"{int(ord_['total']):,}")
|
| 65 |
+
st.caption(f"Mean: {ord_['mean']:,.0f} | Missing: {ord_['missing_count']}")
|
| 66 |
+
|
| 67 |
+
st.divider()
|
| 68 |
+
|
| 69 |
+
# ---------------------------------------------------------------------------
|
| 70 |
+
# Main App Layout
|
| 71 |
+
# ---------------------------------------------------------------------------
|
| 72 |
+
def main():
|
| 73 |
+
st.title("📊 Analytics Validation Engine")
|
| 74 |
+
st.markdown("""
|
| 75 |
+
This demo validates daily business metrics for anomalies, missing data, and consistency errors.
|
| 76 |
+
It uses a deterministic rule engine and an optional local LLM for narration.
|
| 77 |
+
""")
|
| 78 |
+
|
| 79 |
+
# Sidebar parameters
|
| 80 |
+
st.sidebar.header("Configuration")
|
| 81 |
+
uploaded_file = st.sidebar.file_uploader("Upload CSV", type=["csv"])
|
| 82 |
+
|
| 83 |
+
# Check for default data if no upload
|
| 84 |
+
data_path = "data.csv"
|
| 85 |
+
if uploaded_file is not None:
|
| 86 |
+
data_path = uploaded_file
|
| 87 |
+
elif not Path(data_path).exists():
|
| 88 |
+
st.error("❌ `data.csv` not found and no file was uploaded.")
|
| 89 |
+
st.info("Please upload a CSV file in the sidebar or add `data.csv` to your Space files.")
|
| 90 |
+
st.stop()
|
| 91 |
+
|
| 92 |
+
# Load Data
|
| 93 |
+
try:
|
| 94 |
+
if uploaded_file:
|
| 95 |
+
df = pd.read_csv(uploaded_file, parse_dates=["date"])
|
| 96 |
+
if not pd.api.types.is_datetime64_any_dtype(df["date"]):
|
| 97 |
+
df["date"] = pd.to_datetime(df["date"])
|
| 98 |
+
df = df.sort_values("date").reset_index(drop=True)
|
| 99 |
+
else:
|
| 100 |
+
df = load_data_cached(data_path)
|
| 101 |
+
|
| 102 |
+
st.sidebar.success(f"Loaded {len(df)} rows")
|
| 103 |
+
|
| 104 |
+
except Exception as e:
|
| 105 |
+
st.error(f"Error loading data: {e}")
|
| 106 |
+
st.stop()
|
| 107 |
+
|
| 108 |
+
# Run Analysis
|
| 109 |
+
with st.spinner("Running validation rules..."):
|
| 110 |
+
results = run_checks(df)
|
| 111 |
+
|
| 112 |
+
# Display Findings
|
| 113 |
+
|
| 114 |
+
# 1. Executive Summary
|
| 115 |
+
st.header("Executive Summary")
|
| 116 |
+
with st.spinner("Generating summary..."):
|
| 117 |
+
summary = generate_summary(results)
|
| 118 |
+
st.info(summary)
|
| 119 |
+
|
| 120 |
+
# 2. Detailed Issues
|
| 121 |
+
st.header("Detected Issues")
|
| 122 |
+
display_issues(results["issues"])
|
| 123 |
+
|
| 124 |
+
# 3. Data Overview
|
| 125 |
+
st.header("Data Overview")
|
| 126 |
+
display_metrics(results["stats"])
|
| 127 |
+
|
| 128 |
+
with st.expander("View Raw Data"):
|
| 129 |
+
st.dataframe(df)
|
| 130 |
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|