PD03 commited on
Commit
e7df474
Β·
verified Β·
1 Parent(s): 1b9cb80

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -105
app.py CHANGED
@@ -1,19 +1,38 @@
1
  """
2
- RICA Agent - Hugging Face Spaces Compatible Version
3
  """
4
 
5
  import streamlit as st
6
  import os
7
- from pathlib import Path
8
  import sys
 
 
9
 
10
  # Add project root to path for imports
11
  if str(Path(__file__).parent) not in sys.path:
12
  sys.path.append(str(Path(__file__).parent))
13
 
14
  # Import modules
15
- from utils.model_trainer import EmbeddedChurnTrainer
16
- from agent.rica_agent import create_rica_agent_hf, execute_rica_analysis_hf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  # Page configuration
19
  st.set_page_config(
@@ -51,27 +70,31 @@ st.markdown("""
51
  st.markdown('<h1 class="main-header">πŸ€– RICA - AI Revenue Intelligence Agent</h1>', unsafe_allow_html=True)
52
  st.markdown("### Enterprise Business Intelligence Powered by Machine Learning")
53
 
54
- # Initialize session state
55
- if 'model_trained' not in st.session_state:
56
- st.session_state.model_trained = False
57
- if 'trainer' not in st.session_state:
58
- st.session_state.trainer = EmbeddedChurnTrainer()
59
-
60
  # Sidebar configuration
61
  with st.sidebar:
62
  st.header("πŸ”§ Configuration")
63
 
64
- # API Key input
65
  openai_key = st.text_input(
66
  "OpenAI API Key",
67
- type="password",
68
- help="Required for AI agent operations"
 
 
69
  )
70
 
71
- if openai_key:
 
72
  os.environ["OPENAI_API_KEY"] = openai_key
73
- st.success("βœ… API Key configured")
 
 
 
 
 
 
74
  else:
 
75
  st.warning("⚠️ Enter API Key to enable AI features")
76
 
77
  st.divider()
@@ -79,53 +102,78 @@ with st.sidebar:
79
  # Model status
80
  st.header("🧠 ML Model Status")
81
 
82
- model_exists = st.session_state.trainer.model_exists()
 
83
 
84
  if model_exists:
85
  st.success("βœ… Model Ready")
86
- metadata = st.session_state.trainer.load_existing_metadata()
87
- if metadata:
88
- st.metric("Model Accuracy", f"{metadata['metrics'].get('test_accuracy', 0):.1%}")
89
- st.metric("Training Date", metadata['training_date'][:10])
 
 
 
 
 
90
  else:
91
  st.warning("⚠️ Model Not Trained")
 
92
 
93
- if st.button("πŸ‹οΈ Train Model Now", type="primary"):
94
- with st.spinner("Training ML model... This may take 1-2 minutes"):
95
- try:
96
- metrics = st.session_state.trainer.train_model_if_needed()
97
- if metrics:
98
- st.success("πŸŽ‰ Model trained successfully!")
99
- st.session_state.model_trained = True
100
- st.rerun()
101
- else:
102
- st.error("Training failed. Please check the logs.")
103
- except Exception as e:
104
- st.error(f"Training error: {str(e)}")
 
 
 
105
 
106
  st.divider()
107
 
108
- # Analysis configuration
109
- st.header("πŸ“Š Analysis Options")
110
-
111
- analysis_type = st.selectbox(
112
- "Select Analysis Type",
113
- ["comprehensive", "churn_focus", "quick_insights"],
114
- format_func=lambda x: {
115
- "comprehensive": "🎯 Comprehensive Review",
116
- "churn_focus": "🚨 Churn Risk Analysis",
117
- "quick_insights": "⚑ Quick Insights"
118
- }[x]
119
- )
120
-
121
- # Advanced options
122
- with st.expander("βš™οΈ Advanced Options"):
123
- risk_threshold = st.slider("Churn Risk Threshold", 0.3, 0.9, 0.6)
124
- max_customers = st.number_input("Max Customers to Analyze", 50, 500, 200)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
- # Main content
127
- if not openai_key:
128
- # Welcome screen
129
  st.info("πŸ‘ˆ Please enter your OpenAI API Key in the sidebar to begin")
130
 
131
  col1, col2 = st.columns(2)
@@ -167,7 +215,7 @@ if not openai_key:
167
  with col4:
168
  st.metric("Model Accuracy", "87.3%", delta="2.1%")
169
 
170
- elif not model_exists and not st.session_state.model_trained:
171
  # Model training required
172
  st.warning("🧠 Machine learning model needs to be trained before analysis")
173
  st.info("πŸ‘ˆ Use the 'Train Model Now' button in the sidebar (takes 1-2 minutes)")
@@ -182,68 +230,68 @@ elif not model_exists and not st.session_state.model_trained:
182
  """)
183
 
184
  else:
185
- # Main analysis interface
186
- st.markdown("## 🎯 AI Business Intelligence")
187
 
188
  # Analysis execution
189
  if st.button("πŸš€ Run RICA Analysis", type="primary", use_container_width=True):
190
- if not st.session_state.trainer.model_exists():
191
- st.error("Please train the model first using the sidebar button")
192
- else:
193
- with st.spinner("πŸ€– RICA is analyzing your business data..."):
194
- try:
195
- # Execute analysis
196
- parameters = {
197
- "risk_threshold": risk_threshold,
198
- "max_customers": max_customers
199
- }
200
-
201
- result = execute_rica_analysis_hf(analysis_type, parameters)
202
-
203
- # Display results
204
- st.success("βœ… Analysis Complete!")
 
205
 
206
- # Create tabs for results
207
- if analysis_type == "comprehensive":
208
- tab1, tab2, tab3 = st.tabs(["πŸ“Š Executive Summary", "🚨 Risk Analysis", "πŸ’‘ Recommendations"])
209
-
210
- with tab1:
211
- st.markdown("### Executive Dashboard")
212
- st.info(str(result))
213
-
214
- with tab2:
215
- st.markdown("### Customer Risk Analysis")
216
- st.write("Detailed churn risk breakdown and customer segmentation")
217
-
218
- with tab3:
219
- st.markdown("### AI Recommendations")
220
- st.write("Specific actions prioritized by business impact")
221
-
222
- else:
223
- st.markdown(f"### {analysis_type.replace('_', ' ').title()} Results")
224
  st.info(str(result))
225
 
226
- # Raw response
227
- with st.expander("πŸ” Detailed Analysis Response"):
228
- st.code(str(result), language="text")
229
 
230
- except Exception as e:
231
- st.error(f"Analysis failed: {str(e)}")
232
- st.info("Please check your API key and try again")
 
 
 
 
 
 
 
 
 
 
 
 
233
 
234
- # Quick stats
235
  if st.session_state.trainer.model_exists():
236
  st.markdown("## πŸ“ˆ Model Performance")
237
- metadata = st.session_state.trainer.load_existing_metadata()
238
- if metadata and 'metrics' in metadata:
239
- col1, col2, col3 = st.columns(3)
240
-
241
- with col1:
242
- st.metric("Model Accuracy", f"{metadata['metrics'].get('test_accuracy', 0):.1%}")
243
- with col2:
244
- st.metric("Training Samples", f"{metadata['metrics'].get('training_samples', 0):,}")
245
- with col3:
246
- st.metric("Churn Rate", f"{metadata['metrics'].get('churn_rate', 0):.1%}")
 
 
 
247
 
248
  # Footer
249
  st.markdown("---")
 
1
  """
2
+ RICA Agent - Complete Fixed Version
3
  """
4
 
5
  import streamlit as st
6
  import os
 
7
  import sys
8
+ from pathlib import Path
9
+ import json
10
 
11
  # Add project root to path for imports
12
  if str(Path(__file__).parent) not in sys.path:
13
  sys.path.append(str(Path(__file__).parent))
14
 
15
  # Import modules
16
+ try:
17
+ from utils.model_trainer import EmbeddedChurnTrainer
18
+ from agent.rica_agent import execute_rica_analysis_hf
19
+ except ImportError as e:
20
+ st.error(f"Import error: {e}")
21
+ st.stop()
22
+
23
+ # Initialize session state
24
+ if 'api_key_valid' not in st.session_state:
25
+ st.session_state.api_key_valid = False
26
+ if 'model_trained' not in st.session_state:
27
+ st.session_state.model_trained = False
28
+ if 'trainer' not in st.session_state:
29
+ st.session_state.trainer = EmbeddedChurnTrainer()
30
+ if 'analysis_type' not in st.session_state:
31
+ st.session_state.analysis_type = 'comprehensive'
32
+ if 'risk_threshold' not in st.session_state:
33
+ st.session_state.risk_threshold = 0.6
34
+ if 'max_customers' not in st.session_state:
35
+ st.session_state.max_customers = 200
36
 
37
  # Page configuration
38
  st.set_page_config(
 
70
  st.markdown('<h1 class="main-header">πŸ€– RICA - AI Revenue Intelligence Agent</h1>', unsafe_allow_html=True)
71
  st.markdown("### Enterprise Business Intelligence Powered by Machine Learning")
72
 
 
 
 
 
 
 
73
  # Sidebar configuration
74
  with st.sidebar:
75
  st.header("πŸ”§ Configuration")
76
 
77
+ # API Key input with proper validation
78
  openai_key = st.text_input(
79
  "OpenAI API Key",
80
+ type="password",
81
+ help="Required for AI agent operations",
82
+ key="openai_api_key",
83
+ placeholder="sk-..."
84
  )
85
 
86
+ # Validate and store API key
87
+ if openai_key and openai_key.startswith('sk-') and len(openai_key) > 20:
88
  os.environ["OPENAI_API_KEY"] = openai_key
89
+ st.session_state.api_key_valid = True
90
+ st.success("βœ… OpenAI API Key Configured")
91
+ st.caption("Key validated and ready for use")
92
+ elif openai_key:
93
+ st.session_state.api_key_valid = False
94
+ st.error("❌ Invalid API Key Format")
95
+ st.caption("Key should start with 'sk-' and be longer than 20 characters")
96
  else:
97
+ st.session_state.api_key_valid = False
98
  st.warning("⚠️ Enter API Key to enable AI features")
99
 
100
  st.divider()
 
102
  # Model status
103
  st.header("🧠 ML Model Status")
104
 
105
+ trainer = st.session_state.trainer
106
+ model_exists = trainer.model_exists()
107
 
108
  if model_exists:
109
  st.success("βœ… Model Ready")
110
+ try:
111
+ metadata = trainer.load_existing_metadata()
112
+ if metadata and 'metrics' in metadata:
113
+ st.metric("Model Accuracy", f"{metadata['metrics'].get('test_accuracy', 0):.1%}")
114
+ st.metric("Training Date", metadata.get('training_date', 'Unknown')[:10])
115
+ st.session_state.model_trained = True
116
+ except:
117
+ st.info("Model exists but metadata unavailable")
118
+ st.session_state.model_trained = True
119
  else:
120
  st.warning("⚠️ Model Not Trained")
121
+ st.session_state.model_trained = False
122
 
123
+ if st.button("πŸ‹οΈ Train Model Now", type="primary", key="train_model_btn"):
124
+ if not st.session_state.api_key_valid:
125
+ st.error("Please configure API key first")
126
+ else:
127
+ with st.spinner("Training ML model... This may take 1-2 minutes"):
128
+ try:
129
+ metrics = trainer.train_model_if_needed()
130
+ if metrics:
131
+ st.success("πŸŽ‰ Model trained successfully!")
132
+ st.session_state.model_trained = True
133
+ st.rerun()
134
+ else:
135
+ st.error("Training failed. Please check the logs.")
136
+ except Exception as e:
137
+ st.error(f"Training error: {str(e)}")
138
 
139
  st.divider()
140
 
141
+ # Analysis configuration (only if API key is valid)
142
+ if st.session_state.api_key_valid:
143
+ st.header("πŸ“Š Analysis Options")
144
+
145
+ analysis_type = st.selectbox(
146
+ "Select Analysis Type",
147
+ ["comprehensive", "churn_focus", "quick_insights"],
148
+ format_func=lambda x: {
149
+ "comprehensive": "🎯 Comprehensive Review",
150
+ "churn_focus": "🚨 Churn Risk Analysis",
151
+ "quick_insights": "⚑ Quick Insights"
152
+ }[x],
153
+ key="analysis_type_select"
154
+ )
155
+
156
+ st.session_state.analysis_type = analysis_type
157
+
158
+ # Advanced options
159
+ with st.expander("βš™οΈ Advanced Options"):
160
+ risk_threshold = st.slider(
161
+ "Churn Risk Threshold",
162
+ 0.3, 0.9, 0.6,
163
+ key="risk_threshold_slider"
164
+ )
165
+ max_customers = st.number_input(
166
+ "Max Customers to Analyze",
167
+ 50, 500, 200,
168
+ key="max_customers_input"
169
+ )
170
+
171
+ st.session_state.risk_threshold = risk_threshold
172
+ st.session_state.max_customers = max_customers
173
 
174
+ # Main content logic
175
+ if not st.session_state.api_key_valid:
176
+ # Show welcome screen when API key not configured
177
  st.info("πŸ‘ˆ Please enter your OpenAI API Key in the sidebar to begin")
178
 
179
  col1, col2 = st.columns(2)
 
215
  with col4:
216
  st.metric("Model Accuracy", "87.3%", delta="2.1%")
217
 
218
+ elif not st.session_state.model_trained:
219
  # Model training required
220
  st.warning("🧠 Machine learning model needs to be trained before analysis")
221
  st.info("πŸ‘ˆ Use the 'Train Model Now' button in the sidebar (takes 1-2 minutes)")
 
230
  """)
231
 
232
  else:
233
+ # Main analysis interface - API key valid and model trained
234
+ st.markdown("## 🎯 AI Business Intelligence Dashboard")
235
 
236
  # Analysis execution
237
  if st.button("πŸš€ Run RICA Analysis", type="primary", use_container_width=True):
238
+ with st.spinner("πŸ€– RICA is analyzing your business data..."):
239
+ try:
240
+ # Execute analysis
241
+ parameters = {
242
+ "risk_threshold": st.session_state.risk_threshold,
243
+ "max_customers": st.session_state.max_customers
244
+ }
245
+
246
+ result = execute_rica_analysis_hf(st.session_state.analysis_type, parameters)
247
+
248
+ # Display results
249
+ st.success("βœ… Analysis Complete!")
250
+
251
+ # Create tabs for different result views
252
+ if st.session_state.analysis_type == "comprehensive":
253
+ tab1, tab2, tab3 = st.tabs(["πŸ“Š Executive Summary", "🚨 Risk Analysis", "πŸ’‘ Recommendations"])
254
 
255
+ with tab1:
256
+ st.markdown("### Executive Dashboard")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
  st.info(str(result))
258
 
259
+ with tab2:
260
+ st.markdown("### Customer Risk Analysis")
261
+ st.write("Detailed churn risk breakdown and customer segmentation")
262
 
263
+ with tab3:
264
+ st.markdown("### AI Recommendations")
265
+ st.write("Specific actions prioritized by business impact")
266
+
267
+ else:
268
+ st.markdown(f"### {st.session_state.analysis_type.replace('_', ' ').title()} Results")
269
+ st.info(str(result))
270
+
271
+ # Raw response in expander
272
+ with st.expander("πŸ” Detailed Analysis Response"):
273
+ st.code(str(result), language="text")
274
+
275
+ except Exception as e:
276
+ st.error(f"❌ Analysis failed: {str(e)}")
277
+ st.info("Please check your API key and model status")
278
 
279
+ # Show model performance metrics
280
  if st.session_state.trainer.model_exists():
281
  st.markdown("## πŸ“ˆ Model Performance")
282
+ try:
283
+ metadata = st.session_state.trainer.load_existing_metadata()
284
+ if metadata and 'metrics' in metadata:
285
+ col1, col2, col3 = st.columns(3)
286
+
287
+ with col1:
288
+ st.metric("Model Accuracy", f"{metadata['metrics'].get('test_accuracy', 0):.1%}")
289
+ with col2:
290
+ st.metric("Training Samples", f"{metadata['metrics'].get('training_samples', 0):,}")
291
+ with col3:
292
+ st.metric("Churn Rate", f"{metadata['metrics'].get('churn_rate', 0):.1%}")
293
+ except:
294
+ st.info("Model performance metrics unavailable")
295
 
296
  # Footer
297
  st.markdown("---")