data-science-interactive-apps

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Interactive 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

工具选择指南

ToolBest ForStrengths
StreamlitRapid ML demos, data appsSimplest API, large community, great for Python devs
PanelComplex dashboards, reactive layoutsJupyter integration, flexible layout, HoloViz ecosystem
GradioML model sharing, Hugging FaceBuilt-in sharing, model introspection, API generation
Dash (Plotly)Production dashboardsFine-grained control, React backend
NiceGUIDesktop + web appsNative-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
undefined
python
undefined

app.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 pipeline
python
import gradio as gr
from transformers import pipeline

Load 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()
undefined
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()
undefined

Quick 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) 针对受众优化

AudienceApproach
ExecutivesKey metrics, simple filters, clean layout
Data scientistsRaw data access, parameter tuning, debug info
OperationsRefresh buttons, alerts, mobile-friendly
受众方法
管理人员关键指标、简单筛选、简洁布局
数据科学家原始数据访问、参数调优、调试信息
运营人员刷新按钮、告警、移动端友好

3) Handle state carefully

3) 谨慎处理状态

python
undefined
python
undefined

Streamlit: 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
undefined
if 'counter' not in st.session_state: st.session_state.counter = 0
st.session_state.counter += 1
undefined

4) Never expose secrets

4) 绝不暴露敏感信息

python
undefined
python
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-..."
undefined
api_key = "sk-..."
undefined

Deployment options

部署选项

PlatformBest ForNotes
Streamlit Community CloudFree sharingGitHub integration, public by default
Hugging Face SpacesML demosFree tier, Gradio/Streamlit/Docker
Panel + Cloud Run/HerokuCustom hostingMore control, requires setup
Docker + any cloudEnterpriseScalable, 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

进阶资源

  • references/streamlit-advanced.md
    — Caching, custom components, multipage apps
  • references/panel-holoviz.md
    — Linked brushing, geographic visualizations
  • references/gradio-ml.md
    — Model sharing, API generation, Spaces deployment
  • references/app-testing.md
    — Automated testing for interactive apps
  • references/production-deployment.md
    — Docker, authentication, scaling
  • references/streamlit-advanced.md
    — 缓存、自定义组件、多页面应用
  • references/panel-holoviz.md
    — 联动刷选、地理可视化
  • references/gradio-ml.md
    — 模型分享、API生成、Spaces部署
  • references/app-testing.md
    — 交互式应用的自动化测试
  • references/production-deployment.md
    — Docker、身份验证、扩容

Related skills

相关技能

  • @data-science-notebooks
    — Prototype in notebooks, convert to apps
  • @data-science-model-evaluation
    — Present model metrics in apps
  • @data-engineering-orchestration
    — Connect apps to production pipelines
  • @data-science-notebooks
    — 在笔记本中原型开发,再转换为应用
  • @data-science-model-evaluation
    — 在应用中展示模型指标
  • @data-engineering-orchestration
    — 将应用连接到生产流水线

References

参考资料