text stringlengths 0 105k |
|---|
# For the sake of clarity, we have used an AutoRegressive model rather than a pure ML model such as: # Random Forest, Linear Regression, LSTM, etc from statsmodels.tsa.ar_model import AutoReg import pandas as pd from sklearn.metrics import mean_squared_error, mean_absolute_error import numpy as np import datetime as dt def clean_data(initial_dataset: pd.DataFrame): print(" Cleaning data") # Convert the date column to datetime initial_dataset['Date'] = pd.to_datetime(initial_dataset['Date']) cleaned_dataset = initial_dataset.copy() return cleaned_dataset def predict_baseline(cleaned_dataset: pd.DataFrame, n_predictions: int, day: dt.datetime, max_capacity: int): print(" Predicting baseline") # Select the train data train_dataset = cleaned_dataset[cleaned_dataset['Date'] < day] predictions = train_dataset['Value'][-n_predictions:].reset_index(drop=True) predictions = predictions.apply(lambda x: min(x, max_capacity)) return predictions # This is the function that will be used by the task def predict_ml(cleaned_dataset: pd.DataFrame, n_predictions: int, day: dt.datetime, max_capacity: int): print(" Predicting with ML") # Select the train data train_dataset = cleaned_dataset[cleaned_dataset["Date"] < day] # Fit the AutoRegressive model model = AutoReg(train_dataset["Value"], lags=7).fit() # Get the n_predictions forecasts predictions = model.forecast(n_predictions).reset_index(drop=True) predictions = predictions.apply(lambda x: min(x, max_capacity)) return predictions def compute_metrics(historical_data, predicted_data): historical_to_compare = historical_data[-len(predicted_data):]['Value'] rmse = mean_squared_error(historical_to_compare, predicted_data) mae = mean_absolute_error(historical_to_compare, predicted_data) return rmse, mae def create_predictions_dataset(predictions_baseline, predictions_ml, day, n_predictions, cleaned_data): print("Creating predictions dataset...") # Set arbitrarily the time window for the chart as 5 times the number of predictions window = 5 * n_predictions # Create the historical dataset that will be displayed new_length = len(cleaned_data[cleaned_data["Date"] < day]) + n_predictions temp_df = cleaned_data[:new_length] temp_df = temp_df[-window:].reset_index(drop=True) # Create the series that will be used in the concat historical_values = pd.Series(temp_df["Value"], name="Historical values") predicted_values_ml = pd.Series([np.NaN] * len(temp_df), name="Predicted values ML") predicted_values_ml[-len(predictions_ml):] = predictions_ml predicted_values_baseline = pd.Series([np.NaN] * len(temp_df), name="Predicted values Baseline") predicted_values_baseline[-len(predictions_baseline):] = predictions_baseline # Create the predictions dataset # Columns : [Date, Historical values, Predicted values] predictions_dataset = pd.concat([temp_df["Date"], historical_values, predicted_values_ml, predicted_values_baseline], axis=1) return predictions_dataset |
from .data_viz import data_viz from .scenario import scenario_page from .performance import performance from .root import root_page |
""" The rootpage of the application. Page content is imported from the root.md file. Please refer to https://docs.taipy.io/en/latest/manuals/gui/pages for more details. """ from taipy.gui import Markdown root_page = Markdown("pages/root.md") |
from .scenario import scenario_page |
""" The second page of the application. Page content is imported from the page_2.md file. Please refer to https://docs.taipy.io/en/latest/manuals/gui/pages for more details. """ from taipy.gui import Markdown, notify import datetime as dt import pandas as pd scenario = None day = dt.datetime(2021, 7, 26) n_predictions = 40 max_capacity = 200 predictions_dataset = {"Date":[0], "Predicted values ML":[0], "Predicted values Baseline":[0], "Historical values":[0]} def save(state): print("Saving scenario...") # Get the currently selected scenario # Conversion to the right format state_day = dt.datetime(state.day.year, state.day.month, state.day.day) # Change the default parameters by writing in the Data Nodes state.scenario.day.write(state_day) state.scenario.n_predictions.write(int(state.n_predictions)) state.scenario.max_capacity.write(int(state.max_capacity)) notify(state, "success", "Saved!") def on_change(state, var_name, var_value): if var_name == "scenario" and var_value: state.day = state.scenario.day.read() state.n_predictions = state.scenario.n_predictions.read() state.max_capacity = state.scenario.max_capacity.read() if state.scenario.full_predictions.is_ready_for_reading: state.predictions_dataset = state.scenario.full_predictions.read() else: state.predictions_dataset = predictions_dataset scenario_page = Markdown("pages/scenario/scenario.md") |
from .data_viz import data_viz |
""" The first page of the application. Page content is imported from the page_1.md file. Please refer to https://docs.taipy.io/en/latest/manuals/gui/pages for more details. """ from taipy.gui import Markdown import pandas as pd def get_data(path_to_csv: str): # pandas.read_csv() returns a pd.DataFrame dataset = pd.read_csv(path_to_csv) dataset["Date"] = pd.to_datetime(dataset["Date"]) return dataset # Read the dataframe path_to_csv = "data/dataset.csv" dataset = get_data(path_to_csv) # Initial value n_week = 10 # Select the week based on the slider value dataset_week = dataset[dataset["Date"].dt.isocalendar().week == n_week] def on_slider(state): state.dataset_week = dataset[dataset["Date"].dt.isocalendar().week == state.n_week] data_viz = Markdown("pages/data_viz/data_viz.md") |
from .performance import performance |
from taipy.gui import Markdown import pandas as pd import taipy as tp # Initial dataset for comparison comparison_scenario = pd.DataFrame(columns=["Scenario Name", "RMSE baseline", "MAE baseline", "RMSE ML", "MAE ML"]) # Selector for metrics metric_selector = ["RMSE", "MAE"] selected_metric = metric_selector[0] def compare(state): print("Comparing...") # Initialize lists for comparison scenario_data = [] # Go through all the primary scenarios all_scenarios = sorted(tp.get_primary_scenarios(), key=lambda x: x.creation_date.timestamp()) for scenario in all_scenarios: rmse_baseline, mae_baseline = scenario.metrics_baseline.read() rmse_ml, mae_ml = scenario.metrics_ml.read() # Store scenario data in a dictionary scenario_data.append({ "Scenario Name": scenario.name, "RMSE baseline": rmse_baseline, "MAE baseline": mae_baseline, "RMSE ML": rmse_ml, "MAE ML": mae_ml }) # Create a DataFrame from the scenario_data list state.comparison_scenario = pd.DataFrame(scenario_data) performance = Markdown("pages/performance/performance.md") |
import os import re import shutil import subprocess from _fetch_source_file import CLI, GitContext, read_doc_version_from_mkdocs_yml_template_file # Assuming this script is in taipy-doc/tools TOOLS_PATH = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.dirname(TOOLS_PATH) TOP_DIR = os.path.dirname(ROOT_DIR) # Where all the code from all directories/repositories is copied DEST_DIR_NAME = "taipy" REPOS = ["config", "core", "gui", "rest", "taipy", "templates"] PRIVATE_REPOS = ["auth", "enterprise"] OPTIONAL_PACKAGES = { "gui": ["pyarrow", "pyngrok", "python-magic", "python-magic-bin"] } args = CLI(os.path.basename(__file__), REPOS).get_args() # Read version from mkdocs.yml template mkdocs_yml_version = read_doc_version_from_mkdocs_yml_template_file(ROOT_DIR) # Gather version information for each repository repo_defs = {repo if repo == "taipy" else f"taipy-{repo}": {"version": "local", "tag": None} for repo in REPOS + PRIVATE_REPOS} CATCH_VERSION_RE = re.compile(r"(^\d+\.\d+?)(?:(\.\d+)(\..*)?)?|develop|local$") for version in args.version: repo = None if version == "MKDOCS": version = mkdocs_yml_version tag = None else: try: colon = version.index(":") repo = version[:colon] if not repo.startswith("taipy"): repo = f"taipy-{repo}" version = version[colon + 1:] except ValueError as e: pass version_match = CATCH_VERSION_RE.fullmatch(version) if not version_match: raise ValueError(f"'{version}' is not a valid version.") tag = None if version_match.group(1): version = version_match.group(1) if version_match.group(2): tag = version + version_match.group(2) if version_match.group(3): tag += version_match.group(3) if repo: if not repo in repo_defs: raise ValueError(f"'{repo}' is not a valid repository name.") repo_defs[repo]["version"] = version repo_defs[repo]["tag"] = tag else: for repo in repo_defs.keys(): repo_defs[repo]["version"] = version repo_defs[repo]["tag"] = tag # Test git, if needed git_command = "git" if args.no_pull and all(v["version"] == "local" for v in repo_defs.values()): git_command = None else: git_path = shutil.which(git_command) if git_path is None or subprocess.run(f"\"{git_path}\" --version", shell=True, capture_output=True) is None: raise IOError(f"Couldn't find command \"{git_command}\"") git_command = git_path # Check that directory, branches and tags exist for each repository github_token = os.environ.get("GITHUB_TOKEN", "") if github_token: github_token += "@" github_root = f"https://{github_token}github.com/Avaiga/" for repo in repo_defs.keys(): version = repo_defs[repo]["version"] if version == "local": repo_path = os.path.join(TOP_DIR, repo) repo_defs[repo]["path"] = repo_path if not os.path.isdir(repo_path): if repo in PRIVATE_REPOS: repo_defs[repo]["skip"] = True else: raise IOError(f"Repository '{repo}' must be cloned in \"{TOP_DIR}\".") elif version == "develop": with GitContext(repo, PRIVATE_REPOS): cmd = subprocess.run(f"\"{git_path}\" ls-remote -q -h {github_root}{repo}.git", shell=True, capture_output=True, text=True) if cmd.returncode: if repo in PRIVATE_REPOS: repo_defs[repo]["skip"] = True continue else: raise SystemError(f"Problem with {repo}:\nOutput: {cmd.stdout}\nError: {cmd.stderr}") else: with GitContext(repo, PRIVATE_REPOS): cmd = subprocess.run(f"\"{git_path}\" ls-remote --exit-code --heads {github_root}{repo}.git", shell=True, capture_output=True, text=True) if cmd.returncode: if repo in PRIVATE_REPOS: repo_defs[repo]["skip"] = True continue else: raise SystemError(f"Couldn't query branches from {github_root}{repo}.") if not f"release/{version}\n" in cmd.stdout: raise ValueError(f"No branch 'release/{version}' in repository '{repo}'.") tag = repo_defs[repo]["tag"] if tag: cmd = subprocess.run(f"\"{git_path}\" ls-remote -t --refs {github_root}{repo}.git", shell=True, capture_output=True, text=True) if not f"refs/tags/{tag}\n" in cmd.stdout: raise ValueError(f"No tag '{tag}' in repository '{repo}'.") if args.check: print(f"Fetch should perform properly with the following settings:") for repo in repo_defs.keys(): if not repo_defs[repo].get("skip", False): version = repo_defs[repo]['version'] version = "(local)" if version == "local" else f"branch:{version if version == 'develop' else f'release/{version}'}" tag = repo_defs[repo]["tag"] if tag: version += f" tag:{tag}" print(f"- {repo} {version}") exit(0) DEST_DIR = os.path.join(ROOT_DIR, DEST_DIR_NAME) def safe_rmtree(dir: str): if os.path.isdir(dir): shutil.rmtree(dir) # Remove target 'taipy' directory safe_rmtree(DEST_DIR) os.makedirs(DEST_DIR) # If a leftover of a previous failed run safe_rmtree(os.path.join(TOOLS_PATH, DEST_DIR_NAME)) pipfile_packages = {} PIPFILE_PACKAGE_RE = re.compile(r"(.*?)\s?=\s?(.*)") # Fetch files def move_files(repo: str, src_path: str): # Read Pipfile dependency packages pipfile_path = os.path.join(src_path, "Pipfile") if os.path.isfile(pipfile_path): reading_packages = False repo_optional_packages = OPTIONAL_PACKAGES.get(repo, None) with open(pipfile_path, "r") as pipfile: while True: line = pipfile.readline() if str(line) == "" or (reading_packages and (not line.strip() or line[0] == "[")): break line = line.strip() if line == "[packages]": reading_packages = True elif reading_packages: match = PIPFILE_PACKAGE_RE.fullmatch(line) if match and not match.group(1).startswith("taipy"): package = match.group(1).lower() version = match.group(2) if repo_optional_packages is None or not package in repo_optional_packages: if package in pipfile_packages: versions = pipfile_packages[package] if version in versions: versions[version].append(repo) else: versions[version] = [repo] else: pipfile_packages[package] = {version: [repo]} # Copy relevant files for doc generation if repo.startswith("taipy-getting-started"): gs_dir = os.path.join(ROOT_DIR, "docs", "getting_started", repo[6:]) # safe_rmtree(os.path.join(gs_dir, "src")) for step_dir in [step_dir for step_dir in os.listdir(gs_dir) if step_dir.startswith("step_") and os.path.isdir(os.path.join(gs_dir, step_dir))]: safe_rmtree(os.path.join(gs_dir, step_dir)) for step_dir in [step_dir for step_dir in os.listdir(src_path) if step_dir.startswith("step_") and os.path.isdir(os.path.join(src_path, step_dir))]: shutil.copytree(os.path.join(src_path, step_dir), os.path.join(gs_dir, step_dir)) safe_rmtree(os.path.join(gs_dir, "src")) shutil.copytree(os.path.join(src_path, "src"), os.path.join(gs_dir, "src")) shutil.copy(os.path.join(src_path, "index.md"), os.path.join(gs_dir, "index.md")) saved_dir = os.getcwd() os.chdir(os.path.join(ROOT_DIR, "docs", "getting_started", repo[6:])) subprocess.run(f"python {os.path.join(src_path, 'generate_notebook.py')}", shell=True, capture_output=True, text=True) os.chdir(saved_dir) else: tmp_dir = os.path.join(ROOT_DIR, f"{repo}.tmp") safe_rmtree(tmp_dir) gui_dir = os.path.join(ROOT_DIR, f"gui") if repo == "taipy-gui" else None if repo == "taipy-gui" and os.path.isdir(gui_dir): if os.path.isdir(os.path.join(gui_dir, "node_modules")): shutil.move(os.path.join(gui_dir, "node_modules"), os.path.join(ROOT_DIR, f"gui_node_modules")) shutil.rmtree(gui_dir) try: def copy_source(src_path: str, repo: str): def copy(item: str, src: str, dst: str, rel_path: str): full_src = os.path.join(src, item) full_dst = os.path.join(dst, item) if os.path.isdir(full_src): if item in ["__pycache__", "node_modules"]: return if not os.path.isdir(full_dst): os.makedirs(full_dst) rel_path = f"{rel_path}/{item}" for sub_item in os.listdir(full_src): copy(sub_item, full_src, full_dst, rel_path) elif any(item.endswith(ext) for ext in [".py", ".pyi", ".json", ".ipynb"]): if os.path.isfile(full_dst): # File exists - compare with open(full_src, "r") as f: src = f.read() with open(full_dst, "r") as f: dst = f.read() if src != dst: raise FileExistsError(f"File {rel_path}/{item} already exists and is different (copying repository {repo})") else: shutil.copy(full_src, full_dst) dest_path = os.path.join(ROOT_DIR, "taipy") if not os.path.exists(dest_path): os.makedirs(dest_path) src_path = os.path.join(src_path, "src", "taipy") for item in os.listdir(src_path): copy(item, src_path, dest_path, "") copy_source(src_path, repo) if gui_dir: if not os.path.isdir(gui_dir): os.mkdir(gui_dir) src_gui_dir = os.path.join(src_path, "gui") shutil.copytree(os.path.join(src_gui_dir, "src"), os.path.join(gui_dir, "src")) for f in [f for f in os.listdir(src_gui_dir) if f.endswith(".md") or f.endswith(".json")]: shutil.copy(os.path.join(src_gui_dir, f), os.path.join(gui_dir, f)) if os.path.isdir(os.path.join(ROOT_DIR, "gui_node_modules")): shutil.move(os.path.join(ROOT_DIR, "gui_node_modules"), os.path.join(gui_dir, "node_modules")) finally: pass """ shutil.rmtree(tmp_dir) """ for repo in repo_defs.keys(): if repo_defs[repo].get("skip", False): continue version = repo_defs[repo]['version'] print(f"Fetching file for repository {repo} ({version})", flush=True) if version == "local": src_path = repo_defs[repo]['path'] if not args.no_pull: subprocess.run(f"\"{git_path}\" pull {src_path}", shell=True, capture_output=True, text=True) print(f" Copying from {src_path}...", flush=True) move_files(repo, src_path) else: clone_dir = os.path.join(ROOT_DIR, f"{repo}.clone") if version != "develop": version = f"release/{version}" print(" Cloning...", flush=True) subprocess.run(f"\"{git_path}\" clone -b {version} {github_root}{repo}.git {clone_dir}", shell=True, capture_output=True, text=True) tag = repo_defs[repo]['tag'] if tag: # Checkout tag version saved_dir = os.getcwd() os.chdir(clone_dir) subprocess.run(f"\"{git_path}\" checkout {tag}", shell=True, capture_output=True, text=True) os.chdir(saved_dir) move_files(repo, clone_dir) # For some reason, we need to protect the removal of the clone dirs... # See https://stackoverflow.com/questions/1213706/what-user-do-python-scripts-run-as-in-windows def handleRemoveReadonly(func, path, exc): import errno, stat if func == os.unlink and exc[1].errno == errno.EACCES: os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # 0777 func(path) else: raise shutil.rmtree(clone_dir, onerror=handleRemoveReadonly) # Manually add the taipy.run() function. # TODO: Automate this, grabbing the function from the 'taipy' repository, # so we benefit from potential updates. init_path = os.path.join(ROOT_DIR, "taipy", "__init__.py") with open(init_path, "a") as init: run_method = """ import typing as t def run(*services: t.Union[Gui, Rest, Core], **kwargs) -> t.Optional[t.Union[Gui, Rest, Core]]: \"\"\"Run one or multiple Taipy services. A Taipy service is an instance of a class that runs code as a web application. Parameters: services (Union[`Gui^`, `Rest^`, `Core^`]): Services to run.<br/> If several services are provided, all the services run simultaneously. If this is empty or set to None, this method does nothing. **kwargs (dict[str, any]): Other parameters to provide to the services. \"\"\" pass\n""" init.write(run_method) # Generate Pipfile from package dependencies from all repositories pipfile_path = os.path.join(ROOT_DIR, "Pipfile") pipfile_message = "WARNING: Package versions mismatch in Pipfiles - Pipfile not updated." for package, versions in pipfile_packages.items(): if len(versions) != 1: if pipfile_message: print(pipfile_message) pipfile_message = None print(f"- {package}:") for version, repos in versions.items(): print(f" {version} in {', '.join(repos)}.") pipfile_path = None # Update Pipfile from all other Pipfiles if pipfile_path: pipfile_lines = None with open(pipfile_path, "r") as pipfile: pipfile_lines = pipfile.readlines() new_pipfile_path = os.path.join(ROOT_DIR, "Pipfile.new") in_packages_section = False legacy_pipfile_packages = {} pipfile_changes = [] with open(new_pipfile_path, "w") as new_pipfile: for line in pipfile_lines: if in_packages_section: if not line or line[0] == "[": in_packages_section = False # List packages for package in sorted(pipfile_packages.keys(), key=str.casefold): versions = pipfile_packages[package] version = list(versions.keys())[0] if package == "modin": # Remove 'extras' from modin package requirements version = re.sub(r"\{\s*extras.*?,\s*version\s*=\s*(.*?)\s*}", r"\1", version) new_pipfile.write(f"{package} = {version}\n") if not package in legacy_pipfile_packages: pipfile_changes.append(f"Package '{package}' added ({version})") elif legacy_pipfile_packages[package] != version: pipfile_changes.append( f"Package '{package}' version changed from {legacy_pipfile_packages[package]} to {version}") del legacy_pipfile_packages[package] else: del legacy_pipfile_packages[package] new_pipfile.write("\n") skip_line = True new_pipfile.write(line) match = PIPFILE_PACKAGE_RE.fullmatch(line.strip()) if match and not match.group(1).startswith("taipy"): legacy_pipfile_packages[match.group(1).lower()] = match.group(2) else: new_pipfile.write(line) if line.strip() == "[packages]": in_packages_section = True for package, version in legacy_pipfile_packages.items(): pipfile_changes.append(f"Package '{package}' removed ({version})") if pipfile_changes: print(f"Pipfile was updated (Pipfile.bak saved):") for change in pipfile_changes: print(f"- {change}") shutil.move(pipfile_path, os.path.join(ROOT_DIR, "Pipfile.bak")) shutil.move(new_pipfile_path, pipfile_path) print(f"You may want to rebuild you virtual environment:") print(f" - pipenv --rm") print(f" - pipenv install --dev") else: print(f"No changes in Pipfile") os.remove(new_pipfile_path) |
# ################################################################################ # setup_generation.py # Prepares all files before running MkDocs to generate the complete # Taipy documentation set. # # This setup is performed by executing successive steps, depending on the # topic (Reference Manual generation, JavaScript documentation integration # within MkDocs...) # ################################################################################ import os from _setup_generation import run_setup steps = None # -------------------------------------------------------------------------------- # You may want to replace that 'step' initial value with a list of steps you # want to run. # i.e. say you want to run only the Reference Manual generation step. # You could add the following code: # from _setup_generation.step_refman import RefManStep # steps = [RefManStep()] # -------------------------------------------------------------------------------- # Assuming that this script is located in <taipy-doc>/tools run_setup(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), steps) |
# ###################################################################### # # Syntax for cross-references to the Reference Manual: # `ClassName^` # generates a link from `ClassName` to the class doc page. # `functionName(*)^` # generates a link from `functionName(*)` to the function doc section. # `ClassName.methodName(*)^` # generates a link from `ClassName.methodName(*)` to the method doc section. # `(ClassName.)methodName(*)^` # generates a link from `methodName(*)` to the method doc section, hiding the class name. # `package.functionName(*)^` # generates a link from `package.functionName(*)` to the function doc section. # `(package.)functionName(*)^` # generates a link from `functionName(*)` to the function doc section, hiding the package. # `(package.)ClassName^` # generates a link from `ClassName` to the class doc page, hiding the package. # `(package.)ClassName.methodName(*)^` # generates a link from `ClassName.methodName(*)` to the method doc section, hiding the # package. # `(package.ClassName.)methodName(*)^` # generates a link from `methodName(*)` to the method doc section, hiding the package and the # class name. # ###################################################################### import os import re from typing import Dict import logging import json def define_env(env): """ Mandatory to make this a proper MdDocs macro """ match = re.search(r"/en/(develop|(?:release-(\d+\.\d+)))/$", env.conf["site_url"]) env.conf["branch"] = (f"release/{match[2]}" if match[2] else match[1]) if match else "unknown" TOC_ENTRY_PART1 = r"<li\s*class=\"md-nav__item\">\s*<a\s*href=\"" TOC_ENTRY_PART2 = r"\"\s*class=\"md-nav__link\">([^<]*)</a>\s*</li>\s*" # XREF_RE details: # group(1) - The package, class or function name with a trailing '.'. # Can be empty. # This text will not appear as the anchor text. # group(2) - The name of a class, function, method... This text will appear in the anchor text # group(3) - The function parameters, with their (). Can be empty. # group(4) - The anchor text. Can be empty, then group(2)+group(3) is used. ## XREF_RE = re.compile(r"<code>(\()?((?:[^\d\W]\w*\.)*)" ## + r"(?:\))?([^\d\W][\w\.]*)(\(.*?\))?\^<\/code>") XREF_RE = re.compile(r"<code>(?:\(([\w*\.]*)\))?([\.\w]*)(\(.*?\))?\^<\/code>(?:\(([^\)]*)\))?") def find_dummy_h3_entries(content: str) -> Dict[str, str]: """ Find 'dummy <h3>' entries. These are <h3> tags that are just redirections to another page. These need to be removed, and redirection must be used in TOC. """ ids = {} TOC_ENTRY = re.compile(TOC_ENTRY_PART1 + r"(#[^\"]+)" + TOC_ENTRY_PART2, re.M | re.S) while True: toc_entry = TOC_ENTRY.search(content) if toc_entry is None: break content = content[toc_entry.end() :] id = toc_entry.group(1)[1:] dummy_h3 = re.search(r"<h3\s+id=\"" + id + r"\">\s*<a\s+href=\"(.*?)\".*?</h3>", content, re.M | re.S) if dummy_h3 is not None: ids[id] = dummy_h3.group(1) return ids def remove_dummy_h3(content: str, ids: Dict[str, str]) -> str: """ Removes dummy <h3> entries and fix TOC. """ for id, redirect in ids.items(): # Replace redirection in TOC content = re.sub( TOC_ENTRY_PART1 + "#" + id + TOC_ENTRY_PART2, '<li class="md-nav__item"><a href="' + redirect + '" class="md-nav__link">\\1</a></li>\n', content, re.M | re.S, ) # Remove dummy <h3> content = re.sub(r"<h3\s+id=\"" + id + r"\">\s*<a\s+href=\".*?\".*?</h3>", "", content, re.M | re.S) return content def on_post_build(env): """ Post-build actions for Taipy documentation """ log = logging.getLogger("mkdocs") site_dir = env.conf["site_dir"] xrefs = {} multi_xrefs = {} if os.path.exists(site_dir + "/manuals/xrefs"): with open(site_dir + "/manuals/xrefs") as xrefs_file: xrefs = json.load(xrefs_file) if xrefs is None: log.error(f"Could not read xrefs in 'manuals/xrefs'") x_packages = set() for xref, xref_desc in xrefs.items(): if isinstance(xref_desc, list): x_packages.add(xref_desc[0]) if xref_desc[2]: x_packages.update(xref_desc[2]) else: descs = [xrefs[f"{xref}/{i}"] for i in range(0, xref_desc)] # If unspecified, the first xref will be used (the one with the shortests package) multi_xrefs[xref] = sorted(descs, key=lambda p: len(p[0])) manuals_files_path = os.path.join(site_dir, "manuals") ref_files_path = os.path.join(manuals_files_path, "reference") fixed_cross_refs = {} for root, _, file_list in os.walk(site_dir): for f in file_list: # Remove the *_template files if f.endswith("_template"): os.remove(os.path.join(root, f)) # Post-process generated '.html' files elif f.endswith(".html"): filename = os.path.join(root, f) file_was_changed = False with open(filename) as html_file: try: html_content = html_file.read() except Exception as e: print(f"Couldn't read HTML file {filename}") raise e # Rebuild coherent links from TOC to sub-pages ids = find_dummy_h3_entries(html_content) if ids: html_content = remove_dummy_h3(html_content, ids) file_was_changed = True # Remove <h1>Index</h1> part of relevant pages INDEX_H1_RE = re.compile( r"<h1>Index</h1>\s*<h2(.*?)>(.*?)</h2>", re.M | re.S ) match = INDEX_H1_RE.search(html_content) if match: before = html_content[:match.start()] new_title = match.group(2) if new_title.startswith("Package"): USELESS_TITLE_RE = re.compile(r"(?<=<title>)Index(.*?)(?=</title>)", re.M | re.S) t_match = USELESS_TITLE_RE.search(before) if t_match: new_title = re.sub(r"<a\s+.*?</a>", "", new_title) new_title, n = re.subn(r"<code>(.*?)</code>", r"\g<1>", new_title) new_title = "Taipy p" + new_title[1:] before = before[:t_match.start()] + new_title + before[t_match.end():] html_content = (before + f"<h1{match.group(1)}>{match.group(2)}</h1>" + html_content[match.end():]) file_was_changed = True #""" # Collapse doubled <h1>/<h2> page titles REPEATED_H1_H2 = re.compile( r"<h1>(.*?)</h1>\s*<h2\s+(id=\".*?\")>\1(<a\s+class=\"headerlink\".*?</a>)?</h2>", re.M | re.S ) html_content, n_changes = REPEATED_H1_H2.subn('<h1 \\2>\\1\\3</h1>', html_content) if n_changes != 0: file_was_changed = True #""" # Specific processing for Getting Started documentation files if "getting_started" in filename: GS_H1_H2 = re.compile(r"<h1>(.*?)</h1>(.*?<h2.*?>\1)<", re.M | re.S) html_content, n_changes = GS_H1_H2.subn('\\2<', html_content) if n_changes != 0: file_was_changed = True gs_rel_path = os.path.relpath(site_dir, filename).replace("\\", "/").replace("../", "", 1) GS_DOCLINK = re.compile(r"(href=\")https://docs\.taipy\.io/en/latest(.*?\")", re.M | re.S) html_content, n_changes = GS_DOCLINK.subn(f"\\1{gs_rel_path}\\2", html_content) if n_changes != 0: file_was_changed = True GS_IPYNB = re.compile(r"(<a\s*href=\"([^\"]*?)\.ipynb\")\s*>", re.M | re.S) html_content, n_changes = GS_IPYNB.subn(f"\\1 download>", html_content) if n_changes != 0: file_was_changed = True # Add external link icons (and open in new tab) # Note we want this only for the simple [text](http*://ext_url) cases EXTLINK = re.compile( r"<a\s+(href=\"http[^\"]+\">.*?<\/a>)", re.M | re.S ) html_content, n_changes = EXTLINK.subn('<a class="ext-link" target="_blank" \\1', html_content) if n_changes != 0: file_was_changed = True # Find and resolve automatic cross-references to the Reference Manual # The syntax in Markdown is `(class.)method()^` and similar. rel_path = os.path.relpath(ref_files_path, filename).replace("\\", "/").replace("../", "", 1) new_content = "" last_location = 0 for xref in XREF_RE.finditer(html_content): all_parts = (xref[1] + xref[2]) if xref[1] else xref[2] parts = all_parts.split(".") c_name: str = parts.pop() # Class of function name m_name: str = None # Method name # Get potential destination link descriptor from last part desc = xrefs.get(c_name) # Check for class.method (looking at part before last) if len(parts) > 0: potential_class_name = parts[-1] if class_xref := xrefs.get(potential_class_name): desc = class_xref m_name = c_name c_name = potential_class_name parts.pop() if isinstance(desc, int): if parts: package = "." . join(parts) desc = next(d for d in multi_xrefs.get(c_name) if d[0].endswith(package)) else: desc = multi_xrefs.get(c_name)[0] link = None if not desc: if os.path.exists(f"{ref_files_path}/pkg_{all_parts}/index.html"): link = f"pkg_{all_parts}" else: (dir, file) = os.path.split(filename) (dir, dir1) = os.path.split(dir) (dir, dir2) = os.path.split(dir) message = f"Unresolve crossref '{re.sub(r'</?code>', '`', xref[0])}' found in " if file == "index.html": (dir, dir3) = os.path.split(dir) log.error(f"{message}{dir3}/{dir2}/{dir1}.md") else: log.error(f"{message}{dir2}/{dir1}/{file}") else: link = f"{desc[0]}.{c_name}" if m_name: link += f"/index.html#{desc[0]}.{c_name}.{m_name}" if link: new_content += html_content[last_location:xref.start()] new_content += f"<a href=\"{rel_path}/{link}\">" if xref[4]: # Anchor text new_content += xref[4] elif xref[2] or xref[3]: new_content += "<code>" if xref[2]: new_content += xref[2] if xref[3]: new_content += xref[3] new_content += "</code>" else: new_content += f"<b>NO CONTENT</b>" new_content += f"</a>" last_location = xref.end() if last_location: file_was_changed = True html_content = new_content + html_content[last_location:] # Find 'free' crossrefs to the Reference Manual # Syntax in Markdown is [free text]((class.)method()^) and similar new_content = "" last_location = 0 FREE_XREF_RE = re.compile(r"(<a\s+href=\")" + r"([^\d\W]\w*)(?:\.\))?" + r"((?:\.)?(?:[^\d\W]\w*))?(\(.*?\))?\^" + r"(\">.*?</a>)") for xref in FREE_XREF_RE.finditer(html_content): groups = xref.groups() entry = groups[1] method = groups[2] # Function in package? Or method in class? packages = [entry, None] if entry in x_packages else xrefs.get(entry) if packages is None: (dir, file) = os.path.split(filename) (dir, dir1) = os.path.split(dir) (dir, dir2) = os.path.split(dir) bad_xref = xref.group(0) message = f"Unresolve crossref '{bad_xref}' found in " if file == "index.html": (dir, dir3) = os.path.split(dir) log.error(f"{message}{dir3}/{dir2}/{dir1}.md") else: log.error(f"{message}{dir2}/{dir1}/{file}") continue else: # Free XRef was found: forget about the previous warning after all md_file=filename[len(site_dir):] sep=md_file[0] (dir, file) = os.path.split(md_file[1:]) # Drop the separator (dir, dir1) = os.path.split(dir) if file == "index.html": # Other cases to be treated as they come source = f"{dir}{sep}{dir1}.md" dest = f"{dir}{sep}{entry}{method}{groups[3]}^" sources = fixed_cross_refs.get(dest, None) if sources: sources.add(source) else: fixed_cross_refs[dest] = {source} package = packages[0] orig_package = packages[1] new_content += html_content[last_location:xref.start()] new_content += f"{groups[0]}{rel_path}/{package}." if orig_package: new_content += f"{entry}" if method: new_content += f"/index.html#{orig_package}.{entry}{method}\"" else: new_content += f"{method}/" new_content += f"\"{groups[4]}" last_location = xref.end() if last_location: file_was_changed = True html_content = new_content + html_content[last_location:] # Finding xrefs in 'Parameters', 'Returns' and similar constructs. # These would be <typeName>^ fragments located in potentially # complex constructs such as "Optional[Union[str, <typeName>^]]" # # These fragments appear in single-line <td> blocks. # # At this point, this code is pretty sub-optimal and heavily # depends on the MkDocs generation. Time will tell if we can # keep it as is... typing_code = re.compile(r"(<td>\s*<code>)(.*\^.*)(</code>\s*</td>)") # This will match a single <typeName>^ fragment. typing_type = re.compile(r"\w+\^") for xref in typing_code.finditer(html_content): groups = xref.groups() table_line = groups[1] table_line_to_replace = "".join(groups) new_table_line = table_line_to_replace typing_xref_found = False for type_ in typing_type.finditer(table_line): class_ = type_[0][:-1] # Remove ^ packages = xrefs.get(class_) if packages: # TODO - Retrieve the actual XREF if isinstance(packages, int): packages = xrefs.get(f"{class_}/0") # WRONG typing_xref_found = True new_content = f"<a href=\"{rel_path}/{packages[0]}.{class_}\">{class_}</a>" new_table_line = new_table_line.replace(f"{class_}^", new_content) if typing_xref_found: file_was_changed = True html_content = html_content.replace(table_line_to_replace, new_table_line) # Replace data-source attributes in h<N> tags to links to # files in the appropriate repositores. process = process_data_source_attr(html_content, env) if process[0]: html_content = process[1] file_was_changed = True # Replace hrefs to GitHub containg [BRANCH] with proper branch name. process = process_links_to_github(html_content, env) if process[0]: html_content = process[1] file_was_changed = True # Shorten Table of contents in REST API files if "rest/apis_" in filename or "rest\\apis_" in filename: REST_TOC_ENTRY_RE = re.compile(r"(<a\s+href=\"#apiv.*?>\s+)" + r"/api/v\d+(.*?)(?=\s+</a>)") new_content = "" last_location = 0 for toc_entry in REST_TOC_ENTRY_RE.finditer(html_content): new_content += html_content[last_location:toc_entry.start()] new_content += f"{toc_entry.group(1)}{toc_entry.group(2)}" last_location = toc_entry.end() if last_location: file_was_changed = True html_content = new_content + html_content[last_location:] # Rename the GUI Extension API type aliases elif "reference_guiext" in filename: for in_out in [("TaipyAction", "Action", "../interfaces/Action"), ("TaipyContext", "Context", "#context")]: LINK_RE = re.compile(f"<code>{in_out[0]}</code>") new_content = "" last_location = 0 for link in LINK_RE.finditer(html_content): new_content += html_content[last_location:link.start()] new_content += f"<a href=\"{in_out[2]}\"><code>{in_out[1]}</code></a>" last_location = link.end() if last_location: file_was_changed = True html_content = new_content + html_content[last_location:] # Processing for visual element pages: # - Remove <tt> from title # - Add breadcrumbs to Taipy GUI's control, part and core element pages fn_match = re.search(r"(/|\\)gui\1(vis|cor)elements\1(.*?)\1index.html", filename) element_category = None if fn_match is not None: if title_match := re.search(r"<title><tt>(.*?)</tt> - Taipy</title>", html_content): html_content = (html_content[:title_match.start()] + f"<title>{title_match.group(1)} - Taipy</title>" + html_content[title_match.end():]) file_was_changed = True if category_match := re.search(r"<!--\s+Category:\s+(\w+)\s+-->", html_content): element_category = category_match[1] elif re.match(r"^charts(/|\\).*$", fn_match[3]): element_category = "chart" if element_category: # Insert breadcrumbs ARTICLE_RE = re.compile(r"(<div\s+class=\"md-content\".*?>)(\s*<article)") if article_match := ARTICLE_RE.search(html_content): repl = "\n<ul class=\"tp-bc\">" if fn_match[2] == "cor": repl += f"<li><a href=\"../../viselements\"><b>Visual Elements</b></a></li>" repl += "<li><a href=\"../../viselements/controls/#scenario-management-controls\"><b>Scenario management controls</b></a></li>" else: chart_part = "../" if element_category == "chart" else "" repl += f"<li><a href=\"{chart_part}..\"><b>Visual Elements</b></a></li>" repl += (f"<li><a href=\"{chart_part}../blocks\"><b>Blocks</b></a></li>" if element_category == "blocks" else f"<li><a href=\"{chart_part}../controls/#standard-controls\"><b>Standard controls</b></a></li>") if chart_part: repl += f"<li><a href=\"{chart_part}../chart\"><b>Charts</b></a></li>" repl += "</ul>" html_content = (html_content[:article_match.start()] + article_match.group(1) + repl + article_match.group(2) + html_content[article_match.end():]) file_was_changed = True # Processing for the page builder API: fn_match = re.search(r"(/|\\)reference\1taipy\.gui\.builder.(.*?)\1index.html", filename) if fn_match is not None: element_name = fn_match[2] # Default value of properties appear as "dynamic(type" as "indexed(type" prop_re = re.compile(r"<tr>\s*<td><code>.*?</code></td>" + r"\s*<td>\s*<code>(.*?)</code>\s*</td>\s*<td>", re.S) new_content = "" last_location = 0 for prop in prop_re.finditer(html_content): if default_value_re := re.match(r"(dynamic|indexed)\((.*)", prop[1]): new_content += html_content[last_location:prop.start(1)] new_content += f"{default_value_re[2]}<br/><small><i>{default_value_re[1]}</i></small>" last_location = prop.end(1) if last_location: file_was_changed = True html_content = new_content + html_content[last_location:] # '<i>default value</i>' -> <i>default value</i> dv_re = re.compile(r"&\#39;<i>(.*?)</i>&\#39;", re.S) new_content = "" last_location = 0 for dv in dv_re.finditer(html_content): new_content += html_content[last_location:dv.start()] + f"<i>{dv[1]}</i>" last_location = dv.end() if last_location: file_was_changed = True html_content = new_content + html_content[last_location:] # Handle title and header in packages documentation file FONT_SIZE_CHANGE='' def code(s: str) -> str: return f"<code><font size='+2'>{s}</font></code>" fn_match = re.search(r"manuals(/|\\)reference\1pkg_taipy\1index.html", filename) if fn_match is not None: # The root 'taipy' package html_content = re.sub(f"(<h1>)taipy(</h1>)", f"\\1{code('taipy')}\\2", html_content) file_was_changed = True fn_match = re.search(r"manuals(/|\\)reference\1pkg_taipy(\..*)\1index.html", filename) if fn_match is not None: pkg = fn_match[2] sub_match = re.search(r"(\.\w+)(\..*)", pkg) if sub_match is None: html_content = re.sub(f"(<title>)Index\\s", f"\\1taipy{pkg} ", html_content) html_content = re.sub(f"(<h1>)Index(</h1>)", f"\\1{code('taipy'+pkg)}\\2", html_content) html_content = re.sub(f"(<h1>){pkg}(</h1>)", f"\\1{code('taipy'+pkg)}\\2", html_content) else: html_content = re.sub(f"(<title>)({sub_match[2]})\\s", f"\\1taipy{sub_match[1]}\\2 ", html_content) html_content = re.sub(f"(<h1>)(?:<code>){sub_match[2]}(?:</code>)(</h1>)", f"\\1{code('taipy'+pkg)}\\2", html_content) file_was_changed = True if file_was_changed: with open(filename, "w") as html_file: html_file.write(html_content) # Replace path to doc in '.ipynb' files elif f.endswith(".ipynb"): filename = os.path.join(root, f) with open(filename) as ipynb_file: try: content = ipynb_file.read() except Exception as e: print(f"Couldn't read Notebook file {filename}") raise e (new_content, n) = re.subn("(?<=https://docs.taipy.io/en/)latest", f"{env.conf['branch']}", content) if n > 0: with open(filename, "w") as ipynb_file: ipynb_file.write(new_content) if fixed_cross_refs: for dest in sorted(fixed_cross_refs.keys()): sources = ", ".join(sorted(fixed_cross_refs[dest])) log.info(f"FIXED cross-ref to '{dest}' from {sources}") # ################################################################################ # Functions that are used in the postprocessing phase. # I wish we could move them elsewhere, but couldn't figure out how # ################################################################################ def process_data_source_attr(html: str, env): _DATASOURCE_RE = re.compile(r"(<(h\d+))\s+data-source=\"(.*?)\"(.*</\2>)") new_content = "" last_location = 0 for m in _DATASOURCE_RE.finditer(html): ref = m.group(3) repo_m = re.search(r"^([\w\d]+):", ref) if repo_m: ref = ("https://github.com/Avaiga/taipy-" + f"{repo_m.group(0)[:-1]}/blob/{env.conf['branch']}/{ref[repo_m.end():]}") new_content += (html[last_location:m.start()] + f"{m.group(1)}{m.group(4)}" + f"\n<small>You can download the entire source code used in this " + f"section from the <a href=\"{ref}\">GitHub repository</a>.</small>" ) last_location = m.end() if last_location: return (True, new_content + html[last_location:]) else: return (False, None) def process_links_to_github(html: str, env): _LINK_RE = re.compile(r"(?<=href=\"https://github.com/Avaiga/)(taipy-gui/tree/)\[BRANCH\](.*?\")") new_content = "" last_location = 0 for m in _LINK_RE.finditer(html): new_content += html[last_location:m.start()] + m.group(1) + env.conf['branch'] + m.group(2) last_location = m.end() if last_location: return (True, new_content + html[last_location:]) else: return (False, None) |
import os import re import logging SITE_DIR = "site" def to_unix(p): return p.replace("\\","/") # Assuming that this script is located in <taipy-doc>/tools tools_dir = os.path.dirname(__file__) site_path = os.path.join(os.path.dirname(tools_dir), SITE_DIR) ref_site_path = to_unix(site_path) logger = logging.getLogger("taipy-doc-checker") logging.basicConfig(level=logging.INFO) logger.info(f"Site: {site_path}") if not os.path.isdir(site_path): logger.critical("Site does not exist. Please run 'mkdocs build' first.") exit(1) A_RE = re.compile(r"<a href=\"(.*?)\"") for root, _, file_list in os.walk(site_path): this_dir = to_unix(root) for f in file_list: if f.endswith(".html"): filename = to_unix(os.path.join(root, f)) ref_filename = filename[len(ref_site_path):] with open(filename) as html_file: ref_root = to_unix(root) try: html_content = html_file.read() for anchor in A_RE.finditer(html_content): href = anchor.group(1) if href.startswith("/en/develop/"): href = href[12:] if href != "." and href != ".." and not href.startswith("http") and not href.startswith("mailto"): if href.startswith("#"): id=href[1:] if not id in html_content: logger.error(f"No id {id} in {ref_filename}") else: if href.endswith("/"): target = to_unix(os.path.join(ref_root, href))[:-1] if not os.path.isdir(target) or not os.path.isfile(target + "/index.html"): logger.error(f"Bad xref '{href}' in {ref_filename}") except Exception as e: logger.error(f"Couldn't read HTML file {filename}") raise e |
""" Check that parameters' documentation have a uniform format. - `<param_name>`: [The |A |An ]*. """ import sys COMMENTS_CAN_START_WITH = ' The ', ' If ', ' An ', ' A ', ' TODO ' filename = sys.argv[1] for line in open(filename).readlines(): if line.replace(' ', '').startswith('-`') and ':' in line: try: variable, comment = line.split(':', maxsplit=1) assert variable.endswith(' ') is False # Too early for this # ------------------ # assert any(comment.startswith(x) for x in COMMENTS_CAN_START_WITH) # if not comment.startswith(" TODO "): # assert comment[-1] == '.' or comment[-2] == '.' except Exception as _: print(f"Error in file '{filename}': '{line}'") exit(1) |
# ################################################################################ # Taipy REST API Reference Manual generation setup step. # # A Taipy REST server is created and the API is queries dynamically. # Then documentation pages are generated from the retrieved structure. # ################################################################################ from .setup import Setup, SetupStep class RestRefManStep(SetupStep): def __init__(self): self.navigation = None def get_id(self) -> str: return "rest" def get_description(self) -> str: return "Generation of the REST API Reference Manual pages" def enter(self, setup: Setup): self.navigation = None def setup(self, setup: Setup) -> None: setup.move_package_to_tools(Setup.ROOT_PACKAGE) try: self.generate_rest_refman_pages(setup) except Exception as e: raise e finally: setup.move_package_to_root(Setup.ROOT_PACKAGE) def generate_rest_refman_pages(self, setup: Setup): REST_REF_DIR_PATH = setup.manuals_dir + "/reference_rest" from taipy.rest.app import create_app as rest_create_app app = rest_create_app() from taipy.rest.extensions import apispec as rest_apispec with app.app_context(): rest_specs = rest_apispec.swagger_json().json self.navigation = "" path_descs = { "cycle": "Entry points that interact with `Cycle^` entities.", "scenario": "Entry points that interact with `Scenario^` entities.", "sequence": "Entry points that interact with `Sequence^` entities.", "datanode": "Entry points that interact with `DataNode^` entities.", "task": "Entry points that interact with `Task^` entities.", "job": "Entry points that interact with `Job^` entities.", "auth": "Entry points that deal with authentication.", } path_files = {} enterprise_paths = ["auth"] response_statuses = { "200": ("OK", "https://httpwg.org/specs/rfc7231.html#status.200"), "201": ("Created", "https://httpwg.org/specs/rfc7231.html#status.201"), "202": ("Accepted", "https://httpwg.org/specs/rfc7231.html#status.202"), "204": ("No Content", "https://httpwg.org/specs/rfc7231.html#status.204"), "401": ("Unauthorized", "https://httpwg.org/specs/rfc7235.html#status.401"), "404": ("Not Found", "https://httpwg.org/specs/rfc7231.html#status.404"), } def get_property_type(property_desc, from_schemas): type_name = property_desc.get("type", None) a_pre = "" a_post = "" if type_name == "array": property_desc = property_desc["items"] type_name = property_desc.get("type", None) a_pre = "\\[" a_post = "\\]" if type_name is None: type_name = property_desc.get("$ref", None) if type_name is None: # print(f"WARNING - No type...") return "" type_name = type_name[type_name.rfind("/") + 1 :] prefix = "" if from_schemas else "schemas.md" type_name = f"[`{type_name}`]({prefix}#{type_name.lower()})" return f"{a_pre}{type_name}{a_post}" for path, desc in rest_specs["paths"].items(): dest_path = None dest_path_desc = None for p, d in path_descs.items(): if f"/{p}" in path: dest_path = p dest_path_desc = d break if dest_path is None: print(f"Path {path} has no paths bucket") continue file = path_files.get(dest_path) if file is None: file = open(f"{REST_REF_DIR_PATH}/apis_{dest_path}.md", "w") if dest_path in enterprise_paths: file.write(Setup.ENTERPRISE_BANNER) file.write(f"{dest_path_desc}\n\n") self.navigation += f"- \"Paths for {dest_path}\": manuals/reference_rest/apis_{dest_path}.md\n" path_files[dest_path] = file file.write(f"# `{path}`\n\n") for method, method_desc in desc.items(): file.write(f"## {method.upper()}\n\n") file.write(f"{method_desc['description']}\n\n") parameters = method_desc.get("parameters") if parameters is not None: file.write(f"<h4>Parameters</h4>\n\n") file.write("|Name|Type|Required|Description|\n") file.write("|---|---|---|---|\n") for param in parameters: param_type = "TODO" if "schema" in param and len(param["schema"]) == 1: param_type = param["schema"]["type"] file.write( f"|{param['name']}|{param_type}|{'Yes' if param['name'] else 'No'}|{param.get('description', '-')}|\n" ) file.write("\n") request_body = method_desc.get("requestBody") if request_body is not None: file.write(f'<div><h4 style="display: inline-block;">Request body:</h4>\n') schema = request_body["content"]["application/json"]["schema"]["$ref"] schema = schema[schema.rfind("/") + 1 :] file.write(f'<span><a href="schemas.md#{schema.lower()}">{schema}</a></div>\n\n') responses = method_desc.get("responses") if responses is not None: file.write(f"<h4>Responses</h4>\n\n") for response, response_desc in responses.items(): file.write(f"- <b><code>{response}</code></b><br/>\n") status = response_statuses[response] file.write(f" Status: [`{status[0]}`]({status[1]})\n\n") description = response_desc.get("description") if description is not None: file.write(f" {description}\n") content = response_desc.get("content", None) if content is not None: schema = content["application/json"]["schema"] allOf = schema.get("allOf") if allOf is not None: schema = allOf[0] properties = schema.get("properties") if properties is not None: file.write(" |Name|Type|\n") file.write(" |---|---|\n") for property, property_desc in properties.items(): file.write(f" |{property}|{get_property_type(property_desc, False)}|\n") else: print(f"No properties in content in response {response} in method {method} of {path}") elif response != "404": print(f"No content in response {response} in method {method} of {path}") file.write("\n") for f in path_files.values(): f.close() with open(f"{REST_REF_DIR_PATH}/schemas.md", "w") as file: for schema, schema_desc in rest_specs["components"]["schemas"].items(): properties = schema_desc.get("properties") if properties is not None: file.write(f"## {schema}\n\n") file.write("|Name|Type|Description|\n") file.write("|---|---|---|\n") for property, property_desc in properties.items(): file.write(f"|{property}|{get_property_type(property_desc, True)}|-|\n") file.write("\n") self.navigation += "- \"Schemas\": manuals/reference_rest/schemas.md\n" def exit(self, setup: Setup): setup.update_mkdocs_yaml_template( r"^\s*\[REST_REFERENCE_CONTENT\]\s*\n", self.navigation if self.navigation else "" ) |
from .setup import run_setup |
# ################################################################################ # Taipy GUI Extension Reference Manual generation setup step. # # The Reference Manual pages for the Taipy GUI JavaScript extension module # is generated using the typedoc tools, directly from the JavaScript # source files. # ################################################################################ from .setup import Setup, SetupStep import os import re import shutil import subprocess class GuiExtRefManStep(SetupStep): def get_id(self) -> str: return "guiext" def get_description(self) -> str: return "Generating the GUI Extension API documentation" def enter(self, setup: Setup): self.GUI_EXT_REF_DIR_PATH = setup.manuals_dir + "/reference_guiext" if os.path.exists(self.GUI_EXT_REF_DIR_PATH): shutil.rmtree(self.GUI_EXT_REF_DIR_PATH) npm_path = shutil.which("npm") if npm_path: if " " in npm_path: npm_path = f"\"{npm_path}\"" try: subprocess.run(f"{npm_path} --version", shell=True, capture_output=True) except OSError: print(f"WARNING: Couldn't run npm, ignoring this step.", flush=True) npm_path = None self.npm_path = npm_path def setup(self, setup: Setup) -> None: if self.npm_path: saved_cwd = os.getcwd() gui_path = os.path.join(setup.root_dir, "gui") os.chdir(gui_path) print(f"... Installing node modules...", flush=True) subprocess.run(f"{self.npm_path} run inst", shell=True) print(f"... Generating documentation...", flush=True) subprocess.run(f"{self.npm_path} run mkdocs", shell=True) # Process and copy files to docs/manuals os.mkdir(self.GUI_EXT_REF_DIR_PATH) dst_dir = os.path.abspath(self.GUI_EXT_REF_DIR_PATH) src_dir = os.path.abspath(os.path.join(gui_path, "reference_guiext")) JS_EXT_RE = re.compile(r"^(.*?)(\n#.*?\n)", re.MULTILINE | re.DOTALL) for root, dirs, files in os.walk(src_dir): for file in files: file_content = None path_name = os.path.join(root, file) with open(path_name) as input: file_content = input.read() match = JS_EXT_RE.search(file_content) if match: file_content = match.group(2) + match.group(1) + file_content[match.end():] path_name = path_name.replace(src_dir, dst_dir) with open(path_name, "w") as output: output.write(file_content) for dir in dirs: os.mkdir(os.path.join(dst_dir, dir)) os.chdir(saved_cwd) |
# ################################################################################ # Taipy Reference Manual generation setup step. # # Generate the entries for every documented class, method, and function. # This scripts browses the root package (Setup.ROOT_PACKAGE) and builds a # documentation file for every package and every class it finds. # It finally updates the top navigation bar content (in mkdocs.yml) to # reflect the root package structure. # ################################################################################ import json import os import re import shutil from inspect import isclass, isfunction, ismodule from .setup import Setup, SetupStep class RefManStep(SetupStep): # Package grouping (order is kept in generation) PACKAGE_GROUPS = [ "taipy.config", "taipy.core", "taipy.gui", "taipy.gui_core", "taipy.rest", "taipy.auth", "taipy.enterprise", ] # Entries that should be hidden for the time being HIDDEN_ENTRIES = ["get_context_id", "invoke_state_callback"] # Where the Reference Manual files are generated (MUST BE relative to docs_dir) REFERENCE_REL_PATH = "manuals/reference" def __init__(self): self.navigation = None def get_id(self) -> str: return "refman" def get_description(self) -> str: return "Generation of the Reference Manual pages" def enter(self, setup: Setup): os.environ["GENERATING_TAIPY_DOC"] = "true" self.REFERENCE_DIR_PATH = os.path.join(setup.docs_dir, RefManStep.REFERENCE_REL_PATH) self.XREFS_PATH = os.path.join(setup.manuals_dir, "xrefs") def setup(self, setup: Setup) -> None: # Clean REFERENCE_DIR_PATH directory for p in os.listdir(self.REFERENCE_DIR_PATH): fp = os.path.join(self.REFERENCE_DIR_PATH, p) if re.match("^(pkg_)?taipy(\..*)?\.md$", p): os.remove(fp) elif os.path.isdir(fp) and re.match("^pkg_taipy(\..*)?$", p): shutil.rmtree(fp) saved_dir = os.getcwd() try: os.chdir(setup.tools_dir) if not os.path.isdir(os.path.join(setup.tools_dir, Setup.ROOT_PACKAGE)): setup.move_package_to_tools(Setup.ROOT_PACKAGE) self.generate_refman_pages(setup) except Exception as e: raise e finally: os.chdir(saved_dir) setup.move_package_to_root(Setup.ROOT_PACKAGE) def generate_refman_pages(self, setup: Setup) -> None: CLASS_ID = "C" FUNCTION_ID = "F" TYPE_ID = "T" FIRST_DOC_LINE_RE = re.compile(r"^(.*?)(:?\n\s*\n|$)", re.DOTALL) REMOVE_LINE_SKIPS_RE = re.compile(r"\s*\n\s*", re.MULTILINE) loaded_modules = set() # Entries: # full_entry_name -> # name # module (source) # type # doc # packages entries: dict[str, dict[str, any]] = {} module_doc = {} def read_module(module): if module in loaded_modules: return loaded_modules.add(module) if not module.__name__.startswith(Setup.ROOT_PACKAGE): return entry: str for entry in dir(module): # Private? if entry.startswith("_"): continue e = getattr(module, entry) if hasattr(e, "__class__") and e.__class__.__name__.startswith("_"): continue entry_type: str = None if hasattr(e, "__module__") and e.__module__: # Handling alias Types if e.__module__.startswith(Setup.ROOT_PACKAGE): # For local build if e.__class__.__name__ == "NewType": entry_type = TYPE_ID elif e.__module__ == "typing" and hasattr(e, "__name__"): # For Readthedoc build # Manually remove class from 'typing' if e.__name__ == "NewType": continue # Manually remove function from 'typing' if e.__name__ == "overload": continue entry_type = TYPE_ID else: continue # Remove hidden entries if entry in RefManStep.HIDDEN_ENTRIES: continue # Not a function or a class? if not entry_type: if isclass(e): entry_type = CLASS_ID elif isfunction(e): entry_type = FUNCTION_ID elif ismodule(e): module_doc[e.__name__] = e.__doc__ read_module(e) if not entry_type: continue # Add to all entries doc = e.__doc__ if doc: first_line = FIRST_DOC_LINE_RE.match(doc.strip()) if first_line: if first_line.group(0).startswith("NOT DOCUMENTED"): continue doc = REMOVE_LINE_SKIPS_RE.subn(" ", first_line.group(0))[0].strip() else: print( f"WARNING - Couldn't extract doc summary for {e.__name__} in {e.__module__}", flush=True, ) full_name = f"{e.__module__}.{entry}" # Entry module: e.__module__ # Current module: module.__name__ if entry_info := entries.get(full_name): packages = entry_info["packages"] if module.__name__ != Setup.ROOT_PACKAGE: # Is current module a parent of known packages? Use that instead if yes child_idxs = [i for i, p in enumerate(packages) if p.startswith(module.__name__)] if child_idxs: for index in reversed(child_idxs): del packages[index] packages.append(module.__name__) else: # Is any known package a parent of the current module? If yes ignore it parent_idxs = [i for i, p in enumerate(packages) if module.__name__.startswith(p)] if not parent_idxs: packages.append(module.__name__) else: if doc is None: print(f"WARNING - {e.__name__} [in {e.__module__}] has no doc", flush=True) entries[full_name] = { "name": entry, "module": e.__module__, "type": entry_type, "doc": doc, "packages": [module.__name__], } if module.__name__ == Setup.ROOT_PACKAGE: entry = entries[full_name] entry["at_root"] = True if Setup.ROOT_PACKAGE in entry["packages"]: entry["packages"].remove(Setup.ROOT_PACKAGE) taipy_config_dir = os.path.join(setup.tools_dir, "taipy", "config") config_backup_path = os.path.join(taipy_config_dir, "config.py.bak") if os.path.exists(config_backup_path): shutil.move(config_backup_path, os.path.join(taipy_config_dir, "config.py")) read_module(__import__(Setup.ROOT_PACKAGE)) # Compute destination package for each entry for entry, entry_desc in entries.items(): doc_package = None # Where this entity should be exposed module = entry_desc["module"] packages = entry_desc["packages"] # If no packages, it has to be at the root level if not packages: if not entry_desc.get("at_root", False): raise SystemError(f"FATAL - Entry '{entry}' has no package, and not in root") doc_package = Setup.ROOT_PACKAGE else: # If visible from a package above entry module, pick this one parents = list(filter(lambda p: module.startswith(p), packages)) if len(parents) > 1: raise SystemError( "FATAL - Entry '{entry}' has several matching parent packages ([packages])" ) elif len(parents) == 0: if len(packages) == 1: doc_package = packages[0] else: package_groups = list(filter(lambda p: p in RefManStep.PACKAGE_GROUPS, packages)) if len(package_groups) == 1: doc_package = package_groups[0] else: doc_package = parents[0] if doc_package is None: raise SystemError(f"FATAL - Entry '{entry}' has no target package") entry_desc["doc_package"] = doc_package # Group entries by package package_to_entries = {} for entry, info in entries.items(): package = info["doc_package"] if package in package_to_entries: package_to_entries[package].append(info) else: package_to_entries[package] = [info] # Add taipy packages with documentation but no entry for package, doc in module_doc.items(): if not package.startswith("taipy"): continue if package in package_to_entries: continue if not doc: continue package_to_entries[package] = {} # Generate all Reference manual pages and update navigation self.navigation = "" xrefs = {} package_group = None for package in sorted(package_to_entries.keys()): functions = [] classes = [] types = [] for entry_info in package_to_entries[package]: if entry_info["type"] == CLASS_ID: classes.append(entry_info) elif entry_info["type"] == FUNCTION_ID: functions.append(entry_info) elif entry_info["type"] == TYPE_ID: types.append(entry_info) else: raise SystemError( "FATAL - Invalid entry type '{entry_info['type']}' for {entry_info['module']}.{entry_info['name']}" ) if package in RefManStep.PACKAGE_GROUPS: package_group = package package_path = f"{self.REFERENCE_DIR_PATH}/pkg_{package}" os.mkdir(package_path) package_output_path = os.path.join(package_path, "index.md") self.navigation += ( f"- \"<code>{package}</code>\":\n - {RefManStep.REFERENCE_REL_PATH}/pkg_{package}/index.md\n" ) else: high_package_group = None for p in RefManStep.PACKAGE_GROUPS: if package.startswith(p + "."): high_package_group = p break if high_package_group != package_group: if not high_package_group: raise SystemExit( f"FATAL - Unknown package '{high_package_group}' for package '{package}' (renamed from '{package_group}')" ) package_group = high_package_group self.navigation += f"- {package_group}:\n" package_nav_entry = package if package_group: self.navigation += " " package_nav_entry = package[len(package_group):] self.navigation += f"- \"<code>{package_nav_entry}</code>\": {RefManStep.REFERENCE_REL_PATH}/pkg_{package}.md\n" package_output_path = os.path.join( self.REFERENCE_DIR_PATH, f"pkg_{package}.md" ) package_output_path = os.path.join(self.REFERENCE_DIR_PATH, f"pkg_{package}.md") def update_xrefs(name, type, force_package, module, others): if not others: print(f"{name}") pass # xrefs: # entry_name <-> [ exposed_package, entry_module, other_packages] # or # name <-> <number of similar entries> (int) # + entry_name/<index> <-> [ exposed_package, entry_module, other_packages] type_name = "Function" if type == FUNCTION_ID else "Class" if type == CLASS_ID else "Type" if xref := xrefs.get(name): if force_package == xref[0]: raise SystemError( f"FATAL - - {type_name} {name} exposed in {force_package} already declared as {xref[0]}.{xref[1]}" ) print(f"NOTE: duplicate entry {name} - {xref[0]}/{force_package}") #print(f"WARNING - {'Function' if type == FUNCTION_ID else 'Class'} {name} already declared as {xref[0]}.{xref[1]}") xref_array = [] if isinstance(xref, int): # If there already are duplicates for index in range(0..int(xref)): xref = xrefs.get(f"{name}/{index}") if force_package == xref[0]: raise SystemError( "FATAL - - {type_name} {name} exposed in {force_package} already declared as {xref[0]}.{xref[1]}" ) xrefs[f"{name}/{index}"] = [ force_package, module, others ] else: # Create multiple indexed entries for 'name' xrefs[name] = 2 xrefs[f"{name}/0"] = xref xrefs[f"{name}/1"] = [ force_package, module, others ] else: xrefs[name] = [force_package, module, others ] def generate_entries(entry_infos, package, type, package_output_file, in_group): in_group = "../" if in_group else "" for entry_info in sorted(entry_infos, key=lambda i: i["name"]): name = entry_info["name"] force_package = entry_info.get("force_package", package) package_output_file.write( f" - [`{name}" + f"{'()' if type == FUNCTION_ID else ''}`]({in_group}{force_package}.{name}.md)" + f"{': ' + entry_info['doc'] if entry_info['doc'] else ' - NOT DOCUMENTED'}\n" ) output_path = os.path.join(self.REFERENCE_DIR_PATH, f"{force_package}.{name}.md") with open(output_path, "w") as output_file: output_file.write("---\nhide:\n - navigation\n---\n\n" + f"::: {force_package}.{name}\n") update_xrefs(name, type, force_package, entry_info["module"], entry_info["packages"]) with open(package_output_path, "w") as package_output_file: if package in module_doc and module_doc[package]: package_output_file.write(module_doc[package]) package_grouped = package == package_group if types: package_output_file.write(f"## Types\n\n") for type in types: name = type["name"] package_output_file.write(f" - `{name}`" + f"{': ' + type.get('doc', ' - NOT DOCUMENTED')}\n") update_xrefs(name, TYPE_ID, package, entry_info["module"], entry_info.get("packages")) if functions: package_output_file.write(f"## Functions\n\n") generate_entries( functions, package, FUNCTION_ID, package_output_file, package_grouped, ) if classes: package_output_file.write(f"## Classes\n\n") generate_entries(classes, package, CLASS_ID, package_output_file, package_grouped) self.add_external_methods_to_config_class(setup) # Filter out packages that are the exposed package and appear in the packages list for entry, entry_desc in xrefs.items(): if not isinstance(entry_desc, int): package = entry_desc[0] if entry_desc[2]: entry_desc[2] = [p for p in entry_desc[2] if p != package] with open(self.XREFS_PATH, "w") as xrefs_output_file: xrefs_output_file.write(json.dumps(xrefs)) @staticmethod def add_external_methods_to_config_class(setup: Setup): if not os.path.exists("config_doc.txt"): print(f"WARNING - No methods found to inject to Config documentation!") return # Get code of methods to inject with open("config_doc.txt", "r") as f: print(f"INFO - Injecting methods to Config documentation.") methods_to_inject = f.read() # Delete temporary file if os.path.exists("config_doc.txt"): os.remove("config_doc.txt") # Backup file taipy/config/config.py taipy_config_dir = os.path.join(setup.tools_dir, "taipy", "config") config_path = os.path.join(taipy_config_dir, "config.py") shutil.copyfile(config_path, os.path.join(taipy_config_dir, "config.py.bak")) # Read config.py file with open(config_path, "r") as f: contents = f.readlines() # Inject imports and code imports_to_inject = """ from types import NoneType from typing import Any, Callable, Dict, List, Union, Optional import json from .common.scope import Scope from .common.frequency import Frequency from taipy.core.common.mongo_default_document import MongoDefaultDocument from taipy.core.config.job_config import JobConfig from taipy.core.config.data_node_config import DataNodeConfig from taipy.core.config.task_config import TaskConfig from taipy.core.config.scenario_config import ScenarioConfig from taipy.core.config.sequence_config import SequenceConfig\n""" contents.insert(11, imports_to_inject) contents.insert(len(contents) - 2, methods_to_inject) # Fix code injection with open(config_path, "w") as f: new_content = "".join(contents) new_content = new_content.replace( "custom_document: Any = <class 'taipy.core.common.mongo_default_document.MongoDefaultDocument'>", "custom_document: Any = MongoDefaultDocument", ) new_content = new_content.replace("taipy.config.common.scope.Scope", "Scope") new_content = new_content.replace("<Scope.SCENARIO: 2>", "Scope.SCENARIO") new_content = new_content.replace("taipy.core.config.data_node_config.DataNodeConfig", "DataNodeConfig") new_content = new_content.replace("taipy.core.config.task_config.TaskConfig", "TaskConfig") new_content = new_content.replace("taipy.core.config.sequence_config.SequenceConfig", "SequenceConfig") new_content = new_content.replace("taipy.config.common.frequency.Frequency", "Frequency") f.write(new_content) def exit(self, setup: Setup): setup.update_mkdocs_yaml_template(r"^\s*\[REFERENCE_CONTENT\]\s*\n", self.navigation if self.navigation else "") if "GENERATING_TAIPY_DOC" in os.environ: del os.environ["GENERATING_TAIPY_DOC"] |
from abc import ABC, abstractmethod from datetime import datetime import re import shutil import sys from typing import List class Setup(ABC): ROOT_PACKAGE = "taipy" ENTERPRISE_BANNER = """!!! warning "Available in Taipy Enterprise edition" This section is relevant only to the Enterprise edition of Taipy. """ def __init__(self, root_dir: str, steps: List["SetupStep"]): self.root_dir = root_dir.replace("\\", "/") self.docs_dir = self.root_dir + "/docs" self.manuals_dir = self.docs_dir + "/manuals" self.tools_dir = self.root_dir + "/tools" # self.requested_steps, if not None, indicates which steps should be performed. self.requested_steps = None if len(sys.argv) > 1: self.requested_steps = [] for step_id in sys.argv[1:]: if not [step for step in steps if step_id == step.get_id()]: raise SystemError(f"FATAL - '{step_id}' is not a valid step identifier") for step in steps: if step.get_id() in sys.argv[1:]: self.requested_steps.append(step) self.mkdocs_yml_template_content = None self.MKDOCS_YML_PATH = self.root_dir + "/mkdocs.yml" self.MKDOCS_YML_TEMPLATE_PATH = self.MKDOCS_YML_PATH + "_template" with open(self.MKDOCS_YML_TEMPLATE_PATH) as mkdocs_yml_file: self.mkdocs_yml_template_content = mkdocs_yml_file.read() if not self.mkdocs_yml_template_content: raise SystemError( "FATAL - Could not read MkDocs template configuration file at {MKDOCS_YML_TEMPLATE_PATH}" ) self.steps = [] for step in steps: if not self.requested_steps or step in self.requested_steps: self.steps.append(step) step.enter(self) else: step.exit(self) def setup(self): n_steps = len(self.steps) line = "+" + "-" * 60 for step_index, step in enumerate(self.steps): description = step.get_description() if description: description = f": {description}" print(f"{line}\n| Step {step_index + 1}/{n_steps}{description}\n{line}", flush=True) step.setup(self) def exit(self): for step in self.steps: step.exit(self) self.update_mkdocs_yaml_template(r"\[YEAR\]", f"{str(datetime.now().year)}") with open(self.MKDOCS_YML_PATH, "w") as mkdocs_yml_file: mkdocs_yml_file.write(self.mkdocs_yml_template_content) # Utility function to update the MkDocs yml template file def update_mkdocs_yaml_template(self, pattern: str, replacement: str): # Retrieve and keep indendation if pattern.startswith(r"^\s*"): pattern = r"^(\s*)" + pattern[4:] lines = replacement.split("\n") if not lines[-1]: lines = lines[:-1] replacement = "\n".join(map(lambda s: r"\1"+s, lines))+"\n" self.mkdocs_yml_template_content = re.sub( pattern, replacement if replacement else "", self.mkdocs_yml_template_content, flags=re.MULTILINE | re.DOTALL, ) # Move the top package directory to 'tools' when generating the Reference # Manual, or when using Taipy classes. # MkDocs needs it at the root level so we will have to move it back. def move_package_to_tools(self, package: str) -> None: shutil.move(f"{self.root_dir}/{package}", f"{self.tools_dir}/{package}") def move_package_to_root(self, package: str) -> None: shutil.move(f"{self.tools_dir}/{package}", f"{self.root_dir}/{package}") class SetupStep(ABC): @abstractmethod def get_id(self) -> str: return "" def get_description(self) -> str: return "" def enter(self, setup: Setup): pass def exit(self, setup: Setup): """Called after the step is executed. Note that this member function is also called, before _enter()_, if this step is skipped. """ pass @abstractmethod def setup(self, setup: Setup): pass def run_setup(root_dir: str, steps: List[SetupStep] = None): if not steps: from .step_viselements import VisElementsStep from .step_refman import RefManStep from .step_rest_refman import RestRefManStep from .step_gui_ext_refman import GuiExtRefManStep from .step_contributors import ContributorsStep steps = [ VisElementsStep(), RefManStep(), RestRefManStep(), GuiExtRefManStep(), ContributorsStep() ] setup = Setup(root_dir, steps) setup.setup() setup.exit() |
# ################################################################################ # Taipy GUI Visual Elements documentation. # # This includes the update of the Table of Contents for both the controls # and the blocks document pages. # # For each visual element, this script combines its property list and core # documentation, and generates full Markdown files in [VISELEMENTS_DIR_PATH]. All # these files ultimately get integrated in the global doc set. # # The skeleton documentation files # [VISELEMENTS_DIR_PATH]/[controls|blocks].md_template # are also completed with generated table of contents. # ################################################################################ import json import os import re import sys from typing import Dict, List, Optional from .setup import Setup, SetupStep from io import StringIO class VisElementsStep(SetupStep): DEFAULT_PROPERTY = "default_property" PROPERTIES = "properties" NAME = "name" INHERITS = "inherits" def get_id(self) -> str: return "viselements" def get_description(self) -> str: return "Extraction of the visual elements documentation" def enter(self, setup: Setup): self.VISELEMENTS_DIR_PATH = setup.manuals_dir + "/gui/viselements" self.CORELEMENTS_DIR_PATH = setup.manuals_dir + "/gui/corelements" self.controls_path = f"{self.VISELEMENTS_DIR_PATH}/controls.md" template_path = f"{self.controls_path}_template" if not os.access(template_path, os.R_OK): raise FileNotFoundError( f"FATAL - Could not read {template_path} Markdown template" ) self.blocks_path = f"{self.VISELEMENTS_DIR_PATH}/blocks.md" template_path = f"{self.blocks_path}_template" if not os.access(template_path, os.R_OK): raise FileNotFoundError( f"FATAL - Could not read {template_path} Markdown template" ) self.charts_home_html_path = ( self.VISELEMENTS_DIR_PATH + "/charts/home.html_fragment" ) if not os.access(self.charts_home_html_path, os.R_OK): raise FileNotFoundError( f"FATAL - Could not read {self.charts_home_html_path} html fragment" ) # Load Taipy GUI and Taipy elements # ----------------------------------------------------------- # Load elements, check basic features and resolve inheritance def load_elements( self, elements_json_path: str, prefix: str, doc_pages_path: str ) -> None: with open(elements_json_path) as elements_json_file: loaded_elements = json.load(elements_json_file) new_elements = {} for category, elements in loaded_elements.items(): if category not in self.categories: self.categories[category] = [] for element in elements: element_type = element[0] self.categories[category].append(element_type) if element_type in self.elements: raise ValueError( f"FATAL - Duplicate element type '{element_type}' in {elements_json_path}" ) element_desc = element[1] if ( not __class__.PROPERTIES in element_desc and not __class__.INHERITS in element_desc ): raise ValueError( f"FATAL - No properties in element type '{element_type}' in {elements_json_path}" ) element_desc["prefix"] = prefix element_desc["doc_path"] = doc_pages_path element_desc["source"] = elements_json_path new_elements[element_type] = element_desc self.elements.update(new_elements) # Find default property for all element types for element_type, element_desc in new_elements.items(): default_property = None if properties := element_desc.get(__class__.PROPERTIES, None): for property in properties: if __class__.DEFAULT_PROPERTY in property: if property[__class__.DEFAULT_PROPERTY]: default_property = property[__class__.NAME] del property[__class__.DEFAULT_PROPERTY] element_desc[__class__.DEFAULT_PROPERTY] = default_property # Resolve inheritance def merge( element_desc, parent_element_desc, default_property: str ) -> Optional[str]: element_properties = element_desc.get(__class__.PROPERTIES, []) element_property_names = [p[__class__.NAME] for p in element_properties] for property in parent_element_desc.get(__class__.PROPERTIES, []): property_name = property[__class__.NAME] if property_name in element_property_names: element_property = element_properties[ element_property_names.index(property_name) ] for n in ["type", "default_value", "doc"]: if not n in element_property and n in property: element_property[n] = property[n] else: element_property_names.append(property_name) element_properties.append(property) element_desc[__class__.PROPERTIES] = element_properties if not default_property and parent_element_desc.get( __class__.DEFAULT_PROPERTY, False ): default_property = parent_element_desc[__class__.DEFAULT_PROPERTY] return default_property def resolve_inheritance(element_desc): if parent_types := element_desc.get(__class__.INHERITS, None): del element_desc[__class__.INHERITS] original_default_property = element_desc[__class__.DEFAULT_PROPERTY] default_property = original_default_property for parent_type in parent_types: parent_desc = self.elements[parent_type] resolve_inheritance(parent_desc) default_property = merge( element_desc, parent_desc, default_property ) if original_default_property != default_property: element_desc[__class__.DEFAULT_PROPERTY] = default_property for element_desc in self.elements.values(): resolve_inheritance(element_desc) self.elements = {} self.categories = {} load_elements( self, setup.root_dir + "/taipy/gui/viselements.json", "", self.VISELEMENTS_DIR_PATH, ) load_elements( self, setup.root_dir + "/taipy/gui_core/viselements.json", "core_", self.CORELEMENTS_DIR_PATH, ) # Check that documented elements have a default property and a doc file, # and that their properties have the mandatory settings. for category, element_type in [ (c, e) for c, elts in self.categories.items() for e in elts ]: if category == "undocumented": continue element_desc = self.elements[element_type] if not __class__.DEFAULT_PROPERTY in element_desc: raise ValueError( f"FATAL - No default property for element type '{element_type}'" ) if not __class__.PROPERTIES in element_desc: raise ValueError( f"FATAL - No properties for element type '{element_type}'" ) template_path = f"{element_desc['doc_path']}/{element_type}.md_template" if not os.access(template_path, os.R_OK): raise FileNotFoundError( f"FATAL - Could not find template doc file for element type '{element_type}' at {template_path}" ) # Check completeness for property in element_desc[__class__.PROPERTIES]: for n in ["type", "doc"]: if not n in property: raise ValueError( f"FATAL - No value for '{n}' in the '{property[__class__.NAME]}' properties of element type '{element_type}' in {element_desc['source']}" ) # Generate element doc pages for that category # Find first level 2 or 3 header def generate_pages(self, category: str, md_path: str) -> None: FIRST_PARA_RE = re.compile(r"(^.*?)(:?\n\n)", re.MULTILINE | re.DOTALL) # Find first level 2 or 3 header FIRST_HEADER_RE = re.compile(r"(^.*?)(\n#+\s+)", re.MULTILINE | re.DOTALL) md_template = "" with open(f"{md_path}_template") as template_file: md_template = template_file.read() if not md_template: raise FileNotFoundError( f"FATAL - Could not read {md_path}_template markdown template" ) prefixes = set([desc["prefix"] for desc in self.elements.values()]) toc = {} for prefix in prefixes: toc[prefix] = '<div class="tp-ve-cards">\n' def generate_element_doc(element_type: str, element_desc: Dict, prefix: str): """ Returns the entry for the Table of Contents that is inserted in the global Visual Elements or Core Elements doc page. """ template_doc_path = f"{element_desc['doc_path']}/{element_type}.md_template" with open(template_doc_path, "r") as template_doc_file: element_documentation = template_doc_file.read() # Retrieve first paragraph from element documentation match = FIRST_PARA_RE.match(element_documentation) if not match: raise ValueError( f"Couldn't locate first paragraph in documentation for element '{element_type}'" ) first_documentation_paragraph = match.group(1) element_desc['short_doc'] = first_documentation_paragraph # Build properties table properties_table = """ # Properties\n\n <table> <thead> <tr> <th>Name</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> """ STAR = "(★)" default_property_name = element_desc[__class__.DEFAULT_PROPERTY] # Convert properties array to a dict property_descs = {p["name"]: p for p in element_desc[__class__.PROPERTIES]} for property_name in [default_property_name] + list( filter(lambda x: x != default_property_name, property_descs.keys()) ): property_desc = property_descs[property_name] name = property_desc[__class__.NAME] type = property_desc["type"] if m := re.match(r"dynamic\((.*?)\)", type): type = f"<code>{m[1]}</code><br/><i>dynamic</i>" elif m := re.match(r"indexed\((.*?)\)", type): type = f"<code>{m[1]}</code><br/><i>indexed</i>" else: type = f"<code>{type}</code>" default_value = property_desc.get("default_value", None) doc = property_desc.get("doc", None) if not default_value: default_value = ( "<i>Required</i>" if property_desc.get("required", False) else "" ) full_name = f"<code id=\"p-{re.sub('<[^>]+>', '', name)}\">" if name == default_property_name: full_name += f'<u><bold>{name}</bold></u></code><sup><a href="#dv">{STAR}</a></sup>' else: full_name += f"{name}</code>" properties_table += ( "<tr>\n" + f"<td nowrap>{full_name}</td>\n" + f"<td>{type}</td>\n" + f"<td nowrap>{default_value}</td>\n" + f"<td><p>{doc}</p></td>\n" + "</tr>\n" ) properties_table += " </tbody>\n</table>\n\n" if default_property_name: properties_table += ( f'<p><sup id="dv">{STAR}</sup>' + f'<a href="#p-{default_property_name}" title="Jump to the default property documentation.">' + f"<code>{default_property_name}</code></a>" + " is the default property for this visual element.</p>\n" ) # Insert title and properties in element documentation match = FIRST_HEADER_RE.match(element_documentation) if not match: raise ValueError( f"Couldn't locate first header in documentation for element '{element_type}'" ) before_properties = match.group(1) after_properties = match.group(2) + element_documentation[match.end() :] # Chart hook if element_type == "chart": values = self.chart_page_hook( element_documentation, before_properties, after_properties ) before_properties = values[0] after_properties = values[1] with open(f"{element_desc['doc_path']}/{element_type}.md", "w") as md_file: md_file.write( f"---\ntitle: <tt>{element_type}</tt>\nhide:\n - navigation\n---\n\n" + f"<!-- Category: {category} -->\n" + before_properties + properties_table + after_properties ) e = element_type # Shortcut d = "../corelements/" if prefix == "core_" else "" s = ( ' style="font-size: .8em;"' if e == "scenario_selector" or e == "data_node_selector" else "" ) return ( f'<a class="tp-ve-card" href="../{d}{e}/">\n' + f"<div{s}>{e}</div>\n" + f'<img class="tp-ve-l" src="../{d}{e}-l.png"/><img class="tp-ve-lh" src="../{d}{e}-lh.png"/>\n' + f'<img class="tp-ve-d" src="../{d}{e}-d.png"/><img class="tp-ve-dh" src="../{d}{e}-dh.png"/>\n' + f"<p>{first_documentation_paragraph}</p>\n" + "</a>\n" ) # If you want a simple list, use # f"<li><a href=\"../{e}/\"><code>{e}</code></a>: {first_documentation_paragraph}</li>\n" # The toc header and footer must then be "<ui>" and "</ul>" respectively. for element_type in self.categories[category]: element_desc = self.elements[element_type] prefix = element_desc["prefix"] toc[prefix] += generate_element_doc(element_type, element_desc, prefix) with open(md_path, "w") as md_file: for prefix in prefixes: md_template = md_template.replace( f"[{prefix}TOC]", toc[prefix] + "</div>\n" ) md_file.write(md_template) def generate_builder_api(self) -> None: separator = "# Generated code for Page Builder" py_file = "taipy/gui/builder/__init__.py" py_content = None with open(py_file, "r") as file: py_content = file.read() # Remove generated code if m := re.search(f"\\n*{separator}", py_content): py_content = py_content[:m.start(0)+1] def generate(self, category, base_class: str) -> str: element_types = self.categories[category] def build_doc(property, desc, indent: int): type = desc['type'] dynamic = "" dynamic_re = re.match(r"^dynamic\(\s*(.*)\s*\)$", type) if False and dynamic_re: type = dynamic_re[1] dynamic = " (<i>dynamic</i>)" doc = "" if "doc" in desc: doc = str(desc["doc"]).replace("\n", f'\n{(indent+4)*" "}').replace("<br/>", f'<br/>\n{(indent+4)*" "}') default_value = f'{desc["default_value"]}' if "default_value" in desc else "" if m := re.match(r"^(<i>.*?</i>)$", default_value): default_value = f"\"{m[1]}\"" elif m := re.match(r"^`(.*?)`$", default_value): default_value = f"{m[1]}" elif default_value == "scatter" or default_value == "lines+markers": default_value = f"\"{default_value}\"" if default_value: try: x = eval(default_value) except: raise SyntaxError(f"Default value for property '{property}' of element '{element_type}' is not a valid Python expression ({default_value})") return (f"{property}={default_value if default_value else 'None'}, ", f"{indent*' '}{desc['name']} ({type}){dynamic}: {doc}\n") template = f""" class [element_type]({base_class}): '''[short_doc] This class represents the [control_or_block] documented in the [element_md_page] section. ''' _ELEMENT_NAME: str def __init__(self, [arguments]) -> None: '''Create a new `[element_type]` element. Arguments: [arguments_doc] ''' ... """ buffer = StringIO() docline_in_template = next(l for l in template.splitlines() if l.lstrip().startswith("[arguments_doc]")) doc_indent = len(docline_in_template) - len(docline_in_template.lstrip()) for element_type in element_types: desc = self.elements[element_type] properties = desc["properties"] default_prop = next( p for p in properties if p["name"] == desc["default_property"] ) doc = build_doc(default_prop['name'], default_prop, doc_indent) arguments = doc[0] arguments_doc = doc[1] for property in properties: property_name = property["name"] if property_name != desc["default_property"] and not "[" in property_name: doc = build_doc(property_name, property, doc_indent) arguments += doc[0] arguments_doc += doc[1] # Process short doc short_doc = desc["short_doc"] if m := re.search(r"(\[`(\w+)`\]\()\2\.md\)", short_doc): short_doc = short_doc[:m.start()]+f"{m[1]}../gui/viselements/{m[2]}.md)"+short_doc[m.end():] # Link to element doc page element_md_location = "corelements" if desc["prefix"] == "core_" else "viselements" element_md_page = f"[`{element_type}`](../gui/{element_md_location}/{element_type}.md)" buffer.write(template.replace("[element_type]", element_type) .replace("[element_md_page]", element_md_page) .replace("[arguments]", arguments) .replace("[short_doc]", short_doc) .replace("[control_or_block]", "control" if category=="controls" else "block") .replace(" "*doc_indent+"[arguments_doc]\n", arguments_doc)) s = buffer.getvalue() return buffer.getvalue() with open(py_file, "wt") as file: file.write(py_content) file.write(f"\n\n{separator}\n\n") file.write(f"from ._element import _Block, _Control\n\n") file.write(generate(self, "controls", "_Control")) file.write(generate(self, "blocks", "_Block")) def setup(self, setup: Setup) -> None: self.generate_pages("controls", self.controls_path) self.generate_pages("blocks", self.blocks_path) self.generate_builder_api() # Special case for charts: we want to insert the chart gallery that is stored in the # file whose path is in self.charts_home_html_path # This should be inserted before the first level 1 header def chart_page_hook( self, element_documentation: str, before: str, after: str ) -> tuple[str, str]: with open(self.charts_home_html_path, "r") as html_fragment_file: chart_gallery = html_fragment_file.read() # The chart_gallery begins with a comment where all sub-sections # are listed. SECTIONS_RE = re.compile( r"^(?:\s*<!--\s+)(.*?)(?:-->)", re.MULTILINE | re.DOTALL ) match = SECTIONS_RE.match(chart_gallery) if not match: raise ValueError( f"{self.charts_home_html_path} should begin with an HTML comment that lists the chart types" ) chart_gallery = "\n" + chart_gallery[match.end() :] SECTION_RE = re.compile(r"^([\w-]+):(.*)$") chart_sections = "" for line in match.group(1).splitlines(): match = SECTION_RE.match(line) if match: chart_sections += f"- [{match.group(2)}](charts/{match.group(1)}.md)\n" match = re.match( r"(^.*?)(?:\n#\s+)", element_documentation, re.MULTILINE | re.DOTALL ) if not match: raise ValueError( f"Couldn't locate first header1 in documentation for element 'chart'" ) return ( match.group(1) + chart_gallery + before[match.end() :], after + chart_sections, ) |
# ################################################################################ # Taipy Contributor list generation setup step. # # A contributors list is generated based on internal and external contributors # retrieved using GitHub REST APIs. # ################################################################################ import base64 import os import random import requests from .setup import SetupStep, Setup class ContributorsStep(SetupStep): def __init__(self): self.GH_TOKEN = os.getenv("GITHUB_TOKEN", None) self.BASE_URL = "https://api.github.com" self.ORGANIZATION_URL = f"{self.BASE_URL}/orgs/Avaiga" self.MEMBERS_URL = f"{self.ORGANIZATION_URL}/members" self.REPOS = f"{self.ORGANIZATION_URL}/repos" self.REPO_URLS = [] self.MEMBERS = {} self.CONTRIBUTORS = {} self.ANONYMOUS = ["dependabot[bot]"] self.PATH = "" self.TEMPLATE_SUFFIX = "_template" def enter(self, setup: Setup): self.PATH = os.path.join(setup.docs_dir, "contributing", "contributors.md") def get_id(self) -> str: return "contributors" def get_description(self) -> str: return "Generating the contributors list." def setup(self, setup: Setup) -> None: try: self.get_repo_urls() self.get_avaiga_members() self.get_contributors() self.build_content((self.MEMBERS, "[AVAIGA_TEAM_MEMBERS]"), (self.CONTRIBUTORS, "[TAIPY_CONTRIBUTORS]")) except Exception as e: print(f"WARNING - Exception raised while listing contributors:\n{e}") def get_repo_urls(self): response = self.__get(self.REPOS) if response.status_code != 200: print(f"WARNING - Couldn't get repositories. response.status_code: {response.status_code}", flush=True) return repos = response.json() self.REPO_URLS = list(map(lambda _: _['url'], repos)) def get_avaiga_members(self): response = self.__get(self.MEMBERS_URL, with_token=False) if response.status_code != 200: print(f"WARNING - Couldn't get members. response.status_code: {response.status_code}", flush=True) return members = response.json() for member in members: login = member['login'] if login not in self.MEMBERS and login not in self.ANONYMOUS: self.MEMBERS[login] = {"avatar_url": member['avatar_url'], "html_url": member['html_url']} def get_contributors(self): for url in self.REPO_URLS: response = self.__get(url + "/contents/contributors.txt", ignore404=True) public_contributor_logins = [] if response.status_code == 200: data = response.json() content = data["content"] encoding = data["encoding"] if encoding == 'base64': file_content = base64.b64decode(content).decode() public_contributor_logins += file_content.strip().split("\n") else: print(f"WARNING - Couldn't get contributors from {url}. unknown encoding: {encoding}", flush=True) continue elif response.status_code == 404: print(f"INFO - No contributors.txt in repository {url[len(self.BASE_URL)+14:]}.", flush=True) else: print(f"WARNING - Couldn't get contributors for {url}. response.status_code: {response.status_code}", flush=True) continue response = self.__get(url+"/contributors") if response.status_code != 200: print(f"WARNING - Couldn't get contributors. response.status_code: {response.status_code}", flush=True) continue for c in response.json(): login = c['login'] if login not in self.MEMBERS and login not in self.ANONYMOUS and login in public_contributor_logins: self.CONTRIBUTORS[login] = {"avatar_url": c['avatar_url'], "html_url": c['html_url']} def build_content(self, *members_pattern_tuples): pattern_content_tuples = [] for member_pattern in members_pattern_tuples: members = member_pattern[0] pattern = member_pattern[1] content = "" members_list = list(members.items()) random.shuffle(members_list) for login, member_info in members_list: if login not in self.ANONYMOUS: content += f"\n- [<img src='{member_info['avatar_url']}' alt='{login} GitHub avatar' width='20'/>" \ f"{login}]" \ f"({member_info['html_url']})" content += "\n" pattern_content_tuples.append((pattern, content)) self._replace(self.PATH, *pattern_content_tuples) def _replace(self, path, *pattern_content_tuples): # Read in the file with open(path + self.TEMPLATE_SUFFIX, 'r') as file: file_data = file.read() # Replace the patterns by the contents for pattern_content in pattern_content_tuples: pattern = pattern_content[0] content = pattern_content[1] file_data = file_data.replace(pattern, content) # Write the file out without the template suffix with open(path, 'w') as file: file.write(file_data) def __get(self, url, with_token=True, ignore404:bool = False): if with_token and self.GH_TOKEN: headers = { "Accept": "application/vnd.github+json", "Authorization": "Bearer "+self.GH_TOKEN } #{'Authorization': f'token {self.GH_TOKEN}'} return requests.get(url, headers=headers) else: return requests.get(url) def exit(self, setup: Setup): pass |
import os from typing import List class GitContext(object): """Temporarily force GIT_TERMINAL_PROMPT to 0 for private repositories.""" V = "GIT_TERMINAL_PROMPT" def __init__(self, repo: str, private_repos: List[str]): self.value = None self.save_value = repo in private_repos def __enter__(self): if self.save_value: self.value = os.environ.get(__class__.V, None) os.environ[__class__.V] = "0" def __exit__(self, exception_type, exception_value, traceback): if self.save_value: if self.value: os.environ[__class__.V] = self.value else: del os.environ[__class__.V] |
from .git_context import GitContext from .cli import CLI from .utils import read_doc_version_from_mkdocs_yml_template_file |
import argparse class CLI(): DESCRIPTION = """\ Locally copies the source code of Taipy from different places in order to allow the generation of the documentation set. After this script has run, you can run 'mkdocs serve'. """ ARG_N_HELP = "Prevents the source repository update (local only)." ARG_C_HELP = "Only checks if the fetch can be performed then exits." ARG_VERSION_HELP_1 = """\ The version for the whole doc set, or specific repositories. This can be 'local', 'develop' or a valid version number. It can be prefixed with '<repository>:', then the version applies only to that repository. If that prefix is not present, the version applies to all repositories. Valid repository names are: """ ARG_VERSION_HELP_2 = """ Note that each <version> arguments may overwrite the previous ones. i.e.: '2.0 core:1.0' will set all versions to 2.0 except for the 'core' repository. 'core:1.0 2.0' will set version 2.0 for all repositories. If <version> is 'local', the code is retrieved from a directory called 'taipy-<repository-name>', above the current directory. If <version> is 'develop', the develop branch for the indicated repository is used. If <version> is '<Major>.<Minor>', the corresponding branch is used. If <version> contains an additional '.<Patch>[.<More>]' fragment, then the corresponding tag is extracted from the '<Major>.<Minor>' branch for that repository. If any version is not 'local', then the 'git' command must be accessible. The default behaviour is to use a local version for all repositories. """ def __init__(self, script_name, repos): self.parser = argparse.ArgumentParser(prog="python " + script_name, formatter_class=argparse.RawTextHelpFormatter, description=self.DESCRIPTION) self.parser.add_argument("-n", "--no_pull", action='store_true', help=self.ARG_N_HELP) self.parser.add_argument("-c", "--check", action='store_true', help=self.ARG_C_HELP) self.parser.add_argument('version', nargs='*', help=self.ARG_VERSION_HELP_1 + "\n".join([" - " + p for p in repos]) + self.ARG_VERSION_HELP_2) def get_args(self): return self.parser.parse_args() |
import os import re def read_doc_version_from_mkdocs_yml_template_file(root_dir): """Read version from mkdocs.yml template""" mkdocs_yml_template = None mkdocs_yml_template_path = os.path.join(root_dir, "mkdocs.yml_template") with open(mkdocs_yml_template_path, "r") as mkdocs_file: mkdocs_yml_template = mkdocs_file.read() if mkdocs_yml_template is None: raise IOError(f"Couldn't open '{mkdocs_yml_template_path}'") mkdocs_yml_version = re.search(r"site_url:\s*https://docs\.taipy\.io/en/(develop|release-(\d\.\d))$", mkdocs_yml_template, re.MULTILINE) if mkdocs_yml_version is None: raise ValueError( f"'{mkdocs_yml_template_path}' has an invalid site_url value. This must be 'develop' or 'release-[M].[m]'.") return mkdocs_yml_version.group(2) if mkdocs_yml_version.group(2) else mkdocs_yml_version.group(1) |
from datetime import datetime import pandas as pd from taipy import Config, Frequency, Scope def write_orders_plan(data: pd.DataFrame): insert_data = data[["date", "product_id", "number_of_products"]].to_dict("records") return ["DELETE FROM orders", ("INSERT INTO orders VALUES (:date, :product_id, :number_of_products)", insert_data)] def train(sales_history: pd.DataFrame): print("Running training") return "TRAINED_MODEL" def predict(model, current_month): print("Running predicting") return "SALES_PREDICTIONS" def plan(sales_predictions, capacity): print("Running planning") return "PRODUCTION_ORDERS" def compare(previous_month_prediction, current_month_prediction): print("Comparing previous month and current month sale predictions") return "COMPARISON_RESULT" # Configure all six data nodes sales_history_cfg = Config.configure_csv_data_node( id="sales_history", scope=Scope.GLOBAL, default_path="path/sales.csv" ) trained_model_cfg = Config.configure_data_node(id="trained_model", scope=Scope.CYCLE) current_month_cfg = Config.configure_data_node(id="current_month", scope=Scope.CYCLE, default_data=datetime(2020, 1, 1)) sales_predictions_cfg = Config.configure_data_node(id="sales_predictions", scope=Scope.CYCLE) capacity_cfg = Config.configure_data_node(id="capacity") orders_cfg = Config.configure_sql_data_node( id="orders", db_username="admin", db_password="ENV[PWD]", db_name="production_planning", db_engine="mssql", read_query="SELECT orders.ID, orders.date, products.price, orders.number_of_products FROM orders INNER JOIN products ON orders.product_id=products.ID", write_query_builder=write_orders_plan, db_driver="ODBC Driver 17 for SQL Server", ) # Configure the three tasks training_cfg = Config.configure_task("training", train, sales_history_cfg, [trained_model_cfg]) predicting_cfg = Config.configure_task( id="predicting", function=predict, input=[trained_model_cfg, current_month_cfg], output=sales_predictions_cfg ) planning_cfg = Config.configure_task( id="planning", function=plan, input=[sales_predictions_cfg, capacity_cfg], output=[orders_cfg] ) # Configure the scenario monthly_scenario_cfg = Config.configure_scenario( id="scenario_configuration", task_configs=[training_cfg, predicting_cfg, planning_cfg], frequency=Frequency.MONTHLY, comparators={sales_predictions_cfg.id: compare}, sequences={"sales": [training_cfg, predicting_cfg], "production": [planning_cfg]}, ) |
from taipy import Config from datetime import datetime class DailyMinTemp: def __init__(self, Date : datetime=None, Temp : float=None): self.Date = Date self.Temp = Temp def encode(self): return { "date": self.Date.isoformat(), "temperature": self.Temp, } @classmethod def decode(cls, data): return cls( datetime.fromisoformat(data["date"]), data["temperature"], ) historical_data_cfg = Config.configure_mongo_collection_data_node( id="historical_data", db_username="admin", db_password="pa$$w0rd", db_name="taipy", collection_name="historical_data_set", custom_document=DailyMinTemp, ) |
from datetime import timedelta from taipy import Config, Scope date_cfg = Config.configure_data_node( id="date_cfg", description="The current date of the scenario", ) model_cfg = Config.configure_data_node( id="model_cfg", scope=Scope.CYCLE, storage_type="pickle", validity_period=timedelta(days=2), description="Trained model shared by all scenarios", code=54, ) |
from taipy import Config historical_data_cfg = Config.configure_mongo_collection_data_node( id="historical_data", db_username="admin", db_password="pa$$w0rd", db_name="taipy", collection_name="historical_data_set", ) |
import csv from typing import List, Iterator from taipy import Config def read_csv(path: str, delimiter: str = ",") -> Iterator: with open(path, newline=' ') as csvfile: data = csv.reader(csvfile, delimiter=delimiter) return data def write_csv(data: List[str], path: str, delimiter: str = ",") -> None: headers = ["country_code", "country"] with open(path, 'w') as csvfile: writer = csv.writer(csvfile, delimiter=delimiter) writer.writerow(headers) for row in data: writer.writerow(row) csv_country_data_cfg = Config.configure_generic_data_node( id="csv_country_data", read_fct=read_csv, write_fct=write_csv, read_fct_args=["../path/data.csv", ";"], write_fct_args=["../path/data.csv", ";"]) |
from taipy import Config, Scope Config.set_default_data_node_configuration( storage_type="sql_table", db_username="username", db_password="p4$$w0rD", db_name="sale_db", db_engine="mssql", table_name="products", db_host="localhost", db_port=1437, db_driver="ODBC Driver 17 for SQL Server", db_extra_args={"TrustServerCertificate": "yes"}, scope=Scope.GLOBAL, ) products_data_cfg = Config.configure_data_node(id="products_data") users_data_cfg = Config.configure_data_node(id="users_data", table_name="users") retail_data_cfg = Config.configure_data_node(id="retail_data", storage_type="sql_table", table_name="retail_data") wholesale_data_cfg = Config.configure_sql_table_data_node(id="wholesale_data", table_name="wholesale_data") forecast_data_cfg = Config.configure_data_node(id="forecast_data", storage_type="csv", default_path="forecast.csv") |
from datetime import datetime as dt import pandas as pd from taipy import Config def read_csv(path: str) -> pd.DataFrame: # reading a csv file, define some column types and parse a string into datetime custom_parser = lambda x: dt.strptime(x, "%Y %m %d %H:%M:%S") data = pd.read_csv( path, parse_dates=['date'], date_parser=custom_parser, dtype={ "name": str, "grade": int } ) return data def write_csv(data: pd.DataFrame, path: str) -> None: # dropping not a number values before writing data.dropna().to_csv(path) student_data = Config.configure_generic_data_node( id="student_data", read_fct=read_csv, write_fct=write_csv, read_fct_args=["../path/data.csv"], write_fct_args=["../path/data.csv"]) |
from taipy import Config sales_history_cfg = Config.configure_sql_table_data_node( id="sales_history", db_username="admin", db_password="password", db_name="taipy", db_engine="mssql", table_name="sales", db_driver="ODBC Driver 17 for SQL Server", db_extra_args={"TrustServerCertificate": "yes"}, ) |
from taipy import Config import pandas as pd def write_query_builder(data: pd.DataFrame): insert_data = data[["date", "nb_sales"]].to_dict("records") return [ "DELETE FROM sales", ("INSERT INTO sales VALUES (:date, :nb_sales)", insert_data) ] sales_history_cfg = Config.configure_sql_data_node( id="sales_history", db_name="taipy", db_engine="sqlite", read_query="SELECT * from sales", write_query_builder=write_query_builder, sqlite_folder_path="database", sqlite_file_extension=".sqlite3", ) |
from taipy import Config class SaleRow: date: str nb_sales: int hist_temp_cfg = Config.configure_excel_data_node( id="historical_temperature", default_path="path/hist_temp.xlsx", exposed_type="numpy") hist_log_cfg = Config.configure_excel_data_node( id="log_history", default_path="path/hist_log.xlsx", exposed_type="modin") sales_history_cfg = Config.configure_excel_data_node( id="sales_history", default_path="path/sales.xlsx", sheet_name=["January", "February"], exposed_type=SaleRow) |
from taipy import Config from datetime import datetime date_cfg = Config.configure_in_memory_data_node( id="date", default_data=datetime(2022, 1, 25)) |
from taipy import Config sales_history_cfg = Config.configure_sql_table_data_node( id="sales_history", db_name="taipy", db_engine="sqlite", table_name="sales", sqlite_folder_path="database", sqlite_file_extension=".sqlite3", ) |
from taipy import Config data_node_cfg = Config.configure_data_node(id="data_node_cfg") |
from taipy import Config class SaleRow: date: str nb_sales: int temp_cfg = Config.configure_csv_data_node( id="historical_temperature", default_path="path/hist_temp.csv", has_header=True, exposed_type="numpy") log_cfg = Config.configure_csv_data_node( id="log_history", default_path="path/hist_log.csv", exposed_type="modin") sales_history_cfg = Config.configure_csv_data_node( id="sales_history", default_path="path/sales.csv", exposed_type=SaleRow) |
from taipy import Config temp_cfg = Config.configure_parquet_data_node( id="historical_temperature", default_path="path/hist_temp.parquet") |
from taipy import Config import pandas as pd def write_query_builder(data: pd.DataFrame): insert_data = data[["date", "nb_sales"]].to_dict("records") return [ "DELETE FROM sales", ("INSERT INTO sales VALUES (:date, :nb_sales)", insert_data) ] sales_history_cfg = Config.configure_sql_data_node( id="sales_history", db_username="admin", db_password="password", db_name="taipy", db_engine="mssql", read_query="SELECT * from sales", write_query_builder=write_query_builder, db_driver="ODBC Driver 17 for SQL Server", db_extra_args={"TrustServerCertificate": "yes"}, ) |
from taipy import Config import json class SaleRow: date: str nb_sales: int class SaleRowEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, SaleRow): return { '__type__': "SaleRow", 'date': obj.date, 'nb_sales': obj.nb_sales} return json.JSONEncoder.default(self, obj) class SaleRowDecoder(json.JSONDecoder): def __init__(self, *args, **kwargs): json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs) def object_hook(self, d): if d.get('__type__') == "SaleRow": return SaleRow(date=d['date'], nb_sales=d['nb_sales']) return d sales_history_cfg = Config.configure_json_data_node( id="sales_history", path="path/sales.json", encoder=SaleRowEncoder, decoder=SaleRowDecoder) |
from taipy import Config read_kwargs = {"filters": [("log_level", "in", {"ERROR", "CRITICAL"})]} write_kwargs = {"partition_cols": ["log_level"], "compression": None} log_cfg = Config.configure_parquet_data_node( id="log_history", default_path="path/hist_log.parquet", engine="pyarrow", # default compression="snappy", # default, but overridden by the key in write_kwargs exposed_type="modin", read_kwargs=read_kwargs, write_kwargs=write_kwargs) |
from taipy import Config hist_temp_cfg = Config.configure_json_data_node( id="historical_temperature", default_path="path/hist_temp.json", ) |
from taipy import Config def read_text(path: str) -> str: with open(path, 'r') as text_reader: data = text_reader.read() return data def write_text(data: str, path: str) -> None: with open(path, 'w') as text_writer: text_writer.write(data) historical_data_cfg = Config.configure_generic_data_node( id="historical_data", read_fct=read_text, write_fct=write_text, read_fct_args=["../path/data.txt"], write_fct_args=["../path/data.txt"]) |
from taipy import Config, Scope products_data_cfg = Config.configure_sql_table_data_node( id="products_data", db_username="foo", db_password="bar", db_name="db", db_engine="mssql", db_host="localhost", db_port=1437, db_driver="ODBC Driver 17 for SQL Server", db_extra_args={"TrustServerCertificate": "yes"}, table_name="products", ) users_data_cfg = Config.configure_data_node_from( source_configuration=products_data_cfg, id="users_data", scope=Scope.GLOBAL, table_name="users", ) retail_data_cfg = Config.configure_data_node_from( source_configuration=products_data_cfg, id="retail_data", table_name="retail_data", ) wholesale_data_cfg = Config.configure_data_node_from( source_configuration=products_data_cfg, id="wholesale_data", table_name="wholesale_data", ) |
from taipy import Config from datetime import datetime date_cfg = Config.configure_pickle_data_node( id="date_cfg", default_data=datetime(2022, 1, 25)) model_cfg = Config.configure_pickle_data_node( id="model_cfg", default_path="path/to/my/model.p", description="The trained model") |
from taipy import Config def multiply_and_add(nb1, nb2): return nb1 * nb2, nb1 + nb2 nb_1_cfg = Config.configure_data_node("nb_1", default_data=21) nb_2_cfg = Config.configure_data_node("nb_2", default_data=2) multiplication_cfg = Config.configure_data_node("multiplication") addition_cfg = Config.configure_data_node("addition") task_cfg = Config.configure_task("foo", multiply_and_add, [nb_1_cfg, nb_2_cfg], [multiplication_cfg, addition_cfg]) |
from taipy import Config def double(nb): return nb * 2 input_data_node_cfg = Config.configure_data_node("input", default_data=21) output_data_node_cfg = Config.configure_data_node("output") double_task_cfg = Config.configure_task("double_task", double, input_data_node_cfg, output_data_node_cfg, skippable=True) |
import taipy as tp from taipy import Config, Core ################################################################ # Configure your application # ################################################################ def build_message(name): return f"Hello {name}!" # A first data node configuration represents a name name_data_node_cfg = Config.configure_data_node(id="input_name") # A second data node configuration represents the message to print message_data_node_cfg = Config.configure_data_node(id="message") # The task represents the build_message function build_msg_task_cfg = Config.configure_task("build_msg", build_message, name_data_node_cfg, message_data_node_cfg) # The scenario represent the whole execution graph scenario_cfg = Config.configure_scenario("scenario", task_configs=[build_msg_task_cfg]) if __name__ == "__main__": ################################################################ # Instantiate the Core service and run it # ################################################################ Core().run() ################################################################ # Manage your scenarios and data nodes # ################################################################ zinedine_scenario = tp.create_scenario(scenario_cfg) kylian_scenario = tp.create_scenario(scenario_cfg) zinedine_scenario.input_name.write("Zinedine") zinedine_scenario.submit() print(zinedine_scenario.message.read()) kylian_scenario.input_name.write("Kylian Mbappe") kylian_scenario.submit() print(kylian_scenario.message.read()) |
import taipy as tp from taipy import Config, Scope def example_algorithm(entry: str): # does nothing! return entry input_cfg = Config.configure_data_node("input", path="input.pkl", scope=Scope.GLOBAL, default_data="A string") output_cfg = Config.configure_data_node("output", path="output.pkl", scope=Scope.GLOBAL) task_cfg = Config.configure_task("example_algorithm", example_algorithm, input_cfg, output_cfg, skippable=True) scenario_cfg = Config.configure_scenario("my_scenario", [task_cfg]) if __name__ == "__main__": tp.Core().run() tp.create_scenario(scenario_cfg) print(f"Number of scenarios: {len(tp.get_scenarios())}") |
import taipy as tp from taipy import Config def example_algorithm(entry: str): # does nothing! return entry input_cfg = Config.configure_data_node("input", default_data="a_string") output_cfg = Config.configure_data_node("output", description="What a description") task_cfg = Config.configure_task("example_algorithm", example_algorithm, input_cfg, output_cfg) scenario_cfg = Config.configure_scenario("my_scenario", [task_cfg]) if __name__ == "__main__": tp.Core().run() tp.create_scenario(scenario_cfg) print(f"Number of scenarios: {len(tp.get_scenarios())}") |
import taipy as tp from taipy import Config def example_algorithm(entry: str): # does nothing! return entry input_cfg = Config.configure_data_node("input", default_data="a_string") output_cfg = Config.configure_data_node("output") task_cfg = Config.configure_task("example_algorithm", example_algorithm, input_cfg, output_cfg) scenario_cfg = Config.configure_scenario("my_scenario", [task_cfg]) if __name__ == "__main__": tp.Core().run() tp.create_scenario(scenario_cfg) print(f"Number of scenarios: {len(tp.get_scenarios())}") |
from datetime import datetime import pandas as pd from taipy import Config, Frequency, Scope def write_orders_plan(data: pd.DataFrame): insert_data = data[["date", "product_id", "number_of_products"]].to_dict("records") return ["DELETE FROM orders", ("INSERT INTO orders VALUES (:date, :product_id, :number_of_products)", insert_data)] def train(sales_history: pd.DataFrame): print("Running training") return "TRAINED_MODEL" def predict(model, current_month): print("Running predicting") return "SALES_PREDICTIONS" def plan(sales_predictions, capacity): print("Running planning") return "PRODUCTION_ORDERS" def compare(previous_month_prediction, current_month_prediction): print("Comparing previous month and current month sale predictions") return "COMPARISON_RESULT" # Configure all six data nodes sales_history_cfg = Config.configure_csv_data_node( id="sales_history", scope=Scope.GLOBAL, default_path="path/sales.csv" ) trained_model_cfg = Config.configure_data_node(id="trained_model", scope=Scope.CYCLE) current_month_cfg = Config.configure_data_node(id="current_month", scope=Scope.CYCLE, default_data=datetime(2020, 1, 1)) sales_predictions_cfg = Config.configure_data_node(id="sales_predictions", scope=Scope.CYCLE) capacity_cfg = Config.configure_data_node(id="capacity") orders_cfg = Config.configure_sql_data_node( id="orders", db_username="admin", db_password="ENV[PWD]", db_name="production_planning", db_engine="mssql", read_query="SELECT orders.ID, orders.date, products.price, orders.number_of_products FROM orders INNER JOIN products ON orders.product_id=products.ID", write_query_builder=write_orders_plan, db_driver="ODBC Driver 17 for SQL Server", ) # Configure the three tasks training_cfg = Config.configure_task("training", train, sales_history_cfg, [trained_model_cfg]) predicting_cfg = Config.configure_task( id="predicting", function=predict, input=[trained_model_cfg, current_month_cfg], output=sales_predictions_cfg ) planning_cfg = Config.configure_task( id="planning", function=plan, input=[sales_predictions_cfg, capacity_cfg], output=[orders_cfg] ) # Configure the scenario monthly_scenario_cfg = Config.configure_scenario( id="scenario_configuration", task_configs=[training_cfg, predicting_cfg, planning_cfg], frequency=Frequency.MONTHLY, comparators={sales_predictions_cfg.id: compare}, sequences={"sales": [training_cfg, predicting_cfg], "production": [planning_cfg]}, ) |
import taipy as tp if __name__ == "__main__": gui = tp.Gui(page="# Getting started with *Taipy*") rest = tp.Rest() tp.run(gui, rest, title="Taipy application") |
from taipy import Config import taipy as tp import pandas as pd import datetime as dt data = pd.read_csv("https://raw.githubusercontent.com/Avaiga/taipy-getting-started-core/develop/src/daily-min-temperatures.csv") # Normal function used by Taipy def predict(historical_temperature: pd.DataFrame, date_to_forecast: str) -> float: print(f"Running baseline...") historical_temperature['Date'] = pd.to_datetime(historical_temperature['Date']) historical_same_day = historical_temperature.loc[ (historical_temperature['Date'].dt.day == date_to_forecast.day) & (historical_temperature['Date'].dt.month == date_to_forecast.month) ] return historical_same_day['Temp'].mean() Config.load('config.toml') if __name__ == '__main__': scenario_cfg = Config.scenarios['my_scenario'] # Run of the Core tp.Core().run() # Creation of the scenario and execution scenario = tp.create_scenario(scenario_cfg) scenario.historical_temperature.write(data) scenario.date_to_forecast.write(dt.datetime.now()) tp.submit(scenario) print("Value at the end of task", scenario.predictions.read()) def save(state): state.scenario.historical_temperature.write(data) state.scenario.date_to_forecast.write(state.date) tp.gui.notify(state, "s", "Saved! Ready to submit") date = None scenario_md = """ <|{scenario}|scenario_selector|> <|{date}|date|on_change=save|active={scenario}|> <|{scenario}|scenario|> <|{scenario}|scenario_dag|> <|Refresh|button|on_action={lambda s: s.assign("scenario", scenario)}|> <|{scenario.predictions.read() if scenario else ''}|> """ tp.Gui(scenario_md).run() |
from taipy import Config import taipy as tp import pandas as pd import datetime as dt data = pd.read_csv("https://raw.githubusercontent.com/Avaiga/taipy-getting-started-core/develop/src/daily-min-temperatures.csv") # Normal function used by Taipy def predict(historical_temperature: pd.DataFrame, date_to_forecast: str) -> float: print(f"Running baseline...") historical_temperature['Date'] = pd.to_datetime(historical_temperature['Date']) historical_same_day = historical_temperature.loc[ (historical_temperature['Date'].dt.day == date_to_forecast.day) & (historical_temperature['Date'].dt.month == date_to_forecast.month) ] return historical_same_day['Temp'].mean() # Configuration of Data Nodes historical_temperature_cfg = Config.configure_data_node("historical_temperature") date_to_forecast_cfg = Config.configure_data_node("date_to_forecast") predictions_cfg = Config.configure_data_node("predictions") # Configuration of tasks predictions_cfg = Config.configure_task("predict", predict, [historical_temperature_cfg, date_to_forecast_cfg], predictions_cfg) # Configuration of scenario scenario_cfg = Config.configure_scenario(id="my_scenario", task_configs=[predictions_cfg]) Config.export('config.toml') if __name__ == '__main__': # Run of the Core tp.Core().run() # Creation of the scenario and execution scenario = tp.create_scenario(scenario_cfg) scenario.historical_temperature.write(data) scenario.date_to_forecast.write(dt.datetime.now()) tp.submit(scenario) print("Value at the end of task", scenario.predictions.read()) def save(state): state.scenario.historical_temperature.write(data) state.scenario.date_to_forecast.write(state.date) tp.gui.notify(state, "s", "Saved! Ready to submit") date = None scenario_md = """ <|{scenario}|scenario_selector|> Put a Date <|{date}|date|on_change=save|active={scenario}|> Run the scenario <|{scenario}|scenario|> <|{scenario}|scenario_dag|> View all the information on your prediction here <|{scenario.predictions if scenario else None}|data_node|> """ tp.Gui(scenario_md).run() |
from taipy.config import Config, Frequency, Scope import taipy as tp import datetime as dt import pandas as pd def filter_by_month(df, month): df['Date'] = pd.to_datetime(df['Date']) df = df[df['Date'].dt.month == month] return df Config.load('config.toml') scenario_cfg = Config.scenarios["my_scenario"] if __name__ == '__main__': tp.Core().run() scenario_1 = tp.create_scenario(scenario_cfg, creation_date=dt.datetime(2022,10,7), name="Scenario 2022/10/7") scenario_2 = tp.create_scenario(scenario_cfg, creation_date=dt.datetime(2022,10,5), name="Scenario 2022/10/5") scenario_1.month.write(10) print("Month Data Node of Scenario 1:", scenario_1.month.read()) print("Month Data Node of Scenario 2:", scenario_2.month.read()) scenario_1.submit() before_set_1 = scenario_1.is_primary before_set_2 = scenario_2.is_primary tp.set_primary(scenario_2) print('Scenario 1: Primary?', before_set_1, scenario_1.is_primary) print('Scenario 2: Primary?', before_set_2, scenario_2.is_primary) scenario = None data_node = None tp.Gui("""<|{scenario}|scenario_selector|> <|{scenario}|scenario|> <|{scenario}|scenario_dag|> <|{data_node}|data_node_selector|>""").run() |
from taipy.config import Config, Frequency, Scope import taipy as tp import datetime as dt import pandas as pd def filter_by_month(df, month): df['Date'] = pd.to_datetime(df['Date']) df = df[df['Date'].dt.month == month] return df historical_data_cfg = Config.configure_csv_data_node(id="historical_data", default_path="time_series.csv", scope=Scope.GLOBAL) month_cfg = Config.configure_data_node(id="month", scope=Scope.CYCLE) month_values_cfg = Config.configure_data_node(id="month_data", scope=Scope.CYCLE) task_filter_cfg = Config.configure_task(id="filter_by_month", function=filter_by_month, input=[historical_data_cfg, month_cfg], output=month_values_cfg) scenario_cfg = Config.configure_scenario(id="my_scenario", task_configs=[task_filter_cfg], frequency=Frequency.MONTHLY) Config.export('step_04/onfig.toml') if __name__ == '__main__': tp.Core().run() scenario_1 = tp.create_scenario(scenario_cfg, creation_date=dt.datetime(2022,10,7), name="Scenario 2022/10/7") scenario_2 = tp.create_scenario(scenario_cfg, creation_date=dt.datetime(2022,10,5), name="Scenario 2022/10/5") scenario_1.month.write(10) print("Month Data Node of Scenario 1:", scenario_1.month.read()) print("Month Data Node of Scenario 2:", scenario_2.month.read()) scenario_1.submit() before_set_1 = scenario_1.is_primary before_set_2 = scenario_2.is_primary tp.set_primary(scenario_2) print('Scenario 1: Primary?', before_set_1, scenario_1.is_primary) print('Scenario 2: Primary?', before_set_2, scenario_2.is_primary) scenario = None data_node = None tp.Gui("""<|{scenario}|scenario_selector|> <|{scenario}|scenario|> <|{scenario}|scenario_dag|> <|{data_node}|data_node_selector|>""").run() |
from taipy.core.config import Config import taipy as tp import datetime as dt import pandas as pd import time # Normal function used by Taipy def double(nb): return nb * 2 def add(nb): print("Wait 10 seconds in add function") time.sleep(10) return nb + 10 Config.load('config.toml') Config.configure_job_executions(mode="standalone", max_nb_of_workers=2) if __name__=="__main__": scenario_cfg = Config.scenarios['my_scenario'] tp.Core().run() scenario_1 = tp.create_scenario(scenario_cfg) scenario_2 = tp.create_scenario(scenario_cfg) scenario_1.submit() scenario_2.submit() scenario_1 = tp.create_scenario(scenario_cfg) scenario_1.submit(wait=True) scenario_1.submit(wait=True, timeout=5) |
from taipy.core.config import Config import taipy as tp import datetime as dt import pandas as pd import time # Normal function used by Taipy def double(nb): return nb * 2 def add(nb): print("Wait 10 seconds in add function") time.sleep(10) return nb + 10 Config.configure_job_executions(mode="standalone", max_nb_of_workers=2) # Configuration of Data Nodes input_cfg = Config.configure_data_node("input", default_data=21) intermediate_cfg = Config.configure_data_node("intermediate", default_data=21) output_cfg = Config.configure_data_node("output") # Configuration of tasks first_task_cfg = Config.configure_task("double", double, input_cfg, intermediate_cfg) second_task_cfg = Config.configure_task("add", add, intermediate_cfg, output_cfg) # Configuration of the scenario scenario_cfg = Config.configure_scenario(id="my_scenario", task_configs=[first_task_cfg, second_task_cfg]) Config.export("config.toml") if __name__=="__main__": tp.Core().run() scenario_1 = tp.create_scenario(scenario_cfg) scenario_2 = tp.create_scenario(scenario_cfg) scenario_1.submit() scenario_2.submit() scenario_1 = tp.create_scenario(scenario_cfg) scenario_1.submit(wait=True) scenario_1.submit(wait=True, timeout=5) |
from taipy.core.config import Config import taipy as tp # Normal function used by Taipy def double(nb): return nb * 2 def add(nb): return nb + 10 # Configuration of Data Nodes input_cfg = Config.configure_data_node("input", default_data=21) intermediate_cfg = Config.configure_data_node("intermediate") output_cfg = Config.configure_data_node("output") # Configuration of tasks first_task_cfg = Config.configure_task("double", double, input_cfg, intermediate_cfg) second_task_cfg = Config.configure_task("add", add, intermediate_cfg, output_cfg) def compare_function(*data_node_results): # example of function compare_result = {} current_res_i = 0 for current_res in data_node_results: compare_result[current_res_i] = {} next_res_i = 0 for next_res in data_node_results: print(f"comparing result {current_res_i} with result {next_res_i}") compare_result[current_res_i][next_res_i] = next_res - current_res next_res_i += 1 current_res_i += 1 return compare_result scenario_cfg = Config.configure_scenario(id="multiply_scenario", name="my_scenario", task_configs=[first_task_cfg, second_task_cfg], comparators={output_cfg.id: compare_function}) Config.export("config_08.toml") if __name__=="__main__": tp.Core().run() scenario_1 = tp.create_scenario(scenario_cfg) scenario_2 = tp.create_scenario(scenario_cfg) scenario_1.input.write(10) scenario_2.input.write(8) scenario_1.submit() scenario_2.submit() print(tp.compare_scenarios(scenario_1, scenario_2)) |
from taipy.gui import Gui, notify text = "Original text" # Definition of the page page = """ # Getting started with Taipy GUI My text: <|{text}|> <|{text}|input|> <|Run local|button|on_action=on_button_action|> """ def on_button_action(state): notify(state, 'info', f'The text is: {state.text}') state.text = "Button Pressed" def on_change(state, var_name, var_value): if var_name == "text" and var_value == "Reset": state.text = "" return Gui(page).run(debug=True) |
from transformers import AutoTokenizer from transformers import AutoModelForSequenceClassification from scipy.special import softmax import numpy as np import pandas as pd from taipy.gui import Gui, notify text = "Original text" page = """ # Getting started with Taipy GUI <|layout|columns=1 1| <| My text: <|{text}|> Enter a word: <|{text}|input|> <|Analyze|button|on_action=local_callback|> |> <|Table|expandable| <|{dataframe}|table|width=100%|number_format=%.2f|> |> |> <|layout|columns=1 1 1| ## Positive <|{np.mean(dataframe['Score Pos'])}|text|format=%.2f|raw|> ## Neutral <|{np.mean(dataframe['Score Neu'])}|text|format=%.2f|raw|> ## Negative <|{np.mean(dataframe['Score Neg'])}|text|format=%.2f|raw|> |> <|{dataframe}|chart|type=bar|x=Text|y[1]=Score Pos|y[2]=Score Neu|y[3]=Score Neg|y[4]=Overall|color[1]=green|color[2]=grey|color[3]=red|type[4]=line|> """ MODEL = f"cardiffnlp/twitter-roberta-base-sentiment" tokenizer = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForSequenceClassification.from_pretrained(MODEL) dataframe = pd.DataFrame({"Text":[''], "Score Pos":[0.33], "Score Neu":[0.33], "Score Neg":[0.33], "Overall":[0]}) dataframe2 = dataframe.copy() def analyze_text(text): # Run for Roberta Model encoded_text = tokenizer(text, return_tensors='pt') output = model(**encoded_text) scores = output[0][0].detach().numpy() scores = softmax(scores) return {"Text":text[:50], "Score Pos":scores[2], "Score Neu":scores[1], "Score Neg":scores[0], "Overall":scores[2]-scores[0]} def local_callback(state): notify(state, 'Info', f'The text is: {state.text}', True) temp = state.dataframe.copy() scores = analyze_text(state.text) temp.loc[len(temp)] = scores state.dataframe = temp state.text = "" path = "" treatment = 0 page_file = """ <|{path}|file_selector|extensions=.txt|label=Upload .txt file|on_action=analyze_file|> <|{f'Downloading {treatment}%...'}|> <br/> <|Table|expandable| <|{dataframe2}|table|width=100%|number_format=%.2f|> |> <br/> <|{dataframe2}|chart|type=bar|x=Text|y[1]=Score Pos|y[2]=Score Neu|y[3]=Score Neg|y[4]=Overall|color[1]=green|color[2]=grey|color[3]=red|type[4]=line|height=600px|> """ def analyze_file(state): state.dataframe2 = dataframe2 state.treatment = 0 with open(state.path,"r", encoding='utf-8') as f: data = f.read() # split lines and eliminates duplicates file_list = list(dict.fromkeys(data.replace('\n', ' ').split(".")[:-1])) for i in range(len(file_list)): text = file_list[i] state.treatment = int((i+1)*100/len(file_list)) temp = state.dataframe2.copy() scores = analyze_text(text) temp.loc[len(temp)] = scores state.dataframe2 = temp state.path = None pages = {"/":"<|toggle|theme|>\n<center>\n<|navbar|>\n</center>", "line":page, "text":page_file} Gui(pages=pages).run(debug=True) |
from transformers import AutoTokenizer from transformers import AutoModelForSequenceClassification from scipy.special import softmax import numpy as np import pandas as pd from taipy.gui import Gui, notify text = "Original text" page = """ # Getting started with Taipy GUI <|layout|columns=1 1| <| My text: <|{text}|> Enter a word: <|{text}|input|> <|Analyze|button|on_action=local_callback|> |> <|Table|expandable| <|{dataframe}|table|width=100%|number_format=%.2f|> |> |> <|layout|columns=1 1 1| ## Positive <|{float(np.mean(dataframe['Score Pos']))}|text|format=%.2f|raw|>% ## Neutral <|{float(np.mean(dataframe['Score Neu']))}|text|format=%.2f|raw|>% ## Negative <|{float(np.mean(dataframe['Score Neg']))}|text|format=%.2f|raw|>% |> <br/> <|{dataframe}|chart|type=bar|x=Text|y[1]=Score Pos|y[2]=Score Neu|y[3]=Score Neg|y[4]=Overall|color[1]=green|color[2]=grey|color[3]=red|type[4]=line|> """ MODEL = f"cardiffnlp/twitter-roberta-base-sentiment" tokenizer = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForSequenceClassification.from_pretrained(MODEL) dataframe = pd.DataFrame({"Text":[''], "Score Pos":[0.33], "Score Neu":[0.33], "Score Neg":[0.33], "Overall":[0]}) def analyze_text(text): # Run for Roberta Model encoded_text = tokenizer(text, return_tensors='pt') output = model(**encoded_text) scores = output[0][0].detach().numpy() scores = softmax(scores) return {"Text":text, "Score Pos":scores[2], "Score Neu":scores[1], "Score Neg":scores[0], "Overall":scores[2]-scores[0]} def local_callback(state): notify(state, 'Info', f'The text is: {state.text}', True) temp = state.dataframe.copy() scores = analyze_text(state.text) temp.loc[len(temp)] = scores state.dataframe = temp state.text = "" Gui(page).run(debug=True) |
from taipy.gui import Gui text = "Original text" page = """ # Getting started with Taipy GUI My text: <|{text}|> <|{text}|input|> """ Gui(page).run(debug=True) |
from transformers import AutoTokenizer from transformers import AutoModelForSequenceClassification from scipy.special import softmax import numpy as np import pandas as pd from taipy.gui import Gui, notify text = "Original text" MODEL = f"cardiffnlp/twitter-roberta-base-sentiment" tokenizer = AutoTokenizer.from_pretrained(MODEL) model = AutoModelForSequenceClassification.from_pretrained(MODEL) dataframe = pd.DataFrame({"Text":[''], "Score Pos":[0.33], "Score Neu":[0.33], "Score Neg":[0.33], "Overall":[0]}) # Torch is, for now, only available for the Python version between 3.8 and 3.10. # If you cannot install these packages, just return a dictionary of random numbers for the `analyze_text(text).` def analyze_text(text): # Run for Roberta Model encoded_text = tokenizer(text, return_tensors='pt') output = model(**encoded_text) scores = output[0][0].detach().numpy() scores = softmax(scores) return {"Text":text, "Score Pos":scores[2], "Score Neu":scores[1], "Score Neg":scores[0], "Overall":scores[2]-scores[0]} def local_callback(state): notify(state, 'Info', f'The text is: {state.text}', True) temp = state.dataframe.copy() scores = analyze_text(state.text) temp.loc[len(temp)] = scores state.dataframe = temp state.text = "" page = """ <|toggle|theme|> # Getting started with Taipy GUI My text: <|{text}|> Enter a word: <|{text}|input|> <|Analyze|button|on_action=local_callback|> ## Positive <|{float(np.mean(dataframe['Score Pos']))}|text|format=%.2f|>% ## Neutral <|{float(np.mean(dataframe['Score Neu']))}|text|format=%.2f|>% ## Negative <|{float(np.mean(dataframe['Score Neg']))}|text|format=%.2f|>% <|{dataframe}|table|number_format=%.2f|> <|{dataframe}|chart|type=bar|x=Text|y[1]=Score Pos|y[2]=Score Neu|y[3]=Score Neg|y[4]=Overall|color[1]=green|color[2]=grey|color[3]=red|type[4]=line|> """ Gui(page).run(debug=True) |
from taipy import Gui Gui(page="# Getting started with *Taipy*").run(debug=True) |
import pandas as pd from taipy.gui import Gui, notify text = "Original text" page = """ <|toggle|theme|> # Getting started with Taipy GUI My text: <|{text}|> <|{text}|input|> <|Analyze|button|on_action=local_callback|> <|{dataframe}|table|number_format=%.2f|> <|{dataframe}|chart|type=bar|x=Text|y[1]=Score Pos|y[2]=Score Neu|y[3]=Score Neg|y[4]=Overall|color[1]=green|color[2]=grey|color[3]=red|type[4]=line|> """ dataframe = pd.DataFrame({"Text":['Test', 'Other', 'Love'], "Score Pos":[1, 1, 4], "Score Neu":[2, 3, 1], "Score Neg":[1, 2, 0], "Overall":[0, -1, 4]}) def local_callback(state): notify(state, 'info', f'The text is: {state.text}') temp = state.dataframe.copy() temp.loc[len(temp)] = {"Text":state.text, "Score Pos":0, "Score Neu":0, "Score Neg":0, "Overall":0} state.dataframe = temp state.text = "" Gui(page).run(debug=True) |
from taipy.config import Config from taipy.core import Status import taipy as tp import time # Normal function used by Taipy def double(nb): return nb * 2 def add(nb): return nb + 10 # Configuration of Data Nodes input_cfg = Config.configure_data_node("input", default_data=21) intermediate_cfg = Config.configure_data_node("intermediate") output_cfg = Config.configure_data_node("output") # Configuration of tasks first_task_cfg = Config.configure_task("double", double, input_cfg, intermediate_cfg) second_task_cfg = Config.configure_task("add", add, intermediate_cfg, output_cfg) def callback_scenario_state(scenario, job): """All the scenarios are subscribed to the callback_scenario_state function. It means whenever a job is done, it is called. Depending on the job and the status, it will update the message stored in a json that is then displayed on the GUI. Args: scenario (Scenario): the scenario of the job changed job (_type_): the job that has its status changed """ print(f'{job.id} to {job.status}') if job.status == Status.COMPLETED: for data_node in job.task.output.values(): print("Data node value:", data_node.read()) # Configuration of scenario scenario_cfg = Config.configure_scenario(id="my_scenario", task_configs=[first_task_cfg, second_task_cfg], name="my_scenario") if __name__=="__main__": tp.Core().run() scenario_1 = tp.create_scenario(scenario_cfg) scenario_1.subscribe(callback_scenario_state) scenario_1.submit(wait=True) from taipy.gui import Gui, notify def on_submission_status_change(state=None, submittable=None, details=None): submission_status = details.get('submission_status') if submission_status == 'COMPLETED': print(f"{submittable.name} has completed.") notify(state, 'success', 'Completed!') # Add additional actions here, like updating the GUI or logging the completion. elif submission_status == 'FAILED': print(f"{submittable.name} has failed.") notify(state, 'error', 'Completed!') # Handle failure, like sending notifications or logging the error. # Add more conditions for other statuses as needed. if __name__=="__main__": scenario_md = """ <|{scenario_1}|scenario|on_submission_change=on_submission_status_change|> """ Gui(scenario_md).run() |
""" A multi-page Taipy application, which includes 3 pages: - A rootpage which is shared by other pages. - Two pages named page_1 and page_2. Please refer to ../../manuals/gui/pages for more details. """ from pages import data_viz, scenario_page, performance from pages.root import * from configuration.config import * from taipy.gui import Gui import taipy as tp def on_change(state, var_name: str, var_value): state['scenario'].on_change(state, var_name, var_value) pages = { "/": root_page, "data_viz": data_viz, "scenario": scenario_page, "performance": performance } if __name__ == "__main__": tp.Core().run() gui = Gui(pages=pages) gui.run(title="Taipy Application") |
import datetime as dt import pandas as pd from taipy import Config, Scope, Frequency from algorithms.algorithms import * path_to_csv = "data/dataset.csv" # Datanodes (3.1) ## Input Data Nodes initial_dataset_cfg = Config.configure_data_node(id="initial_dataset", storage_type="csv", path=path_to_csv, scope=Scope.GLOBAL) # We assume the current day is the 26th of July 2021. # This day can be changed to simulate multiple executions of scenarios on different days day_cfg = Config.configure_data_node(id="day", default_data=dt.datetime(2021, 7, 26)) n_predictions_cfg = Config.configure_data_node(id="n_predictions", default_data=40) max_capacity_cfg = Config.configure_data_node(id="max_capacity", default_data=200) ## Remaining Data Nodes cleaned_dataset_cfg = Config.configure_data_node(id="cleaned_dataset", scope=Scope.GLOBAL) predictions_baseline_cfg = Config.configure_data_node(id="predictions_baseline") predictions_ml_cfg = Config.configure_data_node(id="predictions_ml") full_predictions_cfg = Config.configure_data_node(id="full_predictions") metrics_baseline_cfg = Config.configure_data_node(id="metrics_baseline") metrics_ml_cfg = Config.configure_data_node(id="metrics_ml") # Functions (3.2) # Tasks (3.3) clean_data_task_cfg = Config.configure_task(id="task_clean_data", function=clean_data, input=initial_dataset_cfg, output=cleaned_dataset_cfg, skippable=True) predict_baseline_task_cfg = Config.configure_task(id="predict_baseline", function=predict_baseline, input=[cleaned_dataset_cfg, n_predictions_cfg, day_cfg, max_capacity_cfg], output=predictions_baseline_cfg) predict_ml_task_cfg = Config.configure_task(id="task_predict_ml", function=predict_ml, input=[cleaned_dataset_cfg, n_predictions_cfg, day_cfg, max_capacity_cfg], output=predictions_ml_cfg) metrics_baseline_task_cfg = Config.configure_task(id="task_metrics_baseline", function=compute_metrics, input=[cleaned_dataset_cfg, predictions_baseline_cfg], output=metrics_baseline_cfg) metrics_ml_task_cfg = Config.configure_task(id="task_metrics_ml", function=compute_metrics, input=[cleaned_dataset_cfg, predictions_ml_cfg], output=metrics_ml_cfg) full_predictions_task_cfg = Config.configure_task(id="task_full_predictions", function=create_predictions_dataset, input=[predictions_baseline_cfg, predictions_ml_cfg, day_cfg, n_predictions_cfg, cleaned_dataset_cfg], output=full_predictions_cfg) # Configure our scenario which is our business problem. scenario_cfg = Config.configure_scenario(id="scenario", task_configs=[clean_data_task_cfg, predict_baseline_task_cfg, predict_ml_task_cfg, metrics_baseline_task_cfg, metrics_ml_task_cfg, full_predictions_task_cfg], frequency=Frequency.WEEKLY) |
# To make things clear, we've opted for an AutoRegressive model instead of a pure ML model like: # Random Forest, Linear Regression, LSTM, etc from statsmodels.tsa.ar_model import AutoReg import pandas as pd from sklearn.metrics import mean_squared_error, mean_absolute_error import numpy as np import datetime as dt def clean_data(initial_dataset: pd.DataFrame): print(" Cleaning data") # Convert the date column to datetime initial_dataset['Date'] = pd.to_datetime(initial_dataset['Date']) cleaned_dataset = initial_dataset.copy() return cleaned_dataset def predict_baseline(cleaned_dataset: pd.DataFrame, n_predictions: int, day: dt.datetime, max_capacity: int): print(" Predicting baseline") # Select the train data train_dataset = cleaned_dataset[cleaned_dataset['Date'] < day] predictions = train_dataset['Value'][-n_predictions:].reset_index(drop=True) predictions = predictions.apply(lambda x: min(x, max_capacity)) return predictions # This is the function that will be used by the task def predict_ml(cleaned_dataset: pd.DataFrame, n_predictions: int, day: dt.datetime, max_capacity: int): print(" Predicting with ML") # Select the train data train_dataset = cleaned_dataset[cleaned_dataset["Date"] < day] # Fit the AutoRegressive model model = AutoReg(train_dataset["Value"], lags=7).fit() # Get the n_predictions forecasts predictions = model.forecast(n_predictions).reset_index(drop=True) predictions = predictions.apply(lambda x: min(x, max_capacity)) return predictions def compute_metrics(historical_data, predicted_data): historical_to_compare = historical_data[-len(predicted_data):]['Value'] rmse = mean_squared_error(historical_to_compare, predicted_data) mae = mean_absolute_error(historical_to_compare, predicted_data) return rmse, mae def create_predictions_dataset(predictions_baseline, predictions_ml, day, n_predictions, cleaned_data): print("Creating predictions dataset...") # Create the historical dataset that will be displayed new_length = len(cleaned_data[cleaned_data["Date"] < day]) + n_predictions historical_data = cleaned_data[:new_length].reset_index(drop=True) create_series = lambda data, name: pd.Series([np.NaN] * (len(historical_data)), name=name).fillna({i: val for i, val in enumerate(data, len(historical_data)-n_predictions)}) predictions_dataset = pd.concat([ historical_data["Date"], historical_data["Value"].rename("Historical values"), create_series(predictions_ml, "Predicted values ML"), create_series(predictions_baseline, "Predicted values Baseline") ], axis=1) return predictions_dataset |
from .data_viz import data_viz from .scenario import scenario_page from .performance import performance from .root import root_page |
""" The rootpage of the application. Page content is imported from the root.md file. Please refer to ../../manuals/gui/pages for more details. """ from taipy.gui import Markdown root_page = Markdown("pages/root.md") |
from .scenario import scenario_page |
""" The second page of the application. Page content is imported from the page_2.md file. Please refer to ../../manuals/gui/pages for more details. """ from taipy.gui import Markdown, notify import datetime as dt import pandas as pd scenario = None data_node = None day = dt.datetime(2021, 7, 26) n_predictions = 40 max_capacity = 200 predictions_dataset = {"Date":[dt.datetime(2021, 7, 26)], "Predicted values ML":[0], "Predicted values Baseline":[0], "Historical values":[0]} def submission_change(state, submittable, details: dict): if details['submission_status'] == 'COMPLETED': notify(state, "success", 'Scenario completed!') state['scenario'].on_change(state, 'scenario', state.scenario) else: notify(state, "error", 'Something went wrong!') def save(state): print("Saving scenario...") # Get the currently selected scenario # Conversion to the right format state_day = dt.datetime(state.day.year, state.day.month, state.day.day) # Change the default parameters by writing in the Data Nodes state.scenario.day.write(state_day) state.scenario.n_predictions.write(int(state.n_predictions)) state.scenario.max_capacity.write(int(state.max_capacity)) notify(state, "success", "Saved!") def on_change(state, var_name, var_value): if var_name == "scenario" and var_value: state.day = state.scenario.day.read() state.n_predictions = state.scenario.n_predictions.read() state.max_capacity = state.scenario.max_capacity.read() if state.scenario.full_predictions.is_ready_for_reading: state.predictions_dataset = state.scenario.full_predictions.read()[-200:] else: state.predictions_dataset = predictions_dataset scenario_page = Markdown("pages/scenario/scenario.md") |
from .data_viz import data_viz |
""" The first page of the application. Page content is imported from the page_1.md file. Please refer to ../../manuals/gui/pages for more details. """ from taipy.gui import Markdown import pandas as pd def get_data(path_to_csv: str): # pandas.read_csv() returns a pd.DataFrame dataset = pd.read_csv(path_to_csv) dataset["Date"] = pd.to_datetime(dataset["Date"]) return dataset # Read the dataframe path_to_csv = "data/dataset.csv" dataset = get_data(path_to_csv) # Initial value n_week = 10 # Select the week based on the slider value dataset_week = dataset[dataset["Date"].dt.isocalendar().week == n_week] def on_slider(state): state.dataset_week = dataset[dataset["Date"].dt.isocalendar().week == state.n_week] data_viz = Markdown("pages/data_viz/data_viz.md") |
from .performance import performance |
from taipy.gui import Markdown import pandas as pd import taipy as tp # Initial dataset for comparison comparison_scenario = pd.DataFrame(columns=["Scenario Name", "RMSE baseline", "MAE baseline", "RMSE ML", "MAE ML"]) # Selector for metrics metric_selector = ["RMSE", "MAE"] selected_metric = metric_selector[0] def compare(state): print("Comparing...") # Initialize lists for comparison scenario_data = [] # Go through all the primary scenarios all_scenarios = sorted(tp.get_primary_scenarios(), key=lambda x: x.creation_date.timestamp()) for scenario in all_scenarios: rmse_baseline, mae_baseline = scenario.metrics_baseline.read() rmse_ml, mae_ml = scenario.metrics_ml.read() # Store scenario data in a dictionary scenario_data.append({ "Scenario Name": scenario.name, "RMSE baseline": rmse_baseline, "MAE baseline": mae_baseline, "RMSE ML": rmse_ml, "MAE ML": mae_ml }) # Create a DataFrame from the scenario_data list state.comparison_scenario = pd.DataFrame(scenario_data) performance = Markdown("pages/performance/performance.md") |
import taipy as tp from taipy import Config, Core, Gui ################################################################ # Configure application # ################################################################ def build_message(name): return f"Hello {name}!" # A first data node configuration to model an input name. input_name_data_node_cfg = Config.configure_data_node(id="input_name") # A second data node configuration to model the message to display. message_data_node_cfg = Config.configure_data_node(id="message") # A task configuration to model the build_message function. build_msg_task_cfg = Config.configure_task("build_msg", build_message, input_name_data_node_cfg, message_data_node_cfg) # The scenario configuration represents the whole execution graph. scenario_cfg = Config.configure_scenario("scenario", task_configs=[build_msg_task_cfg]) ################################################################ # Design graphical interface # ################################################################ input_name = "Taipy" message = None def submit_scenario(state): state.scenario.input_name.write(state.input_name) state.scenario.submit() state.message = scenario.message.read() page = """ Name: <|{input_name}|input|> <|submit|button|on_action=submit_scenario|> Message: <|{message}|text|> """ if __name__ == "__main__": ################################################################ # Instantiate and run Core service # ################################################################ Core().run() ################################################################ # Manage scenarios and data nodes # ################################################################ scenario = tp.create_scenario(scenario_cfg) ################################################################ # Instantiate and run Gui service # ################################################################ Gui(page).run() |
import taipy as tp from taipy import Config, Core ################################################################ # Configure application # ################################################################ def build_message(name): return f"Hello {name}!" # A first data node configuration to model an input name. input_name_data_node_cfg = Config.configure_data_node(id="input_name") # A second data node configuration to model the message to display. message_data_node_cfg = Config.configure_data_node(id="message") # A task configuration to model the build_message function. build_msg_task_cfg = Config.configure_task("build_msg", build_message, input_name_data_node_cfg, message_data_node_cfg) # The scenario configuration represents the whole execution graph. scenario_cfg = Config.configure_scenario("scenario", task_configs=[build_msg_task_cfg]) if __name__ == "__main__": ################################################################ # Instantiate and run Core service # ################################################################ Core().run() ################################################################ # Manage scenarios and data nodes # ################################################################ hello_scenario = tp.create_scenario(scenario_cfg) hello_scenario.input_name.write("Taipy") hello_scenario.submit() print(hello_scenario.message.read()) |
import taipy as tp from taipy import Gui from taipy import Config from taipy import Core # Configure application def build_message(name: str)-> str: return f"Received message : {name}" # A first data node configuration to model an input name. input_name_data_node_cfg = Config.configure_data_node(id="input_name") # A second data node configuration to model the message to display message_data_node_cfg = Config.configure_data_node(id="message") # Configure task between input and output data nodes build_msg_task_cfg = Config.configure_task("build_msg", build_message, input_name_data_node_cfg,message_data_node_cfg) # Scenario Configuration to represent execution graph scenario_cfg = Config.configure_scenario("scenario", task_configs=[build_msg_task_cfg]) # Function to handle state from GUI input_name = "Taipy" message = None def submit_scenario(state): state.scenario.input_name.write(state.input_name) state.scenario.submit() state.message = scenario.message.read() # Markdown representation of the user interface page = """ Name: <|{input_name}|input|> <|submit|button|on_action=submit_scenario|> Message: <|{message}|text|> """ if __name__ == "__main__": # Instantiate and run Core service Core().run() # Instantiate the new scenario name hello_scenario from the scenario configuration built before hello_scenario = tp.create_scenario(scenario_cfg) # Run GUI Gui(page).run() |
import taipy as tp from taipy import Config from taipy import Core def build_message(name: str)-> str: return f"Received message : {name}" # A first data node configuration to model an input name. input_name_data_node_cfg = Config.configure_data_node(id="input_name") # A second data node configuration to model the message to display message_data_node_cfg = Config.configure_data_node(id="message") # Configure task between input and output data nodes build_msg_task_cfg = Config.configure_task("build_msg", build_message, input_name_data_node_cfg,message_data_node_cfg) # Scenario Configuration to represent execution graph scenario_cfg = Config.configure_scenario("scenario", task_configs=[build_msg_task_cfg]) if __name__ == "__main__": # Instantiate and run Core service Core().run() # Instantiate the new scenario name hello_scenario from the scenario configuration built before hello_scenario = tp.create_scenario(scenario_cfg) # sets the input data node input_name of hello_scenario with the string value hello_scenario.input_name.write("In God We Trust !") # submits the hello_scenario for execution, which triggers the creation and execution of a job hello_scenario.submit() # reads and prints the output data node message written by the execution of the scenario hello_scenario print(hello_scenario.message.read()) |
print("----------------------------------------------") print("---------------------TEST---------------------") print("----------------------------------------------") |
import os import shutil import pytest @pytest.fixture(scope="function") def tmp_sqlite(tmpdir_factory): fn = tmpdir_factory.mktemp("db") return os.path.join(fn.strpath, "test.db") @pytest.fixture(autouse=True) def cleanup_data(): from time import sleep from sqlalchemy.orm import close_all_sessions close_all_sessions() sleep(0.1) if os.path.exists(".data"): shutil.rmtree(".data", ignore_errors=True) if os.path.exists("test.db"): os.remove("test.db") init_managers() init_config() init_orchestrator() init_managers() init_config() def init_config(): from taipy import Config from taipy.config import IssueCollector from taipy.config._config import _Config from taipy.config._serializer._toml_serializer import _TomlSerializer from taipy.config.checker._checker import _Checker from taipy.core.config import ( CoreSection, DataNodeConfig, JobConfig, ScenarioConfig, TaskConfig, _DataNodeConfigChecker, _inject_section, _JobConfigChecker, _ScenarioConfigChecker, _TaskConfigChecker, ) Config.unblock_update() Config._default_config = _Config()._default_config() Config._python_config = _Config() Config._file_config = None Config._env_file_config = None Config._applied_config = _Config._default_config() Config._collector = IssueCollector() Config._serializer = _TomlSerializer() _Checker._checkers = [] _inject_section( JobConfig, "job_config", JobConfig("development"), [("configure_job_executions", JobConfig._configure)], True ) _inject_section( DataNodeConfig, "data_nodes", DataNodeConfig.default_config(), [ ("configure_data_node", DataNodeConfig._configure), ("configure_default_data_node", DataNodeConfig._set_default_configuration), ("configure_csv_data_node", DataNodeConfig._configure_csv), ("configure_json_data_node", DataNodeConfig._configure_json), ("configure_sql_table_data_node", DataNodeConfig._configure_sql_table), ("configure_sql_data_node", DataNodeConfig._configure_sql), ("configure_mongo_collection_data_node", DataNodeConfig._configure_mongo_collection), ("configure_in_memory_data_node", DataNodeConfig._configure_in_memory), ("configure_pickle_data_node", DataNodeConfig._configure_pickle), ("configure_excel_data_node", DataNodeConfig._configure_excel), ("configure_generic_data_node", DataNodeConfig._configure_generic), ], ) _inject_section( TaskConfig, "tasks", TaskConfig.default_config(), [("configure_task", TaskConfig._configure), ("configure_default_task", TaskConfig._set_default_configuration)], ) _inject_section( ScenarioConfig, "scenarios", ScenarioConfig.default_config(), [ ("configure_scenario", ScenarioConfig._configure), ("configure_default_scenario", ScenarioConfig._set_default_configuration), ], ) _inject_section( CoreSection, "core", CoreSection.default_config(), [("configure_core", CoreSection._configure)], add_to_unconflicted_sections=True, ) _Checker.add_checker(_JobConfigChecker) _Checker.add_checker(_DataNodeConfigChecker) _Checker.add_checker(_TaskConfigChecker) _Checker.add_checker(_ScenarioConfigChecker) def init_managers(): from taipy.core._version._version_manager_factory import _VersionManagerFactory from taipy.core.cycle._cycle_manager_factory import _CycleManagerFactory from taipy.core.data._data_manager_factory import _DataManagerFactory from taipy.core.job._job_manager_factory import _JobManagerFactory from taipy.core.scenario._scenario_manager_factory import _ScenarioManagerFactory from taipy.core.sequence._sequence_manager_factory import _SequenceManagerFactory from taipy.core.task._task_manager_factory import _TaskManagerFactory _CycleManagerFactory._build_manager()._delete_all() _ScenarioManagerFactory._build_manager()._delete_all() _SequenceManagerFactory._build_manager()._delete_all() _JobManagerFactory._build_manager()._delete_all() _TaskManagerFactory._build_manager()._delete_all() _DataManagerFactory._build_manager()._delete_all() _VersionManagerFactory._build_manager()._delete_all() def init_orchestrator(): from queue import Queue from taipy.core._orchestrator._orchestrator_factory import _OrchestratorFactory if _OrchestratorFactory._orchestrator is None: _OrchestratorFactory._build_orchestrator() _OrchestratorFactory._build_dispatcher(force_restart=True) _OrchestratorFactory._orchestrator.jobs_to_run = Queue() _OrchestratorFactory._orchestrator.blocked_jobs = [] |
import os import pickle import taipy.core as tp from taipy.config import Config def test_pickle_files(): from tests.shared_test_cases.pickle_files import ( PICKLE_DICT_INPUT_PATH, PICKLE_DICT_OUTPUT_PATH, PICKLE_LIST_INPUT_PATH, PICKLE_LIST_OUTPUT_PATH, ROW_COUNT, gen_list_of_dict_input_pickle, gen_list_of_objects_input_pickle, scenario_cfg_1, scenario_cfg_2, ) tp.clean_all_entities_by_version(None) # generate 2 pickles files gen_list_of_dict_input_pickle(PICKLE_DICT_INPUT_PATH, ROW_COUNT) gen_list_of_objects_input_pickle(PICKLE_LIST_INPUT_PATH, ROW_COUNT) with open(PICKLE_DICT_INPUT_PATH, "rb") as f: dict_data = pickle.load(f) with open(PICKLE_LIST_INPUT_PATH, "rb") as f: list_data = pickle.load(f) # π List of dicts scenario_1 = tp.create_scenario(scenario_cfg_1) input_data_node_1 = scenario_1.input_pickle_dataset_1 output_data_node_1 = scenario_1.output_pickle_dataset_1 read_data_1 = input_data_node_1.read() assert len(read_data_1) == ROW_COUNT assert read_data_1 == dict_data assert output_data_node_1.read() is None output_data_node_1.write(read_data_1) assert dict_data == output_data_node_1.read() output_data_node_1.write(None) assert output_data_node_1.read() is None scenario_1.submit() assert dict_data == output_data_node_1.read() os.remove(PICKLE_DICT_INPUT_PATH) os.remove(PICKLE_DICT_OUTPUT_PATH) # π List of objects scenario_2 = tp.create_scenario(scenario_cfg_2) input_data_node_2 = scenario_2.input_pickle_dataset_2 output_data_node_2 = scenario_2.output_pickle_dataset_2 read_data_2 = input_data_node_2.read() assert len(read_data_2) == ROW_COUNT assert read_data_2 == list_data assert output_data_node_2.read() is None output_data_node_2.write(read_data_2) assert list_data == output_data_node_2.read() output_data_node_2.write(None) assert output_data_node_2.read() is None scenario_2.submit() assert list_data == output_data_node_2.read() os.remove(PICKLE_LIST_INPUT_PATH) os.remove(PICKLE_LIST_OUTPUT_PATH) |
import os import shutil from io import StringIO from unittest.mock import patch import pytest from taipy._cli._scaffold_cli import _ScaffoldCLI from taipy._entrypoint import _entrypoint from tests.utils import clean_subparser @pytest.fixture(autouse=True, scope="function") def clean_templates(): clean_subparser() yield if os.path.exists("foo_app"): shutil.rmtree("foo_app", ignore_errors=True) if os.path.exists("bar_app"): shutil.rmtree("bar_app", ignore_errors=True) def test_default_template(): assert os.path.exists(_ScaffoldCLI._TEMPLATE_MAP["default"]) inputs = "\n".join(["foo_app", "main.py", "bar", "", "", ""]) with pytest.raises(SystemExit) as error: with patch("sys.stdin", StringIO(f"{inputs}\n")): with patch("sys.argv", ["prog", "create"]): _entrypoint() assert "foo_app" in os.listdir(os.getcwd()) assert error.value.code == 0 clean_subparser() inputs = "\n".join(["bar_app", "main.py", "bar", "", "", ""]) with pytest.raises(SystemExit) as error: with patch("sys.stdin", StringIO(f"{inputs}\n")): with patch("sys.argv", ["prog", "create", "--template", "default"]): _entrypoint() assert "bar_app" in os.listdir(os.getcwd()) assert error.value.code == 0 def test_scenario_management_template(): assert os.path.exists(_ScaffoldCLI._TEMPLATE_MAP["scenario-management"]) inputs = "\n".join(["foo_app", "main.py", "bar", ""]) with pytest.raises(SystemExit) as error: with patch("sys.stdin", StringIO(f"{inputs}\n")): with patch("sys.argv", ["prog", "create", "--template", "scenario-management"]): _entrypoint() assert "foo_app" in os.listdir(os.getcwd()) assert error.value.code == 0 def test_non_existing_template(capsys): with pytest.raises(SystemExit) as error: with patch("sys.argv", ["prog", "create", "--template", "non-existing-template"]): _entrypoint() assert error.value.code == 2 _, err_msg = capsys.readouterr() assert "argument --template: invalid choice: 'non-existing-template' (choose from" in err_msg |
import os from unittest.mock import patch import pandas as pd import taipy.core.taipy as tp from taipy.config import Config from taipy.core import Core from taipy.core.config.job_config import JobConfig from taipy.core.job.status import Status from .complex_application_configs import ( average, build_churn_classification_config, build_complex_config, build_complex_required_file_paths, build_skipped_jobs_config, ) def assert_true_after_time(assertion, msg=None, time=120): from datetime import datetime from time import sleep start = datetime.now() while (datetime.now() - start).seconds < time: sleep(1) # Limit CPU usage try: if assertion(): return except BaseException as e: print("Raise : ", e) continue if msg: print(msg) assert assertion() def test_skipped_jobs(): scenario_config = build_skipped_jobs_config() with patch("sys.argv", ["prog"]): Core().run() scenario = tp.create_scenario(scenario_config) scenario.input.write(2) scenario.submit() assert len(tp.get_jobs()) == 2 for job in tp.get_jobs(): assert job.status == Status.COMPLETED scenario.submit() assert len(tp.get_jobs()) == 4 skipped = [] for job in tp.get_jobs(): if job.status != Status.COMPLETED: assert job.status == Status.SKIPPED skipped.append(job) assert len(skipped) == 2 def test_complex_development(): # d1 --- t1 # | # | --- t2 --- d5 --- | t10 --- d12 # | | | # | | | # d2 | --- t5 --- d7 --- t7 --- d9 --- t8 --- d10 --- t9 --- d11 # | | | # d3 --- | | | | # | | | t6 --- d8 ------------------- # | t3 --- d6 ---| # | | # | | # t4 d4 _, _, csv_path_sum, excel_path_sum, excel_path_out, csv_path_out = build_complex_required_file_paths() scenario_config = build_complex_config() with patch("sys.argv", ["prog"]): Core().run(force_restart=True) scenario = tp.create_scenario(scenario_config) tp.submit(scenario) csv_sum_res = pd.read_csv(csv_path_sum) excel_sum_res = pd.read_excel(excel_path_sum) csv_out = pd.read_csv(csv_path_out) excel_out = pd.read_excel(excel_path_out) assert csv_sum_res.to_numpy().flatten().tolist() == [i * 20 for i in range(1, 11)] assert excel_sum_res.to_numpy().flatten().tolist() == [i * 2 for i in range(1, 11)] assert average(csv_sum_res["number"] - excel_sum_res["number"]) == csv_out.to_numpy()[0] assert average((csv_sum_res["number"] - excel_sum_res["number"]) * 10) == excel_out.to_numpy()[0] for path in [csv_path_sum, excel_path_sum, csv_path_out, excel_path_out]: os.remove(path) def test_complex_standlone(): # d1 --- t1 # | # | --- t2 --- d5 --- | t10 --- d12 # | | | # | | | # d2 | --- t5 --- d7 --- t7 --- d9 --- t8 --- d10 --- t9 --- d11 # | | | # d3 --- | | | | # | | | t6 --- d8 ------------------- # | t3 --- d6 ---| # | | # | | # t4 d4 _, _, csv_path_sum, excel_path_sum, excel_path_out, csv_path_out = build_complex_required_file_paths() scenario_config = build_complex_config() Config.configure_job_executions(mode=JobConfig._STANDALONE_MODE, max_nb_of_workers=2) with patch("sys.argv", ["prog"]): Core().run(force_restart=True) scenario = tp.create_scenario(scenario_config) jobs = tp.submit(scenario) assert_true_after_time(lambda: os.path.exists(csv_path_out) and os.path.exists(excel_path_out)) assert_true_after_time(lambda: all([job._status == Status.COMPLETED for job in jobs])) csv_sum_res = pd.read_csv(csv_path_sum) excel_sum_res = pd.read_excel(excel_path_sum) csv_out = pd.read_csv(csv_path_out) excel_out = pd.read_excel(excel_path_out) assert csv_sum_res.to_numpy().flatten().tolist() == [i * 20 for i in range(1, 11)] assert excel_sum_res.to_numpy().flatten().tolist() == [i * 2 for i in range(1, 11)] assert average(csv_sum_res["number"] - excel_sum_res["number"]) == csv_out.to_numpy()[0] assert average((csv_sum_res["number"] - excel_sum_res["number"]) * 10) == excel_out.to_numpy()[0] for path in [csv_path_sum, excel_path_sum, csv_path_out, excel_path_out]: os.remove(path) def test_churn_classification_development(): scenario_cfg = build_churn_classification_config() with patch("sys.argv", ["prog"]): Core().run(force_restart=True) scenario = tp.create_scenario(scenario_cfg) jobs = tp.submit(scenario) for job in jobs: if not job.is_completed(): print(job._task.config_id) assert all([job.is_completed() for job in jobs]) def test_churn_classification_standalone(): scenario_cfg = build_churn_classification_config() Config.configure_job_executions(mode=JobConfig._STANDALONE_MODE, max_nb_of_workers=2) with patch("sys.argv", ["prog"]): Core().run(force_restart=True) scenario = tp.create_scenario(scenario_cfg) jobs = tp.submit(scenario) assert_true_after_time(lambda: os.path.exists(scenario.results._path)) assert_true_after_time(lambda: all([job._status == Status.COMPLETED for job in jobs]), time=15) |
from typing import Optional from flask_testing import TestCase from taipy.rest import Rest from tests.shared_test_cases.arima import build_arima_config class BaseTestCase(TestCase): def create_app(self): rest = Rest() rest._app.config["TESTING"] = True return rest._app class RestTest(BaseTestCase): def _create(self, entity: str, config_id: str): return self.client.post(f"/api/v1/{entity}?config_id={config_id}") def _get(self, entity: str, id: Optional[str] = None): url = f"/api/v1/{entity}" if id: url = f"{url}/{id}" return self.client.get(url) def test_create_scenario_should_create_every_entity(self): build_arima_config() response = self._create("scenarios", "Arima_scenario") assert response.status_code == 201 assert response.json["message"] == "Scenario was created." all_scenarios = self._get("scenarios") all_data_nodes = self._get("datanodes") all_tasks = self._get("tasks") assert len(all_scenarios.json) == 1 assert len(all_data_nodes.json) == 4 assert len(all_tasks.json) == 2 def test_submit_scenario(self): build_arima_config() response = self._create("scenarios", "Arima_scenario") assert response.status_code == 201 scenario_id = response.json["scenario"]["id"] response = self.client.post(f"/api/v1/scenarios/submit/{scenario_id}") assert response.status_code == 200 assert response.json == {"message": f"Scenario {scenario_id} was submitted."} all_jobs = self._get("jobs") for jb in all_jobs.json: assert jb["status"] == "Status.COMPLETED" |
# # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. |
import taipy as tp from tests.shared_test_cases.arima.config import build_arima_config def test_submit_scenario_submit_success(): arima_scenario_config = build_arima_config() scenario = tp.create_scenario(arima_scenario_config) tp.submit(scenario) assert scenario.forecast_values.read() is not None assert len(tp.get_tasks()) == 2 assert len(tp.get_jobs()) == 2 assert len(tp.get_data_nodes()) == 4 |
from taipy._cli._base_cli import _CLI def clean_subparser(): if getattr(_CLI._parser, "_subparsers", None): # Loop over all subparsers to find the one that has nested-subparsers and positional arguments for choice in _CLI._parser._subparsers._group_actions[0].choices.values(): # Remove nested _subparsers choice._subparsers = None # Remove positional arguments # The "==SUPPRESS==" is a hack to identify nested-subparsers as positional arguments to_remove = ["application_main_file", "==SUPPRESS=="] actions = choice._actions.copy() for action in actions: opts = action.option_strings if (opts and opts[0] in to_remove) or action.dest in to_remove: choice._remove_action(action) for argument_group in choice._action_groups: for group_action in argument_group._group_actions: opts = group_action.option_strings if (opts and opts[0] in to_remove) or group_action.dest in to_remove: argument_group._group_actions.remove(group_action) def assert_true_after_time(assertion, msg=None, time=120): from datetime import datetime from time import sleep start = datetime.now() while (datetime.now() - start).seconds < time: print(f"waiting {(datetime.now() - start).seconds} seconds...", end="\r") try: if assertion(): print(f"waiting {(datetime.now() - start).seconds} seconds...") return except BaseException as e: print("Raise : ", e) sleep(1) # Limit CPU usage continue print(f"waiting {(datetime.now() - start).seconds} seconds...") if msg: print(msg) assert assertion() |
import os import modin.pandas as modin_pd import numpy as np import pandas as pd import taipy.core as tp from taipy.config import Config def test_excel(): from tests.shared_test_cases.single_excel_sheet import ( EXCEL_SINGLE_SHEET_INPUT_PATH, EXCEL_SINGLE_SHEET_OUTPUT_PATH, ROW_COUNT, Row, scenario_cfg, scenario_cfg_2, scenario_cfg_3, scenario_cfg_4, ) pandas_data = pd.read_excel(EXCEL_SINGLE_SHEET_INPUT_PATH) numpy_data = pandas_data.to_numpy() modin_data = modin_pd.read_excel(EXCEL_SINGLE_SHEET_INPUT_PATH) custom_data = [ Row(int(v.id), int(v.age), float(v.rating)) for i, v in pd.read_excel(EXCEL_SINGLE_SHEET_INPUT_PATH).iterrows() ] tp.clean_all_entities_by_version(None) # π Without exposed type (pandas is the default exposed type) scenario_1 = tp.create_scenario(scenario_cfg) input_data_node_1 = scenario_1.input_excel_single_sheet_dataset_1 output_data_node_1 = scenario_1.output_excel_single_sheet_dataset_1 read_data_1 = input_data_node_1.read() assert len(read_data_1) == ROW_COUNT assert pandas_data.equals(read_data_1) assert output_data_node_1.read() is None output_data_node_1.write(read_data_1) assert pandas_data.equals(output_data_node_1.read()) output_data_node_1.write(None) assert output_data_node_1.read().empty scenario_1.submit() assert pandas_data.equals(output_data_node_1.read()) os.remove(EXCEL_SINGLE_SHEET_OUTPUT_PATH) # π With custom class as exposed type def compare_custom_date(read_data, custom_data): return [ row_1.id == row_2.id and row_1.age == row_2.age and row_1.rating == row_2.rating for row_1, row_2 in zip(read_data, custom_data) ] scenario_2 = tp.create_scenario(scenario_cfg_2) input_data_node_2 = scenario_2.input_excel_single_sheet_dataset_2 output_data_node_2 = scenario_2.output_excel_single_sheet_dataset_2 read_data_2 = input_data_node_2.read() assert len(read_data_2) == ROW_COUNT assert all(compare_custom_date(read_data_2, custom_data)) output_data_node_2.write(read_data_2) assert len(read_data_2) == ROW_COUNT assert all(compare_custom_date(output_data_node_2.read(), custom_data)) output_data_node_2.write(None) assert isinstance(output_data_node_2.read(), list) assert len(output_data_node_2.read()) == 0 scenario_2.submit() assert all(compare_custom_date(output_data_node_2.read(), custom_data)) os.remove(EXCEL_SINGLE_SHEET_OUTPUT_PATH) # π With numpy as exposed type scenario_3 = tp.create_scenario(scenario_cfg_3) input_data_node_3 = scenario_3.input_excel_single_sheet_dataset_3 output_data_node_3 = scenario_3.output_excel_single_sheet_dataset_3 read_data_3 = input_data_node_3.read() assert len(read_data_3) == ROW_COUNT assert np.array_equal(read_data_3, numpy_data) assert output_data_node_3.read() is None output_data_node_3.write(read_data_3) assert np.array_equal(output_data_node_3.read(), numpy_data) output_data_node_3.write(None) assert isinstance(output_data_node_3.read(), np.ndarray) assert output_data_node_3.read().size == 0 scenario_3.submit() assert np.array_equal(output_data_node_3.read(), numpy_data) os.remove(EXCEL_SINGLE_SHEET_OUTPUT_PATH) # π With modin as exposed type scenario_4 = tp.create_scenario(scenario_cfg_4) input_data_node_4 = scenario_4.input_excel_single_sheet_dataset_4 output_data_node_4 = scenario_4.output_excel_single_sheet_dataset_4 read_data_4 = input_data_node_4.read() assert len(read_data_4) == ROW_COUNT assert all(modin_data._to_pandas() == read_data_4._to_pandas()) assert output_data_node_4.read() is None output_data_node_4.write(read_data_4) assert all(modin_data._to_pandas() == output_data_node_4.read()._to_pandas()) output_data_node_4.write(None) assert output_data_node_4.read().empty scenario_4.submit() assert all(modin_data._to_pandas() == output_data_node_4.read()._to_pandas()) os.remove(EXCEL_SINGLE_SHEET_OUTPUT_PATH) |
import os import modin.pandas as modin_pd import numpy as np import pandas as pd import pytest import taipy.core as tp from taipy.config import Config def test_excel_multi_sheet(): from tests.shared_test_cases.multi_excel_sheets import ( EXCEL_INPUT_PATH, EXCEL_OUTPUT_PATH, ROW_COUNT, SHEET_NAMES, Row, scenario_cfg, scenario_cfg_2, scenario_cfg_3, scenario_cfg_4, ) pandas_data = pd.read_excel(EXCEL_INPUT_PATH, sheet_name=SHEET_NAMES) numpy_data = {sheet_name: pandas_data[sheet_name].to_numpy() for sheet_name in SHEET_NAMES} modin_data = modin_pd.read_excel(EXCEL_INPUT_PATH, sheet_name=SHEET_NAMES) custom_data = {} for sheet_name in SHEET_NAMES: rows = [] for _, row in pandas_data[sheet_name].iterrows(): rows.append(Row(int(row.id), int(row.age), float(row.rating))) custom_data[sheet_name] = rows tp.clean_all_entities_by_version(None) # π Without exposed type (pandas is the default exposed type) scenario_1 = tp.create_scenario(scenario_cfg) input_data_node_1 = scenario_1.input_excel_multi_sheet_dataset_1 output_data_node_1 = scenario_1.output_excel_multi_sheet_dataset_1 read_data_1 = input_data_node_1.read() assert len(read_data_1) == len(SHEET_NAMES) assert all([pandas_data[sheet_name].equals(read_data_1[sheet_name]) for sheet_name in SHEET_NAMES]) assert output_data_node_1.read() is None output_data_node_1.write(read_data_1) assert len(output_data_node_1.read()) == len(SHEET_NAMES) assert all([pandas_data[sheet_name].equals(output_data_node_1.read()[sheet_name]) for sheet_name in SHEET_NAMES]) output_data_node_1.write({sheet_name: pd.DataFrame() for sheet_name in SHEET_NAMES}) scenario_1.submit() assert all([pandas_data[sheet_name].equals(output_data_node_1.read()[sheet_name]) for sheet_name in SHEET_NAMES]) os.remove(EXCEL_OUTPUT_PATH) # π With custom class as exposed type # def compare_custom_date(read_data, custom_data): # return [ # row_1.id == row_2.id and row_1.age == row_2.age and row_1.rating == row_2.rating # for row_1, row_2 in zip(read_data, custom_data) # ] # scenario_2 = tp.create_scenario(scenario_cfg_2) # input_data_node_2 = scenario_2.input_excel_multi_sheet_dataset_2 # output_data_node_2 = scenario_2.output_excel_multi_sheet_dataset_2 # read_data_2 = input_data_node_2.read() # assert len(read_data_2) == len(SHEET_NAMES) # assert all(compare_custom_date(read_data_2[sheet_name], custom_data[sheet_name]) for sheet_name in SHEET_NAMES) # breakpoint() # output_data_node_2.write(read_data_2) # assert len(read_data_2) == len(SHEET_NAMES) # print(output_data_node_2.read()) #TODO: failed write function # assert all(compare_custom_date(read_data_2[sheet_name], output_data_node_2.read()[sheet_name]) for sheet_name in SHEET_NAMES) # output_data_node_2.write(None) # assert isinstance(output_data_node_2.read(), list) # assert len(output_data_node_2.read()) == 0 # sequence_2.submit() # assert all(compare_custom_date(read_data_2[sheet_name], output_data_node_2.read()[sheet_name]) for sheet_name in SHEET_NAMES) # output_data_node_2.write(None) # assert isinstance(output_data_node_2.read(), list) # assert len(output_data_node_2.read()) == 0 # scenario_2.submit() # assert all(compare_custom_date(read_data_2[sheet_name], output_data_node_2.read()[sheet_name]) for sheet_name in SHEET_NAMES) # os.remove(EXCEL_OUTPUT_PATH) # # π With numpy as exposed type scenario_3 = tp.create_scenario(scenario_cfg_3) input_data_node_3 = scenario_3.input_excel_multi_sheet_dataset_3 output_data_node_3 = scenario_3.output_excel_multi_sheet_dataset_3 read_data_3 = input_data_node_3.read() assert len(read_data_3) == len(SHEET_NAMES) assert [np.array_equal(read_data_3[sheet_name], numpy_data[sheet_name]) for sheet_name in SHEET_NAMES] assert output_data_node_3.read() is None output_data_node_3.write(read_data_3) assert len(output_data_node_3.read()) == len(SHEET_NAMES) assert [ np.array_equal(read_data_3[sheet_name], output_data_node_3.read()[sheet_name]) for sheet_name in SHEET_NAMES ] # output_data_node_3.write(None) # with pytest.raises(ValueError): # assert output_data_node_1.read() scenario_3.submit() assert [ np.array_equal(read_data_3[sheet_name], output_data_node_3.read()[sheet_name]) for sheet_name in SHEET_NAMES ] os.remove(EXCEL_OUTPUT_PATH) # # π With modin as exposed type scenario_4 = tp.create_scenario(scenario_cfg_4) input_data_node_4 = scenario_4.input_excel_multi_sheet_dataset_4 output_data_node_4 = scenario_4.output_excel_multi_sheet_dataset_4 read_data_4 = input_data_node_4.read() assert len(read_data_4) == len(SHEET_NAMES) assert all( [all(modin_data[sheet_name]._to_pandas() == read_data_4[sheet_name]._to_pandas()) for sheet_name in SHEET_NAMES] ) assert output_data_node_4.read() is None output_data_node_4.write(read_data_4) assert len(read_data_4) == len(SHEET_NAMES) assert all( [ all(modin_data[sheet_name]._to_pandas() == output_data_node_4.read()[sheet_name]._to_pandas()) for sheet_name in SHEET_NAMES ] ) # output_data_node_4.write(None) # with pytest.raises(ValueError): # output_data_node_4.read() # TODO: test excel file has no header provided scenario_4.submit() assert all( [ all(modin_data[sheet_name]._to_pandas() == output_data_node_4.read()[sheet_name]._to_pandas()) for sheet_name in SHEET_NAMES ] ) os.remove(EXCEL_OUTPUT_PATH) |
import json import os import taipy.core as tp from taipy.config import Config def test_json(): from tests.shared_test_cases.json_files import ( JSON_DICT_INPUT_PATH, JSON_DICT_OUTPUT_PATH, JSON_OBJECT_INPUT_PATH, JSON_OBJECT_OUTPUT_PATH, ROW_COUNT, Row, RowDecoder, scenario_cfg_1, scenario_cfg_2, ) tp.clean_all_entities_by_version(None) with open(JSON_DICT_INPUT_PATH, "r") as f: json_dict_data = json.load(f) with open(JSON_OBJECT_INPUT_PATH, "r") as f: json_object_data = json.load(f, cls=RowDecoder) # π Without encoder / decoder scenario_1 = tp.create_scenario(scenario_cfg_1) input_data_node_1 = scenario_1.input_json_dataset_1 output_data_node_1 = scenario_1.output_json_dataset_1 read_data_1 = input_data_node_1.read() assert len(read_data_1) == ROW_COUNT assert json_dict_data == read_data_1 assert output_data_node_1.read() is None output_data_node_1.write(read_data_1) assert json_dict_data == output_data_node_1.read() output_data_node_1.write(None) assert output_data_node_1.read() is None scenario_1.submit() assert json_dict_data == output_data_node_1.read() os.remove(JSON_DICT_OUTPUT_PATH) # π With encoder / decoder def compare_custom_date(read_data, object_data): return [ isinstance(row_1, Row) and row_1.id == row_2.id and row_1.age == row_2.age and row_1.rating == row_2.rating for row_1, row_2 in zip(read_data, object_data) ] scenario_2 = tp.create_scenario(scenario_cfg_2) input_data_node_2 = scenario_2.input_json_dataset_2 output_data_node_2 = scenario_2.output_json_dataset_2 read_data_2 = input_data_node_2.read() assert len(read_data_2) == ROW_COUNT assert all(compare_custom_date(read_data_2, json_object_data)) assert output_data_node_2.read() is None output_data_node_2.write(read_data_2) assert all(compare_custom_date(output_data_node_2.read(), json_object_data)) output_data_node_2.write(None) assert output_data_node_2.read() is None scenario_2.submit() assert all(compare_custom_date(output_data_node_2.read(), json_object_data)) os.remove(JSON_OBJECT_OUTPUT_PATH) |
from unittest.mock import patch import pytest from taipy._entrypoint import _entrypoint from tests.utils import clean_subparser @pytest.fixture(autouse=True, scope="function") def clean_templates(): clean_subparser() yield def test_run_simple_taipy_app_without_taipy_args(capfd): with pytest.raises(SystemExit) as error: with patch("sys.argv", ["prog", "run", "tests/simple_application/no_external_args_app.py"]): _entrypoint() std_out, _ = capfd.readouterr() assert error.value.code == 0 assert "Development mode: Clean all entities of version" in std_out assert "Config.core.version_number: " in std_out assert "Config.core.mode: development" in std_out assert "Config.core.force: False" in std_out assert "Config.gui_config.host: 127.0.0.1" in std_out assert "Config.gui_config.port: 5000" in std_out assert "Config.gui_config.debug: False" in std_out assert "Config.gui_config.use_reloader: False" in std_out assert "Config.gui_config.ngrok_token: " in std_out assert "Config.gui_config.webapp_path: None" in std_out def test_run_simple_taipy_app_with_taipy_args(capfd): with pytest.raises(SystemExit): with patch( "sys.argv", [ "prog", "run", "tests/simple_application/no_external_args_app.py", "--experiment", "1.0", "--force", "--host", "example.com", "--port", "5001", "--debug", "--use-reloader", "--ngrok-token", "1234567890", "--webapp-path", "path/webapp", ], ): _entrypoint() std_out, _ = capfd.readouterr() assert "Config.core.version_number: 1.0" in std_out assert "Config.core.mode: experiment" in std_out assert "Config.core.force: True" in std_out assert "Config.gui_config.host: example.com" in std_out assert "Config.gui_config.port: 5001" in std_out assert "Config.gui_config.debug: True" in std_out assert "Config.gui_config.use_reloader: True" in std_out assert "Config.gui_config.ngrok_token: 1234567890" in std_out assert "Config.gui_config.webapp_path: path/webapp" in std_out def test_run_simple_taipy_app_with_taipy_and_external_args(capfd): with pytest.raises(SystemExit): with patch( "sys.argv", [ "prog", "run", "tests/simple_application/external_args_app.py", "--experiment", "1.0", "--force", "--host", "example.com", "--port", "5001", "external-args", # This is the keyword that separates external args from taipy args "--mode", "inference", "--force", "yes", "--host", "user_host.com", "--port", "8081", "--non-conflict-arg", "non-conflict-arg-value", ], ): _entrypoint() std_out, _ = capfd.readouterr() assert "Config.core.mode: experiment" in std_out assert "User provided mode: inference" in std_out assert "Config.core.force: True" in std_out assert "User provided force: yes" in std_out assert "Config.gui_config.host: example.com" in std_out assert "User provided host: user_host.com" in std_out assert "Config.gui_config.port: 5001" in std_out assert "User provided port: 8081" in std_out assert "User provided non-conflict-arg: non-conflict-arg-value" in std_out |
import datetime as dt from time import sleep import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split def sum(a, b): a = a["number"] b = b["number"] return a + b def subtract(a, b): a = a["number"] b = b["number"] return a - b def mult(a, b): return a * b def mult_by_2(a): return a def divide(a, b): return a / b def average(a): return [a.sum() / len(a)] def div_constant_with_sleep(a): sleep(1) return a["number"] / 10 def return_a_number(): return 10 def return_a_number_with_sleep(): sleep(1) return 10 def preprocess_dataset(initial_dataset: pd.DataFrame, date: dt.datetime = None): """This function preprocess the dataset to be used in the model Args: initial_dataset (pd.DataFrame): the raw format when we first read the data Returns: pd.DataFrame: the preprocessed dataset for classification """ print("\n Preprocessing the dataset...") # We filter the dataframe on the date if date != "None": initial_dataset["Date"] = pd.to_datetime(initial_dataset["Date"]) processed_dataset = initial_dataset[initial_dataset["Date"] <= date] print(len(processed_dataset)) else: processed_dataset = initial_dataset processed_dataset = processed_dataset[ [ "CreditScore", "Geography", "Gender", "Age", "Tenure", "Balance", "NumOfProducts", "HasCrCard", "IsActiveMember", "EstimatedSalary", "Exited", ] ] processed_dataset = pd.get_dummies(processed_dataset) if "Gender_Female" in processed_dataset.columns: processed_dataset.drop("Gender_Female", axis=1, inplace=True) processed_dataset = processed_dataset.apply(pd.to_numeric) columns_to_select = [ "CreditScore", "Age", "Tenure", "Balance", "NumOfProducts", "HasCrCard", "IsActiveMember", "EstimatedSalary", "Geography_France", "Geography_Germany", "Geography_Spain", "Gender_Male", "Exited", ] processed_dataset = processed_dataset[[col for col in columns_to_select if col in processed_dataset.columns]] print(" Preprocessing done!\n") return processed_dataset def create_train_test_data(preprocessed_dataset: pd.DataFrame): """This function will create the train data by segmenting the dataset Args: preprocessed_dataset (pd.DataFrame): the preprocessed dataset Returns: pd.DataFrame: the training dataset """ print("\n Creating the training and testing dataset...") X_train, X_test, y_train, y_test = train_test_split( preprocessed_dataset.iloc[:, :-1], preprocessed_dataset.iloc[:, -1], test_size=0.2, random_state=42 ) train_data = pd.concat([X_train, y_train], axis=1) test_data = pd.concat([X_test, y_test], axis=1) print(" Creating done!") return train_data, test_data def train_model_baseline(train_dataset: pd.DataFrame): """Function to train the Logistic Regression model Args: train_dataset (pd.DataFrame): the training dataset Returns: model (LogisticRegression): the fitted model """ print(" Training the model...\n") X, y = train_dataset.iloc[:, :-1], train_dataset.iloc[:, -1] model_fitted = LogisticRegression().fit(X, y) print("\n ", model_fitted, " is trained!") importance_dict = {"Features": X.columns, "Importance": model_fitted.coef_[0]} importance = pd.DataFrame(importance_dict).sort_values(by="Importance", ascending=True) return model_fitted, importance def train_model(train_dataset: pd.DataFrame): """Function to train the Logistic Regression model Args: train_dataset (pd.DataFrame): the training dataset Returns: model (RandomForest): the fitted model """ print(" Training the model...\n") X, y = train_dataset.iloc[:, :-1], train_dataset.iloc[:, -1] model_fitted = RandomForestClassifier().fit(X, y) print("\n ", model_fitted, " is trained!") importance_dict = {"Features": X.columns, "Importance": model_fitted.feature_importances_} importance = pd.DataFrame(importance_dict).sort_values(by="Importance", ascending=True) return model_fitted, importance def forecast(test_dataset: pd.DataFrame, trained_model: RandomForestClassifier): """Function to forecast the test dataset Args: test_dataset (pd.DataFrame): the test dataset trained_model (LogisticRegression): the fitted model Returns: forecast (pd.DataFrame): the forecasted dataset """ print(" Forecasting the test dataset...") X, y = test_dataset.iloc[:, :-1], test_dataset.iloc[:, -1] # predictions = trained_model.predict(X) predictions = trained_model.predict_proba(X)[:, 1] print(" Forecasting done!") return predictions def forecast_baseline(test_dataset: pd.DataFrame, trained_model: LogisticRegression): """Function to forecast the test dataset Args: test_dataset (pd.DataFrame): the test dataset trained_model (LogisticRegression): the fitted model Returns: forecast (pd.DataFrame): the forecasted dataset """ print(" Forecasting the test dataset...") X, y = test_dataset.iloc[:, :-1], test_dataset.iloc[:, -1] predictions = trained_model.predict_proba(X)[:, 1] print(" Forecasting done!") return predictions def roc_from_scratch(probabilities, test_dataset, partitions=100): print(" Calculation of the ROC curve...") y_test = test_dataset.iloc[:, -1] roc = np.array([]) for i in range(partitions + 1): threshold_vector = np.greater_equal(probabilities, i / partitions).astype(int) tpr, fpr = true_false_positive(threshold_vector, y_test) roc = np.append(roc, [fpr, tpr]) roc_np = roc.reshape(-1, 2) roc_data = pd.DataFrame({"False positive rate": roc_np[:, 0], "True positive rate": roc_np[:, 1]}) print(" Calculation done") print(" Scoring...") score_auc = roc_auc_score(y_test, probabilities) print(" Scoring done\n") return roc_data, score_auc def true_false_positive(threshold_vector: np.array, y_test: np.array): """Function to calculate the true positive rate and the false positive rate Args: threshold_vector (np.array): the test dataset y_test (np.array): the fitted model Returns: tpr (pd.DataFrame): the forecasted dataset fpr (pd.DataFrame): the forecasted dataset """ true_positive = np.equal(threshold_vector, 1) & np.equal(y_test, 1) true_negative = np.equal(threshold_vector, 0) & np.equal(y_test, 0) false_positive = np.equal(threshold_vector, 1) & np.equal(y_test, 0) false_negative = np.equal(threshold_vector, 0) & np.equal(y_test, 1) tpr = true_positive.sum() / (true_positive.sum() + false_negative.sum()) fpr = false_positive.sum() / (false_positive.sum() + true_negative.sum()) return tpr, fpr def create_metrics(predictions: np.array, test_dataset: np.array): print(" Creating the metrics...") threshold = 0.5 threshold_vector = np.greater_equal(predictions, threshold).astype(int) y_test = test_dataset.iloc[:, -1] true_positive = (np.equal(threshold_vector, 1) & np.equal(y_test, 1)).sum() true_negative = (np.equal(threshold_vector, 0) & np.equal(y_test, 0)).sum() false_positive = (np.equal(threshold_vector, 1) & np.equal(y_test, 0)).sum() false_negative = (np.equal(threshold_vector, 0) & np.equal(y_test, 1)).sum() f1_score = np.around(2 * true_positive / (2 * true_positive + false_positive + false_negative), decimals=2) accuracy = np.around( (true_positive + true_negative) / (true_positive + true_negative + false_positive + false_negative), decimals=2 ) dict_ftpn = {"tp": true_positive, "tn": true_negative, "fp": false_positive, "fn": false_negative} number_of_good_predictions = true_positive + true_negative number_of_false_predictions = false_positive + false_negative metrics = { "f1_score": f1_score, "accuracy": accuracy, "dict_ftpn": dict_ftpn, "number_of_predictions": len(predictions), "number_of_good_predictions": number_of_good_predictions, "number_of_false_predictions": number_of_false_predictions, } print(" Creating the metrics done!") return metrics def create_results(forecast_values, test_dataset): forecast_series_proba = pd.Series( np.around(forecast_values, decimals=2), index=test_dataset.index, name="Probability" ) forecast_series = pd.Series((forecast_values > 0.5).astype(int), index=test_dataset.index, name="Forecast") true_series = pd.Series(test_dataset.iloc[:, -1], name="Historical", index=test_dataset.index) index_series = pd.Series(range(len(true_series)), index=test_dataset.index, name="Id") results = pd.concat([index_series, forecast_series_proba, forecast_series, true_series], axis=1) return results |
import os import modin.pandas as modin_pd import numpy as np import pandas as pd import taipy.core as tp from taipy.config import Config def test_csv(): from tests.shared_test_cases.csv_files.config import ( CSV_INPUT_PATH, CSV_OUTPUT_PATH, ROW_COUNT, Row, scenario_cfg, scenario_cfg_2, scenario_cfg_3, scenario_cfg_4, ) tp.clean_all_entities_by_version(None) pandas_data = pd.read_csv(CSV_INPUT_PATH) numpy_data = pandas_data.to_numpy() modin_data = modin_pd.read_csv(CSV_INPUT_PATH) custom_data = [Row(int(v.id), int(v.age), float(v.rating)) for i, v in pd.read_csv(CSV_INPUT_PATH).iterrows()] # π Without exposed type (pandas is the default exposed type) scenario_1 = tp.create_scenario(scenario_cfg) input_data_node_1 = scenario_1.input_csv_dataset_1 output_data_node_1 = scenario_1.output_csv_dataset_1 read_data_1 = input_data_node_1.read() assert len(read_data_1) == ROW_COUNT assert pandas_data.equals(read_data_1) assert output_data_node_1.read() is None output_data_node_1.write(read_data_1) assert pandas_data.equals(output_data_node_1.read()) output_data_node_1.write(None) assert output_data_node_1.read().empty scenario_1.submit() assert pandas_data.equals(output_data_node_1.read()) os.remove(CSV_OUTPUT_PATH) # π With custom class as exposed type def compare_custom_date(read_data, custom_data): return [ row_1.id == row_2.id and row_1.age == row_2.age and row_1.rating == row_2.rating for row_1, row_2 in zip(read_data, custom_data) ] scenario_2 = tp.create_scenario(scenario_cfg_2) input_data_node_2 = scenario_2.input_csv_dataset_2 output_data_node_2 = scenario_2.output_csv_dataset_2 read_data_2 = input_data_node_2.read() assert len(read_data_2) == ROW_COUNT assert all(compare_custom_date(read_data_2, custom_data)) output_data_node_2.write(read_data_2) assert len(read_data_2) == ROW_COUNT assert all(compare_custom_date(output_data_node_2.read(), custom_data)) output_data_node_2.write(None) assert isinstance(output_data_node_2.read(), list) assert len(output_data_node_2.read()) == 0 scenario_2.submit() assert all(compare_custom_date(output_data_node_2.read(), custom_data)) os.remove(CSV_OUTPUT_PATH) # π With numpy as exposed type scenario_3 = tp.create_scenario(scenario_cfg_3) input_data_node_3 = scenario_3.input_csv_dataset_3 output_data_node_3 = scenario_3.output_csv_dataset_3 read_data_3 = input_data_node_3.read() assert len(read_data_3) == ROW_COUNT assert np.array_equal(read_data_3, numpy_data) assert output_data_node_3.read() is None output_data_node_3.write(read_data_3) assert np.array_equal(output_data_node_3.read(), numpy_data) output_data_node_3.write(None) assert isinstance(output_data_node_3.read(), np.ndarray) assert output_data_node_3.read().size == 0 scenario_3.submit() assert np.array_equal(output_data_node_3.read(), numpy_data) os.remove(CSV_OUTPUT_PATH) # π With modin as exposed type scenario_4 = tp.create_scenario(scenario_cfg_4) input_data_node_4 = scenario_4.input_csv_dataset_4 output_data_node_4 = scenario_4.output_csv_dataset_4 read_data_4 = input_data_node_4.read() assert len(read_data_4) == ROW_COUNT assert all(modin_data._to_pandas() == read_data_4._to_pandas()) assert output_data_node_4.read() is None output_data_node_4.write(read_data_4) assert all(modin_data._to_pandas() == output_data_node_4.read()._to_pandas()) output_data_node_4.write(None) assert output_data_node_4.read().empty scenario_4.submit() assert all(modin_data._to_pandas() == output_data_node_4.read()._to_pandas()) os.remove(CSV_OUTPUT_PATH) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.