text
stringlengths
0
105k
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Busiest US airports # Source: https://en.wikipedia.org/wiki/List_of_busiest_airports_by_passenger_traffic airports = { "AMS": {"lat": 52.31047296675518, "lon": 4.76819929439927}, "ATL": {"lat": 33.64086185344307, "lon": -84.43600501711686}, "AYT": {"lat": 36.90419539293911, "lon": 30.801855337974292}, "BOS": {"lat": 42.36556559649881, "lon": -71.00960311751096}, "CAN": {"lat": 23.38848323741897, "lon": 113.30277713668413}, "CDG": {"lat": 49.008029034119915, "lon": 2.550879924581871}, "CJU": {"lat": 33.51035978854847, "lon": 126.4913319405336}, "CKG": {"lat": 29.71931573810283, "lon": 106.64211731662628}, "CLT": {"lat": 35.214730980190616, "lon": -80.9474735034797}, "CSX": {"lat": 28.196638298182446, "lon": 113.22083329905352}, "CTU": {"lat": 30.567492917634063, "lon": 103.94912193845805}, "CUN": {"lat": 21.04160313837335, "lon": -86.87407057500725}, "DEL": {"lat": 28.556426221725868, "lon": 77.10031185913002}, "DEN": {"lat": 39.85589532386815, "lon": -104.67329901305273}, "DFW": {"lat": 32.89998507111719, "lon": -97.04044513206443}, "DME": {"lat": 55.41032513421412, "lon": 37.902386927376234}, "DTW": {"lat": 42.216145762248594, "lon": -83.35541784824225}, "DXB": {"lat": 25.253155060720765, "lon": 55.365672799304534}, "EWR": {"lat": 40.68951508829295, "lon": -74.17446240095387}, "FLL": {"lat": 26.072469069499288, "lon": -80.1502073285754}, "FRA": {"lat": 50.037870541116, "lon": 8.562119610188235}, "GMP": {"lat": 37.558628944763534, "lon": 126.79445244110332}, "GRU": {"lat": -23.430691200492866, "lon": -46.473107371367846}, "HGH": {"lat": 30.2359856421667, "lon": 120.43880486944619}, "HND": {"lat": 35.54938443207139, "lon": 139.77979568388005}, "IAH": {"lat": 29.98997826322153, "lon": -95.33684707873988}, "IST": {"lat": 41.27696594578831, "lon": 28.73004303446375}, "JFK": {"lat": 40.64129497654287, "lon": -73.77813830094803}, "KMG": {"lat": 24.99723271310971, "lon": 102.74030761670535}, "LAS": {"lat": 36.08256046166282, "lon": -115.15700045025673}, "LAX": {"lat": 33.94157995977848, "lon": -118.40848708486908}, "MAD": {"lat": 40.49832400063489, "lon": -3.5676196584173754}, "MCO": {"lat": 28.419119921670067, "lon": -81.30451008534465}, "MEX": {"lat": 19.436096410278736, "lon": -99.07204777544095}, "MIA": {"lat": 25.795823878101675, "lon": -80.28701871639629}, "MSP": {"lat": 44.88471735079015, "lon": -93.22233824616785}, "ORD": {"lat": 41.98024003208415, "lon": -87.9089657513565}, "PEK": {"lat": 40.079816213451416, "lon": 116.60309064055198}, "PHX": {"lat": 33.43614430802288, "lon": -112.01128270596944}, "PKX": {"lat": 39.50978840400886, "lon": 116.41050689906415}, "PVG": {"lat": 31.144398958515847, "lon": 121.80823008537978}, "SAW": {"lat": 40.9053709590178, "lon": 29.316838841845318}, "SEA": {"lat": 47.448024349661814, "lon": -122.30897973141963}, "SFO": {"lat": 37.62122788155908, "lon": -122.37901977603573}, "SHA": {"lat": 31.192227319334787, "lon": 121.33425408454256}, "SLC": {"lat": 40.78985913031307, "lon": -111.97911351851535}, "SVO": {"lat": 55.97381026156798, "lon": 37.412288430689664}, "SZX": {"lat": 22.636827890877626, "lon": 113.81454162446936}, "WUH": {"lat": 30.776589409566686, "lon": 114.21244949898504}, "XIY": {"lat": 34.437119809208546, "lon": 108.7573508575816}, } # Inter US airports flights # Source: https://www.faa.gov/air_traffic/by_the_numbers flights = [ {"from": "ATL", "to": "DFW", "traffic": 580}, {"from": "ATL", "to": "MIA", "traffic": 224}, {"from": "BOS", "to": "LAX", "traffic": 168}, {"from": "DEN", "to": "DFW", "traffic": 558}, {"from": "DFW", "to": "BOS", "traffic": 422}, {"from": "DFW", "to": "CLT", "traffic": 360}, {"from": "DFW", "to": "JFK", "traffic": 56}, {"from": "DFW", "to": "LAS", "traffic": 569}, {"from": "DFW", "to": "SEA", "traffic": 392}, {"from": "DTW", "to": "DFW", "traffic": 260}, {"from": "EWR", "to": "DFW", "traffic": 310}, {"from": "EWR", "to": "ORD", "traffic": 168}, {"from": "FLL", "to": "DFW", "traffic": 336}, {"from": "FLL", "to": "ORD", "traffic": 168}, {"from": "IAH", "to": "DFW", "traffic": 324}, {"from": "JFK", "to": "FLL", "traffic": 112}, {"from": "JFK", "to": "LAS", "traffic": 112}, {"from": "JFK", "to": "LAX", "traffic": 548}, {"from": "JFK", "to": "ORD", "traffic": 56}, {"from": "LAS", "to": "MIA", "traffic": 168}, {"from": "LAX", "to": "DFW", "traffic": 914}, {"from": "LAX", "to": "EWR", "traffic": 54}, {"from": "LAX", "to": "LAS", "traffic": 222}, {"from": "LAX", "to": "MCO", "traffic": 56}, {"from": "LAX", "to": "MIA", "traffic": 392}, {"from": "LAX", "to": "SFO", "traffic": 336}, {"from": "MCO", "to": "DFW", "traffic": 500}, {"from": "MCO", "to": "JFK", "traffic": 224}, {"from": "MCO", "to": "ORD", "traffic": 224}, {"from": "MIA", "to": "BOS", "traffic": 392}, {"from": "MIA", "to": "DEN", "traffic": 112}, {"from": "MIA", "to": "DFW", "traffic": 560}, {"from": "MIA", "to": "DTW", "traffic": 112}, {"from": "MIA", "to": "EWR", "traffic": 168}, {"from": "MIA", "to": "IAH", "traffic": 168}, {"from": "MIA", "to": "JFK", "traffic": 392}, {"from": "MIA", "to": "MCO", "traffic": 448}, {"from": "MSP", "to": "DFW", "traffic": 326}, {"from": "MSP", "to": "MIA", "traffic": 56}, {"from": "ORD", "to": "BOS", "traffic": 430}, {"from": "ORD", "to": "DEN", "traffic": 112}, {"from": "ORD", "to": "DFW", "traffic": 825}, {"from": "ORD", "to": "LAS", "traffic": 280}, {"from": "ORD", "to": "LAX", "traffic": 496}, {"from": "ORD", "to": "MIA", "traffic": 505}, {"from": "ORD", "to": "MSP", "traffic": 160}, {"from": "ORD", "to": "PHX", "traffic": 280}, {"from": "ORD", "to": "SEA", "traffic": 214}, {"from": "ORD", "to": "SFO", "traffic": 326}, {"from": "PHX", "to": "DFW", "traffic": 550}, {"from": "PHX", "to": "MIA", "traffic": 56}, {"from": "SEA", "to": "JFK", "traffic": 56}, {"from": "SFO", "to": "DFW", "traffic": 526}, {"from": "SFO", "to": "JFK", "traffic": 278}, {"from": "SFO", "to": "MIA", "traffic": 168}, {"from": "SLC", "to": "DFW", "traffic": 280}, ] data = [] max_traffic = 0 for flight in flights: airport_from = airports[flight["from"]] airport_to = airports[flight["to"]] # Define data source to plot this flight data.append({"lat": [airport_from["lat"], airport_to["lat"]], "lon": [airport_from["lon"], airport_to["lon"]]}) # Store the maximum traffic if flight["traffic"] > max_traffic: max_traffic = flight["traffic"] properties = { # Chart data "data": data, # Chart type "type": "scattergeo", # Keep lines only "mode": "lines", # Flights display as redish lines "line": {"width": 2, "color": "E22"}, "layout": { # Focus on the USA region "geo": {"scope": "usa"} }, } # Set the proper data source and opacity for each trace for i, flight in enumerate(flights): # lat[trace_index] = "[index_in_data]/lat" properties[f"lat[{i+1}]"] = f"{i}/lat" # lon[trace_index] = "[index_in_data]/lon" properties[f"lon[{i+1}]"] = f"{i}/lon" # Set flight opacity (max traffic -> max opacity) # Hide legend for all flights properties[f"options[{i+1}]"] = {"opacity": flight["traffic"] / max_traffic, "showlegend": False} page = """ # Maps - Multiple Lines <|chart|properties={properties}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui n_slices = 20 # List: [1..n_slices] # Slices are bigger and bigger values = list(range(1, n_slices + 1)) marker = { # Colors move around the Hue color disk "colors": [f"hsl({360 * (i - 1)/(n_slices - 1)},90%,60%)" for i in values] } layout = { # Hide the legend "showlegend": False } options = { # Hide the texts "textinfo": "none" } page = """ # Pie - Style <|{values}|chart|type=pie|marker={marker}|options={options}|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from datetime import datetime import numpy from taipy.gui import Gui def generate_hand_shapes(): # Retrieve and store the current, local time time_now = datetime.now() hours = time_now.hour minutes = time_now.minute seconds = time_now.second # Compute the angle that represents the hours hours_angle = 360 * ((hours % 12) / 12 + (minutes % 60) / 60 / 60 + (seconds % 60) / 60 / 60 / 60) # Short and thick hand for the hours hours_hand = {"r": [0, 4, 5, 4, 0], "a": [0, hours_angle - 7, hours_angle, hours_angle + 7, 0]} # Compute the angle that represents the minutes minutes_angle = 360 * ((minutes % 60) / 60 + (seconds % 60) / 60 / 60) # Longer and slighly thinner hand for the minutes minutes_hand = {"r": [0, 6, 8, 6, 0], "a": [0, minutes_angle - 4, minutes_angle, minutes_angle + 4, 0]} # Compute the angle that represents the seconds seconds_angle = 360 * (seconds % 60) / 60 # Even longer and thinner hand for the seconds seconds_hand = {"r": [0, 8, 10, 8, 0], "a": [0, seconds_angle - 2, seconds_angle, seconds_angle + 2, 0]} # Build and return the whole data set return [hours_hand, minutes_hand, seconds_hand] # Initialize the data set with the current time data = generate_hand_shapes() layout = { "polar": { "angularaxis": { "rotation": 90, "direction": "clockwise", # One tick every 30 degrees "tickvals": list(numpy.arange(0.0, 360.0, 30)), # Text value for every tick "ticktext": ["XII", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI"], }, "radialaxis": {"angle": 90, "visible": False, "range": [0, 12]}, }, "showlegend": False, } # Options to be used for all three traces base_opts = {"fill": "toself"} # Specific for hours hours_opts = dict(base_opts) hours_opts["fillcolor"] = "#FF0000" # Specific for minutes minutes_opts = dict(base_opts) minutes_opts["fillcolor"] = "#00FF00" # Specific for seconds seconds_opts = dict(base_opts) seconds_opts["fillcolor"] = "#0000FF" # Store all the chart control properties in a single object properties = { # Don't show data point markers "mode": "lines", # Data for the hours "theta[1]": "0/a", "r[1]": "0/r", # Data for the minutes "theta[2]": "1/a", "r[2]": "1/r", # Data for the seconds "theta[3]": "2/a", "r[3]": "2/r", # Options for the three traces "options[1]": hours_opts, "options[2]": minutes_opts, "options[3]": seconds_opts, "line": {"color": "black"}, "layout": layout, } # Update time on every refresh def on_navigate(state, page): state.data = generate_hand_shapes() return page page = """ # Polar - Tick texts <|{data}|chart|type=scatterpolar|properties={properties}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = {"Types": ["Visits", "Downloads", "Prospects", "Invoiced", "Closed"], "Visits": [13873, 10533, 5443, 2703, 908]} layout = { # Stack the areas "funnelmode": "stack", # Hide the legend "showlegend": False, } page = """ # Funnel - Area <|{data}|chart|type=funnelarea|values=Visits|text=Types|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import pandas from taipy.gui import Gui # Source https://en.wikipedia.org/wiki/List_of_United_States_presidential_elections_by_popular_vote_margin percentages = [ (1852, 50.83), (1856, 45.29), (1860, 39.65), (1864, 55.03), (1868, 52.66), (1872, 55.58), (1876, 47.92), (1880, 48.31), (1884, 48.85), (1888, 47.80), (1892, 46.02), (1896.0, 51.02), (1900, 51.64), (1904, 56.42), (1908, 51.57), (1912, 41.84), (1916, 49.24), (1920, 60.32), (1924, 54.04), (1928, 58.21), ] # Lost percentage = 100-Won percentage full = [(t[0], t[1], 100 - t[1]) for t in percentages] data = pandas.DataFrame(full, columns=["Year", "Won", "Lost"]) layout = {"barmode": "stack"} page = """ # Bar - Stacked <|{data}|chart|type=bar|x=Year|y[1]=Won|y[2]=Lost|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import numpy import pandas from taipy.gui import Gui # Generate a random value for every hour on a given day data = {"Date": pandas.date_range("2023-01-04", periods=24, freq="H"), "Value": pandas.Series(numpy.random.randn(24))} page = """ # Basics - Timeline <|{data}|chart|x=Date|y=Value|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import random from taipy.gui import Gui # Data set made of two series of random numbers data = [{"x": [random.random() + 1 for i in range(100)]}, {"x": [random.random() + 1.1 for i in range(100)]}] options = [ # First data set displayed as semi-transparent, green bars {"opacity": 0.5, "marker": {"color": "green"}}, # Second data set displayed as semi-transparent, gray bars {"opacity": 0.5, "marker": {"color": "#888"}}, ] layout = { # Overlay the two histograms "barmode": "overlay", # Hide the legend "showlegend": False, } page = """ # Histogram - Overlay <|{data}|chart|type=histogram|options={options}|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = { "Day": ["Mon", "Tue", "Wed", "Thu", "Fri"], "Items": [32, 25, 86, 60, 70], "Price": [80, 50, 140, 10, 70], } options = [ # For items {"fill": "tozeroy"}, # For price # Using "tonexty" not to cover the first trace {"fill": "tonexty"}, ] page = """ # Filled Area - Overlay <|{data}|chart|mode=none|x=Day|y[1]=Items|y[2]=Price|options={options}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # x values are [-10..10] x_range = range(-10, 11) # The data set holds the _x_ series and two distinct series for _y_ data = { "x": x_range, # y1 = x*x "y1": [x * x for x in x_range], # y2 = 100-x*x "y2": [100 - x * x for x in x_range], } page = """ # Basics - Multiple traces <|{data}|chart|x=x|y[1]=y1|y[2]=y2|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- # Two data sets as a bar chart import pandas from taipy.gui import Gui # Source https://en.wikipedia.org/wiki/List_of_United_States_presidential_elections_by_popular_vote_margin percentages = [ (1852, 50.83), (1856, 45.29), (1860, 39.65), (1864, 55.03), (1868, 52.66), (1872, 55.58), (1876, 47.92), (1880, 48.31), (1884, 48.85), (1888, 47.80), (1892, 46.02), (1896.0, 51.02), (1900, 51.64), (1904, 56.42), (1908, 51.57), (1912, 41.84), (1916, 49.24), (1920, 60.32), (1924, 54.04), (1928, 58.21), ] data = pandas.DataFrame(percentages, columns=["Year", "Won"]) lost = [100 - t[1] for t in percentages] data["Lost"] = lost page = """ # Bar - Multiple <|{data}|chart|type=bar|x=Year|y[1]=Won|y[2]=Lost|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # You may need to install the yfinance package as well. # ----------------------------------------------------------------------------------------- import yfinance from taipy import Gui # Extraction of a month of stock data for AAPL using the # yfinance package (see https://pypi.org/project/yfinance/). ticker = yfinance.Ticker("AAPL") # The returned value is a Pandas DataFrame. stock = ticker.history(interval="1d", start="2018-08-01", end="2018-08-31") # Copy the DataFrame's index to a new column stock["Date"] = stock.index page = """ # Candlestick - Simple <|{stock}|chart|type=candlestick|x=Date|open=Open|close=Close|low=Low|high=High|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import random import numpy from taipy.gui import Gui # x = [0..20] x = list(range(0, 21)) data = { "x": x, # A list of random values within [1, 10] "y": [random.uniform(1, 10) for _ in x], } layout = { # Force the Box select tool "dragmode": "select", # Remove all margins around the plot "margin": {"l": 0, "r": 0, "b": 0, "t": 0}, } config = { # Hide Plotly's mode bar "displayModeBar": False } selected_indices = [] mean_value = 0.0 def on_change(state, var, val): if var == "selected_indices": state.mean_value = numpy.mean([data["y"][idx] for idx in val]) if len(val) else 0 page = """ # Advanced - Selection ## Mean of <|{len(selected_indices)}|raw|> selected points: <|{mean_value}|format=%.2f|raw|> <|{data}|chart|selected={selected_indices}|layout={layout}|plot_config={config}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import math import random from taipy.gui import Gui # Number of samples max_x = 20 # x values: [0..max_x-1] x = range(0, max_x) # Generate random sampling error margins error_ranges = [random.uniform(0, 5) for _ in x] # Compute a perfect sine wave perfect_y = [10 * math.sin(4 * math.pi * i / max_x) for i in x] # Compute a sine wave impacted by the sampling error # The error is between ±error_ranges[x]/2 y = [perfect_y[i] + random.uniform(-error_ranges[i] / 2, error_ranges[i] / 2) for i in x] # The chart data is made of the three series data = { "x": x, "y1": y, "y2": perfect_y, } options = { # Create the error bar information: "error_y": {"type": "data", "array": error_ranges} } page = """ # Error bars - Simple <|{data}|chart|x=x|y[1]=y1|y[2]=y2|options[1]={options}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = { "Day": ["Mon", "Tue", "Wed", "Thu", "Fri"], "Items": [32, 25, 86, 60, 70], } options = { # Fill to x axis "fill": "tozeroy" } page = """ # Filled Area - Simple <|{data}|chart|x=Day|y=Items|options={options}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import datetime import dateutil.relativedelta from taipy.gui import Gui # Data is collected from January 1st, 2010, every month start_date = datetime.datetime(year=2010, month=1, day=1) period = dateutil.relativedelta.relativedelta(months=1) # Data # All arrays have the same size (the number of months to track) prices = { # Data for apples "apples": [2.48, 2.47, 2.5, 2.47, 2.46, 2.38, 2.31, 2.25, 2.39, 2.41, 2.59, 2.61], "apples_low": [1.58, 1.58, 1.59, 1.64, 1.79, 1.54, 1.53, 1.61, 1.65, 2.02, 1.92, 1.54], "apples_high": [3.38, 3.32, 2.63, 2.82, 2.58, 2.53, 3.27, 3.15, 3.44, 3.42, 3.08, 2.86], "bananas": [2.94, 2.50, 2.39, 2.77, 2.43, 2.32, 2.37, 1.90, 2.31, 2.71, 3.38, 1.92], "bananas_low": [2.12, 1.90, 1.69, 2.44, 1.58, 1.81, 1.44, 1.00, 1.59, 1.74, 2.78, 0.96], "bananas_high": [3.32, 2.70, 3.12, 3.25, 3.00, 2.63, 2.54, 2.37, 2.97, 3.69, 4.36, 2.95], "cherries": [6.18, None, None, None, 3.69, 2.46, 2.31, 2.57, None, None, 6.50, 4.38], "cherries_high": [7.00, None, None, None, 8.50, 6.27, 5.61, 4.36, None, None, 8.00, 7.23], "cherries_low": [3.55, None, None, None, 1.20, 0.87, 1.08, 1.50, None, None, 5.00, 4.20], } # Create monthly time series months = [start_date + n * period for n in range(0, len(prices["apples"]))] data = [ # Raw data {"Months": months, "apples": prices["apples"], "bananas": prices["bananas"], "cherries": prices["cherries"]}, # Range data (twice as many values) { "Months2": months + list(reversed(months)), "apples": prices["apples_high"] + list(reversed(prices["apples_low"])), "bananas": prices["bananas_high"] + list(reversed(prices["bananas_low"])), "cherries": prices["cherries_high"] + list(reversed(prices["cherries_low"])), }, ] properties = { # First trace: reference for Apples "x[1]": "0/Months", "y[1]": "0/apples", "color[1]": "rgb(0,200,80)", # Hide line "mode[1]": "markers", # Show in the legend "name[1]": "Apples", # Second trace: reference for Bananas "x[2]": "0/Months", "y[2]": "0/bananas", "color[2]": "rgb(0,100,240)", # Hide line "mode[2]": "markers", # Show in the legend "name[2]": "Bananas", # Third trace: reference for Cherries "x[3]": "0/Months", "y[3]": "0/cherries", "color[3]": "rgb(240,60,60)", # Hide line "mode[3]": "markers", # Show in the legend "name[3]": "Cherries", # Fourth trace: range for Apples "x[4]": "1/Months2", "y[4]": "1/apples", "options[4]": { "fill": "tozerox", "showlegend": False, "fillcolor": "rgba(0,100,80,0.4)", }, # No surrounding stroke "color[4]": "transparent", # Fifth trace: range for Bananas "x[5]": "1/Months2", "y[5]": "1/bananas", "options[5]": {"fill": "tozerox", "showlegend": False, "fillcolor": "rgba(0,180,250,0.4)"}, # No surrounding stroke "color[5]": "transparent", # Sixth trace: range for Cherries "x[6]": "1/Months2", "y[6]": "1/cherries", "options[6]": { "fill": "tozerox", "showlegend": False, "fillcolor": "rgba(230,100,120,0.4)", }, # No surrounding stroke "color[6]": "transparent", } page = """ # Continuous Error - Multiple traces <|{data}|chart|properties={properties}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import random from taipy.gui import Gui # Number of samples n_samples = 10 # y values: [0..n_samples-1] y = range(0, n_samples) data = { # The x series is made of random numbers between 1 and 10 "x": [random.uniform(1, 10) for i in y], "y": y, } options = { "error_x": { "type": "data", # Allows for a 'plus' and a 'minus' error data "symmetric": False, # The 'plus' error data is a series of random numbers "array": [random.uniform(0, 5) for i in y], # The 'minus' error data is a series of random numbers "arrayminus": [random.uniform(0, 2) for i in y], # Color of the error bar "color": "red", } } page = """ # Error bars - Asymmetric <|{data}|chart|type=bar|x=x|y=y|orientation=h|options={options}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import math from taipy.gui import Gui # One data point for each degree theta = range(0, 360) # Parametric equation that draws a shape (source Wolfram Mathworld) def draw_heart(angle): a = math.radians(angle) sa = math.sin(a) return 2 - 2 * sa + sa * (math.sqrt(math.fabs(math.cos(a))) / (sa + 1.4)) data = { # Create the heart shape "r": [draw_heart(angle) for angle in theta], "theta": theta, } page = """ # Polar - Simple <|{data}|chart|type=scatterpolar|mode=lines|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # List of countries, used as labels in the pie charts countries = ["US", "China", "European Union", "Russian Federation", "Brazil", "India", "Rest of World"] data = [ { # Values for GHG Emissions "values": [16, 15, 12, 6, 5, 4, 42], "labels": countries, }, { # Values for CO2 Emissions "values": [27, 11, 25, 8, 1, 3, 25], "labels": countries, }, ] options = [ # First pie chart { # Show label value on hover "hoverinfo": "label", # Leave a hole in the middle of the chart "hole": 0.4, # Place the trace on the left side "domain": {"column": 0}, }, # Second pie chart { # Show label value on hover "hoverinfo": "label", # Leave a hole in the middle of the chart "hole": 0.4, # Place the trace on the right side "domain": {"column": 1}, }, ] layout = { # Chart title "title": "Global Emissions 1990-2011", # Show traces in a 1x2 grid "grid": {"rows": 1, "columns": 2}, "annotations": [ # Annotation for the first trace { "text": "GHG", "font": {"size": 20}, # Hide annotation arrow "showarrow": False, # Move to the center of the trace "x": 0.18, "y": 0.5, }, # Annotation for the second trace { "text": "CO2", "font": {"size": 20}, "showarrow": False, # Move to the center of the trace "x": 0.81, "y": 0.5, }, ], "showlegend": False, } page = """ # Pie - Multiple <|{data}|chart|type=pie|x[1]=0/values|x[2]=1/values|options={options}|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # The first data set uses the x interval [-10..10], # with one point at every other unit x1_range = [x * 2 for x in range(-5, 6)] # The second data set uses the x interval [-4..4], # with ten point between every unit x2_range = [x / 10 for x in range(-40, 41)] # Definition of the two data sets data = [ # Coarse data set {"x": x1_range, "Coarse": [x * x for x in x1_range]}, # Fine data set {"x": x2_range, "Fine": [x * x for x in x2_range]}, ] page = """ # Advanced - Unbalanced data sets <|{data}|chart|x[1]=0/x|y[1]=0/Coarse|x[2]=1/x|y[2]=1/Fine|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Flight start and end locations data = { # Hartsfield-Jackson Atlanta International Airport # to # Aéroport de Paris-Charles de Gaulle "lat": [33.64, 49.01], "lon": [-84.44, 2.55], } layout = { # Chart title "title": "ATL to CDG", # Hide legend "showlegend": False, # Focus on relevant area "geo": { "resolution": 50, "showland": True, "showocean": True, "landcolor": "4a4", "oceancolor": "77d", "lataxis": {"range": [20, 60]}, "lonaxis": {"range": [-100, 20]}, }, } # Flight displayed as a thick, red plot line = {"width": 5, "color": "red"} page = """ # Maps - Simple <|{data}|chart|type=scattergeo|mode=lines|lat=lat|lon=lon|line={line}|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import random from taipy.gui import Gui # Random data set data = {"Count": [random.random() for i in range(100)]} page = """ # Histograms - Horizontal <|{data}|chart|type=histogram|y=Count|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import pandas from taipy.gui import Gui dates = pandas.date_range("2023-01-01", periods=365, freq="D") temp = [ -11.33333333, -6, -0.111111111, 1.444444444, 2.388888889, 4.555555556, 4.333333333, 0.666666667, 9, 9.611111111, -0.555555556, 1.833333333, -0.444444444, 2.166666667, -4, -12.05555556, -2.722222222, 5, 9.888888889, 6.611111111, -2.833333333, -3.277777778, -1.611111111, -1.388888889, 5.777777778, 2.166666667, -1.055555556, 1.777777778, 1.5, 8.444444444, 6.222222222, -2.5, -0.388888889, 6.111111111, -1.5, 2.666666667, -2.5, 0.611111111, 8.222222222, 2.333333333, -9.333333333, -7.666666667, -6.277777778, -0.611111111, 7.722222222, 6.111111111, -4, 3.388888889, 9.333333333, -6.333333333, -15, -12.94444444, -8.722222222, -6.222222222, -2.833333333, -2.5, 1.5, 3.444444444, 2.666666667, 0.888888889, 7.555555556, 12.66666667, 12.83333333, 1.777777778, -0.111111111, -1.055555556, 4.611111111, 11.16666667, 8.5, 0.5, 2.111111111, 4.722222222, 8.277777778, 10.66666667, 5.833333333, 5.555555556, 6.944444444, 1.722222222, 2.444444444, 6.111111111, 12.11111111, 15.55555556, 9.944444444, 10.27777778, 5.888888889, 1.388888889, 3.555555556, 1.222222222, 4.055555556, 7.833333333, 0.666666667, 10.05555556, 6.444444444, 4.555555556, 11, 3.555555556, -0.555555556, 11.83333333, 7.222222222, 10.16666667, 17.5, 14.55555556, 6.777777778, 3.611111111, 5.888888889, 10.05555556, 16.61111111, 5.5, 7.055555556, 10.5, 1.555555556, 6.166666667, 11.05555556, 5.111111111, 6.055555556, 11, 11.05555556, 14.72222222, 19.16666667, 16.5, 12.61111111, 8.277777778, 6.611111111, 10.38888889, 15.38888889, 17.22222222, 18.27777778, 18.72222222, 17.05555556, 19.72222222, 16.83333333, 12.66666667, 11.66666667, 12.88888889, 14.77777778, 18, 19.44444444, 16.5, 9.722222222, 7.888888889, 13.72222222, 17.55555556, 18.27777778, 20.11111111, 21.66666667, 23.38888889, 23.5, 16.94444444, 16.27777778, 18.61111111, 20.83333333, 24.61111111, 18.27777778, 17.88888889, 22.27777778, 25.94444444, 25.27777778, 24.72222222, 25.61111111, 23.94444444, 26.33333333, 22.05555556, 20.83333333, 24.5, 27.83333333, 25.61111111, 23.11111111, 19.27777778, 16.44444444, 19.44444444, 17.22222222, 19.44444444, 22.16666667, 21.77777778, 17.38888889, 17.22222222, 23.88888889, 28.44444444, 29.44444444, 29.61111111, 21.05555556, 18.55555556, 25.27777778, 26.55555556, 24.55555556, 23.38888889, 22.55555556, 27.05555556, 27.66666667, 26.66666667, 27.61111111, 26.66666667, 24.77777778, 23, 26.5, 23.11111111, 19.83333333, 22.27777778, 24.61111111, 27.05555556, 27.05555556, 27.94444444, 27.33333333, 22.05555556, 21.5, 22, 19.72222222, 20.27777778, 17.88888889, 18.55555556, 18.94444444, 20, 22.05555556, 23.22222222, 24.38888889, 24.5, 24.5, 21.22222222, 20.83333333, 20.61111111, 22.05555556, 23.77777778, 24.16666667, 24.22222222, 21.83333333, 21.33333333, 21.88888889, 22.44444444, 23.11111111, 20.44444444, 16.88888889, 15.77777778, 17.44444444, 17.72222222, 23.11111111, 24.55555556, 24.88888889, 25.11111111, 25.27777778, 19.5, 19.55555556, 24.05555556, 24.27777778, 21.05555556, 19.88888889, 20.66666667, 20.27777778, 17.66666667, 16.44444444, 15.88888889, 18.44444444, 22.44444444, 23, 24.72222222, 24.16666667, 25.94444444, 24.44444444, 23.33333333, 25.22222222, 25, 23.88888889, 23.72222222, 18.94444444, 16.22222222, 19.5, 21.22222222, 19.72222222, 13.22222222, 11.88888889, 16.55555556, 10.05555556, 12.16666667, 11.5, 10.22222222, 17.27777778, 21.72222222, 13.83333333, 13, 6.944444444, 6.388888889, 4.222222222, 2.5, 1.111111111, 3.055555556, 6.388888889, 10.44444444, -2, -2.222222222, 4.388888889, 8.333333333, 11.11111111, 12.66666667, 10.88888889, 12.83333333, 14.16666667, 12.55555556, 12.05555556, 11.22222222, 12.44444444, 14.38888889, 12, 15.83333333, 6.722222222, 2.5, 4.833333333, 7.5, 8.888888889, 4, 7.388888889, 3.888888889, 1.611111111, -0.333333333, -2, 4.833333333, -1.055555556, -5.611111111, -2.388888889, 5.722222222, 8.444444444, 5.277777778, 0.5, -2.5, 1.111111111, 2.111111111, 5.777777778, 7.555555556, 7.555555556, 4.111111111, -0.388888889, -1, 4.944444444, 9.444444444, 4.722222222, -0.166666667, 0.5, -2.444444444, -2.722222222, -2.888888889, -1.111111111, -4.944444444, -3.111111111, -1.444444444, -0.833333333, 2.333333333, 6.833333333, 4.722222222, 0.888888889, 0.666666667, 4.611111111, 4.666666667, 4.444444444, 6.777777778, 5.833333333, 0.5, 4.888888889, 1.444444444, -2.111111111, 2.444444444, -0.111111111, -2.555555556, -4.611111111, -8.666666667, -8.055555556, 1.555555556, -4.777777778, ] min = [ -14.33333333, -12.9, -3.311111111, -4.955555556, -3.611111111, 0.555555556, 1.133333333, -5.133333333, 2.3, 3.911111111, -7.055555556, -1.366666667, -4.844444444, -3.333333333, -6.1, -17.15555556, -4.822222222, 0.4, 3.488888889, 4.211111111, -6.433333333, -7.577777778, -7.111111111, -7.088888889, 1.577777778, -3.433333333, -4.355555556, -0.722222222, -2.1, 2.044444444, 2.222222222, -4.7, -2.388888889, 4.111111111, -5, -0.133333333, -5.3, -2.288888889, 6.022222222, -1.766666667, -15.53333333, -13.46666667, -9.277777778, -3.211111111, 3.122222222, 1.411111111, -6.8, 1.388888889, 5.333333333, -9.833333333, -22, -19.74444444, -14.62222222, -9.622222222, -8.433333333, -8.5, -2.8, 0.144444444, -3.233333333, -3.411111111, 5.355555556, 8.366666667, 7.333333333, -0.322222222, -6.911111111, -4.955555556, -1.588888889, 4.966666667, 2.5, -4.3, -1.888888889, -1.777777778, 2.477777778, 3.766666667, 0.533333333, 1.755555556, 2.944444444, -4.977777778, -4.055555556, 1.711111111, 6.011111111, 13.15555556, 5.044444444, 6.577777778, 3.388888889, -1.011111111, -0.244444444, -2.477777778, -1.444444444, 2.533333333, -6.333333333, 4.255555556, 1.944444444, 0.855555556, 5.4, -1.244444444, -2.855555556, 4.833333333, 2.722222222, 6.466666667, 14.5, 9.855555556, 2.277777778, -3.188888889, 0.788888889, 4.155555556, 13.41111111, 2.3, 0.855555556, 8.4, -0.444444444, 1.166666667, 7.755555556, -0.288888889, -0.244444444, 8.7, 5.555555556, 8.222222222, 16.26666667, 14.4, 5.711111111, 5.177777778, 4.511111111, 5.988888889, 10.08888889, 10.52222222, 15.37777778, 12.42222222, 14.95555556, 15.22222222, 11.93333333, 6.866666667, 6.866666667, 9.688888889, 11.57777778, 12, 13.34444444, 11.3, 6.222222222, 2.088888889, 8.322222222, 14.05555556, 13.77777778, 16.91111111, 16.86666667, 16.68888889, 18.5, 12.54444444, 12.27777778, 15.91111111, 15.03333333, 22.11111111, 15.77777778, 13.68888889, 17.87777778, 19.94444444, 18.57777778, 18.62222222, 20.11111111, 17.14444444, 20.43333333, 15.75555556, 17.33333333, 20, 23.03333333, 19.61111111, 18.51111111, 15.27777778, 11.44444444, 13.64444444, 11.42222222, 16.14444444, 19.76666667, 18.77777778, 11.88888889, 12.32222222, 20.78888889, 25.04444444, 25.34444444, 23.81111111, 18.35555556, 11.85555556, 18.37777778, 23.15555556, 21.55555556, 17.48888889, 19.05555556, 20.25555556, 23.86666667, 23.86666667, 21.41111111, 21.16666667, 18.67777778, 18.1, 24.4, 19.01111111, 17.13333333, 18.27777778, 21.71111111, 22.85555556, 22.65555556, 25.14444444, 24.13333333, 17.95555556, 14.7, 15.1, 16.02222222, 14.27777778, 11.18888889, 13.65555556, 16.74444444, 16.7, 17.65555556, 16.62222222, 21.68888889, 19.6, 18.6, 15.52222222, 18.53333333, 17.01111111, 17.75555556, 20.47777778, 17.76666667, 22.22222222, 18.23333333, 17.83333333, 15.38888889, 19.64444444, 17.81111111, 15.44444444, 14.88888889, 13.07777778, 15.24444444, 11.82222222, 20.81111111, 21.45555556, 18.98888889, 19.71111111, 19.27777778, 12.7, 15.05555556, 19.15555556, 20.77777778, 15.35555556, 17.68888889, 18.26666667, 15.47777778, 12.76666667, 10.54444444, 13.38888889, 12.54444444, 19.84444444, 19.5, 21.92222222, 17.86666667, 22.44444444, 19.64444444, 20.73333333, 22.02222222, 19, 20.48888889, 19.02222222, 16.44444444, 14.22222222, 16.3, 16.42222222, 17.22222222, 8.322222222, 8.288888889, 13.95555556, 5.555555556, 5.666666667, 7.7, 4.022222222, 11.77777778, 16.42222222, 11.83333333, 9.7, 0.044444444, 3.688888889, -2.077777778, 0.1, -5.388888889, -3.244444444, 0.688888889, 5.744444444, -7.7, -7.022222222, -0.211111111, 4.833333333, 8.111111111, 5.766666667, 7.888888889, 10.43333333, 11.56666667, 10.15555556, 7.155555556, 4.522222222, 7.144444444, 10.88888889, 9.5, 12.13333333, 4.022222222, -3.9, 1.433333333, 0.7, 3.188888889, -1.7, 3.588888889, -0.111111111, -2.788888889, -7.133333333, -5, 0.733333333, -7.555555556, -12.51111111, -8.188888889, 3.122222222, 2.944444444, 0.477777778, -3.2, -9.2, -4.788888889, -0.288888889, 1.077777778, 4.755555556, 5.455555556, 0.511111111, -3.888888889, -7.4, -1.355555556, 5.144444444, 0.122222222, -5.166666667, -5, -5.144444444, -8.822222222, -6.388888889, -6.811111111, -8.944444444, -10.11111111, -7.144444444, -5.133333333, -1.166666667, 1.833333333, -1.477777778, -1.811111111, -2.433333333, -1.188888889, -2.333333333, 0.744444444, 1.877777778, 1.333333333, -1.7, 0.888888889, -3.855555556, -8.211111111, -1.055555556, -4.211111111, -7.355555556, -8.111111111, -10.96666667, -13.05555556, -4.644444444, -7.577777778, ] max = [ -7.233333333, -1.6, 5.488888889, 7.744444444, 6.188888889, 6.555555556, 10.53333333, 6.766666667, 14.1, 14.11111111, 2.044444444, 4.633333333, 2.055555556, 8.666666667, -1.4, -5.555555556, 4.177777778, 11.8, 15.58888889, 12.31111111, 3.666666667, -0.977777778, 1.288888889, 4.211111111, 9.377777778, 5.266666667, 2.144444444, 3.977777778, 7.2, 11.94444444, 11.32222222, 4, 6.611111111, 8.211111111, 3.5, 8.866666667, 3.6, 3.711111111, 13.12222222, 7.833333333, -3.333333333, -2.166666667, -2.877777778, 5.188888889, 13.12222222, 12.11111111, -0.7, 6.688888889, 14.03333333, -2.433333333, -8.6, -8.244444444, -2.122222222, -2.722222222, 1.266666667, 2.8, 5.7, 6.944444444, 5.066666667, 5.688888889, 13.35555556, 16.66666667, 17.33333333, 7.277777778, 6.388888889, 1.344444444, 9.111111111, 17.96666667, 12.8, 5.8, 6.911111111, 6.822222222, 11.87777778, 13.16666667, 9.233333333, 8.655555556, 10.04444444, 7.022222222, 7.644444444, 8.311111111, 16.71111111, 18.85555556, 12.14444444, 13.27777778, 11.18888889, 7.088888889, 8.255555556, 7.522222222, 9.955555556, 9.933333333, 4.866666667, 15.25555556, 9.244444444, 9.755555556, 14, 8.955555556, 2.344444444, 17.43333333, 12.12222222, 13.46666667, 23, 18.45555556, 12.77777778, 7.211111111, 8.588888889, 14.35555556, 19.01111111, 12.4, 9.155555556, 15.6, 4.955555556, 8.966666667, 16.95555556, 9.511111111, 10.15555556, 16, 14.45555556, 21.02222222, 25.76666667, 20.5, 15.71111111, 11.67777778, 12.81111111, 12.88888889, 17.58888889, 23.12222222, 21.77777778, 24.42222222, 20.05555556, 24.32222222, 18.83333333, 19.56666667, 14.96666667, 19.68888889, 18.57777778, 23, 23.34444444, 20.7, 11.82222222, 11.48888889, 17.52222222, 22.55555556, 20.47777778, 23.01111111, 27.86666667, 30.28888889, 30.3, 22.94444444, 18.57777778, 25.51111111, 24.13333333, 30.01111111, 24.77777778, 20.28888889, 28.67777778, 32.74444444, 31.37777778, 28.52222222, 31.81111111, 27.24444444, 32.53333333, 26.15555556, 24.63333333, 28.3, 31.23333333, 32.21111111, 28.21111111, 23.07777778, 21.64444444, 24.34444444, 19.62222222, 25.14444444, 24.46666667, 23.87777778, 21.28888889, 20.22222222, 29.98888889, 32.04444444, 36.44444444, 36.01111111, 24.85555556, 23.45555556, 29.17777778, 32.25555556, 28.75555556, 30.28888889, 28.85555556, 30.45555556, 31.26666667, 28.86666667, 33.31111111, 30.66666667, 28.67777778, 27.4, 32.2, 25.41111111, 22.23333333, 26.67777778, 30.21111111, 29.15555556, 29.65555556, 31.94444444, 31.43333333, 28.35555556, 24.8, 25.5, 25.42222222, 24.17777778, 20.88888889, 24.35555556, 25.54444444, 22, 27.95555556, 29.42222222, 28.88888889, 26.8, 28.2, 26.92222222, 24.13333333, 22.61111111, 26.15555556, 30.57777778, 30.86666667, 29.92222222, 27.33333333, 23.43333333, 24.68888889, 26.94444444, 28.81111111, 25.54444444, 22.48888889, 21.67777778, 19.74444444, 23.82222222, 25.91111111, 30.85555556, 28.48888889, 29.21111111, 28.37777778, 22.4, 25.55555556, 27.35555556, 30.67777778, 27.95555556, 25.98888889, 23.46666667, 25.37777778, 20.46666667, 22.54444444, 20.18888889, 22.24444444, 26.84444444, 25.8, 29.62222222, 26.36666667, 32.24444444, 29.84444444, 28.33333333, 31.22222222, 29.9, 29.98888889, 27.42222222, 25.54444444, 20.22222222, 24, 24.52222222, 25.02222222, 16.12222222, 17.58888889, 23.25555556, 15.75555556, 18.66666667, 18.4, 12.52222222, 20.07777778, 28.62222222, 17.23333333, 16.6, 13.34444444, 10.98888889, 9.522222222, 5.8, 6.811111111, 6.555555556, 12.18888889, 12.64444444, 4.2, 3.577777778, 8.888888889, 15.23333333, 16.11111111, 18.36666667, 16.98888889, 15.63333333, 16.46666667, 15.55555556, 15.65555556, 17.42222222, 18.74444444, 19.48888889, 15.9, 19.73333333, 13.02222222, 8.1, 8.933333333, 11.3, 12.38888889, 8.3, 12.38888889, 6.388888889, 4.211111111, 4.666666667, 0.7, 7.133333333, 2.344444444, 1.088888889, 0.111111111, 11.62222222, 10.84444444, 8.777777778, 3.5, 3.4, 7.211111111, 5.711111111, 9.677777778, 12.25555556, 10.15555556, 6.511111111, 4.911111111, 1.5, 11.44444444, 15.54444444, 8.122222222, 6.233333333, 7, 4.355555556, 0.277777778, 3.711111111, 2.888888889, 1.555555556, 3.888888889, 4.555555556, 5.666666667, 7.833333333, 9.833333333, 10.02222222, 6.288888889, 5.366666667, 11.41111111, 9.566666667, 9.744444444, 13.57777778, 9.433333333, 3.1, 11.08888889, 3.844444444, 2.488888889, 7.544444444, 4.488888889, -0.455555556, -2.111111111, -3.566666667, -1.955555556, 3.955555556, 1.222222222, ] start = 50 size = 100 data = {"Date": dates[start:size], "Temp°C": temp[start:size], "Min": min[start:size], "Max": max[start:size]} page = """ # Line - Style <|{data}|chart|mode=lines|x=Date|y[1]=Temp°C|y[2]=Min|y[3]=Max|line[1]=dash|color[2]=blue|color[3]=red|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = [ { "x": [1, 2, 3, 4], "y": [10, 11, 12, 13], }, { "x": [1, 2, 3, 4], "y": [11, 12, 13, 14], }, { "x": [1, 2, 3, 4], "y": [12, 13, 14, 15], }, ] options = [ # First data set is represented by increasingly large # disks, getting more and more opaque {"marker": {"color": "red", "size": [12, 22, 32, 42], "opacity": [0.2, 0.5, 0.7, 1]}}, # Second data set is represented with a different symbol # for each data point { "marker": {"color": "blue", "size": 18, "symbol": ["circle", "square", "diamond", "cross"]}, }, # Third data set is represented with green disks surrounded # by a red circle that becomes thicker and thicker { "marker": {"color": "green", "size": 20, "line": {"color": "red", "width": [2, 4, 6, 8]}}, }, ] markers = [ # First data set is represented by increasingly large # disks, getting more and more opaque {"color": "red", "size": [12, 22, 32, 42], "opacity": [0.2, 0.5, 0.7, 1]}, # Second data set is represented with a different symbol # for each data point {"color": "blue", "size": 18, "symbol": ["circle", "square", "diamond", "cross"]}, # Third data set is represented with green disks surrounded # by a red circle that becomes thicker and thicker {"color": "green", "size": 20, "line": {"color": "red", "width": [2, 4, 6, 8]}}, ] layout = { # Hide the chart legend "showlegend": False, # Remove all ticks from the x axis "xaxis": {"showticklabels": False}, # Remove all ticks from the y axis "yaxis": {"showticklabels": False}, } page = """ ## Scatter - Customize markers <|{data}|chart|mode=markers|layout={layout}|marker={markers}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = { "Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], "Milk": [80, 85, 95, 120, 140, 130, 145, 150, 120, 100, 90, 110], "Bread": [100, 90, 85, 90, 100, 110, 105, 95, 100, 110, 120, 125], "Apples": [50, 65, 70, 65, 70, 75, 85, 70, 60, 65, 70, 80], } # Name of the three sets to trace items = ["Milk", "Bread", "Apples"] options = { # Group all traces in the same stack group "stackgroup": "first_group" } page = """ # Filled Area - Stacked <|{data}|chart|mode=none|x=Month|y={items}|options={options}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Data set data = [ { # The quarterly periods are grouped by year "Period": [["Carry", "Q1", "Q2", "Q3", "Q4", "Current"], ["N-1", "N", "N", "N", "N", "N+1"]] }, { "Cash Flow": [25, -17, 12, 18, -8, None], "Measure": ["absolute", "relative", "relative", "relative", "relative", "total"], }, ] page = """ # Waterfall - Period levels <|{data}|chart|type=waterfall|x=0/Period|y=1/Cash Flow|measure=1/Measure|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Major countries and their surface (in km2), for every continent # Source: https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_area continents = { "Africa": [ {"name": "Algeria", "surface": 2381741}, {"name": "Dem. Rep. Congo", "surface": 2344858}, {"name": "Sudan", "surface": 1886068}, {"name": "Libya", "surface": 1759540}, {"name": "Chad", "surface": 1284000}, ], "Asia": [ {"name": "Russia-Asia", "surface": 17098246}, {"name": "China", "surface": 9596961}, {"name": "India", "surface": 3287263}, {"name": "Kazakhstan", "surface": 2724900}, {"name": "Saudi Arabia", "surface": 2149690}, ], "Europe": [ {"name": "Russia-Eur", "surface": 3972400}, {"name": "Ukraine", "surface": 603628}, {"name": "France", "surface": 551695}, {"name": "Spain", "surface": 498980}, {"name": "Sweden", "surface": 450295}, ], "Americas": [ {"name": "Canada", "surface": 9984670}, {"name": "U.S.A.", "surface": 9833517}, {"name": "Brazil", "surface": 8515767}, {"name": "Argentina", "surface": 2780400}, {"name": "Mexico", "surface": 1964375}, ], "Oceania": [ {"name": "Australia", "surface": 7692024}, {"name": "Papua New Guinea", "surface": 462840}, {"name": "New Zealand", "surface": 270467}, {"name": "Solomon Islands", "surface": 28896}, {"name": "Fiji", "surface": 18274}, ], "Antarctica": [{"name": "Whole", "surface": 14200000}], } name = [] surface = [] continent = [] for continent_name, countries in continents.items(): # Create continent in root rectangle name.append(continent_name) surface.append(0) continent.append("") # Create countries in that continent rectangle for country in countries: name.append(country["name"]) surface.append(country["surface"]) continent.append(continent_name) data = {"names": name, "surfaces": surface, "continent": continent} page = """ # TreeMap - Hierarchical values <|{data}|chart|type=treemap|labels=names|values=surfaces|parents=continent|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import datetime from taipy.gui import Gui # Retrieved history: # (Open, Close, Low, High) stock_history = [ (311.05, 311.00, 310.75, 311.33), (308.53, 308.31, 307.72, 309.00), (307.35, 306.24, 306.12, 307.46), (306.35, 304.90, 304.34, 310.10), (304.90, 302.99, 302.27, 307.00), (303.03, 301.66, 301.20, 303.25), (301.61, 299.58, 299.50, 301.89), (299.58, 297.95, 297.80, 300.06), (297.95, 299.03, 297.14, 299.67), (299.03, 301.87, 296.71, 301.89), (301.89, 299.40, 298.73, 302.93), (299.50, 299.35, 298.83, 299.50), (299.35, 299.20, 299.19, 299.68), (299.42, 300.50, 299.42, 300.50), (300.70, 300.65, 300.32, 300.75), (300.65, 299.91, 299.91, 300.76), ] start_date = datetime.datetime(year=2022, month=10, day=21) period = datetime.timedelta(seconds=4 * 60 * 60) # 4 hours data = { # Compute date series "Date": [start_date + n * period for n in range(0, len(stock_history))], # Extract open values "Open": [v[0] for v in stock_history], # Extract close values "Close": [v[1] for v in stock_history], # Extract low values "Low": [v[2] for v in stock_history], # Extract high values "High": [v[3] for v in stock_history], } md = """ # Candlestick - Timeline <|{data}|chart|type=candlestick|x=Date|open=Open|close=Close|low=Low|high=High|> """ Gui(md).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = { "John_us": [500, 450, 340, 230, 220, 110], "John_eu": [600, 500, 400, 300, 200, 100], "Robert_us": [510, 480, 440, 330, 220, 100], "Robert_eu": [360, 250, 240, 130, 120, 60], } # Values for each trace values = ["John_us", "John_eu", "Robert_us", "Robert_eu"] options = [ # For John/US { "scalegroup": "first", "textinfo": "value", "title": { # "position": "top", "text": "John in the U.S." }, # Lower-left corner "domain": {"x": [0, 0.5], "y": [0, 0.5]}, }, # For John/EU { "scalegroup": "first", "textinfo": "value", "title": { # "position": "top", "text": "John in the E.U." }, # Upper-left corner "domain": {"x": [0, 0.5], "y": [0.55, 1]}, }, # For Robert/US { "scalegroup": "second", "textinfo": "value", "title": { # "position": "top", "text": "Robert in the U.S." }, # Lower-right corner "domain": {"x": [0.51, 1], "y": [0, 0.5]}, }, # For Robert/EU { "scalegroup": "second", "textinfo": "value", "title": { # "position": "top", "text": "Robert in the E.U." }, # Upper-right corner "domain": {"x": [0.51, 1], "y": [0.51, 1]}, }, ] layout = { "title": "Sales per Salesman per Region", "showlegend": False, # Draw frames around each trace "shapes": [ {"x0": 0, "x1": 0.5, "y0": 0, "y1": 0.5}, {"x0": 0, "x1": 0.5, "y0": 0.52, "y1": 1}, {"x0": 0.52, "x1": 1, "y0": 0, "y1": 0.5}, {"x0": 0.52, "x1": 1, "y0": 0.52, "y1": 1}, ], } page = """ # Funnel Area - Multiple Charts <|{data}|chart|type=funnelarea|values={values}|options={options}|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import math from taipy.gui import Gui # One data point for each degree theta = range(0, 360) # Parametric equation that draws a shape (source Wolfram Mathworld) def draw_heart(angle): a = math.radians(angle) sa = math.sin(a) return 2 - 2 * sa + sa * (math.sqrt(math.fabs(math.cos(a))) / (sa + 1.4)) data = { # Create the heart shape "r": [draw_heart(angle) for angle in theta], "theta": theta, } options = {"fill": "toself"} layout = { # Hide the legend "showlegend": False, "polar": { # Hide the angular axis "angularaxis": {"visible": False}, # Hide the radial axis "radialaxis": {"visible": False}, }, } page = """ # Polar - Area <|{data}|chart|type=scatterpolar|mode=none|layout={layout}|options={options}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Partial family tree of the British House of Windsor # Source: https://en.wikipedia.org/wiki/Family_tree_of_the_British_royal_family tree = { "name": [ "Queen Victoria", "Princess Victoria", "Edward VII", "Alice", "Alfred", "Wilhelm II", "Albert Victor", "George V", "Louise", "Ernest Louis", "Alfred (2)", "Marie", "Victoria Melita", "Edward VIII", "George VI", "Mary", "Elizabeth II", "Margaret", "Charles III", "Anne", "Andrew", ], "parent": [ "", "Queen Victoria", "Queen Victoria", "Queen Victoria", "Queen Victoria", "Princess Victoria", "Edward VII", "Edward VII", "Edward VII", "Alice", "Alfred", "Alfred", "Alfred", "George V", "George V", "George V", "George VI", "George VI", "Elizabeth II", "Elizabeth II", "Elizabeth II", ], } page = """ # TreeMap - Hierarchical <|{tree}|chart|type=treemap|labels=name|parents=parent|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # You may need to install the scikit-learn package as well. # ----------------------------------------------------------------------------------------- import numpy as np import pandas as pd from sklearn.datasets import make_classification from taipy.gui import Gui # Let scikit-learn generate a random 2-class classification problem n_samples = 100 features, label = make_classification(n_samples=n_samples, n_features=2, n_informative=2, n_redundant=0) random_data = pd.DataFrame({"x": features[:, 0], "y": features[:, 1], "label": label}) data_x = random_data["x"] class_A = [random_data.loc[i, "y"] if random_data.loc[i, "label"] == 0 else np.nan for i in range(n_samples)] class_B = [random_data.loc[i, "y"] if random_data.loc[i, "label"] == 1 else np.nan for i in range(n_samples)] data = {"x": random_data["x"], "Class A": class_A, "Class B": class_B} marker_A = {"symbol": "circle-open", "size": 16} marker_B = {"symbol": "triangle-up-dot", "size": 20, "opacity": 0.7} page = """ # Scatter - Styling <|{data}|chart|mode=markers|x=x|y[1]=Class A|y[2]=Class B|width=60%|marker[1]={marker_A}|marker[2]={marker_B}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = { "Temperatures": [ [17.2, 27.4, 28.6, 21.5], [5.6, 15.1, 20.2, 8.1], [26.6, 22.8, 21.8, 24.0], [22.3, 15.5, 13.4, 19.6], ], "Cities": ["Hanoi", "Paris", "Rio", "Sydney"], "Seasons": ["Winter", "Spring", "Summer", "Autumn"], } options = {"colorscale": "Portland"} page = """ # Heatmap - Colorscale <|{data}|chart|type=heatmap|z=Temperatures|x=Seasons|y=Cities|options={options}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui layout = { "xaxis": { # Force the title of the x axis "title": "Values for x" } } page = """ # Basics - Title <|{[x*x for x in range(0, 11)]}|chart|title=Plotting x squared|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Data set: the first 10 elements of the Fibonacci sequence n_numbers = 10 fibonacci = [0, 1] for i in range(2, n_numbers): fibonacci.append(fibonacci[i - 1] + fibonacci[i - 2]) data = {"index": [i for i in range(1, n_numbers + 1)], "fibonacci": fibonacci} page = """ # TreeMap - Simple <|{data}|chart|type=treemap|labels=index|values=fibonacci|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy import Gui # The chart control's data is defined as inline # code. page = """ # Basics - Simple line <|{[x*x for x in range(0, 11)]}|chart|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import random from taipy import Gui # Random data set data = [random.gauss(0, 5) for i in range(1000)] page = """ # Histogram - Simple <|{data}|chart|type=histogram|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import pandas from taipy.gui import Gui # Source https://en.wikipedia.org/wiki/List_of_United_States_presidential_elections_by_popular_vote_margin percentages = [ (1852, 50.83), (1856, 45.29), (1860, 39.65), (1864, 55.03), (1868, 52.66), (1872, 55.58), (1876, 47.92), (1880, 48.31), (1884, 48.85), (1888, 47.80), (1892, 46.02), (1896.0, 51.02), (1900, 51.64), (1904, 56.42), (1908, 51.57), (1912, 41.84), (1916, 49.24), (1920, 60.32), (1924, 54.04), (1928, 58.21), (1932, 57.41), (1936, 60.80), (1940, 54.74), (1944, 53.39), (1948, 49.55), (1952, 55.18), (1956, 57.37), (1960, 49.72), (1964, 61.05), (1968, 43.42), (1972, 60.67), (1976, 50.08), (1980, 50.75), (1984, 58.77), (1988, 53.37), (1992, 43.01), (1996, 49.23), (2000, 47.87), (2004, 50.73), (2008, 52.93), (2012, 51.06), (2016, 46.09), (2020, 51.31), ] data = pandas.DataFrame(percentages, columns=["Year", "%"]) page = """ # Bar - Simple <|{data}|chart|type=bar|x=Year|y=%|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import random from taipy.gui import Gui # Random set of 100 samples samples = {"x": [random.gauss() for i in range(100)]} # Use the same data for both traces data = [samples, samples] options = [ # First data set displayed as green-ish, and 5 bins {"marker": {"color": "#4A4"}, "nbinsx": 5}, # Second data set displayed as red-ish, and 25 bins {"marker": {"color": "#A33"}, "nbinsx": 25}, ] layout = { # Overlay the two histograms "barmode": "overlay", # Hide the legend "showlegend": False, } page = """ # Histogram - NBins <|{data}|chart|type=histogram|options={options}|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Data set data = {"Opps": ["Hot leads", "Doc sent", "Quote", "Closed Won"], "Visits": [316, 238, 125, 83]} page = """ # Funnel Chart - Simple <|{data}|chart|type=funnel|x=Visits|y=Opps|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = [ { "Temperatures": [ [17.2, 27.4, 28.6, 21.5], [5.6, 15.1, 20.2, 8.1], [26.6, 22.8, 21.8, 24.0], [22.3, 15.5, 13.4, 19.6], [3.9, 18.9, 25.7, 9.8], ], "Cities": ["Hanoi", "Paris", "Rio", "Sydney", "Washington"], }, {"Seasons": ["Winter", "Spring", "Summer", "Autumn"]}, ] page = """ # Heatmap - Unbalanced <|{data}|chart|type=heatmap|z=0/Temperatures|x=1/Seasons|y=0/Cities|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Sample small plot definition trace = { "r": [1, 2, 3, 4, 1], "theta": [0, 40, 80, 120, 160], } # The same data is used in both traces data = [trace, trace] # Naming the subplot is mandatory to get them both in # the same chart options = [ { "subplot": "polar", }, {"subplot": "polar2"}, ] layout = { # Hide the legend "showlegend": False, # Restrict the angular values for second trace "polar2": {"sector": [30, 130]}, } md = """ # Polar - Sectors <|{data}|chart|type=scatterpolar|layout={layout}|options={options}|> """ Gui(md).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # You may need to install the yfinance package as well. # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = { "x": [1, 2, 3], "y": [1, 2, 3], "Colors": ["blue", "green", "red"], "Sizes": [20, 40, 30], "Opacities": [1, 0.4, 1], } marker = {"color": "Colors", "size": "Sizes", "opacity": "Opacities"} page = """ # Bubble - Simple <|{data}|chart|mode=markers|x=x|y=y|marker={marker}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Source: www.statista.com (Most used programming languages in 2022) data = { # List of programming languages "Language": ["JavaScript", "HTML/CSS", "SQL", "Python", "Typescript", "Java", "Bash/Shell"], # Percentage of usage, per language "%": [65.36, 55.08, 49.43, 48.07, 34.83, 33.27, 29.07], } # Close the shape for a nice-looking stroke # If the first point is *not* appended to the end of the list, # then the shape does not look as it is closed. data["%"].append(data["%"][0]) data["Language"].append(data["Language"][0]) layout = { "polar": { "radialaxis": { # Force the radial range to 0-100 "range": [0, 100], } }, # Hide legend "showlegend": False, } options = { # Fill the trace "fill": "toself" } md = """ # Radar - Simple <|{data}|chart|type=scatterpolar|r=%|theta=Language|options={options}|layout={layout}|> """ Gui(md).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Initial data set. y = count_of(x) samples = {"x": ["Apples", "Apples", "Apples", "Oranges", "Bananas", "Oranges"], "y": [5, 10, 3, 8, 5, 2]} # Create a data set array to allow for two traces data = [samples, samples] # Gather those settings in a single dictionary properties = { # 'x' of the first trace is the 'x' data from the first element of data "x[1]": "0/x", # 'y' of the first trace is the 'y' data from the first element of data "y[1]": "0/y", # 'x' of the second trace is the 'x' data from the second element of data "x[2]": "1/x", # 'y' of the second trace is the 'y' data from the second element of data "y[2]": "1/y", # Data set colors "color": ["#cd5c5c", "#505070"], # Data set names (for the legend) "name": ["Count", "Sum"], # Configure the binning functions "options": [ # First trace: count the bins {"histfunc": "count"}, # Second trace: sum the bin occurences {"histfunc": "sum"}, ], # Set x axis name "layout": {"xaxis": {"title": "Fruit"}}, } page = """ # Histogram - Binning function <|{data}|chart|type=histogram|properties={properties}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Skill categories skills = ["HTML", "CSS", "Java", "Python", "PHP", "JavaScript", "Photoshop"] data = [ # Proportion of skills used for Backend development {"Backend": [10, 10, 80, 70, 90, 30, 0], "Skills": skills}, # Proportion of skills used for Frontend development {"Frontend": [90, 90, 0, 10, 20, 80, 60], "Skills": skills}, ] # Append first elements to all arrays for a nice stroke skills.append(skills[0]) data[0]["Backend"].append(data[0]["Backend"][0]) data[1]["Frontend"].append(data[1]["Frontend"][0]) layout = { # Force the radial axis displayed range "polar": {"radialaxis": {"range": [0, 100]}} } # Fill the trace options = {"fill": "toself"} # Reflected in the legend names = ["Backend", "Frontend"] # To shorten the chart control definition r = ["0/Backend", "1/Frontend"] theta = ["0/Skills", "1/Skills"] page = """ # Radar - Multiple <|{data}|chart|type=scatterpolar|name={names}|r={r}|theta={theta}|options={options}|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # x values are [-10..10] x_range = range(-10, 11) # The data set holds the _x_ series and two distinct series for _y_ data = { "x": x_range, # y1 = x*x "y1": [x * x for x in x_range], # y2 = 2-x*x/50 "y2": [(100 - x * x) / 50 for x in x_range], } layout = { "yaxis2": { # Second axis overlays with the first y axis "overlaying": "y", # Place the second axis on the right "side": "right", # and give it a title "title": "Second y axis", }, "legend": { # Place the legend above chart "yanchor": "bottom" }, } page = """ # Basics - Multiple axis Shared axis: <|{data}|chart|x=x|y[1]=y1|y[2]=y2|height=300px|> With two axis: <|{data}|chart|x=x|y[1]=y1|y[2]=y2|yaxis[2]=y2|layout={layout}|height=300px|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Source https://www.fao.org/faostat/en/#data/SDGB data = { "Country": [ "Rest of the world", "Russian Federation", "Brazil", "Canada", "United States of America", "China", "Australia", "Democratic Republic of the Congo", "Indonesia", "Peru", ], "Area": [1445674.66, 815312, 496620, 346928, 309795, 219978, 134005, 126155, 92133.2, 72330.4], } page = """ # Pie - Simple <|{data}|chart|type=pie|values=Area|label=Country|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # You may need to install the scikit-learn package as well. # ----------------------------------------------------------------------------------------- from os.path import exists from sklearn.datasets import make_regression from sklearn.linear_model import LinearRegression from taipy.gui import Gui # Let scikit-learn generate a random regression problem n_samples = 300 X, y, coef = make_regression(n_samples=n_samples, n_features=1, n_informative=1, n_targets=1, noise=25, coef=True) model = LinearRegression().fit(X, y) x_data = X.flatten() y_data = y.flatten() predict = model.predict(X) data = {"x": x_data, "y": y_data, "Regression": predict} page = """ # Scatter - Regression <|{data}|chart|x=x|y[1]=y|mode[1]=markers|y[2]=Regression|mode[2]=line|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = { "x": [1, 2, 3], "y": [1, 2, 3], "Texts": ["Blue<br>Small", "Green<br>Medium", "Red<br>Large"], "Sizes": [60, 80, 100], "Colors": [ "rgb(93, 164, 214)", "rgb(44, 160, 101)", "rgb(255, 65, 54)", ], } marker = {"size": "Sizes", "color": "Colors"} page = """ # Bubble - Hover text <|{data}|chart|mode=markers|x=x|y=y|marker={marker}|text=Texts|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = { "Temperatures": [ [17.2, 27.4, 28.6, 21.5], [5.6, 15.1, 20.2, 8.1], [26.6, 22.8, 21.8, 24.0], [22.3, 15.5, 13.4, 19.6], ], "Cities": ["Hanoi", "Paris", "Rio", "Sydney"], "Seasons": ["Winter", "Spring", "Summer", "Autumn"], } layout = { # This array contains the information we want to display in the cells # These are filled later "annotations": [], # No ticks on the x axis, show labels on top the of the chart "xaxis": {"ticks": "", "side": "top"}, # No ticks on the y axis # Add a space character for a small margin with the text "yaxis": {"ticks": "", "ticksuffix": " "}, } seasons = data["Seasons"] cities = data["Cities"] # Iterate over all cities for city in range(len(cities)): # Iterate over all seasons for season in range(len(seasons)): temperature = data["Temperatures"][city][season] # Create the annotation annotation = { # The name of the season "x": seasons[season], # The name of the city "y": cities[city], # The temperature, as a formatted string "text": f"{temperature}\N{DEGREE SIGN}C", # Change the text color depending on the temperature # so it results in a better contrast "font": {"color": "white" if temperature < 14 else "black"}, # Remove the annotation arrow "showarrow": False, } # Add the annotation to the layout's annotations array layout["annotations"].append(annotation) page = """ ## Heatmap - Annotated <|{data}|chart|type=heatmap|z=Temperatures|x=Seasons|y=Cities|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Function to plot: x^3/3 - x def f(x): return x * x * x / 3 - x # x values: [-2.2, ..., 2.2] x = [(x - 10) / 4.5 for x in range(0, 21)] data = { "x": x, # y: [f(-2.2), ..., f(2.2)] "y": [f(x) for x in x], } layout = { # Chart title "title": "Local extrema", "annotations": [ # Annotation for local maximum (x = -1) {"text": "Local <b>max</b>", "font": {"size": 20}, "x": -1, "y": f(-1)}, # Annotation for local minimum (x = 1) {"text": "Local <b>min</b>", "font": {"size": 20}, "x": 1, "y": f(1), "xanchor": "left"}, ], } page = """ # Advanced - Annotations <|{data}|chart|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = { "Types": ["Website visit", "Downloads", "Prospects", "Invoice sent", "Closed"], "Visits_us": [13873, 10533, 5443, 2703, 908], "Visits_eu": [7063, 4533, 3443, 1003, 1208], "Visits_ap": [6873, 2533, 3443, 1703, 508], } # Columns for each trace x = ["Visits_us", "Visits_eu", "Visits_ap"] # Legend text for each trace names = ["US", "EU", "AP"] page = """ # Funnel - Multiple traces <|{data}|chart|type=funnel|x={x}|y=Types|name={names}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = { "Temperatures": [ [17.2, 27.4, 28.6, 21.5], [5.6, 15.1, 20.2, 8.1], [26.6, 22.8, 21.8, 24.0], [22.3, 15.5, 13.4, 19.6], ], "Cities": ["Hanoi", "Paris", "Rio", "Sydney"], "Seasons": ["Winter", "Spring", "Summer", "Autumn"], } page = """ # Heatmap - Basic <|{data}|chart|type=heatmap|z=Temperatures|x=Seasons|y=Cities|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import numpy import pandas from taipy.gui import Gui # Largest cities: name, location and population # Source: https://simplemaps.com/data/world-cities cities = [ {"name": "Tokyo", "lat": 35.6839, "lon": 139.7744, "population": 39105000}, {"name": "Jakarta", "lat": -6.2146, "lon": 106.8451, "population": 35362000}, {"name": "Delhi", "lat": 28.6667, "lon": 77.2167, "population": 31870000}, {"name": "Manila", "lat": 14.6, "lon": 120.9833, "population": 23971000}, {"name": "São Paulo", "lat": -23.5504, "lon": -46.6339, "population": 22495000}, {"name": "Seoul", "lat": 37.56, "lon": 126.99, "population": 22394000}, {"name": "Mumbai", "lat": 19.0758, "lon": 72.8775, "population": 22186000}, {"name": "Shanghai", "lat": 31.1667, "lon": 121.4667, "population": 22118000}, {"name": "Mexico City", "lat": 19.4333, "lon": -99.1333, "population": 21505000}, {"name": "Guangzhou", "lat": 23.1288, "lon": 113.259, "population": 21489000}, {"name": "Cairo", "lat": 30.0444, "lon": 31.2358, "population": 19787000}, {"name": "Beijing", "lat": 39.904, "lon": 116.4075, "population": 19437000}, {"name": "New York", "lat": 40.6943, "lon": -73.9249, "population": 18713220}, {"name": "Kolkāta", "lat": 22.5727, "lon": 88.3639, "population": 18698000}, {"name": "Moscow", "lat": 55.7558, "lon": 37.6178, "population": 17693000}, {"name": "Bangkok", "lat": 13.75, "lon": 100.5167, "population": 17573000}, {"name": "Dhaka", "lat": 23.7289, "lon": 90.3944, "population": 16839000}, {"name": "Buenos Aires", "lat": -34.5997, "lon": -58.3819, "population": 16216000}, {"name": "Ōsaka", "lat": 34.752, "lon": 135.4582, "population": 15490000}, {"name": "Lagos", "lat": 6.45, "lon": 3.4, "population": 15487000}, {"name": "Istanbul", "lat": 41.01, "lon": 28.9603, "population": 15311000}, {"name": "Karachi", "lat": 24.86, "lon": 67.01, "population": 15292000}, {"name": "Kinshasa", "lat": -4.3317, "lon": 15.3139, "population": 15056000}, {"name": "Shenzhen", "lat": 22.535, "lon": 114.054, "population": 14678000}, {"name": "Bangalore", "lat": 12.9791, "lon": 77.5913, "population": 13999000}, {"name": "Ho Chi Minh City", "lat": 10.8167, "lon": 106.6333, "population": 13954000}, {"name": "Tehran", "lat": 35.7, "lon": 51.4167, "population": 13819000}, {"name": "Los Angeles", "lat": 34.1139, "lon": -118.4068, "population": 12750807}, {"name": "Rio de Janeiro", "lat": -22.9083, "lon": -43.1964, "population": 12486000}, {"name": "Chengdu", "lat": 30.66, "lon": 104.0633, "population": 11920000}, {"name": "Baoding", "lat": 38.8671, "lon": 115.4845, "population": 11860000}, {"name": "Chennai", "lat": 13.0825, "lon": 80.275, "population": 11564000}, {"name": "Lahore", "lat": 31.5497, "lon": 74.3436, "population": 11148000}, {"name": "London", "lat": 51.5072, "lon": -0.1275, "population": 11120000}, {"name": "Paris", "lat": 48.8566, "lon": 2.3522, "population": 11027000}, {"name": "Tianjin", "lat": 39.1467, "lon": 117.2056, "population": 10932000}, {"name": "Linyi", "lat": 35.0606, "lon": 118.3425, "population": 10820000}, {"name": "Shijiazhuang", "lat": 38.0422, "lon": 114.5086, "population": 10784600}, {"name": "Zhengzhou", "lat": 34.7492, "lon": 113.6605, "population": 10136000}, {"name": "Nanyang", "lat": 32.9987, "lon": 112.5292, "population": 10013600}, {"name": "Hyderābād", "lat": 17.3617, "lon": 78.4747, "population": 9840000}, {"name": "Wuhan", "lat": 30.5872, "lon": 114.2881, "population": 9729000}, {"name": "Handan", "lat": 36.6116, "lon": 114.4894, "population": 9549700}, {"name": "Nagoya", "lat": 35.1167, "lon": 136.9333, "population": 9522000}, {"name": "Weifang", "lat": 36.7167, "lon": 119.1, "population": 9373000}, {"name": "Lima", "lat": -12.06, "lon": -77.0375, "population": 8992000}, {"name": "Zhoukou", "lat": 33.625, "lon": 114.6418, "population": 8953172}, {"name": "Luanda", "lat": -8.8383, "lon": 13.2344, "population": 8883000}, {"name": "Ganzhou", "lat": 25.8292, "lon": 114.9336, "population": 8677600}, {"name": "Tongshan", "lat": 34.261, "lon": 117.1859, "population": 8669000}, {"name": "Kuala Lumpur", "lat": 3.1478, "lon": 101.6953, "population": 8639000}, {"name": "Chicago", "lat": 41.8373, "lon": -87.6862, "population": 8604203}, {"name": "Heze", "lat": 35.2333, "lon": 115.4333, "population": 8287693}, {"name": "Chongqing", "lat": 29.55, "lon": 106.5069, "population": 8261000}, {"name": "Hanoi", "lat": 21.0245, "lon": 105.8412, "population": 8246600}, {"name": "Fuyang", "lat": 32.8986, "lon": 115.8045, "population": 8200264}, {"name": "Changsha", "lat": 28.1987, "lon": 112.9709, "population": 8154700}, {"name": "Dongguan", "lat": 23.0475, "lon": 113.7493, "population": 8142000}, {"name": "Jining", "lat": 35.4, "lon": 116.5667, "population": 8081905}, {"name": "Jinan", "lat": 36.6667, "lon": 116.9833, "population": 7967400}, {"name": "Pune", "lat": 18.5196, "lon": 73.8553, "population": 7948000}, {"name": "Foshan", "lat": 23.0292, "lon": 113.1056, "population": 7905700}, {"name": "Bogotá", "lat": 4.6126, "lon": -74.0705, "population": 7743955}, {"name": "Ahmedabad", "lat": 23.03, "lon": 72.58, "population": 7717000}, {"name": "Nanjing", "lat": 32.05, "lon": 118.7667, "population": 7729000}, {"name": "Changchun", "lat": 43.9, "lon": 125.2, "population": 7674439}, {"name": "Tangshan", "lat": 39.6292, "lon": 118.1742, "population": 7577289}, {"name": "Cangzhou", "lat": 38.3037, "lon": 116.8452, "population": 7544300}, {"name": "Dar es Salaam", "lat": -6.8, "lon": 39.2833, "population": 7461000}, {"name": "Hefei", "lat": 31.8639, "lon": 117.2808, "population": 7457027}, {"name": "Hong Kong", "lat": 22.3069, "lon": 114.1831, "population": 7398000}, {"name": "Shaoyang", "lat": 27.2418, "lon": 111.4725, "population": 7370500}, {"name": "Zhanjiang", "lat": 21.1967, "lon": 110.4031, "population": 7332000}, {"name": "Shangqiu", "lat": 34.4259, "lon": 115.6467, "population": 7325300}, {"name": "Nantong", "lat": 31.9829, "lon": 120.8873, "population": 7283622}, {"name": "Yancheng", "lat": 33.3936, "lon": 120.1339, "population": 7260240}, {"name": "Nanning", "lat": 22.8192, "lon": 108.315, "population": 7254100}, {"name": "Hengyang", "lat": 26.8968, "lon": 112.5857, "population": 7243400}, {"name": "Zhumadian", "lat": 32.9773, "lon": 114.0253, "population": 7231234}, {"name": "Shenyang", "lat": 41.8039, "lon": 123.4258, "population": 7208000}, {"name": "Xingtai", "lat": 37.0659, "lon": 114.4753, "population": 7104103}, {"name": "Xi’an", "lat": 34.2667, "lon": 108.9, "population": 7090000}, {"name": "Santiago", "lat": -33.45, "lon": -70.6667, "population": 7026000}, {"name": "Yantai", "lat": 37.3997, "lon": 121.2664, "population": 6968202}, {"name": "Riyadh", "lat": 24.65, "lon": 46.71, "population": 6889000}, {"name": "Luoyang", "lat": 34.6587, "lon": 112.4245, "population": 6888500}, {"name": "Kunming", "lat": 25.0433, "lon": 102.7061, "population": 6850000}, {"name": "Shangrao", "lat": 28.4419, "lon": 117.9633, "population": 6810700}, {"name": "Hangzhou", "lat": 30.25, "lon": 120.1675, "population": 6713000}, {"name": "Bijie", "lat": 27.3019, "lon": 105.2863, "population": 6686100}, {"name": "Quanzhou", "lat": 24.9139, "lon": 118.5858, "population": 6480000}, {"name": "Miami", "lat": 25.7839, "lon": -80.2102, "population": 6445545}, {"name": "Wuxi", "lat": 31.5667, "lon": 120.2833, "population": 6372624}, {"name": "Huanggang", "lat": 30.45, "lon": 114.875, "population": 6333000}, {"name": "Maoming", "lat": 21.6618, "lon": 110.9178, "population": 6313200}, {"name": "Nanchong", "lat": 30.7991, "lon": 106.0784, "population": 6278614}, {"name": "Zunyi", "lat": 27.705, "lon": 106.9336, "population": 6270700}, {"name": "Qujing", "lat": 25.5102, "lon": 103.8029, "population": 6155400}, {"name": "Baghdad", "lat": 33.35, "lon": 44.4167, "population": 6107000}, {"name": "Xinyang", "lat": 32.1264, "lon": 114.0672, "population": 6109106}, ] # Convert to Pandas DataFrame data = pandas.DataFrame(cities) # Add a column holding the bubble size: # Min(population) -> size = 5 # Max(population) -> size = 60 solve = numpy.linalg.solve([[data["population"].min(), 1], [data["population"].max(), 1]], [5, 60]) data["size"] = data["population"].apply(lambda p: p * solve[0] + solve[1]) # Add a column holding the bubble hover texts # Format is "<city name> [<population>]" data["text"] = data.apply(lambda row: f"{row['name']} [{row['population']}]", axis=1) marker = { # Use the "size" column to set the bubble size "size": "size" } layout = {"geo": {"showland": True, "landcolor": "4A4"}} page = """ # Maps - Bubbles <|{data}|chart|type=scattergeo|lat=lat|lon=lon|mode=markers|marker={marker}|text=text|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- # Face-to-face bar charts example import numpy from taipy.gui import Gui n_years = 10 proportions_female = numpy.zeros(n_years) proportions_male = numpy.zeros(n_years) # Prepare the data set with random variations proportions_female[0] = 0.4 proportions_male[0] = proportions_female[0] * (1 + numpy.random.normal(0, 0.1)) for i in range(1, n_years): mean_i = (0.5 - proportions_female[i - 1]) / 5 new_value = proportions_female[i - 1] + numpy.random.normal(mean_i, 0.1) new_value = min(max(0, new_value), 1) proportions_female[i] = new_value proportions_male[i] = proportions_female[i] * (1 + numpy.random.normal(0, 0.1)) data = { "Hobbies": [ "Archery", "Tennis", "Football", "Basket", "Volley", "Golf", "Video-Games", "Reading", "Singing", "Music", ], "Female": proportions_female, # Negate these values so they appear to the left side "Male": -proportions_male, } properties = { # Shared y values "y": "Hobbies", # Bars for the female data set "x[1]": "Female", "color[1]": "#c26391", # Bars for the male data set "x[2]": "Male", "color[2]": "#5c91de", # Both data sets are represented with an horizontal orientation "orientation": "h", # "layout": { # This makes left and right bars aligned on the same y value "barmode": "overlay", # Set a relevant title for the x axis "xaxis": {"title": "Gender"}, # Hide the legend "showlegend": False, "margin": {"l": 100}, }, } page = """ # Bar - Facing <|{data}|chart|type=bar|properties={properties}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import random from taipy.gui import Gui # Random data set data = [random.random() for i in range(100)] # Normalize to show bin probabilities options = {"histnorm": "probability"} page = """ # Histogram - Normalized <|{data}|chart|type=histogram|options={options}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # You may need to install the scikit-learn package as well. # ----------------------------------------------------------------------------------------- import numpy import pandas from sklearn.datasets import make_classification from taipy.gui import Gui # Let scikit-learn generate a random 2-class classification problem features, label = make_classification(n_samples=1000, n_features=2, n_informative=2, n_redundant=0) random_data = pandas.DataFrame({"x": features[:, 0], "y": features[:, 1], "label": label}) data_x = random_data["x"] class_A = [random_data.loc[i, "y"] if random_data.loc[i, "label"] == 0 else numpy.nan for i in range(len(random_data))] class_B = [random_data.loc[i, "y"] if random_data.loc[i, "label"] == 1 else numpy.nan for i in range(len(random_data))] data = {"x": random_data["x"], "Class A": class_A, "Class B": class_B} page = """ # Scatter - Classification <|{data}|chart|mode=markers|x=x|y[1]=Class A|y[2]=Class B|width=60%|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from itertools import accumulate import numpy as np from taipy.gui import Gui grid_size = 10 data = [ { # z is set to: # - 0 if row+col is a multiple of 4 # - 1 if row+col is a multiple of 2 # - 0.5 otherwise "z": [ [0.0 if (row + col) % 4 == 0 else 1 if (row + col) % 2 == 0 else 0.5 for col in range(grid_size)] for row in range(grid_size) ] }, { # A series of coordinates, growing exponentially "x": [0] + list(accumulate(np.logspace(0, 1, grid_size))), # A series of coordinates, shrinking exponentially "y": [0] + list(accumulate(np.logspace(1, 0, grid_size))), }, ] # Axis template used in the layout object axis_template = { # Don't show any line or tick or label "showgrid": False, "zeroline": False, "ticks": "", "showticklabels": False, "visible": False, } layout = {"xaxis": axis_template, "yaxis": axis_template} options = { # Remove the color scale display "showscale": False } page = """ ## Heatmap - Unequal block sizes <|{data}|chart|type=heatmap|z=0/z|x=1/x|y=1/y|layout={layout}|options={options}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # 9-hole course n_holes = 9 # Data set # Each entry holds an array of values. One for each hole, plus one for th data = { # ["Hole1", "Hole2", ..., "Hole9"] "Hole": [f"Hole{h}" for h in range(1, n_holes + 1)] + ["Score"], # Par for each hole "Par": [3, 4, 4, 5, 3, 5, 4, 5, 3] + [None], # Score for each hole "Score": [4, 4, 5, 4, 4, 5, 4, 5, 4] + [None], # Represented as relative values except for the last one "M": n_holes * ["relative"] + ["total"], } # Compute difference (Score-Par) data["Diff"] = [data["Score"][i] - data["Par"][i] for i in range(0, n_holes)] + [None] # Show positive values in red, and negative values in green options = {"decreasing": {"marker": {"color": "green"}}, "increasing": {"marker": {"color": "red"}}} page = """ # Waterfall - Styling <|{data}|chart|type=waterfall|x=Hole|y=Diff|measure=M|options={options}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import random from taipy.gui import Gui # Common axis for all data: [1..10] x = list(range(1, 11)) # Sample data samples = [5, 7, 8, 4, 5, 9, 8, 8, 6, 5] # Generate error data # Error that adds to the input data error_plus = [3 * random.random() + 0.5 for _ in x] # Error substracted from to the input data error_minus = [3 * random.random() + 0.5 for _ in x] # Upper bound (y + error_plus) error_upper = [y + e for (y, e) in zip(samples, error_plus)] # Lower bound (y - error_minus) error_lower = [y - e for (y, e) in zip(samples, error_minus)] data = [ # Trace for samples {"x": x, "y": samples}, # Trace for error range { # Roundtrip around the error bounds: onward then return "x": x + list(reversed(x)), # The two error bounds, with lower bound reversed "y": error_upper + list(reversed(error_lower)), }, ] properties = { # Error data "x[1]": "1/x", "y[1]": "1/y", "options[1]": { # Shows as filled area "fill": "toself", "fillcolor": "rgba(70,70,240,0.6)", "showlegend": False, }, # Don't show surrounding stroke "color[1]": "transparent", # Raw data (displayed on top of the error band) "x[2]": "0/x", "y[2]": "0/y", "color[2]": "rgb(140,50,50)", # Shown in the legend "name[2]": "Input", } page = """ # Continuous Error - Simple <|{data}|chart|properties={properties}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = { "Products": [ "Nail polish", "Eyebrow pencil", "Rouge", "Lipstick", "Eyeshadows", "Eyeliner", "Foundation", "Lip gloss", "Mascara", ], "USA": [12814, 13012, 11624, 8814, 12998, 12321, 10342, 22998, 11261], "China": [3054, 5067, 7004, 9054, 12043, 15067, 10119, 12043, 10419], "EU": [4376, 3987, 3574, 4376, 4572, 3417, 5231, 4572, 6134], "Africa": [4229, 3932, 5221, 9256, 3308, 5432, 13701, 4008, 18712], } # Order the different traces ys = ["USA", "China", "EU", "Africa"] options = [ # For the USA {"stackgroup": "one", "groupnorm": "percent"}, # For China {"stackgroup": "one"}, # For the EU {"stackgroup": "one"}, # For Africa {"stackgroup": "one"}, ] layout = { # Show all values when hovering on a data point "hovermode": "x unified" } page = """ # Filled Area - Stacked Normalized <|{data}|chart|mode=none|x=Products|y={ys}|options={options}|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import math from taipy.gui import Gui # One data point for each degree theta = range(0, 360) # Create a rose-like shaped radius-array def create_rose(n_petals): return [math.cos(math.radians(n_petals * angle)) for angle in theta] data = {"theta": theta, "r1": create_rose(2), "r2": create_rose(3), "r3": create_rose(4)} # We want three traces in the same chart r = ["r1", "r2", "r3"] layout = { # Hide the legend "showlegend": False, "polar": { # Hide the angular axis "angularaxis": {"visible": False}, # Hide the radial axis "radialaxis": {"visible": False}, }, } page = """ # Polar - Multiple <|{data}|chart|type=scatterpolar|mode=lines|r={r}|theta=theta|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # You may need to install the yfinance package as well. # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = { "x": [1, 2, 3, 4, 5], "y": [10, 7, 4, 1, 5], "Sizes": [20, 30, 40, 50, 30], "Symbols": ["circle-open", "triangle-up", "hexagram", "star-diamond", "circle-cross"], } marker = { "color": "#77A", "size": "Sizes", "symbol": "Symbols", } page = """ # Bubble - Symbols <|{data}|chart|mode=markers|x=x|y=y|marker={marker}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # You may need to install the yfinance package as well. # ----------------------------------------------------------------------------------------- import yfinance from taipy.gui import Gui # Extraction of a few days of stock historical data for AAPL using # the yfinance package (see https://pypi.org/project/yfinance/). # The returned value is a Pandas DataFrame. ticker = yfinance.Ticker("AAPL") stock = ticker.history(interval="1d", start="2018-08-18", end="2018-09-10") # Copy the DataFrame index to a new column stock["Date"] = stock.index options = { # Candlesticks that show decreasing values are orange "decreasing": {"line": {"color": "orange"}}, # Candlesticks that show decreasing values are blue "increasing": {"line": {"color": "blue"}}, } layout = { "xaxis": { # Hide the range slider "rangeslider": {"visible": False} } } page = """ # Candlestick - Styling <|{stock}|chart|type=candlestick|x=Date|open=Open|close=Close|low=Low|high=High|options={options}|layout={layout}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui data = { "Types": ["Website visit", "Downloads", "Prospects", "Invoice sent", "Closed"], "Visits": [13873, 10533, 5443, 2703, 908], } marker = { # Boxes are filled with a blue gradient color "color": ["hsl(210,50%,50%)", "hsl(210,60%,60%)", "hsl(210,70%,70%)", "hsl(210,80%,80%)", "hsl(210,90%,90%)"], # Lines get thicker, with an orange-to-green gradient color "line": {"width": [1, 1, 2, 3, 4], "color": ["f5720a", "f39c1d", "f0cc3d", "aadb12", "8cb709"]}, } options = { # Lines connecting boxes are thick, dotted and green "connector": {"line": {"color": "green", "dash": "dot", "width": 4}} } page = """ # Funnel Chart - Custom markers <|{data}|chart|type=funnel|x=Visits|y=Types|marker={marker}|options={options}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import random from taipy.gui import Gui # Random data set data = [random.random() for i in range(500)] options = { # Enable the cumulative histogram "cumulative": {"enabled": True} } page = """ # Histogram - Cumulative <|{data}|chart|type=histogram|options={options}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import numpy import pandas from taipy.gui import Gui dates = pandas.date_range("2023-01-01", periods=365, freq="D") temp = [ -11.33333333, -6, -0.111111111, 1.444444444, 2.388888889, 4.555555556, 4.333333333, 0.666666667, 9, 9.611111111, -0.555555556, 1.833333333, -0.444444444, 2.166666667, -4, -12.05555556, -2.722222222, 5, 9.888888889, 6.611111111, -2.833333333, -3.277777778, -1.611111111, -1.388888889, 5.777777778, 2.166666667, -1.055555556, 1.777777778, 1.5, 8.444444444, 6.222222222, -2.5, -0.388888889, 6.111111111, -1.5, 2.666666667, -2.5, 0.611111111, 8.222222222, 2.333333333, -9.333333333, -7.666666667, -6.277777778, -0.611111111, 7.722222222, 6.111111111, -4, 3.388888889, 9.333333333, -6.333333333, -15, -12.94444444, -8.722222222, -6.222222222, -2.833333333, -2.5, 1.5, 3.444444444, 2.666666667, 0.888888889, 7.555555556, 12.66666667, 12.83333333, 1.777777778, -0.111111111, -1.055555556, 4.611111111, 11.16666667, 8.5, 0.5, 2.111111111, 4.722222222, 8.277777778, 10.66666667, 5.833333333, 5.555555556, 6.944444444, 1.722222222, 2.444444444, 6.111111111, 12.11111111, 15.55555556, 9.944444444, 10.27777778, 5.888888889, 1.388888889, 3.555555556, 1.222222222, 4.055555556, 7.833333333, 0.666666667, 10.05555556, 6.444444444, 4.555555556, 11, 3.555555556, -0.555555556, 11.83333333, 7.222222222, 10.16666667, 17.5, 14.55555556, 6.777777778, 3.611111111, 5.888888889, 10.05555556, 16.61111111, 5.5, 7.055555556, 10.5, 1.555555556, 6.166666667, 11.05555556, 5.111111111, 6.055555556, 11, 11.05555556, 14.72222222, 19.16666667, 16.5, 12.61111111, 8.277777778, 6.611111111, 10.38888889, 15.38888889, 17.22222222, 18.27777778, 18.72222222, 17.05555556, 19.72222222, 16.83333333, 12.66666667, 11.66666667, 12.88888889, 14.77777778, 18, 19.44444444, 16.5, 9.722222222, 7.888888889, 13.72222222, 17.55555556, 18.27777778, 20.11111111, 21.66666667, 23.38888889, 23.5, 16.94444444, 16.27777778, 18.61111111, 20.83333333, 24.61111111, 18.27777778, 17.88888889, 22.27777778, 25.94444444, 25.27777778, 24.72222222, 25.61111111, 23.94444444, 26.33333333, 22.05555556, 20.83333333, 24.5, 27.83333333, 25.61111111, 23.11111111, 19.27777778, 16.44444444, 19.44444444, 17.22222222, 19.44444444, 22.16666667, 21.77777778, 17.38888889, 17.22222222, 23.88888889, 28.44444444, 29.44444444, 29.61111111, 21.05555556, 18.55555556, 25.27777778, 26.55555556, 24.55555556, 23.38888889, 22.55555556, 27.05555556, 27.66666667, 26.66666667, 27.61111111, 26.66666667, 24.77777778, 23, 26.5, 23.11111111, 19.83333333, 22.27777778, 24.61111111, 27.05555556, 27.05555556, 27.94444444, 27.33333333, 22.05555556, 21.5, 22, 19.72222222, 20.27777778, 17.88888889, 18.55555556, 18.94444444, 20, 22.05555556, 23.22222222, 24.38888889, 24.5, 24.5, 21.22222222, 20.83333333, 20.61111111, 22.05555556, 23.77777778, 24.16666667, 24.22222222, 21.83333333, 21.33333333, 21.88888889, 22.44444444, 23.11111111, 20.44444444, 16.88888889, 15.77777778, 17.44444444, 17.72222222, 23.11111111, 24.55555556, 24.88888889, 25.11111111, 25.27777778, 19.5, 19.55555556, 24.05555556, 24.27777778, 21.05555556, 19.88888889, 20.66666667, 20.27777778, 17.66666667, 16.44444444, 15.88888889, 18.44444444, 22.44444444, 23, 24.72222222, 24.16666667, 25.94444444, 24.44444444, 23.33333333, 25.22222222, 25, 23.88888889, 23.72222222, 18.94444444, 16.22222222, 19.5, 21.22222222, 19.72222222, 13.22222222, 11.88888889, 16.55555556, 10.05555556, 12.16666667, 11.5, 10.22222222, 17.27777778, 21.72222222, 13.83333333, 13, 6.944444444, 6.388888889, 4.222222222, 2.5, 1.111111111, 3.055555556, 6.388888889, 10.44444444, -2, -2.222222222, 4.388888889, 8.333333333, 11.11111111, 12.66666667, 10.88888889, 12.83333333, 14.16666667, 12.55555556, 12.05555556, 11.22222222, 12.44444444, 14.38888889, 12, 15.83333333, 6.722222222, 2.5, 4.833333333, 7.5, 8.888888889, 4, 7.388888889, 3.888888889, 1.611111111, -0.333333333, -2, 4.833333333, -1.055555556, -5.611111111, -2.388888889, 5.722222222, 8.444444444, 5.277777778, 0.5, -2.5, 1.111111111, 2.111111111, 5.777777778, 7.555555556, 7.555555556, 4.111111111, -0.388888889, -1, 4.944444444, 9.444444444, 4.722222222, -0.166666667, 0.5, -2.444444444, -2.722222222, -2.888888889, -1.111111111, -4.944444444, -3.111111111, -1.444444444, -0.833333333, 2.333333333, 6.833333333, 4.722222222, 0.888888889, 0.666666667, 4.611111111, 4.666666667, 4.444444444, 6.777777778, 5.833333333, 0.5, 4.888888889, 1.444444444, -2.111111111, 2.444444444, -0.111111111, -2.555555556, -4.611111111, -8.666666667, -8.055555556, 1.555555556, -4.777777778, ] min = [ -14.33333333, -12.9, -3.311111111, -4.955555556, -3.611111111, 0.555555556, 1.133333333, -5.133333333, 2.3, 3.911111111, -7.055555556, -1.366666667, -4.844444444, -3.333333333, -6.1, -17.15555556, -4.822222222, 0.4, 3.488888889, 4.211111111, -6.433333333, -7.577777778, -7.111111111, -7.088888889, 1.577777778, -3.433333333, -4.355555556, -0.722222222, -2.1, 2.044444444, 2.222222222, -4.7, -2.388888889, 4.111111111, -5, -0.133333333, -5.3, -2.288888889, 6.022222222, -1.766666667, -15.53333333, -13.46666667, -9.277777778, -3.211111111, 3.122222222, 1.411111111, -6.8, 1.388888889, 5.333333333, -9.833333333, -22, -19.74444444, -14.62222222, -9.622222222, -8.433333333, -8.5, -2.8, 0.144444444, -3.233333333, -3.411111111, 5.355555556, 8.366666667, 7.333333333, -0.322222222, -6.911111111, -4.955555556, -1.588888889, 4.966666667, 2.5, -4.3, -1.888888889, -1.777777778, 2.477777778, 3.766666667, 0.533333333, 1.755555556, 2.944444444, -4.977777778, -4.055555556, 1.711111111, 6.011111111, 13.15555556, 5.044444444, 6.577777778, 3.388888889, -1.011111111, -0.244444444, -2.477777778, -1.444444444, 2.533333333, -6.333333333, 4.255555556, 1.944444444, 0.855555556, 5.4, -1.244444444, -2.855555556, 4.833333333, 2.722222222, 6.466666667, 14.5, 9.855555556, 2.277777778, -3.188888889, 0.788888889, 4.155555556, 13.41111111, 2.3, 0.855555556, 8.4, -0.444444444, 1.166666667, 7.755555556, -0.288888889, -0.244444444, 8.7, 5.555555556, 8.222222222, 16.26666667, 14.4, 5.711111111, 5.177777778, 4.511111111, 5.988888889, 10.08888889, 10.52222222, 15.37777778, 12.42222222, 14.95555556, 15.22222222, 11.93333333, 6.866666667, 6.866666667, 9.688888889, 11.57777778, 12, 13.34444444, 11.3, 6.222222222, 2.088888889, 8.322222222, 14.05555556, 13.77777778, 16.91111111, 16.86666667, 16.68888889, 18.5, 12.54444444, 12.27777778, 15.91111111, 15.03333333, 22.11111111, 15.77777778, 13.68888889, 17.87777778, 19.94444444, 18.57777778, 18.62222222, 20.11111111, 17.14444444, 20.43333333, 15.75555556, 17.33333333, 20, 23.03333333, 19.61111111, 18.51111111, 15.27777778, 11.44444444, 13.64444444, 11.42222222, 16.14444444, 19.76666667, 18.77777778, 11.88888889, 12.32222222, 20.78888889, 25.04444444, 25.34444444, 23.81111111, 18.35555556, 11.85555556, 18.37777778, 23.15555556, 21.55555556, 17.48888889, 19.05555556, 20.25555556, 23.86666667, 23.86666667, 21.41111111, 21.16666667, 18.67777778, 18.1, 24.4, 19.01111111, 17.13333333, 18.27777778, 21.71111111, 22.85555556, 22.65555556, 25.14444444, 24.13333333, 17.95555556, 14.7, 15.1, 16.02222222, 14.27777778, 11.18888889, 13.65555556, 16.74444444, 16.7, 17.65555556, 16.62222222, 21.68888889, 19.6, 18.6, 15.52222222, 18.53333333, 17.01111111, 17.75555556, 20.47777778, 17.76666667, 22.22222222, 18.23333333, 17.83333333, 15.38888889, 19.64444444, 17.81111111, 15.44444444, 14.88888889, 13.07777778, 15.24444444, 11.82222222, 20.81111111, 21.45555556, 18.98888889, 19.71111111, 19.27777778, 12.7, 15.05555556, 19.15555556, 20.77777778, 15.35555556, 17.68888889, 18.26666667, 15.47777778, 12.76666667, 10.54444444, 13.38888889, 12.54444444, 19.84444444, 19.5, 21.92222222, 17.86666667, 22.44444444, 19.64444444, 20.73333333, 22.02222222, 19, 20.48888889, 19.02222222, 16.44444444, 14.22222222, 16.3, 16.42222222, 17.22222222, 8.322222222, 8.288888889, 13.95555556, 5.555555556, 5.666666667, 7.7, 4.022222222, 11.77777778, 16.42222222, 11.83333333, 9.7, 0.044444444, 3.688888889, -2.077777778, 0.1, -5.388888889, -3.244444444, 0.688888889, 5.744444444, -7.7, -7.022222222, -0.211111111, 4.833333333, 8.111111111, 5.766666667, 7.888888889, 10.43333333, 11.56666667, 10.15555556, 7.155555556, 4.522222222, 7.144444444, 10.88888889, 9.5, 12.13333333, 4.022222222, -3.9, 1.433333333, 0.7, 3.188888889, -1.7, 3.588888889, -0.111111111, -2.788888889, -7.133333333, -5, 0.733333333, -7.555555556, -12.51111111, -8.188888889, 3.122222222, 2.944444444, 0.477777778, -3.2, -9.2, -4.788888889, -0.288888889, 1.077777778, 4.755555556, 5.455555556, 0.511111111, -3.888888889, -7.4, -1.355555556, 5.144444444, 0.122222222, -5.166666667, -5, -5.144444444, -8.822222222, -6.388888889, -6.811111111, -8.944444444, -10.11111111, -7.144444444, -5.133333333, -1.166666667, 1.833333333, -1.477777778, -1.811111111, -2.433333333, -1.188888889, -2.333333333, 0.744444444, 1.877777778, 1.333333333, -1.7, 0.888888889, -3.855555556, -8.211111111, -1.055555556, -4.211111111, -7.355555556, -8.111111111, -10.96666667, -13.05555556, -4.644444444, -7.577777778, ] max = [ -7.233333333, -1.6, 5.488888889, 7.744444444, 6.188888889, 6.555555556, 10.53333333, 6.766666667, 14.1, 14.11111111, 2.044444444, 4.633333333, 2.055555556, 8.666666667, -1.4, -5.555555556, 4.177777778, 11.8, 15.58888889, 12.31111111, 3.666666667, -0.977777778, 1.288888889, 4.211111111, 9.377777778, 5.266666667, 2.144444444, 3.977777778, 7.2, 11.94444444, 11.32222222, 4, 6.611111111, 8.211111111, 3.5, 8.866666667, 3.6, 3.711111111, 13.12222222, 7.833333333, -3.333333333, -2.166666667, -2.877777778, 5.188888889, 13.12222222, 12.11111111, -0.7, 6.688888889, 14.03333333, -2.433333333, -8.6, -8.244444444, -2.122222222, -2.722222222, 1.266666667, 2.8, 5.7, 6.944444444, 5.066666667, 5.688888889, 13.35555556, 16.66666667, 17.33333333, 7.277777778, 6.388888889, 1.344444444, 9.111111111, 17.96666667, 12.8, 5.8, 6.911111111, 6.822222222, 11.87777778, 13.16666667, 9.233333333, 8.655555556, 10.04444444, 7.022222222, 7.644444444, 8.311111111, 16.71111111, 18.85555556, 12.14444444, 13.27777778, 11.18888889, 7.088888889, 8.255555556, 7.522222222, 9.955555556, 9.933333333, 4.866666667, 15.25555556, 9.244444444, 9.755555556, 14, 8.955555556, 2.344444444, 17.43333333, 12.12222222, 13.46666667, 23, 18.45555556, 12.77777778, 7.211111111, 8.588888889, 14.35555556, 19.01111111, 12.4, 9.155555556, 15.6, 4.955555556, 8.966666667, 16.95555556, 9.511111111, 10.15555556, 16, 14.45555556, 21.02222222, 25.76666667, 20.5, 15.71111111, 11.67777778, 12.81111111, 12.88888889, 17.58888889, 23.12222222, 21.77777778, 24.42222222, 20.05555556, 24.32222222, 18.83333333, 19.56666667, 14.96666667, 19.68888889, 18.57777778, 23, 23.34444444, 20.7, 11.82222222, 11.48888889, 17.52222222, 22.55555556, 20.47777778, 23.01111111, 27.86666667, 30.28888889, 30.3, 22.94444444, 18.57777778, 25.51111111, 24.13333333, 30.01111111, 24.77777778, 20.28888889, 28.67777778, 32.74444444, 31.37777778, 28.52222222, 31.81111111, 27.24444444, 32.53333333, 26.15555556, 24.63333333, 28.3, 31.23333333, 32.21111111, 28.21111111, 23.07777778, 21.64444444, 24.34444444, 19.62222222, 25.14444444, 24.46666667, 23.87777778, 21.28888889, 20.22222222, 29.98888889, 32.04444444, 36.44444444, 36.01111111, 24.85555556, 23.45555556, 29.17777778, 32.25555556, 28.75555556, 30.28888889, 28.85555556, 30.45555556, 31.26666667, 28.86666667, 33.31111111, 30.66666667, 28.67777778, 27.4, 32.2, 25.41111111, 22.23333333, 26.67777778, 30.21111111, 29.15555556, 29.65555556, 31.94444444, 31.43333333, 28.35555556, 24.8, 25.5, 25.42222222, 24.17777778, 20.88888889, 24.35555556, 25.54444444, 22, 27.95555556, 29.42222222, 28.88888889, 26.8, 28.2, 26.92222222, 24.13333333, 22.61111111, 26.15555556, 30.57777778, 30.86666667, 29.92222222, 27.33333333, 23.43333333, 24.68888889, 26.94444444, 28.81111111, 25.54444444, 22.48888889, 21.67777778, 19.74444444, 23.82222222, 25.91111111, 30.85555556, 28.48888889, 29.21111111, 28.37777778, 22.4, 25.55555556, 27.35555556, 30.67777778, 27.95555556, 25.98888889, 23.46666667, 25.37777778, 20.46666667, 22.54444444, 20.18888889, 22.24444444, 26.84444444, 25.8, 29.62222222, 26.36666667, 32.24444444, 29.84444444, 28.33333333, 31.22222222, 29.9, 29.98888889, 27.42222222, 25.54444444, 20.22222222, 24, 24.52222222, 25.02222222, 16.12222222, 17.58888889, 23.25555556, 15.75555556, 18.66666667, 18.4, 12.52222222, 20.07777778, 28.62222222, 17.23333333, 16.6, 13.34444444, 10.98888889, 9.522222222, 5.8, 6.811111111, 6.555555556, 12.18888889, 12.64444444, 4.2, 3.577777778, 8.888888889, 15.23333333, 16.11111111, 18.36666667, 16.98888889, 15.63333333, 16.46666667, 15.55555556, 15.65555556, 17.42222222, 18.74444444, 19.48888889, 15.9, 19.73333333, 13.02222222, 8.1, 8.933333333, 11.3, 12.38888889, 8.3, 12.38888889, 6.388888889, 4.211111111, 4.666666667, 0.7, 7.133333333, 2.344444444, 1.088888889, 0.111111111, 11.62222222, 10.84444444, 8.777777778, 3.5, 3.4, 7.211111111, 5.711111111, 9.677777778, 12.25555556, 10.15555556, 6.511111111, 4.911111111, 1.5, 11.44444444, 15.54444444, 8.122222222, 6.233333333, 7, 4.355555556, 0.277777778, 3.711111111, 2.888888889, 1.555555556, 3.888888889, 4.555555556, 5.666666667, 7.833333333, 9.833333333, 10.02222222, 6.288888889, 5.366666667, 11.41111111, 9.566666667, 9.744444444, 13.57777778, 9.433333333, 3.1, 11.08888889, 3.844444444, 2.488888889, 7.544444444, 4.488888889, -0.455555556, -2.111111111, -3.566666667, -1.955555556, 3.955555556, 1.222222222, ] week_number = [f"W{i//7}" if i % 7 == 0 else None for i in range(0, 365)] start = 50 size = 100 data = { "Date": dates[start:size], "Temp°C": temp[start:size], "Week": numpy.array(max[start:size]) + 5, "WeekN": week_number[start:size], } page = """ # Line - Texts <|{data}|chart|x=Date|y[1]=Temp°C|y[2]=Week|mode[2]=text|text[2]=WeekN|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Create a star shape data = {"r": [3, 1] * 5 + [3], "theta": list(range(0, 360, 36)) + [0]} options = [ # First plot is filled with a yellow-ish color {"subplot": "polar", "fill": "toself", "fillcolor": "#E4FF87"}, # Second plot is filled with a blue-ish color {"fill": "toself", "subplot": "polar2", "fillcolor": "#709BFF"}, ] layout = { "polar": { # This actually is the default value "angularaxis": { "direction": "counterclockwise", }, }, "polar2": { "angularaxis": { # Rotate the axis 180° (0 is on the left) "rotation": 180, # Orient the axis clockwise "direction": "clockwise", # Show the angles as radians "thetaunit": "radians", }, }, # Hide the legend "showlegend": False, } page = """ # Polar Charts - Direction <|{data}|chart|type=scatterpolar|layout={layout}|options={options}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui value = "XS" page = """ # Slider - List of values <|{value}|slider|lov=XXS;XS;S;M;L;XL;XXL|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import io from decimal import Decimal, getcontext from taipy.gui import Gui, download # Initial precision precision = 10 def pi(precision: int) -> list[int]: """Compute Pi to the required precision. Adapted from https://docs.python.org/3/library/decimal.html """ saved_precision = getcontext().prec # Save precision getcontext().prec = precision three = Decimal(3) # substitute "three=3.0" for regular floats lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 while s != lasts: lasts = s n, na = n + na, na + 8 d, da = d + da, da + 32 t = (t * n) / d s += t digits = [] while s != 0: integral = int(s) digits.append(integral) s = (s - integral) * 10 getcontext().prec = saved_precision return digits # Generate the digits, save them in a CSV file content, and trigger a download action # so the user can retrieve them def download_pi(state): digits = pi(state.precision) buffer = io.StringIO() buffer.write("index,digit\n") for i, d in enumerate(digits): buffer.write(f"{i},{d}\n") download(state, content=bytes(buffer.getvalue(), "UTF-8"), name="pi.csv") page = """ # File Download - Dynamic content Precision: <|{precision}|slider|min=2|max=10000|> <|{None}|file_download|on_action=download_pi|label=Download Pi digits|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui value = 9 page = """ # Slider - Custom range <|{value}|slider|min=1|max=10|> Value: <|{value}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from datetime import date, timedelta from taipy.gui import Gui # Create the list of dates (all year 2000) all_dates = {} all_dates_str = [] start_date = date(2000, 1, 1) end_date = date(2001, 1, 1) a_date = start_date while a_date < end_date: date_str = a_date.strftime("%Y/%m/%d") all_dates_str.append(date_str) all_dates[date_str] = a_date a_date += timedelta(days=1) # Initial selection: first and last day dates = [all_dates_str[1], all_dates_str[-1]] # These two variables are used in text controls start_sel = all_dates[dates[0]] end_sel = all_dates[dates[1]] def on_change(state, _, var_value): # Update the text controls state.start_sel = all_dates[var_value[0]] state.end_sel = all_dates[var_value[1]] page = """ # Slider - Date range <|{dates}|slider|lov={all_dates_str}|> Start: <|{start_sel}|text|format=d MMM|> End: <|{end_sel}|text|format=d MMM|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- import os from decimal import Decimal, getcontext from tempfile import NamedTemporaryFile from taipy.gui import Gui, download # Initial precision precision = 10 # Stores the path to the temporary file temp_path = None def pi(precision: int) -> list[int]: """Compute Pi to the required precision. Adapted from https://docs.python.org/3/library/decimal.html """ saved_precision = getcontext().prec # Save precision getcontext().prec = precision three = Decimal(3) # substitute "three=3.0" for regular floats lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 while s != lasts: lasts = s n, na = n + na, na + 8 d, da = d + da, da + 32 t = (t * n) / d s += t digits = [] while s != 0: integral = int(s) digits.append(integral) s = (s - integral) * 10 getcontext().prec = saved_precision return digits # Remove the temporary file def clean_up(state): os.remove(state.temp_path) # Generate the digits, save them in a CSV temporary file, then trigger a download action # for that file. def download_pi(state): digits = pi(state.precision) with NamedTemporaryFile("r+t", suffix=".csv", delete=False) as temp_file: state.temp_path = temp_file.name temp_file.write("index,digit\n") for i, d in enumerate(digits): temp_file.write(f"{i},{d}\n") download(state, content=temp_file.name, name="pi.csv", on_action=clean_up) page = """ # File Download - Dynamic content Precision: <|{precision}|slider|min=2|max=10000|> <|{None}|file_download|on_action=download_pi|label=Download Pi digits|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui value = 50 page = """ # Slider - Simple <|{value}|slider|> Value: <|{value}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui value = 40 page = """ # Slider - Vertical <|{value}|slider|orientation=v|> Value: <|{value}|> """ Gui(page).run()
# # 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. # ----------------------------------------------------------------------------------------- # To execute this script, make sure that the taipy-gui package is installed in your # Python environment and run: # python <script> # ----------------------------------------------------------------------------------------- from taipy.gui import Gui # Initial values values = [20, 40, 80] page = """ # Slider - Range <|{values}|slider|> Selection: <|{values}|> """ Gui(page).run()
# # 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 importlib.util import find_spec if find_spec("taipy"): if find_spec("taipy.config"): from taipy.config._init import * # type: ignore if find_spec("taipy.gui"): from taipy.gui._init import * # type: ignore if find_spec("taipy.core"): from taipy.core._init import * # type: ignore if find_spec("taipy.rest"): from taipy.rest._init import * # type: ignore if find_spec("taipy.gui_core"): from taipy.gui_core._init import * # type: ignore if find_spec("taipy.enterprise"): from taipy.enterprise._init import * # type: ignore if find_spec("taipy._run"): from taipy._run import _run as run # type: ignore
import typing as t class Icon: """Small image in the User Interface. Icons are typically used in controls like [button](../gui/viselements/button.md) or items in a [menu](../gui/viselements/menu.md). Attributes: path (str): The path to the image file. text (Optional[str]): The text associated to the image or None if there is none. svg (Optional[bool]): True if the image is svg. If a text is associated to an icon, it is rendered by the visual elements that uses this Icon. """ @staticmethod def get_dict_or(value: t.Union[str, t.Any]) -> t.Union[str, dict]: return value._to_dict() if isinstance(value, Icon) else value def __init__( self, path: str, text: t.Optional[str] = None, light_path: t.Optional[bool] = None, dark_path: t.Optional[bool] = None, ) -> None: """Initialize a new Icon. Arguments: path (str): The path to an image file.<br/> This path must be relative to and inside the root directory of the application (where the Python file that created the `Gui` instance is located).<br/> In situations where the image file is located outside the application directory, a _path mapping_ must be used: the _path_mapping_ parameter of the `Gui^` constructor makes it possible to access a resource anywhere on the server filesystem, as if it were located in a subdirectory of the application directory. text (Optional[str]): The text associated to the image. If *text* is None, there is no text associated to this image. light_path (Optional[str]): The path to the light theme image (fallback to *path* if not defined). dark_path (Optional[str]): The path to the dark theme image (fallback to *path* if not defined). """ self.path = path self.text = text if light_path is not None: self.light_path = light_path if dark_path is not None: self.dark_path = dark_path def _to_dict(self, a_dict: t.Optional[dict] = None) -> dict: if a_dict is None: a_dict = {} a_dict["path"] = self.path if self.text is not None: a_dict["text"] = self.text if hasattr(self, "light_path") and self.light_path is not None: a_dict["lightPath"] = self.light_path if hasattr(self, "dark_path") and self.dark_path is not None: a_dict["darkPath"] = self.dark_path return a_dict
from __future__ import annotations import contextlib import logging import os import pathlib import re import sys import time import typing as t import webbrowser from importlib import util from random import randint import __main__ from flask import Blueprint, Flask, json, jsonify, render_template, send_from_directory from flask_cors import CORS from flask_socketio import SocketIO from gitignore_parser import parse_gitignore from kthread import KThread from werkzeug.serving import is_running_from_reloader from taipy.logger._taipy_logger import _TaipyLogger from ._renderers.json import _TaipyJsonProvider from .config import ServerConfig from .utils import _is_in_notebook, _is_port_open, _RuntimeManager if t.TYPE_CHECKING: from .gui import Gui class _Server: __RE_OPENING_CURLY = re.compile(r"([^\"])(\{)") __RE_CLOSING_CURLY = re.compile(r"(\})([^\"])") __OPENING_CURLY = r"\1&#x7B;" __CLOSING_CURLY = r"&#x7D;\2" def __init__( self, gui: Gui, flask: t.Optional[Flask] = None, path_mapping: t.Optional[dict] = None, async_mode: t.Optional[str] = None, allow_upgrades: bool = True, server_config: t.Optional[ServerConfig] = None, ): self._gui = gui server_config = server_config or {} self._flask = flask if self._flask is None: flask_config: t.Dict[str, t.Any] = {"import_name": "Taipy"} if "flask" in server_config and isinstance(server_config["flask"], dict): flask_config.update(server_config["flask"]) self._flask = Flask(**flask_config) if "SECRET_KEY" not in self._flask.config or not self._flask.config["SECRET_KEY"]: self._flask.config["SECRET_KEY"] = "TaIpY" # setup cors if "cors" not in server_config or ( "cors" in server_config and (isinstance(server_config["cors"], dict) or server_config["cors"] is True) ): cors_config = ( server_config["cors"] if "cors" in server_config and isinstance(server_config["cors"], dict) else {} ) CORS(self._flask, **cors_config) # setup socketio socketio_config: t.Dict[str, t.Any] = { "cors_allowed_origins": "*", "ping_timeout": 10, "ping_interval": 5, "json": json, "async_mode": async_mode, "allow_upgrades": allow_upgrades, } if "socketio" in server_config and isinstance(server_config["socketio"], dict): socketio_config.update(server_config["socketio"]) self._ws = SocketIO(self._flask, **socketio_config) self._apply_patch() # set json encoder (for Taipy specific types) self._flask.json_provider_class = _TaipyJsonProvider self._flask.json = self._flask.json_provider_class(self._flask) # type: ignore self.__path_mapping = path_mapping or {} self.__ssl_context = server_config.get("ssl_context", None) self._is_running = False # Websocket (handle json message) # adding args for the one call with a server ack request @self._ws.on("message") def handle_message(message, *args) -> None: if "status" in message: _TaipyLogger._get_logger().info(message["status"]) elif "type" in message: gui._manage_message(message["type"], message) def __is_ignored(self, file_path: str) -> bool: if not hasattr(self, "_ignore_matches"): __IGNORE_FILE = ".taipyignore" ignore_file = ( (pathlib.Path(__main__.__file__).parent / __IGNORE_FILE) if hasattr(__main__, "__file__") else None ) if not ignore_file or not ignore_file.is_file(): ignore_file = pathlib.Path(self._gui._root_dir) / __IGNORE_FILE self._ignore_matches = ( parse_gitignore(ignore_file) if ignore_file.is_file() and os.access(ignore_file, os.R_OK) else None ) if callable(self._ignore_matches): return self._ignore_matches(file_path) return False def _get_default_blueprint( self, static_folder: str, template_folder: str, title: str, favicon: str, root_margin: str, scripts: t.List[str], styles: t.List[str], version: str, client_config: t.Dict[str, t.Any], watermark: t.Optional[str], css_vars: str, base_url: str, ) -> Blueprint: taipy_bp = Blueprint("Taipy", __name__, static_folder=static_folder, template_folder=template_folder) # Serve static react build @taipy_bp.route("/", defaults={"path": ""}) @taipy_bp.route("/<path:path>") def my_index(path): if path == "" or path == "index.html" or "." not in path: try: return render_template( "index.html", title=title, favicon=favicon, root_margin=root_margin, watermark=watermark, config=client_config, scripts=scripts, styles=styles, version=version, css_vars=css_vars, base_url=base_url, ) except Exception: # pragma: no cover raise RuntimeError( "Something is wrong with the taipy-gui front-end installation. Check that the js bundle has been properly built (is Node.js installed?)." ) if path == "taipy.status.json": return self._direct_render_json(self._gui._serve_status(pathlib.Path(template_folder) / path)) if str(os.path.normpath(file_path := ((base_path := static_folder + os.path.sep) + path))).startswith( base_path ) and os.path.isfile(file_path): return send_from_directory(base_path, path) # use the path mapping to detect and find resources for k, v in self.__path_mapping.items(): if ( path.startswith(f"{k}/") and str( os.path.normpath(file_path := ((base_path := v + os.path.sep) + path[len(k) + 1 :])) ).startswith(base_path) and os.path.isfile(file_path) ): return send_from_directory(base_path, path[len(k) + 1 :]) if ( hasattr(__main__, "__file__") and str( os.path.normpath( file_path := ((base_path := os.path.dirname(__main__.__file__) + os.path.sep) + path) ) ).startswith(base_path) and os.path.isfile(file_path) and not self.__is_ignored(file_path) ): return send_from_directory(base_path, path) if ( str(os.path.normpath(file_path := (base_path := self._gui._root_dir + os.path.sep) + path)).startswith( base_path ) and os.path.isfile(file_path) and not self.__is_ignored(file_path) ): return send_from_directory(base_path, path) return ("", 404) return taipy_bp # Update to render as JSX def _render(self, html_fragment, style, head, context): template_str = _Server.__RE_OPENING_CURLY.sub(_Server.__OPENING_CURLY, html_fragment) template_str = _Server.__RE_CLOSING_CURLY.sub(_Server.__CLOSING_CURLY, template_str) template_str = template_str.replace('"{!', "{") template_str = template_str.replace('!}"', "}") return self._direct_render_json( { "jsx": template_str, "style": (style + os.linesep) if style else "", "head": head or [], "context": context or self._gui._get_default_module_name(), } ) def _direct_render_json(self, data): return jsonify(data) def get_flask(self): return self._flask def test_client(self): return self._flask.test_client() def _run_notebook(self): self._is_running = True self._ws.run(self._flask, host=self._host, port=self._port, debug=False, use_reloader=False) def _get_async_mode(self) -> str: return self._ws.async_mode def _apply_patch(self): if self._get_async_mode() == "gevent" and util.find_spec("gevent"): from gevent import monkey if not monkey.is_module_patched("time"): monkey.patch_time() if self._get_async_mode() == "eventlet" and util.find_spec("eventlet"): from eventlet import monkey_patch, patcher if not patcher.is_monkey_patched("time"): monkey_patch(time=True) def _get_random_port(self): # pragma: no cover while True: port = randint(49152, 65535) if port not in _RuntimeManager().get_used_port() and not _is_port_open(self._host, port): return port def run(self, host, port, debug, use_reloader, flask_log, run_in_thread, allow_unsafe_werkzeug, notebook_proxy): host_value = host if host != "0.0.0.0" else "localhost" self._host = host self._port = port if _is_in_notebook() and notebook_proxy: # pragma: no cover from .utils.proxy import NotebookProxy # Start proxy if not already started self._proxy = NotebookProxy(gui=self._gui, listening_port=port) self._proxy.run() self._port = self._get_random_port() if _is_in_notebook() or run_in_thread: runtime_manager = _RuntimeManager() runtime_manager.add_gui(self._gui, port) if debug and not is_running_from_reloader() and _is_port_open(host_value, port): raise ConnectionError( f"Port {port} is already opened on {host_value}. You have another server application running on the same port." ) if not flask_log: log = logging.getLogger("werkzeug") log.disabled = True if not is_running_from_reloader(): _TaipyLogger._get_logger().info(f" * Server starting on http://{host_value}:{port}") else: _TaipyLogger._get_logger().info(f" * Server reloaded on http://{host_value}:{port}") if not is_running_from_reloader() and self._gui._get_config("run_browser", False): webbrowser.open(f"http://{host_value}{f':{port}' if port else ''}", new=2) if _is_in_notebook() or run_in_thread: self._thread = KThread(target=self._run_notebook) self._thread.start() return self._is_running = True run_config = { "app": self._flask, "host": host, "port": port, "debug": debug, "use_reloader": use_reloader, } if self.__ssl_context is not None: run_config["ssl_context"] = self.__ssl_context # flask-socketio specific conditions for 'allow_unsafe_werkzeug' parameters to be popped out of kwargs if self._get_async_mode() == "threading" and (not sys.stdin or not sys.stdin.isatty()): run_config = {**run_config, "allow_unsafe_werkzeug": allow_unsafe_werkzeug} self._ws.run(**run_config) def stop_thread(self): if hasattr(self, "_thread") and self._thread.is_alive() and self._is_running: self._is_running = False with contextlib.suppress(Exception): if self._get_async_mode() == "gevent": if self._ws.wsgi_server is not None: self._ws.wsgi_server.stop() else: self._thread.kill() else: self._thread.kill() while _is_port_open(self._host, self._port): time.sleep(0.1) def stop_proxy(self): if hasattr(self, "_proxy"): self._proxy.stop()
import os import re import typing as t from importlib.util import find_spec import pytz import tzlocal from dotenv import dotenv_values from werkzeug.serving import is_running_from_reloader from taipy.logger._taipy_logger import _TaipyLogger from ._gui_cli import _GuiCLI from ._page import _Page from ._warnings import _warn from .partial import Partial from .utils import _is_in_notebook ConfigParameter = t.Literal[ "allow_unsafe_werkzeug", "async_mode", "change_delay", "chart_dark_template", "base_url", "dark_mode", "dark_theme", "data_url_max_size", "debug", "extended_status", "favicon", "flask_log", "host", "light_theme", "margin", "ngrok_token", "notebook_proxy", "notification_duration", "propagate", "run_browser", "run_in_thread", "run_server", "server_config", "single_client", "system_notification", "theme", "time_zone", "title", "stylekit", "upload_folder", "use_arrow", "use_reloader", "watermark", "webapp_path", "port", ] Stylekit = t.TypedDict( "Stylekit", { "color_primary": str, "color_secondary": str, "color_error": str, "color_warning": str, "color_success": str, "color_background_light": str, "color_paper_light": str, "color_background_dark": str, "color_paper_dark": str, "font_family": str, "root_margin": str, "border_radius": int, "input_button_height": str, }, total=False, ) ServerConfig = t.TypedDict( "ServerConfig", { "cors": t.Optional[t.Union[bool, t.Dict[str, t.Any]]], "socketio": t.Optional[t.Dict[str, t.Any]], "ssl_context": t.Optional[t.Union[str, t.Tuple[str, str]]], "flask": t.Optional[t.Dict[str, t.Any]], }, total=False, ) Config = t.TypedDict( "Config", { "allow_unsafe_werkzeug": bool, "async_mode": str, "change_delay": t.Optional[int], "chart_dark_template": t.Optional[t.Dict[str, t.Any]], "base_url": t.Optional[str], "dark_mode": bool, "dark_theme": t.Optional[t.Dict[str, t.Any]], "data_url_max_size": t.Optional[int], "debug": bool, "extended_status": bool, "favicon": t.Optional[str], "flask_log": bool, "host": str, "light_theme": t.Optional[t.Dict[str, t.Any]], "margin": t.Optional[str], "ngrok_token": str, "notebook_proxy": bool, "notification_duration": int, "propagate": bool, "run_browser": bool, "run_in_thread": bool, "run_server": bool, "server_config": t.Optional[ServerConfig], "single_client": bool, "system_notification": bool, "theme": t.Optional[t.Dict[str, t.Any]], "time_zone": t.Optional[str], "title": t.Optional[str], "stylekit": t.Union[bool, Stylekit], "upload_folder": t.Optional[str], "use_arrow": bool, "use_reloader": bool, "watermark": t.Optional[str], "webapp_path": t.Optional[str], "port": int, }, total=False, ) class _Config(object): __RE_PORT_NUMBER = re.compile( r"^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$" ) def __init__(self): self.pages: t.List[_Page] = [] self.root_page: t.Optional[_Page] = None self.routes: t.List[str] = [] self.partials: t.List[Partial] = [] self.partial_routes: t.List[str] = [] self.config: Config = {} def _load(self, config: Config) -> None: self.config.update(config) # Check that the user timezone configuration setting is valid self.get_time_zone() def _get_config(self, name: ConfigParameter, default_value: t.Any) -> t.Any: # pragma: no cover if name in self.config and self.config[name] is not None: if default_value is not None and not isinstance(self.config[name], type(default_value)): try: return type(default_value)(self.config[name]) except Exception as e: _warn(f'app_config "{name}" value "{self.config[name]}" is not of type {type(default_value)}', e) return default_value return self.config[name] return default_value def get_time_zone(self) -> t.Optional[str]: tz = self.config.get("time_zone") if tz is None or tz == "client": return tz if tz == "server": # return python tzlocal IANA Time Zone return str(tzlocal.get_localzone()) # Verify user defined IANA Time Zone is valid if tz not in pytz.all_timezones_set: raise Exception( "Time Zone configuration is not valid. Mistyped 'server', 'client' options or invalid IANA Time Zone" ) # return user defined IANA Time Zone (https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) return tz def _handle_argparse(self): _GuiCLI.create_parser() args = _GuiCLI.parse_arguments() config = self.config if args.taipy_port: if not _Config.__RE_PORT_NUMBER.match(args.taipy_port): _warn("Port value for --port option is not valid.") else: config["port"] = int(args.taipy_port) if args.taipy_host: config["host"] = args.taipy_host if args.taipy_debug: config["debug"] = True if args.taipy_no_debug: config["debug"] = False if args.taipy_use_reloader: config["use_reloader"] = True if args.taipy_no_reloader: config["use_reloader"] = False if args.taipy_ngrok_token: config["ngrok_token"] = args.taipy_ngrok_token if args.taipy_webapp_path: config["webapp_path"] = args.taipy_webapp_path elif os.environ.get("TAIPY_GUI_WEBAPP_PATH"): config["webapp_path"] = os.environ.get("TAIPY_GUI_WEBAPP_PATH") def _build_config(self, root_dir, env_filename, kwargs): # pragma: no cover config = self.config env_file_abs_path = env_filename if os.path.isabs(env_filename) else os.path.join(root_dir, env_filename) # Load keyword arguments for key, value in kwargs.items(): key = key.lower() if value is not None and key in config: # Special case for "stylekit" that can be a Boolean or a dict if key == "stylekit" and isinstance(value, bool): from ._default_config import _default_stylekit config[key] = _default_stylekit if value else {} continue try: if isinstance(value, dict) and isinstance(config[key], dict): config[key].update(value) else: config[key] = value if config[key] is None else type(config[key])(value) # type: ignore except Exception as e: _warn( f"Invalid keyword arguments value in Gui.run {key} - {value}. Unable to parse value to the correct type", e, ) # Load config from env file if os.path.isfile(env_file_abs_path): for key, value in dotenv_values(env_file_abs_path).items(): key = key.lower() if value is not None and key in config: try: config[key] = value if config[key] is None else type(config[key])(value) # type: ignore except Exception as e: _warn( f"Invalid env value in Gui.run(): {key} - {value}. Unable to parse value to the correct type", e, ) # Taipy-config if find_spec("taipy") and find_spec("taipy.config"): from taipy.config import Config as TaipyConfig try: section = TaipyConfig.unique_sections["gui"] self.config.update(section._to_dict()) except KeyError: _warn("taipy-config section for taipy-gui is not initialized.") # Load from system arguments self._handle_argparse() def __log_outside_reloader(self, logger, msg): if not is_running_from_reloader(): logger.info(msg) def resolve(self): app_config = self.config logger = _TaipyLogger._get_logger() # Special config for notebook runtime if _is_in_notebook() or app_config["run_in_thread"] and not app_config["single_client"]: app_config["single_client"] = True self.__log_outside_reloader(logger, "Running in 'single_client' mode in notebook environment") if app_config["run_server"] and app_config["ngrok_token"] and app_config["use_reloader"]: app_config["use_reloader"] = False self.__log_outside_reloader( logger, "'use_reloader' parameter will not be used when 'ngrok_token' parameter is available" ) if app_config["use_reloader"] and _is_in_notebook(): app_config["use_reloader"] = False self.__log_outside_reloader(logger, "'use_reloader' parameter is not available in notebook environment") if app_config["use_reloader"] and not app_config["debug"]: app_config["debug"] = True self.__log_outside_reloader(logger, "application is running in 'debug' mode") if app_config["debug"] and not app_config["allow_unsafe_werkzeug"]: app_config["allow_unsafe_werkzeug"] = True self.__log_outside_reloader(logger, "'allow_unsafe_werkzeug' has been set to True") if app_config["debug"] and app_config["async_mode"] != "threading": app_config["async_mode"] = "threading" self.__log_outside_reloader( logger, "'async_mode' parameter has been overridden to 'threading'. Using Flask built-in development server with debug mode", ) self._resolve_notebook_proxy() self._resolve_stylekit() self._resolve_url_prefix() def _resolve_stylekit(self): app_config = self.config # support legacy margin variable stylekit_config = app_config["stylekit"] if isinstance(app_config["stylekit"], dict) and "root_margin" in app_config["stylekit"]: from ._default_config import _default_stylekit, default_config stylekit_config = app_config["stylekit"] if ( stylekit_config["root_margin"] == _default_stylekit["root_margin"] and app_config["margin"] != default_config["margin"] ): app_config["stylekit"]["root_margin"] = str(app_config["margin"]) app_config["margin"] = None def _resolve_url_prefix(self): app_config = self.config base_url = app_config.get("base_url") if base_url is None: app_config["base_url"] = "/" else: base_url = f"{'' if base_url.startswith('/') else '/'}{base_url}" base_url = f"{base_url}{'' if base_url.endswith('/') else '/'}" app_config["base_url"] = base_url def _resolve_notebook_proxy(self): app_config = self.config app_config["notebook_proxy"] = app_config["notebook_proxy"] if _is_in_notebook() else False
from .gui import Gui
"""# Taipy Graphical User Interface generator The Taipy GUI package provides User Interface generation based on page templates. It can run a web server that a web browser can connect to. The pages are generated by a web server that allows web clients to connect, display and interact with the page content through visual elements. Each page can contain regular text and images, as well as Taipy controls that are typically linked to some value that is managed by the whole Taipy application. Here is how you can create your first Taipy User Interface: - Create a Python source file. Copy these two lines into a file called *taipy_app.py*. ```py title="taipy_app.py" from taipy import Gui Gui("# Hello Taipy!").run() ``` - Install Taipy: ``` pip install taipy ``` - Run your application: ``` python taipy_app.py ``` Your browser opens a new page, showing the content of your graphical application. !!! Note "Optional packages" There are Python packages that you can install in your environment to add functionality to Taipy GUI: - [`python-magic`](https://pypi.org/project/python-magic/): identifies image format from byte buffers so the [`image`](../../gui/viselements/image.md) control can display them, and so that [`file_download`](../../gui/viselements/file_download.md) can request the browser to display the image content when relevant.<br/> You can install that package with the regular `pip install python-magic` command (then potentially `pip install python-magic` on Windows), or install Taipy GUI using: `pip install taipy-gui[image]`. - [`pyarrow`](https://pypi.org/project/pyarrow/): can improve the performance of your application by reducing the volume of data transferred between the web server and the clients. This is relevant if your application uses large tabular data.<br/> You can install that package with the regular `pip install pyarrow` command, or install Taipy GUI using: `pip install taipy-gui[arrow]`. - [`simple-websocket`](https://pypi.org/project/simple-websocket/): enables the debugging of the WebSocket part of the server execution.<br/> You can install that package with the regular `pip install simple-websocket` command, or install Taipy GUI using: `pip install taipy-gui[simple-websocket]`. - [`pyngrok`](https://pypi.org/project/pyngrok/): enables use of [Ngrok](https://ngrok.com/) to access Taipy GUI application from the internet.<br/> You can install that package with the regular `pip install pyngrok` command, or install Taipy GUI using: `pip install taipy-gui[pyngrok]`. """ from importlib.util import find_spec from ._init import * from ._renderers import Html, Markdown from .gui_actions import ( broadcast_callback, download, get_module_context, get_module_name_from_state, get_state_id, get_user_content_url, hold_control, invoke_callback, invoke_long_callback, navigate, notify, resume_control, ) from .icon import Icon from .page import Page from .partial import Partial from .state import State from .utils import is_debugging if find_spec("taipy") and find_spec("taipy.config"): from taipy.config import _inject_section from ._default_config import default_config from ._gui_section import _GuiSection _inject_section( _GuiSection, "gui_config", _GuiSection(property_list=list(default_config)), [("configure_gui", _GuiSection._configure)], add_to_unconflicted_sections=True, )
from __future__ import annotations import inspect import typing as t from types import FrameType from .utils import _filter_locals, _get_module_name_from_frame if t.TYPE_CHECKING: from ._renderers import _Element class Page: """Generic page generator. The `Page` class transforms template text into actual pages that can be displayed on a web browser. When a page is requested to be displayed, it is converted into HTML code that can be sent to the client. All control placeholders are replaced by their respective graphical component so you can show your application variables and interact with them. """ def __init__(self, **kwargs) -> None: self._class_module_name = "" self._class_locals: t.Dict[str, t.Any] = {} self._frame: t.Optional[FrameType] = None self._renderer: t.Optional[Page] = self.create_page() if "frame" in kwargs: self._frame = kwargs.get("frame") elif self._renderer: self._frame = self._renderer._frame elif len(inspect.stack()) < 4: raise RuntimeError(f"Can't resolve module. Page '{type(self).__name__}' is not registered.") else: self._frame = t.cast(FrameType, t.cast(FrameType, inspect.stack()[3].frame)) if self._renderer: # Extract the page module's attributes and methods cls = type(self) cls_locals = dict(vars(self)) funcs = [ i[0] for i in inspect.getmembers(cls) if not i[0].startswith("_") and (inspect.ismethod(i[1]) or inspect.isfunction(i[1])) ] for f in funcs: func = getattr(self, f) if hasattr(func, "__func__") and func.__func__ is not None: cls_locals[f] = func.__func__ self._class_module_name = cls.__name__ self._class_locals = cls_locals def create_page(self) -> t.Optional[Page]: """Create the page content for page modules. If this page is a page module, this method must be overloaded and return the page content. This method should never be called directly: only the Taipy GUI internals will. The default implementation returns None, indicating that this class does not implement a page module. Returns: The page content for this Page subclass, making it a page module. """ return None def _get_locals(self) -> t.Optional[t.Dict[str, t.Any]]: return ( self._class_locals if self._is_class_module() else None if (frame := self._get_frame()) is None else _filter_locals(frame.f_locals) ) def _is_class_module(self): return self._class_module_name != "" def _get_frame(self): if not hasattr(self, "_frame"): raise RuntimeError(f"Page '{type(self).__name__}' was not registered correctly.") return self._frame def _get_module_name(self) -> t.Optional[str]: return ( None if (frame := self._get_frame()) is None else f"{_get_module_name_from_frame(frame)}{'.' if self._class_module_name else ''}{self._class_module_name}" ) def _get_content_detail(self, gui) -> str: return f"in class {type(self).__name__}" def render(self, gui) -> str: if self._renderer is not None: return self._renderer.render(gui) return "<h1>No renderer found for page</h1>"
import sys import traceback import typing as t import warnings class TaipyGuiWarning(UserWarning): """NOT DOCUMENTED Warning category for Taipy warnings generated in user code. """ _tp_debug_mode = False @staticmethod def set_debug_mode(debug_mode: bool): TaipyGuiWarning._tp_debug_mode = ( debug_mode if debug_mode else hasattr(sys, "gettrace") and sys.gettrace() is not None ) def _warn(message: str, e: t.Optional[BaseException] = None): warnings.warn( f"{message}:\n{''.join(traceback.format_exception(type(e), e, e.__traceback__))}" if e and TaipyGuiWarning._tp_debug_mode else f"{message}:\n{e}" if e else message, TaipyGuiWarning, stacklevel=2, )
import threading import typing as t from ._warnings import _warn from .gui import Gui from .state import State def download( state: State, content: t.Any, name: t.Optional[str] = "", on_action: t.Optional[t.Union[str, t.Callable]] = "" ): """Download content to the client. Arguments: state (State^): The current user state as received in any callback. content: File path or file content. See below. name: File name for the content on the client browser (defaults to content name). on_action: Callback function (or callback name) to call when the download ends. See below. ## Notes: - *content*: this parameter can hold several values depending on your use case: - a string: the value must be an existing path name to the file that gets downloaded or the URL to the resource you want to download. - a buffer (such as a `bytes` object): if the size of the buffer is smaller than the [*data_url_max_size*](../gui/configuration.md#p-data_url_max_size) configuration setting, then the [`python-magic`](https://pypi.org/project/python-magic/) package is used to determine the [MIME type](https://en.wikipedia.org/wiki/Media_type) of the buffer content, and the download is performed using a generated "data:" URL with the relevant type, and a base64-encoded version of the buffer content.<br/> If the buffer is too large, its content is transferred after saving it in a temporary server file. - *on_action*: this callback is triggered when the transfer of the content is achieved.</br> In this function, you can perform any clean-up operation that could be required after the download is completed.<br/> This callback can use three optional parameters: - *state*: the `State^` instance of the caller. - *id* (optional): a string representing the identifier of the caller. If this function is called directly, this will always be "Gui.download". Some controls may also trigger download actions, and then *id* would reflect the identifier of those controls. - *payload* (optional): an optional payload from the caller.<br/> This is a dictionary with the following keys: - *action*: the name of the callback; - *args*: an array of two strings. The first element reflects the *name* parameter, and the second element reflects the server-side URL where the file is located. """ if state and isinstance(state._gui, Gui): state._gui._download(content, name, on_action) else: _warn("'download()' must be called in the context of a callback.") def notify( state: State, notification_type: str = "I", message: str = "", system_notification: t.Optional[bool] = None, duration: t.Optional[int] = None, ): """Send a notification to the user interface. Arguments: state (State^): The current user state as received in any callback. notification_type: The notification type. This can be one of "success", "info", "warning", or "error".<br/> To remove the last notification, set this parameter to the empty string. message: The text message to display. system_notification: If True, the system will also show the notification.<br/> If not specified or set to None, this parameter will use the value of *configuration[system_notification]*. duration: The time, in milliseconds, during which the notification is shown. If not specified or set to None, this parameter will use the value of *configuration[notification_duration]*. Note that you can also call this function with *notification_type* set to the first letter or the alert type (i.e. setting *notification_type* to "i" is equivalent to setting it to "info"). If *system_notification* is set to True, then the browser requests the system to display a notification as well. They usually appear in small windows that fly out of the system tray.<br/> The first time your browser is requested to show such a system notification for Taipy applications, you may be prompted to authorize the browser to do so. Please refer to your browser documentation for details on how to allow or prevent this feature. """ if state and isinstance(state._gui, Gui): state._gui._notify(notification_type, message, system_notification, duration) else: _warn("'notify()' must be called in the context of a callback.") def hold_control( state: State, callback: t.Optional[t.Union[str, t.Callable]] = None, message: t.Optional[str] = "Work in Progress...", ): """Hold the User Interface actions. When the User Interface is held, users cannot interact with visual elements.<br/> The application must call `resume_control()^` so that users can interact again with the visual elements. You can set a callback function (or the name of a function) in the *callback* parameter. Then, a "Cancel" button will be displayed so the user can cancel whatever is happening in the application. When pressed, the callback is invoked. Arguments: state (State^): The current user state received in any callback. callback (Optional[Union[str, Callable]]): The function to be called if the user chooses to cancel.<br/> If empty or None, no cancel action is provided to the user.<br/> The signature of this function is: - state (State^): The user state; - id (str): the id of the button that triggered the callback. That will always be "UIBlocker" since it is created and managed internally; message: The message to show. The default value is the string "Work in Progress...". """ if state and isinstance(state._gui, Gui): state._gui._hold_actions(callback, message) else: _warn("'hold_actions()' must be called in the context of a callback.") def resume_control(state: State): """Resume the User Interface actions. This function must be called after `hold_control()^` was invoked, when interaction must be allowed again for the user. Arguments: state (State^): The current user state as received in any callback. """ if state and isinstance(state._gui, Gui): state._gui._resume_actions() else: _warn("'resume_actions()' must be called in the context of a callback.") def navigate( state: State, to: t.Optional[str] = "", params: t.Optional[t.Dict[str, str]] = None, tab: t.Optional[str] = None, force: t.Optional[bool] = False, ): """Navigate to a page. Arguments: state (State^): The current user state as received in any callback. to: The name of the page to navigate to. This can be a page identifier (as created by `Gui.add_page()^` with no leading '/') or an URL.<br/> If omitted, the application navigates to the root page. params: A dictionary of query parameters. tab: When navigating to a page that is not a known page, the page is opened in a tab identified by *tab* (as in [window.open](https://developer.mozilla.org/en-US/docs/Web/API/Window/open)).<br/> The default value creates a new tab for the page (which is equivalent to setting *tab* to "_blank"). force: When navigating to a known page, the content is refreshed even it the page is already shown. """ if state and isinstance(state._gui, Gui): state._gui._navigate(to, params, tab, force) else: _warn("'navigate()' must be called in the context of a callback.") def get_user_content_url( state: State, path: t.Optional[str] = None, params: t.Optional[t.Dict[str, str]] = None ) -> t.Optional[str]: """Get a user content URL. This function can be used if you need to deliver dynamic content to your page: you can create a path at run-time that, when queried, will deliver some user-defined content defined in the *on_user_content* callback (see the description of the `Gui^` class for more information). Arguments: state (State^): The current user state as received in any callback. path: An optional additional path to the URL. params: An optional dictionary sent to the *on_user_content* callback.<br/> These arguments are added as query parameters to the generated URL and converted into strings. Returns: An URL that, when queried, triggers the *on_user_content* callback. """ if state and isinstance(state._gui, Gui): return state._gui._get_user_content_url(path, params) _warn("'get_user_content_url()' must be called in the context of a callback.") return None def get_state_id(state: State) -> t.Optional[str]: """Get the identifier of a state. The state identifier is a string generated by Taipy GUI for a given `State^` that is used to serialize callbacks. See the [User Manual section on Long Running Callbacks](../gui/callbacks.md#long-running-callbacks) for details on when and how this function can be used. Arguments: state (State^): The current user state as received in any callback. Returns: A string that uniquely identifies the state.<br/> If None, then **state** was not handled by a `Gui^` instance. """ if state and isinstance(state._gui, Gui): return state._gui._get_client_id() return None def get_module_context(state: State) -> t.Optional[str]: """Get the name of the module currently in used when using page scopes Arguments: state (State^): The current user state as received in any callback. Returns: The name of the current module """ if state and isinstance(state._gui, Gui): return state._gui._get_locals_context() return None def get_context_id(state: State) -> t.Any: _warn("'get_context_id()' was deprecated in Taipy GUI 2.0. Use 'get_state_id()' instead.") return get_state_id(state) def get_module_name_from_state(state: State) -> t.Optional[str]: """Get the module name that triggered a callback. Pages can be defined in different modules yet refer to callback functions declared elsewhere (typically, the application's main module). This function returns the name of the module where the page that holds the control that triggered the callback was declared. This lets applications implement different behaviors depending on what page is involved. This function must be called only in the body of a callback function. Arguments: state (State^): The `State^` instance, as received in any callback. Returns: The name of the module that holds the definition of the page containing the control that triggered the callback that was provided the *state* object. """ if state and isinstance(state._gui, Gui): return state._gui._get_locals_context() return None def invoke_callback( gui: Gui, state_id: str, callback: t.Callable, args: t.Union[t.Tuple, t.List], module_context: t.Optional[str] = None, ) -> t.Any: """Invoke a user callback for a given state. See the [User Manual section on Long Running Callbacks in a Thread](../gui/callbacks.md#long-running-callbacks-in-a-thread) for details on when and how this function can be used. Arguments: gui (Gui^): The current Gui instance. state_id: The identifier of the state to use, as returned by `get_state_id()^`. callback (Callable[[State^, ...], None]): The user-defined function that is invoked.<br/> The first parameter of this function **must** be a `State^`. args (Union[Tuple, List]): The remaining arguments, as a List or a Tuple. module_context (Optional[str]): the name of the module that will be used. """ if isinstance(gui, Gui): return gui._call_user_callback(state_id, callback, list(args), module_context) _warn("'invoke_callback()' must be called with a valid Gui instance.") def broadcast_callback( gui: Gui, callback: t.Callable, args: t.Optional[t.Union[t.Tuple, t.List]] = None, module_context: t.Optional[str] = None, ) -> t.Any: """Invoke a callback for every client. This callback gets invoked for every client connected to the application with the appropriate `State^` instance. You can then perform client-specific tasks, such as updating the state variable reflected in the user interface. Arguments: gui (Gui^): The current Gui instance. callback: The user-defined function to be invoked.<br/> The first parameter of this function must be a `State^` object representing the client for which it is invoked.<br/> The other parameters should reflect the ones provided in the *args* collection. args: The parameters to send to *callback*, if any. """ if isinstance(gui, Gui): return gui._call_broadcast_callback(callback, list(args) if args else [], module_context) _warn("'broadcast_callback()' must be called with a valid Gui instance.") def invoke_state_callback(gui: Gui, state_id: str, callback: t.Callable, args: t.Union[t.Tuple, t.List]) -> t.Any: _warn("'invoke_state_callback()' was deprecated in Taipy GUI 2.0. Use 'invoke_callback()' instead.") return invoke_callback(gui, state_id, callback, args) def invoke_long_callback( state: State, user_function: t.Callable, user_function_args: t.Union[t.Tuple, t.List] = [], user_status_function: t.Optional[t.Callable] = None, user_status_function_args: t.Union[t.Tuple, t.List] = [], period=0, ): """Invoke a long running user callback. Long-running callbacks are run in a separate thread to not block the application itself. This function expects to be provided a function to run in the background (in *user_function*).<br/> It can also be specified a *status function* that is called when the operation performed by *user_function* is finished (successfully or not), or periodically (using the *period* parameter). See the [User Manual section on Long Running Callbacks](../gui/callbacks.md#long-running-callbacks) for details on when and how this function can be used. Arguments: state (State^): The `State^` instance, as received in any callback. user_function (Callable[[...], None]): The function that will be run independently of Taipy GUI. Note that this function must not use *state*, which is not persisted across threads. user_function_args (Optional[List|Tuple]): The arguments to send to *user_function*. user_status_function (Optional(Callable[[State^, bool, ...], None])): The optional user-defined status function that is invoked at the end of and possibly during the runtime of *user_function*: - The first parameter of this function is set to a `State^` instance. - The second parameter of this function is set to a bool or an int, depending on the conditions under which it is called: - If this parameter is set to a bool value, then: - If True, this indicates that *user_function* has finished properly. The last argument passed will be the result of the user_function call. - If False, this indicates that *user_function* failed. - If this parameter is set to an int value, then this value indicates how many periods (as lengthy as indicated in *period*) have elapsed since *user_function* was started. user_status_function_args (Optional[List|Tuple]): The remaining arguments of the user status function. period (int): The interval, in milliseconds, at which *user_status_function* is called.<br/> The default value is 0, meaning no call to *user_status_function* will happen until *user_function* terminates (then the second parameter of that call will be ).</br> When set to a value smaller than 500, *user_status_function* is called only when *user_function* terminates (as if *period* was set to 0). """ if not state or not isinstance(state._gui, Gui): _warn("'invoke_long_callback()' must be called in the context of a callback.") return state_id = get_state_id(state) module_context = get_module_context(state) if not isinstance(state_id, str) or not isinstance(module_context, str): return this_gui = state._gui def callback_on_exception(state: State, function_name: str, e: Exception): if not this_gui._call_on_exception(function_name, e): _warn(f"invoke_long_callback(): Exception raised in function {function_name}()", e) def callback_on_status( status: t.Union[int, bool], e: t.Optional[Exception] = None, function_name: t.Optional[str] = None, function_result: t.Optional[t.Any] = None, ): if callable(user_status_function): invoke_callback( this_gui, str(state_id), user_status_function, [status] + list(user_status_function_args) + [function_result], # type: ignore str(module_context), ) if e: invoke_callback( this_gui, str(state_id), callback_on_exception, ( str(function_name), e, ), str(module_context), ) def user_function_in_thread(*uf_args): try: res = user_function(*uf_args) callback_on_status(True, function_result=res) except Exception as e: callback_on_status(False, e, user_function.__name__) def thread_status(name: str, period_s: float, count: int): active_thread = next((t for t in threading.enumerate() if t.name == name), None) if active_thread: callback_on_status(count) threading.Timer(period_s, thread_status, (name, period_s, count + 1)).start() thread = threading.Thread(target=user_function_in_thread, args=user_function_args) thread.start() if isinstance(period, int) and period >= 500 and callable(user_status_function): thread_status(thread.name, period / 1000.0, 0)
import typing as t from copy import copy from taipy.config import Config as TaipyConfig from taipy.config import UniqueSection from ._default_config import default_config class _GuiSection(UniqueSection): name = "gui" def __init__(self, property_list: t.Optional[t.List] = None, **properties): self._property_list = property_list super().__init__(**properties) def __copy__(self): return _GuiSection(property_list=copy(self._property_list), **copy(self._properties)) def _clean(self): self._properties.clear() def _to_dict(self): as_dict = {} as_dict.update(self._properties) return as_dict @classmethod def _from_dict(cls, as_dict: t.Dict[str, t.Any], *_): return _GuiSection(property_list=list(default_config), **as_dict) def _update(self, as_dict: t.Dict[str, t.Any]): if self._property_list: as_dict = {k: v for k, v in as_dict.items() if k in self._property_list} self._properties.update(as_dict) @staticmethod def _configure(**properties) -> "_GuiSection": """NOT DOCUMENTED Configure the Graphical User Interface. Parameters: **properties (dict[str, any]): Keyword arguments that configure the behavior of the `Gui^` instances.<br/> Please refer to the [Configuration section](../gui/configuration.md#configuring-the-gui-instance) of the User Manual for more information on the accepted arguments. Returns: The GUI configuration. """ section = _GuiSection(property_list=list(default_config), **properties) TaipyConfig._register(section) return TaipyConfig.unique_sections[_GuiSection.name]
import typing as t from enum import Enum from inspect import isclass from .data import Decimator from .utils import ( _TaipyBase, _TaipyBool, _TaipyContent, _TaipyContentHtml, _TaipyContentImage, _TaipyData, _TaipyDate, _TaipyDateRange, _TaipyDict, _TaipyLoNumbers, _TaipyLov, _TaipyLovValue, _TaipyNumber, ) class _WsType(Enum): ACTION = "A" MULTIPLE_UPDATE = "MU" REQUEST_UPDATE = "RU" DATA_UPDATE = "DU" UPDATE = "U" ALERT = "AL" BLOCK = "BL" NAVIGATE = "NA" CLIENT_ID = "ID" MULTIPLE_MESSAGE = "MS" DOWNLOAD_FILE = "DF" PARTIAL = "PR" ACKNOWLEDGEMENT = "ACK" NumberTypes = {"int", "int64", "float", "float64"} class PropertyType(Enum): """ All the possible element property types. This is used when creating custom visual elements, where you have to indicate the type of each property. Some types are 'dynamic', meaning that if the property value is modified, it is automatically handled by Taipy and propagated to the entire application. See `ElementProperty^` for more details. """ boolean = "boolean" """ The property holds a Boolean value. """ toHtmlContent = _TaipyContentHtml content = _TaipyContent data = _TaipyData date = _TaipyDate date_range = _TaipyDateRange dict = "dict" """ The property holds a dictionary. """ dynamic_dict = _TaipyDict """ The property holds a dynamic dictionary. """ dynamic_number = _TaipyNumber """ The property holds a dynamic number. """ dynamic_lo_numbers = _TaipyLoNumbers """ The property holds a dynamic list of numbers. """ dynamic_boolean = _TaipyBool """ The property holds a dynamic Boolean value. """ dynamic_list = "dynamiclist" dynamic_string = "dynamicstring" """ The property holds a dynamic string. """ function = "function" """ The property holds a reference to a function. """ image = _TaipyContentImage json = "json" lov = _TaipyLov """ The property holds a LoV (list of values). """ lov_value = _TaipyLovValue """ The property holds a value in a LoV (list of values). """ number = "number" """ The property holds a number. """ react = "react" broadcast = "broadcast" string = "string" """ The property holds a string. """ string_or_number = "string|number" """ The property holds a string or a number. This is typically used to handle CSS dimension values, where a unit can be used. """ boolean_or_list = "boolean|list" slider_value = "number|number[]|lovValue" string_list = "stringlist" decimator = Decimator """ The property holds an inner attributes that is defined by a library and cannot be overridden by the user. """ inner = "inner" @t.overload def _get_taipy_type(a_type: None) -> None: ... @t.overload def _get_taipy_type(a_type: t.Type[_TaipyBase]) -> t.Type[_TaipyBase]: ... @t.overload def _get_taipy_type(a_type: PropertyType) -> t.Type[_TaipyBase]: ... @t.overload def _get_taipy_type( a_type: t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]] ) -> t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]]: ... def _get_taipy_type( a_type: t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]] ) -> t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]]: if a_type is None: return None if isinstance(a_type, PropertyType) and not isinstance(a_type.value, str): return a_type.value if isclass(a_type) and not isinstance(a_type, PropertyType) and issubclass(a_type, _TaipyBase): return a_type if a_type == PropertyType.boolean: return _TaipyBool elif a_type == PropertyType.number: return _TaipyNumber return None
# _Page for multipage support from __future__ import annotations import logging import typing as t import warnings if t.TYPE_CHECKING: from ._renderers import Page from .gui import Gui class _Page(object): def __init__(self): self._rendered_jsx: t.Optional[str] = None self._renderer: t.Optional[Page] = None self._style: t.Optional[str] = None self._route: t.Optional[str] = None self._head: t.Optional[list] = None def render(self, gui: Gui): if self._renderer is None: raise RuntimeError(f"Can't render page {self._route}: no renderer found") with warnings.catch_warnings(record=True) as w: warnings.resetwarnings() with gui._set_locals_context(self._renderer._get_module_name()): self._rendered_jsx = self._renderer.render(gui) if w: s = "\033[1;31m\n" s += ( message := f"--- {len(w)} warning(s) were found for page '{'/' if self._route == gui._get_root_page_name() else self._route}' {self._renderer._get_content_detail(gui)} ---\n" ) for i, wm in enumerate(w): s += f" - Warning {i + 1}: {wm.message}\n" s += "-" * len(message) s += "\033[0m\n" logging.warn(s) if hasattr(self._renderer, "head"): self._head = list(self._renderer.head) # type: ignore # return renderer module_name from frame return self._renderer._get_module_name()
from .config import Config, Stylekit _default_stylekit: Stylekit = { # Primary and secondary colors "color_primary": "#ff6049", "color_secondary": "#293ee7", # Contextual color "color_error": "#FF595E", "color_warning": "#FAA916", "color_success": "#96E6B3", # Background and elevation color for LIGHT MODE "color_background_light": "#f0f5f7", "color_paper_light": "#ffffff", # Background and elevation color for DARK MODE "color_background_dark": "#152335", "color_paper_dark": "#1f2f44", # DEFINING FONTS # Set main font family "font_family": "Lato, Arial, sans-serif", # DEFINING ROOT STYLES # Set root margin "root_margin": "1rem", # DEFINING SHAPES # Base border radius in px "border_radius": 8, # DEFINING MUI COMPONENTS STYLES # Matching input and button height in css size unit "input_button_height": "48px", } # Default config loaded by app.py default_config: Config = { "allow_unsafe_werkzeug": False, "async_mode": "gevent", "change_delay": None, "chart_dark_template": None, "base_url": "/", "dark_mode": True, "dark_theme": None, "debug": False, "extended_status": False, "favicon": None, "flask_log": False, "host": "127.0.0.1", "light_theme": None, "margin": "1em", "ngrok_token": "", "notebook_proxy": True, "notification_duration": 3000, "propagate": True, "run_browser": True, "run_in_thread": False, "run_server": True, "server_config": None, "single_client": False, "system_notification": False, "theme": None, "time_zone": None, "title": None, "stylekit": _default_stylekit.copy(), "upload_folder": None, "use_arrow": False, "use_reloader": False, "watermark": "Taipy inside", "webapp_path": None, "port": 5000, }
from __future__ import annotations import typing as t from ._page import _Page from ._warnings import _warn from .state import State if t.TYPE_CHECKING: from .page import Page class Partial(_Page): """Re-usable Page content. Partials are used when you need to use a partial page content in different and not related pages. This allows not to have to repeat yourself when creating your page templates. Visual elements such as [`part`](../gui/viselements/part.md), [`dialog`](../gui/viselements/dialog.md) or [`pane`](../gui/viselements/pane.md) can use Partials. Note that `Partial` has no constructor (no `__init__()` method): to create a `Partial`, you must call the `Gui.add_partial()^` function. Partials can be really handy if you want to modify a section of a page: the `update_content()` method dynamically update pages that make use of this `Partial` therefore making it easy to change the content of any page, at any moment. """ _PARTIALS = "__partials" __partials: t.Dict[str, Partial] = {} def __init__(self, route: t.Optional[str] = None): super().__init__() if route is None: self._route = f"TaiPy_partials_{len(Partial.__partials)}" Partial.__partials[self._route] = self else: self._route = route def update_content(self, state: State, content: str | "Page"): """Update partial content. Arguments: state (State^): The current user state as received in any callback. content (str): The new content to use and display. """ if state and state._gui and callable(state._gui._update_partial): state._gui._update_partial(self.__copy(content)) else: _warn("'Partial.update_content()' must be called in the context of a callback.") def __copy(self, content: str | "Page") -> Partial: new_partial = Partial(self._route) from .page import Page if isinstance(content, Page): new_partial._renderer = content else: new_partial._renderer = type(self._renderer)(content=content) if self._renderer is not None else None return new_partial
from typing import Dict, Tuple from taipy._cli._base_cli import _CLI class _GuiCLI: """Command-line interface of GUI.""" __GUI_ARGS: Dict[Tuple, Dict] = { ("--port", "-P"): { "dest": "taipy_port", "metavar": "PORT", "nargs": "?", "default": "", "const": "", "help": "Specify server port", }, ("--host", "-H"): { "dest": "taipy_host", "metavar": "HOST", "nargs": "?", "default": "", "const": "", "help": "Specify server host", }, ("--ngrok-token",): { "dest": "taipy_ngrok_token", "metavar": "NGROK_TOKEN", "nargs": "?", "default": "", "const": "", "help": "Specify NGROK Authtoken", }, ("--webapp-path",): { "dest": "taipy_webapp_path", "metavar": "WEBAPP_PATH", "nargs": "?", "default": "", "const": "", "help": "The path to the web app to be used. The default is the webapp directory under gui in the Taipy GUI package directory.", }, } __DEBUG_ARGS: Dict[str, Dict] = { "--debug": {"dest": "taipy_debug", "help": "Turn on debug", "action": "store_true"}, "--no-debug": {"dest": "taipy_no_debug", "help": "Turn off debug", "action": "store_true"}, } __RELOADER_ARGS: Dict[str, Dict] = { "--use-reloader": {"dest": "taipy_use_reloader", "help": "Auto reload on code changes", "action": "store_true"}, "--no-reloader": {"dest": "taipy_no_reloader", "help": "No reload on code changes", "action": "store_true"}, } @classmethod def create_parser(cls): gui_parser = _CLI._add_groupparser("Taipy GUI", "Optional arguments for Taipy GUI service") for args, arg_dict in cls.__GUI_ARGS.items(): taipy_arg = (args[0], cls.__add_taipy_prefix(args[0]), *args[1:]) gui_parser.add_argument(*taipy_arg, **arg_dict) debug_group = gui_parser.add_mutually_exclusive_group() for debug_arg, debug_arg_dict in cls.__DEBUG_ARGS.items(): debug_group.add_argument(debug_arg, cls.__add_taipy_prefix(debug_arg), **debug_arg_dict) reloader_group = gui_parser.add_mutually_exclusive_group() for reloader_arg, reloader_arg_dict in cls.__RELOADER_ARGS.items(): reloader_group.add_argument(reloader_arg, cls.__add_taipy_prefix(reloader_arg), **reloader_arg_dict) @classmethod def create_run_parser(cls): run_parser = _CLI._add_subparser("run", help="Run a Taipy application.") for args, arg_dict in cls.__GUI_ARGS.items(): run_parser.add_argument(*args, **arg_dict) debug_group = run_parser.add_mutually_exclusive_group() for debug_arg, debug_arg_dict in cls.__DEBUG_ARGS.items(): debug_group.add_argument(debug_arg, **debug_arg_dict) reloader_group = run_parser.add_mutually_exclusive_group() for reloader_arg, reloader_arg_dict in cls.__RELOADER_ARGS.items(): reloader_group.add_argument(reloader_arg, **reloader_arg_dict) @classmethod def parse_arguments(cls): return _CLI._parse() @classmethod def __add_taipy_prefix(cls, key: str): if key.startswith("--no-"): return key[:5] + "taipy-" + key[5:] return key[:2] + "taipy-" + key[2:]
from __future__ import annotations import contextlib import importlib import inspect import json import os import pathlib import re import sys import tempfile import time import typing as t import warnings from importlib import metadata, util from importlib.util import find_spec from types import FrameType, SimpleNamespace from urllib.parse import unquote, urlencode, urlparse import __main__ import markdown as md_lib import tzlocal from flask import Blueprint, Flask, g, jsonify, request, send_file, send_from_directory from werkzeug.utils import secure_filename from taipy.logger._taipy_logger import _TaipyLogger if util.find_spec("pyngrok"): from pyngrok import ngrok from ._default_config import _default_stylekit, default_config from ._page import _Page from ._renderers import _EmptyPage from ._renderers._markdown import _TaipyMarkdownExtension from ._renderers.factory import _Factory from ._renderers.json import _TaipyJsonEncoder from ._renderers.utils import _get_columns_dict from ._warnings import TaipyGuiWarning, _warn from .builder import _ElementApiGenerator from .config import Config, ConfigParameter, _Config from .data.content_accessor import _ContentAccessor from .data.data_accessor import _DataAccessor, _DataAccessors from .data.data_format import _DataFormat from .data.data_scope import _DataScopes from .extension.library import Element, ElementLibrary from .page import Page from .partial import Partial from .server import _Server from .state import State from .types import _WsType from .utils import ( _delscopeattr, _filter_locals, _get_broadcast_var_name, _get_client_var_name, _get_css_var_value, _get_expr_var_name, _get_module_name_from_frame, _get_non_existent_file_path, _get_page_from_module, _getscopeattr, _getscopeattr_drill, _hasscopeattr, _is_in_notebook, _LocalsContext, _MapDict, _setscopeattr, _setscopeattr_drill, _TaipyBase, _TaipyContent, _TaipyContentHtml, _TaipyContentImage, _TaipyData, _TaipyLov, _TaipyLovValue, _to_camel_case, _variable_decode, is_debugging, ) from .utils._adapter import _Adapter from .utils._bindings import _Bindings from .utils._evaluator import _Evaluator from .utils._variable_directory import _MODULE_ID, _VariableDirectory from .utils.chart_config_builder import _build_chart_config from .utils.table_col_builder import _enhance_columns class _DoNotUpdate: def __repr__(self): return "Taipy: Do not update" class Gui: """Entry point for the Graphical User Interface generation. Attributes: on_action (Callable): The function that is called when a control triggers an action, as the result of an interaction with the end-user.<br/> It defaults to the `on_action()` global function defined in the Python application. If there is no such function, actions will not trigger anything.<br/> The signature of the *on_action* callback function must be: - *state*: the `State^` instance of the caller. - *id* (optional): a string representing the identifier of the caller. - *payload* (optional): an optional payload from the caller. on_change (Callable): The function that is called when a control modifies variables it is bound to, as the result of an interaction with the end-user.<br/> It defaults to the `on_change()` global function defined in the Python application. If there is no such function, user interactions will not trigger anything.<br/> The signature of the *on_change* callback function must be: - *state*: the `State^` instance of the caller. - *var_name* (str): The name of the variable that triggered this callback. - *var_value* (any): The new value for this variable. on_init (Callable): The function that is called on the first connection of a new client.<br/> It defaults to the `on_init()` global function defined in the Python application. If there is no such function, the first connection will not trigger anything.<br/> The signature of the *on_init* callback function must be: - *state*: the `State^` instance of the caller. on_navigate (Callable): The function that is called when a page is requested.<br/> It defaults to the `on_navigate()` global function defined in the Python application. If there is no such function, page requests will not trigger anything.<br/> The signature of the *on_navigate* callback function must be: - *state*: the `State^` instance of the caller. - *page_name*: the name of the page the user is navigating to. - *params* (Optional): the query parameters provided in the URL. The *on_navigate* callback function must return the name of the page the user should be directed to. on_exception (Callable): The function that is called an exception occurs on user code.<br/> It defaults to the `on_exception()` global function defined in the Python application. If there is no such function, exceptions will not trigger anything.<br/> The signature of the *on_exception* callback function must be: - *state*: the `State^` instance of the caller. - *function_name*: the name of the function that raised the exception. - *exception*: the exception object that was raised. on_status (Callable): The function that is called when the status page is shown.<br/> It defaults to the `on_status()` global function defined in the Python application. If there is no such function, status page content shows only the status of the server.<br/> The signature of the *on_status* callback function must be: - *state*: the `State^` instance of the caller. It must return raw and valid HTML content as a string. on_user_content (Callable): The function that is called when a specific URL (generated by `get_user_content_url()^`) is requested.<br/> This callback function must return the raw HTML content of the page to be displayed on the browser. This attribute defaults to the `on_user_content()` global function defined in the Python application. If there is no such function, those specific URLs will not trigger anything.<br/> The signature of the *on_user_content* callback function must be: - *state*: the `State^` instance of the caller. - *path*: the path provided to the `get_user_content_url()^` to build the URL. - *parameters*: An optional dictionary as defined in the `get_user_content_url()^` call. The returned HTML content can therefore use both the variables stored in the *state* and the parameters provided in the call to `get_user_content_url()^`. state (State^): **Only defined when running in an IPython notebook context.**<br/> The unique instance of `State^` that you can use to change bound variables directly, potentially impacting the user interface in real-time. !!! note This class belongs to and is documented in the `taipy.gui` package but it is accessible from the top `taipy` package to simplify its access, allowing to use: ```py from taipy import Gui ``` """ __root_page_name = "TaiPy_root_page" __env_filename = "taipy.gui.env" __UI_BLOCK_NAME = "TaipyUiBlockVar" __MESSAGE_GROUPING_NAME = "TaipyMessageGrouping" __ON_INIT_NAME = "TaipyOnInit" __ARG_CLIENT_ID = "client_id" __INIT_URL = "taipy-init" __JSX_URL = "taipy-jsx" __CONTENT_ROOT = "taipy-content" __UPLOAD_URL = "taipy-uploads" _EXTENSION_ROOT = "taipy-extension" __USER_CONTENT_URL = "taipy-user-content" __BROADCAST_G_ID = "taipy_broadcasting" __BRDCST_CALLBACK_G_ID = "taipy_brdcst_callback" __SELF_VAR = "__gui" __DO_NOT_UPDATE_VALUE = _DoNotUpdate() _HTML_CONTENT_KEY = "__taipy_html_content" __USER_CONTENT_CB = "custom_user_content_cb" __RE_HTML = re.compile(r"(.*?)\.html$") __RE_MD = re.compile(r"(.*?)\.md$") __RE_PY = re.compile(r"(.*?)\.py$") __RE_PAGE_NAME = re.compile(r"^[\w\-\/]+$") __reserved_routes: t.List[str] = [ __INIT_URL, __JSX_URL, __CONTENT_ROOT, __UPLOAD_URL, _EXTENSION_ROOT, __USER_CONTENT_URL, ] __LOCAL_TZ = str(tzlocal.get_localzone()) __extensions: t.Dict[str, t.List[ElementLibrary]] = {} __shared_variables: t.List[str] = [] __content_providers: t.Dict[type, t.Callable[..., str]] = {} def __init__( self, page: t.Optional[t.Union[str, Page]] = None, pages: t.Optional[dict] = None, css_file: t.Optional[str] = None, path_mapping: t.Optional[dict] = {}, env_filename: t.Optional[str] = None, libraries: t.Optional[t.List[ElementLibrary]] = None, flask: t.Optional[Flask] = None, ): """Initialize a new Gui instance. Arguments: page (Optional[Union[str, Page^]]): An optional `Page^` instance that is used when there is a single page in this interface, referenced as the *root* page (located at `/`).<br/> If *page* is a raw string and if it holds a path to a readable file then a `Markdown^` page is built from the content of that file.<br/> If *page* is a string that does not indicate a path to readable file then a `Markdown^` page is built from that string.<br/> Note that if *pages* is provided, those pages are added as well. pages (Optional[dict]): Used if you want to initialize this instance with a set of pages.<br/> The method `(Gui.)add_pages(pages)^` is called if *pages* is not None. You can find details on the possible values of this argument in the documentation for this method. css_file (Optional[str]): A pathname to a CSS file that gets used as a style sheet in all the pages.<br/> The default value is a file that has the same base name as the Python file defining the `main` function, sitting next to this Python file, with the `.css` extension. path_mapping (Optional[dict]): A dictionary that associates a URL prefix to a path in the server file system.<br/> If the assets of your application are located in */home/me/app_assets* and you want to access them using only '*assets*' in your application, you can set *path_mapping={"assets": "/home/me/app_assets"}*. If your application then requests the file *"/assets/images/logo.png"*, the server searches for the file *"/home/me/app_assets/images/logo.png"*.<br/> If empty or not defined, access through the browser to all resources under the directory of the main Python file is allowed. env_filename (Optional[str]): An optional file from which to load application configuration variables (see the [Configuration](../gui/configuration.md#configuring-the-gui-instance) section of the User Manual for details.)<br/> The default value is "taipy.gui.env" libraries (Optional[List[ElementLibrary]]): An optional list of extension library instances that pages can reference.<br/> Using this argument is equivalent to calling `(Gui.)add_library()^` for each list's elements. flask (Optional[Flask]): An optional instance of a Flask application object.<br/> If this argument is set, this `Gui` instance will use the value of this argument as the underlying server. If omitted or set to None, this `Gui` will create its own Flask application instance and use it to serve the pages. """ # store suspected local containing frame self.__frame = t.cast(FrameType, t.cast(FrameType, inspect.currentframe()).f_back) self.__default_module_name = _get_module_name_from_frame(self.__frame) self._set_css_file(css_file) # Preserve server config for server initialization self._path_mapping = path_mapping self._flask = flask self._config = _Config() self.__content_accessor = None self._accessors = _DataAccessors() self.__state: t.Optional[State] = None self.__bindings = _Bindings(self) self.__locals_context = _LocalsContext() self.__var_dir = _VariableDirectory(self.__locals_context) self.__evaluator: _Evaluator = None # type: ignore self.__adapter = _Adapter() self.__directory_name_of_pages: t.List[str] = [] # default actions self.on_action: t.Optional[t.Callable] = None self.on_change: t.Optional[t.Callable] = None self.on_init: t.Optional[t.Callable] = None self.on_navigate: t.Optional[t.Callable] = None self.on_exception: t.Optional[t.Callable] = None self.on_status: t.Optional[t.Callable] = None self.on_user_content: t.Optional[t.Callable] = None # sid from client_id self.__client_id_2_sid: t.Dict[str, t.Set[str]] = {} # Load default config self._flask_blueprint: t.List[Blueprint] = [] self._config._load(default_config) # get taipy version try: gui_file = pathlib.Path(__file__ or ".").resolve() with open(gui_file.parent / "version.json") as version_file: self.__version = json.load(version_file) except Exception as e: # pragma: no cover _warn("Cannot retrieve version.json file", e) self.__version = {} # Load Markdown extension # NOTE: Make sure, if you change this extension list, that the User Manual gets updated. # There's a section that explicitly lists these extensions in # docs/gui/pages.md#markdown-specifics self._markdown = md_lib.Markdown( extensions=[ "fenced_code", "meta", "admonition", "sane_lists", "tables", "attr_list", "md_in_html", _TaipyMarkdownExtension(gui=self), ] ) if page: self.add_page(name=Gui.__root_page_name, page=page) if pages is not None: self.add_pages(pages) if env_filename is not None: self.__env_filename = env_filename if libraries is not None: for library in libraries: Gui.add_library(library) @staticmethod def add_library(library: ElementLibrary) -> None: """Add a custom visual element library. This application will be able to use custom visual elements defined in this library. Arguments: library: The custom visual element library to add to this application. Multiple libraries with the same name can be added. This allows to split multiple custom visual elements in several `ElementLibrary^` instances, but still refer to these elements with the same prefix in the page definitions. """ if isinstance(library, ElementLibrary): _Factory.set_library(library) library_name = library.get_name() if library_name.isidentifier(): libs = Gui.__extensions.get(library_name) if libs is None: Gui.__extensions[library_name] = [library] else: libs.append(library) _ElementApiGenerator().add_library(library) else: raise NameError(f"ElementLibrary passed to add_library() has an invalid name: '{library_name}'") else: # pragma: no cover raise RuntimeError( f"add_library() argument should be a subclass of ElementLibrary instead of '{type(library)}'" ) @staticmethod def register_content_provider(content_type: type, content_provider: t.Callable[..., str]) -> None: """Add a custom content provider. The application can use custom content for the `part` block when its *content* property is set to an object with type *type*. Arguments: content_type: The type of the content that triggers the content provider. content_provider: The function that converts content of type *type* into an HTML string. """ if Gui.__content_providers.get(content_type): _warn(f"The type {content_type} is already associated with a provider.") return if not callable(content_provider): _warn(f"The provider for {content_type} must be a function.") return Gui.__content_providers[content_type] = content_provider def __process_content_provider(self, state: State, path: str, query: t.Dict[str, str]): variable_name = query.get("variable_name") content = None if variable_name: content = _getscopeattr(self, variable_name) if isinstance(content, _TaipyContentHtml): content = content.get() provider_fn = Gui.__content_providers.get(type(content)) if provider_fn is None: # try plotly if find_spec("plotly") and find_spec("plotly.graph_objs"): from plotly.graph_objs import Figure as PlotlyFigure if isinstance(content, PlotlyFigure): def get_plotly_content(figure: PlotlyFigure): return figure.to_html() Gui.register_content_provider(PlotlyFigure, get_plotly_content) provider_fn = get_plotly_content if provider_fn is None: # try matplotlib if find_spec("matplotlib") and find_spec("matplotlib.figure"): from matplotlib.figure import Figure as MatplotlibFigure if isinstance(content, MatplotlibFigure): def get_matplotlib_content(figure: MatplotlibFigure): import base64 from io import BytesIO buf = BytesIO() figure.savefig(buf, format="png") data = base64.b64encode(buf.getbuffer()).decode("ascii") return f'<img src="data:image/png;base64,{data}"/>' Gui.register_content_provider(MatplotlibFigure, get_matplotlib_content) provider_fn = get_matplotlib_content if callable(provider_fn): try: return provider_fn(content) except Exception as e: _warn(f"Error in content provider for type {str(type(content))}", e) return ( '<div style="background:white;color:red;">' + (f"No valid provider for type {type(content).__name__}" if content else "Wrong context.") + "</div>" ) @staticmethod def add_shared_variable(*names: str) -> None: """Add shared variables. The variables will be synchronized between all clients when updated. Note that only variables from the main module will be registered. This is a synonym for `(Gui.)add_shared_variables()^`. Arguments: names: The names of the variables that become shared, as a list argument. """ for name in names: if name not in Gui.__shared_variables: Gui.__shared_variables.append(name) @staticmethod def add_shared_variables(*names: str) -> None: """Add shared variables. The variables will be synchronized between all clients when updated. Note that only variables from the main module will be registered. This is a synonym for `(Gui.)add_shared_variable()^`. Arguments: names: The names of the variables that become shared, as a list argument. """ Gui.add_shared_variable(*names) def _get_shared_variables(self) -> t.List[str]: return self.__evaluator.get_shared_variables() def __get_content_accessor(self): if self.__content_accessor is None: self.__content_accessor = _ContentAccessor(self._get_config("data_url_max_size", 50 * 1024)) return self.__content_accessor def _bindings(self): return self.__bindings def _get_data_scope(self) -> SimpleNamespace: return self.__bindings._get_data_scope() def _get_all_data_scopes(self) -> t.Dict[str, SimpleNamespace]: return self.__bindings._get_all_scopes() def _get_config(self, name: ConfigParameter, default_value: t.Any) -> t.Any: return self._config._get_config(name, default_value) def _get_themes(self) -> t.Optional[t.Dict[str, t.Any]]: theme = self._get_config("theme", None) dark_theme = self._get_config("dark_theme", None) light_theme = self._get_config("light_theme", None) res = {} if theme: res["base"] = theme if dark_theme: res["dark"] = dark_theme if light_theme: res["light"] = light_theme return res if theme or dark_theme or light_theme else None def _bind(self, name: str, value: t.Any) -> None: self._bindings()._bind(name, value) def __get_state(self): return self.__state def _get_client_id(self) -> str: return ( _DataScopes._GLOBAL_ID if self._bindings()._is_single_client() else getattr(g, Gui.__ARG_CLIENT_ID, "unknown id") ) def __set_client_id_in_context(self, client_id: t.Optional[str] = None, force=False): if not client_id and request: client_id = request.args.get(Gui.__ARG_CLIENT_ID, "") if not client_id and force: res = self._bindings()._get_or_create_scope("") client_id = res[0] if res[1] else None if client_id and request: if sid := getattr(request, "sid", None): sids = self.__client_id_2_sid.get(client_id, None) if sids is None: sids = set() self.__client_id_2_sid[client_id] = sids sids.add(sid) g.client_id = client_id def __is_var_modified_in_context(self, var_name: str, derived_vars: t.Set[str]) -> bool: modified_vars: t.Optional[t.Set[str]] = getattr(g, "modified_vars", None) der_vars: t.Optional[t.Set[str]] = getattr(g, "derived_vars", None) setattr(g, "update_count", getattr(g, "update_count", 0) + 1) if modified_vars is None: modified_vars = set() g.modified_vars = modified_vars if der_vars is None: g.derived_vars = derived_vars else: der_vars.update(derived_vars) if var_name in modified_vars: return True modified_vars.add(var_name) return False def __clean_vars_on_exit(self) -> t.Optional[t.Set[str]]: update_count = getattr(g, "update_count", 0) - 1 if update_count < 1: derived_vars: t.Set[str] = getattr(g, "derived_vars", set()) delattr(g, "update_count") delattr(g, "modified_vars") delattr(g, "derived_vars") return derived_vars else: setattr(g, "update_count", update_count) return None def _manage_message(self, msg_type: _WsType, message: dict) -> None: try: client_id = None if msg_type == _WsType.CLIENT_ID.value: res = self._bindings()._get_or_create_scope(message.get("payload", "")) client_id = res[0] if res[1] else None self.__set_client_id_in_context(client_id or message.get(Gui.__ARG_CLIENT_ID)) with self._set_locals_context(message.get("module_context") or None): if msg_type == _WsType.UPDATE.value: payload = message.get("payload", {}) self.__front_end_update( str(message.get("name")), payload.get("value"), message.get("propagate", True), payload.get("relvar"), payload.get("on_change"), ) elif msg_type == _WsType.ACTION.value: self.__on_action(message.get("name"), message.get("payload")) elif msg_type == _WsType.DATA_UPDATE.value: self.__request_data_update(str(message.get("name")), message.get("payload")) elif msg_type == _WsType.REQUEST_UPDATE.value: self.__request_var_update(message.get("payload")) self.__send_ack(message.get("ack_id")) except Exception as e: # pragma: no cover _warn(f"Decoding Message has failed: {message}", e) def __front_end_update( self, var_name: str, value: t.Any, propagate=True, rel_var: t.Optional[str] = None, on_change: t.Optional[str] = None, ) -> None: if not var_name: return # Check if Variable is a managed type current_value = _getscopeattr_drill(self, self.__evaluator.get_hash_from_expr(var_name)) if isinstance(current_value, _TaipyData): return elif rel_var and isinstance(current_value, _TaipyLovValue): # pragma: no cover lov_holder = _getscopeattr_drill(self, self.__evaluator.get_hash_from_expr(rel_var)) if isinstance(lov_holder, _TaipyLov): val = value if isinstance(value, list) else [value] elt_4_ids = self.__adapter._get_elt_per_ids(lov_holder.get_name(), lov_holder.get()) ret_val = [elt_4_ids.get(x, x) for x in val] if isinstance(value, list): value = ret_val elif ret_val: value = ret_val[0] elif isinstance(current_value, _TaipyBase): value = current_value.cast_value(value) self._update_var( var_name, value, propagate, current_value if isinstance(current_value, _TaipyBase) else None, on_change ) def _update_var( self, var_name: str, value: t.Any, propagate=True, holder: t.Optional[_TaipyBase] = None, on_change: t.Optional[str] = None, ) -> None: if holder: var_name = holder.get_name() hash_expr = self.__evaluator.get_hash_from_expr(var_name) derived_vars = {hash_expr} # set to broadcast mode if hash_expr is in shared_variable if hash_expr in self._get_shared_variables(): self._set_broadcast() # Use custom attrsetter function to allow value binding for _MapDict if propagate: _setscopeattr_drill(self, hash_expr, value) # In case expression == hash (which is when there is only a single variable in expression) if var_name == hash_expr or hash_expr.startswith("tpec_"): derived_vars.update(self._re_evaluate_expr(var_name)) elif holder: derived_vars.update(self._evaluate_holders(hash_expr)) # if the variable has been evaluated then skip updating to prevent infinite loop var_modified = self.__is_var_modified_in_context(hash_expr, derived_vars) if not var_modified: self._call_on_change( var_name, value.get() if isinstance(value, _TaipyBase) else value._dict if isinstance(value, _MapDict) else value, on_change, ) derived_modified = self.__clean_vars_on_exit() if derived_modified is not None: self.__send_var_list_update(list(derived_modified), var_name) def _get_real_var_name(self, var_name: str) -> t.Tuple[str, str]: if not var_name: return (var_name, var_name) # Handle holder prefix if needed if var_name.startswith(_TaipyBase._HOLDER_PREFIX): for hp in _TaipyBase._get_holder_prefixes(): if var_name.startswith(hp): var_name = var_name[len(hp) :] break suffix_var_name = "" if "." in var_name: first_dot_index = var_name.index(".") suffix_var_name = var_name[first_dot_index + 1 :] var_name = var_name[:first_dot_index] var_name_decode, module_name = _variable_decode(self._get_expr_from_hash(var_name)) current_context = self._get_locals_context() # #583: allow module resolution for var_name in current_context root_page context if ( module_name and self._config.root_page and self._config.root_page._renderer and self._config.root_page._renderer._get_module_name() == module_name ): return f"{var_name_decode}.{suffix_var_name}" if suffix_var_name else var_name_decode, module_name if module_name == current_context: var_name = var_name_decode else: if var_name not in self.__var_dir._var_head: raise NameError(f"Can't find matching variable for {var_name} on context: {current_context}") _found = False for k, v in self.__var_dir._var_head[var_name]: if v == current_context: var_name = k _found = True break if not _found: # pragma: no cover raise NameError(f"Can't find matching variable for {var_name} on context: {current_context}") return f"{var_name}.{suffix_var_name}" if suffix_var_name else var_name, current_context def _call_on_change(self, var_name: str, value: t.Any, on_change: t.Optional[str] = None): try: var_name, current_context = self._get_real_var_name(var_name) except Exception as e: # pragma: no cover _warn("", e) return on_change_fn = self._get_user_function(on_change) if on_change else None if not callable(on_change_fn): on_change_fn = self._get_user_function("on_change") if callable(on_change_fn): try: argcount = on_change_fn.__code__.co_argcount if argcount > 0 and inspect.ismethod(on_change_fn): argcount -= 1 args: t.List[t.Any] = [None for _ in range(argcount)] if argcount > 0: args[0] = self.__get_state() if argcount > 1: args[1] = var_name if argcount > 2: args[2] = value if argcount > 3: args[3] = current_context on_change_fn(*args) except Exception as e: # pragma: no cover if not self._call_on_exception(on_change or "on_change", e): _warn(f"{on_change or 'on_change'}(): callback function raised an exception", e) def _get_content(self, var_name: str, value: t.Any, image: bool) -> t.Any: ret_value = self.__get_content_accessor().get_info(var_name, value, image) return f"/{Gui.__CONTENT_ROOT}/{ret_value[0]}" if isinstance(ret_value, tuple) else ret_value def __serve_content(self, path: str) -> t.Any: self.__set_client_id_in_context() parts = path.split("/") if len(parts) > 1: file_name = parts[-1] (dir_path, as_attachment) = self.__get_content_accessor().get_content_path( path[: -len(file_name) - 1], file_name, request.args.get("bypass") ) if dir_path: return send_from_directory(str(dir_path), file_name, as_attachment=as_attachment) return ("", 404) def _get_user_content_url( self, path: t.Optional[str] = None, query_args: t.Optional[t.Dict[str, str]] = None ) -> t.Optional[str]: qargs = query_args or {} qargs.update({Gui.__ARG_CLIENT_ID: self._get_client_id()}) return f"/{Gui.__USER_CONTENT_URL}/{path or 'TaIpY'}?{urlencode(qargs)}" def __serve_user_content(self, path: str) -> t.Any: self.__set_client_id_in_context() qargs: t.Dict[str, str] = {} qargs.update(request.args) qargs.pop(Gui.__ARG_CLIENT_ID, None) cb_function: t.Optional[t.Union[t.Callable, str]] = None cb_function_name = None if qargs.get(Gui._HTML_CONTENT_KEY): cb_function = self.__process_content_provider cb_function_name = cb_function.__name__ else: cb_function_name = qargs.get(Gui.__USER_CONTENT_CB) if cb_function_name: cb_function = self._get_user_function(cb_function_name) if not callable(cb_function): parts = cb_function_name.split(".", 1) if len(parts) > 1: base = _getscopeattr(self, parts[0], None) if base and (meth := getattr(base, parts[1], None)): cb_function = meth else: base = self.__evaluator._get_instance_in_context(parts[0]) if base and (meth := getattr(base, parts[1], None)): cb_function = meth if not callable(cb_function): _warn(f"{cb_function_name}() callback function has not been defined.") cb_function = None if cb_function is None: cb_function_name = "on_user_content" if hasattr(self, cb_function_name) and callable(self.on_user_content): cb_function = self.on_user_content else: _warn("on_user_content() callback function has not been defined.") if callable(cb_function): try: args: t.List[t.Any] = [] if path: args.append(path) if len(qargs): args.append(qargs) ret = self._call_function_with_state(cb_function, args) if ret is None: _warn(f"{cb_function_name}() callback function must return a value.") else: return (ret, 200) except Exception as e: # pragma: no cover if not self._call_on_exception(str(cb_function_name), e): _warn(f"{cb_function_name}() callback function raised an exception", e) return ("", 404) def __serve_extension(self, path: str) -> t.Any: parts = path.split("/") last_error = "" resource_name = None if len(parts) > 1: libs = Gui.__extensions.get(parts[0], []) for library in libs: try: resource_name = library.get_resource("/".join(parts[1:])) if resource_name: return send_file(resource_name) except Exception as e: last_error = f"\n{e}" # Check if the resource is served by another library with the same name _warn(f"Resource '{resource_name or path}' not accessible for library '{parts[0]}'{last_error}") return ("", 404) def __get_version(self) -> str: return f'{self.__version.get("major", 0)}.{self.__version.get("minor", 0)}.{self.__version.get("patch", 0)}' def __append_libraries_to_status(self, status: t.Dict[str, t.Any]): libraries: t.Dict[str, t.Any] = {} for libs_list in self.__extensions.values(): for lib in libs_list: if not isinstance(lib, ElementLibrary): continue libs = libraries.get(lib.get_name()) if libs is None: libs = [] libraries[lib.get_name()] = libs elts: t.List[t.Dict[str, str]] = [] libs.append({"js module": lib.get_js_module_name(), "elements": elts}) for element_name, elt in lib.get_elements().items(): if not isinstance(elt, Element): continue elt_dict = {"name": element_name} if hasattr(elt, "_render_xhtml"): elt_dict["render function"] = elt._render_xhtml.__code__.co_name else: elt_dict["react name"] = elt._get_js_name(element_name) elts.append(elt_dict) status.update({"libraries": libraries}) def _serve_status(self, template: pathlib.Path) -> t.Dict[str, t.Dict[str, str]]: base_json: t.Dict[str, t.Any] = {"user_status": str(self.__call_on_status() or "")} if self._get_config("extended_status", False): base_json.update( { "flask_version": str(metadata.version("flask") or ""), "backend_version": self.__get_version(), "host": f'{self._get_config("host", "localhost")}:{self._get_config("port", "default")}', "python_version": sys.version, } ) self.__append_libraries_to_status(base_json) try: base_json.update(json.loads(template.read_text())) except Exception as e: # pragma: no cover _warn(f"Exception raised reading JSON in '{template}'", e) return {"gui": base_json} def __upload_files(self): self.__set_client_id_in_context() if "var_name" not in request.form: _warn("No var name") return ("No var name", 400) var_name = request.form["var_name"] multiple = "multiple" in request.form and request.form["multiple"] == "True" if "blob" not in request.files: _warn("No file part") return ("No file part", 400) file = request.files["blob"] # If the user does not select a file, the browser submits an # empty file without a filename. if file.filename == "": _warn("No selected file") return ("No selected file", 400) suffix = "" complete = True part = 0 if "total" in request.form: total = int(request.form["total"]) if total > 1 and "part" in request.form: part = int(request.form["part"]) suffix = f".part.{part}" complete = part == total - 1 if file: # and allowed_file(file.filename) upload_path = pathlib.Path(self._get_config("upload_folder", tempfile.gettempdir())).resolve() file_path = _get_non_existent_file_path(upload_path, secure_filename(file.filename)) file.save(str(upload_path / (file_path.name + suffix))) if complete: if part > 0: try: with open(file_path, "wb") as grouped_file: for nb in range(part + 1): with open(upload_path / f"{file_path.name}.part.{nb}", "rb") as part_file: grouped_file.write(part_file.read()) except EnvironmentError as ee: # pragma: no cover _warn("Cannot group file after chunk upload", ee) return # notify the file is uploaded newvalue = str(file_path) if multiple: value = _getscopeattr(self, var_name) if not isinstance(value, t.List): value = [] if value is None else [value] value.append(newvalue) newvalue = value setattr(self._bindings(), var_name, newvalue) return ("", 200) _data_request_counter = 1 def __send_var_list_update( # noqa C901 self, modified_vars: t.List[str], front_var: t.Optional[str] = None, ): ws_dict = {} values = {v: _getscopeattr_drill(self, v) for v in modified_vars} for k, v in values.items(): if isinstance(v, (_TaipyData, _TaipyContentHtml)) and v.get_name() in modified_vars: modified_vars.remove(v.get_name()) elif isinstance(v, _DoNotUpdate): modified_vars.remove(k) for _var in modified_vars: newvalue = values.get(_var) if isinstance(newvalue, _TaipyData): # A changing integer that triggers a data request newvalue = Gui._data_request_counter Gui._data_request_counter = (Gui._data_request_counter % 100) + 1 else: if isinstance(newvalue, (_TaipyContent, _TaipyContentImage)): ret_value = self.__get_content_accessor().get_info( front_var, newvalue.get(), isinstance(newvalue, _TaipyContentImage) ) if isinstance(ret_value, tuple): newvalue = f"/{Gui.__CONTENT_ROOT}/{ret_value[0]}" else: newvalue = ret_value elif isinstance(newvalue, _TaipyContentHtml): newvalue = self._get_user_content_url( None, {"variable_name": str(_var), Gui._HTML_CONTENT_KEY: str(time.time())} ) elif isinstance(newvalue, _TaipyLov): newvalue = [self.__adapter._run_for_var(newvalue.get_name(), elt) for elt in newvalue.get()] elif isinstance(newvalue, _TaipyLovValue): if isinstance(newvalue.get(), list): newvalue = [ self.__adapter._run_for_var(newvalue.get_name(), elt, id_only=True) for elt in newvalue.get() ] else: newvalue = self.__adapter._run_for_var(newvalue.get_name(), newvalue.get(), id_only=True) if isinstance(newvalue, (dict, _MapDict)): continue # this var has no transformer debug_warnings: t.List[warnings.WarningMessage] = [] with warnings.catch_warnings(record=True) as warns: warnings.resetwarnings() json.dumps(newvalue, cls=_TaipyJsonEncoder) if len(warns): keep_value = True for w in list(warns): if is_debugging(): debug_warnings.append(w) if w.category is not DeprecationWarning and w.category is not PendingDeprecationWarning: keep_value = False break if not keep_value: # do not send data that is not serializable continue for w in debug_warnings: warnings.warn(w.message, w.category) ws_dict[_var] = newvalue # TODO: What if value == newvalue? self.__send_ws_update_with_dict(ws_dict) def __request_data_update(self, var_name: str, payload: t.Any) -> None: # Use custom attrgetter function to allow value binding for _MapDict newvalue = _getscopeattr_drill(self, var_name) if isinstance(newvalue, _TaipyData): ret_payload = None if isinstance(payload, dict): lib_name = payload.get("library") if isinstance(lib_name, str): libs = self.__extensions.get(lib_name, []) for lib in libs: user_var_name = var_name try: with contextlib.suppress(NameError): # ignore name error and keep var_name user_var_name = self._get_real_var_name(var_name)[0] ret_payload = lib.get_data(lib_name, payload, user_var_name, newvalue) if ret_payload: break except Exception as e: # pragma: no cover _warn( f"Exception raised in '{lib_name}.get_data({lib_name}, payload, {user_var_name}, value)'", e, ) if not isinstance(ret_payload, dict): ret_payload = self._accessors._get_data(self, var_name, newvalue, payload) self.__send_ws_update_with_dict({var_name: ret_payload}) def __request_var_update(self, payload: t.Any): if isinstance(payload, dict) and isinstance(payload.get("names"), list): if payload.get("refresh", False): # refresh vars for _var in t.cast(list, payload.get("names")): val = _getscopeattr_drill(self, _var) self._refresh_expr( val.get_name() if isinstance(val, _TaipyBase) else _var, val if isinstance(val, _TaipyBase) else None, ) self.__send_var_list_update(payload["names"]) def __send_ws(self, payload: dict, allow_grouping=True) -> None: grouping_message = self.__get_message_grouping() if allow_grouping else None if grouping_message is None: try: self._server._ws.emit( "message", payload, to=self.__get_ws_receiver(), ) time.sleep(0.001) except Exception as e: # pragma: no cover _warn(f"Exception raised in WebSocket communication in '{self.__frame.f_code.co_name}'", e) else: grouping_message.append(payload) def __broadcast_ws(self, payload: dict): try: self._server._ws.emit( "message", payload, ) time.sleep(0.001) except Exception as e: # pragma: no cover _warn(f"Exception raised in WebSocket communication in '{self.__frame.f_code.co_name}'", e) def __send_ack(self, ack_id: t.Optional[str]) -> None: if ack_id: try: self._server._ws.emit("message", {"type": _WsType.ACKNOWLEDGEMENT.value, "id": ack_id}) time.sleep(0.001) except Exception as e: # pragma: no cover _warn(f"Exception raised in WebSocket communication (send ack) in '{self.__frame.f_code.co_name}'", e) def _send_ws_id(self, id: str) -> None: self.__send_ws( { "type": _WsType.CLIENT_ID.value, "id": id, }, allow_grouping=False, ) def __send_ws_download(self, content: str, name: str, on_action: str) -> None: self.__send_ws({"type": _WsType.DOWNLOAD_FILE.value, "content": content, "name": name, "onAction": on_action}) def __send_ws_alert(self, type: str, message: str, system_notification: bool, duration: int) -> None: self.__send_ws( { "type": _WsType.ALERT.value, "atype": type, "message": message, "system": system_notification, "duration": duration, } ) def __send_ws_partial(self, partial: str): self.__send_ws( { "type": _WsType.PARTIAL.value, "name": partial, } ) def __send_ws_block( self, action: t.Optional[str] = None, message: t.Optional[str] = None, close: t.Optional[bool] = False, cancel: t.Optional[bool] = False, ): self.__send_ws( { "type": _WsType.BLOCK.value, "action": action, "close": close, "message": message, "noCancel": not cancel, } ) def __send_ws_navigate( self, to: str, params: t.Optional[t.Dict[str, str]], tab: t.Optional[str], force: bool, ): self.__send_ws({"type": _WsType.NAVIGATE.value, "to": to, "params": params, "tab": tab, "force": force}) def __send_ws_update_with_dict(self, modified_values: dict) -> None: payload = [ {"name": _get_client_var_name(k), "payload": (v if isinstance(v, dict) and "value" in v else {"value": v})} for k, v in modified_values.items() ] if self._is_broadcasting(): self.__broadcast_ws({"type": _WsType.MULTIPLE_UPDATE.value, "payload": payload}) self._set_broadcast(False) else: self.__send_ws({"type": _WsType.MULTIPLE_UPDATE.value, "payload": payload}) def __send_ws_broadcast(self, var_name: str, var_value: t.Any): self.__broadcast_ws( {"type": _WsType.UPDATE.value, "name": _get_broadcast_var_name(var_name), "payload": {"value": var_value}} ) def __get_ws_receiver(self) -> t.Union[t.List[str], t.Any, None]: if self._bindings()._is_single_client(): return None sid = getattr(request, "sid", None) if request else None sids = self.__client_id_2_sid.get(self._get_client_id(), set()) if sid: sids.add(sid) return list(sids) def __get_message_grouping(self): return ( _getscopeattr(self, Gui.__MESSAGE_GROUPING_NAME) if _hasscopeattr(self, Gui.__MESSAGE_GROUPING_NAME) else None ) def __enter__(self): self.__hold_messages() return self def __exit__(self, exc_type, exc_value, traceback): try: self.__send_messages() except Exception as e: # pragma: no cover _warn("Exception raised while sending messages", e) if exc_value: # pragma: no cover _warn(f"An {exc_type or 'Exception'} was raised", exc_value) return True def __hold_messages(self): grouping_message = self.__get_message_grouping() if grouping_message is None: self._bind_var_val(Gui.__MESSAGE_GROUPING_NAME, []) def __send_messages(self): grouping_message = self.__get_message_grouping() if grouping_message is not None: _delscopeattr(self, Gui.__MESSAGE_GROUPING_NAME) if len(grouping_message): self.__send_ws({"type": _WsType.MULTIPLE_MESSAGE.value, "payload": grouping_message}) def _get_user_function(self, func_name: str) -> t.Union[t.Callable, str]: func = _getscopeattr(self, func_name, None) if not callable(func): func = self._get_locals_bind().get(func_name) if not callable(func): func = self.__locals_context.get_default().get(func_name) return func if callable(func) else func_name def _get_user_instance(self, class_name: str, class_type: type) -> t.Union[object, str]: cls = _getscopeattr(self, class_name, None) if not isinstance(cls, class_type): cls = self._get_locals_bind().get(class_name) if not isinstance(cls, class_type): cls = self.__locals_context.get_default().get(class_name) return cls if isinstance(cls, class_type) else class_name def __on_action(self, id: t.Optional[str], payload: t.Any) -> None: if isinstance(payload, dict): action = payload.get("action") else: action = str(payload) payload = {"action": action} if action: if self.__call_function_with_args(action_function=self._get_user_function(action), id=id, payload=payload): return else: # pragma: no cover _warn(f"on_action(): '{action}' is not a valid function.") if hasattr(self, "on_action"): self.__call_function_with_args(action_function=self.on_action, id=id, payload=payload) def __call_function_with_args(self, **kwargs): action_function = kwargs.get("action_function") id = kwargs.get("id") payload = kwargs.get("payload") if callable(action_function): try: argcount = action_function.__code__.co_argcount if argcount > 0 and inspect.ismethod(action_function): argcount -= 1 args = [None for _ in range(argcount)] if argcount > 0: args[0] = self.__get_state() if argcount > 1: try: args[1] = self._get_real_var_name(id)[0] except Exception: args[1] = id if argcount > 2: args[2] = payload action_function(*args) return True except Exception as e: # pragma: no cover if not self._call_on_exception(action_function.__name__, e): _warn(f"on_action(): Exception raised in '{action_function.__name__}()'", e) return False def _call_function_with_state(self, user_function: t.Callable, args: t.List[t.Any]) -> t.Any: args.insert(0, self.__get_state()) argcount = user_function.__code__.co_argcount if argcount > 0 and inspect.ismethod(user_function): argcount -= 1 if argcount > len(args): args += (argcount - len(args)) * [None] else: args = args[:argcount] return user_function(*args) def _set_module_context(self, module_context: t.Optional[str]) -> t.ContextManager[None]: return self._set_locals_context(module_context) if module_context is not None else contextlib.nullcontext() def _call_user_callback( self, state_id: t.Optional[str], user_callback: t.Callable, args: t.List[t.Any], module_context: t.Optional[str] ) -> t.Any: try: with self.get_flask_app().app_context(): self.__set_client_id_in_context(state_id) with self._set_module_context(module_context): return self._call_function_with_state(user_callback, args) except Exception as e: # pragma: no cover if not self._call_on_exception(user_callback.__name__, e): _warn(f"invoke_callback(): Exception raised in '{user_callback.__name__}()'", e) return None def _call_broadcast_callback( self, user_callback: t.Callable, args: t.List[t.Any], module_context: t.Optional[str] ) -> t.Any: @contextlib.contextmanager def _broadcast_callback() -> t.Iterator[None]: try: setattr(g, Gui.__BRDCST_CALLBACK_G_ID, True) yield finally: setattr(g, Gui.__BRDCST_CALLBACK_G_ID, False) with _broadcast_callback(): # Use global scopes for broadcast callbacks return self._call_user_callback(_DataScopes._GLOBAL_ID, user_callback, args, module_context) def _is_in_brdcst_callback(self): try: return getattr(g, Gui.__BRDCST_CALLBACK_G_ID, False) except RuntimeError: return False # Proxy methods for Evaluator def _evaluate_expr(self, expr: str) -> t.Any: return self.__evaluator.evaluate_expr(self, expr) def _re_evaluate_expr(self, var_name: str) -> t.Set[str]: return self.__evaluator.re_evaluate_expr(self, var_name) def _refresh_expr(self, var_name: str, holder: t.Optional[_TaipyBase]): return self.__evaluator.refresh_expr(self, var_name, holder) def _get_expr_from_hash(self, hash_val: str) -> str: return self.__evaluator.get_expr_from_hash(hash_val) def _evaluate_bind_holder(self, holder: t.Type[_TaipyBase], expr: str) -> str: return self.__evaluator.evaluate_bind_holder(self, holder, expr) def _evaluate_holders(self, expr: str) -> t.List[str]: return self.__evaluator.evaluate_holders(self, expr) def _is_expression(self, expr: str) -> bool: if self.__evaluator is None: return False return self.__evaluator._is_expression(expr) # make components resettable def _set_building(self, building: bool): self._building = building def __is_building(self): return hasattr(self, "_building") and self._building def _get_rebuild_fn_name(self, name: str): return f"{Gui.__SELF_VAR}.{name}" def __get_attributes(self, attr_json: str, hash_json: str, args_dict: t.Dict[str, t.Any]): attributes: t.Dict[str, t.Any] = json.loads(unquote(attr_json)) hashes: t.Dict[str, str] = json.loads(unquote(hash_json)) attributes.update({k: args_dict.get(v) for k, v in hashes.items()}) return attributes, hashes def _tbl_cols( self, rebuild: bool, rebuild_val: t.Optional[bool], attr_json: str, hash_json: str, **kwargs ) -> t.Union[str, _DoNotUpdate]: if not self.__is_building(): try: rebuild = rebuild_val if rebuild_val is not None else rebuild if rebuild: attributes, hashes = self.__get_attributes(attr_json, hash_json, kwargs) data_hash = hashes.get("data", "") data = kwargs.get(data_hash) col_dict = _get_columns_dict( data, attributes.get("columns", {}), self._accessors._get_col_types(data_hash, _TaipyData(data, data_hash)), attributes.get("date_format"), attributes.get("number_format"), ) _enhance_columns(attributes, hashes, col_dict, "table(cols)") return json.dumps(col_dict, cls=_TaipyJsonEncoder) except Exception as e: # pragma: no cover _warn("Exception while rebuilding table columns", e) return Gui.__DO_NOT_UPDATE_VALUE def _chart_conf( self, rebuild: bool, rebuild_val: t.Optional[bool], attr_json: str, hash_json: str, **kwargs ) -> t.Union[str, _DoNotUpdate]: if not self.__is_building(): try: rebuild = rebuild_val if rebuild_val is not None else rebuild if rebuild: attributes, hashes = self.__get_attributes(attr_json, hash_json, kwargs) data_hash = hashes.get("data", "") config = _build_chart_config( self, attributes, self._accessors._get_col_types(data_hash, _TaipyData(kwargs.get(data_hash), data_hash)), ) return json.dumps(config, cls=_TaipyJsonEncoder) except Exception as e: # pragma: no cover _warn("Exception while rebuilding chart config", e) return Gui.__DO_NOT_UPDATE_VALUE # Proxy methods for Adapter def _add_adapter_for_type(self, type_name: str, adapter: t.Callable) -> None: self.__adapter._add_for_type(type_name, adapter) def _add_type_for_var(self, var_name: str, type_name: str) -> None: self.__adapter._add_type_for_var(var_name, type_name) def _get_adapter_for_type(self, type_name: str) -> t.Optional[t.Callable]: return self.__adapter._get_for_type(type_name) def _get_unique_type_adapter(self, type_name: str) -> str: return self.__adapter._get_unique_type(type_name) def _run_adapter( self, adapter: t.Optional[t.Callable], value: t.Any, var_name: str, id_only=False ) -> t.Union[t.Tuple[str, ...], str, None]: return self.__adapter._run(adapter, value, var_name, id_only) def _get_valid_adapter_result(self, value: t.Any, id_only=False) -> t.Union[t.Tuple[str, ...], str, None]: return self.__adapter._get_valid_result(value, id_only) def _is_ui_blocked(self): return _getscopeattr(self, Gui.__UI_BLOCK_NAME, False) def __get_on_cancel_block_ui(self, callback: t.Optional[str]): def _taipy_on_cancel_block_ui(guiApp, id: t.Optional[str], payload: t.Any): if _hasscopeattr(guiApp, Gui.__UI_BLOCK_NAME): _setscopeattr(guiApp, Gui.__UI_BLOCK_NAME, False) guiApp.__on_action(id, {"action": callback}) return _taipy_on_cancel_block_ui def __add_pages_in_folder(self, folder_name: str, folder_path: str): from ._renderers import Html, Markdown list_of_files = os.listdir(folder_path) for file_name in list_of_files: if file_name.startswith("__"): continue if (re_match := Gui.__RE_HTML.match(file_name)) and f"{re_match.group(1)}.py" not in list_of_files: _renderers = Html(os.path.join(folder_path, file_name), frame=None) _renderers.modify_taipy_base_url(folder_name) self.add_page(name=f"{folder_name}/{re_match.group(1)}", page=_renderers) elif (re_match := Gui.__RE_MD.match(file_name)) and f"{re_match.group(1)}.py" not in list_of_files: _renderers_md = Markdown(os.path.join(folder_path, file_name), frame=None) self.add_page(name=f"{folder_name}/{re_match.group(1)}", page=_renderers_md) elif re_match := Gui.__RE_PY.match(file_name): module_name = re_match.group(1) module_path = os.path.join(folder_name, module_name).replace(os.path.sep, ".") try: module = importlib.import_module(module_path) page_instance = _get_page_from_module(module) if page_instance is not None: self.add_page(name=f"{folder_name}/{module_name}", page=page_instance) except Exception as e: _warn(f"Error while importing module '{module_path}'", e) elif os.path.isdir(child_dir_path := os.path.join(folder_path, file_name)): child_dir_name = f"{folder_name}/{file_name}" self.__add_pages_in_folder(child_dir_name, child_dir_path) # Proxy methods for LocalsContext def _get_locals_bind(self) -> t.Dict[str, t.Any]: return self.__locals_context.get_locals() def _get_default_locals_bind(self) -> t.Dict[str, t.Any]: return self.__locals_context.get_default() def _get_locals_bind_from_context(self, context: t.Optional[str]) -> t.Dict[str, t.Any]: return self.__locals_context._get_locals_bind_from_context(context) def _get_locals_context(self) -> str: current_context = self.__locals_context.get_context() return current_context if current_context is not None else self.__default_module_name def _set_locals_context(self, context: t.Optional[str]) -> t.ContextManager[None]: return self.__locals_context.set_locals_context(context) def _get_page_context(self, page_name: str) -> str | None: if page_name not in self._config.routes: return None page = None for p in self._config.pages: if p._route == page_name: page = p if page is None: return None return ( (page._renderer._get_module_name() or self.__default_module_name) if page._renderer is not None else self.__default_module_name ) @staticmethod def _get_root_page_name(): return Gui.__root_page_name def _set_flask(self, flask: Flask): self._flask = flask def _get_default_module_name(self): return self.__default_module_name @staticmethod def _get_timezone() -> str: return Gui.__LOCAL_TZ @staticmethod def _set_timezone(tz: str): Gui.__LOCAL_TZ = tz # Public methods def add_page( self, name: str, page: t.Union[str, Page], style: t.Optional[str] = "", ) -> None: """Add a page to the Graphical User Interface. Arguments: name: The name of the page. page (Union[str, Page^]): The content of the page.<br/> It can be an instance of `Markdown^` or `Html^`.<br/> If *page* is a string, then: - If *page* is set to the pathname of a readable file, the page content is read as Markdown input text. - If it is not, the page content is read from this string as Markdown text. style (Optional[str]): Additional CSS style to apply to this page. - if there is style associated with a page, it is used at a global level - if there is no style associated with the page, the style is cleared at a global level - if the page is embedded in a block control, the style is ignored Note that page names cannot start with the slash ('/') character and that each page must have a unique name. """ # Validate name if name is None: # pragma: no cover raise Exception("name is required for add_page() function.") if not Gui.__RE_PAGE_NAME.match(name): # pragma: no cover raise SyntaxError( f'Page name "{name}" is invalid. It must only contain letters, digits, dash (-), underscore (_), and forward slash (/) characters.' ) if name.startswith("/"): # pragma: no cover raise SyntaxError(f'Page name "{name}" cannot start with forward slash (/) character.') if name in self._config.routes: # pragma: no cover raise Exception(f'Page name "{name if name != Gui.__root_page_name else "/"}" is already defined.') if isinstance(page, str): from ._renderers import Markdown page = Markdown(page, frame=None) elif not isinstance(page, Page): # pragma: no cover raise Exception( f'Parameter "page" is invalid for page name "{name if name != Gui.__root_page_name else "/"}.' ) # Init a new page new_page = _Page() new_page._route = name new_page._renderer = page new_page._style = style # Append page to _config self._config.pages.append(new_page) self._config.routes.append(name) # set root page if name == Gui.__root_page_name: self._config.root_page = new_page # Update locals context self.__locals_context.add(page._get_module_name(), page._get_locals()) # Update variable directory if not page._is_class_module(): self.__var_dir.add_frame(page._frame) def add_pages(self, pages: t.Optional[t.Union[t.Mapping[str, t.Union[str, Page]], str]] = None) -> None: """Add several pages to the Graphical User Interface. Arguments: pages (Union[dict[str, Union[str, Page^]], str]): The pages to add.<br/> If *pages* is a dictionary, a page is added to this `Gui` instance for each of the entries in *pages*: - The entry key is used as the page name. - The entry value is used as the page content: - The value can can be an instance of `Markdown^` or `Html^`, then it is used as the page definition. - If entry value is a string, then: - If it is set to the pathname of a readable file, the page content is read as Markdown input text. - If it is not, the page content is read from this string as Markdown text. !!! note "Reading pages from a directory" If *pages* is a string that holds the path to a readable directory, then this directory is traversed, recursively, to find files that Taipy can build pages from. For every new directory that is traversed, a new hierarchical level for pages is created. For every file that is found: - If the filename extension is *.md*, it is read as Markdown content and a new page is created with the base name of this filename. - If the filename extension is *.html*, it is read as HTML content and a new page is created with the base name of this filename. For example, say you have the following directory structure: ``` reports ├── home.html ├── budget/ │ ├── expenses/ │ │ ├── marketing.md │ │ └── production.md │ └── revenue/ │ ├── EMAE.md │ ├── USA.md │ └── ASIA.md └── cashflow/ ├── weekly.md ├── monthly.md └── yearly.md ``` Calling `gui.add_pages('reports')` is equivalent to calling: ```py gui.add_pages({ "reports/home", Html("reports/home.html"), "reports/budget/expenses/marketing", Markdown("reports/budget/expenses/marketing.md"), "reports/budget/expenses/production", Markdown("reports/budget/expenses/production.md"), "reports/budget/revenue/EMAE", Markdown("reports/budget/revenue/EMAE.md"), "reports/budget/revenue/USA", Markdown("reports/budget/revenue/USA.md"), "reports/budget/revenue/ASIA", Markdown("reports/budget/revenue/ASIA.md"), "reports/cashflow/weekly", Markdown("reports/cashflow/weekly.md"), "reports/cashflow/monthly", Markdown("reports/cashflow/monthly.md"), "reports/cashflow/yearly", Markdown("reports/cashflow/yearly.md") }) ``` """ if isinstance(pages, dict): for k, v in pages.items(): if k == "/": k = Gui.__root_page_name self.add_page(name=k, page=v) elif isinstance(folder_name := pages, str): if not hasattr(self, "_root_dir"): self._root_dir = os.path.dirname(inspect.getabsfile(self.__frame)) folder_path = folder_name if os.path.isabs(folder_name) else os.path.join(self._root_dir, folder_name) folder_name = os.path.basename(folder_path) if not os.path.isdir(folder_path): # pragma: no cover raise RuntimeError(f"Path {folder_path} is not a valid directory") if folder_name in self.__directory_name_of_pages: # pragma: no cover raise Exception(f"Base directory name {folder_name} of path {folder_path} is not unique") if folder_name in Gui.__reserved_routes: # pragma: no cover raise Exception(f"Invalid directory. Directory {folder_name} is a reserved route") self.__directory_name_of_pages.append(folder_name) self.__add_pages_in_folder(folder_name, folder_path) # partials def add_partial( self, page: t.Union[str, Page], ) -> Partial: """Create a new `Partial^`. The [User Manual section on Partials](../gui/pages/index.md#partials) gives details on when and how to use this class. Arguments: page (Union[str, Page^]): The page to create a new Partial from.<br/> It can be an instance of `Markdown^` or `Html^`.<br/> If *page* is a string, then: - If *page* is set to the pathname of a readable file, the content of the new `Partial` is read as Markdown input text. - If it is not, the content of the new `Partial` is read from this string as Markdown text. Returns: The new `Partial` object defined by *page*. """ new_partial = Partial() # Validate name if ( new_partial._route in self._config.partial_routes or new_partial._route in self._config.routes ): # pragma: no cover _warn(f'Partial name "{new_partial._route}" is already defined.') if isinstance(page, str): from ._renderers import Markdown page = Markdown(page, frame=None) elif not isinstance(page, Page): # pragma: no cover raise Exception(f'Partial name "{new_partial._route}" has an invalid Page.') new_partial._renderer = page # Append partial to _config self._config.partials.append(new_partial) self._config.partial_routes.append(str(new_partial._route)) # Update locals context self.__locals_context.add(page._get_module_name(), page._get_locals()) # Update variable directory self.__var_dir.add_frame(page._frame) return new_partial def _update_partial(self, partial: Partial): partials = _getscopeattr(self, Partial._PARTIALS, {}) partials[partial._route] = partial _setscopeattr(self, Partial._PARTIALS, partials) self.__send_ws_partial(str(partial._route)) def _get_partial(self, route: str) -> t.Optional[Partial]: partials = _getscopeattr(self, Partial._PARTIALS, {}) partial = partials.get(route) if partial is None: partial = next((p for p in self._config.partials if p._route == route), None) return partial # Main binding method (bind in markdown declaration) def _bind_var(self, var_name: str) -> str: bind_context = None if var_name in self._get_locals_bind().keys(): bind_context = self._get_locals_context() if bind_context is None: encoded_var_name = self.__var_dir.add_var(var_name, self._get_locals_context(), var_name) else: encoded_var_name = self.__var_dir.add_var(var_name, bind_context) if not hasattr(self._bindings(), encoded_var_name): bind_locals = self._get_locals_bind_from_context(bind_context) if var_name in bind_locals.keys(): self._bind(encoded_var_name, bind_locals[var_name]) else: _warn( f"Variable '{var_name}' is not available in either the '{self._get_locals_context()}' or '__main__' modules." ) return encoded_var_name def _bind_var_val(self, var_name: str, value: t.Any) -> bool: if _MODULE_ID not in var_name: var_name = self.__var_dir.add_var(var_name, self._get_locals_context()) if not hasattr(self._bindings(), var_name): self._bind(var_name, value) return True return False def __bind_local_func(self, name: str): func = getattr(self, name, None) if func is not None and not callable(func): # pragma: no cover _warn(f"{self.__class__.__name__}.{name}: {func} should be a function; looking for {name} in the script.") func = None if func is None: func = self._get_locals_bind().get(name) if func is not None: if callable(func): setattr(self, name, func) else: # pragma: no cover _warn(f"{name}: {func} should be a function.") def load_config(self, config: Config) -> None: self._config._load(config) def _broadcast(self, name: str, value: t.Any): """NOT UNDOCUMENTED Send the new value of a variable to all connected clients. Arguments: name: The name of the variable to update or create. value: The value (must be serializable to the JSON format). """ self.__send_ws_broadcast(name, value) def _broadcast_all_clients(self, name: str, value: t.Any): try: self._set_broadcast() self._update_var(name, value) finally: self._set_broadcast(False) def _set_broadcast(self, broadcast: bool = True): with contextlib.suppress(RuntimeError): setattr(g, Gui.__BROADCAST_G_ID, broadcast) def _is_broadcasting(self) -> bool: try: return getattr(g, Gui.__BROADCAST_G_ID, False) except RuntimeError: return False def _download( self, content: t.Any, name: t.Optional[str] = "", on_action: t.Optional[t.Union[str, t.Callable]] = "" ): if callable(on_action) and on_action.__name__: on_action_name = ( _get_expr_var_name(str(on_action.__code__)) if on_action.__name__ == "<lambda>" else _get_expr_var_name(on_action.__name__) ) if on_action_name: self._bind_var_val(on_action_name, on_action) on_action = on_action_name else: _warn("download() on_action is invalid.") content_str = self._get_content("Gui.download", content, False) self.__send_ws_download(content_str, str(name), str(on_action)) def _notify( self, notification_type: str = "I", message: str = "", system_notification: t.Optional[bool] = None, duration: t.Optional[int] = None, ): self.__send_ws_alert( notification_type, message, self._get_config("system_notification", False) if system_notification is None else system_notification, self._get_config("notification_duration", 3000) if duration is None else duration, ) def _hold_actions( self, callback: t.Optional[t.Union[str, t.Callable]] = None, message: t.Optional[str] = "Work in Progress...", ): # pragma: no cover action_name = callback.__name__ if callable(callback) else callback # TODO: what if lambda? (it does work) func = self.__get_on_cancel_block_ui(action_name) def_action_name = func.__name__ _setscopeattr(self, def_action_name, func) if _hasscopeattr(self, Gui.__UI_BLOCK_NAME): _setscopeattr(self, Gui.__UI_BLOCK_NAME, True) else: self._bind(Gui.__UI_BLOCK_NAME, True) self.__send_ws_block(action=def_action_name, message=message, cancel=bool(action_name)) def _resume_actions(self): # pragma: no cover if _hasscopeattr(self, Gui.__UI_BLOCK_NAME): _setscopeattr(self, Gui.__UI_BLOCK_NAME, False) self.__send_ws_block(close=True) def _navigate( self, to: t.Optional[str] = "", params: t.Optional[t.Dict[str, str]] = None, tab: t.Optional[str] = None, force: t.Optional[bool] = False, ): to = to or Gui.__root_page_name if not to.startswith("/") and to not in self._config.routes and not urlparse(to).netloc: _warn(f'Cannot navigate to "{to if to != Gui.__root_page_name else "/"}": unknown page.') return False self.__send_ws_navigate(to if to != Gui.__root_page_name else "/", params, tab, force or False) return True def __init_libs(self): for name, libs in self.__extensions.items(): for lib in libs: if not isinstance(lib, ElementLibrary): continue try: self._call_function_with_state(lib.on_user_init, []) except Exception as e: # pragma: no cover if not self._call_on_exception(f"{name}.on_user_init", e): _warn(f"Exception raised in {name}.on_user_init()", e) def __init_route(self): self.__set_client_id_in_context(force=True) if not _hasscopeattr(self, Gui.__ON_INIT_NAME): _setscopeattr(self, Gui.__ON_INIT_NAME, True) self.__pre_render_pages() self.__init_libs() if hasattr(self, "on_init") and callable(self.on_init): try: self._call_function_with_state(self.on_init, []) except Exception as e: # pragma: no cover if not self._call_on_exception("on_init", e): _warn("Exception raised in on_init()", e) return self._render_route() def _call_on_exception(self, function_name: str, exception: Exception) -> bool: if hasattr(self, "on_exception") and callable(self.on_exception): try: self.on_exception(self.__get_state(), str(function_name), exception) except Exception as e: # pragma: no cover _warn("Exception raised in on_exception()", e) return True return False def __call_on_status(self) -> t.Optional[str]: if hasattr(self, "on_status") and callable(self.on_status): try: return self.on_status(self.__get_state()) except Exception as e: # pragma: no cover if not self._call_on_exception("on_status", e): _warn("Exception raised in on_status", e) return None def __pre_render_pages(self) -> None: """Pre-render all pages to have a proper initialization of all variables""" self.__set_client_id_in_context() for page in self._config.pages: if page is not None: with contextlib.suppress(Exception): page.render(self) def __render_page(self, page_name: str) -> t.Any: self.__set_client_id_in_context() nav_page = page_name if hasattr(self, "on_navigate") and callable(self.on_navigate): try: if self.on_navigate.__code__.co_argcount == 2: nav_page = self.on_navigate(self.__get_state(), page_name) else: params = request.args.to_dict() if hasattr(request, "args") else {} params.pop("client_id", None) params.pop("v", None) nav_page = self.on_navigate(self.__get_state(), page_name, params) if nav_page != page_name: if isinstance(nav_page, str): if self._navigate(nav_page): return ("Root page cannot be re-routed by on_navigate().", 302) else: _warn(f"on_navigate() returned an invalid page name '{nav_page}'.") nav_page = page_name except Exception as e: # pragma: no cover if not self._call_on_exception("on_navigate", e): _warn("Exception raised in on_navigate()", e) page = next((page_i for page_i in self._config.pages if page_i._route == nav_page), None) # Try partials if page is None: page = self._get_partial(nav_page) # Make sure that there is a page instance found if page is None: return ( jsonify({"error": f"Page '{nav_page}' doesn't exist."}), 400, {"Content-Type": "application/json; charset=utf-8"}, ) context = page.render(self) if ( nav_page == Gui.__root_page_name and page._rendered_jsx is not None and "<PageContent" not in page._rendered_jsx ): page._rendered_jsx += "<PageContent />" # Return jsx page if page._rendered_jsx is not None: return self._server._render( page._rendered_jsx, page._style if page._style is not None else "", page._head, context ) else: return ("No page template", 404) def _render_route(self) -> t.Any: return self._server._direct_render_json( { "locations": { "/" if route == Gui.__root_page_name else f"/{route}": f"/{route}" for route in self._config.routes }, "blockUI": self._is_ui_blocked(), } ) def _register_data_accessor(self, data_accessor_class: t.Type[_DataAccessor]) -> None: self._accessors._register(data_accessor_class) def get_flask_app(self) -> Flask: """Get the internal Flask application. This method must be called **after** `(Gui.)run()^` was invoked. Returns: The Flask instance used. """ if hasattr(self, "_server"): return self._server.get_flask() raise RuntimeError("get_flask_app() cannot be invoked before run() has been called.") def _set_frame(self, frame: FrameType): if not isinstance(frame, FrameType): # pragma: no cover raise RuntimeError("frame must be a FrameType where Gui can collect the local variables.") self.__frame = frame self.__default_module_name = _get_module_name_from_frame(self.__frame) def _set_css_file(self, css_file: t.Optional[str] = None): if css_file is None: script_file = pathlib.Path(self.__frame.f_code.co_filename or ".").resolve() if script_file.with_suffix(".css").exists(): css_file = f"{script_file.stem}.css" elif script_file.is_dir() and (script_file / "taipy.css").exists(): css_file = "taipy.css" self.__css_file = css_file def _set_state(self, state: State): if isinstance(state, State): self.__state = state def __get_client_config(self) -> t.Dict[str, t.Any]: config = { "timeZone": self._config.get_time_zone(), "darkMode": self._get_config("dark_mode", True), "baseURL": self._config._get_config("base_url", "/"), } if themes := self._get_themes(): config["themes"] = themes if len(self.__extensions): config["extensions"] = {} for libs in self.__extensions.values(): for lib in libs: config["extensions"][f"./{Gui._EXTENSION_ROOT}/{lib.get_js_module_name()}"] = [ # type: ignore e._get_js_name(n) for n, e in lib.get_elements().items() if isinstance(e, Element) and not e._is_server_only() ] if stylekit := self._get_config("stylekit", _default_stylekit): config["stylekit"] = {_to_camel_case(k): v for k, v in stylekit.items()} return config def __get_css_vars(self) -> str: css_vars = [] if stylekit := self._get_config("stylekit", _default_stylekit): for k, v in stylekit.items(): css_vars.append(f'--{k.replace("_", "-")}:{_get_css_var_value(v)};') return " ".join(css_vars) def __init_server(self): app_config = self._config.config # Init server if there is no server if not hasattr(self, "_server"): self._server = _Server( self, path_mapping=self._path_mapping, flask=self._flask, async_mode=app_config["async_mode"], allow_upgrades=not app_config["notebook_proxy"], server_config=app_config.get("server_config"), ) # Stop and reinitialize the server if it is still running as a thread if (_is_in_notebook() or app_config["run_in_thread"]) and hasattr(self._server, "_thread"): self.stop() self._flask_blueprint = [] self._server = _Server( self, path_mapping=self._path_mapping, flask=self._flask, async_mode=app_config["async_mode"], allow_upgrades=not app_config["notebook_proxy"], server_config=app_config.get("server_config"), ) self._bindings()._new_scopes() def __init_ngrok(self): app_config = self._config.config if app_config["run_server"] and app_config["ngrok_token"]: # pragma: no cover if not util.find_spec("pyngrok"): raise RuntimeError("Cannot use ngrok as pyngrok package is not installed.") ngrok.set_auth_token(app_config["ngrok_token"]) http_tunnel = ngrok.connect(app_config["port"], "http") _TaipyLogger._get_logger().info(f" * NGROK Public Url: {http_tunnel.public_url}") def __bind_default_function(self): with self.get_flask_app().app_context(): self.__var_dir.process_imported_var() # bind on_* function if available self.__bind_local_func("on_init") self.__bind_local_func("on_change") self.__bind_local_func("on_action") self.__bind_local_func("on_navigate") self.__bind_local_func("on_exception") self.__bind_local_func("on_status") self.__bind_local_func("on_user_content") def __register_blueprint(self): # add en empty main page if it is not defined if Gui.__root_page_name not in self._config.routes: new_page = _Page() new_page._route = Gui.__root_page_name new_page._renderer = _EmptyPage() self._config.pages.append(new_page) self._config.routes.append(Gui.__root_page_name) pages_bp = Blueprint("taipy_pages", __name__) self._flask_blueprint.append(pages_bp) # server URL Rule for taipy images images_bp = Blueprint("taipy_images", __name__) images_bp.add_url_rule(f"/{Gui.__CONTENT_ROOT}/<path:path>", view_func=self.__serve_content) self._flask_blueprint.append(images_bp) # server URL for uploaded files upload_bp = Blueprint("taipy_upload", __name__) upload_bp.add_url_rule(f"/{Gui.__UPLOAD_URL}", view_func=self.__upload_files, methods=["POST"]) self._flask_blueprint.append(upload_bp) # server URL for user content user_content_bp = Blueprint("taipy_user_content", __name__) user_content_bp.add_url_rule(f"/{Gui.__USER_CONTENT_URL}/<path:path>", view_func=self.__serve_user_content) self._flask_blueprint.append(user_content_bp) # server URL for extension resources extension_bp = Blueprint("taipy_extensions", __name__) extension_bp.add_url_rule(f"/{Gui._EXTENSION_ROOT}/<path:path>", view_func=self.__serve_extension) scripts = [ s if bool(urlparse(s).netloc) else f"/{Gui._EXTENSION_ROOT}/{name}/{s}{lib.get_query(s)}" for name, libs in Gui.__extensions.items() for lib in libs for s in (lib.get_scripts() or []) ] styles = [ s if bool(urlparse(s).netloc) else f"/{Gui._EXTENSION_ROOT}/{name}/{s}{lib.get_query(s)}" for name, libs in Gui.__extensions.items() for lib in libs for s in (lib.get_styles() or []) ] if self._get_config("stylekit", True): styles.append("stylekit/stylekit.css") else: styles.append("https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap") if self.__css_file: styles.append(f"/{self.__css_file}") self._flask_blueprint.append(extension_bp) _conf_webapp_path = ( pathlib.Path(self._get_config("webapp_path", None)) if self._get_config("webapp_path", None) else None ) _webapp_path = str((pathlib.Path(__file__).parent / "webapp").resolve()) if _conf_webapp_path: if _conf_webapp_path.is_dir(): _webapp_path = str(_conf_webapp_path.resolve()) _warn(f"Using webapp_path: '{_conf_webapp_path}'.") else: # pragma: no cover _warn( f"webapp_path: '{_conf_webapp_path}' is not a valid directory path. Falling back to '{_webapp_path}'." ) self._flask_blueprint.append( self._server._get_default_blueprint( static_folder=_webapp_path, template_folder=_webapp_path, title=self._get_config("title", "Taipy App"), favicon=self._get_config("favicon", "favicon.png"), root_margin=self._get_config("margin", None), scripts=scripts, styles=styles, version=self.__get_version(), client_config=self.__get_client_config(), watermark=self._get_config("watermark", None), css_vars=self.__get_css_vars(), base_url=self._get_config("base_url", "/"), ) ) # Run parse markdown to force variables binding at runtime pages_bp.add_url_rule(f"/{Gui.__JSX_URL}/<path:page_name>", view_func=self.__render_page) # server URL Rule for flask rendered react-router pages_bp.add_url_rule(f"/{Gui.__INIT_URL}", view_func=self.__init_route) # Register Flask Blueprint if available for bp in self._flask_blueprint: self._server.get_flask().register_blueprint(bp) def run( self, run_server: bool = True, run_in_thread: bool = False, async_mode: str = "gevent", **kwargs, ) -> t.Optional[Flask]: """ Start the server that delivers pages to web clients. Once you enter `run()`, users can run web browsers and point to the web server URL that `Gui` serves. The default is to listen to the *localhost* address (127.0.0.1) on the port number 5000. However, the configuration of this `Gui` object may impact that (see the [Configuration](../gui/configuration.md#configuring-the-gui-instance) section of the User Manual for details). Arguments: run_server (bool): Whether or not to run a web server locally. If set to *False*, a web server is *not* created and started. run_in_thread (bool): Whether or not to run a web server in a separated thread. If set to *True*, the web server runs is a separated thread.<br/> Note that if you are running in an IPython notebook context, the web server always runs in a separate thread. async_mode (str): The asynchronous model to use for the Flask-SocketIO. Valid values are:<br/> - "gevent": Use a [gevent](https://www.gevent.org/servers.html) server. - "threading": Use the Flask Development Server. This allows the application to use the Flask reloader (the *use_reloader* option) and Debug mode (the *debug* option). - "eventlet": Use an [*eventlet*](https://flask.palletsprojects.com/en/2.2.x/deploying/eventlet/) event-driven WSGI server. The default value is "gevent"<br/> Note that only the "threading" value provides support for the development reloader functionality (*use_reloader* option). Any other value makes the *use_reloader* configuration parameter ignored.<br/> Also note that setting the *debug* argument to True forces *async_mode* to "threading". **kwargs (dict[str, any]): Additional keyword arguments that configure how this `Gui` is run. Please refer to the [Configuration section](../gui/configuration.md#configuring-the-gui-instance) of the User Manual for more information. Returns: The Flask instance if *run_server* is False else None. """ # -------------------------------------------------------------------------------- # The ssl_context argument was removed just after 1.1. It was defined as: # t.Optional[t.Union[ssl.SSLContext, t.Tuple[str, t.Optional[str]], t.Literal["adhoc"]]] = None # # With the doc: # ssl_context (Optional[Union[ssl.SSLContext, Tuple[str, Optional[str]], te.Literal['adhoc']]]): # Configures TLS to serve over HTTPS. This value can be: # # - An `ssl.SSLContext` object # - A `(cert_file, key_file)` tuple to create a typical context # - The string "adhoc" to generate a temporary self-signed certificate. # # The default value is None. # -------------------------------------------------------------------------------- app_config = self._config.config run_root_dir = os.path.dirname(inspect.getabsfile(self.__frame)) # Register _root_dir for abs path if not hasattr(self, "_root_dir"): self._root_dir = run_root_dir is_reloading = kwargs.pop("_reload", False) if not is_reloading: self.__run_kwargs = kwargs = { **kwargs, "run_server": run_server, "run_in_thread": run_in_thread, "async_mode": async_mode, } # Load application config from multiple sources (env files, kwargs, command line) self._config._build_config(run_root_dir, self.__env_filename, kwargs) self._config.resolve() TaipyGuiWarning.set_debug_mode(self._get_config("debug", False)) self.__init_server() self.__init_ngrok() locals_bind = _filter_locals(self.__frame.f_locals) self.__locals_context.set_default(locals_bind, self.__default_module_name) self.__var_dir.set_default(self.__frame) if self.__state is None or is_reloading: self.__state = State(self, self.__locals_context.get_all_keys(), self.__locals_context.get_all_context()) if _is_in_notebook(): # Allow gui.state.x in notebook mode self.state = self.__state self.__bind_default_function() # Base global ctx is TaipyHolder classes + script modules and callables glob_ctx: t.Dict[str, t.Any] = {t.__name__: t for t in _TaipyBase.__subclasses__()} glob_ctx.update({k: v for k, v in locals_bind.items() if inspect.ismodule(v) or callable(v)}) glob_ctx[Gui.__SELF_VAR] = self # Call on_init on each library for name, libs in self.__extensions.items(): for lib in libs: if not isinstance(lib, ElementLibrary): continue try: lib_context = lib.on_init(self) if ( isinstance(lib_context, tuple) and len(lib_context) > 1 and isinstance(lib_context[0], str) and lib_context[0].isidentifier() ): if lib_context[0] in glob_ctx: _warn(f"Method {name}.on_init() returned a name already defined '{lib_context[0]}'.") else: glob_ctx[lib_context[0]] = lib_context[1] elif lib_context: _warn( f"Method {name}.on_init() should return a Tuple[str, Any] where the first element must be a valid Python identifier." ) except Exception as e: # pragma: no cover if not self._call_on_exception(f"{name}.on_init", e): _warn(f"Method {name}.on_init() raised an exception", e) # Initiate the Evaluator with the right context self.__evaluator = _Evaluator(glob_ctx, self.__shared_variables) self.__register_blueprint() # Register data accessor communication data format (JSON, Apache Arrow) self._accessors._set_data_format(_DataFormat.APACHE_ARROW if app_config["use_arrow"] else _DataFormat.JSON) # Use multi user or not self._bindings()._set_single_client(bool(app_config["single_client"])) # Start Flask Server if not run_server: return self.get_flask_app() return self._server.run( host=app_config["host"], port=app_config["port"], debug=app_config["debug"], use_reloader=app_config["use_reloader"], flask_log=app_config["flask_log"], run_in_thread=app_config["run_in_thread"], allow_unsafe_werkzeug=app_config["allow_unsafe_werkzeug"], notebook_proxy=app_config["notebook_proxy"], ) def reload(self): # pragma: no cover """ Reload the web server. This function reloads the underlying web server only in the situation where it was run in a separated thread: the *run_in_thread* parameter to the `(Gui.)run^` method was set to True, or you are running in an IPython notebook context. """ if hasattr(self, "_server") and hasattr(self._server, "_thread") and self._server._is_running: self._server.stop_thread() self.run(**self.__run_kwargs, _reload=True) _TaipyLogger._get_logger().info("Gui server has been reloaded.") def stop(self): """ Stop the web server. This function stops the underlying web server only in the situation where it was run in a separated thread: the *run_in_thread* parameter to the `(Gui.)run()^` method was set to True, or you are running in an IPython notebook context. """ if hasattr(self, "_server") and hasattr(self._server, "_thread") and self._server._is_running: self._server.stop_thread() _TaipyLogger._get_logger().info("Gui server has been stopped.")
import inspect import typing as t from contextlib import nullcontext from operator import attrgetter from types import FrameType from flask import has_app_context from flask.ctx import AppContext from .utils import _get_module_name_from_frame, _is_in_notebook from .utils._attributes import _attrsetter if t.TYPE_CHECKING: from .gui import Gui class State: """Accessor to the bound variables from callbacks. `State` is used when you need to access the value of variables bound to visual elements (see [Binding](../gui/binding.md)).<br/> Because each browser connected to the application server may represent and modify any variable at any moment as the result of user interaction, each connection holds its own set of variables along with their values. We call the set of these the application variables the application _state_, as seen by a given client. Each callback (see [Callbacks](../gui/callbacks.md)) receives a specific instance of the `State` class, where you can find all the variables bound to visual elements in your application. Note that `State` also is a Python Context Manager: In situations where you have several variables to update, it is more clear and more efficient to assign the variable values in a `with` construct: ```py def my_callback(state, ...): ... with state as s: s.var1 = value1 s.var2 = value2 ... ``` You cannot set a variable in the context of a lambda function because Python prevents any use of the assignment operator.<br/> You can, however, use the `assign()` method on the state that the lambda function receives, so you can work around this limitation: Here is how you could define a button that changes the value of a variable directly in a page expressed using Markdown: ``` <|Set variable|button|on_action={lambda s: s.assign("var_name", new_value)}|> ``` This would be strictly similar to the Markdown line: ``` <|Set variable|button|on_action=change_variable|> ``` with the Python code: ```py def change_variable(state): state.var_name = new_value ``` """ __gui_attr = "_gui" __attrs = ( __gui_attr, "_user_var_list", "_context_list", ) __methods = ( "assign", "broadcast", "get_gui", "refresh", "_set_context", "_notebook_context", "_get_placeholder", "_set_placeholder", "_get_gui_attr", "_get_placeholder_attrs", "_add_attribute", ) __placeholder_attrs = ( "_taipy_p1", "_current_context", ) __excluded_attrs = __attrs + __methods + __placeholder_attrs def __init__(self, gui: "Gui", var_list: t.Iterable[str], context_list: t.Iterable[str]) -> None: super().__setattr__(State.__attrs[1], list(State.__filter_var_list(var_list, State.__excluded_attrs))) super().__setattr__(State.__attrs[2], list(context_list)) super().__setattr__(State.__attrs[0], gui) def get_gui(self) -> "Gui": """Return the Gui instance for this state object. Returns: Gui: The Gui instance for this state object. """ return super().__getattribute__(State.__gui_attr) @staticmethod def __filter_var_list(var_list: t.Iterable[str], excluded_attrs: t.Iterable[str]) -> t.Iterable[str]: return filter(lambda n: n not in excluded_attrs, var_list) def __getattribute__(self, name: str) -> t.Any: if name in State.__methods: return super().__getattribute__(name) gui: "Gui" = self.get_gui() if name == State.__gui_attr: return gui if name in State.__excluded_attrs: raise AttributeError(f"Variable '{name}' is protected and is not accessible.") if gui._is_in_brdcst_callback() and ( name not in gui._get_shared_variables() and not gui._bindings()._is_single_client() ): raise AttributeError(f"Variable '{name}' is not available to be accessed in shared callback.") if name not in super().__getattribute__(State.__attrs[1]): raise AttributeError(f"Variable '{name}' is not defined.") with self._notebook_context(gui), self._set_context(gui): encoded_name = gui._bind_var(name) return getattr(gui._bindings(), encoded_name) def __setattr__(self, name: str, value: t.Any) -> None: gui: "Gui" = super().__getattribute__(State.__gui_attr) if gui._is_in_brdcst_callback() and ( name not in gui._get_shared_variables() and not gui._bindings()._is_single_client() ): raise AttributeError(f"Variable '{name}' is not available to be accessed in shared callback.") if name not in super().__getattribute__(State.__attrs[1]): raise AttributeError(f"Variable '{name}' is not accessible.") with self._notebook_context(gui), self._set_context(gui): encoded_name = gui._bind_var(name) setattr(gui._bindings(), encoded_name, value) def __getitem__(self, key: str): context = key if key in super().__getattribute__(State.__attrs[2]) else None if context is None: gui: "Gui" = super().__getattribute__(State.__gui_attr) page_ctx = gui._get_page_context(key) context = page_ctx if page_ctx is not None else None if context is None: raise RuntimeError(f"Can't resolve context '{key}' from state object") self._set_placeholder(State.__placeholder_attrs[1], context) return self def _set_context(self, gui: "Gui") -> t.ContextManager[None]: if (pl_ctx := self._get_placeholder(State.__placeholder_attrs[1])) is not None: self._set_placeholder(State.__placeholder_attrs[1], None) if pl_ctx != gui._get_locals_context(): return gui._set_locals_context(pl_ctx) if len(inspect.stack()) > 1: ctx = _get_module_name_from_frame(t.cast(FrameType, t.cast(FrameType, inspect.stack()[2].frame))) current_context = gui._get_locals_context() # ignore context if the current one starts with the new one (to resolve for class modules) if ctx != current_context and not current_context.startswith(str(ctx)): return gui._set_locals_context(ctx) return nullcontext() def _notebook_context(self, gui: "Gui"): return gui.get_flask_app().app_context() if not has_app_context() and _is_in_notebook() else nullcontext() def _get_placeholder(self, name: str): if name in State.__placeholder_attrs: try: return super().__getattribute__(name) except AttributeError: return None return None def _set_placeholder(self, name: str, value: t.Any): if name in State.__placeholder_attrs: super().__setattr__(name, value) def _get_placeholder_attrs(self): return State.__placeholder_attrs def _add_attribute(self, name: str, default_value: t.Optional[t.Any] = None) -> bool: attrs: t.List[str] = super().__getattribute__(State.__attrs[1]) if name not in attrs: attrs.append(name) gui = super().__getattribute__(State.__gui_attr) return gui._bind_var_val(name, default_value) return False def assign(self, name: str, value: t.Any) -> t.Any: """Assign a value to a state variable. This should be used only from within a lambda function used as a callback in a visual element. Arguments: name (str): The variable name to assign to. value (Any): The new variable value. Returns: Any: The previous value of the variable. """ val = attrgetter(name)(self) _attrsetter(self, name, value) return val def refresh(self, name: str): """Refresh a state variable. This allows to re-sync the user interface with a variable value. Arguments: name (str): The variable name to refresh. """ val = attrgetter(name)(self) _attrsetter(self, name, val) def broadcast(self, name: str, value: t.Any): """Update a variable on all clients. All connected clients will receive an update of the variable called *name* with the provided value, even if it is not shared. Arguments: name (str): The variable name to update. value (Any): The new variable value. """ gui: "Gui" = super().__getattribute__(State.__gui_attr) with self._set_context(gui): encoded_name = gui._bind_var(name) gui._broadcast_all_clients(encoded_name, value) def __enter__(self): super().__getattribute__(State.__attrs[0]).__enter__() return self def __exit__(self, exc_type, exc_value, traceback): return super().__getattribute__(State.__attrs[0]).__exit__(exc_type, exc_value, traceback)
import re import sys import typing as t import xml.etree.ElementTree as etree from abc import ABC, abstractmethod from inspect import isclass from pathlib import Path from urllib.parse import urlencode from .._renderers.builder import _Builder from .._warnings import _warn from ..types import PropertyType from ..utils import _get_broadcast_var_name, _TaipyBase, _to_camel_case if t.TYPE_CHECKING: from ..gui import Gui from ..state import State class ElementProperty: """ The declaration of a property of a visual element. Each visual element property is described by an instance of `ElementProperty`. This class holds the information on the name, type and default value for the element property. """ def __init__( self, property_type: PropertyType, default_value: t.Optional[t.Any] = None, js_name: t.Optional[str] = None, ) -> None: """Initializes a new custom property declaration for an `Element^`. Arguments: property_type (PropertyType): The type of this property. default_value (Optional[Any]): The default value for this property. Default is None. js_name (Optional[str]): The name of this property, in the front-end JavaScript code.<br/> If unspecified, a camel case version of `name` is generated: for example, if `name` is "my_property_name", then this property is referred to as "myPropertyName" in the JavaScript code. """ self.default_value = default_value if property_type == PropertyType.broadcast: if isinstance(default_value, str): self.default_value = _get_broadcast_var_name(default_value) else: _warn("Element property with type 'broadcast' must define a string default value.") self.property_type = PropertyType.react else: self.property_type = property_type self._js_name = js_name super().__init__() def check(self, element_name: str, prop_name: str): if not isinstance(prop_name, str) or not prop_name or not prop_name.isidentifier(): _warn(f"Property name '{prop_name}' is invalid for element '{element_name}'.") if not isinstance(self.property_type, PropertyType) and not ( isclass(self.property_type) and issubclass(self.property_type, _TaipyBase) ): _warn(f"Property type '{self.property_type}' is invalid for element property '{element_name}.{prop_name}'.") def _get_tuple(self, name: str) -> tuple: return (name, self.property_type, self.default_value) def get_js_name(self, name: str) -> str: return self._js_name or _to_camel_case(name) class Element: """ The definition of a custom visual element. An element is defined by its properties (name, type and default value) and what the default property name is. """ __RE_PROP_VAR = re.compile(r"<tp:prop:(\w+)>") def __init__( self, default_property: str, properties: t.Dict[str, ElementProperty], react_component: t.Optional[str] = None, render_xhtml: t.Optional[t.Callable[[t.Dict[str, t.Any]], str]] = None, inner_properties: t.Optional[t.Dict[str, ElementProperty]] = None, ) -> None: """Initializes a new custom element declaration. If *render_xhtml* is specified, then this is a static element, and *react_component* is ignored. Arguments: default_property (str): the name of the default property for this element. properties (List[ElementProperty]): The list of properties for this element. inner_properties (Optional[List[ElementProperty]]): The optional list of inner properties for this element.<br/> Default values are set/binded automatically. react_component (Optional[str]): The name of the component to be created on the front-end.<br/> If not specified, it is set to a camel case version of the element's name ("one_name" is transformed to "OneName"). render_xhtml (Optional[callable[[dict[str, Any]], str]]): A function that receives a dictionary containing the element's properties and their values and that must return a valid XHTML string. """ self.default_attribute = default_property self.attributes = properties self.inner_properties = inner_properties self.js_name = react_component if callable(render_xhtml): self._render_xhtml = render_xhtml super().__init__() def _get_js_name(self, name: str) -> str: return self.js_name or _to_camel_case(name, True) def check(self, name: str): if not isinstance(name, str) or not name or not name.isidentifier(): _warn(f"Invalid element name: '{name}'.") default_found = False if self.attributes: for prop_name, property in self.attributes.items(): if isinstance(property, ElementProperty): property.check(name, prop_name) if not default_found: default_found = self.default_attribute == prop_name else: _warn(f"Property must inherit from 'ElementProperty' '{name}.{prop_name}'.") if not default_found: _warn(f"Element {name} has no default property.") def _is_server_only(self): return hasattr(self, "_render_xhtml") and callable(self._render_xhtml) def _call_builder( self, name, gui: "Gui", properties: t.Optional[t.Dict[str, t.Any]], lib: "ElementLibrary", is_html: t.Optional[bool] = False, ) -> t.Union[t.Any, t.Tuple[str, str]]: attributes = properties if isinstance(properties, dict) else {} if self.inner_properties: self.attributes.update(self.inner_properties) for prop, attr in self.inner_properties.items(): val = attr.default_value if val: # handling property replacement in inner properties <tp:prop:...> while m := Element.__RE_PROP_VAR.search(val): var = attributes.get(m.group(1)) hash_value = "None" if var is None else gui._evaluate_expr(var) val = val[: m.start()] + hash_value + val[m.end() :] attributes[prop] = val # this modifies attributes hash_names = _Builder._get_variable_hash_names(gui, attributes) # variable replacement # call user render if any if self._is_server_only(): xhtml = self._render_xhtml(attributes) try: xml_root = etree.fromstring(xhtml) if is_html: return xhtml, name else: return xml_root except Exception as e: _warn(f"{name}.render_xhtml() did not return a valid XHTML string", e) return f"{name}.render_xhtml() did not return a valid XHTML string. {e}" else: default_attr: t.Optional[ElementProperty] = None default_value = None default_name = None attrs = [] if self.attributes: for prop_name, property in self.attributes.items(): if isinstance(property, ElementProperty): if self.default_attribute == prop_name: default_name = prop_name default_attr = property default_value = property.default_value else: attrs.append(property._get_tuple(prop_name)) elt_built = _Builder( gui=gui, control_type=name, element_name=f"{lib.get_js_module_name()}_{self._get_js_name(name)}", attributes=properties, hash_names=hash_names, lib_name=lib.get_name(), default_value=default_value, ) if default_attr is not None: elt_built.set_value_and_default( var_name=default_name, var_type=default_attr.property_type, default_val=default_attr.default_value, with_default=default_attr.property_type != PropertyType.data, ) elt_built.set_attributes(attrs) return elt_built._build_to_string() if is_html else elt_built.el class ElementLibrary(ABC): """ A library of user-defined visual elements. An element library can declare any number of custom visual elements. In order to use those elements you must register the element library using the function `Gui.add_library()^`. An element library can mix *static* and *dynamic* elements. """ @abstractmethod def get_elements(self) -> t.Dict[str, Element]: """ Return the dictionary holding all visual element declarations. The key for each of this dictionary's entry is the name of the element, and the value is an instance of `Element^`. The default implementation returns an empty dictionary, indicating that this library contains no custom visual elements. """ return {} @abstractmethod def get_name(self) -> str: """ Return the library name. This string is used for different purposes: - It allows for finding the definition of visual elements when parsing the page content.<br/> Custom elements are defined with the fragment `<|<library_name>.<element_name>|>` in Markdown pages, and with the tag `<<library_name>:<element_name>>` in HTML pages. - In element libraries that hold elements with dynamic properties (where JavaScript) is involved, the name of the JavaScript module that has the front-end code is derived from this name, as described in `(ElementLibrary.)get_js_module_name()^`. Returns: The name of this element library. This must be a valid Python identifier. !!! note "Element libraries with the same name" You can add different libraries that have the same name.<br/> This is useful in large projects where you want to split a potentially large number of custom visual elements into different groups but still access them from your pages using the same library name prefix.<br/> In this situation, you will have to implement `(ElementLibrary.)get_js_module_name()^` because each JavaScript module will have to have a unique name. """ return NotImplementedError # type: ignore def get_js_module_name(self) -> str: """ Return the name of the JavaScript module. The JavaScript module is the JavaScript file that contains all the front-end code for this element library. Typically, the name of JavaScript modules uses camel case.<br/> This module name must be unique on the browser window scope: if your application uses several custom element libraries, they must define a unique name for their JavaScript module. The default implementation transforms the return value of `(ElementLibrary.)get_name()^` in the following manner: - The JavaScript module name is a camel case version of the element library name (see `(ElementLibrary.)get_name()^`): - If the library name is "library", the JavaScript module name defaults to "Library". - If the library name is "myLibrary", the JavaScript module name defaults to "Mylibrary". - If the element library name has underscore characters, each underscore-separated fragment is considered as a distinct word: - If the library name is "my_library", the JavaScript module name defaults to "MyLibrary". Returns: The name of the JavaScript module for this element library.<br/> The default implementation returns a camel case version of `self.get_name()`, as described above. """ return _to_camel_case(self.get_name(), True) def get_scripts(self) -> t.List[str]: """ Return the list of the mandatory script file pathnames. If a script file pathname is an absolute URL it will be used as is.<br/> If it's not it will be passed to `(ElementLibrary.)get_resource()^` to retrieve a local path to the resource. The default implementation returns an empty list, indicating that this library contains no custom visual elements with dynamic properties. Returns: A list of paths (relative to the element library Python implementation file or absolute) to all JavaScript module files to be loaded on the front-end.<br/> The default implementation returns an empty list. """ return [] def get_styles(self) -> t.List[str]: """ TODO Returns the list of resources names for the css stylesheets. Defaults to [] """ return [] def get_resource(self, name: str) -> Path: """ TODO Defaults to return None? Returns a path for a resource name. Resource URL should be formed as /taipy-extension/<library_name>/<resource virtual path> with(see get_resource_url) - <resource virtual path> being the `name` parameter - <library_name> the value returned by `get_name()` Arguments: name (str): The name of the resource for which a local Path should be returned. """ module_obj = sys.modules.get(self.__class__.__module__) base = (Path(".") if module_obj is None else Path(module_obj.__file__).parent).resolve() # type: ignore base = base if base.exists() else Path(".").resolve() file = (base / name).resolve() if str(file).startswith(str(base)) and file.exists(): return file else: raise FileNotFoundError(f"Cannot access resource {file}.") def get_resource_url(self, resource: str) -> str: """TODO""" from ..gui import Gui return f"/{Gui._EXTENSION_ROOT}/{self.get_name()}/{resource}{self.get_query(resource)}" def get_data(self, library_name: str, payload: t.Dict, var_name: str, value: t.Any) -> t.Optional[t.Dict]: """ TODO Called if implemented (i.e returns a dict). Arguments: library_name (str): The name of this library. payload (dict): The payload send by the `createRequestDataUpdateAction()` front-end function. var_name (str): The name of the variable holding the data. value (any): The current value of the variable identified by *var_name*. """ return None def on_init(self, gui: "Gui") -> t.Optional[t.Tuple[str, t.Any]]: """ Initialize this element library. This method is invoked by `Gui.run()^`. It allows to define variables that are accessible from elements defined in this element library. Arguments gui: The `Gui^` instance. Returns: An optional tuple composed of a variable name (that *must* be a valid Python identifier), associated with its value.<br/> This name can be used as the name of a variable accessible by the elements defined in this library.<br/> This name must be unique across the entire application, which is a problem since different element libraries might use the same symbol. A good development practice is to make this variable name unique by prefixing it with the name of the element library itself. """ return None def on_user_init(self, state: "State"): """ Initialize user state on first access. Arguments state: The `State^` instance. """ pass def get_query(self, name: str) -> str: """ Return an URL query depending on the resource name.<br/> Default implementation returns the version if defined. Arguments: name (str): The name of the resource for which a query should be returned. Returns: A string that holds the query part of an URL (starting with ?). """ if version := self.get_version(): return f"?{urlencode({'v': version})}" return "" def get_version(self) -> t.Optional[str]: """ The optional library version Returns: An optional string representing the library version.<br/> This version will be appended to the resource URL as a query arg (?v=<version>) """ return None
from ..types import PropertyType from .library import Element, ElementLibrary, ElementProperty
from __future__ import annotations import typing as t class _MapDict(object): """ Provide class binding, can utilize getattr, setattr functionality Also perform update operation """ __local_vars = ("_dict", "_update_var") def __init__(self, dict_import: dict, app_update_var=None): self._dict = dict_import # Bind app update var function self._update_var = app_update_var def __len__(self): return self._dict.__len__() def __length_hint__(self): return self._dict.__length_hint__() def __getitem__(self, key): value = self._dict.__getitem__(key) if isinstance(value, dict): if self._update_var: return _MapDict(value, lambda s, v: self._update_var(f"{key}.{s}", v)) else: return _MapDict(value) return value def __setitem__(self, key, value): if self._update_var: self._update_var(key, value) else: self._dict.__setitem__(key, value) def __delitem__(self, key): self._dict.__delitem__(key) def __missing__(self, key): return self._dict.__missing__(key) def __iter__(self): return self._dict.__iter__() def __reversed__(self): return self._dict.__reversed__() def __contains__(self, item): return self._dict.__contains__(item) # to be able to use getattr def __getattr__(self, attr): value = self._dict.__getitem__(attr) if isinstance(value, dict): if self._update_var: return _MapDict(value, lambda s, v: self._update_var(f"{attr}.{s}", v)) else: return _MapDict(value) return value def __setattr__(self, attr, value): if attr in _MapDict.__local_vars: super().__setattr__(attr, value) else: self.__setitem__(attr, value) def keys(self): return self._dict.keys() def values(self): return self._dict.values() def items(self): return self._dict.items() def get(self, key: t.Any, default_value: t.Optional[str] = None) -> t.Optional[t.Any]: return self._dict.get(key, default_value) def clear(self) -> None: self._dict.clear() def setdefault(self, key, value=None) -> t.Optional[t.Any]: return self._dict.setdefault(key, value) def pop(self, key, default=None) -> t.Any: return self._dict.pop(key, default) def popitem(self) -> tuple: return self._dict.popitem() def copy(self) -> _MapDict: return _MapDict(self._dict.copy(), self._update_var) def update(self, d: dict) -> None: current_keys = self.keys() for k, v in d.items(): if k not in current_keys or self[k] != v: self.__setitem__(k, v)
import re import typing as t from enum import Enum from .._renderers.utils import _get_columns_dict from .._warnings import _warn from ..types import PropertyType from ..utils import _MapDict if t.TYPE_CHECKING: from ..gui import Gui class _Chart_iprops(Enum): x = 0 y = 1 z = 2 label = 3 text = 4 mode = 5 type = 6 color = 7 xaxis = 8 yaxis = 9 selected_color = 10 marker = 11 selected_marker = 12 orientation = 13 _name = 14 line = 15 text_anchor = 16 options = 17 lon = 18 lat = 19 base = 20 r = 21 theta = 22 close = 23 open = 24 high = 25 low = 26 locations = 27 values = 28 labels = 29 decimator = 30 measure = 31 parents = 32 __CHART_AXIS: t.Dict[str, t.Tuple[_Chart_iprops, ...]] = { "bar": (_Chart_iprops.x, _Chart_iprops.y, _Chart_iprops.base), "candlestick": ( _Chart_iprops.x, _Chart_iprops.close, _Chart_iprops.open, _Chart_iprops.high, _Chart_iprops.low, ), "choropleth": (_Chart_iprops.locations, _Chart_iprops.z), "densitymapbox": (_Chart_iprops.lon, _Chart_iprops.lat, _Chart_iprops.z), "funnelarea": (_Chart_iprops.values,), "pie": (_Chart_iprops.values, _Chart_iprops.labels), "scattergeo": (_Chart_iprops.lon, _Chart_iprops.lat), "scattermapbox": (_Chart_iprops.lon, _Chart_iprops.lat), "scatterpolar": (_Chart_iprops.r, _Chart_iprops.theta), "scatterpolargl": (_Chart_iprops.r, _Chart_iprops.theta), "treemap": (_Chart_iprops.labels, _Chart_iprops.parents, _Chart_iprops.values), "waterfall": (_Chart_iprops.x, _Chart_iprops.y, _Chart_iprops.measure), } __CHART_DEFAULT_AXIS: t.Tuple[_Chart_iprops, ...] = (_Chart_iprops.x, _Chart_iprops.y, _Chart_iprops.z) __CHART_MARKER_TO_COLS: t.Tuple[str, ...] = ("color", "size", "symbol", "opacity") __CHART_NO_INDEX: t.Tuple[str, ...] = ("pie", "histogram", "heatmap", "funnelarea") _CHART_NAMES: t.Tuple[str, ...] = tuple(e.name[1:] if e.name[0] == "_" else e.name for e in _Chart_iprops) def __check_dict(values: t.List[t.Any], properties: t.Iterable[_Chart_iprops]) -> None: for prop in properties: if values[prop.value] is not None and not isinstance(values[prop.value], (dict, _MapDict)): _warn(f"Property {prop.name} of chart control should be a dict.") values[prop.value] = None def __get_multiple_indexed_attributes( attributes: t.Dict[str, t.Any], names: t.Iterable[str], index: t.Optional[int] = None ) -> t.List[t.Optional[str]]: names = names if index is None else [f"{n}[{index}]" for n in names] # type: ignore return [attributes.get(name) for name in names] __RE_INDEXED_DATA = re.compile(r"^(\d+)\/(.*)") def __get_col_from_indexed(col_name: str, idx: int) -> t.Optional[str]: if re_res := __RE_INDEXED_DATA.search(col_name): return col_name if str(idx) == re_res.group(1) else None return col_name def _build_chart_config(gui: "Gui", attributes: t.Dict[str, t.Any], col_types: t.Dict[str, str]): # noqa: C901 default_type = attributes.get("_default_type", "scatter") default_mode = attributes.get("_default_mode", "lines+markers") trace = __get_multiple_indexed_attributes(attributes, _CHART_NAMES) if not trace[_Chart_iprops.mode.value]: trace[_Chart_iprops.mode.value] = default_mode # type if not trace[_Chart_iprops.type.value]: trace[_Chart_iprops.type.value] = default_type if not trace[_Chart_iprops.xaxis.value]: trace[_Chart_iprops.xaxis.value] = "x" if not trace[_Chart_iprops.yaxis.value]: trace[_Chart_iprops.yaxis.value] = "y" # Indexed properties: Check for arrays for prop in _Chart_iprops: values = trace[prop.value] if isinstance(values, (list, tuple)) and len(values): prop_name = prop.name[1:] if prop.name[0] == "_" else prop.name for idx, val in enumerate(values): if idx == 0: trace[prop.value] = val if val is not None: indexed_prop = f"{prop_name}[{idx + 1}]" if attributes.get(indexed_prop) is None: attributes[indexed_prop] = val # marker selected_marker options __check_dict(trace, (_Chart_iprops.marker, _Chart_iprops.selected_marker, _Chart_iprops.options)) axis = [] traces: t.List[t.List[t.Optional[str]]] = [] idx = 1 indexed_trace = __get_multiple_indexed_attributes(attributes, _CHART_NAMES, idx) if len([x for x in indexed_trace if x]): while len([x for x in indexed_trace if x]): axis.append( __CHART_AXIS.get( indexed_trace[_Chart_iprops.type.value] or trace[_Chart_iprops.type.value] or "", __CHART_DEFAULT_AXIS, ) ) # marker selected_marker options __check_dict(indexed_trace, (_Chart_iprops.marker, _Chart_iprops.selected_marker, _Chart_iprops.options)) if trace[_Chart_iprops.decimator.value] and not indexed_trace[_Chart_iprops.decimator.value]: # copy the decimator only once indexed_trace[_Chart_iprops.decimator.value] = trace[_Chart_iprops.decimator.value] trace[_Chart_iprops.decimator.value] = None traces.append([x or trace[i] for i, x in enumerate(indexed_trace)]) idx += 1 indexed_trace = __get_multiple_indexed_attributes(attributes, _CHART_NAMES, idx) else: traces.append(trace) # axis names axis.append(__CHART_AXIS.get(trace[_Chart_iprops.type.value] or "", __CHART_DEFAULT_AXIS)) # list of data columns name indexes with label text dt_idx = tuple(e.value for e in (axis[0] + (_Chart_iprops.label, _Chart_iprops.text))) # configure columns columns: t.Set[str] = set() for j, trace in enumerate(traces): dt_idx = tuple( e.value for e in (axis[j] if j < len(axis) else axis[0]) + (_Chart_iprops.label, _Chart_iprops.text) ) columns.update([trace[i] or "" for i in dt_idx if trace[i]]) # add optionnal column if any markers = [ t[_Chart_iprops.marker.value] or ({"color": t[_Chart_iprops.color.value]} if t[_Chart_iprops.color.value] else None) for t in traces ] opt_cols = set() for m in markers: if isinstance(m, (dict, _MapDict)): for prop1 in __CHART_MARKER_TO_COLS: val = m.get(prop1) if isinstance(val, str) and val not in columns: opt_cols.add(val) # Validate the column names col_dict = _get_columns_dict(attributes.get("data"), list(columns), col_types, opt_columns=opt_cols) # Manage Decimator decimators: t.List[t.Optional[str]] = [] for tr in traces: if tr[_Chart_iprops.decimator.value]: cls = gui._get_user_instance( class_name=str(tr[_Chart_iprops.decimator.value]), class_type=PropertyType.decimator.value ) if isinstance(cls, PropertyType.decimator.value): decimators.append(str(tr[_Chart_iprops.decimator.value])) continue decimators.append(None) # set default columns if not defined icols = [[c2 for c2 in [__get_col_from_indexed(c1, i) for c1 in col_dict.keys()] if c2] for i in range(len(traces))] for i, tr in enumerate(traces): if i < len(axis): used_cols = {tr[ax.value] for ax in axis[i] if tr[ax.value]} unused_cols = [c for c in icols[i] if c not in used_cols] if unused_cols and not any(tr[ax.value] for ax in axis[i]): traces[i] = list( v or (unused_cols.pop(0) if unused_cols and _Chart_iprops(j) in axis[i] else v) for j, v in enumerate(tr) ) if col_dict is not None: reverse_cols = {str(cd.get("dfid")): c for c, cd in col_dict.items()} # List used axis used_axis = [[e for e in (axis[j] if j < len(axis) else axis[0]) if tr[e.value]] for j, tr in enumerate(traces)] ret_dict = { "columns": col_dict, "labels": [ reverse_cols.get(tr[_Chart_iprops.label.value] or "", (tr[_Chart_iprops.label.value] or "")) for tr in traces ], "texts": [ reverse_cols.get(tr[_Chart_iprops.text.value] or "", (tr[_Chart_iprops.text.value] or None)) for tr in traces ], "modes": [tr[_Chart_iprops.mode.value] for tr in traces], "types": [tr[_Chart_iprops.type.value] for tr in traces], "xaxis": [tr[_Chart_iprops.xaxis.value] for tr in traces], "yaxis": [tr[_Chart_iprops.yaxis.value] for tr in traces], "markers": markers, "selectedMarkers": [ tr[_Chart_iprops.selected_marker.value] or ( {"color": tr[_Chart_iprops.selected_color.value]} if tr[_Chart_iprops.selected_color.value] else None ) for tr in traces ], "traces": [ [reverse_cols.get(c or "", c) for c in [tr[e.value] for e in used_axis[j]]] for j, tr in enumerate(traces) ], "orientations": [tr[_Chart_iprops.orientation.value] for tr in traces], "names": [tr[_Chart_iprops._name.value] for tr in traces], "lines": [ tr[_Chart_iprops.line.value] if isinstance(tr[_Chart_iprops.line.value], (dict, _MapDict)) else {"dash": tr[_Chart_iprops.line.value]} if tr[_Chart_iprops.line.value] else None for tr in traces ], "textAnchors": [tr[_Chart_iprops.text_anchor.value] for tr in traces], "options": [tr[_Chart_iprops.options.value] for tr in traces], "axisNames": [[e.name for e in ax] for ax in used_axis], "addIndex": [tr[_Chart_iprops.type.value] not in __CHART_NO_INDEX for tr in traces], } if len([d for d in decimators if d]): ret_dict.update(decimators=decimators) return ret_dict return {}
import re import typing as t _RE_MODULE = re.compile(r"^__(.*?)__$") def _filter_locals(locals_dict: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]: return {k: v for k, v in locals_dict.items() if (not _RE_MODULE.match(k) or k == "__name__")}
import typing as t from .singleton import _Singleton if t.TYPE_CHECKING: from ..gui import Gui class _RuntimeManager(object, metaclass=_Singleton): def __init__(self): self.__port_gui: t.Dict[int, "Gui"] = {} def add_gui(self, gui: "Gui", port: int): if port in self.__port_gui: self.__port_gui[port].stop() self.__port_gui[port] = gui def get_used_port(self): return list(self.__port_gui.keys())