Beispiel #1
0
    def _block(self, block_proto=Block_pb2.Block()):
        # Switch to the active DeltaGenerator, in case we're in a `with` block.
        self = self._active_dg

        if self._container is None or self._cursor is None:
            return self

        msg = ForwardMsg_pb2.ForwardMsg()
        msg.metadata.parent_block.container = self._container
        msg.metadata.parent_block.path[:] = self._cursor.path
        msg.metadata.delta_id = self._cursor.index
        msg.delta.add_block.CopyFrom(block_proto)

        # Normally we'd return a new DeltaGenerator that uses the locked cursor
        # below. But in this case we want to return a DeltaGenerator that uses
        # a brand new cursor for this new block we're creating.
        block_cursor = cursor.RunningCursor(path=self._cursor.path +
                                            (self._cursor.index, ))
        block_dg = DeltaGenerator(container=self._container,
                                  cursor=block_cursor,
                                  parent=self)

        # Must be called to increment this cursor's index.
        self._cursor.get_locked_cursor(last_index=None)
        _enqueue_message(msg)

        return block_dg
Beispiel #2
0
    def beta_expander(self, label=None, expanded=False):
        """Create a container that can be expanded and collapsed.

        Similar to `st.container`, `st.expander` provides a container
        to add elements to. However, it has the added benefit of being expandable and
        collapsible. Users will be able to expand and collapse the container that is
        identifiable with the provided label.

        Parameters
        ----------
        label : str
            A short label used as the header for the expander.
            This will always be displayed even when the container is collapsed.
        expanded : boolean
            The default state for the expander.
            Defaults to False

        Examples
        --------
        >>> expander = st.beta_expander("Expand Me")
        >>> expander.write("I can be expanded")

        """
        if label is None:
            raise StreamlitAPIException("A label is required for an expander")

        expandable_proto = Block_pb2.Block.Expandable()
        expandable_proto.expanded = expanded
        expandable_proto.label = label

        block_proto = Block_pb2.Block()
        block_proto.expandable.CopyFrom(expandable_proto)

        return self._block(block_proto=block_proto)
Beispiel #3
0
    def beta_columns(self, weights):
        """Create several columns, side-by-side.

        Parameters
        ----------
        weights : int or list of positive floats
            If a single int: lay out that many columns of equal width.

            If a list of numbers: create a column for each number.
            Each column's width is proportional to the number provided.
            For example, `st.beta_columns([3, 1, 2])` would create 3 columns of varying widths.
            The first column would be 3x the width of the second column;
            the last column would be 2x the width of the second.

        Returns
        -------
        A list of containers, each of which can have their own elements.

        Examples
        --------
        >>> col1, col2, col3 = st.beta_columns(3)
        >>> col1.write('Hello?')
        >>> col2.button('Press me!')
        >>> col3.checkbox('Good to go~')

        """
        weights_exception = StreamlitAPIException(
            "The input argument to st.beta_columns must be either a " +
            "positive integer or a list of numeric weights. " +
            "See [documentation](https://docs.streamlit.io/en/stable/api.html#streamlit.beta_columns) "
            + "for more information.")

        if isinstance(weights, int):
            # If the user provided a single number, expand into equal weights.
            # E.g. (1,) * 3 => (1, 1, 1)
            # NOTE: A negative/zero spec will expand into an empty tuple.
            weights = (1, ) * weights

        if len(weights) == 0 or any(weight <= 0 for weight in weights):
            raise weights_exception

        def column_proto(weight):
            col_proto = Block_pb2.Block()
            col_proto.column.weight = weight
            col_proto.allow_empty = True
            return col_proto

        horiz_proto = Block_pb2.Block()
        horiz_proto.horizontal.unused = True
        row = self._block(horiz_proto)
        return [row._block(column_proto(w)) for w in weights]
