示例#1
0
    def test_set_option(self):
        """Test streamlit.set_option."""
        # This is set in lib/tests/conftest.py to off
        self.assertEqual("off", st.get_option("global.sharingMode"))

        st.set_option("global.sharingMode", "s3")
        self.assertEqual("s3", st.get_option("global.sharingMode"))
示例#2
0
    def test_set_option_scriptable(self):
        """Test that scriptable options can be set from API."""
        # This is set in lib/tests/conftest.py to off
        self.assertEqual(True, st.get_option("client.displayEnabled"))

        # client.displayEnabled and client.caching can be set after run starts.
        st.set_option("client.displayEnabled", False)
        self.assertEqual(False, st.get_option("client.displayEnabled"))
示例#3
0
    def test_set_option(self):
        """Test streamlit.set_option."""
        # This is set in lib/tests/conftest.py to off
        self.assertEqual('off', st.get_option('global.sharingMode'))

        st.set_option('global.sharingMode', 'streamlit-public')
        self.assertEqual('streamlit-public',
                         st.get_option('global.sharingMode'))
示例#4
0
    def test_set_option_unscriptable(self):
        """Test that unscriptable options cannot be set with st.set_option."""
        # This is set in lib/tests/conftest.py to off
        self.assertEqual(True, st.get_option("server.enableCORS"))

        with self.assertRaises(StreamlitAPIException):
            st.set_option("server.enableCORS", False)
示例#5
0
def show_utilities() -> None:
    st.header("Utility functions")

    st.subheader("Show help for an object")
    with st.echo():
        if st.button("Show help"):
            st.help(pd.DataFrame)

    st.markdown('-' * 6)

    st.subheader("Placeholder")
    with st.echo():
        placeholder = st.empty()
        st.info("This message was created **after** the placeholder!")
        choice = st.radio("Option", [None, 'markdown', 'dataframe'])

        if choice == "markdown":
            placeholder.markdown("This was written at a later point in time :wave:")
        elif choice == "dataframe":
            placeholder.dataframe(pd.DataFrame(np.random.randint(0, 100, size=(5, 4)), columns=list('ABCD')))

    st.markdown('-' * 6)

    st.subheader("Get and set options")

    st.write("""Show and change options for streamlit.  
    Available options can be viewed by entering `streamlit config show` in the terminal.  
    Option key has structure `section.optionName`.
    """)

    st.code("""
    ...
    [server]
    ...
    # Max size, in megabytes, for files uploaded with the file_uploader.
    # Default: 200
    maxUploadSize = 200
    ...
    """)

    with st.echo():
        up_size = st.get_option("server.maxUploadSize")
        st.write(f"Maximum upload size upload size is `{up_size} MB`")

    st.write("""
    #### Updating client settings 
    Changing config options currently works ony for client options, i.e.:
    * client.caching
    * client.displayEnabled
    """)
示例#6
0
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import streamlit as st

if st.button("Rerun test"):
    st.test_run_count = -1

if hasattr(st, "test_run_count"):
    st.test_run_count += 1
else:
    st.test_run_count = 0 if st.get_option("server.headless") else -1

if st.test_run_count < 1:
    w1 = st.slider("label", 0, 100, 25, 1)
else:
    w1 = st.selectbox("label", ("m", "f"), 1)

st.write("value 1:", w1)
st.write("test_run_count:", st.test_run_count)
st.write("""
    If this is failing locally, it could be because you have a browser with
    Streamlit open. Close it and the test should pass.
""")
# TODO: Use session-specific state for test_run_count, to fix the issue above.
示例#7
0
 def test_get_option(self):
     """Test streamlit.get_option."""
     # This is set in lib/tests/conftest.py to False
     self.assertEqual(False, st.get_option("browser.gatherUsageStats"))
示例#8
0
import datetime
import pandas as pd
from urllib.error import HTTPError
import streamlit as st
from time import sleep
import ffn
st.set_option('deprecation.showPyplotGlobalUse', False)
st.set_page_config(layout="wide",
                   page_icon=":art:",
                   page_title="Custom Theming")
blank, title_col, blank = st.beta_columns([2, 3.5, 2])
st.get_option("theme.primaryColor")
txt_clr = st.get_option("theme.textColor")
# Idea tab:
# LSTM preditction
# RNN Prediction
# Impliment other quant libraries
# Link Articles and possibly summarise them as recent news
# Moving Averages

