data-science-interactive-apps
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseInteractive Web Apps
交互式Web应用
Use this skill for building lightweight web interfaces to ML models, data visualizations, and analytical tools.
使用该技能为机器学习模型、数据可视化工具和分析工具构建轻量级Web界面。
When to use this skill
何时使用该技能
- ML model demos — let stakeholders interact with predictions
- Data exploration tools — filter, visualize, drill down
- Internal dashboards — monitoring, reporting, self-service analytics
- Prototyping — validate UX before full engineering investment
- A/B test interfaces — experiment with different presentations
- 机器学习模型演示 — 让相关方可以与预测结果交互
- 数据探索工具 — 筛选、可视化、深入分析
- 内部仪表盘 — 监控、报告、自助式分析
- 原型开发 — 在投入完整工程资源前验证用户体验(UX)
- 界面A/B测试 — 尝试不同的展示方式
Tool selection guide
工具选择指南
| Tool | Best For | Strengths |
|---|---|---|
| Streamlit | Rapid ML demos, data apps | Simplest API, large community, great for Python devs |
| Panel | Complex dashboards, reactive layouts | Jupyter integration, flexible layout, HoloViz ecosystem |
| Gradio | ML model sharing, Hugging Face | Built-in sharing, model introspection, API generation |
| Dash (Plotly) | Production dashboards | Fine-grained control, React backend |
| NiceGUI | Desktop + web apps | Native-like UI, async support |
| 工具 | 适用场景 | 优势 |
|---|---|---|
| Streamlit | 快速机器学习模型演示、数据应用 | 最简单的API、庞大的社区、非常适合Python开发者 |
| Panel | 复杂仪表盘、响应式布局 | Jupyter集成、灵活的布局、HoloViz生态系统 |
| Gradio | 机器学习模型分享、Hugging Face | 内置分享功能、模型自省、API生成 |
| Dash (Plotly) | 生产级仪表盘 | 细粒度控制、React后端 |
| NiceGUI | 桌面+Web应用 | 类原生UI、异步支持 |
Quick start: Streamlit
快速入门:Streamlit
python
undefinedpython
undefinedapp.py
app.py
import streamlit as st
import pandas as pd
import plotly.express as px
st.title("Sales Dashboard")
import streamlit as st
import pandas as pd
import plotly.express as px
st.title("Sales Dashboard")
Sidebar controls
Sidebar controls
region = st.sidebar.selectbox("Region", ["All", "North", "South", "East", "West"])
region = st.sidebar.selectbox("Region", ["All", "North", "South", "East", "West"])
Load and filter data
Load and filter data
df = pd.read_parquet("sales.parquet")
if region != "All":
df = df[df['region'] == region]
df = pd.read_parquet("sales.parquet")
if region != "All":
df = df[df['region'] == region]
Display metrics
Display metrics
col1, col2, col3 = st.columns(3)
col1.metric("Total Sales", f"${df['sales'].sum():,.0f}")
col2.metric("Orders", len(df))
col3.metric("Avg Order", f"${df['sales'].mean():.2f}")
col1, col2, col3 = st.columns(3)
col1.metric("Total Sales", f"${df['sales'].sum():,.0f}")
col2.metric("Orders", len(df))
col3.metric("Avg Order", f"${df['sales'].mean():.2f}")
Visualization
Visualization
fig = px.line(df.groupby('date')['sales'].sum().reset_index(), x='date', y='sales')
st.plotly_chart(fig, use_container_width=True)
fig = px.line(df.groupby('date')['sales'].sum().reset_index(), x='date', y='sales')
st.plotly_chart(fig, use_container_width=True)
Data table
Data table
st.dataframe(df.head(100))
Run: `streamlit run app.py`st.dataframe(df.head(100))
运行:`streamlit run app.py`Quick start: Gradio
快速入门:Gradio
python
import gradio as gr
from transformers import pipelinepython
import gradio as gr
from transformers import pipelineLoad model (example: sentiment analysis)
Load model (example: sentiment analysis)
classifier = pipeline("sentiment-analysis")
def predict(text):
result = classifier(text)[0]
return result['label'], result['score']
interface = gr.Interface(
fn=predict,
inputs=gr.Textbox(lines=2, placeholder="Enter text..."),
outputs=[gr.Label(label="Sentiment"), gr.Number(label="Confidence")],
title="Sentiment Analysis",
description="Enter text to analyze sentiment"
)
interface.launch()
undefinedclassifier = pipeline("sentiment-analysis")
def predict(text):
result = classifier(text)[0]
return result['label'], result['score']
interface = gr.Interface(
fn=predict,
inputs=gr.Textbox(lines=2, placeholder="Enter text..."),
outputs=[gr.Label(label="Sentiment"), gr.Number(label="Confidence")],
title="Sentiment Analysis",
description="Enter text to analyze sentiment"
)
interface.launch()
undefinedQuick start: Panel
快速入门:Panel
python
import panel as pn
import hvplot.pandas
import pandas as pd
pn.extension()
df = pd.read_parquet("data.parquet")python
import panel as pn
import hvplot.pandas
import pandas as pd
pn.extension()
df = pd.read_parquet("data.parquet")Widgets
Widgets
region = pn.widgets.Select(name='Region', options=['All'] + df['region'].unique().tolist())
metric = pn.widgets.RadioBoxGroup(name='Metric', options=['sales', 'profit', 'units'])
region = pn.widgets.Select(name='Region', options=['All'] + df['region'].unique().tolist())
metric = pn.widgets.RadioBoxGroup(name='Metric', options=['sales', 'profit', 'units'])
Reactive function
Reactive function
@pn.depends(region, metric)
def plot(region, metric):
data = df if region == 'All' else df[df['region'] == region]
return data.hvplot.line(x='date', y=metric, title=f'{metric.title()} by Date')
@pn.depends(region, metric)
def plot(region, metric):
data = df if region == 'All' else df[df['region'] == region]
return data.hvplot.line(x='date', y=metric, title=f'{metric.title()} by Date')
Layout
Layout
app = pn.Column(
"# Sales Dashboard",
pn.Row(region, metric),
plot
)
app.servable()
Run: `panel serve app.py`app = pn.Column(
"# Sales Dashboard",
pn.Row(region, metric),
plot
)
app.servable()
运行:`panel serve app.py`Core design principles
核心设计原则
1) Start simple, iterate
1) 从简开始,逐步迭代
- MVP with one widget + one visualization
- Add complexity only when needed
- Test with real users early
- 最小可行产品(MVP):一个组件 + 一个可视化图表
- 仅在需要时增加复杂度
- 尽早与真实用户测试
2) Optimize for the audience
2) 针对受众优化
| Audience | Approach |
|---|---|
| Executives | Key metrics, simple filters, clean layout |
| Data scientists | Raw data access, parameter tuning, debug info |
| Operations | Refresh buttons, alerts, mobile-friendly |
| 受众 | 方法 |
|---|---|
| 管理人员 | 关键指标、简单筛选、简洁布局 |
| 数据科学家 | 原始数据访问、参数调优、调试信息 |
| 运营人员 | 刷新按钮、告警、移动端友好 |
3) Handle state carefully
3) 谨慎处理状态
python
undefinedpython
undefinedStreamlit: use session_state for persistence
Streamlit: use session_state for persistence
if 'counter' not in st.session_state:
st.session_state.counter = 0
st.session_state.counter += 1
undefinedif 'counter' not in st.session_state:
st.session_state.counter = 0
st.session_state.counter += 1
undefined4) Never expose secrets
4) 绝不暴露敏感信息
python
undefinedpython
undefined✅ Use st.secrets (Streamlit Cloud) or environment variables
✅ Use st.secrets (Streamlit Cloud) or environment variables
api_key = st.secrets["openai_api_key"]
api_key = st.secrets["openai_api_key"]
❌ Never hardcode
❌ Never hardcode
api_key = "sk-..."
undefinedapi_key = "sk-..."
undefinedDeployment options
部署选项
| Platform | Best For | Notes |
|---|---|---|
| Streamlit Community Cloud | Free sharing | GitHub integration, public by default |
| Hugging Face Spaces | ML demos | Free tier, Gradio/Streamlit/Docker |
| Panel + Cloud Run/Heroku | Custom hosting | More control, requires setup |
| Docker + any cloud | Enterprise | Scalable, private, more work |
| 平台 | 适用场景 | 说明 |
|---|---|---|
| Streamlit Community Cloud | 免费分享 | GitHub集成,默认公开 |
| Hugging Face Spaces | 机器学习模型演示 | 免费层级,支持Gradio/Streamlit/Docker |
| Panel + Cloud Run/Heroku | 自定义托管 | 更多控制权,需要配置 |
| Docker + 任意云服务 | 企业级部署 | 可扩展、私有、配置工作量大 |
Common anti-patterns
常见反模式
- ❌ Loading data on every interaction (use caching)
- ❌ Blocking the UI with long computations
- ❌ No error handling for edge cases
- ❌ Hardcoded file paths or credentials
- ❌ Too many widgets (cognitive overload)
- ❌ No mobile consideration
- ❌ 每次交互都加载数据(使用缓存)
- ❌ 长时间计算阻塞UI
- ❌ 未处理边缘情况的错误
- ❌ 硬编码文件路径或凭证
- ❌ 组件过多(认知过载)
- ❌ 未考虑移动端适配
Progressive disclosure
进阶资源
- — Caching, custom components, multipage apps
references/streamlit-advanced.md - — Linked brushing, geographic visualizations
references/panel-holoviz.md - — Model sharing, API generation, Spaces deployment
references/gradio-ml.md - — Automated testing for interactive apps
references/app-testing.md - — Docker, authentication, scaling
references/production-deployment.md
- — 缓存、自定义组件、多页面应用
references/streamlit-advanced.md - — 联动刷选、地理可视化
references/panel-holoviz.md - — 模型分享、API生成、Spaces部署
references/gradio-ml.md - — 交互式应用的自动化测试
references/app-testing.md - — Docker、身份验证、扩容
references/production-deployment.md
Related skills
相关技能
- — Prototype in notebooks, convert to apps
@data-science-notebooks - — Present model metrics in apps
@data-science-model-evaluation - — Connect apps to production pipelines
@data-engineering-orchestration
- — 在笔记本中原型开发,再转换为应用
@data-science-notebooks - — 在应用中展示模型指标
@data-science-model-evaluation - — 将应用连接到生产流水线
@data-engineering-orchestration