Beispiel #4
0
    def beta_expander(self, label=None, expanded=False):
        """Insert a multi-element container that can be expanded/collapsed.

        Inserts a container into your app that can be used to hold multiple elements
        and can be expanded or collapsed by the user. When collapsed, all that is
        visible is the provided label.

        To add elements to the returned container, you can use "with" notation
        (preferred) or just call methods directly on the returned object. See
        examples below.

        .. warning::
            Currently, you may not put expanders inside another expander.

        Parameters
        ----------
        label : str
            A string to use as the header for the expander.
        expanded : bool
            If True, initializes the expander in "expanded" state. Defaults to
            False (collapsed).

        Examples
        --------
        >>> st.line_chart({"data": [1, 5, 2, 6, 2, 1]})
        >>>
        >>> with st.beta_expander("See explanation"):
        ...     st.write(\"\"\"
        ...         The chart above shows some numbers I picked for you.
        ...         I rolled actual dice for these, so they're *guaranteed* to
        ...         be random.
        ...     \"\"\").
        ...     st.image("https://static.streamlit.io/examples/dice.jpg")

        .. output ::
            https://static.streamlit.io/0.66.0-2BLtg/index.html?id=LzfUAiT1eM9Xy8EDMRkWyF
            height: 750px

        """
        if label is None:
            raise StreamlitAPIException("A label is required for an expander")

        expandable_proto = Block_pb2.Block.Expandable()
        expandable_proto.expanded = expanded
        expandable_proto.label = label

        block_proto = Block_pb2.Block()
        block_proto.allow_empty = True
        block_proto.expandable.CopyFrom(expandable_proto)

        return self._block(block_proto=block_proto)
Beispiel #5
0
    def beta_columns(self, weights):
        """Create several columns, side-by-side.

        Parameters
        ----------
        weights : int or list of numbers
            If a single int: lay out that many columns of equal width.

            If a list of numbers: create a column for each number.
            Each column's width is proportional to the number provided.
            For example, `st.beta_columns([3, 1, 2])` would create 3 columns of varying widths.
            The first column would be 3x the width of the second column;
            the last column would be 2x the width of the second.

        Returns
        -------
        A list of containers, each of which can have their own elements.

        Examples
        --------
        >>> col1, col2, col3 = st.beta_columns(3)
        >>> col1.write('Hello?')
        >>> col2.button('Press me!')
        >>> col3.checkbox('Good to go~')

        """

        if isinstance(weights, int):
            if weights <= 0:
                raise StreamlitAPIException(
                    "You have to create at least one column!")
            if weights == 1:
                raise StreamlitAPIException(
                    "Instead of creating only one column, use st.beta_container."
                )
            # If the user provided a single number, expand into equal weights.
            # E.g. 3 => (1, 1, 1)
            weights = (1, ) * weights

        def column_proto(weight):
            col_proto = Block_pb2.Block()
            col_proto.column.weight = weight
            col_proto.allow_empty = True
            return col_proto

        horiz_proto = Block_pb2.Block()
        horiz_proto.horizontal.unused = True
        row = self._block(horiz_proto)
        return [row._block(column_proto(w)) for w in weights]
Beispiel #6
0
    def form(self, key: str):
        """Create a form that batches elements together with a "Submit" button.

        A form is a container that visually groups other elements and
        widgets together, and contains a Submit button. When the form's
        Submit button is pressed, all widget values inside the form will be
        sent to Streamlit in a batch.

        To add elements to the returned form object, you can use "with" notation
        (preferred) or just call methods directly on the returned object. See
        examples below.

        Forms have a few constraints:
        - Every form must contain a `st.form_submit_button`.
        - You cannot add a normal `st.button` to a form.
        - Forms can appear anywhere in your app (sidebar, columns, etc),
          but they cannot be embedded inside other forms.

        Parameters
        ----------
        key : str
            A string that identifies the form. Each form must have its own
            key. (This key is not displayed to the user in the interface.)

        """

        if is_in_form(self.dg):
            raise StreamlitAPIException(
                "Forms cannot be nested in other forms.")

        # A form is uniquely identified by its key.
        form_id = key

        ctx = get_report_ctx()
        if ctx is not None:
            added_form_id = ctx.form_ids_this_run.add(form_id)
            if not added_form_id:
                raise StreamlitAPIException(_build_duplicate_form_message(key))

        block_proto = Block_pb2.Block()
        block_proto.form_id = form_id
        block_dg = self.dg._block(block_proto)

        # Attach the form's button info to the newly-created block's
        # DeltaGenerator.
        block_dg._form_data = FormData(form_id)
        return block_dg
