Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/doc#986 - Document best practice on main script #1582

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 34 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,60 +128,63 @@ import taipy as tp
import pandas as pd
from taipy import Config, Scope, Gui

# Taipy Scenario & Data Management
# Defining the helper functions

# Callback definition - submits scenario with genre selection
def on_genre_selected(state):
scenario.selected_genre_node.write(state.selected_genre)
tp.submit(scenario)
state.df = scenario.filtered_data.read()

## Set initial value to Action
def on_init(state):
on_genre_selected(state)

# Filtering function - task
def filter_genre(initial_dataset: pd.DataFrame, selected_genre):
filtered_dataset = initial_dataset[initial_dataset["genres"].str.contains(selected_genre)]
filtered_data = filtered_dataset.nlargest(7, "Popularity %")
return filtered_data

# Load the configuration made with Taipy Studio
Config.load("config.toml")
scenario_cfg = Config.scenarios["scenario"]
# The main script
if __name__ == "__main__":
# Taipy Scenario & Data Management

# Start Taipy Core service
tp.Core().run()
# Load the configuration made with Taipy Studio
Config.load("config.toml")
scenario_cfg = Config.scenarios["scenario"]

# Create a scenario
scenario = tp.create_scenario(scenario_cfg)
# Start Taipy Core service
tp.Core().run()

# Create a scenario
scenario = tp.create_scenario(scenario_cfg)

# Taipy User Interface
# Let's add a GUI to our Scenario Management for a full application
# Taipy User Interface
# Let's add a GUI to our Scenario Management for a full application

# Callback definition - submits scenario with genre selection
def on_genre_selected(state):
scenario.selected_genre_node.write(state.selected_genre)
tp.submit(scenario)
state.df = scenario.filtered_data.read()

