Code Monkey home page Code Monkey logo

streamlit-condition-tree's Introduction

Based on react-awesome-query-builder

Check out live demo !

This component allows users to build complex condition trees that can be used to filter a dataframe or build a query.

preview

Install

pip install streamlit-condition-tree

Features

  • Highly configurable
  • Fields can be of type:
    • simple (string, number, bool, date/time/datetime, list)
    • structs (will be displayed in selectbox as tree)
  • Comparison operators can be:
    • binary (== != < > ..)
    • unary (is empty, is null)
    • 'between' (for numbers, dates, times)
    • complex operators like 'proximity'
  • RHS can be:
    • values
    • another fields (of same type)
    • functions (arguments also can be values/fields/funcs)
  • LHS can be field or function
  • Reordering (drag-n-drop) support for rules and groups of rules
  • Export to MongoDb, SQL, JsonLogic, SpEL or ElasticSearch

Basic usage

Filter a dataframe

import pandas as pd
from streamlit_condition_tree import condition_tree, config_from_dataframe

# Initial dataframe
df = pd.DataFrame({
    'First Name': ['Georges', 'Alfred'],
    'Age': [45, 98],
    'Favorite Color': ['Green', 'Red'],
    'Like Tomatoes': [True, False]
})

# Basic field configuration from dataframe
config = config_from_dataframe(df)

# Condition tree
query_string = condition_tree(
  config,
  always_show_buttons=True,
  placeholder="Empty condition tree"
)

# Filtered dataframe
df = df.query(query_string)

Build a query

import streamlit as st
from streamlit_condition_tree import condition_tree

# Build a custom configuration
config = {
    'fields': {
        'name': {
            'label': 'Name',
            'type': 'text',
        },
        'age': {
            'label': 'Age',
            'type': 'number',
            'fieldSettings': {
                'min': 0
            },
        },
        'like_tomatoes': {
            'label': 'Likes tomatoes',
            'type': 'boolean',
        }
    }
}

# Condition tree
return_val = condition_tree(
    config,
    return_type='sql'
)

# Generated SQL
st.write(return_val)

API

Parameters

def condition_tree(
    config: dict,
    return_type: str [Optional],
    tree: dict [Optional],
    min_height: int [Optional],
    placeholder: str [Optional],
    always_show_buttons: bool [Optional],
    key: str [Optional]
)
  • config: Python dictionary (mostly used to define the fields) that resembles the JSON counterpart of the React component.

A basic configuration can be built from a DataFrame with config_from_dataframe.
For a more advanced configuration, see the component doc and demo. Custom javascript functions must be wrapped into the JsCode class (see Advanced config)

  • return_type: Format of the returned value :

    • queryString
    • mongodb
    • sql
    • spel
    • elasticSearch
    • jsonLogic

    Default : queryString (can be used to filter a pandas DataFrame using DataFrame.query)

  • tree: Input condition tree (see section below)

    Default : None

  • min_height: Minimum height of the component frame

    Default : 400

  • placeholder: Text displayed when the condition tree is empty

    Default : None

  • always_show_buttons: Show buttons (create rule, etc.) even when they are not hovered

    Default: False

  • key: Fixed identity if you want to change its arguments over time and not have it be re-created.
    Can also be used to access the generated condition tree (see section below).

    Default : None

Export & import a condition tree

When a key is defined for the component, the condition tree generated is accessible through st.session_state[key] as a dictionary.
It can be loaded as an input tree through the tree parameter.

streamlit-condition-tree's People

Contributors

cedricvlt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

streamlit-condition-tree's Issues

Issue with streamlit-condition-tree Component Not Updating Correctly with "config"


Description

I'm experiencing an issue with the streamlit-condition-tree component in my Streamlit application where the component does not seem to update correctly with its configuration. Initially, the component displays a default "index in index" query string, and then it should update based on user interaction and configuration changes. However, this update does not seem to occur as expected.
Steps to Reproduce

  • Initialize the streamlit-condition-tree component with a DataFrame configuration.
  • Run the Streamlit application.
  • Interact with the component or trigger an update.
  • Observe that the component does not update as expected and remains at the default state.

Expected Behavior

Upon interaction or receiving new configuration data, the streamlit-condition-tree component should update and reflect the changes based on user input or updated configuration.


