### Install Preswald SDK Source: https://github.com/structuredlabs/preswald/blob/main/docs/quickstart.mdx Commands to install the Preswald SDK using pip or uv pip, which are common Python package managers. ```bash pip install preswald or uv pip install preswald ``` -------------------------------- ### Run Preswald Example Application Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Command to navigate to an example application directory and run it using the Preswald CLI, verifying the development setup. ```bash cd examples/iris && preswald run ``` -------------------------------- ### Run Preswald App Locally Source: https://github.com/structuredlabs/preswald/blob/main/docs/quickstart.mdx Command to launch a Preswald application locally in the browser. The app runs entirely client-side, requiring no server setup. ```bash preswald run ``` -------------------------------- ### Create a Basic Preswald App Source: https://github.com/structuredlabs/preswald/blob/main/docs/quickstart.mdx Example Python code for a simple Preswald application that displays a title and loads data from a CSV file into a table. This demonstrates Preswald's Python-based UI components and direct data access. ```python from preswald import text, table, get_df # Add a title text("# Welcome to Preswald") # Load and display data df = get_df("data/sample.csv") table(df) ``` -------------------------------- ### Run Preswald Example Application Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Steps to navigate into an example directory and execute a Preswald application, demonstrating how to run a test instance. ```bash cd examples/earthquakes && preswald run ``` -------------------------------- ### Initialize Pyodide and Install Python Packages Source: https://github.com/structuredlabs/preswald/blob/main/tests/pyodide_test.html This snippet demonstrates how to asynchronously load Pyodide in a web environment, configure its output streams, and then use `micropip` to install a custom Python package (`preswald`) from a local wheel file. It also shows commented-out alternatives for installing from PyPI and loading `typing-extensions`. ```JavaScript async function main() { const output = document.getElementById("output"); const appendOutput = (text) => { output.value += text + "\\n"; }; appendOutput("Loading Pyodide..."); const pyodide = await loadPyodide({ stdout: (text) => appendOutput(text), stderr: (text) => appendOutput("ERROR: " + text) }); appendOutput("Pyodide loaded!"); // Load micropip package first appendOutput("Loading micropip..."); await pyodide.loadPackagesFromImports("import micropip"); appendOutput("micropip loaded!"); // // Load typing-extensions package next // appendOutput("Loading typing-extensions..."); // await pyodide.loadPackagesFromImports("import typing_extensions"); // appendOutput("typing-extensions loaded!"); // Test your package try { // Alternative 1: Install from PyPI if published // await pyodide.runPythonAsync(` // import micropip // await micropip.install("preswald") // # Try importing your modules // import preswald // print("Successfully imported preswald") // # Test specific modules/functionality // # import preswald.submodule // # print(preswald.__version__) // `); // Alternative 2: If not published, you can load from wheel // First, build your wheel: python -m build --wheel // Then serve it locally and load it: await pyodide.runPythonAsync(` import micropip await micropip.install("http://localhost:8000/dist/preswald-0.1.51-py3-none-any.whl"); import preswald print("Successfully imported from wheel") from preswald.engine.service import PreswaldService PreswaldService.initialize() `); appendOutput("All tests completed!"); } catch (error) { appendOutput("ERROR: " + error); } } main(); ``` ```Python import micropip await micropip.install("http://localhost:8000/dist/preswald-0.1.51-py3-none-any.whl"); import preswald print("Successfully imported from wheel") from preswald.engine.service import PreswaldService PreswaldService.initialize() ``` -------------------------------- ### Run preswald tutorial command Source: https://github.com/structuredlabs/preswald/blob/main/docs/cli/tutorial.mdx This command starts a local preswald server for a tutorial application, allowing users to explore the bundled project. ```bash preswald tutorial ``` -------------------------------- ### JavaScript Pyodide Setup and Dependency Installation Source: https://github.com/structuredlabs/preswald/blob/main/tests/fastapi_test.html Handles the initialization of the Pyodide runtime and the installation of required Python packages (micropip, FastAPI, typing_extensions, starlette) within the browser. It includes UI feedback for loading and installation progress, and error handling. ```JavaScript document .getElementById("setupBtn") .addEventListener("click", async function () { clearOutput(); const loadingElement = document.getElementById("loadingSetup"); loadingElement.style.display = "block"; this.disabled = true; try { log("Loading Pyodide..."); pyodide = await loadPyodide(); log("Pyodide loaded successfully."); log("Installing micropip..."); await pyodide.loadPackagesFromImports(` import micropip `); log("Installing FastAPI and dependencies..."); await pyodide.runPythonAsync(` import micropip await micropip.install(['fastapi', 'typing_extensions', 'starlette']) print("✅ FastAPI and dependencies installed") `); document.getElementById("createAppBtn").disabled = false; log("Setup complete! You can now create a FastAPI application."); } catch (error) { log(`Error during setup: ${error.message}`); console.error(error); } finally { loadingElement.style.display = "none"; } }); ``` -------------------------------- ### Install uv for Python Environment Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Optional step to install 'uv', a fast Python package installer, using a curl command. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Example: Building and Executing a Basic Workflow Source: https://github.com/structuredlabs/preswald/blob/main/docs/workflow/workflow.mdx This example demonstrates how to create a `Workflow` instance, define atoms for data loading, cleaning, and analysis with dependencies, and execute the workflow to process data. It showcases the automatic passing of atom outputs as arguments between dependent atoms. ```python from preswald import Workflow import pandas as pd # Create a workflow instance workflow = Workflow() # Define an atom for loading data @workflow.atom() def load_data(): # This atom has no dependencies return pd.read_csv("data.csv") # Define an atom for cleaning data, dependent on load_data @workflow.atom(dependencies=['load_data']) def clean_data(load_data): # Automatically passes the output of load_data as an argument return load_data.dropna() # Define an atom for analysis, dependent on clean_data @workflow.atom(dependencies=['clean_data']) def analyze_data(clean_data): # Uses the cleaned data from the previous atom return clean_data.describe() # Execute the workflow results = workflow.execute() # Access the results print(results) ``` -------------------------------- ### Quick Start: Initialize and Run a Preswald App Source: https://github.com/structuredlabs/preswald/blob/main/README.md This sequence of commands provides a quick start for Preswald, initializing a new project, navigating into its directory, and launching the development server. It sets up the basic project structure and makes the app accessible locally in your browser. ```bash pip install preswald preswald init my_app cd my_app preswald run ``` -------------------------------- ### Initialize Preswald Project Source: https://github.com/structuredlabs/preswald/blob/main/docs/quickstart.mdx Commands to bootstrap a new Preswald application project, creating a scaffolded directory structure with essential files like `hello.py`, `preswald.toml`, and `secrets.toml`. ```bash preswald init my_project cd my_project ``` -------------------------------- ### Verify Docker Installation Source: https://github.com/structuredlabs/preswald/blob/main/docs/usage/troubleshooting.mdx Check if Docker is installed and accessible on your system by running the version command in your terminal. ```bash docker --version ``` -------------------------------- ### Install Python Dependencies for Preswald Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Commands to install development dependencies for Preswald using either pip or uv, enabling editable installation. ```bash pip install -e ".[dev]" ``` ```bash uv pip install -e ".[dev]" # if you installed uv ``` -------------------------------- ### Run Preswald Tutorial Application Source: https://github.com/structuredlabs/preswald/blob/main/preswald/tutorial/README.md Execute this command in your terminal to launch the Preswald tutorial application. It will start a local server, enabling you to interact with various components and observe their behavior in a live environment. ```bash preswald tutorial ``` -------------------------------- ### Run Preswald Application Source: https://github.com/structuredlabs/preswald/blob/main/examples/earthquakes/README.md Command to start the Preswald application. Execute this command in your terminal to launch the project. ```Shell preswald run ``` -------------------------------- ### Install Preswald Pip Package Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Command to install the locally built Preswald Python package from its distribution archive using 'uv pip'. ```bash uv pip install dist/preswald-0.xx.xx.tar.gz ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Command to install Git pre-commit hooks, which automate code quality checks before commits. ```bash pre-commit install ``` -------------------------------- ### Display 'Hello, World!' with Preswald Source: https://github.com/structuredlabs/preswald/blob/main/docs/usage/examples.mdx Demonstrates how to display a simple 'Hello, World!' message using the Preswald `text` component, illustrating basic UI output. ```python from preswald import text text("# Hello, World!") ``` -------------------------------- ### Verify Google Cloud CLI Installation Source: https://github.com/structuredlabs/preswald/blob/main/docs/usage/troubleshooting.mdx Confirm that the Google Cloud CLI (gcloud) is installed and configured correctly on your system by checking its version. ```bash gcloud --version ``` -------------------------------- ### Export Preswald App as Static Site Source: https://github.com/structuredlabs/preswald/blob/main/docs/quickstart.mdx Command to export a Preswald application as a static site. This creates a `dist/` folder containing all bundled code, data, and UI components, ready for sharing or static hosting. ```bash preswald export ``` -------------------------------- ### Example TOML Configuration for Detailed Logging Source: https://github.com/structuredlabs/preswald/blob/main/docs/configuration.mdx This TOML snippet provides an example configuration for Preswald's logging. It sets the log level to 'DEBUG' for maximum verbosity and defines a comprehensive format including timestamp, logger name, level, and message, ensuring detailed log output. ```toml [logging] level = "DEBUG" format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" ``` -------------------------------- ### Upgrade Preswald SDK Source: https://github.com/structuredlabs/preswald/blob/main/docs/quickstart.mdx Commands to upgrade the Preswald SDK to its latest version using pip or uv pip, ensuring access to new features and bug fixes. ```bash pip install --upgrade preswald or uv pip install --upgrade preswald ``` -------------------------------- ### Build Preswald Frontend and Backend Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Commands to compile the Preswald frontend assets and then build the main Python package, preparing it for installation or distribution. ```bash python -m preswald.build frontend python -m build ``` -------------------------------- ### Initialize a new Preswald project via CLI Source: https://github.com/structuredlabs/preswald/blob/main/docs/cli/init.mdx Demonstrates how to use the `preswald init` command to create a new project directory named 'my_app' with preconfigured boilerplate files, saving setup time. ```bash preswald init my_app ``` -------------------------------- ### Install Preswald Python Package Source: https://github.com/structuredlabs/preswald/blob/main/README.md Install the Preswald library using either pip or uv, the standard Python package managers. This command makes the `preswald` command-line interface available for creating and managing data applications. ```bash pip install preswald or uv pip install preswald ``` -------------------------------- ### Set Up Conda Environment for Preswald Testing Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Steps to create and activate a new Conda environment specifically for testing the Preswald project, ensuring a clean and isolated setup. ```bash conda deactivate conda create -n preswald-test python=3.10 -y conda activate preswald-test ``` -------------------------------- ### Support for Tuple Unpacking and Reactive Consumers Source: https://github.com/structuredlabs/preswald/blob/main/docs/usage/examples.mdx Demonstrates how Preswald supports tuple unpacking and ensures that consumers of unpacked values react automatically to changes in the source input. This highlights advanced reactivity patterns within the library. ```python from preswald import slider, text def compute_pair(n): return (n, n * 2) val = slider("Input", min_val=1, max_val=10, default=3) a, b = compute_pair(val) text(f"a: {a}, b: {b}") ``` -------------------------------- ### Create Interactive Dashboard with Slider Source: https://github.com/structuredlabs/preswald/blob/main/docs/usage/examples.mdx Shows how to build a simple interactive dashboard using Preswald, allowing users to control data display limits via a slider component. This demonstrates dynamic UI elements and their interaction with data. ```python from preswald import text, slider, table text("# Interactive Dashboard") rows = slider("Rows to Display", min_val=5, max_val=50, default=10) table(data, limit=rows) ``` -------------------------------- ### Example Usage of topbar() Function Source: https://github.com/structuredlabs/preswald/blob/main/docs/layout/topbar.mdx Demonstrates how to import and integrate the `topbar()` function into a Python application to add a fixed topbar component. ```python from preswald import topbar #add the topbar topbar() ``` -------------------------------- ### Display Data from Files with Preswald Source: https://github.com/structuredlabs/preswald/blob/main/docs/usage/examples.mdx Illustrates how to connect to and display data from various file types (CSV, JSON) using Preswald's data viewing components like `table` and `view`. ```python from preswald import connect, get_df, table data = get_df("example_data.csv") table(data) ``` ```python from preswald import connect, get_df, view data = get_df("user_event.csv") view(data) ``` -------------------------------- ### Python Example: Basic Usage of table Function Source: https://github.com/structuredlabs/preswald/blob/main/docs/displays/table.mdx Demonstrates how to import and use the `table` function with a Pandas DataFrame, showing examples of displaying data with and without a custom title. This snippet illustrates the fundamental way to render tabular data. ```python from preswald import table # Example DataFrame import pandas as pd data = { "Name": ["Alice", "Bob", "Charlie"], "Age": [25, 30, 35], "City": ["New York", "Los Angeles", "Chicago"] } df = pd.DataFrame(data) # Display the dataset with a title table(df, title="Employee Data") # Display just the data table(df) ``` -------------------------------- ### Python Usage Example: Integrating `checkbox` for Conditional Logic Source: https://github.com/structuredlabs/preswald/blob/main/docs/controls/checkbox.mdx This example demonstrates how to import and use the `checkbox` function from `preswald` to create a user-interactive checkbox. It shows how to retrieve the checkbox's state and use it to conditionally display text within the application. ```python from preswald import checkbox, text # Create a checkbox for selecting money_shown = checkbox(label="Show me the money") if money_shown: text("The money") ``` -------------------------------- ### Python Example: Creating and Using a `slider` Source: https://github.com/structuredlabs/preswald/blob/main/docs/controls/slider.mdx Illustrates how to import and use the `slider` function in a Python application to create an interactive numerical input component, demonstrating parameter configuration and value retrieval. ```python from preswald import slider # Create a slider for selecting the number of rows to display value = slider( label="Rows to Display", min_val=1, max_val=100, step=10, default=20 ) # Use the selected value print(f"Slider selected value: {value}") ``` -------------------------------- ### Python Usage Example for text_input Source: https://github.com/structuredlabs/preswald/blob/main/docs/controls/text_input.mdx Demonstrates how to use the `text_input` function for basic user input and within a form, showing how to capture and react to entered values. ```python from preswald import text_input, text, alert # Basic text input name = text_input(label="Enter your name", placeholder="John Doe") # Using text input in a form email = text_input(label="Email", placeholder="user@example.com") password = text_input(label="Password", placeholder="Enter password") if name and email and password: alert(f"Welcome {name}!", level="success") ``` -------------------------------- ### Python Example: Visualizing a Workflow DAG Source: https://github.com/structuredlabs/preswald/blob/main/docs/workflow/workflow_dag.mdx This Python example demonstrates how to use the `workflow_dag` function to visualize a custom workflow. It illustrates the creation of a `Workflow` object, the definition of two dependent tasks (`task_a` and `task_b`), and the final rendering of the workflow's DAG with a custom title. ```python from preswald import workflow_dag, Workflow # Create a workflow object workflow = Workflow() # Add some tasks to the workflow @workflow.task() def task_a(): return "A" @workflow.task(depends_on=[task_a]) def task_b(): return "B" # Render the workflow DAG workflow_dag(workflow, title="Example Workflow") ``` -------------------------------- ### Example Usage of Sidebar Function Source: https://github.com/structuredlabs/preswald/blob/main/docs/layout/sidebar.mdx Demonstrates how to add a customizable sidebar to a Preswald app, including setting a custom logo and name. ```python from preswald import sidebar sidebar( defaultopen=True, logo="https://upload.wikimedia.org/wikipedia/commons/a/a7/React-icon.svg", name="Iris Dashboard" ) ``` -------------------------------- ### Python Usage Example for selectbox Source: https://github.com/structuredlabs/preswald/blob/main/docs/controls/selectbox.mdx Demonstrates how to import and use the `selectbox` function to create a dropdown menu and capture the user's selection in a Python application. ```python from preswald import selectbox # Create a dropdown menu to select a dataset choice = selectbox( label="Choose Dataset", options=["Dataset A", "Dataset B", "Dataset C"] ) # Use the selected option print(f"User selected: {choice}") ``` -------------------------------- ### Complete Workflow Example with RetryPolicy Source: https://github.com/structuredlabs/preswald/blob/main/docs/workflow/retrypolicy.mdx Demonstrates a full workflow integrating both workflow-level and atom-specific retry policies, showcasing how to handle transient failures. ```python from preswald import Workflow, RetryPolicy # Define a workflow-wide retry policy workflow = Workflow( default_retry_policy=RetryPolicy( max_attempts=3, delay=1.0, backoff_factor=2.0, retry_exceptions=(IOError, TimeoutError) ) ) @workflow.atom() def load_data(): raise IOError("Simulated failure") # Atom-specific retry policy @workflow.atom(retry_policy=RetryPolicy(max_attempts=5, delay=0.5)) def fetch_data(): raise TimeoutError("Another simulated failure") # Execute the workflow try: workflow.execute() except Exception as e: print(f"Workflow execution failed: {e}") ``` -------------------------------- ### Example Issue Reporting Template Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md A template for reporting issues, detailing sections for describing the bug, steps to reproduce, expected behavior, screenshots, and environment details. ```plaintext **Describe the bug** A clear and concise description of the issue. **Steps to Reproduce** 1. Go to '...' 2. Click on '...' 3. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain the issue. **Environment** - OS: [e.g., Windows, macOS, Linux] - Python version: [e.g., 3.9] - Browser: [e.g., Chrome, Firefox] ``` -------------------------------- ### Run Preswald Frontend in Watch Mode Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Command to start the Preswald frontend build in watch mode, automatically rebuilding upon file changes. ```bash python -m preswald.build watch ``` -------------------------------- ### WorkflowAnalyzer Usage Example Source: https://github.com/structuredlabs/preswald/blob/main/docs/workflow/workflow_analyzer.mdx Demonstrates how to use the `WorkflowAnalyzer` to create, analyze, and visualize a sample workflow. It covers initializing the analyzer, executing the workflow, visualizing dependencies, identifying the critical path, and finding parallel execution groups. ```python from preswald import Workflow, WorkflowAnalyzer import pandas as pd # Create a sample workflow workflow = Workflow() @workflow.atom() def load_data(): return pd.read_csv("data.csv") @workflow.atom(dependencies=['load_data']) def clean_data(load_data): return load_data.dropna() @workflow.atom(dependencies=['clean_data']) def analyze_data(clean_data): return clean_data.describe() # Initialize the WorkflowAnalyzer analyzer = WorkflowAnalyzer(workflow) # Execute the workflow workflow.execute() # Visualize the workflow fig = analyzer.visualize(title="Workflow Dependency Graph") fig.show() # Opens visualization in a web browser # Identify and display the critical path critical_path = analyzer.get_critical_path() print("Critical path:", ' -> '.join(critical_path)) # Visualize the critical path fig_critical = analyzer.visualize( highlight_path=critical_path, title="Workflow Critical Path" ) fig_critical.show() # Identify and display parallel execution groups parallel_groups = analyzer.get_parallel_groups() print("\nParallel execution groups:") for i, group in enumerate(parallel_groups, 1): print(f"Group {i}: {', '.join(group)}") ``` -------------------------------- ### Demonstrate Automatic Reactivity and Side Effects Source: https://github.com/structuredlabs/preswald/blob/main/docs/usage/examples.mdx Illustrates Preswald's automatic dependency tracking and selective recomputation for top-level expressions. It also shows how side effects like logging are handled reactively, ensuring they run only when relevant inputs change. ```python from preswald import slider, text base = slider("Base", min_val=1, max_val=10, default=2) double = base * 2 text(f"Double: {double}") ``` ```python import logging from preswald import slider logger = logging.getLogger(__name__) val = slider("Level", min_val=0, max_val=5, default=1) logger.info(f"Slider moved: {val}") ``` -------------------------------- ### Preswald Project Directory Structure Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Overview of the Preswald repository's main directories and their contents, including the SDK, frontend, examples, and tests. ```plaintext preswald/ ├── preswald/ # SDK + Python FastAPI backend ├── frontend/ # React + Vite frontend ├── examples/ # Sample apps to showcase Preswald's capabilities ├── tutorial/ # Tutorial for getting started with Preswald ├── tests/ # Unit and integration tests ├── pyproject.toml # Python package configuration └── README.md # Project overview ``` -------------------------------- ### Example Pull Request Description Template Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md A template demonstrating how to write a clear and concise pull request description, including a type prefix, context, and links to relevant issues. ```plaintext feat: add new user authentication system This PR adds user authentication via JWT tokens. Includes: - Backend API endpoints for login and signup. - React context integration for frontend. - Unit tests for new functionality. Fixes #42 ``` -------------------------------- ### Python FastAPI Application and In-Browser Request Handler Source: https://github.com/structuredlabs/preswald/blob/main/tests/fastapi_test.html Defines a complete FastAPI application with Pydantic models, an in-memory database, and standard RESTful endpoints (GET all, GET by ID, POST new item). It also includes a custom `handle_request` function designed to simulate HTTP requests against the FastAPI app directly within the Pyodide environment, enabling serverless API interaction. ```Python from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import List, Optional import json # Create the FastAPI app app = FastAPI(title="Browser FastAPI Demo") # Define data model class Item(BaseModel): id: Optional[int] = None name: str description: Optional[str] = None price: float # In-memory database items_db = [ {"id": 1, "name": "Laptop", "description": "High-performance laptop", "price": 999.99}, {"id": 2 ``` -------------------------------- ### Handling Errors with preswald.query Source: https://github.com/structuredlabs/preswald/blob/main/docs/data/query.mdx Provides an example of implementing error handling for the `query` function using `try-except` blocks. It demonstrates catching `ValueError` for configuration issues and general `Exception` for other query-related errors. ```python from preswald import query try: results = query("SELECT * FROM events", 'eq_clickhouse') except ValueError as e: print(f"Configuration error: {e}") except Exception as e: print(f"Query error: {e}") ``` -------------------------------- ### Example: Workflow Execution Output Structure Source: https://github.com/structuredlabs/preswald/blob/main/docs/workflow/workflow.mdx Illustrates the typical structure of the dictionary returned by `workflow.execute()`, showing how atom names are mapped to their computed results, such as DataFrames or analysis outputs. ```python { "load_data": , "clean_data": , "analyze_data": } ``` -------------------------------- ### Quick Start: Develop Preswald App Logic in Python Source: https://github.com/structuredlabs/preswald/blob/main/README.md This Python code snippet demonstrates how to define the core logic of a Preswald application. It imports UI components like `text` and `table`, retrieves data using `get_df`, and renders them, forming the interactive elements of the app. ```python from preswald import text, table, get_df text("# Hello Preswald") df = get_df("sample.csv") table(df) ... ``` -------------------------------- ### Configure Parquet Data Connections in TOML Source: https://github.com/structuredlabs/preswald/blob/main/docs/configuration.mdx This TOML configuration demonstrates how to define Parquet data sources for Preswald. It shows examples for a full dataset and a subset with specific columns, enabling the application to connect to and utilize Parquet files. ```toml [data.sales_parquet] type = "parquet" path = "data/sales_data.parquet" [data.analytics_subset] type = "parquet" path = "data/analytics.parquet" columns = ["region", "revenue", "score"] ``` -------------------------------- ### View Transformed Source Code with Debug Logging (Python) Source: https://github.com/structuredlabs/preswald/blob/main/docs/workflow/workflow.mdx This code block shows an example of the source code after Preswald's automatic transformation, as seen in debug logs. It demonstrates how top-level statements are converted into decorated workflow atoms with generated names and inferred dependencies. This illustrates the underlying mechanism that enables full reactivity from minimal Python scripts. ```python 2025-05-05 05:50:56,327 - preswald.engine.transformers.reactive_runtime - INFO - Transformed source code: from preswald import get_df, text, slider, table from preswald import get_workflow @workflow.atom(name='_auto_atom_b4f77a63') def _auto_atom_b4f77a63(): return slider('Pick a number', min_val=0, max_val=10, default=1, component_id='slider-b4f77a63') @workflow.atom(name='_auto_atom_d93912c6', dependencies=['_auto_atom_b4f77a63']) def _auto_atom_d93912c6(param0): return table(df, limit=param0, component_id='table-d93912c6') workflow = get_workflow() df = get_df('iris_csv') workflow.execute() ``` -------------------------------- ### Get Parallel Execution Groups Source: https://github.com/structuredlabs/preswald/blob/main/docs/workflow/workflow_analyzer.mdx Identifies groups of workflow atoms that can be executed concurrently. This helps in optimizing workflow execution by leveraging parallel processing opportunities. ```APIDOC def get_parallel_groups(self) -> List[Set[str]]: Returns: parallel_groups (list of sets): Each subset contains atom names that can be computed simultaneously. ``` -------------------------------- ### Retrieve Data from CSV Source with get_df Source: https://github.com/structuredlabs/preswald/blob/main/docs/data/get_df.mdx Demonstrates how to use the `get_df` function to read data from a CSV file. The example shows reading a configured CSV source and a specific CSV file directly from a path. ```python from preswald import get_df # Read entire CSV file customers_df = get_df('eq_csv') # Or, read specific CSV file customers_df = get_df('data/sample.csv') ``` -------------------------------- ### Applying Custom Styling to Preswald Image Source: https://github.com/structuredlabs/preswald/blob/main/docs/displays/image.mdx Shows how to enhance the appearance of an image by applying custom CSS classes using the `className` property. This example adds rounded corners and a shadow effect to the image. ```python import preswald as pw def app(): pw.image( src="https://example.com/image.jpg", alt="Styled image", className="rounded-lg shadow-md" ) pw.run(app) ``` -------------------------------- ### Handle Errors During Data Retrieval with get_df Source: https://github.com/structuredlabs/preswald/blob/main/docs/data/get_df.mdx Provides an example of using `try-except` blocks to gracefully handle potential `ValueError` for configuration issues or general exceptions that may occur when calling the `get_df` function. ```python from preswald import get_df try: df = get_df('eq_pg', 'large_table') except ValueError as e: print(f"Configuration error: {e}") except Exception as e: print(f"Error retrieving data: {e}") ``` -------------------------------- ### Arrange Multiple Components in a Row using Python Source: https://github.com/structuredlabs/preswald/blob/main/docs/layout/sizing.mdx This Python example demonstrates how to use the `size` parameter with `preswald` components like `slider` and `button` to arrange multiple elements side-by-side in a single row. It shows two sliders sharing a row with `size=0.5` each, and a button and slider sharing a row with `size=0.3` and `size=0.7` respectively, illustrating how to manage horizontal space. ```python from preswald import slider, button # Two sliders sharing a row slider1 = slider("Filter 1", min_val=0.0, max_val=10.0, default=5.0, size=0.5) slider2 = slider("Filter 2", min_val=0.0, max_val=10.0, default=5.0, size=0.5) # Button and slider sharing a row submit_button = button("Submit", size=0.3) threshold_slider = slider("Threshold", min_val=0.0, max_val=100.0, default=50.0, size=0.7) ``` -------------------------------- ### Get Workflow Critical Path Source: https://github.com/structuredlabs/preswald/blob/main/docs/workflow/workflow_analyzer.mdx Identifies the critical path within the workflow. This path represents the longest sequence of dependent atoms, determining the minimum total execution time and highlighting bottlenecks. ```APIDOC def get_critical_path(self) -> List[str]: Returns: critical_path (list): A list of atom names in the critical path. ``` -------------------------------- ### Example: Manual Dependency Declaration in Workflow Atoms Source: https://github.com/structuredlabs/preswald/blob/main/docs/workflow/workflow.mdx Demonstrates how to explicitly declare dependencies between atoms using the `dependencies` argument in the `@workflow.atom()` decorator. This ensures a specific execution order, even if the output of the dependency is not directly consumed, which is useful for side effects or when dependencies cannot be inferred. ```python @workflow.atom() def task_a(): return text("A") @workflow.atom(dependencies=['task_a']) def task_b(task_a): return text("B") workflow.execute() ``` -------------------------------- ### Define Workflow Atoms with Automatic Dependency Inference (Python) Source: https://github.com/structuredlabs/preswald/blob/main/docs/workflow/workflow.mdx This Python example demonstrates how Preswald automatically infers dependencies between workflow atoms. When one atom's parameter name matches another atom's name, Preswald establishes a dependency, ensuring that `show_value` recomputes only when `select_value` changes. This simplifies reactive programming by eliminating manual dependency declarations. ```python @workflow.atom() def select_value(): return slider("Pick a number", min_val=0, max_val=10, default=1) @workflow.atom() def show_value(select_value): return text(f"You picked: {select_value}") workflow.execute() ``` -------------------------------- ### Embed Plotly Bar Chart in Python Source: https://github.com/structuredlabs/preswald/blob/main/docs/displays/plotly.mdx Illustrates embedding a bar chart using the `plotly` function. This example uses Plotly Express to create a simple bar chart from dictionary data and then embeds it into the application. ```python from preswald import plotly import plotly.express as px # Data for the chart data = {"Category": ["A", "B", "C"], "Values": [10, 20, 30]} fig = px.bar(data, x="Category", y="Values", title="Sample Bar Chart") # Embed the bar chart plotly(fig) ``` -------------------------------- ### Lift Top-Level Producer Assignments to Workflow Atoms (Python) Source: https://github.com/structuredlabs/preswald/blob/main/docs/workflow/workflow.mdx This example shows how Preswald automatically lifts top-level assignments that depend on reactive inputs into workflow atoms. The `double` variable, which is derived from the reactive `base` slider, becomes part of the reactive graph. This ensures that `double` is recomputed efficiently whenever `base` changes, without explicit atom decoration. ```python base = slider("Base", min_val=1, max_val=10) double = base * 2 ``` -------------------------------- ### Preswald CLI: `init` Command Reference Source: https://github.com/structuredlabs/preswald/blob/main/docs/cli/init.mdx Detailed documentation for the `preswald init` command, which initializes a new project directory and generates boilerplate files. It requires a project name and creates a standard set of files and directories for a Preswald application. ```APIDOC Command: preswald init Arguments: project_name (str): The name of the new project. Generated Files: hello.py: Starter application script. preswald.toml: Configuration file for your app. secrets.toml: Secure file for storing sensitive data. Workbook.md: Markdown notes describing your Preswald project. data/: Directory for some sample data. images/: Directory with logo, favicon, and readme gif. ``` -------------------------------- ### Launch Preswald Development Server Source: https://github.com/structuredlabs/preswald/blob/main/docs/cli/run.mdx Demonstrates how to launch the Preswald local development server using the `preswald run` command, including options for port, log level, and disabling new tab opening. ```bash preswald run ``` ```bash preswald run --port 8504 --log-level DEBUG --disable-new-tab ``` -------------------------------- ### Run Preswald Application Source: https://github.com/structuredlabs/preswald/blob/main/examples/iris/README.md Execute the Preswald application from the command line. This command initiates the application after all necessary configuration files have been set up. ```Shell preswald run ``` -------------------------------- ### Run Preswald Application Source: https://github.com/structuredlabs/preswald/blob/main/examples/fires/README.md Executes the Preswald application from the command line after initial configuration steps are completed. ```Shell preswald run ``` -------------------------------- ### Default Preswald Project Configuration Source: https://github.com/structuredlabs/preswald/blob/main/docs/configuration.mdx Illustrates the default structure of the `preswald.toml` file created during project initialization, defining core settings for project, branding, data connections, and logging. ```toml [project] title = "Preswald Project" version = "0.1.0" port = 8501 slug = "preswald-project" entrypoint = "hello.py" [branding] name = "Preswald Project" logo = "images/logo.png" favicon = "images/favicon.ico" primaryColor = "#F89613" [data.sample_csv] type = "csv" path = "data/sample.csv" [logging] level = "INFO" # Options: DEBUG, INFO, WARNING, ERROR, CRITICAL format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" ``` -------------------------------- ### Run Preswald Application Source: https://github.com/structuredlabs/preswald/blob/main/examples/network/README.md Executes the Preswald application. Ensure `preswald.toml` is configured for data connections and `secrets.toml` for sensitive information before running. ```Shell preswald run ``` -------------------------------- ### Configure PostgreSQL Data Source in Preswald Source: https://github.com/structuredlabs/preswald/blob/main/docs/configuration.mdx Explains how to set up a PostgreSQL database connection in `preswald.toml`, including host, port, database name, and user. Notes that the password should be stored in `secrets.toml`. ```toml # preswald.toml [data.earthquake_db] type = "postgres" host = "localhost" # PostgreSQL host port = 5432 # PostgreSQL port dbname = "earthquakes" # Database name user = "user" # Username #secrets.toml [data.earthquake_db] password = "" ``` -------------------------------- ### Preswald Project and Branding Configuration Fields Source: https://github.com/structuredlabs/preswald/blob/main/docs/configuration.mdx Details the configurable fields within the `[project]` and `[branding]` sections of `preswald.toml`, including application title, version, port, reactivity settings, branding name, logo, favicon, and primary UI color. ```APIDOC [project] title: Name of the app displayed in the interface. version: Version of the app. port: Port the app runs on (default is 8501). disable_reactivity (optional): Set to true to disable Preswald’s reactive runtime. When disabled, Preswald will rerun the entire script on every update instead of selectively recomputing affected parts using its dependency graph (DAG). This can be useful for debugging, performance benchmarking, or in environments where reactivity fallback is expected. [branding] name: Displayed name of the app. logo: Path to the logo file (relative to the project directory). favicon: Path to the favicon file. primaryColor: The primary UI color, specified as a CSS-compatible color (e.g., #3498db). ``` -------------------------------- ### Clone Preswald Repository Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Instructions to clone the forked Preswald repository from GitHub to your local machine and navigate into the project directory. ```bash git clone https://github.com/StructuredLabs/preswald.git cd preswald ``` -------------------------------- ### Basic Call to topbar() Source: https://github.com/structuredlabs/preswald/blob/main/docs/layout/topbar.mdx A simple demonstration of calling the `topbar()` function. ```python topbar() ``` -------------------------------- ### Build Preswald Frontend Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Command to perform a one-time build of the Preswald frontend using the project's Python build script. ```bash python -m preswald.build frontend ``` -------------------------------- ### Export Preswald App to Static Site Source: https://github.com/structuredlabs/preswald/blob/main/README.md This command builds your Preswald application into a static site within the `dist/` directory. The generated folder contains all necessary files to run the app locally or share it, bundling Python code, data, and DuckDB queries for offline use in any modern browser. ```bash preswald export ``` -------------------------------- ### Create and Activate Python Virtual Environment (venv) Source: https://github.com/structuredlabs/preswald/blob/main/docs/usage/troubleshooting.mdx Set up and activate a new isolated Python virtual environment using the `venv` module to manage project dependencies. Commands are provided for both macOS/Linux and Windows. ```bash python -m venv env ``` ```bash source env/bin/activate ``` ```bash env\Scripts\activate ``` -------------------------------- ### Create and Activate Conda Environment Source: https://github.com/structuredlabs/preswald/blob/main/docs/usage/troubleshooting.mdx Set up and activate a new isolated Python environment using Conda to manage project dependencies, specifying the desired Python version. ```bash conda create --name myenv python=3.9 ``` ```bash conda activate myenv ``` -------------------------------- ### Exporting Preswald Application to Static Site Source: https://github.com/structuredlabs/preswald/blob/main/docs/cli/export.mdx The `export` command builds your Preswald app into a static site that can be run locally or shared with others. It creates a `dist/` directory containing all the files needed to run your app as a static site, including bundled Python code, application data, UI components, and dependencies. ```bash preswald export ``` -------------------------------- ### Initialize WorkflowAnalyzer Source: https://github.com/structuredlabs/preswald/blob/main/docs/workflow/workflow_analyzer.mdx Initializes a new instance of the `WorkflowAnalyzer` class. Requires a `preswald.Workflow` object to be passed for analysis. ```APIDOC def __init__(self, workflow): Parameters: workflow (preswald.Workflow object): The workflow object to be analyzed. ``` -------------------------------- ### Configure Clickhouse Data Source in Preswald Source: https://github.com/structuredlabs/preswald/blob/main/docs/configuration.mdx Details how to configure a Clickhouse database connection in `preswald.toml`, specifying host, port, database name, and user. Highlights that the password should be in `secrets.toml`. ```toml # preswald.toml [data.eq_clickhouse] type = "clickhouse" host = "localhost" port = 8123 database = "default" user = "default" # secrets.toml [data.eq_clickhouse] password = "" ``` -------------------------------- ### Basic Usage of Preswald Image Widget Source: https://github.com/structuredlabs/preswald/blob/main/docs/displays/image.mdx Demonstrates the fundamental way to display an image in a Preswald application using a remote URL. It initializes a Preswald application and adds an image with a source and alternative text. ```python import preswald as pw def app(): pw.image(src="https://example.com/image.jpg", alt="Example image") pw.run(app) ``` -------------------------------- ### Run Ruff for Python Formatting and Linting Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Commands to manually run 'ruff' for formatting Python code and fixing linting issues, though typically automated by pre-commit hooks. ```bash ruff format ``` ```bash ruff check --fix ``` -------------------------------- ### topbar() Function API Reference Source: https://github.com/structuredlabs/preswald/blob/main/docs/layout/topbar.mdx Detailed API documentation for the `topbar()` function, including its parameters and return values. ```APIDOC topbar() Parameters: - None Returns: - topbar component object ``` -------------------------------- ### Configure Parquet Data Source in Preswald Source: https://github.com/structuredlabs/preswald/blob/main/docs/configuration.mdx Illustrates how to configure a Parquet file as a data source in `preswald.toml`, supporting local files and optional column subset loading for performance. ```APIDOC [data.sample_parquet] type: Use "parquet". path: Path to a local .parquet file (absolute or relative). columns (optional): List of column names to load as a subset. Useful for large files with many columns. ``` -------------------------------- ### Preswald Project Configuration File (TOML) Source: https://github.com/structuredlabs/preswald/blob/main/README.md This TOML configuration file defines the core settings for a Preswald application, including project metadata, UI branding, and logging parameters. It specifies the application's title, version, port, entrypoint, branding elements like logo and colors, and logging level and format. ```TOML [project] title = "Preswald Project" version = "0.1.0" port = 8501 slug = "preswald-project" entrypoint = "hello.py" [branding] name = "Preswald Project" logo = "images/logo.png" favicon = "images/favicon.ico" primaryColor = "#F89613" [logging] level = "INFO" # Options: DEBUG, INFO, WARNING, ERROR, CRITICAL format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" ``` -------------------------------- ### Run Preswald Application Source: https://github.com/structuredlabs/preswald/blob/main/examples/user_event/README.md This command executes the Preswald application, leveraging the `preswald` command-line tool to run a specified Python script. It assumes prior configuration of `preswald.toml` and `secrets.toml` for data connections and sensitive information. ```Shell preswald run hello.py ``` -------------------------------- ### Resolve Common GCloud CLI Issues Source: https://github.com/structuredlabs/preswald/blob/main/docs/usage/troubleshooting.mdx Address common Google Cloud CLI problems such as authentication failures and incorrect project configuration by running the respective commands. ```bash gcloud auth login ``` ```bash gcloud config set project ``` -------------------------------- ### Python Best Practice: Selecting Columns for table Source: https://github.com/structuredlabs/preswald/blob/main/docs/displays/table.mdx Shows how to select specific columns from a DataFrame before passing it to `table` to enhance readability and focus on relevant data, especially when dealing with wide datasets. ```python table(df[['Name', 'Age', 'City']]) ``` -------------------------------- ### Create and Activate Conda Environment for Preswald Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Commands to create a new Conda environment named 'preswald' with Python 3.10 and activate it for development. ```bash conda create -n preswald python=3.10 -y conda activate preswald ``` -------------------------------- ### Configure CSV Data Source in Preswald Source: https://github.com/structuredlabs/preswald/blob/main/docs/configuration.mdx Demonstrates how to define local or remote CSV files as data sources in `preswald.toml`, specifying the type and path. ```toml [data.customers_csv] type = "csv" path = "data/customers.csv" [data.sample_csv] type = "csv" path = "https://storage.googleapis.com/test/sample_data.csv" ``` -------------------------------- ### Update Preswald Python Package Source: https://github.com/structuredlabs/preswald/blob/main/docs/usage/troubleshooting.mdx Upgrade the Preswald Python package to its latest version using pip to ensure you have the most recent features and bug fixes. ```bash pip install --upgrade preswald ``` -------------------------------- ### Run ESLint for JavaScript Linting Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Command to run ESLint for linting JavaScript code, typically configured as an npm script. ```bash npm run lint ``` -------------------------------- ### Configure JSON Data Source in Preswald Source: https://github.com/structuredlabs/preswald/blob/main/docs/configuration.mdx Shows how to connect to a JSON file, including optional parameters for `record_path` to extract nested records and `flatten` for structure normalization. ```toml [data.sample_json] type = "json" path = "data/sample.json" record_path = "results.items" # Optional: Path to the records within the JSON flatten = true # Optional: Set to false to retain nested structures ``` -------------------------------- ### selectbox Function API Reference Source: https://github.com/structuredlabs/preswald/blob/main/docs/controls/selectbox.mdx Comprehensive API documentation for the `selectbox` function, detailing its signature, parameters, and return value. ```APIDOC selectbox( label: str, options: List[str], default: Optional[str] = None, size: float = 1.0 ) -> str Parameters: label (str): The label displayed above the dropdown, describing its purpose. options (list): A list of options that users can select from. default (str) (Optional): The default option. Must be one of the options provided. size (float) (Optional): The width of the component in a row. Defaults to 1.0 (full row). Returns: str: The current selected value. ``` -------------------------------- ### Push Git Branch to Fork Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Command to push local changes from a feature branch to the remote fork on GitHub. ```bash git push origin feature/your-feature-name ``` -------------------------------- ### CSS Styling for FastAPI Browser Demo Source: https://github.com/structuredlabs/preswald/blob/main/tests/fastapi_test.html Defines the visual styles for the FastAPI application running in the browser, including general layout, button appearance, and the display of API output and endpoint sections. ```CSS body { font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.6; } .container { display: flex; flex-direction: column; gap: 20px; } button { padding: 8px 16px; background-color: #4caf50; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; } button:hover { background-color: #45a049; } #output { padding: 15px; background-color: #f5f5f5; border-radius: 4px; min-height: 200px; white-space: pre-wrap; overflow-y: auto; border: 1px solid #ddd; } .endpoint { padding: 15px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 10px; } .method { display: inline-block; padding: 3px 6px; border-radius: 3px; color: white; font-weight: bold; margin-right: 10px; } .get { background-color: #61affe; } .post { background-color: #49cc90; } .loading { color: #666; font-style: italic; } ``` -------------------------------- ### Querying ClickHouse Data with preswald.query Source: https://github.com/structuredlabs/preswald/blob/main/docs/data/query.mdx Shows how to use the `query` function to execute SQL queries against a configured ClickHouse database, aggregating daily event counts. ```python from preswald import query # Query ClickHouse table sql = """ SELECT toDate(timestamp) as date, count() as event_count FROM events GROUP BY date ORDER BY date DESC LIMIT 7 """ daily_events = query(sql, 'eq_clickhouse') ``` -------------------------------- ### Check Docker and GCloud Application Logs Source: https://github.com/structuredlabs/preswald/blob/main/docs/usage/troubleshooting.mdx Access detailed error messages from Docker container logs and Google Cloud App Engine logs to diagnose issues and identify root causes. ```bash docker logs ``` ```bash gcloud app logs read ``` -------------------------------- ### Querying PostgreSQL Data with preswald.query Source: https://github.com/structuredlabs/preswald/blob/main/docs/data/query.mdx Illustrates how to use the `query` function to execute SQL queries directly against a configured PostgreSQL database, retrieving specific event data. ```python from preswald import query # Query PostgreSQL table sql = """ SELECT date, magnitude, location FROM earthquake_events WHERE magnitude > 5.0 ORDER BY magnitude DESC LIMIT 10 """ major_earthquakes = query(sql, 'eq_pg') ``` -------------------------------- ### Clear Old Preswald Build Artifacts Source: https://github.com/structuredlabs/preswald/blob/main/CONTRIBUTING.md Command to remove existing build directories and Python egg-info files, ensuring a clean slate before a new build process. ```bash rm -rf dist/ build/ *.egg-info ``` -------------------------------- ### RetryPolicy Class API Reference Source: https://github.com/structuredlabs/preswald/blob/main/docs/workflow/retrypolicy.mdx Detailed API documentation for the `RetryPolicy` class, including its constructor, parameters, and methods for managing retry logic within workflows. ```APIDOC class RetryPolicy __init__(self, max_attempts: int = 3, delay: float = 1.0, backoff_factor: float = 2.0, retry_exceptions: tuple = (Exception,)) max_attempts: Maximum number of retry attempts. Default: 3 delay: Initial delay in seconds between retry attempts. Default: 1.0 backoff_factor: Multiplier to increase delay between each failed attempt. Default: 2.0 retry_exceptions: Specific exceptions on which retries are attempted. By default, retries are attempted on all exceptions (Exception). Default: (Exception,) Description: If no custom retry policy is provided, the defaults above are used. should_retry(self, attempt: int, error: Exception) -> bool Description: Determines if another retry attempt should be made. get_delay(self, attempt: int) -> float Description: Calculate the delay before the next retry attempt. ```