Created
May 18, 2026 14:05
-
-
Save SpiffGreen/65d9b010c265247b5cfa6d835734edb7 to your computer and use it in GitHub Desktop.
Learn Streamlit & Gradio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## https://www.youtube.com/watch?v=RiCQzBluTxU | |
| ## https://www.youtube.com/watch?v=eE7CamOE-PA | |
| ############################################## | |
| import gradio as gr | |
| def add_numbers(a, b): | |
| return a + b | |
| def reverse_text(text: str) -> str: | |
| return text[::-1] | |
| def square_number(x): | |
| return x ** 2 | |
| def calculator(num1, num2, operation): | |
| if operation == "Add": | |
| return num1 + num2 | |
| elif operation == "Subtract": | |
| return num1 - num2 | |
| elif operation == "Multiply": | |
| return num1 * num2 | |
| elif operation == "Divide": | |
| return num1 / num2 if num2 != 0 else "Cannot divide by zero" | |
| else: | |
| return "Invalid operation" | |
| def word_count(file): | |
| if file is None: | |
| return f"The file contains {0} words." | |
| with open(file.name, 'r', encoding='utf-8') as f: | |
| text = f.read() | |
| return f"The file contains {len(text.split())} words." | |
| def resize_image(image, width, height): | |
| img_resized = image.resize((width, height)) | |
| return img_resized | |
| def trivia_game(answer): | |
| correct_answer = "Python" | |
| if answer == correct_answer: | |
| return "Correct! Python is known as a snake." | |
| else: | |
| return f"Incorrect. The correct answer is {correct_answer}." | |
| def check_answers(selected_colors): | |
| if not selected_colors: | |
| return "No colors selected." | |
| result = "" | |
| if len(selected_colors) == 1: | |
| result = selected_colors[0] + "." | |
| return result | |
| for idx, color in enumerate(selected_colors, start=1): | |
| if idx == len(selected_colors): | |
| result += f"and {color}." | |
| else: | |
| result += f"{color}, " | |
| return result | |
| def main(): | |
| # interface = gr.Interface(fn=add_numbers, inputs=["number", "number"], outputs="number") | |
| # interface = gr.Interface( | |
| # fn=add_numbers, | |
| # inputs=[gr.Number(label="First Number"), | |
| # gr.Number(label="Second Number")], | |
| # outputs=gr.Number(label="Result")) | |
| # interface = gr.Interface( | |
| # fn=reverse_text, | |
| # inputs=gr.Textbox(label="Input text"), | |
| # outputs=gr.Textbox(label="Reversed text") | |
| # ) | |
| # interface = gr.Interface( | |
| # fn=square_number, | |
| # inputs=gr.Slider(minimum=0, maximum=100, step=1, label="Select a number"), | |
| # outputs=gr.Number(label="Squared result") | |
| # ) | |
| interface = gr.Interface( | |
| fn=calculator, | |
| inputs=[ | |
| gr.Number(label="First Number"), | |
| gr.Number(label="Second Number"), | |
| # gr.Radio(["Add", "Subtract", "Multiply", "Divide"], label="Operation") | |
| gr.Dropdown(["Add", "Subtract", "Multiply", "Divide"], label="Operation") | |
| ], | |
| outputs=gr.Number(label="Result") | |
| ) | |
| # interface = gr.Interface( | |
| # fn=word_count, | |
| # inputs=gr.File(label="Upload a text file"), | |
| # outputs=gr.Text(label="Word Count") | |
| # ) | |
| # interface = gr.Interface( | |
| # fn=resize_image, | |
| # inputs=[ | |
| # gr.Image(type="pil", label="Upload an image"), | |
| # gr.Number(label="Width(px)"), | |
| # gr.Number(label="Height(px)") | |
| # ], | |
| # outputs=gr.Image(type="pil", label="Resized Image") | |
| # ) | |
| # interface = gr.Interface( | |
| # fn=trivia_game, | |
| # inputs=[ | |
| # gr.Radio(["Java", "C++", "Python", "JavaScript"], | |
| # label="Which programming language is known as a snake?"), | |
| # ], | |
| # outputs=gr.Text(label="Result"), | |
| # title="Simple Trivia", | |
| # description="Enter the correct answer to the trivia question." | |
| # ) | |
| # interface = gr.Interface( | |
| # fn=check_answers, | |
| # inputs=gr.CheckboxGroup( | |
| # choices=["Red", "Green", "Blue", "Yellow"], | |
| # label="Select your primary colors" | |
| # ), | |
| # outputs=gr.Text(label="Selected Colors"), | |
| # ) | |
| interface.launch() | |
| if __name__ == "__main__": | |
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## https://www.youtube.com/watch?v=o8p7uQCGD0U | |
| ########################### | |
| import streamlit as st | |
| import os | |
| import pandas as pd | |
| import numpy as np | |
| # st.write("Hello, Streamlit!") | |
| st.write("This is a simple Streamlit app.") | |
| "hello world" | |
| pressed = st.button("Press me") | |
| if pressed: | |
| st.write("Button was pressed!") | |
| # ----------------------- | |
| # ----------------------- | |
| st.title("My First Streamlit App") | |
| st.header("This is a header") | |
| st.subheader("This is a subheader") | |
| st.text("This is some text.") | |
| st.markdown("This is **Markdown** _text_.") | |
| st.caption("This is a caption.") | |
| code_example = """ | |
| def greet(name): | |
| return f"Hello, {name}!" | |
| """ | |
| st.code(code_example, language="python") | |
| st.divider() | |
| st.image("https://picsum.photos/536/354", caption="Placeholder Image") | |
| st.divider() | |
| st.image(os.path.join("static", "img1.png"), caption="Local Image") | |
| st.divider() | |
| st.subheader("Dataframes") | |
| df = pd.DataFrame({ | |
| "Name": ["Alice", "Bob", "Charlie"], | |
| "Age": [25, 30, 35], | |
| "City": ["New York", "Los Angeles", "Chicago"] | |
| }) | |
| st.dataframe(df) | |
| st.divider() | |
| editable_df = st.data_editor(df) | |
| # print(editable_df) | |
| # Metrics Section | |
| st.subheader("Metrics") | |
| st.metric(label="Temperature", value="25 °C", delta="+2 °C") | |
| st.metric(label="Stock Price", value="$150", delta="-5%") | |
| # Charts | |
| chart_data = pd.DataFrame( | |
| np.random.randn(20, 3), | |
| columns=["Category", "Values1", "Values2"] | |
| ) | |
| st.divider() | |
| st.header("Charts") | |
| st.subheader("Area Chart") | |
| st.area_chart(chart_data) | |
| st.subheader("Line Chart") | |
| st.line_chart(chart_data) | |
| st.subheader("Bar Chart") | |
| st.bar_chart(chart_data) | |
| st.subheader("Scatter Chart") | |
| scatter_data = pd.DataFrame( | |
| np.random.randn(100, 2), | |
| columns=["X", "Y"] | |
| ) | |
| st.scatter_chart(scatter_data) | |
| # Maps | |
| st.divider() | |
| st.header("Maps") | |
| map_data = pd.DataFrame( | |
| np.random.randn(100, 2) / [50, 50] + [37.76, -122.4], | |
| columns=["lat", "lon"] | |
| ) | |
| st.map(map_data) | |
| # Pyplot Section | |
| st.divider() | |
| st.header("Pyplot") | |
| import matplotlib.pyplot as plt | |
| fig, ax = plt.subplots() | |
| ax.plot(chart_data["Values1"], label="Values1") | |
| ax.plot(chart_data["Values2"], label="Values2") | |
| ax.set_title("Pyplot Line Chart") | |
| ax.legend() | |
| st.pyplot(fig) | |
| # ---------------------- | |
| # Forms | |
| # ---------------------- | |
| st.divider() | |
| st.header("User Information Form") | |
| form_values = { | |
| "name": None, | |
| "height": None, | |
| "gender": None, | |
| "dob": None, | |
| "location": None | |
| } | |
| with st.form(key="user_info_form", clear_on_submit=True): | |
| form_values["name"] = st.text_input("Enter your name: ") | |
| form_values["height"] = st.number_input("Enter your height (cm): ", step=1, min_value=0) | |
| form_values["gender"] = st.selectbox("Select your gender: ", options=["Male", "Female", "Other"]) | |
| form_values["dob"] = st.date_input("Enter your date of birth: ", min_value=pd.to_datetime("1950-01-01"), max_value=pd.to_datetime("2024-12-31")) | |
| form_values["location"] = st.text_input("Enter your location: ") | |
| # print(form_values) | |
| submitted = st.form_submit_button(label="Submit") | |
| if submitted: | |
| if not all(form_values.values()): | |
| st.error("Please fill in all the fields.") | |
| else: | |
| st.balloons() | |
| st.success("Form submitted successfully!") | |
| st.write("Here are the details you entered:") | |
| for key, value in form_values.items(): | |
| st.write(f"{key.capitalize()}: {value}") | |
| # ---------------------- | |
| # Session State: Problem | |
| # ---------------------- | |
| counter = 0 | |
| st.write(f"Counter: {counter}") | |
| if st.button("Increment Counter"): | |
| counter += 1 | |
| st.write(f"Counter incremented to: {counter}") | |
| else: | |
| st.write(f"Counter not incremented: {counter}") | |
| # ---------------------- | |
| # Session State: Solution | |
| # ---------------------- | |
| if "counter" not in st.session_state: | |
| st.session_state.counter = 0 | |
| if st.button("Increment Counter"): | |
| st.session_state.counter += 1 | |
| st.write(f"Counter incremented to: {st.session_state.counter}") | |
| if st.button("Reset"): | |
| st.session_state.counter = 0 | |
| else: | |
| st.write("Counter did not reset.") | |
| st.write(f"Current Counter Value: {st.session_state.counter}") | |
| # Manual Rerun | |
| st.title("Manual Rerun Example") | |
| if "count" not in st.session_state: | |
| st.session_state.count = 0 | |
| st.write(f"Current Count: {st.session_state.count}") | |
| if st.button("Increment Count"): | |
| st.session_state.count += 1 | |
| st.rerun() # Manually trigger a rerun of the app | |
| # Fragments allow you keep parts of the app from being re-executed when you call st.rerun(). | |
| # This is useful when you want to preserve the state of certain components while allowing others to update | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment