Open in VS Code: From your cloned
s26-06643repository, run in the terminal:code sse/optional/web-apps/web-apps.ipynb
Web Applications for Science#
Scientists increasingly need to share their tools and results as interactive web applications. Modern Python frameworks make it possible to build dashboards, data explorers, and interactive tools with minimal web development knowledge. In this lecture, we cover Streamlit, Gradio, and Panel, and walk through building and deploying a simple scientific dashboard.
Section 1: Why Web Apps for Science?#
Traditional scientific workflows end with a script, a notebook, or a paper. But many use cases benefit from an interactive interface:
Collaborators who do not write code can explore your data or run your model
Reviewers can interact with your results rather than staring at static figures
Students can experiment with parameters and build intuition
You can build internal tools to speed up repetitive analysis tasks
The key insight is that you do not need to learn HTML, CSS, and JavaScript. Several Python frameworks let you build web apps using only Python.
Section 2: Framework Overview#
Streamlit#
Streamlit is the most popular framework for building data apps in Python. It uses a simple top-to-bottom script model — your app is just a Python script that Streamlit reruns on each interaction.
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
st.title("Gaussian Distribution Explorer")
mu = st.slider("Mean", -5.0, 5.0, 0.0)
sigma = st.slider("Standard Deviation", 0.1, 5.0, 1.0)
n_samples = st.slider("Number of samples", 100, 10000, 1000)
samples = np.random.normal(mu, sigma, n_samples)
fig, ax = plt.subplots()
ax.hist(samples, bins=50, density=True, alpha=0.7)
x = np.linspace(mu - 4 * sigma, mu + 4 * sigma, 200)
ax.plot(x, (1 / (sigma * np.sqrt(2 * np.pi))) * np.exp(-0.5 * ((x - mu) / sigma) ** 2), 'r-')
ax.set_xlabel("Value")
ax.set_ylabel("Density")
st.pyplot(fig)
Run with: streamlit run app.py
Strengths: Simple mental model, great documentation, large ecosystem of components.
Limitations: Reruns the full script on every interaction (can be slow for heavy computation without caching).
Gradio#
Gradio is designed for building interfaces around machine learning models, but works well for any function-based tool.
import gradio as gr
import numpy as np
def predict_reaction_rate(temperature, concentration, activation_energy):
"""Arrhenius equation: k = A * exp(-Ea / RT)"""
R = 8.314 # J/(mol*K)
A = 1e13 # pre-exponential factor
k = A * np.exp(-activation_energy / (R * temperature))
rate = k * concentration
return f"Rate constant: {k:.4e} s⁻¹\nReaction rate: {rate:.4e} mol/(L·s)"
demo = gr.Interface(
fn=predict_reaction_rate,
inputs=[
gr.Slider(200, 1000, value=300, label="Temperature (K)"),
gr.Slider(0.01, 10, value=1.0, label="Concentration (mol/L)"),
gr.Slider(10000, 200000, value=50000, label="Activation Energy (J/mol)"),
],
outputs="text",
title="Arrhenius Rate Calculator",
)
demo.launch()
Strengths: Function-centric API, built-in sharing via HuggingFace Spaces, great for ML demos.
Limitations: Less flexible layout than Streamlit for complex dashboards.
Panel#
Panel is part of the HoloViz ecosystem and integrates well with other HoloViz tools (HoloViews, hvPlot, Datashader). It is more flexible than Streamlit but has a steeper learning curve.
import panel as pn
import numpy as np
import matplotlib.pyplot as plt
pn.extension()
freq = pn.widgets.FloatSlider(name="Frequency", start=0.1, end=10, value=1.0)
amp = pn.widgets.FloatSlider(name="Amplitude", start=0.1, end=5, value=1.0)
@pn.depends(freq, amp)
def plot_wave(f, a):
fig, ax = plt.subplots()
x = np.linspace(0, 2 * np.pi, 200)
ax.plot(x, a * np.sin(f * x))
ax.set_ylim(-6, 6)
plt.close(fig)
return fig
pn.Column(freq, amp, plot_wave).servable()
Strengths: Very flexible, notebook-friendly, supports multiple plotting libraries.
Limitations: More verbose, smaller community than Streamlit.
Section 3: Building a Scientific Dashboard#
Let’s build a more complete Streamlit app — a dashboard that lets users upload a CSV of experimental data, explore it, and fit a model.
Create a file called dashboard.py:
import streamlit as st
import pandas as pd
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
st.title("Experimental Data Explorer")
# File upload
uploaded_file = st.file_uploader("Upload CSV data", type="csv")
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
st.write("### Raw Data")
st.dataframe(df)
# Column selection
columns = df.columns.tolist()
x_col = st.selectbox("X column", columns)
y_col = st.selectbox("Y column", columns, index=min(1, len(columns) - 1))
# Plot
fig, ax = plt.subplots()
ax.scatter(df[x_col], df[y_col], alpha=0.6)
ax.set_xlabel(x_col)
ax.set_ylabel(y_col)
# Curve fitting
fit_type = st.selectbox("Fit type", ["None", "Linear", "Polynomial", "Exponential"])
if fit_type == "Linear":
coeffs = np.polyfit(df[x_col], df[y_col], 1)
x_fit = np.linspace(df[x_col].min(), df[x_col].max(), 100)
ax.plot(x_fit, np.polyval(coeffs, x_fit), 'r-', label=f"y = {coeffs[0]:.3f}x + {coeffs[1]:.3f}")
ax.legend()
elif fit_type == "Polynomial":
degree = st.slider("Polynomial degree", 2, 10, 2)
coeffs = np.polyfit(df[x_col], df[y_col], degree)
x_fit = np.linspace(df[x_col].min(), df[x_col].max(), 100)
ax.plot(x_fit, np.polyval(coeffs, x_fit), 'r-', label=f"Degree {degree} polynomial")
ax.legend()
elif fit_type == "Exponential":
def exp_func(x, a, b, c):
return a * np.exp(b * x) + c
try:
popt, _ = curve_fit(exp_func, df[x_col], df[y_col], p0=[1, 0.1, 0], maxfev=5000)
x_fit = np.linspace(df[x_col].min(), df[x_col].max(), 100)
ax.plot(x_fit, exp_func(x_fit, *popt), 'r-',
label=f"y = {popt[0]:.3f}·exp({popt[1]:.3f}x) + {popt[2]:.3f}")
ax.legend()
except RuntimeError:
st.warning("Exponential fit did not converge. Try different data.")
st.pyplot(fig)
else:
st.info("Upload a CSV file to get started.")
Section 4: Deployment#
Once your app works locally, you want to share it. Here are the main free options:
Streamlit Community Cloud#
Push your app to a public GitHub repository
Include a
requirements.txtwith your dependenciesGo to share.streamlit.io and connect your repo
Your app is live at
https://your-app.streamlit.app
HuggingFace Spaces#
Create a new Space at huggingface.co/spaces
Select Gradio or Streamlit as the SDK
Push your code to the Space’s git repo
The app builds and deploys automatically
Tips for Deployment#
Pin your dependency versions in
requirements.txtDo not hardcode file paths — use relative paths or uploaded files
Use
@st.cache_data(Streamlit) or caching decorators to avoid recomputing expensive resultsKeep your app lightweight — free hosting tiers have limited resources
Exercise: Build an Interactive Data Explorer#
Build a Streamlit or Gradio app that does the following:
Accepts a CSV file upload (or generates synthetic data if no file is uploaded)
Displays a scatter plot of two user-selected columns
Lets the user choose a fit type (linear, polynomial, or exponential)
Displays the fit equation and R² value
Has a “Download Results” button that exports the fit parameters as a JSON file
Bonus: Deploy your app to Streamlit Community Cloud or HuggingFace Spaces and share the link.
Hints:
Start with the dashboard example above and extend it
Use
st.download_buttonfor the export featureUse
sklearn.metrics.r2_scorefor R² calculation
Summary#
Framework |
Best For |
Learning Curve |
|---|---|---|
Streamlit |
General data apps, dashboards |
Low |
Gradio |
ML model demos, function-based tools |
Low |
Panel |
Complex dashboards, HoloViz integration |
Medium |
All three frameworks let you build useful scientific web apps without any web development expertise. Start with Streamlit for most use cases, and explore Gradio or Panel when you need their specific strengths.
Tips and Tricks#
Prompt: “Write a Streamlit app that [description]”: AI generates working Streamlit apps from surprisingly brief descriptions.
Start with
st.write()and sliders: Get a working prototype with basic widgets before adding complexity.Use
@st.cache_dataon expensive functions: AI often forgets this — prompt: “Add caching to avoid recomputing [function] on every rerun.”Prompt: “Convert this matplotlib plot to a Streamlit app with interactive controls”: This is a common pattern AI handles well.
Test locally before deploying:
streamlit run app.pyshould work perfectly on your machine before pushing to Streamlit Cloud.Keep your
requirements.txtminimal: Only include what the app actually imports — bloated dependencies slow down cloud deployments.Prompt: “Add a file upload widget that reads a CSV and displays a table”: File upload is the most common interactive pattern for scientific apps.
Use Gradio for function-centric demos: If your tool is one function with inputs and outputs, Gradio is simpler than Streamlit.
Foundational Concepts to Commit to Memory#
Streamlit reruns your entire script on every user interaction — this is its core mental model. Use
@st.cache_datato avoid recomputing expensive results.Gradio wraps a single function as a web interface — if you can write a function, you can build a Gradio app.
Panel is the most flexible of the three frameworks but has a steeper learning curve; it shines when you need complex layouts or HoloViz integration.
You do not need HTML, CSS, or JavaScript to build useful scientific web apps. All three frameworks are pure Python.
Deployment options are free: Streamlit Community Cloud and HuggingFace Spaces both offer zero-cost hosting for public apps.
Pin your dependencies in
requirements.txtfor deployment — an unpinned dependency updating can silently break your app.st.file_uploader,st.selectbox, andst.sliderare the three widgets you will use in almost every Streamlit app.The purpose of a scientific web app is to make your work accessible to people who do not write code — collaborators, reviewers, students, and your future self.
Knowing vs. Doing: Reflection#
Web apps are a perfect example of where AI agents dramatically expand your solution space. Before tools like Streamlit and Gradio existed, building a web interface meant learning HTML, CSS, JavaScript, and a backend framework. That was weeks of learning before you could show a single slider to a collaborator. Now, an AI agent can scaffold a working Streamlit app in minutes — and you can iterate on it by describing what you want changed. The barrier between “I have a Python function” and “anyone can use my tool in a browser” has nearly vanished.
But here is the catch: if you do not understand what the app is doing, you cannot debug it when the slider does not update, when the cache is stale, or when the deployment fails. You need to know enough about the rerun model, caching, and deployment to ask the right questions and verify the answers. You do not need to memorize every Streamlit widget — that is what documentation and AI are for. You need to know that widgets exist, roughly what they do, and how data flows through the app.
The real value you bring with web apps is not the code — it is the decision about what to build. Which data should the user be able to explore? What parameters matter? What visualization tells the story? Those are domain decisions that require your expertise. Let the AI handle the st.slider syntax. You handle the science.