Beispiel #7
0
    def _block(self, block_proto=Block_pb2.Block()) -> "DeltaGenerator":
        # Operate on the active DeltaGenerator, in case we're in a `with` block.
        dg = self._active_dg

        # Prevent nested columns & expanders by checking all parents.
        block_type = block_proto.WhichOneof("type")
        # Convert the generator to a list, so we can use it multiple times.
        parent_block_types = frozenset(dg._parent_block_types)
        if block_type == "column" and block_type in parent_block_types:
            raise StreamlitAPIException(
                "Columns may not be nested inside other columns."
            )
        if block_type == "expandable" and block_type in parent_block_types:
            raise StreamlitAPIException(
                "Expanders may not be nested inside other expanders."
            )

        if dg._root_container is None or dg._cursor is None:
            return dg

        msg = ForwardMsg_pb2.ForwardMsg()
        msg.metadata.delta_path[:] = dg._cursor.delta_path
        msg.delta.add_block.CopyFrom(block_proto)

        # Normally we'd return a new DeltaGenerator that uses the locked cursor
        # below. But in this case we want to return a DeltaGenerator that uses
        # a brand new cursor for this new block we're creating.
        block_cursor = cursor.RunningCursor(
            root_container=dg._root_container,
            parent_path=dg._cursor.parent_path + (dg._cursor.index,),
        )
        block_dg = DeltaGenerator(
            root_container=dg._root_container,
            cursor=block_cursor,
            parent=dg,
            block_type=block_type,
        )
        # Blocks inherit their parent form ids.
        # NOTE: Container form ids aren't set in proto.
        block_dg._form_data = FormData(current_form_id(dg))

        # Must be called to increment this cursor's index.
        dg._cursor.get_locked_cursor(last_index=None)
        _enqueue_message(msg)

        return block_dg
Beispiel #8
0
    def beta_columns(self, weights):
        if isinstance(weights, int):
            # If the user provided a single number, expand into equal weights.
            # E.g. 3 => (1, 1, 1)
            # TODO: check that the number > 0
            weights = (1, ) * weights

        def column_proto(weight):
            col_proto = Block_pb2.Block()
            col_proto.column.weight = weight
            col_proto.allow_empty = True
            return col_proto

        horiz_proto = Block_pb2.Block()
        horiz_proto.horizontal.unused = True
        row = self._block(horiz_proto)
        return [row._block(column_proto(w)) for w in weights]
Beispiel #9
0
    def _block(self, block_proto=Block_pb2.Block()):
        # Switch to the active DeltaGenerator, in case we're in a `with` block.
        self = self._active_dg

        # Prevent nested columns & expanders by checking all parents.
        block_type = block_proto.WhichOneof("type")
        # Convert the generator to a list, so we can use it multiple times.
        parent_block_types = [t for t in self._parent_block_types]
        if block_type == "column" and block_type in parent_block_types:
            raise StreamlitAPIException(
                "Columns may not be nested inside other columns.")
        if block_type == "expandable" and block_type in parent_block_types:
            raise StreamlitAPIException(
                "Expanders may not be nested inside other expanders.")

        if self._container is None or self._cursor is None:
            return self

        msg = ForwardMsg_pb2.ForwardMsg()
        msg.metadata.parent_block.container = self._container
        msg.metadata.parent_block.path[:] = self._cursor.path
        msg.metadata.delta_id = self._cursor.index
        msg.delta.add_block.CopyFrom(block_proto)

        # Normally we'd return a new DeltaGenerator that uses the locked cursor
        # below. But in this case we want to return a DeltaGenerator that uses
        # a brand new cursor for this new block we're creating.
        block_cursor = cursor.RunningCursor(path=self._cursor.path +
                                            (self._cursor.index, ))
        block_dg = DeltaGenerator(
            container=self._container,
            cursor=block_cursor,
            parent=self,
            block_type=block_type,
        )

        # Must be called to increment this cursor's index.
        self._cursor.get_locked_cursor(last_index=None)
        _enqueue_message(msg)

        return block_dg