# Get list of genres
genres = [
"Action", "Adventure", "Animation", "Children", "Comedy", "Fantasy", "IMAX"
"Romance","Sci-FI", "Western", "Crime", "Mystery", "Drama", "Horror", "Thriller", "Film-Noir","War", "Musical", "Documentary"
# Get list of genres
genres = [
"Action", "Adventure", "Animation", "Children", "Comedy", "Fantasy", "IMAX"
"Romance","Sci-FI", "Western", "Crime", "Mystery", "Drama", "Horror", "Thriller", "Film-Noir","War", "Musical", "Documentary"
]

# Initialization of variables
df = pd.DataFrame(columns=["Title", "Popularity %"])
selected_genre = "Action"

## Set initial value to Action
def on_init(state):
on_genre_selected(state)
# Initialization of variables
df = pd.DataFrame(columns=["Title", "Popularity %"])
selected_genre = "Action"

# User interface definition
my_page = """
# User interface definition
my_page = """
# Film recommendation

## Choose your favorite genre
<|{selected_genre}|selector|lov={genres}|on_change=on_genre_selected|dropdown|>

## Here are the top seven picks by popularity
<|{df}|chart|x=Title|y=Popularity %|type=bar|title=Film Popularity|>
"""
"""

Gui(page=my_page).run()
Gui(page=my_page).run()
```

And the final result:
Expand Down
22 changes: 12 additions & 10 deletions doc/gui/examples/broadcast.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,6 @@
thread = None
thread_event = Event()

button_texts = ["Start", "Stop"]
# Text in the start/stop button (initially "Start")
button_text = button_texts[0]


def count(event, gui):
while not event.is_set():
Expand All @@ -58,15 +54,21 @@ def start_or_stop(state: State):
state.assign("button_text", button_texts[1 if thread else 0])


page = """# Broadcasting values
if __name__ == "__main__":
button_texts = ["Start", "Stop"]
# Text in the start/stop button (initially "Start")
button_text = button_texts[0]

page = """
# Broadcasting values

Counter: <|{counter}|>

Timer: <|{button_text}|button|on_action=start_or_stop|>
"""
"""

# Declare "button_text" as a shared variable.
# Assigning a value to a state's 'button_text' property is propagated to all clients
Gui.add_shared_variable("button_text")
# Declare "button_text" as a shared variable.
# Assigning a value to a state's 'button_text' property is propagated to all clients
Gui.add_shared_variable("button_text")

Gui(page).run()
Gui(page).run()
23 changes: 12 additions & 11 deletions doc/gui/examples/broadcast_callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@

from taipy.gui import Gui

current_time = datetime.now()
update = False


# Update the 'current_time' state variable if 'update' is True
def update_state(state, updated_time):
Expand All @@ -41,17 +38,21 @@ def update_time(gui):
sleep(1)


page = """
if __name__ == "__main__":
current_time = datetime.now()
update = False

page = """
Current time is: <|{current_time}|format=HH:mm:ss|>

Update: <|{update}|toggle|>
"""
"""

gui = Gui(page)
gui = Gui(page)

# Run thread that regularly updates the current time
thread = Thread(target=update_time, args=[gui], name="clock")
thread.daemon = True
thread.start()
# Run thread that regularly updates the current time
thread = Thread(target=update_time, args=[gui], name="clock")
thread.daemon = True
thread.start()

gui.run()
gui.run()
21 changes: 11 additions & 10 deletions doc/gui/examples/broadcast_change.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@

from taipy.gui import Gui

current_time = datetime.now()


# The function that executes in its own thread.
# Update the current time every second.
Expand All @@ -34,15 +32,18 @@ def update_time(gui):
sleep(1)


page = """
if __name__ == "__main__":
current_time = datetime.now()

page = """
Current time is: <|{current_time}|format=HH:mm:ss|>
"""
"""

gui = Gui(page)
gui = Gui(page)

# Run thread that regularly updates the current time
thread = Thread(target=update_time, args=[gui], name="clock")
thread.daemon = True
thread.start()
# Run thread that regularly updates the current time
thread = Thread(target=update_time, args=[gui], name="clock")
thread.daemon = True
thread.start()

gui.run()
gui.run()
48 changes: 24 additions & 24 deletions doc/gui/examples/charts/advanced-annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,31 @@ 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 = """
if __name__ == "__main__":
# 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()
Gui(page).run()
53 changes: 29 additions & 24 deletions doc/gui/examples/charts/advanced-python-lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,29 +21,34 @@

from taipy.gui import Gui

# Create the Plotly figure object
figure = go.Figure()

# Add trace for Normal Distribution
figure.add_trace(
go.Violin(name="Normal", y=np.random.normal(loc=0, scale=1, size=1000), box_visible=True, meanline_visible=True)
)

# Add trace for Exponential Distribution
figure.add_trace(
go.Violin(name="Exponential", y=np.random.exponential(scale=1, size=1000), box_visible=True, meanline_visible=True)
)

# Add trace for Uniform Distribution
figure.add_trace(
go.Violin(name="Uniform", y=np.random.uniform(low=0, high=1, size=1000), box_visible=True, meanline_visible=True)
)

# Updating layout for better visualization
figure.update_layout(title="Different Probability Distributions")

page = """
if __name__ == "__main__":
# Create the Plotly figure object
figure = go.Figure()

# Add trace for Normal Distribution
figure.add_trace(
go.Violin(name="Normal", y=np.random.normal(loc=0, scale=1, size=1000), box_visible=True, meanline_visible=True)
)

# Add trace for Exponential Distribution
figure.add_trace(
go.Violin(
name="Exponential", y=np.random.exponential(scale=1, size=1000), box_visible=True, meanline_visible=True
)
)

# Add trace for Uniform Distribution
figure.add_trace(
go.Violin(
name="Uniform", y=np.random.uniform(low=0, high=1, size=1000), box_visible=True, meanline_visible=True
)
)

# Updating layout for better visualization
figure.update_layout(title="Different Probability Distributions")

page = """
<|chart|figure={figure}|>
"""
"""

Gui(page).run()
Gui(page).run()
51 changes: 26 additions & 25 deletions doc/gui/examples/charts/advanced-selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,43 +20,44 @@

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],
}
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

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
}
if __name__ == "__main__":
# x = [0..20]
x = list(range(0, 21))

selected_indices: List = []
data = {
"x": x,
# A list of random values within [1, 10]
"y": [random.uniform(1, 10) for _ in x],
}

mean_value = 0.0
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
}

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
selected_indices: List = []

mean_value = 0.0

page = """
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()
Gui(page).run()
Loading
Loading