
Gradio vs Streamlit is a choice about how users interact with your Python code. Gradio is a useful starting point when the application revolves around functions connected to explicit inputs, outputs, and events. Streamlit fits well when you want to assemble a page of controls, results, tables, and explanations using a script that reruns as people interact.
Both can build a small data tool or a model interface. Gradio is not limited to machine learning demos, and Streamlit is not limited to dashboards. Choose by the interaction and state behavior you need, then evaluate the work required to host the app for other people.
| Question | Gradio | Streamlit |
|---|---|---|
| How does an action reach Python? | Components and event listeners connect inputs to functions and outputs. | Interactions commonly trigger a script rerun; forms and fragments offer more control. |
| How do you group edits before running work? | Attach the calculation to a button or another chosen event. | Put inputs in a form and calculate when its submit button is pressed. |
| Where can per-session values live? | gr.State can carry values between events in a page session. | st.session_state can carry values across reruns in a session. |
| What must be considered separately? | Shared Python objects, long-running jobs, access control, and hosting. | Shared caches, long-running jobs, access control, and hosting. |
The Gradio Blocks guide explains the input-function-output connections. Streamlit's execution-flow reference describes controls such as forms and fragments. Avoid treating every Streamlit interaction as an unavoidable full recalculation: where the calculation sits and which controls surround it matter.
This example accepts pasted CSV text, counts its rows, totals a column, and tracks successful submissions in the current page session. It uses no model, database, file upload, shared cache, or external API. Keeping the calculation identical makes it easier to inspect the differences between the two interfaces.
Create a new directory and an isolated Python environment. The commands below use Windows PowerShell and the versions tested for this article:
python -m venv .venv
.venv/Scripts/python.exe -m pip install gradio==6.32.0 streamlit==1.67.0
Save the shared code as review_csv.py. It accepts exactly the columns item,units, up to 100 data rows and 20,000 characters. Units must contain digits representing an integer from zero to one million. These application-level checks run after the text reaches Python; they are not HTTP request-size limits.
import csv
import io
import re
SAMPLE = "item,units\nalpha,3\nbeta,5\ngamma,2"
def summarize(text):
if not isinstance(text, str) or not text.strip():
raise ValueError("Paste CSV text first.")
if len(text) > 20_000:
raise ValueError("Use at most 20,000 characters.")
reader = csv.DictReader(io.StringIO(text), strict=True)
try:
if reader.fieldnames != ["item", "units"]:
raise ValueError("Use exactly the header item,units.")
count, total = 0, 0
for row in reader:
count += 1
if count > 100:
raise ValueError("Use at most 100 data rows.")
if None in row or any(v is None for v in row.values()):
raise ValueError("Each row needs exactly two fields.")
if not row["item"].strip() or len(row["item"]) > 80:
raise ValueError("Each item needs 1 to 80 characters.")
units = row["units"]
if not re.fullmatch(r"[0-9]{1,7}", units) or int(units) > 1_000_000:
raise ValueError("Units must be an integer from 0 to 1,000,000.")
total += int(units)
if count == 0:
raise ValueError("Include at least one data row.")
return count, total
except csv.Error as error:
raise ValueError("The CSV quoting is invalid.") from error
def review(text, accepted):
try:
rows, total = summarize(text)
except ValueError as error:
return f"Error: {error}", accepted
accepted += 1
return f"Accepted review {accepted} | Rows: {rows} | Total units: {total}", accepted
The input is deliberately narrow. This is not a general spreadsheet importer: it does not detect delimiters, infer types, or accept arbitrary column names. An error replaces the displayed result and leaves the successful-submission counter unchanged. A valid repeat increments that counter, even if the CSV is identical.
Save this as gradio_app.py:
import os
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
import gradio as gr
from review_csv import SAMPLE, review
with gr.Blocks(analytics_enabled=False) as demo:
gr.Markdown("# CSV review with Gradio")
gr.Markdown("Results reflect the last submission. Paste only sample data.")
accepted = gr.State(0)
source = gr.Textbox(label="CSV text", value=SAMPLE, lines=6)
submit = gr.Button("Review CSV")
output = gr.Textbox(label="Last submitted result", interactive=False)
submit.click(review, inputs=[source, accepted], outputs=[output, accepted])
if __name__ == "__main__":
demo.launch(server_name="127.0.0.1", server_port=7865, share=False,
inbrowser=False)
The button passes the current text and session counter to review(). Its two returned values update the result box and the counter. The input box has no change handler, so editing it alone does not run the calculation. The label makes clear that a displayed result belongs to the last submission.
Save this as streamlit_app.py:
import streamlit as st
from review_csv import SAMPLE, review
st.title("CSV review with Streamlit")
st.caption("Results reflect the last submission. Paste only sample data.")
if "accepted" not in st.session_state:
st.session_state.accepted = 0
st.session_state.result = "No submission yet."
with st.form("csv_review"):
source = st.text_area("CSV text", value=SAMPLE, height=180)
submitted = st.form_submit_button("Review CSV")
if submitted:
text, count = review(source, st.session_state.accepted)
st.session_state.result = text
st.session_state.accepted = count
st.text("Last submitted result")
st.text(st.session_state.result)
The script initializes session values only when they are absent. The submitted branch runs the calculation after form submission; ordinary script execution does not increment the counter. Streamlit forms group input changes until the user submits them.
Start Gradio from the example directory:
.venv/Scripts/python.exe gradio_app.py
Open http://127.0.0.1:7865. In a second terminal, start Streamlit:
.venv/Scripts/python.exe -m streamlit run streamlit_app.py --server.address 127.0.0.1 --server.port 8505 --server.headless true --browser.gatherUsageStats false
Open http://127.0.0.1:8505. Both apps bind to the local machine. Gradio sharing is disabled; no public tunnel is created. Stop each server with Ctrl+C when you finish. These commands are a local exercise, not a public deployment configuration.
The prefilled sample contains three rows with units of 3, 5, and 2. Clicking Review CSV should display Accepted review 1 | Rows: 3 | Total units: 10. Submit it again to see review 2. Change a unit to bad and submit: an error should replace the result. Restore valid input and the next successful review should be 3.
Validation, November 17, 2026: the shared logic passed 27 checks on Windows with Python 3.12.14. Browser checks exercised valid and repeated submissions, unsubmitted edits, invalid input, recovery, and two separate tab sessions for each app. Reloading a tested tab reset its counter. This was a local functional test, not a throughput, authentication, multi-user security, cloud, or GPU test.
| Behavior to inspect | What the example is designed to show |
|---|---|
| First valid submission | Three rows, ten units, and a session counter of one. |
| Repeat submission | The same total, with the counter incremented once. |
| Edited but unsubmitted text | The previous submitted result remains visible. |
| Invalid units | An error replaces the result; the successful counter does not increase. |
| Two separate tabs | Each app session maintains its own result and counter in this example. |
| Page reload | Session values are not a durable record of previous work. |
A counter that belongs to one visitor should not be an ordinary mutable global shared by the server. Gradio distinguishes global, session, and browser state in its state guide. This example uses gr.State, not browser storage or a shared global counter.
Streamlit's Session State reference explains persistence across reruns and the connection to a browser session. Keeping a value through a rerun does not make it a database record. If users need saved work, define ownership, storage, expiry, and recovery explicitly.
Caching is a separate decision. Current Streamlit data caches and resource caches support global or session scope. A globally cached resource is shared and must be safe for concurrent use. Choose scope deliberately, especially for user-specific data. The examples here use no cache and do not test caching behavior.
Long-running calculations also need a decision beyond the interface. A form submission or callback does not by itself make a job recoverable after the process stops. For CPU-intensive work, our Python multiprocessing guide explains a separate process-pool example. Integrating a worker, job status, cancellation, and recovery with either UI requires its own tests.
Start with Gradio when a few functions and their input-output relationships describe the workflow clearly. An event-driven prototype can be easy to inspect because each action has explicit inputs and outputs. Check how your layout, state, and error handling develop as the number of interactions grows.
Start with Streamlit when the app reads naturally as a page assembled from Python: controls, narrative, tables, and results. Its script model can keep that page concise, provided you understand when code reruns and where state belongs. Use forms or other execution controls where they suit the interaction.
For a larger application, compare navigation, accessibility, authorization, team familiarity, and the maintenance cost of custom UI behavior. Build one representative user journey before selecting either library. A small demo proves that a path can work; it does not establish that every future requirement fits.
Neither interface library makes this CSV calculation require a GPU. The server runs the Python work, while the browser presents the interface. Streamlit describes that division in its client-server architecture guide. If you later add model inference, evaluate that backend's compute needs separately from the UI.
Before making the app available to others, decide who can use it, how traffic reaches it, where state lives, and who operates the process. Check HTTPS, connection behavior, request limits, dependency updates, logs, restart behavior, and recovery. A working local tab does not verify any of those production requirements.
The API hosting comparison provides a useful starting point for weighing a self-managed VM against a managed platform. For private evaluation on a Compute instance, Hivenet's port-forwarding documentation describes reaching a loopback service through SSH. That private connection is separate from a public, authenticated deployment.
If your team wants to operate the Python environment, evaluate CPU compute with Hivenet. Bring the app's dependencies, observed memory use, expected simultaneous sessions, calculation duration, and availability requirements. Test a representative workload on the intended instance. This article does not claim a managed Gradio or Streamlit service, a tested Hivenet deployment, or a capacity estimate.
Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.