Beispiel #10
0
    def form(self, key: str, clear_on_submit: bool = False):
        """Create a form that batches elements together with a "Submit" button.

        A form is a container that visually groups other elements and
        widgets together, and contains a Submit button. When the form's
        Submit button is pressed, all widget values inside the form will be
        sent to Streamlit in a batch.

        To add elements to a form object, you can use "with" notation
        (preferred) or just call methods directly on the form. See
        examples below.

        Forms have a few constraints:

        * Every form must contain a `st.form_submit_button`.
        * You cannot add a normal `st.button` to a form.
        * Forms can appear anywhere in your app (sidebar, columns, etc),
          but they cannot be embedded inside other forms.

        For more information about forms, check out our
        `blog post <https://blog.streamlit.io/introducing-submit-button-and-forms/>`_.

        Parameters
        ----------
        key : str
            A string that identifies the form. Each form must have its own
            key. (This key is not displayed to the user in the interface.)
        clear_on_submit : bool
            If True, all widgets inside the form will be reset to their default
            values after the user presses the Submit button. Defaults to False.
            (Note that Custom Components are unaffected by this flag, and
            will not be reset to their defaults on form submission.)

        Examples
        --------

        Inserting elements using "with" notation:

        >>> with st.form("my_form"):
        ...    st.write("Inside the form")
        ...    slider_val = st.slider("Form slider")
        ...    checkbox_val = st.checkbox("Form checkbox")
        ...
        ...    # Every form must have a submit button.
        ...    submitted = st.form_submit_button("Submit")
        ...    if submitted:
        ...        st.write("slider", slider_val, "checkbox", checkbox_val)
        ...
        >>> st.write("Outside the form")

        Inserting elements out of order:

        >>> form = st.form("my_form")
        >>> form.slider("Inside the form")
        >>> st.slider("Outside the form")
        >>>
        >>> # Now add a submit button to the form:
        >>> form.form_submit_button("Submit")

        """
        from .utils import check_session_state_rules

        if is_in_form(self.dg):
            raise StreamlitAPIException("Forms cannot be nested in other forms.")

        check_session_state_rules(default_value=None, key=key, writes_allowed=False)

        # A form is uniquely identified by its key.
        form_id = key

        ctx = get_report_ctx()
        if ctx is not None:
            added_form_id = ctx.form_ids_this_run.add(form_id)
            if not added_form_id:
                raise StreamlitAPIException(_build_duplicate_form_message(key))

        block_proto = Block_pb2.Block()
        block_proto.form.form_id = form_id
        block_proto.form.clear_on_submit = clear_on_submit
        block_dg = self.dg._block(block_proto)

        # Attach the form's button info to the newly-created block's
        # DeltaGenerator.
        block_dg._form_data = FormData(form_id)
        return block_dg
Beispiel #11
0
 def column_proto(weight):
     col_proto = Block_pb2.Block()
     col_proto.column.weight = weight
     col_proto.allow_empty = True
     return col_proto