# Custom Back ground
# st.markdown('<style>body{background-color: #93AFC0;}</style>', unsafe_allow_html=True)
# st.markdown(
#     """
# <style>
# .sidebar .sidebar-content {
#     background-image: linear-gradient(#7B9AB8,#7B9AB8);
#     color: white;
# }
# </style>
# """,
示例#9
0
 def test_arrow_is_default(self):
     """The 'arrow' config option is the default."""
     self.assertEqual("arrow",
                      streamlit.get_option("global.dataFrameSerialization"))
示例#10
0

def check_variables(
        variables,
        values):  #  https://codereview.stackexchange.com/a/259505/230104
    for variable, flag in variables.items():
        if flag != (variable in values):
            return False
    return True


##########
# Styles #
##########

primaryColor = st.get_option("theme.primaryColor")
s = f"""
<style>
@import url('https://fonts.googleapis.com/css2?family=Atma:wght@600&display=swap');
div.stButton > button:first-child {{ border: 5px solid {primaryColor}; border-radius:20px 20px 20px 20px; }}
<style>
"""
st.markdown(s, unsafe_allow_html=True)

##############
# Dictionary #
##############

strings = {
    'বাংলা': {
        'title':
示例#11
0
def image_crop(
    image: Union[bytes, Image],
    crop: Optional[Crop] = None,
    width_preview: Optional[int] = None,
    image_alt: Optional[str] = None,
    min_width: Optional[int] = None,
    min_height: Optional[int] = None,
    max_width: Optional[int] = None,
    max_height: Optional[int] = None,
    # FIXME: Changing these properties, the component is rerendered unfortunately.
    # ----
    # keep_selection: Optional[bool] = None,
    # disabled: Optional[bool] = None,
    # locked: Optional[bool] = None,
    rule_of_thirds: Optional[bool] = None,
    circular_crop: Optional[bool] = None,
    # ----
    key: Optional[str] = None,
) -> Optional[Image]:
    import dataclasses
    from io import BytesIO
    from os import path

    import streamlit as st
    from PIL.Image import composite as composite_image
    from PIL.Image import new as new_image
    from PIL.Image import open as open_image
    from PIL.ImageDraw import Draw
    from streamlit.components import v1 as components
    from streamlit.elements.image import image_to_url

    global _impl

    if _impl is None:
        if _DEBUG:
            option_address = st.get_option("browser.serverAddress")
            option_port = st.get_option("browser.serverPort")
            _impl = (
                components.declare_component(
                    "image_crop",
                    url="http://localhost:3001",
                ),
                lambda s: f"http://{option_address}:{option_port}" + s,
            )
        else:
            _impl = (
                components.declare_component(
                    "image_crop",
                    path=path.join(path.dirname(path.abspath(__file__)),
                                   "frontend/build"),
                ),
                lambda s: s,
            )

    if isinstance(image, Image):
        image_ = image
    else:
        image_ = open_image(BytesIO(image))

    width, _ = image_.size

    src = image_to_url(
        image_,
        width=min(width, width_preview) if width_preview else width,
        clamp=False,
        channels="RGB",
        output_format="auto",
        image_id="foo",
    )

    crop_ = None if crop is None else dataclasses.asdict(crop)

    default = {
        "width": 0.0,
        "height": 0.0,
        "x": 0.0,
        "y": 0.0,
    }

    component, build_url = _impl

    result = component(
        src=build_url(src),
        image_alt=image_alt,
        minWidth=min_width,
        minHeight=min_height,
        maxWidth=max_width,
        maxHeight=max_height,
        # FIXME: Changing these properties, the component is rerendered unfortunately.
        # ----
        keepSelection=None,
        disabled=None,
        locked=None,
        ruleOfThirds=rule_of_thirds,
        circularCrop=circular_crop,
        # ----
        crop=crop_,
        key=key,
        default=default,
    )

    w, h = image_.size

    w_crop = int(w * float(result["width"]) / 100)
    h_crop = int(h * float(result["height"]) / 100)
    x0 = int(w * float(result["x"]) / 100)
    y0 = int(h * float(result["y"]) / 100)
    x1 = x0 + w_crop
    y1 = y0 + h_crop

    if w_crop <= 0 or h_crop <= 0:
        return None
    else:
        image_crop = image_.crop((x0, y0, x1, y1))
        if circular_crop:
            background = new_image("RGBA", (w_crop, h_crop), (0, 0, 0, 0))
            mask = new_image("L", (w_crop, h_crop), 0)
            draw = Draw(mask)
            draw.ellipse((0, 0, w_crop, h_crop), fill="white")
            image_crop = composite_image(image_crop, background, mask)

        return image_crop