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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(
|
| 20 |
+
page_title="RICA - AI Revenue Intelligence",
|
| 21 |
+
page_icon="π€",
|
| 22 |
+
layout="wide",
|
| 23 |
+
initial_sidebar_state="expanded"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# Custom CSS
|
| 27 |
+
st.markdown("""
|
| 28 |
+
<style>
|
| 29 |
+
.main-header {
|
| 30 |
+
font-size: 2.5rem;
|
| 31 |
+
font-weight: bold;
|
| 32 |
+
text-align: center;
|
| 33 |
+
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
|
| 34 |
+
-webkit-background-clip: text;
|
| 35 |
+
-webkit-text-fill-color: transparent;
|
| 36 |
+
margin-bottom: 1rem;
|
| 37 |
+
}
|
| 38 |
+
.stAlert > div {
|
| 39 |
+
padding: 0.5rem;
|
| 40 |
+
}
|
| 41 |
+
.metric-container {
|
| 42 |
+
background: #f0f2f6;
|
| 43 |
+
padding: 1rem;
|
| 44 |
+
border-radius: 0.5rem;
|
| 45 |
+
margin: 0.5rem 0;
|
| 46 |
+
}
|
| 47 |
+
</style>
|
| 48 |
+
""", unsafe_allow_html=True)
|
| 49 |
+
|
| 50 |
+
# Header
|
| 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()
|
| 78 |
+
|
| 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)
|
| 132 |
+
|
| 133 |
+
with col1:
|
| 134 |
+
st.markdown("""
|
| 135 |
+
## π Capabilities
|
| 136 |
+
|
| 137 |
+
**RICA** combines machine learning with autonomous AI to deliver:
|
| 138 |
+
|
| 139 |
+
- π― **Churn Prediction**: ML models identify at-risk customers
|
| 140 |
+
- π **Real-time Analysis**: Direct SAP data integration
|
| 141 |
+
- π€ **Autonomous Insights**: LLM-powered recommendations
|
| 142 |
+
- π **Business Impact**: Actionable revenue optimization
|
| 143 |
+
""")
|
| 144 |
+
|
| 145 |
+
with col2:
|
| 146 |
+
st.markdown("""
|
| 147 |
+
## ποΈ Architecture
|
| 148 |
+
|
| 149 |
+
- **Data Source**: Real SAP/SALT dataset
|
| 150 |
+
- **ML Engine**: Scikit-learn Random Forest
|
| 151 |
+
- **Agent Framework**: smolagents + OpenAI
|
| 152 |
+
- **Analytics**: DuckDB high-performance processing
|
| 153 |
+
- **UI**: Streamlit interactive interface
|
| 154 |
+
""")
|
| 155 |
+
|
| 156 |
+
# Demo metrics
|
| 157 |
+
st.markdown("## π Sample Analytics Preview")
|
| 158 |
+
|
| 159 |
+
col1, col2, col3, col4 = st.columns(4)
|
| 160 |
+
|
| 161 |
+
with col1:
|
| 162 |
+
st.metric("Customers", "2,847", delta="12%")
|
| 163 |
+
with col2:
|
| 164 |
+
st.metric("Churn Risk", "23 customers", delta="-8", delta_color="inverse")
|
| 165 |
+
with col3:
|
| 166 |
+
st.metric("Revenue at Risk", "$1.2M", delta="15%")
|
| 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)")
|
| 174 |
+
|
| 175 |
+
st.markdown("## π Training Process")
|
| 176 |
+
st.markdown("""
|
| 177 |
+
1. **Load SAP Data**: Customer and sales data from Hugging Face Hub
|
| 178 |
+
2. **Feature Engineering**: RFM analysis and behavioral patterns
|
| 179 |
+
3. **Model Training**: Random Forest classifier with cross-validation
|
| 180 |
+
4. **Performance Validation**: Accuracy testing and metrics calculation
|
| 181 |
+
5. **Model Persistence**: Save for future predictions
|
| 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("---")
|
| 250 |
+
st.markdown("π€ **RICA Agent** | ML + AI for Business Intelligence | Deployed on π€ Hugging Face Spaces")
|