Current Behavior

The component initializes with a default "index in index" state but does not update as expected with user interactions or when provided with new configuration data.


Environment

Streamlit version: 1.28.2
streamlit-condition-tree version: 0.1.2
Browser version: Chrome Version 119.0.6045.159 (Official Build) (64-bit) / Firefox 119.0.1 (64-bit)
Operating System: Ubuntu 22.04.3 LTS

Additional Context and Observations

The debug logs show that the component is registered and the script reruns on interaction, but the component's state does not seem to update with the new configuration.
Initial tests with different configurations suggest that the issue might be related to how the component's state is managed in Streamlit's reactive framework.
I have tried various troubleshooting steps, including checking the component's initialization, ensuring correct configuration formats, and testing in different environments (local and deployed).


I really appreciate the functionality that streamlit-condition-tree brings to Streamlit applications, and I'm eager to resolve this issue. Any insights or suggestions from the community or maintainers would be incredibly helpful.

Thank you for your time and effort in developing and maintaining this useful component.

Condition Tree does not accept updated config when using a key

When setting a key for the condition_tree(), upon rerunning the app and updating the config (i.e. table changes), the dropdown of available fields does not change. Even deleting the session state key before calling condition_tree() does not change the available fields.

Code:

config = config_from_dataframe(table)

# Optional, does not affect results
if 'condition_tree' in st.session_state:
        del st.session_state['condition_tree']

 query_string = condition_tree(config,
        min_height = 400,
        placeholder = 'No rules created',
        always_show_buttons = True,
        key = 'condition_tree'
        )

Basically, even if my table changes in this code, the condition tree will still hold on to the old config. This does not happen when not using a key. My intention with using the key is to be able to save the query and recall it at a different time.

Typing Crashes Streamlit App

Hi!

I've been able to reproduce a rather unique bug, it seems like typing fast in text fields or even typing at normal speed in larger trees crashes the component and renders the entire tree empty.

My understanding is that Streamlit is rerunning code whenever a field receives input (every key) and that may be the culprit, potentially debouncing user input could fix it but I can't determine whether this is a Streamlit issue, a streamlit-condition-tree issue or the actual react library issue.

I've recorded a Jam showcasing this happening in the official demo page here.

Doesn't appear to work with Streamlit 1.33.0 using pages.

I stuck "example.py" inside of pages folder using latest 1.33.0

import streamlit as st
import pandas as pd
from streamlit_condition_tree import condition_tree, config_from_dataframe

# Initial dataframe
df = pd.DataFrame({
    'First Name': ['Georges', 'Alfred'],
    'Age': [45, 98],
    'Favorite Color': ['Green', 'Red'],
    'Like Tomatoes': [True, False]
})

# Basic field configuration from dataframe
config = config_from_dataframe(df)

# Condition tree
query_string = condition_tree(config)

# Filtered dataframe
df = df.query(query_string)

Output is entirely blank except for "None". Tried "Build a query too" but also didn't work.

Using Microsoft Edge browser. Python 3.11

image

Issues with Query Tree in a Form

Hello, thanks for this great Streamlit component. It has been a great addition and an elegant solution for my app.

For my use case, I have the query tree builder in a st.form. I have noticed that when it loads, the form partially cuts off the top row buttons (whether or not I specify a height). When I reload the page or interact with an UI element, this cutoff disappears. I'm hoping you can reproduce it. I can also attach a video.

Here is my minimal example:

import pandas as pd
import streamlit as st

from streamlit_condition_tree import condition_tree, config_from_dataframe

# Initial dataframe
df = pd.DataFrame(
    {
        "First Name": ["Georges", "Alfred"],
        "Age": [45, 98],
        "Favorite Color": ["Green", "Red"],
        "Like Tomatoes": [True, False],
    }
)

# Basic field configuration from dataframe
config = config_from_dataframe(df)

# Condition tree
with st.form("test"):
    query_string = condition_tree(config)
    st.form_submit_button("Submit")

Here is the result:
SCR-20240219-rzp

Streamlit app runs twice upon first opening

When I launch an app with the condition tree, it runs twice from top to bottom when using the condition tree. You can see this in the demo code provided. Not sure what is causing this, but the fork on this project has some small changes which I wonder if they are related.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.