intrainmode commited on
Commit
86b54f8
Β·
verified Β·
1 Parent(s): c4edcc0

Update src/streamlit-app.py with actual code

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +128 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,130 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
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
+ from sentence_transformers import SentenceTransformer
3
+ import chromadb
4
+ import time
5
 
6
+ # 1. System Configurations
7
+ st.set_page_config(page_title="InsightStream AI", page_icon="⚑", layout="wide")
8
+
9
+ # Custom CSS to force a high-end dark theme aesthetic
10
+ st.markdown("""
11
+ <style>
12
+ .main .block-container {padding-top: 2rem;}
13
+ .metric-card {background-color: #1e222b; padding: 15px; border-radius: 8px; border: 1px solid #2d3139;}
14
+ </style>
15
+ """, unsafe_allow_html=True)
16
+
17
+ # 2. Optimized Resource Initializations
18
+ @st.cache_resource
19
+ def load_analytics_engine():
20
+ return SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
21
+
22
+ @st.cache_resource
23
+ def init_vector_vault():
24
+ client = chromadb.Client()
25
+ return client.get_or_create_collection(
26
+ name="stream_intelligence_vault",
27
+ metadata={"hnsw:space": "cosine"}
28
+ )
29
+
30
+ engine = load_analytics_engine()
31
+ vault = init_vector_vault()
32
+
33
+ # Curated high-value corporate intel data
34
+ FEED_PRESETS = [
35
+ "Market Alert: High structural inflation signals aggressive interest rate hikes next quarter.",
36
+ "R&D Update: Quantum entanglement framework successfully processing multi-dimensional data arrays.",
37
+ "Operations Briefing: Deep learning algorithms integrated into production pipelines to automate code audits.",
38
+ "Infrastructure Notice: Storage systems transitioning entirely to vectorized database mathematical modeling.",
39
+ "Wellness Policy: New corporate initiatives mandate daily physical breaks and bio-balanced nutrition tracking.",
40
+ "Logistics Report: Autonomous supply chain mechanisms deployed across regional fulfillment hubs.",
41
+ "Biotech News: Synthetic neural networks showing unprecedented mastery over biochemical sequencing tasks."
42
+ ]
43
+
44
+ # 3. Main Dashboard Header Layout
45
+ t1, t2 = st.columns([7, 3])
46
+ with t1:
47
+ st.title("⚑ INSIGHTSTREAM")
48
+ st.markdown("### *Real-Time Neural Text Processing & Stream Auditing Hub*")
49
+ with t2:
50
+ st.write("")
51
+ st.write("")
52
+ # Dynamic KPI metric cards
53
+ st.markdown(
54
+ f'<div class="metric-card">'
55
+ f'πŸ“Ά <b>SYSTEM STATUS:</b> <span style="color:#00ffcc;">ACTIVE</span><br>'
56
+ f'πŸ“¦ <b>INDEXED DATA STREAMS:</b> {vault.count()}'
57
+ f'</div>',
58
+ unsafe_allow_html=True
59
+ )
60
+
61
+ st.divider()
62
+
63
+ # 4. Tabbed Workplace Navigation (Eliminating the traditional sidebar)
64
+ tab_monitor, tab_ingest = st.tabs(["πŸ“Š INTELLIGENCE STREAM MONITOR", "πŸ“₯ DATA INGESTION ENGINE"])
65
+
66
+ # --- TAB 1: SEARCH & MONITOR ---
67
+ with tab_monitor:
68
+ if vault.count() == 0:
69
+ st.error("🚨 Neural Index Empty: No data feeds detected in the pipeline.")
70
+ if st.button("⚑ Trigger Auto-Seed Pipeline"):
71
+ with st.spinner("Processing framework initialization vectors..."):
72
+ embeddings = engine.encode(FEED_PRESETS).tolist()
73
+ ids = [f"feed_id_{i}" for i in range(len(FEED_PRESETS))]
74
+ vault.add(embeddings=embeddings, documents=FEED_PRESETS, ids=ids)
75
+ st.success("System auto-seeded successfully!")
76
+ st.rerun()
77
+ else:
78
+ # Search controls integrated horizontally into the main screen layout
79
+ ctrl1, ctrl2 = st.columns([3, 1])
80
+ with ctrl1:
81
+ intel_query = st.text_input("🎯 Filter streams via conceptual query:", placeholder="Type a concept, e.g., corporate financial stress or machine learning automation...")
82
+ with ctrl2:
83
+ max_nodes = st.select_slider("Max Nodes to Map:", options=[1, 2, 3, 4, 5], value=3)
84
+
85
+ if intel_query:
86
+ with st.spinner("Executing high-dimensional vector search..."):
87
+ t_start = time.time()
88
+ query_vec = engine.encode([intel_query]).tolist()
89
+ payload = vault.query(query_embeddings=query_vec, n_results=max_nodes)
90
+ latency = (time.time() - t_start) * 1000
91
+
92
+ st.markdown(f"##### πŸ›°οΈ Stream Analysis Complete (`{latency:.2f}ms latency`)")
93
+
94
+ if payload and payload['documents']:
95
+ feeds = payload['documents'][0]
96
+ metrics = payload['distances'][0]
97
+ node_ids = payload['ids'][0]
98
+
99
+ # Render clean metric-driven grid modules
100
+ for i in range(len(feeds)):
101
+ confidence = (1 - metrics[i]) * 100
102
+
103
+ with st.expander(f"πŸ”΄ STREAM NODE {node_ids[i]} β€” Match Confidence: {confidence:.2f}%", expanded=True):
104
+ st.write(f"**Data Payload:**")
105
+ st.code(feeds[i], language="markdown")
106
+ else:
107
+ st.warning("No nodes matched the conceptual threshold.")
108
+
109
+ # --- TAB 2: DATA INGESTION ---
110
+ with tab_ingest:
111
+ st.subheader("πŸ“₯ Raw Text Ingestion Port")
112
+ st.markdown("Manually inject unstructured text blocks into the vector analytics cluster.")
113
+
114
+ stream_payload = st.text_area("Raw Document Payload:", placeholder="Paste text logs, reports, or data streams here...")
115
+
116
+ if st.button("πŸš€ Commit Payload to Cluster"):
117
+ if stream_payload.strip():
118
+ with st.spinner("Vectorizing input stream..."):
119
+ assigned_id = f"feed_user_{vault.count() + 1}"
120
+ payload_vec = engine.encode([stream_payload]).tolist()
121
+
122
+ vault.add(
123
+ embeddings=payload_vec,
124
+ documents=[stream_payload],
125
+ ids=[assigned_id]
126
+ )
127
+ st.success(f"Success: Nodes updated. Assigned ID: {assigned_id}")
128
+ st.rerun()
129
+ else:
130
+ st.error("Aborted: Ingestion payload cannot be empty.")