### Install streamlit-antd Package Source: https://github.com/pragmatic-streamlit/streamlit-antd/blob/main/README.md This snippet shows the standard pip command to install the streamlit-antd library. It has no external dependencies beyond pip itself. ```bash pip install streamlit-antd ``` -------------------------------- ### Visualize Steps with Streamlit Antd Source: https://context7.com/pragmatic-streamlit/streamlit-antd/llms.txt Illustrates the use of the `st_antd_steps` component to visualize multi-step processes. It supports both horizontal and vertical layouts, progress indicators, and error states. This component is useful for guiding users through a sequence of actions or displaying the status of a workflow. ```python from streamlit_antd.steps import st_antd_steps, Item import streamlit as st # Define steps steps = [ Item( title="Initialization", description="System setup and configuration. Loading required resources and validating inputs.", ), Item( title="Data Processing", description="Processing input data. Running transformations and quality checks.", ), Item( title="Model Training", description="Training machine learning model. Optimizing hyperparameters.", ), Item( title="Results", description="Generating outputs and saving results. Validation complete.", ), ] # Show current step (horizontal layout) current_step = 2 st_antd_steps( steps, current=current_step, process=True, key='training_progress' ) # Vertical layout with error state st_antd_steps( steps, current=1, process=False, error=True, direction="vertical", label_placement="horizontal", key='failed_process' ) # Step-by-step form if 'current_step' not in st.session_state: st.session_state.current_step = 0 st.session_state.form_data = {} form_steps = [ Item('Input Data', 'Upload or select your dataset'), Item('Configure', 'Set processing parameters'), Item('Review', 'Confirm and submit'), ] st_antd_steps(form_steps, st.session_state.current_step, key='form_steps') # Render current step if st.session_state.current_step == 0: uploaded = st.file_uploader("Upload dataset") if uploaded: st.session_state.form_data['file'] = uploaded elif st.session_state.current_step == 1: st.session_state.form_data['batch_size'] = st.number_input("Batch size", 1, 100) else: st.json(st.session_state.form_data) # Example of how to advance the step (e.g., on button click) # if st.button('Next'): # st.session_state.current_step += 1 # st.experimental_rerun() ``` -------------------------------- ### Create Breadcrumb Navigation with streamlit-antd Source: https://github.com/pragmatic-streamlit/streamlit-antd/blob/main/README.md Demonstrates the usage of `st_antd_breadcrumb` to create a breadcrumb navigation trail. Each item in the breadcrumb is a dictionary with a 'Label'. Clicking an item can trigger navigation actions, as shown in the example with router redirection. ```python from streamlit_antd.breadcrumb import st_antd_breadcrumb # Assuming 'router', 'application' are defined elsewhere. items = [ {"Label": "My Applications"}, {"Label": f"Application({application.name})"}, {"Label": "Edit Documentation"}, ] clicked_event = st_antd_breadcrumb(items) if clicked_event: if clicked_event["payload"]["Label"] == "My Applications": router.redirect(*router.build("show_applications")) elif clicked_event["payload"]["Label"].startswith("Application"): router.redirect( *router.build("show_application", {"name": application.name}) ) ``` -------------------------------- ### Render Cards with Streamlit Antd Source: https://context7.com/pragmatic-streamlit/streamlit-antd/llms.txt Demonstrates the usage of the `st_antd_cards` component to display a grid of items. Each item can have a title, description, cover image/video, and actions. The component supports features like search and video playback with adjustable volume. ```python from streamlit_antd.cards import st_antd_cards, Item, Action import streamlit as st # Assume 'datasets' is a list of objects with attributes like name, title, description, creator_email, thumbnail_url datasets = [ type('obj', (object,), { 'name': 'dataset1', 'title': 'Dataset 1', 'description': 'Description 1', 'creator_email': 'a@b.com', 'thumbnail_url': 'http://example.com/img1.png' }), type('obj', (object,), { 'name': 'dataset2', 'title': 'Dataset 2', 'description': 'Description 2', 'creator_email': 'c@d.com', 'thumbnail_url': 'http://example.com/img2.png' }) ] # Define card items items = [ Item( id=dataset.name, title=dataset.title, description=dataset.description, email=dataset.creator_email, cover=dataset.thumbnail_url, actions=[ Action("config", "SettingOutlined"), Action("edit", "EditOutlined"), Action("open", "FolderOpenOutlined"), Action("delete", "DeleteOutlined"), ], ) for dataset in datasets ] # Render cards with search event = st_antd_cards( items, width=280, height=180, margin='20px', desc_max_len=120, show_search=True, search_text='machine learning', video_volume=0.5, key='dataset_cards' ) if event: action = event['action'] item_id = event['payload']['id'] if action in ('detail', 'click', 'open'): st.session_state.selected_dataset = item_id st.experimental_rerun() elif action == 'edit': st.session_state.edit_dataset = item_id st.experimental_rerun() elif action == 'delete': # Placeholder for delete_dataset function # delete_dataset(item_id) st.write(f"Deleting item: {item_id}") # Example action st.experimental_rerun() # Cards with video covers video_items = [ Item( id=f"tutorial_{i}", title=f"Tutorial {i}", description="Learn advanced techniques in this comprehensive video tutorial", cover=f"https://example.com/videos/tutorial_{i}.mp4", avatar="https://www.gravatar.com/avatar/hash.png", actions=[ Action('play', 'PlayCircleOutlined'), Action('bookmark', 'StarOutlined'), ] ) for i in range(10) ] video_event = st_antd_cards(video_items, video_volume=0.3, key='tutorials') ``` -------------------------------- ### Create Card Layouts with streamlit-antd Source: https://github.com/pragmatic-streamlit/streamlit-antd/blob/main/README.md Shows how to generate a grid of cards using `st_antd_cards`. Each card can display a title, description, image, and actions. The `Item` class structures card content, and `Action` defines clickable buttons on the card. It supports navigation on click events. ```python from streamlit_antd.cards import Action, Item, st_antd_cards # Assuming 'datasets', 'tag', 'router' are defined elsewhere. items = [ Item( **{ "id": dataset.name, "title": dataset.title, "description": dataset.description, "email": dataset.creator, "cover": dataset.get_image_cover(resize="238x160,s"), "actions": [ Action("config", "SettingOutlined"), Action("edit", "EditOutlined"), Action("open", "FolderOpenOutlined"), ], } ) for dataset in datasets if (not tag or tag == "All") or tag in dataset.tags ] event = st_antd_cards(items) if event and event["action"] in ("detail", "click", "open"): router.redirect( *router.build("show_dataset", {"dataset_name": event["payload"]["id"]}) ) ``` -------------------------------- ### Display Stepped Progress with streamlit-antd Source: https://github.com/pragmatic-streamlit/streamlit-antd/blob/main/README.md Demonstrates how to use `st_antd_steps` to visualize a multi-step process. It takes a list of `Item` objects, each with a title and description, and allows specifying the current step, processing status, and direction (e.g., 'vertical'). ```python from streamlit_antd.steps import Item, st_antd_steps # Assuming 'current', 'process', 'error' are defined elsewhere. items = [ Item( "Initialization", "In this stage, the system is being set up and initialized to prepare for the task. This includes configuring the necessary settings, loading any required data, and initializing any resources that will be used during the task.", # noqa: E501 ), Item( "PreProcessing", "In this stage, the task is being submitted to the system for processing. This involves sending the task request to the server and waiting for a response to confirm that the task has been accepted.", ), Item( "Running", "In this stage, the task is actively being processed by the system. This involves running the necessary algorithms and computations to complete the task, and monitoring the progress to ensure that the task is proceeding as expected.", # noqa: E501 ), Item( "PostProcessing", "In this stage, the task has been completed and the results are being retrieved from the system. This involves retrieving the output data generated by the task, saving it to a designated location, and closing any resources that were used during the task.", # noqa: E501 ), ] st_antd_steps( items, current, process=process, error=error, direction="vertical" ) ``` -------------------------------- ### Create Tabs with streamlit-antd Source: https://github.com/pragmatic-streamlit/streamlit-antd/blob/main/README.md Demonstrates how to create tabbed interfaces using the `st_antd_tabs` function. It takes a list of dictionaries, where each dictionary represents a tab with a 'Label', and returns the selected tab's label. This requires the 'streamlit-antd' library. ```python from streamlit_antd.tabs import st_antd_tabs options = ["Option 1", "Option 2", "Option 3"] event = st_antd_tabs([{"Label": op} for op in options], key="labs_tab") logger.info(f"event : {event}") ``` -------------------------------- ### Basic and Dynamic Antd Tables in Streamlit Source: https://context7.com/pragmatic-streamlit/streamlit-antd/llms.txt Demonstrates how to use st_antd_table for a feature-rich, interactive table and st_antd_dynamic_table for server-side pagination. These components allow for customization of columns, sorting, searching, and row actions. They require pandas for data manipulation and Streamlit for app creation. ```python import streamlit as st import pandas as pd from streamlit_antd import st_antd_table, st_antd_dynamic_table # Basic table with features df = pd.DataFrame({ "id": range(1, 101), "name": [f"User {i}" for i in range(1, 101)], "age": [20 + (i % 50) for i in range(100)], "tags": ["Python, Streamlit, AI" for _ in range(100)], "city": [f"City {i%10}" for i in range(100)], "status": ["Active" if i % 2 else "Inactive" for i in range(100)], }) event = st_antd_table( df, row_key='id', hidden_columns=['id'], fixed_left_columns=['name'], tags_columns=['tags'], linkable_columns=['name'], searchable_columns=['name', 'city'], sorter_columns=['age', 'status'], color_backgroud="#f9f6f1", rows_per_page=20, actions_mapper=lambda row: ['Edit', 'Delete'] if row['status'] == 'Active' else ['View'], batch_actions=['Batch Delete', 'Batch Export'], key='user_table' ) if event: action = event['payload']['action'] records = event['payload']['records'] if action == 'Delete': st.warning(f"Deleting user: {records[0]['name']}") elif action == 'Batch Delete': st.error(f"Deleting {len(records)} users") elif action == 'link': st.info(f"Clicked on: {records[0]['name']}") # Dynamic table with server-side pagination def load_users(page, page_size): offset = (page - 1) * page_size return df.iloc[offset:offset + page_size] event = st_antd_dynamic_table( 'dynamic_users', load_users, total=len(df), page_size=10, row_key='id', unsafe_html_columns=['avatar'], expand_column="description" ) ``` -------------------------------- ### Implement Pagination with streamlit-antd Source: https://github.com/pragmatic-streamlit/streamlit-antd/blob/main/README.md Shows how to use the `st_pager` function for implementing pagination. It takes a data fetching function, total item count, and page size. The lambda function fetches data based on page and limit, returning a list of jobs. ```python from streamlit_antd.pager import st_pager # Assuming 'JobManager', 'job_count', 'application' are defined elsewhere. jobs = st_pager( lambda page, limit: JobManager.get_jobs( application_name=application.name, offset=((page - 1) * limit), limit=limit, )[1], job_count, page_size=100, key="job-pager", ) ``` -------------------------------- ### Streamlit Navigation Buttons Source: https://context7.com/pragmatic-streamlit/streamlit-antd/llms.txt Implements navigation between steps in a form using Streamlit columns and buttons. It manages the current step using session state and reruns the script on button clicks. ```python col1, col2 = st.columns(2) if st.session_state.current_step > 0: if col1.button("Previous"): st.session_state.current_step -= 1 st.experimental_rerun() if st.session_state.current_step < len(form_steps) - 1: if col2.button("Next"): st.session_state.current_step += 1 st.experimental_rerun() else: if col2.button("Submit"): process_form(st.session_state.form_data) ``` -------------------------------- ### Implement Cascader Component with streamlit-antd Source: https://github.com/pragmatic-streamlit/streamlit-antd/blob/main/README.md Shows how to use the `st_antd_cascader` function to create a cascader select component. This component allows users to select options from nested lists. It accepts options, multiple selection, disabled state, and a key for Streamlit's state management. ```python from streamlit_antd.cascader import st_antd_cascader # Assuming 'options', 'multiple', 'disabled', 'key', 'saved_value', and 'kwargs' are defined elsewhere. selected = st_antd_cascader( options, multiple=multiple, disabled=disabled, key=f"{key}_cascader_machine", **{"defaultValue": saved_value, **kwargs}, ) ``` -------------------------------- ### Streamlit Antd Tabs Component Usage Source: https://context7.com/pragmatic-streamlit/streamlit-antd/llms.txt Demonstrates the basic and advanced usage of the Tabs component from Streamlit Antd. It allows for creating navigation tabs with different views or sections within a Streamlit app. Supports default active tabs and integration with session state via Streamlit Router. ```python import streamlit as st from streamlit_antd.tabs import st_antd_tabs # Basic usage options = ["Overview", "Analytics", "Settings"] items = [{"Label": op} for op in options] event = st_antd_tabs(items, key="main_tabs") if event: st.write(f"Selected tab: {event['Label']}") # With default active tab and session state from streamlit_router import StreamlitRouter router = StreamlitRouter(default_path='/') def show_dashboard(tab=None): tabs = [{"Label": "Metrics"}, {"Label": "Charts"}, {"Label": "Reports"}] event = st_antd_tabs( tabs, default_active=tab, session_state=router.get_request_state(), key='dashboard_tabs' ) if event: if event['Label'] == 'Metrics': st.metric("Revenue", "$1.2M") elif event['Label'] == 'Charts': st.line_chart({"data": [1, 2, 3]}) router.register(show_dashboard, "/dashboard") router.register(show_dashboard, "/dashboard/", endpoint='dashboard_tab') ``` -------------------------------- ### Streamlit Antd Pager Component Source: https://context7.com/pragmatic-streamlit/streamlit-antd/llms.txt Provides a pagination component (st_pager) for efficiently loading and displaying data in chunks. It requires a loader function that accepts page number and limit, the total number of items, and the desired page size. It can optionally integrate with Streamlit Router for state management. ```python from streamlit_antd.pager import st_pager import streamlit as st # Dummy function to simulate fetching jobs def fetch_jobs_from_db(offset, limit): # In a real application, this would query a database or API all_jobs = [{"name": f"Job {i}", "status": "Completed"} for i in range(1000)] return all_jobs[offset:offset + limit] # Define data loader def load_jobs(page, limit): # Fetch from database or API offset = (page - 1) * limit return fetch_jobs_from_db(offset=offset, limit=limit) # Total count of items job_count = 1000 # Render paginated data jobs = st_pager( loader=load_jobs, total=job_count, page_size=50, key="job_pager" ) # Display the loaded data for job in jobs: st.write(f"Job: {job['name']}, Status: {job['status']}") # With custom state management (example - requires streamlit_router setup) # from streamlit_router import StreamlitRouter # router = StreamlitRouter() # application_count = 500 # Example total applications # class ApplicationManager: # @staticmethod # def get_applications(name, offset, limit): # # Simulate fetching applications # return [{"name": f"App {i}", "description": "A sample application"} for i in range(offset, offset + limit)] # def show_applications(application_name): # applications = st_pager( # lambda page, limit: ApplicationManager.get_applications( # name=application_name, # offset=((page - 1) * limit), # limit=limit, # ), # total=application_count, # page_size=20, # state=router.get_request_state(), # key="app-pager" # ) # for app in applications: # st.subheader(app['name']) # st.write(app['description']) ``` -------------------------------- ### Streamlit Ant Design Tag Component Source: https://context7.com/pragmatic-streamlit/streamlit-antd/llms.txt Provides an interactive tag management component using Streamlit Ant Design. Supports adding, removing, and customizing tags with options for non-removable initial tags and long tag handling. ```python from streamlit_antd.tag import st_antd_tag # Basic tag editor tags = st_antd_tag( tag_list=('Python', 'Machine Learning', 'Streamlit'), removable_start_idx=0, log_tag_threshold=20, new_tag_name='Add Tag', key='topic_tags' ) st.write(f"Current tags: {tags}") # Non-removable initial tags project_tags = st_antd_tag( tag_list=('Production', 'Critical', 'user_tag_1', 'user_tag_2'), removable_start_idx=2, # First 2 tags cannot be removed new_tag_name='Custom Tag', key='project_tags' ) # Long tag handling documentation_tags = st_antd_tag( tag_list=( 'API', 'Authentication', 'very_long_tag_name_that_exceeds_normal_length' ), removable_start_idx=0, log_tag_threshold=30, # Truncate tags longer than 30 chars key='doc_tags' ) # Update backend when tags change if 'previous_tags' not in st.session_state: st.session_state.previous_tags = [] current_tags = st_antd_tag(key='editable_tags') if current_tags != st.session_state.previous_tags: save_tags_to_database(current_tags) st.session_state.previous_tags = current_tags st.success("Tags updated!") ``` -------------------------------- ### Display Data in an Ant Design Table with streamlit-antd Source: https://github.com/pragmatic-streamlit/streamlit-antd/blob/main/README.md Illustrates how to render a Pandas DataFrame using the `st_antd_table` function. This allows for styled tables with options to hide specific columns and set background colors. Requires pandas and streamlit-antd. ```python import pandas as pd from streamlit_antd.table import st_antd_table # Assuming 'data' is a pandas DataFrame df = pd.DataFrame(data) st_antd_table(df, color_backgroud="#f9f6f1", hidden_columns=["Index"]) ``` -------------------------------- ### Display Result Messages with streamlit-antd Source: https://github.com/pragmatic-streamlit/streamlit-antd/blob/main/README.md Demonstrates the use of `st_antd_result` to display success, error, or information messages with optional actions. It takes a title, subtitle, and a list of `Action` objects. Clicking an action can trigger specific functions. ```python from streamlit_antd.result import Action, st_antd_result # Assuming 'job_name' is defined elsewhere. title = "Job Created Successfully!" sub_title = f"job name: {job_name}. The job running takes a few minutes, please wait." actions = [ Action("show_job", "Job details", primary=True), Action("create", "Create a new job"), Action("edit", "Back edit"), ] clicked_event = st_antd_result(title, sub_title, actions) ``` -------------------------------- ### Streamlit Antd Breadcrumb Component Source: https://context7.com/pragmatic-streamlit/streamlit-antd/llms.txt Implements a navigation breadcrumb trail using st_antd_breadcrumb for hierarchical page structures. It takes a list of dictionaries, where each dictionary represents a breadcrumb item with a 'Label' and optional 'route'. It handles click events to navigate or trigger reruns. ```python from streamlit_antd.breadcrumb import st_antd_breadcrumb import streamlit as st # Assuming streamlit_router is installed and configured # from streamlit_router import StreamlitRouter # Basic breadcrumb items = [ {"Label": "Home"}, {"Label": "Projects"}, {"Label": "Project Alpha"}, {"Label": "Settings"}, ] clicked_event = st_antd_breadcrumb(items, key="nav_breadcrumb") if clicked_event: clicked_label = clicked_event["payload"]["Label"] st.write(f"Navigating to: {clicked_label}") # Route based on clicked breadcrumb if clicked_label == "Home": st.session_state.page = "home" st.experimental_rerun() elif clicked_label == "Projects": st.session_state.page = "projects" st.experimental_rerun() elif clicked_label.startswith("Project"): st.session_state.page = "project_detail" st.experimental_rerun() # Integration with router (example - requires streamlit_router setup) # router = StreamlitRouter() # app_name = "ExampleApp" # items_with_routes = [ # {"Label": "Applications", "route": "show_applications"}, # {"Label": f"App({app_name})", "route": "show_application"}, # {"Label": "Documentation", "route": "current"}, # ] # clicked = st_antd_breadcrumb(items_with_routes) # if clicked and clicked['payload'].get('route'): # route = clicked['payload']['route'] # if route == 'show_applications': # router.redirect(*router.build("show_applications")) # elif route == 'show_application': # router.redirect(*router.build("show_application", {"name": app_name})) ``` -------------------------------- ### Display Result Messages with Streamlit Antd Source: https://context7.com/pragmatic-streamlit/streamlit-antd/llms.txt Shows how to display success or error messages to the user using the `st_antd_result` component. This component can include a title, subtitle, and action buttons. It returns the clicked action, allowing for conditional navigation or further processing. ```python from streamlit_antd import st_antd_result, Action import streamlit as st # Success result title = "Job Created Successfully!" sub_title = f"Job name: data_processing_job. The job will start in a few minutes." actions = [ Action("view_job", "View Job Details", primary=True), Action("create_new", "Create Another Job"), Action("back", "Return to Dashboard"), ] clicked = st_antd_result( title, sub_title, actions, status='success', key='job_result' ) if clicked: action_name = clicked['payload']['action'] if action_name == 'view_job': st.session_state.page = 'job_detail' elif action_name == 'create_new': st.session_state.page = 'job_create' elif action_name == 'back': st.session_state.page = 'dashboard' st.experimental_rerun() # Error result error_title = "Payment Failed" error_sub = "Your payment could not be processed. Please check your card details." error_actions = [ Action("retry", "Try Again", primary=True), Action("contact", "Contact Support"), ] error_event = st_antd_result( error_title, error_sub, error_actions, status='error', key='payment_error' ) ``` -------------------------------- ### Streamlit Antd Result Component Source: https://context7.com/pragmatic-streamlit/streamlit-antd/llms.txt Displays operation result pages using st_antd_result, supporting success or error states along with action buttons. This component is useful for providing feedback to users after an operation. ```python from streamlit_antd.result import st_antd_result, Action import streamlit as st # Example usage for a success state # st_antd_result( # title="Operation Successful", # status="success", # description="Your changes have been saved.", # actions=[ # Action("Back to Dashboard", "primary", "/dashboard"), # Action("View Details", "secondary", "/details/123") # ] # ) # Example usage for an error state # st_antd_result( # title="Operation Failed", # status="error", # description="An unexpected error occurred. Please try again later.", # actions=[ # Action("Retry", "primary", "#"), # Action("Contact Support", "ghost", "mailto:support@example.com") # ] # ) ``` -------------------------------- ### Streamlit Antd Cascader Component Usage Source: https://context7.com/pragmatic-streamlit/streamlit-antd/llms.txt Illustrates the usage of the Cascader component for hierarchical data selection. It supports both single and multiple selections, with options for defining nested structures and handling selection changes via callbacks. The `defaultValue` can be used to pre-select items. ```python from streamlit_antd.cascader import st_antd_cascader # Define hierarchical options options = [ { "value": 'usa', "label": 'United States', "children": [ { "value": 'california', "label": 'California', "children": [ {"value": 'sf', "label": 'San Francisco'}, {"value": 'la', "label": 'Los Angeles'}, {"value": 'sd', "label": 'San Diego', "disabled": True}, ], }, ], }, { "value": 'canada', "label": 'Canada', "children": [ { "value": 'ontario', "label": 'Ontario', "children": [ {"value": 'toronto', "label": 'Toronto'}, ], }, ], }, ] # Single selection selected = st_antd_cascader( options, multiple=False, key="location_selector", defaultValue=["usa", "california", "sf"] ) st.write(f"Selected path: {selected}") # Multiple selection with onChange callback def on_location_change(): st.success("Location updated!") selected_multi = st_antd_cascader( options, multiple=True, key="multi_location", on_change=on_location_change ) st.write(f"Selected locations: {selected_multi}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.