VAH6002's picture
Upload app.py
68a4e70 verified
Raw History Blame Contribute Delete
12.4 kB
"""
MCP AI Data Scientist - Hugging Face Spaces Demo
Standalone demo version for Hugging Face Spaces deployment.
"""
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime
import json
# Configure Streamlit page
st.set_page_config(
page_title="MCP AI Data Scientist",
page_icon="πŸ€–",
layout="wide",
initial_sidebar_state="expanded"
)
def main():
"""Main demo application."""
# Header
st.title("πŸ€– MCP AI Data Scientist")
st.markdown("*Intelligent data analysis powered by AI agents - Demo Version*")
# Info banner
st.info("🌟 This is a demo version running on Hugging Face Spaces. For the full interactive experience with real-time AI analysis, please visit our [GitHub repository](https://github.com/your-repo/mcp-ai-data-scientist).")
# Sidebar
with st.sidebar:
st.header("πŸŽ›οΈ Demo Controls")
demo_mode = st.selectbox(
"Select Demo",
["Platform Overview", "Sample Analysis", "Architecture", "Features"]
)
st.markdown("---")
st.markdown("### πŸ”— Links")
st.markdown("- [GitHub Repository](https://github.com/your-repo/mcp-ai-data-scientist)")
st.markdown("- [Documentation](https://github.com/your-repo/mcp-ai-data-scientist/blob/main/README.md)")
st.markdown("- [Setup Guide](https://github.com/your-repo/mcp-ai-data-scientist/blob/main/docs/setup.md)")
# Main content
if demo_mode == "Platform Overview":
render_overview()
elif demo_mode == "Sample Analysis":
render_sample_analysis()
elif demo_mode == "Architecture":
render_architecture()
elif demo_mode == "Features":
render_features()
def render_overview():
"""Render platform overview."""
st.header("πŸ“Š Platform Overview")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("AI Agents", "6", "Specialized")
with col2:
st.metric("Analysis Steps", "50+", "Automated")
with col3:
st.metric("File Formats", "4", "Supported")
st.markdown("---")
st.subheader("🎯 What is MCP AI Data Scientist?")
st.markdown("""
MCP AI Data Scientist is an intelligent data analysis platform that uses multiple specialized AI agents
working together through the Model Context Protocol (MCP) to provide comprehensive data insights.
**Key Benefits:**
- **Automated Analysis**: No manual coding required
- **Expert-Level Insights**: AI agents with specialized domain knowledge
- **Real-Time Processing**: Live progress updates and streaming results
- **Business-Focused**: Actionable recommendations and reports
- **Secure & Scalable**: Enterprise-ready architecture
""")
st.subheader("πŸ”„ How It Works")
steps = [
{"step": 1, "title": "Upload Data", "desc": "CSV, Excel, JSON, or Parquet files"},
{"step": 2, "title": "Provide Context", "desc": "Describe your business objectives"},
{"step": 3, "title": "AI Processing", "desc": "6 specialized agents analyze your data"},
{"step": 4, "title": "Get Insights", "desc": "Receive reports and recommendations"}
]
for i, step_info in enumerate(steps):
col1, col2 = st.columns([1, 4])
with col1:
st.markdown(f"### {step_info['step']}")
with col2:
st.markdown(f"**{step_info['title']}**")
st.markdown(step_info['desc'])
if i < len(steps) - 1:
st.markdown("↓")
def render_sample_analysis():
"""Render sample analysis demo."""
st.header("πŸ“ˆ Sample Analysis Demo")
# Generate sample data
np.random.seed(42)
dates = pd.date_range('2023-01-01', periods=365, freq='D')
sample_data = pd.DataFrame({
'date': dates,
'sales': np.random.normal(1000, 200, 365) + np.sin(np.arange(365) * 2 * np.pi / 365) * 100,
'marketing_spend': np.random.normal(500, 100, 365),
'customer_satisfaction': np.random.normal(4.2, 0.5, 365),
'region': np.random.choice(['North', 'South', 'East', 'West'], 365),
'product_category': np.random.choice(['Electronics', 'Clothing', 'Home', 'Sports'], 365)
})
st.subheader("πŸ“Š Sample Dataset")
st.dataframe(sample_data.head(10))
st.subheader("πŸ” AI-Generated Insights")
# Simulated AI insights
insights = [
{
"agent": "Data Cleaning Agent",
"finding": "Dataset is 98% complete with minimal missing values",
"action": "Applied intelligent imputation for 2% missing customer satisfaction scores"
},
{
"agent": "Hypothesis Testing Agent",
"finding": "Strong correlation (r=0.73) between marketing spend and sales",
"action": "Recommended increasing marketing budget by 15% for optimal ROI"
},
{
"agent": "Feature Engineering Agent",
"finding": "Seasonal patterns detected with 23% higher sales in Q4",
"action": "Created seasonal features and holiday indicators"
},
{
"agent": "Model Training Agent",
"finding": "XGBoost model achieved 89% accuracy in sales prediction",
"action": "Deployed ensemble model with confidence intervals"
}
]
for insight in insights:
with st.expander(f"πŸ€– {insight['agent']}"):
st.markdown(f"**Finding:** {insight['finding']}")
st.markdown(f"**Action:** {insight['action']}")
# Sample visualizations
st.subheader("πŸ“Š Generated Visualizations")
col1, col2 = st.columns(2)
with col1:
fig1 = px.line(sample_data, x='date', y='sales', title='Sales Trend Over Time')
st.plotly_chart(fig1, use_container_width=True)
with col2:
fig2 = px.scatter(sample_data, x='marketing_spend', y='sales',
color='region', title='Marketing Spend vs Sales by Region')
st.plotly_chart(fig2, use_container_width=True)
# Business recommendations
st.subheader("πŸ’Ό Business Recommendations")
recommendations = [
"Increase marketing spend by 15% to maximize ROI based on correlation analysis",
"Focus promotional campaigns in Q4 to leverage seasonal sales patterns",
"Implement customer satisfaction monitoring in the South region (lowest scores)",
"Consider expanding Electronics category (highest profit margins detected)"
]
for i, rec in enumerate(recommendations, 1):
st.markdown(f"{i}. {rec}")
def render_architecture():
"""Render system architecture."""
st.header("πŸ—οΈ System Architecture")
st.markdown("""
The MCP AI Data Scientist uses a distributed microservices architecture with specialized AI agents:
""")
# Architecture diagram (text-based)
st.subheader("πŸ”„ Data Flow")
architecture_steps = [
{"component": "Streamlit UI", "description": "User interface for file upload and configuration"},
{"component": "FastAPI Orchestrator", "description": "Central coordinator powered by Google Gemini"},
{"component": "Data Cleaning Agent", "description": "Validates, cleans, and prepares data"},
{"component": "Hypothesis Testing Agent", "description": "Generates and tests statistical hypotheses"},
{"component": "Preprocessing Agent", "description": "Feature mapping and data transformation"},
{"component": "Feature Engineering Agent", "description": "Creates new features and encodings"},
{"component": "Model Training Agent", "description": "Trains and evaluates ML models"},
{"component": "Action Generation Agent", "description": "Creates business reports and recommendations"}
]
for step in architecture_steps:
st.markdown(f"**{step['component']}**: {step['description']}")
st.markdown("↓")
st.markdown("**Results & Reports**: Delivered back to user interface")
st.subheader("πŸ”§ Technology Stack")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("**Frontend**")
st.markdown("- Streamlit")
st.markdown("- Plotly")
st.markdown("- Real-time SSE")
with col2:
st.markdown("**Backend**")
st.markdown("- FastAPI")
st.markdown("- MCP Protocol")
st.markdown("- Google Gemini")
with col3:
st.markdown("**Data & ML**")
st.markdown("- Pandas/NumPy")
st.markdown("- Scikit-learn")
st.markdown("- XGBoost")
def render_features():
"""Render detailed features."""
st.header("✨ Platform Features")
features = [
{
"title": "πŸ€– Multi-Agent AI System",
"description": "Six specialized AI agents work together, each expert in their domain",
"details": [
"Data cleaning and validation",
"Statistical hypothesis generation",
"Feature engineering and selection",
"Model training and evaluation",
"Business insight generation",
"Report and recommendation creation"
]
},
{
"title": "πŸ“Š Comprehensive Analysis",
"description": "End-to-end data science pipeline automation",
"details": [
"Automated data quality assessment",
"Statistical significance testing",
"Feature importance analysis",
"Model performance evaluation",
"Business impact quantification",
"Actionable recommendation generation"
]
},
{
"title": "πŸ”„ Real-Time Processing",
"description": "Live progress updates and streaming results",
"details": [
"Server-sent events for live updates",
"Progress tracking per agent",
"Intermediate result streaming",
"Error handling and recovery",
"Performance monitoring",
"Resource usage optimization"
]
},
{
"title": "πŸ”’ Enterprise Security",
"description": "Secure, scalable, and compliant architecture",
"details": [
"User authentication and authorization",
"Data isolation and privacy",
"Audit logging and monitoring",
"Error tracking and alerting",
"Performance optimization",
"Scalable microservices design"
]
}
]
for feature in features:
with st.expander(feature["title"]):
st.markdown(feature["description"])
st.markdown("**Capabilities:**")
for detail in feature["details"]:
st.markdown(f"- {detail}")
st.subheader("πŸš€ Getting Started")
st.markdown("""
Ready to try the full platform? Here's how to get started:
1. **Clone the Repository**
```bash
git clone https://github.com/your-repo/mcp-ai-data-scientist
cd mcp-ai-data-scientist
```
2. **Install Dependencies**
```bash
pip install -r requirements.txt
```
3. **Configure Environment**
```bash
cp .env.example .env
# Edit .env with your API keys
```
4. **Start Services**
```bash
python -m orchestrator.main # Start orchestrator
streamlit run streamlit_app/main.py # Start UI
```
5. **Upload Data & Analyze**
- Open http://localhost:8501
- Upload your dataset
- Provide business context
- Watch AI agents work their magic!
""")
if __name__ == "__main__":
main()