Beispiel #12
0
    def beta_columns(self, spec):
        """Insert containers laid out as side-by-side columns.

        Inserts a number of multi-element containers laid out side-by-side and
        returns a list of container objects.

        To add elements to the returned containers, you can use "with" notation
        (preferred) or just call methods directly on the returned object. See
        examples below.

        .. warning::
            Currently, you may not put columns inside another column.

        Parameters
        ----------
        spec : int or list of numbers
            If an int
                Specifies the number of columns to insert, and all columns
                have equal width.

            If a list of numbers
                Creates a column for each number, and each
                column's width is proportional to the number provided. Numbers can
                be ints or floats, but they must be positive.

                For example, `st.beta_columns([3, 1, 2])` creates 3 columns where
                the first column is 3 times the width of the second, and the last
                column is 2 times that width.

        Returns
        -------
        list of containers
            A list of container objects.

        Examples
        --------

        You can use `with` notation to insert any element into a column:

        >>> col1, col2, col3 = st.beta_columns(3)
        >>>
        >>> with col1:
        ...    st.header("A cat")
        ...    st.image("https://static.streamlit.io/examples/cat.jpg", use_column_width=True)
        ...
        >>> with col2:
        ...    st.header("A dog")
        ...    st.image("https://static.streamlit.io/examples/dog.jpg", use_column_width=True)
        ...
        >>> with col3:
        ...    st.header("An owl")
        ...    st.image("https://static.streamlit.io/examples/owl.jpg", use_column_width=True)

        .. output ::
            https://static.streamlit.io/0.66.0-Wnid/index.html?id=VW45Va5XmSKed2ayzf7vYa
            height: 550px

        Or you can just call methods directly in the returned objects:

        >>> col1, col2 = st.beta_columns([3, 1])
        >>> data = np.random.randn(10, 1)
        >>>
        >>> col1.subheader("A wide column with a chart")
        >>> col1.line_chart(data)
        >>>
        >>> col2.subheader("A narrow column with the data")
        >>> col2.write(data)

        .. output ::
            https://static.streamlit.io/0.66.0-Wnid/index.html?id=XSQ6VkonfGcT2AyNYMZN83
            height: 400px

        """
        weights = spec
        weights_exception = StreamlitAPIException(
            "The input argument to st.beta_columns must be either a " +
            "positive integer or a list of positive numeric weights. " +
            "See [documentation](https://docs.streamlit.io/en/stable/api.html#streamlit.beta_columns) "
            + "for more information.")

        if isinstance(weights, int):
            # If the user provided a single number, expand into equal weights.
            # E.g. (1,) * 3 => (1, 1, 1)
            # NOTE: A negative/zero spec will expand into an empty tuple.
            weights = (1, ) * weights

        if len(weights) == 0 or any(weight <= 0 for weight in weights):
            raise weights_exception

        def column_proto(weight):
            col_proto = Block_pb2.Block()
            col_proto.column.weight = weight
            col_proto.allow_empty = True
            return col_proto

        horiz_proto = Block_pb2.Block()
        horiz_proto.horizontal.total_weight = sum(weights)
        row = self._block(horiz_proto)
        return [row._block(column_proto(w)) for w in weights]
Beispiel #13
0
    def form(self, key: str):
        """Create a form that batches elements together with a "Submit" button.

        A form is a container that visually groups other elements and
        widgets together, and contains a Submit button. When the form's
        Submit button is pressed, all widget values inside the form will be
        sent to Streamlit in a batch.

        To add elements to the returned form object, you can use "with" notation
        (preferred) or just call methods directly on the returned object. See
        examples below.

        Forms have a few constraints:
        - Every form must contain a `st.form_submit_button`.
        - You cannot add a normal `st.button` to a form.
        - Forms can appear anywhere in your app (sidebar, columns, etc),
          but they cannot be embedded inside other forms.

        Parameters
        ----------
        key : str
            A string that identifies the form. Each form must have its own
            key. (This key is not displayed to the user in the interface.)

        Examples
        --------

        Inserting elements using "with" notation:

        >>> with st.form("my_form"):
        ...    st.write("Inside the form")
        ...    slider_val = st.slider("Form slider")
        ...    checkbox_val = st.checkbox("Form checkbox")
        ...
        ...    # Every form must have a submit button.
        ...    submitted = st.form_submit_button("Submit")
        ...    if submitted:
        ...        st.write("slider", slider_val, "checkbox", checkbox_val)
        ...
        >>> st.write("Outside the form")

        .. output ::
            https://static.streamlit.io/0.80.0-xWVf/index.html?id=JMUHDxSEHmT9yRPNDDWAb5

        Inserting elements out of order:

        >>> form = st.form("my_form")
        >>> form.slider("Inside the form")
        >>> st.slider("Outside the form")
        >>>
        >>> # Now add a submit button to the form:
        >>> form.form_submit_button("Submit")

        .. output ::
            https://static.streamlit.io/0.80.0-xWVf/index.html?id=9DmSCcbDAfyC6dPxaKmJK4
        """

        if is_in_form(self.dg):
            raise StreamlitAPIException(
                "Forms cannot be nested in other forms.")

        # A form is uniquely identified by its key.
        form_id = key

        ctx = get_report_ctx()
        if ctx is not None:
            added_form_id = ctx.form_ids_this_run.add(form_id)
            if not added_form_id:
                raise StreamlitAPIException(_build_duplicate_form_message(key))

        block_proto = Block_pb2.Block()
        block_proto.form_id = form_id
        block_dg = self.dg._block(block_proto)

        # Attach the form's button info to the newly-created block's
        # DeltaGenerator.
        block_dg._form_data = FormData(form_id)
        return block_dg