def test_path_and_url(self): """Fail if path AND url are provided.""" with pytest.raises(StreamlitAPIException) as exception_message: components.declare_component("test", path=PATH, url=URL) self.assertEqual( "Either 'path' or 'url' must be set, but not both.", str(exception_message.value), )
def test_no_path_and_no_url(self): """Fail if neither path nor url is provided.""" with pytest.raises(StreamlitAPIException) as exception_message: components.declare_component("test", path=None, url=None) self.assertEqual( "Either 'path' or 'url' must be set, but not both.", str(exception_message.value), )
def test_name(self): """Test component name generation""" # Test a component defined in a module with no package component = components.declare_component("foo", url=URL) self.assertEqual("components_test.foo", component.name) # Test a component defined in __init__.py from component_test_data import component as init_component self.assertEqual( "component_test_data.foo", init_component.name, ) # Test a component defined in a module within a package from component_test_data.outer_module import component as outer_module_component self.assertEqual( "component_test_data.outer_module.foo", outer_module_component.name, ) # Test a component defined in module within a nested package from component_test_data.nested.inner_module import ( component as inner_module_component, ) self.assertEqual( "component_test_data.nested.inner_module.foo", inner_module_component.name, )
def test_only_url(self): """Succeed when a URL is provided.""" component = components.declare_component("test", url=URL) self.assertEqual(URL, component.url) self.assertIsNone(component.path) self.assertEqual( ComponentRegistry.instance().get_component_path("components_test"), component.abspath, )
def test_only_path(self): """Succeed when a path is provided.""" def isdir(path): return path == PATH or path == os.path.abspath(PATH) with mock.patch("streamlit.components.v1.components.os.path.isdir", side_effect=isdir): component = components.declare_component("test", path=PATH) self.assertEqual(PATH, component.path) self.assertIsNone(component.url) self.assertEqual( ComponentRegistry.instance().get_component_path(component.name), component.abspath, )
def create_component(cls) -> None: if cls.component is not None: return import streamlit as st try: import streamlit.components.v1 as components except ModuleNotFoundError as e: raise RuntimeError( f'Your streamlit version ({st.__version__}) is too old and does not support components. Please update streamlit with `pip install -U streamlit`' ) from e assert st._is_running_with_streamlit built_path = (Path(__file__).parent / "static" / "built" / "streamlit_component").resolve() assert (built_path / "index.html").is_file( ), f"""HiPlot component does not appear to exist in {built_path} If you did not install hiplot using official channels (pip, conda...), maybe you forgot to build javascript files? See https://facebookresearch.github.io/hiplot/contributing.html#building-javascript-bundle """ cls.component = components.declare_component("hiplot", path=str(built_path))
def render_results(ranking_df, metrics_data): st.title('Rankings') st.write( 'See which states are favorable based on what\'s important to you.') st.write(state.poi) overview = ranking_df[['State', 'Score']] google_geochart( key="map", data=overview.to_records(index=False).tolist(), headers=['State', 'Score'], google_maps_api_key="AIzaSyAqFvKJYNukFmJl_erO9xFg_1M0T9jbehc", options={ 'region': 'US', 'displayMode': 'regions', 'resolution': 'provinces' }) tab_component = components.declare_component("tabs", path="components/tabs/build") tabs = list( map(lambda metric: metric[0] if isinstance(metric, tuple) else metric, metrics)) tabs.insert(0, "Overview") active_tab = tab_component(key="tabs", tabs=tabs) overall = st.beta_container() ranking_df = ranking_df.sort_values(by=['Score'], ascending=False) if (active_tab == "Overview"): ranking_df = ranking_df.sort_values(by=['Score'], ascending=False) st.write(ranking_df) else: for metric_name, is_lower_favorable in metrics: if (metric_name == active_tab): st.write(metrics_data[metric_name].get('data'))
import os from os.path import join import streamlit as st import streamlit.components.v1 as components from col_data import Dictionary st.set_page_config( page_title="Dictionary App", layout="wide", ) json_viewer_build_dir = join(os.path.dirname(os.path.abspath(__file__)), "components", "json_viewer", "component", "frontend", "build") json_viewer = components.declare_component("json_viewer", path=json_viewer_build_dir) dictionary = Dictionary() init_word = 'a' def switch_word(word): st.session_state['current_word'] = word st.session_state['current_word_data'] = dictionary.get_word(word) st.session_state['current_next_words'] = dictionary.get_next_words(word) if __name__ == '__main__': if 'current_word' not in st.session_state: switch_word(init_word) # SIDEBAR
import os import streamlit.components.v1 as components from typing import Tuple # Now the React interface only accepts an array of 1 or 2 elements. _component_func = components.declare_component( "custom_slider", url="http://localhost:3001", ) # Edit arguments sent and result received from React component, so the initial input is converted to an array and returned value extracted from the component def st_custom_slider(label: str, min_value: int, max_value: int, value: int = 0, key=None) -> int: component_value = _component_func(label=label, minValue=min_value, maxValue=max_value, initialValue=[value], key=key, default=[value]) return component_value[0] # Define a new public method which takes as input a tuple of numbers to define a range slider, and returns back a tuple. def st_range_slider(label: str, min_value: int, max_value: int,
if ranking_df is False: ranking_df = metric_score ranking_df.insert(1, 'Score', 0.0) else: ranking_df = pd.merge(ranking_df, metric_score, on="State") ranking_df['Score'] = ranking_df['Score'] + weight * ranking_df[metric] # end cleanup st.title('Rankings') st.write('See which states are favorable based on what\'s important to you.') overview = ranking_df[['State', 'Score']] map_component = components.declare_component("home_map", path="components/map") home_map = map_component(key="map", data=overview.to_numpy().tolist()) tab_component = components.declare_component("tabs", path="components/tabs/build") tabs = list( map(lambda metric: metric[0] if isinstance(metric, tuple) else metric, metrics)) tabs.insert(0, "Overview") active_tab = tab_component(key="tabs", tabs=tabs) if (active_tab == "Overview"): ranking_df = ranking_df.sort_values(by=['Score'], ascending=False) st.write(ranking_df) else: for metric_name, is_lower_favorable in metrics:
import os import spacy import streamlit.components.v1 as components _RELEASE = True if not _RELEASE: _component_func = components.declare_component( "st_ner_annotate", url="http://localhost:5000", ) else: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/public") _component_func = components.declare_component( "st_ner_annotate", path=build_dir) def st_ner_annotate(label, text, ents, key=None): """st_edit_named_entities. Parameters ---------- text: str Text to render ents: object Entities found in text key: str or None An optional key that uniquely identifies this component. If this is None, and the component's arguments are changed, the component will be re-mounted in the Streamlit frontend and lose its current state.
# https://github.com/python-poetry/poetry/issues/1036#issuecomment-489880822 # https://github.com/python-poetry/poetry/issues/144#issuecomment-623927302 # https://github.com/python-poetry/poetry/pull/2366#issuecomment-652418094 try: __version__ = importlib_metadata.version(__name__) except importlib_metadata.PackageNotFoundError: pass LOGGER = logging.getLogger(__name__) LOGGER.addHandler(logging.NullHandler()) _RELEASE = True # TODO: How to dynamically manage this variable? if not _RELEASE: _component_func = components.declare_component( "webrtc_streamer", url="http://localhost:3001", ) else: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") _component_func = components.declare_component("webrtc_streamer", path=build_dir) _session_state = SessionState.get(webrtc_workers={}) def _get_webrtc_worker(key: Hashable) -> Union[WebRtcWorker, None]: return _session_state.webrtc_workers.get(key) def _set_webrtc_worker(key: Hashable, webrtc_worker: WebRtcWorker) -> None:
import os import streamlit.components.v1 as components import pandas as pd # Set this to False while we're developing the component, and True when we're # ready to package and distribute it. _RELEASE = False COMPONENT_NAME = "vega_lite_component" if not _RELEASE: _component_func = components.declare_component( COMPONENT_NAME, url="http://localhost:3001", ) else: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") _component_func = components.declare_component(COMPONENT_NAME, path=build_dir) def vega_lite_component(spec={}, key=None, **kwargs): """Returns selections from the Vega-Lite chart. Parameters ---------- spec: dict The Vega-Lite spec for the chart. See https://vega.github.io/vega-lite/docs/ for more info. key: str or None
import streamlit as st import streamlit.components.v1 as components counter_component = components.declare_component( "counter", # Production: path="frontend/build/", # Development: # url="http://localhost:3000/", ) count = counter_component(key="count", default=0) st.markdown(f"The value of the counter is **{count}**.")
# function "_component_func", with an underscore prefix, because we don't want # to expose it directly to users. Instead, we will create a custom wrapper # function, below, that will serve as our component's public API. # It's worth noting that this call to `declare_component` is the # *only thing* you need to do to create the binding between Streamlit and # your component frontend. Everything else we do in this file is simply a # best practice. if not _RELEASE: host = os.environ.get("STREAMLIT_HOST", "localhost") _component_func = components.declare_component( # We give the component a simple, descriptive name ("my_component" # does not fit this bill, so please choose something better for your # own component :) "hgb", # Pass `url` here to tell Streamlit that the component will be served # by the local dev server that you run via `npm run start`. # (This is useful while your component is in development.) url="http://{}:3001".format(host), ) else: # When we're distributing a production version of the component, we'll # replace the `url` param with `path`, and point it to to the component's # build directory: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") _component_func = components.declare_component("hgb", path=build_dir) # Retrieve samples from yaml file @st.cache()
import os import streamlit.components.v1 as components _RELEASE = True if not _RELEASE: _component_func = components.declare_component( "streamlit_location", url="http://localhost:3001", ) else: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") _component_func = components.declare_component("streamlit_location", path=build_dir) DEFAULT_LOCATION_RESULT = { "latitude": None, "longitude": None, "accuracy": None, "speed": None, "altitude": None, "altitudeAccuracy": None, "err": None } DEFAULT_PATTERN = [100] def location(key=None): component_value = _component_func(key=key,
import os import streamlit.components.v1 as components _RELEASE = True if not _RELEASE: _ace = components.declare_component("ace", url="http://localhost:3001") else: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") _ace = components.declare_component("ace", path=build_dir) def st_ace(value="", placeholder="", height=500, language="plain_text", theme="chrome", keybinding="vscode", min_lines=None, max_lines=None, font_size=12, tab_size=4, wrap=False, show_gutter=True, show_print_margin=False, readonly=False, annotations=None, markers=None, auto_update=True, key=None):
import os import streamlit as st import streamlit.components.v1 as components _RELEASE = True if not _RELEASE: _pandas_profiling = components.declare_component("pandas_profiling", url="http://localhost:3001") else: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") _pandas_profiling = components.declare_component("pandas_profiling", path=build_dir) def st_profile_report(profile_report, key=None): """Display a profile report. Parameters ---------- profile_report: pandas_profiling.ProfileReport The profile report instance to display. key: str or None An optional key that uniquely identifies this component. If this is None, and the component's arguments are changed, the component will be re-mounted in the Streamlit frontend and lose its current state. """ with st.spinner("Generating profile report..."): _pandas_profiling(html=profile_report.to_html(), key=key)
import os import numpy as np import streamlit.components.v1 as components _RELEASE = False # on packaging, pass this to True if not _RELEASE: _component_func = components.declare_component( "st_canvas", url="http://localhost:3001", ) else: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") _component_func = components.declare_component("st_canvas", path=build_dir) def st_canvas( brush_width: int = 20, brush_color: str = "black", background_color: str = "#eee", height: int = 400, width: int = 600, drawing_mode: bool = True, key=None, ) -> np.array: """Create a drawing canvas in Streamlit app. Retrieve the RGBA image data into a 4D numpy array (r, g, b, alpha) on mouse up event. :param brush_width: Width of drawing brush in pixels. :param brush_color: Color of drawing brush in hex.
from operator import itemgetter import streamlit.components.v1 as components from typing import List, Set import networkx as nx from networkx.algorithms import community import streamlit as st _RELEASE = True if not _RELEASE: _agraph = components.declare_component( "agraph", url="http://localhost:3001", ) else: # When we're distributing a production version of the component, we'll # replace the `url` param with `path`, and point it to to the component's # build directory: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") _agraph = components.declare_component("agraph", path=build_dir) class Config: def __init__(self, height=800, width=1000, graphviz_layout=None, graphviz_config=None, nodeHighlightBehavior=True, highlightColor="#F7A7A6", directed=True, collapsible=True, **kwargs): self.height = height self.width = width
# Copyright 2018-2022 Streamlit Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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.components.v1 as components url = "http://not.a.real.url" test_component = components.declare_component("test_component", url=url) test_component()
from transcribe import get_state, put_state, transcribe def _update_state(state, query, value): state["transcript"] = query state["value"] = value put_state(state) def _urlify(value): if value and (value.startswith("http") or value.startswith("www.")): return f'<a href="{value}">{value}</a>' return value get_audio = components.declare_component("get_audio", path="frontend/build") audio = get_audio() os.makedirs("data", exist_ok=True) file_name = os.path.join("data", "out.mp4") Path(file_name).touch() if audio: with open(file_name, "wb") as out: out.write(base64.b64decode(audio.split(",")[1])) transcript = transcribe(file_=file_name) query = st.text_input("Query:", transcript) top_doc, id_ = get_doc(query)
def setUp(self): super().setUp() self.test_component = components.declare_component("test", url=URL)
# Declare a Streamlit component. `declare_component` returns a function # that is used to create instances of the component. We're naming this # function "_component_func", with an underscore prefix, because we don't want # to expose it directly to users. Instead, we will create a custom wrapper # function, below, that will serve as our component's public API. # It's worth noting that this call to `declare_component` is the # *only thing* you need to do to create the binding between Streamlit and # your component frontend. Everything else we do in this file is simply a # best practice. if not _RELEASE: _component_func = components.declare_component( "covid-record-button", # Pass `url` here to tell Streamlit that the component will be served # by the local dev server that you run via `npm run start`. # (This is useful while your component is in development.) url="http://localhost:3001", ) else: # When we're distributing a production version of the component, we'll # replace the `url` param with `path`, and point it to to the component's # build directory: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") _component_func = components.declare_component("covid-record-button", path=build_dir) # Create a wrapper function for the component. This is an optional # best practice - we could simply expose the component function returned by
import os import streamlit.components.v1 as components parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") if "DEBUG_MODE" in os.environ: _component_func = components.declare_component( "document_viewer", url="http://gil.ccs.neu.edu:5010", ) else: _component_func = components.declare_component("document_viewer", path=build_dir) def annotation_block(page, key): return _component_func(data=page.html(), css=page.css(), key=key)
# Copyright 2018-2020 Streamlit Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. from streamlit.components.v1 import declare_component component = declare_component("foo", url="http://not.a.url")
import os import streamlit.components.v1 as components _RELEASE = True if not _RELEASE: _component_func = components.declare_component( "vanilla_component", url="http://localhost:3000") # vite dev server port else: _component_func = components.declare_component( "vanilla_component", path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "frontend/dist")) def vanilla_component(name, key=None, default=0): component_value = _component_func(name=name, key=key, default=default) return component_value if not _RELEASE: import streamlit as st st.subheader("Component Test") num_clicks = vanilla_component(name="Vanilla") st.markdown("You've clicked %s times!" % int(num_clicks))
import os import spacy import streamlit.components.v1 as components _RELEASE = False if not _RELEASE: _component_func = components.declare_component( "streamlit_named_entity", url="http://localhost:5000", ) else: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") _component_func = components.declare_component("streamlit_named_entity", path=build_dir) def st_named_entity_demo(text, ents, key=None): entities = _component_func(text=text, ents=ents, key=key, default=ents) return entities if not _RELEASE: import streamlit as st st.title("Named entity recognition demo") text = "Google was founded in September 1998 by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University in California. Together they own about 14 percent of its shares and control 56 percent of the stockholder voting power through supervoting stock. They incorporated Google as a California privately held company on September 4, 1998, in California. Google was then reincorporated in Delaware on October 22, 2002 by Me." nlp = spacy.load("en_core_web_sm") doc = nlp(text) ents = doc.to_json()['ents']
def weighted_path(conn, country): country = country.drop([0]).reset_index(drop=True) country = country.to_string(index=False) _map_compoent = components.declare_component("United States", url="http://localhost:3000") component_value = _map_compoent(name="weighted", key=country)
import os from typing import Dict from typing import List from typing import Tuple import streamlit.components.v1 as components _RELEASE = False # on packaging, pass this to True if not _RELEASE: _component_func = components.declare_component( "d3_demo", url="http://localhost:3001", ) else: parent_dir = os.path.dirname(os.path.abspath(__file__)) build_dir = os.path.join(parent_dir, "frontend/build") _component_func = components.declare_component("d3_demo", path=build_dir) def d3_line( data: List[Tuple[int, int]], circle_radius: int = 15, circle_color: str = "#6495ed", height: int = 400, width: int = 600, margin: Dict = None, key=None, ): """Display a line chart with overlapping circles on a list of (x, y) points, using the D3 library.