text
stringlengths
0
5.92k
import os import re from collections import UserDict from datetime import datetime, timedelta from importlib import import_module from operator import attrgetter from pydoc import locate from ..exceptions.exceptions import InconsistentEnvVariableError, MissingEnvVariableError from .frequency import Frequency from .scope import Scope class _TemplateHandler: """Factory to handle actions related to config value templating.""" _PATTERN = r"^ENV\[([a-zA-Z_]\w*)\](:(\bbool\b|\bstr\b|\bfloat\b|\bint\b))?$" @classmethod def _replace_templates(cls, template, type=str, required=True, default=None): if isinstance(template, tuple): return tuple(cls._replace_template(item, type, required, default) for item in template) if isinstance(template, list): return [cls._replace_template(item, type, required, default) for item in template] if isinstance(template, dict): return {str(k): cls._replace_template(v, type, required, default) for k, v in template.items()} if isinstance(template, UserDict): return {str(k): cls._replace_template(v, type, required, default) for k, v in template.items()} return cls._replace_template(template, type, required, default) @classmethod def _replace_template(cls, template, type, required, default): if "ENV" not in str(template): return template match = re.fullmatch(cls._PATTERN, str(template)) if match: var = match.group(1) dynamic_type = match.group(3) val = os.environ.get(var) if val is None: if required: raise MissingEnvVariableError(f"Environment variable {var} is not set.") return default if type == bool: return cls._to_bool(val) elif type == int: return cls._to_int(val) elif type == float: return cls._to_float(val) elif type == Scope: return cls._to_scope(val) elif type == Frequency: return cls._to_frequency(val) else: if dynamic_type == "bool": return cls._to_bool(val) elif dynamic_type == "int": return cls._to_int(val) elif dynamic_type == "float": return cls._to_float(val) return val return template @staticmethod def _to_bool(val: str) -> bool: possible_values = ["true", "false"] if str.lower(val) not in possible_values: raise InconsistentEnvVariableError("{val} is not a Boolean.") return str.lower(val) == "true" or not (str.lower(val) == "false") @staticmethod def _to_int(val: str) -> int: try: return int(val) except ValueError: raise InconsistentEnvVariableError(f"{val} is not an integer.") @staticmethod def _to_float(val: str) -> float: try: return float(val) except ValueError: raise InconsistentEnvVariableError(f"{val} is not a float.") @staticmethod def _to_datetime(val: str) -> datetime: try: return datetime.fromisoformat(val) except ValueError: raise InconsistentEnvVariableError(f"{val} is not a valid datetime.") @staticmethod def _to_timedelta(val: str) -> timedelta: """ Parse a time string e.g. (2h13m) into a timedelta object. :param timedelta_str: A string identifying a duration. (eg. 2h13m) :return datetime.timedelta: A datetime.timedelta object """ regex = re.compile( r"^((?P<days>[\.\d]+?)d)? *" r"((?P<hours>[\.\d]+?)h)? *" r"((?P<minutes>[\.\d]+?)m)? *" r"((?P<seconds>[\.\d]+?)s)?$" ) parts = regex.match(val) if not parts: raise InconsistentEnvVariableError(f"{val} is not a valid timedelta.") time_params = {name: float(param) for name, param in parts.groupdict().items() if param} return timedelta(**time_params) # type: ignore @staticmethod def _to_scope(val: str) -> Scope: try: return Scope[str.upper(val)] except Exception: raise InconsistentEnvVariableError(f"{val} is not a valid scope.") @staticmethod def _to_frequency(val: str) -> Frequency: try: return Frequency[str.upper(val)] except Exception: raise InconsistentEnvVariableError(f"{val} is not a valid frequency.") @staticmethod def _to_function(val: str): module_name, fct_name = val.rsplit(".", 1) try: module = import_module(module_name) return attrgetter(fct_name)(module) except Exception: raise InconsistentEnvVariableError(f"{val} is not a valid function.") @staticmethod def _to_class(val: str): try: return locate(val) except Exception: raise InconsistentEnvVariableError(f"{val} is not a valid class.")
from __future__ import annotations from typing import Any, Dict, Optional, Union from ..common._config_blocker import _ConfigBlocker from ..common._template_handler import _TemplateHandler as _tpl class GlobalAppConfig: """ Configuration fields related to the global application. Attributes: **properties (Dict[str, Any]): A dictionary of additional properties. """ def __init__(self, **properties): self._properties = properties @property def properties(self): return {k: _tpl._replace_templates(v) for k, v in self._properties.items()} @properties.setter # type: ignore @_ConfigBlocker._check() def properties(self, val): self._properties = val def __getattr__(self, item: str) -> Optional[Any]: return _tpl._replace_templates(self._properties.get(item)) @classmethod def default_config(cls) -> GlobalAppConfig: return GlobalAppConfig() def _clean(self): self._properties.clear() def _to_dict(self): as_dict = {} as_dict.update(self._properties) return as_dict @classmethod def _from_dict(cls, config_as_dict: Dict[str, Any]): config = GlobalAppConfig() config._properties = config_as_dict return config def _update(self, config_as_dict): self._properties.update(config_as_dict)
# # 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 pathlib import sys from cookiecutter.main import cookiecutter import taipy from taipy._cli._base_cli import _CLI class _ScaffoldCLI: __TAIPY_PATH = pathlib.Path(taipy.__file__).parent.resolve() / "templates" _TEMPLATE_MAP = {str(x.name): str(x) for x in __TAIPY_PATH.iterdir() if x.is_dir()} @classmethod def create_parser(cls): create_parser = _CLI._add_subparser("create", help="Create a new Taipy application.") create_parser.add_argument( "--template", choices=list(cls._TEMPLATE_MAP.keys()), default="default", help="The Taipy template to create new application.", ) @classmethod def parse_arguments(cls): args = _CLI._parse() if getattr(args, "which", None) == "create": cookiecutter(cls._TEMPLATE_MAP[args.template]) sys.exit(0)
import subprocess import sys from taipy._cli._base_cli import _CLI class _RunCLI: @classmethod def create_parser(cls): run_parser = _CLI._add_subparser("run", help="Run a Taipy application.") run_parser.add_argument( "application_main_file", ) sub_run_parser = run_parser.add_subparsers(title="subcommands") sub_run_parser.add_parser( "external-args", help=""" Arguments defined after this keyword will be considered as external arguments to be passed to the application """, ) @classmethod def parse_arguments(cls): args = _CLI._parse() if getattr(args, "which", None) == "run": all_args = sys.argv[3:] # First 3 args are always (1) Python executable, (2) run, (3) Python file external_args = [] try: external_args_index = all_args.index("external-args") except ValueError: pass else: external_args.extend(all_args[external_args_index + 1 :]) all_args = all_args[:external_args_index] taipy_args = [f"--taipy-{arg[2:]}" if arg.startswith("--") else arg for arg in all_args] subprocess.run( [sys.executable, args.application_main_file, *(external_args + taipy_args)], stdout=sys.stdout, stderr=sys.stdout, ) sys.exit(0)
# # 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 sys from taipy._cli._base_cli import _CLI from taipy.logger._taipy_logger import _TaipyLogger class _HelpCLI: __logger = _TaipyLogger._get_logger() @classmethod def create_parser(cls): create_parser = _CLI._add_subparser("help", help="Show the Taipy help message.", add_help=False) create_parser.add_argument( "command", nargs="?", type=str, const="", default="", help="Show the help message of the command." ) @classmethod def parse_arguments(cls): args = _CLI._parse() if getattr(args, "which", None) == "help": if args.command: if args.command in _CLI._sub_taipyparsers.keys(): _CLI._sub_taipyparsers.get(args.command).print_help() else: cls.__logger.error(f"{args.command} is not a valid command.") else: _CLI._parser.print_help() sys.exit(0)
import argparse from typing import Dict class _CLI: """Argument parser for Taipy application.""" # The conflict_handler is set to "resolve" to override conflict arguments _subparser_action = None _parser = argparse.ArgumentParser(conflict_handler="resolve") _sub_taipyparsers: Dict[str, argparse.ArgumentParser] = {} _arg_groups: Dict[str, argparse._ArgumentGroup] = {} @classmethod def _add_subparser(cls, name: str, **kwargs) -> argparse.ArgumentParser: """Create a new subparser and return a argparse handler.""" if subparser := cls._sub_taipyparsers.get(name): return subparser if not cls._subparser_action: cls._subparser_action = cls._parser.add_subparsers() subparser = cls._subparser_action.add_parser( name=name, conflict_handler="resolve", **kwargs, ) cls._sub_taipyparsers[name] = subparser subparser.set_defaults(which=name) return subparser @classmethod def _add_groupparser(cls, title: str, description: str = "") -> argparse._ArgumentGroup: """Create a new group for arguments and return a argparser handler.""" if groupparser := cls._arg_groups.get(title): return groupparser groupparser = cls._parser.add_argument_group(title=title, description=description) cls._arg_groups[title] = groupparser return groupparser @classmethod def _parse(cls): """Parse and return only known arguments.""" args, _ = cls._parser.parse_known_args() return args @classmethod def _remove_argument(cls, arg: str): """Remove an argument from the parser. Note that the `arg` must be without --. Source: https://stackoverflow.com/questions/32807319/disable-remove-argument-in-argparse """ for action in cls._parser._actions: opts = action.option_strings if (opts and opts[0] == arg) or action.dest == arg: cls._parser._remove_action(action) break for argument_group in cls._parser._action_groups: for group_action in argument_group._group_actions: opts = group_action.option_strings if (opts and opts[0] == arg) or group_action.dest == arg: argument_group._group_actions.remove(group_action) return
from ._cli import _CLI
import typing as t class Icon: """Small image in the User Interface. Icons are typically used in controls like [button](../gui/viselements/button.md) or items in a [menu](../gui/viselements/menu.md). Attributes: path (str): The path to the image file. text (Optional[str]): The text associated to the image or None if there is none. svg (Optional[bool]): True if the image is svg. If a text is associated to an icon, it is rendered by the visual elements that uses this Icon. """ @staticmethod def get_dict_or(value: t.Union[str, t.Any]) -> t.Union[str, dict]: return value._to_dict() if isinstance(value, Icon) else value def __init__( self, path: str, text: t.Optional[str] = None, light_path: t.Optional[bool] = None, dark_path: t.Optional[bool] = None, ) -> None: """Initialize a new Icon. Arguments: path (str): The path to an image file.<br/> This path must be relative to and inside the root directory of the application (where the Python file that created the `Gui` instance is located).<br/> In situations where the image file is located outside the application directory, a _path mapping_ must be used: the _path_mapping_ parameter of the `Gui^` constructor makes it possible to access a resource anywhere on the server filesystem, as if it were located in a subdirectory of the application directory. text (Optional[str]): The text associated to the image. If *text* is None, there is no text associated to this image. light_path (Optional[str]): The path to the light theme image (fallback to *path* if not defined). dark_path (Optional[str]): The path to the dark theme image (fallback to *path* if not defined). """ self.path = path self.text = text if light_path is not None: self.light_path = light_path if dark_path is not None: self.dark_path = dark_path def _to_dict(self, a_dict: t.Optional[dict] = None) -> dict: if a_dict is None: a_dict = {} a_dict["path"] = self.path if self.text is not None: a_dict["text"] = self.text if hasattr(self, "light_path") and self.light_path is not None: a_dict["lightPath"] = self.light_path if hasattr(self, "dark_path") and self.dark_path is not None: a_dict["darkPath"] = self.dark_path return a_dict
from .gui import Gui
import typing as t from enum import Enum from inspect import isclass from .data import Decimator from .utils import ( _TaipyBase, _TaipyBool, _TaipyContent, _TaipyContentHtml, _TaipyContentImage, _TaipyData, _TaipyDate, _TaipyDateRange, _TaipyDict, _TaipyLoNumbers, _TaipyLov, _TaipyLovValue, _TaipyNumber, ) class _WsType(Enum): ACTION = "A" MULTIPLE_UPDATE = "MU" REQUEST_UPDATE = "RU" DATA_UPDATE = "DU" UPDATE = "U" ALERT = "AL" BLOCK = "BL" NAVIGATE = "NA" CLIENT_ID = "ID" MULTIPLE_MESSAGE = "MS" DOWNLOAD_FILE = "DF" PARTIAL = "PR" ACKNOWLEDGEMENT = "ACK" NumberTypes = {"int", "int64", "float", "float64"} class PropertyType(Enum): """ All the possible element property types. This is used when creating custom visual elements, where you have to indicate the type of each property. Some types are 'dynamic', meaning that if the property value is modified, it is automatically handled by Taipy and propagated to the entire application. See `ElementProperty^` for more details. """ boolean = "boolean" """ The property holds a Boolean value. """ toHtmlContent = _TaipyContentHtml content = _TaipyContent data = _TaipyData date = _TaipyDate date_range = _TaipyDateRange dict = "dict" """ The property holds a dictionary. """ dynamic_dict = _TaipyDict """ The property holds a dynamic dictionary. """ dynamic_number = _TaipyNumber """ The property holds a dynamic number. """ dynamic_lo_numbers = _TaipyLoNumbers """ The property holds a dynamic list of numbers. """ dynamic_boolean = _TaipyBool """ The property holds a dynamic Boolean value. """ dynamic_list = "dynamiclist" dynamic_string = "dynamicstring" """ The property holds a dynamic string. """ function = "function" """ The property holds a reference to a function. """ image = _TaipyContentImage json = "json" lov = _TaipyLov """ The property holds a LoV (list of values). """ lov_value = _TaipyLovValue """ The property holds a value in a LoV (list of values). """ number = "number" """ The property holds a number. """ react = "react" broadcast = "broadcast" string = "string" """ The property holds a string. """ string_or_number = "string|number" """ The property holds a string or a number. This is typically used to handle CSS dimension values, where a unit can be used. """ boolean_or_list = "boolean|list" slider_value = "number|number[]|lovValue" string_list = "stringlist" decimator = Decimator """ The property holds an inner attributes that is defined by a library and cannot be overridden by the user. """ inner = "inner" @t.overload # noqa: F811 def _get_taipy_type(a_type: None) -> None: ... @t.overload def _get_taipy_type(a_type: t.Type[_TaipyBase]) -> t.Type[_TaipyBase]: # noqa: F811 ... @t.overload def _get_taipy_type(a_type: PropertyType) -> t.Type[_TaipyBase]: # noqa: F811 ... @t.overload def _get_taipy_type( # noqa: F811 a_type: t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]] ) -> t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]]: ... def _get_taipy_type( # noqa: F811 a_type: t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]] ) -> t.Optional[t.Union[t.Type[_TaipyBase], t.Type[Decimator], PropertyType]]: if a_type is None: return None if isinstance(a_type, PropertyType) and not isinstance(a_type.value, str): return a_type.value if isclass(a_type) and not isinstance(a_type, PropertyType) and issubclass(a_type, _TaipyBase): return a_type if a_type == PropertyType.boolean: return _TaipyBool elif a_type == PropertyType.number: return _TaipyNumber return None
"""# Taipy Graphical User Interface generator The Taipy GUI package provides User Interface generation based on page templates. It can run a web server that a web browser can connect to. The pages are generated by a web server that allows web clients to connect, display and interact with the page content through visual elements. Each page can contain regular text and images, as well as Taipy controls that are typically linked to some value that is managed by the whole Taipy application. Here is how you can create your first Taipy User Interface: - Create a Python source file. Copy these two lines into a file called *taipy_app.py*. ```py title="taipy_app.py" from taipy import Gui Gui("# Hello Taipy!").run() ``` - Install Taipy: ``` pip install taipy ``` - Run your application: ``` python taipy_app.py ``` Your browser opens a new page, showing the content of your graphical application. !!! Note "Optional packages" There are Python packages that you can install in your environment to add functionality to Taipy GUI: - [`python-magic`](https://pypi.org/project/python-magic/): identifies image format from byte buffers so the [`image`](../../gui/viselements/image.md) control can display them, and so that [`file_download`](../../gui/viselements/file_download.md) can request the browser to display the image content when relevant.<br/> You can install that package with the regular `pip install python-magic` command (then potentially `pip install python-magic` on Windows), or install Taipy GUI using: `pip install taipy-gui[image]`. - [`pyarrow`](https://pypi.org/project/pyarrow/): can improve the performance of your application by reducing the volume of data transferred between the web server and the clients. This is relevant if your application uses large tabular data.<br/> You can install that package with the regular `pip install pyarrow` command, or install Taipy GUI using: `pip install taipy-gui[arrow]`. - [`simple-websocket`](https://pypi.org/project/simple-websocket/): enables the debugging of the WebSocket part of the server execution.<br/> You can install that package with the regular `pip install simple-websocket` command, or install Taipy GUI using: `pip install taipy-gui[simple-websocket]`. - [`pyngrok`](https://pypi.org/project/pyngrok/): enables use of [Ngrok](https://ngrok.com/) to access Taipy GUI application from the internet.<br/> You can install that package with the regular `pip install pyngrok` command, or install Taipy GUI using: `pip install taipy-gui[pyngrok]`. """ from importlib.util import find_spec from ._init import * from ._renderers import Html, Markdown from .gui_actions import ( broadcast_callback, download, get_module_context, get_module_name_from_state, get_state_id, get_user_content_url, hold_control, invoke_callback, invoke_long_callback, navigate, notify, resume_control, ) from .icon import Icon from .page import Page from .partial import Partial from .state import State from .utils import is_debugging if find_spec("taipy") and find_spec("taipy.config"): from taipy.config import _inject_section from ._default_config import default_config from ._gui_section import _GuiSection _inject_section( _GuiSection, "gui_config", _GuiSection(property_list=list(default_config)), [("configure_gui", _GuiSection._configure)], add_to_unconflicted_sections=True, )
from __future__ import annotations import inspect import typing as t from types import FrameType from .utils import _filter_locals, _get_module_name_from_frame if t.TYPE_CHECKING: from ._renderers import _Element class Page: """Generic page generator. The `Page` class transforms template text into actual pages that can be displayed on a web browser. When a page is requested to be displayed, it is converted into HTML code that can be sent to the client. All control placeholders are replaced by their respective graphical component so you can show your application variables and interact with them. """ def __init__(self, **kwargs) -> None: self._class_module_name = "" self._class_locals: t.Dict[str, t.Any] = {} self._frame: t.Optional[FrameType] = None self._renderer: t.Optional[Page] = self.create_page() if "frame" in kwargs: self._frame = kwargs.get("frame") elif self._renderer: self._frame = self._renderer._frame elif len(inspect.stack()) < 4: raise RuntimeError(f"Can't resolve module. Page '{type(self).__name__}' is not registered.") else: self._frame = t.cast(FrameType, t.cast(FrameType, inspect.stack()[3].frame)) if self._renderer: # Extract the page module's attributes and methods cls = type(self) cls_locals = dict(vars(self)) funcs = [ i[0] for i in inspect.getmembers(cls) if not i[0].startswith("_") and (inspect.ismethod(i[1]) or inspect.isfunction(i[1])) ] for f in funcs: func = getattr(self, f) if hasattr(func, "__func__") and func.__func__ is not None: cls_locals[f] = func.__func__ self._class_module_name = cls.__name__ self._class_locals = cls_locals def create_page(self) -> t.Optional[Page]: """Create the page content for page modules. If this page is a page module, this method must be overloaded and return the page content. This method should never be called directly: only the Taipy GUI internals will. The default implementation returns None, indicating that this class does not implement a page module. Returns: The page content for this Page subclass, making it a page module. """ return None def _get_locals(self) -> t.Optional[t.Dict[str, t.Any]]: return ( self._class_locals if self._is_class_module() else None if (frame := self._get_frame()) is None else _filter_locals(frame.f_locals) ) def _is_class_module(self): return self._class_module_name != "" def _get_frame(self): if not hasattr(self, "_frame"): raise RuntimeError(f"Page '{type(self).__name__}' was not registered correctly.") return self._frame def _get_module_name(self) -> t.Optional[str]: return ( None if (frame := self._get_frame()) is None else f"{_get_module_name_from_frame(frame)}{'.' if self._class_module_name else ''}{self._class_module_name}" # noqa: E501 ) def _get_content_detail(self, gui) -> str: return f"in class {type(self).__name__}" def render(self, gui) -> str: if self._renderer is not None: return self._renderer.render(gui) return "<h1>No renderer found for page</h1>"
import sys import traceback import typing as t import warnings class TaipyGuiWarning(UserWarning): """NOT DOCUMENTED Warning category for Taipy warnings generated in user code. """ _tp_debug_mode = False @staticmethod def set_debug_mode(debug_mode: bool): TaipyGuiWarning._tp_debug_mode = ( debug_mode if debug_mode else hasattr(sys, "gettrace") and sys.gettrace() is not None ) def _warn(message: str, e: t.Optional[BaseException] = None): warnings.warn( f"{message}:\n{''.join(traceback.format_exception(type(e), e, e.__traceback__))}" if e and TaipyGuiWarning._tp_debug_mode else f"{message}:\n{e}" if e else message, TaipyGuiWarning, stacklevel=2, )
import typing as t from copy import copy from taipy.config import Config as TaipyConfig from taipy.config import UniqueSection from ._default_config import default_config class _GuiSection(UniqueSection): name = "gui" def __init__(self, property_list: t.Optional[t.List] = None, **properties): self._property_list = property_list super().__init__(**properties) def __copy__(self): return _GuiSection(property_list=copy(self._property_list), **copy(self._properties)) def _clean(self): self._properties.clear() def _to_dict(self): as_dict = {} as_dict.update(self._properties) return as_dict @classmethod def _from_dict(cls, as_dict: t.Dict[str, t.Any], *_): return _GuiSection(property_list=list(default_config), **as_dict) def _update(self, as_dict: t.Dict[str, t.Any]): if self._property_list: as_dict = {k: v for k, v in as_dict.items() if k in self._property_list} self._properties.update(as_dict) @staticmethod def _configure(**properties) -> "_GuiSection": """NOT DOCUMENTED Configure the Graphical User Interface. Parameters: **properties (dict[str, any]): Keyword arguments that configure the behavior of the `Gui^` instances.<br/> Please refer to the [Configuration section](../gui/configuration.md#configuring-the-gui-instance) of the User Manual for more information on the accepted arguments. Returns: The GUI configuration. """ section = _GuiSection(property_list=list(default_config), **properties) TaipyConfig._register(section) return TaipyConfig.unique_sections[_GuiSection.name]
# _Page for multipage support from __future__ import annotations import logging import typing as t import warnings if t.TYPE_CHECKING: from ._renderers import Page from .gui import Gui class _Page(object): def __init__(self): self._rendered_jsx: t.Optional[str] = None self._renderer: t.Optional[Page] = None self._style: t.Optional[str] = None self._route: t.Optional[str] = None self._head: t.Optional[list] = None def render(self, gui: Gui): if self._renderer is None: raise RuntimeError(f"Can't render page {self._route}: no renderer found") with warnings.catch_warnings(record=True) as w: warnings.resetwarnings() with gui._set_locals_context(self._renderer._get_module_name()): self._rendered_jsx = self._renderer.render(gui) if w: s = "\033[1;31m\n" s += ( message := f"--- {len(w)} warning(s) were found for page '{'/' if self._route == gui._get_root_page_name() else self._route}' {self._renderer._get_content_detail(gui)} ---\n" # noqa: E501 ) for i, wm in enumerate(w): s += f" - Warning {i + 1}: {wm.message}\n" s += "-" * len(message) s += "\033[0m\n" logging.warn(s) if hasattr(self._renderer, "head"): self._head = list(self._renderer.head) # type: ignore # return renderer module_name from frame return self._renderer._get_module_name()
#!/usr/bin/env python """The setup script.""" import json import os from pathlib import Path from setuptools import find_namespace_packages, find_packages, setup from setuptools.command.build_py import build_py readme = Path("README.md").read_text() with open(f"src{os.sep}taipy{os.sep}gui{os.sep}version.json") as version_file: version = json.load(version_file) version_string = f'{version.get("major", 0)}.{version.get("minor", 0)}.{version.get("patch", 0)}' if vext := version.get("ext"): version_string = f"{version_string}.{vext}" requirements = [ "flask>=3.0.0,<3.1", "flask-cors>=4.0.0,<5.0", "flask-socketio>=5.3.6,<6.0", "markdown>=3.4.4,<4.0", "pandas>=2.0.0,<3.0", "python-dotenv>=1.0.0,<1.1", "pytz>=2021.3,<2022.2", "tzlocal>=3.0,<5.0", "backports.zoneinfo>=0.2.1,<0.3;python_version<'3.9'", "gevent>=23.7.0,<24.0", "gevent-websocket>=0.10.1,<0.11", "kthread>=0.2.3,<0.3", "taipy-config@git+https://git@github.com/Avaiga/taipy-config.git@develop", "gitignore-parser>=0.1,<0.2", "simple-websocket>=0.10.1,<1.0", "twisted>=23.8.0,<24.0", ] test_requirements = ["pytest>=3.8"] extras_require = { "ngrok": ["pyngrok>=5.1,<6.0"], "image": [ "python-magic>=0.4.24,<0.5;platform_system!='Windows'", "python-magic-bin>=0.4.14,<0.5;platform_system=='Windows'", ], "arrow": ["pyarrow>=10.0.1,<11.0"], } def _build_webapp(): already_exists = Path("./src/taipy/gui/webapp/index.html").exists() if not already_exists: os.system("cd ../../../frontend/taipy-gui/dom && npm ci") os.system("cd ../../../frontend/taipy-gui && npm ci --omit=optional && npm run build") class NPMInstall(build_py): def run(self): _build_webapp() build_py.run(self) setup( author="Avaiga", author_email="dev@taipy.io", python_requires=">=3.8", classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Natural Language :: English", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", ], description="Low-code library to create graphical user interfaces on the Web for your Python applications.", long_description=readme, long_description_content_type="text/markdown", install_requires=requirements, license="Apache License 2.0", include_package_data=True, keywords="taipy-gui", name="taipy-gui", package_dir={"": "src"}, packages=find_namespace_packages(where="src") + find_packages(include=["taipy", "taipy.gui", "taipy.gui.*"]), test_suite="tests", tests_require=test_requirements, url="https://github.com/avaiga/taipy-gui", version=version_string, zip_safe=False, extras_require=extras_require, cmdclass={"build_py": NPMInstall}, )
from .config import Config, Stylekit _default_stylekit: Stylekit = { # Primary and secondary colors "color_primary": "#ff6049", "color_secondary": "#293ee7", # Contextual color "color_error": "#FF595E", "color_warning": "#FAA916", "color_success": "#96E6B3", # Background and elevation color for LIGHT MODE "color_background_light": "#f0f5f7", "color_paper_light": "#ffffff", # Background and elevation color for DARK MODE "color_background_dark": "#152335", "color_paper_dark": "#1f2f44", # DEFINING FONTS # Set main font family "font_family": "Lato, Arial, sans-serif", # DEFINING ROOT STYLES # Set root margin "root_margin": "1rem", # DEFINING SHAPES # Base border radius in px "border_radius": 8, # DEFINING MUI COMPONENTS STYLES # Matching input and button height in css size unit "input_button_height": "48px", } # Default config loaded by app.py default_config: Config = { "allow_unsafe_werkzeug": False, "async_mode": "gevent", "change_delay": None, "chart_dark_template": None, "base_url": "/", "dark_mode": True, "dark_theme": None, "debug": False, "extended_status": False, "favicon": None, "flask_log": False, "host": "127.0.0.1", "light_theme": None, "margin": "1em", "ngrok_token": "", "notebook_proxy": True, "notification_duration": 3000, "propagate": True, "run_browser": True, "run_in_thread": False, "run_server": True, "server_config": None, "single_client": False, "system_notification": False, "theme": None, "time_zone": None, "title": None, "stylekit": _default_stylekit.copy(), "upload_folder": None, "use_arrow": False, "use_reloader": False, "watermark": "Taipy inside", "webapp_path": None, "port": 5000, }
from __future__ import annotations import typing as t from ._page import _Page from ._warnings import _warn from .state import State if t.TYPE_CHECKING: from .page import Page class Partial(_Page): """Re-usable Page content. Partials are used when you need to use a partial page content in different and not related pages. This allows not to have to repeat yourself when creating your page templates. Visual elements such as [`part`](../gui/viselements/part.md), [`dialog`](../gui/viselements/dialog.md) or [`pane`](../gui/viselements/pane.md) can use Partials. Note that `Partial` has no constructor (no `__init__()` method): to create a `Partial`, you must call the `Gui.add_partial()^` function. Partials can be really handy if you want to modify a section of a page: the `update_content()` method dynamically update pages that make use of this `Partial` therefore making it easy to change the content of any page, at any moment. """ _PARTIALS = "__partials" __partials: t.Dict[str, Partial] = {} def __init__(self, route: t.Optional[str] = None): super().__init__() if route is None: self._route = f"TaiPy_partials_{len(Partial.__partials)}" Partial.__partials[self._route] = self else: self._route = route def update_content(self, state: State, content: str | "Page"): """Update partial content. Arguments: state (State^): The current user state as received in any callback. content (str): The new content to use and display. """ if state and state._gui and callable(state._gui._update_partial): state._gui._update_partial(self.__copy(content)) else: _warn("'Partial.update_content()' must be called in the context of a callback.") def __copy(self, content: str | "Page") -> Partial: new_partial = Partial(self._route) from .page import Page if isinstance(content, Page): new_partial._renderer = content else: new_partial._renderer = type(self._renderer)(content=content) if self._renderer is not None else None return new_partial
from typing import Dict, Tuple from taipy._cli._base_cli import _CLI class _GuiCLI: """Command-line interface of GUI.""" __GUI_ARGS: Dict[Tuple, Dict] = { ("--port", "-P"): { "dest": "taipy_port", "metavar": "PORT", "nargs": "?", "default": "", "const": "", "help": "Specify server port", }, ("--host", "-H"): { "dest": "taipy_host", "metavar": "HOST", "nargs": "?", "default": "", "const": "", "help": "Specify server host", }, ("--ngrok-token",): { "dest": "taipy_ngrok_token", "metavar": "NGROK_TOKEN", "nargs": "?", "default": "", "const": "", "help": "Specify NGROK Authtoken", }, ("--webapp-path",): { "dest": "taipy_webapp_path", "metavar": "WEBAPP_PATH", "nargs": "?", "default": "", "const": "", "help": "The path to the web app to be used. The default is the webapp directory under gui in the Taipy GUI package directory.", # noqa: E501 }, } __DEBUG_ARGS: Dict[str, Dict] = { "--debug": {"dest": "taipy_debug", "help": "Turn on debug", "action": "store_true"}, "--no-debug": {"dest": "taipy_no_debug", "help": "Turn off debug", "action": "store_true"}, } __RELOADER_ARGS: Dict[str, Dict] = { "--use-reloader": {"dest": "taipy_use_reloader", "help": "Auto reload on code changes", "action": "store_true"}, "--no-reloader": {"dest": "taipy_no_reloader", "help": "No reload on code changes", "action": "store_true"}, } @classmethod def create_parser(cls): gui_parser = _CLI._add_groupparser("Taipy GUI", "Optional arguments for Taipy GUI service") for args, arg_dict in cls.__GUI_ARGS.items(): taipy_arg = (args[0], cls.__add_taipy_prefix(args[0]), *args[1:]) gui_parser.add_argument(*taipy_arg, **arg_dict) debug_group = gui_parser.add_mutually_exclusive_group() for debug_arg, debug_arg_dict in cls.__DEBUG_ARGS.items(): debug_group.add_argument(debug_arg, cls.__add_taipy_prefix(debug_arg), **debug_arg_dict) reloader_group = gui_parser.add_mutually_exclusive_group() for reloader_arg, reloader_arg_dict in cls.__RELOADER_ARGS.items(): reloader_group.add_argument(reloader_arg, cls.__add_taipy_prefix(reloader_arg), **reloader_arg_dict) @classmethod def create_run_parser(cls): run_parser = _CLI._add_subparser("run", help="Run a Taipy application.") for args, arg_dict in cls.__GUI_ARGS.items(): run_parser.add_argument(*args, **arg_dict) debug_group = run_parser.add_mutually_exclusive_group() for debug_arg, debug_arg_dict in cls.__DEBUG_ARGS.items(): debug_group.add_argument(debug_arg, **debug_arg_dict) reloader_group = run_parser.add_mutually_exclusive_group() for reloader_arg, reloader_arg_dict in cls.__RELOADER_ARGS.items(): reloader_group.add_argument(reloader_arg, **reloader_arg_dict) @classmethod def parse_arguments(cls): return _CLI._parse() @classmethod def __add_taipy_prefix(cls, key: str): if key.startswith("--no-"): return key[:5] + "taipy-" + key[5:] return key[:2] + "taipy-" + key[2:]
from ..gui_types import PropertyType from .library import Element, ElementLibrary, ElementProperty
from __future__ import annotations import typing as t class _MapDict(object): """ Provide class binding, can utilize getattr, setattr functionality Also perform update operation """ __local_vars = ("_dict", "_update_var") def __init__(self, dict_import: dict, app_update_var=None): self._dict = dict_import # Bind app update var function self._update_var = app_update_var def __len__(self): return self._dict.__len__() def __length_hint__(self): return self._dict.__length_hint__() def __getitem__(self, key): value = self._dict.__getitem__(key) if isinstance(value, dict): if self._update_var: return _MapDict(value, lambda s, v: self._update_var(f"{key}.{s}", v)) else: return _MapDict(value) return value def __setitem__(self, key, value): if self._update_var: self._update_var(key, value) else: self._dict.__setitem__(key, value) def __delitem__(self, key): self._dict.__delitem__(key) def __missing__(self, key): return self._dict.__missing__(key) def __iter__(self): return self._dict.__iter__() def __reversed__(self): return self._dict.__reversed__() def __contains__(self, item): return self._dict.__contains__(item) # to be able to use getattr def __getattr__(self, attr): value = self._dict.__getitem__(attr) if isinstance(value, dict): if self._update_var: return _MapDict(value, lambda s, v: self._update_var(f"{attr}.{s}", v)) else: return _MapDict(value) return value def __setattr__(self, attr, value): if attr in _MapDict.__local_vars: super().__setattr__(attr, value) else: self.__setitem__(attr, value) def keys(self): return self._dict.keys() def values(self): return self._dict.values() def items(self): return self._dict.items() def get(self, key: t.Any, default_value: t.Optional[str] = None) -> t.Optional[t.Any]: return self._dict.get(key, default_value) def clear(self) -> None: self._dict.clear() def setdefault(self, key, value=None) -> t.Optional[t.Any]: return self._dict.setdefault(key, value) def pop(self, key, default=None) -> t.Any: return self._dict.pop(key, default) def popitem(self) -> tuple: return self._dict.popitem() def copy(self) -> _MapDict: return _MapDict(self._dict.copy(), self._update_var) def update(self, d: dict) -> None: current_keys = self.keys() for k, v in d.items(): if k not in current_keys or self[k] != v: self.__setitem__(k, v)
import re import typing as t _RE_MODULE = re.compile(r"^__(.*?)__$") def _filter_locals(locals_dict: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]: return {k: v for k, v in locals_dict.items() if (not _RE_MODULE.match(k) or k == "__name__")}
import typing as t from .singleton import _Singleton if t.TYPE_CHECKING: from ..gui import Gui class _RuntimeManager(object, metaclass=_Singleton): def __init__(self): self.__port_gui: t.Dict[int, "Gui"] = {} def add_gui(self, gui: "Gui", port: int): if port in self.__port_gui: self.__port_gui[port].stop() self.__port_gui[port] = gui def get_used_port(self): return list(self.__port_gui.keys())
import inspect import sys import typing as t from types import FrameType, ModuleType def _get_module_name_from_frame(frame: FrameType): return frame.f_globals["__name__"] if "__name__" in frame.f_globals else None def _get_module_name_from_imported_var(var_name: str, value: t.Any, sub_module_name: str) -> str: module_list = sys.modules.copy() # the provided sub_module_name are expected to contain only part of the full module_name provided by sys.modules # --> we can find potential matched modules based on the sub_module_name potential_matched_module = [m for m in module_list.keys() if m.endswith(sub_module_name)] for m in potential_matched_module: module = module_list[m] if hasattr(module, var_name) and getattr(module, var_name) is value: return m # failed fetching any matched module with variable and value return sub_module_name
import contextlib import typing as t import warnings from threading import Thread from urllib.parse import quote as urlquote from urllib.parse import urlparse from twisted.internet import reactor from twisted.web.proxy import ProxyClient, ProxyClientFactory from twisted.web.resource import Resource from twisted.web.server import NOT_DONE_YET, Site from .is_port_open import _is_port_open # flake8: noqa: E402 from .singleton import _Singleton warnings.filterwarnings( "ignore", category=UserWarning, message="You do not have a working installation of the service_identity module: 'No module named 'service_identity''.*", # noqa: E501 ) if t.TYPE_CHECKING: from ..gui import Gui def _modifiedHandleResponseEnd(self): if self._finished: return self._finished = True with contextlib.suppress(Exception): self.father.finish() self.transport.loseConnection() setattr(ProxyClient, "handleResponseEnd", _modifiedHandleResponseEnd) class _TaipyReverseProxyResource(Resource): proxyClientFactoryClass = ProxyClientFactory def __init__(self, host, path, gui: "Gui", reactor=reactor): Resource.__init__(self) self.host = host self.path = path self.reactor = reactor self._gui = gui def getChild(self, path, request): return _TaipyReverseProxyResource( self.host, self.path + b"/" + urlquote(path, safe=b"").encode("utf-8"), self._gui, self.reactor, ) def _get_port(self): return self._gui._server._port def render(self, request): port = self._get_port() host = self.host if port == 80 else "%s:%d" % (self.host, port) request.requestHeaders.setRawHeaders(b"host", [host.encode("ascii")]) request.content.seek(0, 0) rest = self.path + b"?" + qs if (qs := urlparse(request.uri)[4]) else self.path clientFactory = self.proxyClientFactoryClass( request.method, rest, request.clientproto, request.getAllHeaders(), request.content.read(), request, ) self.reactor.connectTCP(self.host, port, clientFactory) return NOT_DONE_YET class NotebookProxy(object, metaclass=_Singleton): def __init__(self, gui: "Gui", listening_port: int) -> None: self._listening_port = listening_port self._gui = gui self._is_running = False def run(self): if self._is_running: return host = self._gui._get_config("host", "127.0.0.1") port = self._listening_port if _is_port_open(host, port): raise ConnectionError( f"Port {port} is already opened on {host}. You have another server application running on the same port." # noqa: E501 ) site = Site(_TaipyReverseProxyResource(host, b"", self._gui)) reactor.listenTCP(port, site) Thread(target=reactor.run, args=(False,)).start() self._is_running = True def stop(self): if not self._is_running: return self._is_running = False reactor.stop()
import typing as t from operator import attrgetter if t.TYPE_CHECKING: from ..gui import Gui def _getscopeattr(gui: "Gui", name: str, *more) -> t.Any: if more: return getattr(gui._get_data_scope(), name, more[0]) return getattr(gui._get_data_scope(), name) def _getscopeattr_drill(gui: "Gui", name: str) -> t.Any: return attrgetter(name)(gui._get_data_scope()) def _setscopeattr(gui: "Gui", name: str, value: t.Any): if gui._is_broadcasting(): for scope in gui._get_all_data_scopes().values(): setattr(scope, name, value) else: setattr(gui._get_data_scope(), name, value) def _setscopeattr_drill(gui: "Gui", name: str, value: t.Any): if gui._is_broadcasting(): for scope in gui._get_all_data_scopes().values(): _attrsetter(scope, name, value) else: _attrsetter(gui._get_data_scope(), name, value) def _hasscopeattr(gui: "Gui", name: str) -> bool: return hasattr(gui._get_data_scope(), name) def _delscopeattr(gui: "Gui", name: str): delattr(gui._get_data_scope(), name) def _attrsetter(obj: object, attr_str: str, value: object) -> None: var_name_split = attr_str.split(sep=".") for i in range(len(var_name_split) - 1): sub_name = var_name_split[i] obj = getattr(obj, sub_name) setattr(obj, var_name_split[-1], value)
import typing as t def _get_css_var_value(value: t.Any) -> str: if isinstance(value, str): if " " in value: return f'"{value}"' return value if isinstance(value, int): return f"{value}px" return f"{value}"
import typing as t from types import ModuleType from ..page import Page def _get_page_from_module(module: ModuleType) -> t.Optional[Page]: return next((v for v in vars(module).values() if isinstance(v, Page)), None)
from __future__ import annotations import typing as t if t.TYPE_CHECKING: from ..gui import Gui def _varname_from_content(gui: Gui, content: str) -> t.Optional[str]: return next((k for k, v in gui._get_locals_bind().items() if isinstance(v, str) and v == content), None)
from __future__ import annotations import contextlib import typing as t from flask import g class _LocalsContext: __ctx_g_name = "locals_context" def __init__(self) -> None: self.__default_module: str = "" self._lc_stack: t.List[str] = [] self._locals_map: t.Dict[str, t.Dict[str, t.Any]] = {} def set_default(self, default: t.Dict[str, t.Any], default_module_name: str = "") -> None: self.__default_module = default_module_name self._locals_map[self.__default_module] = default def get_default(self) -> t.Dict[str, t.Any]: return self._locals_map[self.__default_module] def get_all_keys(self) -> t.Set[str]: keys = set() for v in self._locals_map.values(): for i in v.keys(): keys.add(i) return keys def get_all_context(self): return self._locals_map.keys() def add(self, context: t.Optional[str], locals_dict: t.Optional[t.Dict[str, t.Any]]): if context is not None and locals_dict is not None and context not in self._locals_map: self._locals_map[context] = locals_dict @contextlib.contextmanager def set_locals_context(self, context: t.Optional[str]) -> t.Iterator[None]: try: if context in self._locals_map: if hasattr(g, _LocalsContext.__ctx_g_name): self._lc_stack.append(getattr(g, _LocalsContext.__ctx_g_name)) setattr(g, _LocalsContext.__ctx_g_name, context) yield finally: if hasattr(g, _LocalsContext.__ctx_g_name): if len(self._lc_stack) > 0: setattr(g, _LocalsContext.__ctx_g_name, self._lc_stack.pop()) else: delattr(g, _LocalsContext.__ctx_g_name) def get_locals(self) -> t.Dict[str, t.Any]: return self.get_default() if (context := self.get_context()) is None else self._locals_map[context] def get_context(self) -> t.Optional[str]: return getattr(g, _LocalsContext.__ctx_g_name) if hasattr(g, _LocalsContext.__ctx_g_name) else None def is_default(self) -> bool: return self.get_default() == self.get_locals() def _get_locals_bind_from_context(self, context: t.Optional[str]): if context is None: context = self.__default_module return self._locals_map[context]
from ._attributes import ( _delscopeattr, _getscopeattr, _getscopeattr_drill, _hasscopeattr, _setscopeattr, _setscopeattr_drill, ) from ._locals_context import _LocalsContext from ._map_dict import _MapDict from ._runtime_manager import _RuntimeManager from ._variable_directory import _variable_decode, _variable_encode, _VariableDirectory from .boolean import _is_boolean, _is_boolean_true from .clientvarname import _get_broadcast_var_name, _get_client_var_name, _to_camel_case from .datatype import _get_data_type from .date import _date_to_string, _string_to_date from .expr_var_name import _get_expr_var_name from .filename import _get_non_existent_file_path from .filter_locals import _filter_locals from .get_imported_var import _get_imported_var from .get_module_name import _get_module_name_from_frame, _get_module_name_from_imported_var from .get_page_from_module import _get_page_from_module from .getdatecolstrname import _RE_PD_TYPE, _get_date_col_str_name from .html import _get_css_var_value from .is_debugging import is_debugging from .is_port_open import _is_port_open from .isnotebook import _is_in_notebook from .types import ( _TaipyBase, _TaipyBool, _TaipyContent, _TaipyContentHtml, _TaipyContentImage, _TaipyData, _TaipyDate, _TaipyDateRange, _TaipyDict, _TaipyLoNumbers, _TaipyLov, _TaipyLovValue, _TaipyNumber, ) from .varnamefromcontent import _varname_from_content
import re import typing as t __expr_var_name_index: t.Dict[str, int] = {} _RE_NOT_IN_VAR_NAME = r"[^A-Za-z0-9]+" def _get_expr_var_name(expr: str) -> str: var_name = re.sub(_RE_NOT_IN_VAR_NAME, "_", expr) index = 0 if var_name in __expr_var_name_index.keys(): index = __expr_var_name_index[var_name] __expr_var_name_index[var_name] = index + 1 return f"tp_{var_name}_{index}" def _reset_expr_var_name(): __expr_var_name_index.clear()
import socket def _is_port_open(host, port) -> bool: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((host, port)) sock.close() return result == 0
import json import typing as t from abc import ABC from datetime import datetime from .._warnings import _warn from . import _date_to_string, _MapDict, _string_to_date, _variable_decode class _TaipyBase(ABC): __HOLDER_PREFIXES: t.Optional[t.List[str]] = None _HOLDER_PREFIX = "_Tp" def __init__(self, data: t.Any, hash_name: str) -> None: self.__data = data self.__hash_name = hash_name def get(self): return self.__data def get_name(self): return self.__hash_name def set(self, data: t.Any): self.__data = data def cast_value(self, value: t.Any): return value def _get_readable_name(self): try: name, mod = _variable_decode( self.__hash_name[5:] if self.__hash_name.startswith("tpec_") else self.__hash_name ) return name if mod is None or mod == "__main__" else f"{mod}.{name}" except BaseException: return self.__hash_name @staticmethod def get_hash(): return NotImplementedError @staticmethod def _get_holder_prefixes() -> t.List[str]: if _TaipyBase.__HOLDER_PREFIXES is None: _TaipyBase.__HOLDER_PREFIXES = [cls.get_hash() + "_" for cls in _TaipyBase.__subclasses__()] return _TaipyBase.__HOLDER_PREFIXES class _TaipyData(_TaipyBase): @staticmethod def get_hash(): return _TaipyBase._HOLDER_PREFIX + "D" class _TaipyBool(_TaipyBase): def get(self): return self.cast_value(super().get()) def cast_value(self, value: t.Any): return bool(value) @staticmethod def get_hash(): return _TaipyBase._HOLDER_PREFIX + "B" class _TaipyNumber(_TaipyBase): def get(self): try: return float(super().get()) except Exception as e: raise TypeError(f"Variable '{self._get_readable_name()}' should hold a number: {e}") def cast_value(self, value: t.Any): if isinstance(value, str): try: return float(value) if value else 0.0 except Exception as e: _warn(f"{self._get_readable_name()}: Parsing {value} as float", e) return 0.0 return super().cast_value(value) @staticmethod def get_hash(): return _TaipyBase._HOLDER_PREFIX + "N" class _TaipyLoNumbers(_TaipyBase): def cast_value(self, value: t.Any): if isinstance(value, str): try: return list(map(lambda f: float(f), value[1:-1].split(","))) except Exception as e: _warn(f"{self._get_readable_name()}: Parsing {value} as an array of numbers", e) return [] return super().cast_value(value) @staticmethod def get_hash(): return _TaipyBase._HOLDER_PREFIX + "Ln" class _TaipyDate(_TaipyBase): def get(self): val = super().get() if isinstance(val, datetime): val = _date_to_string(val) elif val is not None: val = str(val) return val def cast_value(self, value: t.Any): if isinstance(value, str): return _string_to_date(value) return super().cast_value(value) @staticmethod def get_hash(): return _TaipyBase._HOLDER_PREFIX + "Dt" class _TaipyDateRange(_TaipyBase): def get(self): val = super().get() if isinstance(val, list): return [_date_to_string(v) if isinstance(v, datetime) else None if v is None else str(v) for v in val] return val def cast_value(self, value: t.Any): if isinstance(value, list): return [_string_to_date(v) if isinstance(v, str) else str(v) for v in value] return super().cast_value(value) @staticmethod def get_hash(): return _TaipyBase._HOLDER_PREFIX + "Dr" class _TaipyLovValue(_TaipyBase): @staticmethod def get_hash(): return _TaipyBase._HOLDER_PREFIX + "Lv" class _TaipyLov(_TaipyBase): @staticmethod def get_hash(): return _TaipyBase._HOLDER_PREFIX + "L" class _TaipyContent(_TaipyBase): @staticmethod def get_hash(): return _TaipyBase._HOLDER_PREFIX + "C" class _TaipyContentImage(_TaipyBase): @staticmethod def get_hash(): return _TaipyBase._HOLDER_PREFIX + "Ci" class _TaipyContentHtml(_TaipyBase): @staticmethod def get_hash(): return _TaipyBase._HOLDER_PREFIX + "Ch" class _TaipyDict(_TaipyBase): def get(self): val = super().get() return json.dumps(val._dict if isinstance(val, _MapDict) else val) @staticmethod def get_hash(): return _TaipyBase._HOLDER_PREFIX + "Di"
import sys def is_debugging() -> bool: """NOT DOCUMENTED""" return hasattr(sys, "gettrace") and sys.gettrace() is not None
import typing as t def _is_boolean_true(s: t.Union[bool, str]) -> bool: return ( s if isinstance(s, bool) else s.lower() in ["true", "1", "t", "y", "yes", "yeah", "sure"] if isinstance(s, str) else False ) def _is_boolean(s: t.Any) -> bool: if isinstance(s, bool): return True elif isinstance(s, str): return s.lower() in ["true", "1", "t", "y", "yes", "yeah", "sure", "false", "0", "f", "no"] else: return False
_replace_dict = {".": "__", "[": "_SqrOp_", "]": "_SqrCl_"} def _get_client_var_name(var_name: str) -> str: for k, v in _replace_dict.items(): var_name = var_name.replace(k, v) return var_name def _to_camel_case(value: str, upcase_first=False) -> str: if not isinstance(value, str): raise Exception("_to_camel_case allows only string parameter") if len(value) <= 1: return value.lower() value = value.replace("_", " ").title().replace(" ", "").replace("[", "_").replace("]", "_") return value[0].lower() + value[1:] if not upcase_first else value def _get_broadcast_var_name(s: str) -> str: return _get_client_var_name(f"_bc_{s}")
import re import typing as t from .._warnings import _warn from .boolean import _is_boolean, _is_boolean_true from .clientvarname import _to_camel_case def _get_column_desc(columns: t.Dict[str, t.Any], key: str) -> t.Optional[t.Dict[str, t.Any]]: return next((x for x in columns.values() if x.get("dfid") == key), None) def _get_name_indexed_property(attributes: t.Dict[str, t.Any], name: str) -> t.Dict[str, t.Any]: ret = {} index_re = re.compile(name + r"\[(.*)\]$") for key in attributes.keys(): if m := index_re.match(key): ret[m.group(1)] = attributes.get(key) return ret def _update_col_desc_from_indexed( attributes: t.Dict[str, t.Any], columns: t.Dict[str, t.Any], name: str, elt_name: str ): col_value = _get_name_indexed_property(attributes, name) for k, v in col_value.items(): if col_desc := next((x for x in columns.values() if x.get("dfid") == k), None): if col_desc.get(_to_camel_case(name)) is None: col_desc[_to_camel_case(name)] = str(v) else: _warn(f"{elt_name}: {name}[{k}] is not in the list of displayed columns.") def _enhance_columns( # noqa: C901 attributes: t.Dict[str, t.Any], hash_names: t.Dict[str, str], columns: t.Dict[str, t.Any], elt_name: str ): _update_col_desc_from_indexed(attributes, columns, "nan_value", elt_name) _update_col_desc_from_indexed(attributes, columns, "width", elt_name) filters = _get_name_indexed_property(attributes, "filter") for k, v in filters.items(): if _is_boolean_true(v): if col_desc := _get_column_desc(columns, k): col_desc["filter"] = True else: _warn(f"{elt_name}: filter[{k}] is not in the list of displayed columns.") editables = _get_name_indexed_property(attributes, "editable") for k, v in editables.items(): if _is_boolean(v): if col_desc := _get_column_desc(columns, k): col_desc["notEditable"] = not _is_boolean_true(v) else: _warn(f"{elt_name}: editable[{k}] is not in the list of displayed columns.") group_by = _get_name_indexed_property(attributes, "group_by") for k, v in group_by.items(): if _is_boolean_true(v): if col_desc := _get_column_desc(columns, k): col_desc["groupBy"] = True else: _warn(f"{elt_name}: group_by[{k}] is not in the list of displayed columns.") apply = _get_name_indexed_property(attributes, "apply") for k, v in apply.items(): # pragma: no cover if col_desc := _get_column_desc(columns, k): if callable(v): value = hash_names.get(f"apply[{k}]") elif isinstance(v, str): value = v.strip() else: _warn(f"{elt_name}: apply[{k}] should be a user or predefined function.") value = None if value: col_desc["apply"] = value else: _warn(f"{elt_name}: apply[{k}] is not in the list of displayed columns.") styles = _get_name_indexed_property(attributes, "style") for k, v in styles.items(): # pragma: no cover if col_desc := _get_column_desc(columns, k): if callable(v): value = hash_names.get(f"style[{k}]") elif isinstance(v, str): value = v.strip() else: value = None if value in columns.keys(): _warn(f"{elt_name}: style[{k}]={value} cannot be a column's name.") elif value: col_desc["style"] = value else: _warn(f"{elt_name}: style[{k}] is not in the list of displayed columns.") tooltips = _get_name_indexed_property(attributes, "tooltip") for k, v in tooltips.items(): # pragma: no cover if col_desc := _get_column_desc(columns, k): if callable(v): value = hash_names.get(f"tooltip[{k}]") elif isinstance(v, str): value = v.strip() else: value = None if value in columns.keys(): _warn(f"{elt_name}: tooltip[{k}]={value} cannot be a column's name.") elif value: col_desc["tooltip"] = value else: _warn(f"{elt_name}: tooltip[{k}] is not in the list of displayed columns.") return columns
import typing as t from datetime import datetime from random import random from ..data.data_scope import _DataScopes from ._map_dict import _MapDict if t.TYPE_CHECKING: from ..gui import Gui class _Bindings: def __init__(self, gui: "Gui") -> None: self.__gui = gui self.__scopes = _DataScopes() def _bind(self, name: str, value: t.Any) -> None: if hasattr(self, name): raise ValueError(f"Variable '{name}' is already bound") if not name.isidentifier(): raise ValueError(f"Variable name '{name}' is invalid") if isinstance(value, dict): setattr(self._get_data_scope(), name, _MapDict(value)) else: setattr(self._get_data_scope(), name, value) # prop = property(self.__value_getter(name), self.__value_setter(name)) setattr(_Bindings, name, self.__get_property(name)) def __get_property(self, name): def __setter(ud: _Bindings, value: t.Any): if isinstance(value, dict): value = _MapDict(value, None) ud.__gui._update_var(name, value) def __getter(ud: _Bindings) -> t.Any: value = getattr(ud._get_data_scope(), name) if isinstance(value, _MapDict): return _MapDict(value._dict, lambda k, v: ud.__gui._update_var(f"{name}.{k}", v)) else: return value return property(__getter, __setter) # Getter, Setter def _set_single_client(self, value: bool) -> None: self.__scopes.set_single_client(value) def _is_single_client(self) -> bool: return self.__scopes.is_single_client() def _get_or_create_scope(self, id: str): create = not id if create: id = f"{datetime.now().strftime('%Y%m%d%H%M%S%f')}-{random()}" self.__gui._send_ws_id(id) self.__scopes.create_scope(id) return id, create def _new_scopes(self): self.__scopes = _DataScopes() def _get_data_scope(self): return self.__scopes.get_scope(self.__gui._get_client_id()) def _get_all_scopes(self): return self.__scopes.get_all_scopes()
import re import typing as t from types import FrameType from ._locals_context import _LocalsContext from .get_imported_var import _get_imported_var from .get_module_name import _get_module_name_from_frame, _get_module_name_from_imported_var class _VariableDirectory: def __init__(self, locals_context: _LocalsContext): self._locals_context = locals_context self._default_module = "" self._var_dir: t.Dict[str, t.Dict] = {} self._var_head: t.Dict[str, t.List[t.Tuple[str, str]]] = {} self._imported_var_dir: t.Dict[str, t.List[t.Tuple[str, str, str]]] = {} def set_default(self, frame: FrameType) -> None: self._default_module = _get_module_name_from_frame(frame) self.add_frame(frame) def add_frame(self, frame: t.Optional[FrameType]) -> None: if frame is None: return module_name = _get_module_name_from_frame(frame) if module_name not in self._imported_var_dir: imported_var_list = _get_imported_var(frame) self._imported_var_dir[module_name] = imported_var_list def pre_process_module_import_all(self) -> None: for imported_dir in self._imported_var_dir.values(): additional_var_list: t.List[t.Tuple[str, str, str]] = [] for name, asname, module in imported_dir: if name != "*" or asname != "*": continue if module not in self._locals_context._locals_map.keys(): continue with self._locals_context.set_locals_context(module): additional_var_list.extend( (v, v, module) for v in self._locals_context.get_locals().keys() if not v.startswith("_") ) imported_dir.extend(additional_var_list) def process_imported_var(self) -> None: self.pre_process_module_import_all() default_imported_dir = self._imported_var_dir[self._default_module] with self._locals_context.set_locals_context(self._default_module): for name, asname, module in default_imported_dir: if name == "*" and asname == "*": continue imported_module_name = _get_module_name_from_imported_var( name, self._locals_context.get_locals().get(asname, None), module ) temp_var_name = self.add_var(asname, self._default_module) self.add_var(name, imported_module_name, temp_var_name) for k, v in self._imported_var_dir.items(): with self._locals_context.set_locals_context(k): for name, asname, module in v: if name == "*" and asname == "*": continue imported_module_name = _get_module_name_from_imported_var( name, self._locals_context.get_locals().get(asname, None), module ) var_name = self.get_var(name, imported_module_name) var_asname = self.get_var(asname, k) if var_name is None and var_asname is None: temp_var_name = self.add_var(asname, k) self.add_var(name, imported_module_name, temp_var_name) elif var_name is not None: self.add_var(asname, k, var_name) else: self.add_var(name, imported_module_name, var_asname) def add_var(self, name: str, module: t.Optional[str], var_name: t.Optional[str] = None) -> str: if module is None: module = self._default_module if gv := self.get_var(name, module): return gv var_encode = _variable_encode(name, module) if module != self._default_module else name if var_name is None: var_name = var_encode self.__add_var_head(name, module, var_name) if var_encode != var_name: var_name_decode, module_decode = _variable_decode(var_name) if module_decode is None: module_decode = self._default_module self.__add_var_head(var_name_decode, module_decode, var_encode) if name not in self._var_dir: self._var_dir[name] = {module: var_name} else: self._var_dir[name][module] = var_name return var_name def __add_var_head(self, name: str, module: str, var_head: str) -> None: if var_head not in self._var_head: self._var_head[var_head] = [(name, module)] else: self._var_head[var_head].append((name, module)) def get_var(self, name: str, module: str) -> t.Optional[str]: if name in self._var_dir and module in self._var_dir[name]: return self._var_dir[name][module] return None _MODULE_NAME_MAP: t.List[str] = [] _MODULE_ID = "_TPMDL_" _RE_TPMDL_DECODE = re.compile(r"(.*?)" + _MODULE_ID + r"(\d+)$") def _variable_encode(var_name: str, module_name: t.Optional[str]): if module_name is None: return var_name if module_name not in _MODULE_NAME_MAP: _MODULE_NAME_MAP.append(module_name) return f"{var_name}{_MODULE_ID}{_MODULE_NAME_MAP.index(module_name)}" def _variable_decode(var_name: str): from ._evaluator import _Evaluator if result := _RE_TPMDL_DECODE.match(var_name): return _Evaluator._expr_decode(str(result[1])), _MODULE_NAME_MAP[int(result[2])] return _Evaluator._expr_decode(var_name), None def _reset_name_map(): _MODULE_NAME_MAP.clear()
from typing import Dict class _Singleton(type): _instances: Dict = {} def __call__(self, *args, **kwargs): if self not in self._instances: self._instances[self] = super(_Singleton, self).__call__(*args, **kwargs) return self._instances[self]
import re import pandas as pd def _get_data_type(value): if pd.api.types.is_bool_dtype(value): return "bool" elif pd.api.types.is_integer_dtype(value): return "int" elif pd.api.types.is_float_dtype(value): return "float" return re.match(r"^<class '(.*\.)?(.*?)(\d\d)?'>", str(type(value))).group(2)
import ast import inspect import typing as t from types import FrameType def _get_imported_var(frame: FrameType) -> t.List[t.Tuple[str, str, str]]: st = ast.parse(inspect.getsource(frame)) var_list: t.List[t.Tuple[str, str, str]] = [] for node in ast.walk(st): if isinstance(node, ast.ImportFrom): # get the imported element as (name, asname, module) # ex: from module1 import a as x --> ("a", "x", "module1") var_list.extend( ( child_node.name, child_node.asname if child_node.asname is not None else child_node.name, node.module or "", ) for child_node in node.names ) return var_list
import re import typing as t from datetime import date, datetime, time from dateutil import parser from pytz import utc from .._warnings import _warn def _date_to_string(date_val: t.Union[datetime, date, time]) -> str: if isinstance(date_val, datetime): # return date.isoformat() + 'Z', if possible try: return date_val.astimezone(utc).isoformat() except Exception as e: # astimezone() fails on Windows for pre-epoch times # See https://bugs.python.org/issue36759 _warn("Exception raised converting date to ISO 8601", e) return date_val.isoformat() def _string_to_date(date_str: str) -> t.Union[datetime, date]: # return datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%fZ') # return datetime.fromisoformat(date_str) date = parser.parse(date_str) date_regex = r"^[A-Z][a-z]{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{2} \d{4}$" return date.date() if re.match(date_regex, date_str) else date
from importlib import util def _is_in_notebook(): # pragma: no cover try: if not util.find_spec("IPython"): return False from IPython import get_ipython ipython = get_ipython() if ipython is None or "IPKernelApp" not in ipython.config: return False except (ImportError, AttributeError): return False return True
import typing as t from pathlib import Path def _get_non_existent_file_path(dir_path: Path, file_name: str) -> Path: if not file_name: file_name = "taipy_file.bin" file_path = dir_path / file_name index = 0 file_stem = file_path.stem file_suffix = file_path.suffix while file_path.exists(): file_path = dir_path / f"{file_stem}.{index}{file_suffix}" index += 1 return file_path
import re import typing as t _RE_PD_TYPE = re.compile(r"^([^\s\d\[]+)(\d+)(\[(.*,\s(\S+))\])?") def _get_date_col_str_name(columns: t.List[str], col: str) -> str: suffix = "_str" while col + suffix in columns: suffix += "_" return col + suffix
import typing as t import numpy import pandas as pd from ..gui import Gui from .data_format import _DataFormat from .pandas_data_accessor import _PandasDataAccessor class _NumpyDataAccessor(_PandasDataAccessor): __types = (numpy.ndarray,) @staticmethod def get_supported_classes() -> t.List[str]: return [t.__name__ for t in _NumpyDataAccessor.__types] # type: ignore def __get_dataframe(self, value: t.Any) -> pd.DataFrame: return pd.DataFrame(value) def get_col_types(self, var_name: str, value: t.Any) -> t.Union[None, t.Dict[str, str]]: # type: ignore if isinstance(value, _NumpyDataAccessor.__types): # type: ignore return super().get_col_types(var_name, self.__get_dataframe(value)) return None def get_data( # noqa: C901 self, guiApp: Gui, var_name: str, value: t.Any, payload: t.Dict[str, t.Any], data_format: _DataFormat ) -> t.Dict[str, t.Any]: if isinstance(value, _NumpyDataAccessor.__types): # type: ignore return super().get_data(guiApp, var_name, self.__get_dataframe(value), payload, data_format) return {}
import typing as t import pandas as pd from ..gui import Gui from ..utils import _MapDict from .data_format import _DataFormat from .pandas_data_accessor import _PandasDataAccessor class _ArrayDictDataAccessor(_PandasDataAccessor): __types = (dict, list, tuple, _MapDict) @staticmethod def get_supported_classes() -> t.List[str]: return [t.__name__ for t in _ArrayDictDataAccessor.__types] # type: ignore def __get_dataframe(self, value: t.Any) -> t.Union[t.List[pd.DataFrame], pd.DataFrame]: if isinstance(value, list): if not value or isinstance(value[0], (str, int, float, bool)): return pd.DataFrame({"0": value}) types = {type(x) for x in value} if len(types) == 1: type_elt = next(iter(types), None) if type_elt == list: lengths = {len(x) for x in value} return ( pd.DataFrame(value) if len(lengths) == 1 else [pd.DataFrame({f"{i}/0": v}) for i, v in enumerate(value)] ) elif type_elt == dict: return [pd.DataFrame(v) for v in value] elif type_elt == _MapDict: return [pd.DataFrame(v._dict) for v in value] elif type_elt == pd.DataFrame: return value elif len(types) == 2 and list in types and pd.DataFrame in types: return [v if isinstance(v, pd.DataFrame) else pd.DataFrame({f"{i}/0": v}) for i, v in enumerate(value)] elif isinstance(value, _MapDict): return pd.DataFrame(value._dict) return pd.DataFrame(value) def get_col_types(self, var_name: str, value: t.Any) -> t.Union[None, t.Dict[str, str]]: # type: ignore if isinstance(value, _ArrayDictDataAccessor.__types): # type: ignore return super().get_col_types(var_name, self.__get_dataframe(value)) return None def get_data( # noqa: C901 self, guiApp: Gui, var_name: str, value: t.Any, payload: t.Dict[str, t.Any], data_format: _DataFormat ) -> t.Dict[str, t.Any]: if isinstance(value, _ArrayDictDataAccessor.__types): # type: ignore return super().get_data(guiApp, var_name, self.__get_dataframe(value), payload, data_format) return {}
from .data_accessor import _DataAccessor from .decimator import LTTB, RDP, MinMaxDecimator, ScatterDecimator from .utils import Decimator
import inspect import typing as t from abc import ABC, abstractmethod from .._warnings import _warn from ..utils import _TaipyData from .data_format import _DataFormat class _DataAccessor(ABC): _WS_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" @staticmethod @abstractmethod def get_supported_classes() -> t.List[str]: pass @abstractmethod def get_data( self, guiApp: t.Any, var_name: str, value: t.Any, payload: t.Dict[str, t.Any], data_format: _DataFormat ) -> t.Dict[str, t.Any]: pass @abstractmethod def get_col_types(self, var_name: str, value: t.Any) -> t.Dict[str, str]: pass class _InvalidDataAccessor(_DataAccessor): @staticmethod def get_supported_classes() -> t.List[str]: return [type(None).__name__] def get_data( self, guiApp: t.Any, var_name: str, value: t.Any, payload: t.Dict[str, t.Any], data_format: _DataFormat ) -> t.Dict[str, t.Any]: return {} def get_col_types(self, var_name: str, value: t.Any) -> t.Dict[str, str]: return {} class _DataAccessors(object): def __init__(self) -> None: self.__access_4_type: t.Dict[str, _DataAccessor] = {} self.__invalid_data_accessor = _InvalidDataAccessor() self.__data_format = _DataFormat.JSON from .array_dict_data_accessor import _ArrayDictDataAccessor from .numpy_data_accessor import _NumpyDataAccessor from .pandas_data_accessor import _PandasDataAccessor self._register(_PandasDataAccessor) self._register(_ArrayDictDataAccessor) self._register(_NumpyDataAccessor) def _register(self, cls: t.Type[_DataAccessor]) -> None: if not inspect.isclass(cls): raise AttributeError("The argument of 'DataAccessors.register' should be a class") if not issubclass(cls, _DataAccessor): raise TypeError(f"Class {cls.__name__} is not a subclass of DataAccessor") names = cls.get_supported_classes() if not names: raise TypeError(f"method {cls.__name__}.get_supported_classes returned an invalid value") # check existence inst: t.Optional[_DataAccessor] = None for name in names: inst = self.__access_4_type.get(name) if inst: break if inst is None: try: inst = cls() except Exception as e: raise TypeError(f"Class {cls.__name__} cannot be instanciated") from e if inst: for name in names: self.__access_4_type[name] = inst # type: ignore def __get_instance(self, value: _TaipyData) -> _DataAccessor: # type: ignore value = value.get() access = self.__access_4_type.get(type(value).__name__) if access is None: _warn(f"Can't find Data Accessor for type {type(value).__name__}.") return self.__invalid_data_accessor return access def _get_data( self, guiApp: t.Any, var_name: str, value: _TaipyData, payload: t.Dict[str, t.Any] ) -> t.Dict[str, t.Any]: return self.__get_instance(value).get_data(guiApp, var_name, value.get(), payload, self.__data_format) def _get_col_types(self, var_name: str, value: _TaipyData) -> t.Dict[str, str]: return self.__get_instance(value).get_col_types(var_name, value.get()) def _set_data_format(self, data_format: _DataFormat): self.__data_format = data_format
from __future__ import annotations import typing as t from abc import ABC, abstractmethod import numpy as np from .._warnings import _warn if t.TYPE_CHECKING: import pandas as pd class Decimator(ABC): """Base class for decimating chart data. *Decimating* is the term used to name the process of reducing the number of data points displayed in charts while retaining the overall shape of the traces. `Decimator` is a base class that does decimation on data sets. Taipy GUI comes out-of-the-box with several implementation of this class for different use cases. """ _CHART_MODES: t.List[str] = [] def __init__(self, threshold: t.Optional[int], zoom: t.Optional[bool]) -> None: """Initialize a new `Decimator`. Arguments: threshold (Optional[int]): The minimum amount of data points before the decimator class is applied. zoom (Optional[bool]): set to True to reapply the decimation when zoom or re-layout events are triggered. """ super().__init__() self.threshold = threshold self._zoom = zoom if zoom is not None else True def _is_applicable(self, data: t.Any, nb_rows_max: int, chart_mode: str): if chart_mode not in self._CHART_MODES: _warn(f"{type(self).__name__} is only applicable for {' '.join(self._CHART_MODES)}.") return False if self.threshold is None: if nb_rows_max < len(data): return True elif self.threshold < len(data): return True return False @abstractmethod def decimate(self, data: np.ndarray, payload: t.Dict[str, t.Any]) -> np.ndarray: """Decimate function. This method is executed when the appropriate conditions specified in the constructor are met. This function implements the algorithm that determines which data points are kept or dropped. Arguments: data (numpy.array): An array containing all the data points represented as tuples. payload (Dict[str, any]): additional information on charts that is provided at runtime. Returns: An array of Boolean mask values. The array should set True or False for each of its indexes where True indicates that the corresponding data point from *data* should be preserved, or False requires that this data point be dropped. """ return NotImplementedError # type: ignore def _df_data_filter( dataframe: pd.DataFrame, x_column_name: t.Optional[str], y_column_name: str, z_column_name: str, decimator: Decimator, payload: t.Dict[str, t.Any], is_copied: bool, ): df = dataframe.copy() if not is_copied else dataframe if not x_column_name: index = 0 while f"tAiPy_index_{index}" in df.columns: index += 1 x_column_name = f"tAiPy_index_{index}" df[x_column_name] = df.index column_list = [x_column_name, y_column_name, z_column_name] if z_column_name else [x_column_name, y_column_name] points = df[column_list].to_numpy() mask = decimator.decimate(points, payload) return df[mask], is_copied def _df_relayout( dataframe: pd.DataFrame, x_column: t.Optional[str], y_column: str, chart_mode: str, x0: t.Optional[float], x1: t.Optional[float], y0: t.Optional[float], y1: t.Optional[float], is_copied: bool, ): if chart_mode not in ["lines+markers", "markers"]: return dataframe, is_copied # if chart data is invalid if x0 is None or x1 is None or y0 is None or y1 is None: return dataframe, is_copied df = dataframe.copy() if not is_copied else dataframe is_copied = True has_x_col = True if not x_column: index = 0 while f"tAiPy_index_{index}" in df.columns: index += 1 x_column = f"tAiPy_index_{index}" df[x_column] = df.index has_x_col = False # if chart_mode is empty if chart_mode == "lines+markers": # only filter by x column df = df.loc[(df[x_column] > x0) & (df[x_column] < x1)] else: # filter by both x and y columns df = df.loc[(df[x_column] > x0) & (df[x_column] < x1) & (df[y_column] > y0) & (df[y_column] < y1)] # noqa if not has_x_col: df.drop(x_column, axis=1, inplace=True) return df, is_copied
from enum import Enum class _DataFormat(Enum): JSON = "JSON" APACHE_ARROW = "ARROW"
import base64 import pathlib import tempfile import typing as t import urllib.parse from importlib import util from pathlib import Path from sys import getsizeof from .._warnings import _warn from ..utils import _get_non_existent_file_path, _variable_decode _has_magic_module = False if util.find_spec("magic"): import magic _has_magic_module = True class _ContentAccessor: def __init__(self, data_url_max_size: int) -> None: self.__content_paths: t.Dict[str, pathlib.Path] = {} self.__url_is_image: t.Dict[str, bool] = {} self.__paths: t.Dict[pathlib.Path, str] = {} self.__data_url_max_size = data_url_max_size self.__temp_dir_path = Path(tempfile.gettempdir()) def get_path(self, path: pathlib.Path) -> str: url_path = self.__paths.get(path) if url_path is None: self.__paths[path] = url_path = "taipyStatic" + str(len(self.__paths)) return url_path def get_content_path( self, url_path: str, file_name: str, bypass: t.Optional[str] ) -> t.Tuple[t.Union[pathlib.Path, None], bool]: content_path = self.__content_paths.get(url_path) if not content_path: return (None, True) return (content_path, bypass is not None or self.__url_is_image.get(f"{url_path}/{file_name}", False)) def __get_mime_from_file(self, path: pathlib.Path): if _has_magic_module: try: return magic.from_file(str(path), mime=True) except Exception as e: _warn(f"Exception reading mime type in '{path}'", e) return None def __get_display_name(self, var_name: str) -> str: if not isinstance(var_name, str): return var_name if var_name.startswith("_tpC_"): var_name = var_name[5:] if var_name.startswith("tpec_"): var_name = var_name[5:] return _variable_decode(var_name)[0] def get_info(self, var_name: str, value: t.Any, image: bool) -> t.Union[str, t.Tuple[str], t.Any]: # noqa: C901 if value is None: return "" newvalue = value mime = None if not isinstance(newvalue, (str, pathlib.Path)) and ( getsizeof(newvalue) > self.__data_url_max_size or not _has_magic_module ): # write data to file file_name = "TaiPyContent.bin" if _has_magic_module: try: mime = magic.from_buffer(value, mime=True) file_name = "TaiPyContent." + mime.split("/")[-1] except Exception as e: _warn(f"{self.__get_display_name(var_name)} ({type(value)}) cannot be typed", e) file_path = _get_non_existent_file_path(self.__temp_dir_path, file_name) try: with open(file_path, "wb") as temp_file: temp_file.write(value) except Exception as e: _warn(f"{self.__get_display_name(var_name)} ({type(value)}) cannot be written to file {file_path}", e) newvalue = file_path if isinstance(newvalue, (str, pathlib.Path)): path = pathlib.Path(newvalue) if isinstance(newvalue, str) else newvalue if not path.is_file(): if ( var_name != "Gui.download" and not str(path).startswith("http") and not str(path).startswith("/") and not str(path).strip().lower().startswith("<svg") ): _warn(f"{self.__get_display_name(var_name)}: file '{value}' does not exist.") return str(value) if image: if not mime: mime = self.__get_mime_from_file(path) if mime and not mime.startswith("image"): _warn(f"{self.__get_display_name(var_name)}: file '{path}' mime type ({mime}) is not an image.") return f"Invalid content: {mime}" dir_path = path.resolve().parent url_path = self.get_path(dir_path) self.__content_paths[url_path] = dir_path file_url = f"{url_path}/{path.name}" self.__url_is_image[file_url] = image return (urllib.parse.quote_plus(file_url, safe="/"),) elif _has_magic_module: try: mime = magic.from_buffer(value, mime=True) if not image or mime.startswith("image"): return f"data:{mime};base64," + str(base64.b64encode(value), "utf-8") _warn(f"{self.__get_display_name(var_name)}: ({type(value)}) does not have an image mime type: {mime}.") return f"Invalid content: {mime}" except Exception as e: _warn(f"{self.__get_display_name(var_name)}: ({type(value)}) cannot be base64 encoded", e) return "Cannot be base64 encoded" else: _warn( "python-magic (and python-magic-bin on Windows) packages need to be installed if you want to process content as an array of bytes." # noqa: E501 ) return "Cannot guess content type"
from __future__ import annotations import typing as t from types import SimpleNamespace from .._warnings import _warn class _DataScopes: _GLOBAL_ID = "global" def __init__(self) -> None: self.__scopes: t.Dict[str, SimpleNamespace] = {_DataScopes._GLOBAL_ID: SimpleNamespace()} self.__single_client = True def set_single_client(self, value: bool) -> None: self.__single_client = value def is_single_client(self) -> bool: return self.__single_client def get_scope(self, client_id: t.Optional[str]) -> SimpleNamespace: if self.__single_client: return self.__scopes[_DataScopes._GLOBAL_ID] # global context in case request is not registered or client_id is not # available (such as in the context of running tests) if not client_id: _warn("Empty session id, using global scope instead.") return self.__scopes[_DataScopes._GLOBAL_ID] if client_id not in self.__scopes: _warn( f"Session id {client_id} not found in data scope. Taipy will automatically create a scope for this session id but you may have to reload your page." # noqa: E501 ) self.create_scope(client_id) return self.__scopes[client_id] def get_all_scopes(self) -> t.Dict[str, SimpleNamespace]: return self.__scopes def create_scope(self, id: str) -> None: if self.__single_client: return if id is None: _warn("Empty session id, might be due to unestablished WebSocket connection.") return if id not in self.__scopes: self.__scopes[id] = SimpleNamespace() def delete_scope(self, id: str) -> None: # pragma: no cover if self.__single_client: return if id is None: _warn("Empty session id, might be due to unestablished WebSocket connection.") return if id in self.__scopes: del self.__scopes[id]
import typing as t import numpy as np from ..utils import Decimator class ScatterDecimator(Decimator): """A decimator designed for scatter charts. This algorithm fits the data points into a grid. If multiple points are in the same grid cell, depending on the chart configuration, some points are removed to reduce the number points being displayed. This class can only be used with scatter charts. """ _CHART_MODES = ["markers"] def __init__( self, binning_ratio: t.Optional[float] = None, max_overlap_points: t.Optional[int] = None, threshold: t.Optional[int] = None, zoom: t.Optional[bool] = True, ): """Initialize a new `ScatterDecimator`. Arguments: binning_ratio (Optional[float]): the size of the data grid for the algorithm. The higher the value, the smaller the grid size. max_overlap_points (Optional(int)): the maximum number of points for a single cell within the data grid within the algorithm. This dictates how dense a single grid cell can be. threshold (Optional[int]): The minimum amount of data points before the decimation is applied. zoom (Optional[bool]): set to True to reapply the decimation when zoom or re-layout events are triggered. """ super().__init__(threshold, zoom) binning_ratio = binning_ratio if binning_ratio is not None else 1 self._binning_ratio = binning_ratio if binning_ratio > 0 else 1 self._max_overlap_points = max_overlap_points if max_overlap_points is not None else 3 def decimate(self, data: np.ndarray, payload: t.Dict[str, t.Any]) -> np.ndarray: n_rows = data.shape[0] mask = np.empty(n_rows, dtype=bool) width = payload.get("width", None) height = payload.get("height", None) if width is None or height is None: mask.fill(True) return mask mask.fill(False) grid_x, grid_y = round(width / self._binning_ratio), round(height / self._binning_ratio) x_col, y_col = data[:, 0], data[:, 1] min_x, max_x = np.amin(x_col), np.amax(x_col) min_y, max_y = np.amin(y_col), np.amax(y_col) min_max_x_diff, min_max_y_diff = max_x - min_x, max_y - min_y x_grid_map = np.rint((x_col - min_x) * grid_x / min_max_x_diff).astype(int) y_grid_map = np.rint((y_col - min_y) * grid_y / min_max_y_diff).astype(int) z_grid_map = None grid_shape = (grid_x + 1, grid_y + 1) if len(data[0]) == 3: grid_z = grid_x grid_shape = (grid_x + 1, grid_y + 1, grid_z + 1) # type: ignore z_col = data[:, 2] min_z, max_z = np.amin(z_col), np.amax(z_col) min_max_z_diff = max_z - min_z z_grid_map = np.rint((z_col - min_z) * grid_z / min_max_z_diff).astype(int) grid = np.empty(grid_shape, dtype=int) grid.fill(0) if z_grid_map is not None: for i in np.arange(n_rows): if grid[x_grid_map[i], y_grid_map[i], z_grid_map[i]] < self._max_overlap_points: grid[x_grid_map[i], y_grid_map[i], z_grid_map[i]] += 1 mask[i] = True else: for i in np.arange(n_rows): if grid[x_grid_map[i], y_grid_map[i]] < self._max_overlap_points: grid[x_grid_map[i], y_grid_map[i]] += 1 mask[i] = True return mask
from .lttb import LTTB from .minmax import MinMaxDecimator from .rdp import RDP from .scatter_decimator import ScatterDecimator
import typing as t import numpy as np from ..utils import Decimator class MinMaxDecimator(Decimator): """A decimator using the MinMax algorithm. The MinMax algorithm is an efficient algorithm that preserves the peaks within the data. It can work very well with noisy signal data where data peeks need to be highlighted. This class can only be used with line charts. """ _CHART_MODES = ["lines+markers"] def __init__(self, n_out: int, threshold: t.Optional[int] = None, zoom: t.Optional[bool] = True): """Initialize a new `MinMaxDecimator`. Arguments: n_out (int): The maximum number of points that will be displayed after decimation. threshold (Optional[int]): The minimum amount of data points before the decimation is applied. zoom (Optional[bool]): set to True to reapply the decimation when zoom or re-layout events are triggered. """ super().__init__(threshold, zoom) self._n_out = n_out // 2 def decimate(self, data: np.ndarray, payload: t.Dict[str, t.Any]) -> np.ndarray: if self._n_out >= data.shape[0]: return np.full(len(data), False) # Create a boolean mask x = data[:, 0] y = data[:, 1] num_bins = self._n_out pts_per_bin = x.size // num_bins # Create temp to hold the reshaped & slightly cropped y y_temp = y[: num_bins * pts_per_bin].reshape((num_bins, pts_per_bin)) # use argmax/min to get column locations cc_max = np.argmax(y_temp, axis=1) cc_min = np.argmin(y_temp, axis=1) rr = np.arange(0, num_bins) # compute the flat index to where these are flat_max = cc_max + rr * pts_per_bin flat_min = cc_min + rr * pts_per_bin mm_mask = np.full((x.size,), False) mm_mask[flat_max] = True mm_mask[flat_min] = True return mm_mask
import typing as t import numpy as np from ..utils import Decimator class LTTB(Decimator): """A decimator using the LTTB algorithm. The LTTB algorithm is an high performance algorithm that significantly reduces the number of data points. It can work very well with time-series data to show trends using by using only a few data points. This class can only be used with line charts. """ _CHART_MODES = ["lines+markers"] def __init__(self, n_out: int, threshold: t.Optional[int] = None, zoom: t.Optional[bool] = True) -> None: """Initialize a new `LTTB`. Arguments: n_out (int): The maximum number of points that will be displayed after decimation. threshold (Optional[int]): The minimum amount of data points before the decimation is applied. zoom (Optional[bool]): set to True to reapply the decimation when zoom or re-layout events are triggered. """ super().__init__(threshold, zoom) self._n_out = n_out @staticmethod def _areas_of_triangles(a, bs, c): bs_minus_a = bs - a a_minus_bs = a - bs return 0.5 * abs((a[0] - c[0]) * (bs_minus_a[:, 1]) - (a_minus_bs[:, 0]) * (c[1] - a[1])) def decimate(self, data: np.ndarray, payload: t.Dict[str, t.Any]) -> np.ndarray: n_out = self._n_out if n_out >= data.shape[0]: return np.full(len(data), True) if n_out < 3: raise ValueError("Can only down-sample to a minimum of 3 points") # Split data into bins n_bins = n_out - 2 data_bins = np.array_split(data[1:-1], n_bins) prev_a = data[0] start_pos = 0 # Prepare output mask array # First and last points are the same as in the input. out_mask = np.full(len(data), False) out_mask[0] = True out_mask[len(data) - 1] = True # Largest Triangle Three Buckets (LTTB): # In each bin, find the point that makes the largest triangle # with the point saved in the previous bin # and the centroid of the points in the next bin. for i in range(len(data_bins)): this_bin = data_bins[i] next_bin = data_bins[i + 1] if i < n_bins - 1 else data[-1:] a = prev_a bs = this_bin c = next_bin.mean(axis=0) areas = LTTB._areas_of_triangles(a, bs, c) bs_pos = np.argmax(areas) prev_a = bs[bs_pos] out_mask[start_pos + bs_pos] = True start_pos += len(this_bin) return out_mask
import typing as t import numpy as np from ..utils import Decimator class RDP(Decimator): """A decimator using the RDP algorithm. The RDP algorithm reduces a shape made of line segments into a similar shape with less points. This algorithm should be used if the final visual representation is prioritized over the performance of the application. This class can only be used with line charts. """ _CHART_MODES = ["lines+markers"] def __init__( self, epsilon: t.Optional[int] = None, n_out: t.Optional[int] = None, threshold: t.Optional[int] = None, zoom: t.Optional[bool] = True, ): """Initialize a new `RDP`. Arguments: epsilon (Optional[int]): The epsilon value for the RDP algorithm. If this value is being used, the *n_out* argument is ignored. n_out (Optional(int)): The maximum number of points that are displayed after decimation. This value is ignored if the epsilon value is used.<br/> This process is not very efficient so consider using `LTTB` or `MinMaxDecimator` if the provided data has more than 100.000 data points. threshold (Optional[int]): The minimum amount of data points before the decimation is applied. zoom (Optional[bool]): set to True to reapply the decimation when zoom or re-layout events are triggered. """ super().__init__(threshold, zoom) self._epsilon = epsilon self._n_out = n_out @staticmethod def dsquared_line_points(P1, P2, points): """ Calculate only squared distance, only needed for comparison """ xdiff = P2[0] - P1[0] ydiff = P2[1] - P1[1] nom = (ydiff * points[:, 0] - xdiff * points[:, 1] + P2[0] * P1[1] - P2[1] * P1[0]) ** 2 denom = ydiff ** 2 + xdiff ** 2 return np.divide(nom, denom) @staticmethod def __rdp_epsilon(data, epsilon: int): # initiate mask array # same amount of points mask = np.empty(data.shape[0], dtype=bool) # Assume all points are valid and falsify those which are found mask.fill(True) # The stack to select start and end index stack: t.List[t.Tuple[int, int]] = [(0, data.shape[0] - 1)] # type: ignore while stack: # Pop the last item (start, end) = stack.pop() # nothing to calculate if no points in between if end - start <= 1: continue # Calculate distance to points P1 = data[start] P2 = data[end] points = data[start + 1 : end] dsq = RDP.dsquared_line_points(P1, P2, points) mask_eps = dsq > epsilon ** 2 if mask_eps.any(): # max point outside eps # Include index that was sliced out # Also include the start index to get absolute index # And not relative mid = np.argmax(dsq) + 1 + start stack.append((start, mid)) # type: ignore stack.append((mid, end)) # type: ignore else: # Points in between are redundant mask[start + 1 : end] = False return mask @staticmethod def __rdp_points(M, n_out): M_len = M.shape[0] if M_len <= n_out: mask = np.empty(M_len, dtype=bool) mask.fill(True) return mask weights = np.empty(M_len) # weights.fill(0) weights[0] = float("inf") weights[M_len - 1] = float("inf") stack = [(0, M_len - 1)] while stack: (start, end) = stack.pop() if end - start <= 1: continue dsq = RDP.dsquared_line_points(M[start], M[end], M[start + 1 : end]) max_dist_index = np.argmax(dsq) + start + 1 weights[max_dist_index] = np.amax(dsq) stack.append((start, max_dist_index)) stack.append((max_dist_index, end)) maxTolerance = np.sort(weights)[M_len - n_out] return weights >= maxTolerance def decimate(self, data: np.ndarray, payload: t.Dict[str, t.Any]) -> np.ndarray: if self._epsilon: return RDP.__rdp_epsilon(data, self._epsilon) elif self._n_out: return RDP.__rdp_points(data, self._n_out) raise RuntimeError("RDP Decimator failed to run. Fill in either 'epsilon' or 'n_out' value")
import typing as t from ..utils.singleton import _Singleton if t.TYPE_CHECKING: from ._element import _Block class _BuilderContextManager(object, metaclass=_Singleton): def __init__(self): self.__blocks: t.List["_Block"] = [] def push(self, element: "_Block") -> None: self.__blocks.append(element) def pop(self) -> t.Optional["_Block"]: return self.__blocks.pop() if self.__blocks else None def peek(self) -> t.Optional["_Block"]: return self.__blocks[-1] if self.__blocks else None
from ._api_generator import _ElementApiGenerator from ._element import html # separate import for "Page" class so stubgen can properly generate pyi file from .page import Page _ElementApiGenerator().add_default()
import typing as t from .._renderers import _Renderer from ._context_manager import _BuilderContextManager from ._element import _Block, _DefaultBlock, _Element class Page(_Renderer): """Page generator for the Builder API. This class is used to create a page created with the Builder API.<br/> Instance of this class can be added to the application using `Gui.add_page()^`. This class is typically be used as a Python Context Manager to add the elements.<br/> Here is how you can create a single-page application, creating the elements with code: ```py from taipy.gui import Gui from taipy.gui.builder import Page, button def do_something(state): pass with Page() as page: button(label="Press me", on_action=do_something) Gui(page).run() ``` """ def __init__(self, element: t.Optional[_Element] = None, **kwargs) -> None: """Initialize a new page. Arguments: element (*Element*): An optional element, defined in the `taipy.gui.builder` module, that is created in the page.<br/> The default creates a `part` where several elements can be stored. """ if element is None: element = _DefaultBlock() kwargs["content"] = element super().__init__(**kwargs) # Generate JSX from Element Object def render(self, gui) -> str: if self._base_element is None: return "<h1>No Base Element found for Page</h1>" return self._base_element._render(gui) def add(self, *elements: _Element): if not isinstance(self._base_element, _Block): raise RuntimeError("Can't add child element to non-block element") for element in elements: if element not in self._base_element._children: self._base_element._children.append(element) return self def __enter__(self): if self._base_element is None: raise RuntimeError("Can't use context manager with missing block element for Page") if not isinstance(self._base_element, _Block): raise RuntimeError("Can't add child element to non-block element") _BuilderContextManager().push(self._base_element) return self def __exit__(self, exc_type, exc_value, traceback): _BuilderContextManager().pop()
import typing as t from .._renderers.factory import _Factory class _BuilderFactory(_Factory): @staticmethod def create_element(gui, element_type: str, properties: t.Dict[str, t.Any]) -> t.Tuple[str, str]: builder_html = _Factory.call_builder(gui, element_type, properties, True) if builder_html is None: return f"<div>INVALID SYNTAX - Element is '{element_type}'", "div" return builder_html # type: ignore
from __future__ import annotations import copy import typing as t from abc import ABC, abstractmethod from collections.abc import Iterable from ._context_manager import _BuilderContextManager from ._factory import _BuilderFactory if t.TYPE_CHECKING: from ..gui import Gui class _Element(ABC): """NOT DOCUMENTED""" _ELEMENT_NAME = "" _DEFAULT_PROPERTY = "" def __new__(cls, *args, **kwargs): obj = super(_Element, cls).__new__(cls) parent = _BuilderContextManager().peek() if parent is not None: parent.add(obj) return obj def __init__(self, *args, **kwargs): self._properties: t.Dict[str, t.Any] = {} if args and self._DEFAULT_PROPERTY != "": self._properties = {self._DEFAULT_PROPERTY: args[0]} self._properties.update(kwargs) self.parse_properties() def update(self, **kwargs): self._properties.update(kwargs) self.parse_properties() # Convert property value to string def parse_properties(self): self._properties = {k: _Element._parse_property(v) for k, v in self._properties.items()} # Get a deepcopy version of the properties def _deepcopy_properties(self): return copy.deepcopy(self._properties) @staticmethod def _parse_property(value: t.Any) -> t.Any: if isinstance(value, (str, dict, Iterable)): return value if hasattr(value, "__name__"): return str(getattr(value, "__name__")) return str(value) @abstractmethod def _render(self, gui: "Gui") -> str: pass class _Block(_Element): """NOT DOCUMENTED""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._children: t.List[_Element] = [] def add(self, *elements: _Element): for element in elements: if element not in self._children: self._children.append(element) return self def __enter__(self): _BuilderContextManager().push(self) return self def __exit__(self, exc_type, exc_value, traceback): _BuilderContextManager().pop() def _render(self, gui: "Gui") -> str: el = _BuilderFactory.create_element(gui, self._ELEMENT_NAME, self._deepcopy_properties()) return f"{el[0]}{self._render_children(gui)}</{el[1]}>" def _render_children(self, gui: "Gui") -> str: return "\n".join([child._render(gui) for child in self._children]) class _DefaultBlock(_Block): _ELEMENT_NAME = "part" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class html(_Block): """A visual element defined as an HTML tag. Use this class to integrate raw HTML to your page. This element can be used as a block element. """ def __init__(self, *args, **kwargs): """Create a new `html` block. Arguments: args (any[]): A list of one or two unnamed arguments: - *args[0]* is the HTML tag name. If empty or None, this represents an HTML text node. - *args[1]* (optional) is the text of this element.<br/> Note that special HTML characters (such as '&lt;' or '&amp;') do not need to be protected. kwargs (dict[str, any]): the HTML attributes for this element.<br/> These should be valid attribute names, with valid attribute values. Examples: - To generate `<br/>`, use: ``` html("br") ``` - To generate `<h1>My page title</h1>`, use: ``` html("h1", "My page title") ``` - To generate `<h1 id="page-title">My page title</h1>`, use: ``` html("h1", "My page title", id="page-title") ``` - To generate `<p>This is a <b>Taipy GUI</b> element.</p>`, use: ``` with html("p"): html(None, "This is a ") html("b", "Taipy GUI") html(None, " element.") ``` """ super().__init__(*args, **kwargs) if not args: raise RuntimeError("Can't render html element. Missing html tag name.") self._ELEMENT_NAME = args[0] if args[0] else None self._content = args[1] if len(args) > 1 else "" def _render(self, gui: "Gui") -> str: if self._ELEMENT_NAME: attrs = "" if self._properties: attrs = " " + " ".join([f'{k}="{str(v)}"' for k, v in self._properties.items()]) return f"<{self._ELEMENT_NAME}{attrs}>{self._content}{self._render_children(gui)}</{self._ELEMENT_NAME}>" else: return self._content class _Control(_Element): """NOT DOCUMENTED""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _render(self, gui: "Gui") -> str: el = _BuilderFactory.create_element(gui, self._ELEMENT_NAME, self._deepcopy_properties()) return ( f"<div>{el[0]}</{el[1]}></div>" if f"<{el[1]}" in el[0] and f"</{el[1]}" not in el[0] else f"<div>{el[0]}</div>" ) def __enter__(self): raise RuntimeError(f"Can't use Context Manager for control type '{self._ELEMENT_NAME}'") def __exit__(self, exc_type, exc_value, traceback): raise RuntimeError(f"Can't use Context Manager for control type '{self._ELEMENT_NAME}'")
import inspect import json import os import sys import types import typing as t from taipy.logger._taipy_logger import _TaipyLogger from ..utils.singleton import _Singleton from ._element import _Block, _Control if t.TYPE_CHECKING: from ..extension.library import ElementLibrary class _ElementApiGenerator(object, metaclass=_Singleton): def __init__(self): self.__module: t.Optional[types.ModuleType] = None @staticmethod def find_default_property(property_list: t.List[t.Dict[str, t.Any]]) -> str: for property in property_list: if "default_property" in property and property["default_property"] is True: return property["name"] return "" def add_default(self): current_frame = inspect.currentframe() error_message = "Cannot generate elements API for the current module" if current_frame is None: raise RuntimeError(f"{error_message}: No frame found.") if current_frame.f_back is None: raise RuntimeError(f"{error_message}: taipy-gui module not found.") module_name = current_frame.f_back.f_globals["__name__"] self.__module = module = sys.modules[module_name] with open(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "viselements.json"))) as viselements: data = json.load(viselements) if "blocks" not in data or "controls" not in data: raise RuntimeError(f"{error_message}: Invalid viselements.json file.") for blockElement in data["blocks"]: default_property = _ElementApiGenerator.find_default_property(blockElement[1]["properties"]) setattr( module, blockElement[0], _ElementApiGenerator.create_block_api(blockElement[0], blockElement[0], default_property), ) for controlElement in data["controls"]: default_property = _ElementApiGenerator.find_default_property(controlElement[1]["properties"]) setattr( module, controlElement[0], _ElementApiGenerator.create_control_api(controlElement[0], controlElement[0], default_property), ) def add_library(self, library: "ElementLibrary"): library_name = library.get_name() if self.__module is None: _TaipyLogger._get_logger().info( f"Python API for extension library '{library_name}' is not available. To fix this, import 'taipy.gui.builder' before importing the extension library." # noqa: E501 ) return library_module = getattr(self.__module, library_name, None) if library_module is None: library_module = types.ModuleType(library_name) setattr(self.__module, library_name, library_module) for element_name, element in library.get_elements().items(): setattr( library_module, element_name, _ElementApiGenerator().create_control_api( element_name, f"{library_name}.{element_name}", element.default_attribute ), ) @staticmethod def create_block_api( classname: str, element_name: str, default_property: str, ): return _ElementApiGenerator.create_element_api(classname, element_name, default_property, _Block) @staticmethod def create_control_api( classname: str, element_name: str, default_property: str, ): return _ElementApiGenerator.create_element_api(classname, element_name, default_property, _Control) @staticmethod def create_element_api( classname: str, element_name: str, default_property: str, ElementBaseClass: t.Union[t.Type[_Block], t.Type[_Control]], ): return type( classname, (ElementBaseClass,), { "__init__": lambda self, *args, **kwargs: ElementBaseClass.__init__(self, *args, **kwargs), "_ELEMENT_NAME": element_name, "_DEFAULT_PROPERTY": default_property, }, )
import typing as t from abc import ABC, abstractmethod from os import path from ..page import Page from ..utils import _is_in_notebook, _varname_from_content from ._html import _TaipyHTMLParser if t.TYPE_CHECKING: from ..builder._element import _Element from ..gui import Gui class _Renderer(Page, ABC): def __init__(self, **kwargs) -> None: """NOT DOCUMENTED Initialize a new _Renderer with the indicated content. Arguments: content (str): The text content or the path to the file holding the text to be transformed. If *content* is a path to a readable file, the file is read entirely as the text template. """ from ..builder._element import _Element # noqa: F811 super().__init__(**kwargs) content: t.Optional[t.Union[str, _Element]] = kwargs.get("content", None) if content is None: raise ValueError("'content' argument is missing for class '_Renderer'") self._content = "" self._base_element: t.Optional[_Element] = None self._filepath = "" if isinstance(content, str): self.__process_content(content) elif isinstance(content, _Element): self._base_element = content else: raise ValueError( f"'content' argument has incorrect type '{type(content).__name__}'. This must be a string or an Builder element." # noqa: E501 ) def __process_content(self, content: str) -> None: if path.exists(content) and path.isfile(content): return self.__parse_file_content(content) if self._frame is not None: frame_dir_path = path.dirname(path.abspath(self._frame.f_code.co_filename)) content_path = path.join(frame_dir_path, content) if path.exists(content_path) and path.isfile(content_path): return self.__parse_file_content(content_path) self._content = content def __parse_file_content(self, content): with open(t.cast(str, content), "r") as f: self._content = f.read() # Save file path for error handling self._filepath = content def set_content(self, content: str) -> None: """Set a new page content. Reads the new page content and reinitializes the `Page^` instance to reflect the change. !!! important This function can only be used in an IPython notebook context. Arguments: content (str): The text content or the path to the file holding the text to be transformed. If *content* is a path to a readable file, the file is read entirely as the text template. Exceptions: RuntimeError: If this method is called outside an IPython notebook context. """ if not _is_in_notebook(): raise RuntimeError("'set_content()' must be used in an IPython notebook context") self.__process_content(content) def _get_content_detail(self, gui: "Gui") -> str: if self._filepath: return f"in file '{self._filepath}'" if varname := _varname_from_content(gui, self._content): return f"in variable '{varname}'" return "" @abstractmethod def render(self, gui: "Gui") -> str: pass class _EmptyPage(_Renderer): def __init__(self) -> None: super().__init__(content="<PageContent />") def render(self, gui: "Gui") -> str: return self._content class Markdown(_Renderer): """Page generator for *Markdown* text. Taipy can use Markdown text to create pages that are the base of user interfaces. You can find details on the Taipy Markdown-specific syntax and how to add Taipy Visual Elements in the [section on HTML](../gui/pages/index.md#using-markdown) of the User Manual. """ def __init__(self, content: str, **kwargs) -> None: """Initialize a new `Markdown` page. Arguments: content (str): The text content or the path to the file holding the Markdown text to be transformed.<br/> If _content_ is a path to a readable file, the file is read as the Markdown template content. """ kwargs["content"] = content super().__init__(**kwargs) # Generate JSX from Markdown def render(self, gui: "Gui") -> str: return gui._markdown.convert(self._content) class Html(_Renderer): """Page generator for *HTML* text. Taipy can use HTML code to create pages that are the base of user interfaces. You can find details on HTML-specific constructs and how to add Taipy Visual Elements in the [section on HTML](../gui/pages/index.md#using-html) of the User Manual. """ def __init__(self, content: str, **kwargs) -> None: """Initialize a new `Html` page. Arguments: content (str): The text content or the path to the file holding the HTML text to be transformed.<br/> If *content* is a path to a readable file, the file is read as the HTML template content. """ kwargs["content"] = content super().__init__(**kwargs) self.head = None # Modify path routes def modify_taipy_base_url(self, base_url): self._content = self._content.replace("{{taipy_base_url}}", f"{base_url}") # Generate JSX from HTML def render(self, gui: "Gui") -> str: parser = _TaipyHTMLParser(gui) parser.feed_data(self._content) self.head = parser.head return parser.get_jsx()
import typing as t from .._warnings import _warn from ..gui_types import NumberTypes from ..utils import _RE_PD_TYPE, _get_date_col_str_name, _MapDict def _add_to_dict_and_get(dico: t.Dict[str, t.Any], key: str, value: t.Any) -> t.Any: if key not in dico.keys(): dico[key] = value return dico[key] def _get_tuple_val(attr: tuple, index: int, default_val: t.Any) -> t.Any: return attr[index] if len(attr) > index else default_val def _get_columns_dict_from_list( col_list: t.Union[t.List[str], t.Tuple[str]], col_types_keys: t.List[str], value: t.Any ): col_dict = {} idx = 0 for col in col_list: if col in col_types_keys: col_dict[col] = {"index": idx} idx += 1 elif col: _warn( f'Error column "{col}" is not present in the Dataframe "{value.head(0) if hasattr(value, "head") else value}".' # noqa: E501 ) return col_dict def _get_columns_dict( # noqa: C901 value: t.Any, columns: t.Union[str, t.List[str], t.Tuple[str], t.Dict[str, t.Any], _MapDict], col_types: t.Optional[t.Dict[str, str]] = None, date_format: t.Optional[str] = None, number_format: t.Optional[str] = None, opt_columns: t.Optional[t.Set[str]] = None, ): if col_types is None: return None col_dict: t.Optional[dict] = None if isinstance(columns, str): col_dict = _get_columns_dict_from_list([s.strip() for s in columns.split(";")], col_types_keys, value) elif isinstance(columns, (list, tuple)): col_dict = _get_columns_dict_from_list(columns, col_types_keys, value) elif isinstance(columns, _MapDict): col_dict = columns._dict.copy() elif isinstance(columns, dict): col_dict = columns.copy() if not isinstance(col_dict, dict): _warn("Error: columns attributes should be a string, a list, a tuple or a dict.") col_dict = {} nb_cols = len(col_dict) if nb_cols == 0: for col in col_types_keys: col_dict[col] = {"index": nb_cols} nb_cols += 1 else: col_dict = {str(k): v for k, v in col_dict.items()} if opt_columns: for col in opt_columns: if col in col_types_keys and col not in col_dict: col_dict[col] = {"index": nb_cols} nb_cols += 1 idx = 0 for col, ctype in col_types.items(): col = str(col) if col in col_dict: re_type = _RE_PD_TYPE.match(ctype) grps = re_type.groups() if re_type else () ctype = grps[0] if grps else ctype col_dict[col]["type"] = ctype col_dict[col]["dfid"] = col if len(grps) > 4 and grps[4]: col_dict[col]["tz"] = grps[4] idx = _add_to_dict_and_get(col_dict[col], "index", idx) + 1 if ctype == "datetime": if date_format: _add_to_dict_and_get(col_dict[col], "format", date_format) col_dict[_get_date_col_str_name(col_types.keys(), col)] = col_dict.pop(col) # type: ignore elif number_format and ctype in NumberTypes: _add_to_dict_and_get(col_dict[col], "format", number_format) return col_dict
# # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. from __future__ import annotations from datetime import date, datetime, time from json import JSONEncoder from pathlib import Path from flask.json.provider import DefaultJSONProvider from .._warnings import _warn from ..icon import Icon from ..utils import _date_to_string, _MapDict, _TaipyBase def _default(o): if isinstance(o, Icon): return o._to_dict() if isinstance(o, _MapDict): return o._dict if isinstance(o, _TaipyBase): return o.get() if isinstance(o, (datetime, date, time)): return _date_to_string(o) if isinstance(o, Path): return str(o) try: raise TypeError(f"Object of type {o.__class__.__name__} is not JSON serializable") except Exception as e: _warn("Exception in JSONEncoder", e) return None class _TaipyJsonEncoder(JSONEncoder): def default(self, o): return _default(o) class _TaipyJsonProvider(DefaultJSONProvider): default = staticmethod(_default) # type: ignore sort_keys = False
from markdown.treeprocessors import Treeprocessor from ..builder import _Builder class _Postprocessor(Treeprocessor): @staticmethod def extend(md, gui, priority): instance = _Postprocessor(md) md.treeprocessors.register(instance, "taipy", priority) instance._gui = gui def run(self, root): MD_PARA_CLASSNAME = "md-para" for p in root.iter(): if p.tag == "p": classes = p.get("class") classes = f"{MD_PARA_CLASSNAME} {classes}" if classes else MD_PARA_CLASSNAME p.set("class", classes) p.tag = "div" if p != root: p.set("key", _Builder._get_key(p.tag)) return root
from markdown.inlinepatterns import InlineProcessor from .factory import _MarkdownFactory class _ControlPattern(InlineProcessor): __PATTERN = _MarkdownFactory._TAIPY_START + r"([a-zA-Z][\.a-zA-Z_$0-9]*)(.*?)" + _MarkdownFactory._TAIPY_END @staticmethod def extend(md, gui, priority): instance = _ControlPattern(_ControlPattern.__PATTERN, md) md.inlinePatterns.register(instance, "taipy", priority) instance._gui = gui def handleMatch(self, m, data): return _MarkdownFactory.create_element(self._gui, m.group(1), m.group(2)), m.start(0), m.end(0)
import re from markdown.blockprocessors import BlockProcessor from .factory import _MarkdownFactory class _StartBlockProcessor(BlockProcessor): __RE_FENCE_START = re.compile( _MarkdownFactory._TAIPY_START + r"([a-zA-Z][\.a-zA-Z_$0-9]*)\.start(.*?)" + _MarkdownFactory._TAIPY_END ) # start line __RE_OTHER_FENCE = re.compile( _MarkdownFactory._TAIPY_START + r"([a-zA-Z][\.a-zA-Z_$0-9]*)\.(start|end)(.*?)" + _MarkdownFactory._TAIPY_END ) # start or end tag @staticmethod def extend(md, gui, priority): instance = _StartBlockProcessor(md.parser) md.parser.blockprocessors.register(instance, "taipy", priority) instance._gui = gui def test(self, parent, block): return re.match(_StartBlockProcessor.__RE_FENCE_START, block) def run(self, parent, blocks): original_block = blocks[0] original_match = re.search(_StartBlockProcessor.__RE_FENCE_START, original_block) blocks[0] = re.sub(_StartBlockProcessor.__RE_FENCE_START, "", blocks[0], 1) tag = original_match.group(1) queue = [tag] # Find block with ending fence for block_num, block in enumerate(blocks): matches = re.findall(_StartBlockProcessor.__RE_OTHER_FENCE, block) for match in matches: if queue[-1] == match[0] and match[1] == "end": queue.pop() elif match[1] == "start": queue.append(match[0]) if not queue: # remove end fence blocks[block_num] = re.sub( _MarkdownFactory._TAIPY_START + tag + r"\.end(.*?)" + _MarkdownFactory._TAIPY_END, "", block, 1, ) # render fenced area inside a new div e = _MarkdownFactory.create_element(self._gui, original_match.group(1), original_match.group(2)) parent.append(e) # parse inside blocks self.parser.parseBlocks(e, blocks[: block_num + 1]) # remove used blocks del blocks[: block_num + 1] return True # or could have had no return statement # No closing marker! Restore and do nothing blocks[0] = original_block return False # equivalent to our test() routine returning False
from typing import Any from markdown.extensions import Extension from .blocproc import _StartBlockProcessor from .control import _ControlPattern from .postproc import _Postprocessor from .preproc import _Preprocessor class _TaipyMarkdownExtension(Extension): config = {"gui": ["", "Gui object for extension"]} def extendMarkdown(self, md): from ...gui import Gui gui = self.config["gui"][0] if not isinstance(gui, Gui): raise RuntimeError("Gui instance is not bound to Markdown Extension") md.registerExtension(self) _Preprocessor.extend(md, gui, 210) _ControlPattern.extend(md, gui, 205) _StartBlockProcessor.extend(md, gui, 175) _Postprocessor.extend(md, gui, 200)
import typing as t from ..factory import _Factory class _MarkdownFactory(_Factory): # Taipy Markdown tags _TAIPY_START = "TaIpY:" _TAIPY_END = ":tAiPy" _TAIPY_BLOCK_TAGS = ["layout", "part", "expandable", "dialog", "pane"] @staticmethod def create_element(gui, control_type: str, all_properties: str) -> t.Union[t.Any, str]: # Create properties dict from all_properties property_pairs = _Factory._PROPERTY_RE.findall(all_properties) properties = {property[0]: property[1] for property in property_pairs} builder_md = _Factory.call_builder(gui, control_type, properties) if builder_md is None: return f"<|INVALID SYNTAX - Control is '{control_type}'|>" return builder_md
from .parser import _TaipyHTMLParser
import typing as t from ..factory import _Factory class _HtmlFactory(_Factory): @staticmethod def create_element(gui, namespace: str, control_type: str, all_properties: t.Dict[str, str]) -> t.Tuple[str, str]: builder_html = _Factory.call_builder(gui, f"{namespace}.{control_type}", all_properties, True) if builder_html is None: return f"<div>INVALID SYNTAX - Control is '{namespace}:{control_type}'</div>", "div" return builder_html # type: ignore
import re import typing as t from html.parser import HTMLParser from ..._warnings import _warn from .factory import _HtmlFactory class _TaipyHTMLParser(HTMLParser): __TAIPY_NAMESPACE_RE = re.compile(r"([a-zA-Z\_]+):([a-zA-Z\_]*)") def __init__(self, gui): super().__init__() self._gui = gui self.body = "" self.head = [] self.taipy_tag = None self.tag_mapping = {} self.is_body = True self.head_tag = None self._line_count = 0 self._tag_queue = [] # @override def handle_starttag(self, tag, props) -> None: self._tag_queue.append((tag, self._line_count)) if tag == "html": return if self.head_tag is not None: self.head.append(self.head_tag) self.head_tag = None if self.taipy_tag is not None: self.parse_taipy_tag() if tag == "head": self.is_body = False elif tag == "body": self.is_body = True elif m := self.__TAIPY_NAMESPACE_RE.match(tag): self.taipy_tag = _TaipyTag(m.group(1), m.group(2), props) elif not self.is_body: head_props = {prop[0]: prop[1] for prop in props} self.head_tag = {"tag": tag, "props": head_props, "content": ""} else: self.append_data(str(self.get_starttag_text())) # @override def handle_data(self, data: str) -> None: data = data.strip() if data and self.taipy_tag is not None and self.taipy_tag.set_value(data): self.parse_taipy_tag() elif not self.is_body and self.head_tag is not None: self.head_tag["content"] = data else: self.append_data(data) # @override def handle_endtag(self, tag) -> None: if not self._tag_queue: _warn(f"Closing '{tag}' at line {self._line_count} is missing an opening tag.") else: opening_tag, opening_tag_line = self._tag_queue.pop() if opening_tag != tag: _warn( f"Opening tag '{opening_tag}' at line {opening_tag_line} has no matching closing tag '{tag}' at line {self._line_count}." # noqa: E501 ) if tag in ["head", "body", "html"]: return if self.taipy_tag is not None: self.parse_taipy_tag() if not self.is_body: self.head.append(self.head_tag) self.head_tag = None elif tag in self.tag_mapping: self.append_data(f"</{self.tag_mapping[tag]}>") else: self.append_data(f"</{tag}>") def append_data(self, data: str) -> None: if self.is_body: self.body += data def parse_taipy_tag(self) -> None: tp_string, tp_element_name = self.taipy_tag.parse(self._gui) self.append_data(tp_string) self.tag_mapping[f"{self.taipy_tag.namespace}:{self.taipy_tag.control_type}"] = tp_element_name self.taipy_tag = None def get_jsx(self) -> str: return self.body def feed_data(self, data: str): data_lines = data.split("\n") for line, data_line in enumerate(data_lines): self._line_count = line + 1 self.feed(data_line) while self._tag_queue: opening_tag, opening_tag_line = self._tag_queue.pop() _warn(f"Opening tag '{opening_tag}' at line {opening_tag_line} has no matching closing tag.") class _TaipyTag(object): def __init__(self, namespace: str, tag_name: str, properties: t.List[t.Tuple[str, str]]) -> None: self.namespace = namespace self.control_type = tag_name self.properties = {prop[0]: prop[1] for prop in properties} self.has_set_value = False def set_value(self, value: str) -> bool: if self.has_set_value: return False property_name = _HtmlFactory.get_default_property_name(f"{self.namespace}.{self.control_type}") # Set property only if it is not already defined if property_name and property_name not in self.properties.keys(): self.properties[property_name] = value self.has_set_value = True return True def parse(self, gui) -> t.Tuple[str, str]: for k, v in self.properties.items(): self.properties[k] = v if v is not None else "true" # allow usage of 'class' property in html taipy tag if "class" in self.properties and "class_name" not in self.properties: self.properties["class_name"] = self.properties["class"] return _HtmlFactory.create_element(gui, self.namespace, self.control_type, self.properties)
"""The setup script.""" import json import os from setuptools import find_namespace_packages, find_packages, setup with open("README.md", "rb") as readme_file: readme = readme_file.read().decode("UTF-8") with open(f"src{os.sep}taipy{os.sep}templates{os.sep}version.json") as version_file: version = json.load(version_file) version_string = f'{version.get("major", 0)}.{version.get("minor", 0)}.{version.get("patch", 0)}' if vext := version.get("ext"): version_string = f"{version_string}.{vext}" test_requirements = ["pytest>=3.8"] setup( author="Avaiga", author_email="dev@taipy.io", python_requires=">=3.8", classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Natural Language :: English", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", ], description="An open-source package holding Taipy application templates.", license="Apache License 2.0", long_description=readme, long_description_content_type="text/markdown", keywords="taipy-templates", name="taipy-templates", package_dir={"": "src"}, packages=find_namespace_packages(where="src") + find_packages(include=["taipy"]), include_package_data=True, test_suite="tests", url="https://github.com/avaiga/taipy-templates", version=version_string, zip_safe=False, )
from config.config import configure from pages import job_page, scenario_page from pages.root import content, root, selected_data_node, selected_scenario import taipy as tp from taipy import Core, Gui def on_init(state): ... def on_change(state, var, val): if var == "selected_data_node" and val: state["scenario"].manage_data_node_partial(state) pages = { "/": root, "scenario": scenario_page, "jobs": job_page, } if __name__ == "__main__": # Instantiate, configure and run the Core core = Core() default_scenario_cfg = configure() core.run() # ################################################################################################################## # PLACEHOLDER: Initialize your data application here # # # # Example: # if len(tp.get_scenarios()) == 0: tp.create_scenario(default_scenario_cfg, name="Default Scenario") # Comment, remove or replace the previous lines with your own use case # # ################################################################################################################## # Instantiate, configure and run the GUI gui = Gui(pages=pages) data_node_partial = gui.add_partial("") gui.run(title="{{cookiecutter.__application_title}}", margin="0em")
from algos import clean_data from taipy import Config, Frequency, Scope def configure(): # ################################################################################################################## # PLACEHOLDER: Add your scenario configurations here # # # # Example: # initial_dataset_cfg = Config.configure_csv_data_node("initial_dataset", scope=Scope.CYCLE) replacement_type_cfg = Config.configure_data_node("replacement_type", default_data="NO VALUE") cleaned_dataset_cfg = Config.configure_csv_data_node("cleaned_dataset") clean_data_cfg = Config.configure_task( "clean_data", function=clean_data, input=[initial_dataset_cfg, replacement_type_cfg], output=cleaned_dataset_cfg, ) scenario_cfg = Config.configure_scenario( "scenario_configuration", task_configs=[clean_data_cfg], frequency=Frequency.DAILY ) return scenario_cfg # Comment, remove or replace the previous lines with your own use case # # ##################################################################################################################
from taipy import Config def configure(): Config.load("config/config.toml") return Config.scenarios["scenario_configuration"]
def clean_data(df, replacement_type): df = df.fillna(replacement_type) return df
from .algos import clean_data
from .job_page import job_page from .scenario_page import scenario_page
from taipy.gui import Markdown selected_scenario = None selected_data_node = None content = "" root = Markdown("pages/root.md")
from .job_page import job_page
from taipy.gui import Markdown job_page = Markdown("pages/job_page/job_page.md")
from taipy.gui import Markdown, notify from .data_node_management import manage_partial def notify_on_submission(state, submitable, details): if details["submission_status"] == "COMPLETED": notify(state, "success", "Submision completed!") elif details["submission_status"] == "FAILED": notify(state, "error", "Submission failed!") else: notify(state, "info", "In progress...") def manage_data_node_partial(state): manage_partial(state) scenario_page = Markdown("pages/scenario_page/scenario_page.md")
from .scenario_page import scenario_page
# build partial content for a specific data node def build_dn_partial(dn, dn_label): partial_content = "<|part|render={selected_scenario}|\n\n" # ################################################################################################################## # PLACEHOLDER: data node specific content before automatic content # # # # Example: # if dn_label == "replacement_type": partial_content += "All missing values will be replaced by the data node value." # Comment, remove or replace the previous lines with your own use case # # ################################################################################################################## # Automatic data node content partial_content += ( "<|{selected_scenario.data_nodes['" + dn.config_id + "']}|data_node|scenario={" "selected_scenario}|>\n\n " ) # ################################################################################################################## # PLACEHOLDER: data node specific content after automatic content # # # # Example: # if dn_label == "initial_dataset": partial_content += ( "Select your CSV file: <|{selected_data_node.path}|file_selector|extensions=.csv|on_action" "={lambda s: s.refresh('selected_scenario')}|>\n\n " ) # Comment, remove or replace the previous lines with your own use case # # ################################################################################################################## partial_content += "|>\n\n" return partial_content def manage_partial(state): dn = state.selected_data_node dn_label = dn.get_simple_label() partial_content = build_dn_partial(dn, dn_label) state.data_node_partial.update_content(state, partial_content)
import os import taipy # Add taipy version to requirements.txt with open(os.path.join(os.getcwd(), "requirements.txt"), "a") as requirement_file: requirement_file.write(f"taipy=={taipy.version._get_version()}\n") # Use TOML config file or not use_toml_config = "{{ cookiecutter.__use_toml_config }}".upper() if use_toml_config == "YES" or use_toml_config == "Y": os.remove(os.path.join(os.getcwd(), "config", "config.py")) os.rename( os.path.join(os.getcwd(), "config", "config_with_toml.py"), os.path.join(os.getcwd(), "config", "config.py") ) else: os.remove(os.path.join(os.getcwd(), "config", "config_with_toml.py")) os.remove(os.path.join(os.getcwd(), "config", "config.toml")) main_file_name = "{{cookiecutter.__main_file}}.py" print( f"New Taipy application has been created at {os.path.join(os.getcwd())}" f"\n\nTo start the application, change directory to the newly created folder:" f"\n\tcd {os.path.join(os.getcwd())}" f"\nand run the application as follows:" f"\n\ttaipy run {main_file_name}" )
# # 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 subprocess import sys def _run_template(main_path, time_out=30): """Run the templates on a subprocess and get stdout after timeout""" with subprocess.Popen([sys.executable, main_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc: try: stdout, stderr = proc.communicate(timeout=time_out) except subprocess.TimeoutExpired: proc.kill() stdout, stderr = proc.communicate() # Print the error if there is any (for debugging) if stderr := str(stderr, "utf-8"): print(stderr) return stdout
import os from cookiecutter.main import cookiecutter from .utils import _run_template def test_scenario_management_with_toml_config(tmpdir): cookiecutter( template="src/taipy/templates/scenario-management", output_dir=tmpdir, no_input=True, extra_context={ "Application root folder name": "foo_app", "Application main Python file": "main.py", "Application title": "bar", "Does the application use TOML Config?": "yes", }, ) assert os.listdir(tmpdir) == ["foo_app"] assert ( os.listdir(os.path.join(tmpdir, "foo_app")).sort() == ["requirements.txt", "main.py", "algos", "config", "pages"].sort() ) # Assert post_gen_project hook is successful with open(os.path.join(tmpdir, "foo_app", "requirements.txt")) as requirements_file: assert "taipy==" in requirements_file.read() assert ( os.listdir(os.path.join(tmpdir, "foo_app", "config")).sort() == ["__init__.py", "config.py", "config.toml"].sort() ) with open(os.path.join(tmpdir, "foo_app", "config", "config.py")) as config_file: assert 'Config.load("config/config.toml")' in config_file.read() oldpwd = os.getcwd() os.chdir(os.path.join(tmpdir, "foo_app")) stdout = _run_template("main.py") os.chdir(oldpwd) # Assert the message when the application is run successfully is in the stdout assert "[Taipy][INFO] Configuration 'config/config.toml' successfully loaded." in str(stdout, "utf-8") assert "[Taipy][INFO] * Server starting on" in str(stdout, "utf-8") def test_scenario_management_without_toml_config(tmpdir): cookiecutter( template="src/taipy/templates/scenario-management", output_dir=tmpdir, no_input=True, extra_context={ "Application root folder name": "foo_app", "Application main Python file": "main.py", "Application title": "bar", "Does the application use TOML Config?": "no", }, ) assert os.listdir(tmpdir) == ["foo_app"] assert ( os.listdir(os.path.join(tmpdir, "foo_app")).sort() == ["requirements.txt", "main.py", "algos", "config", "pages"].sort() ) # Assert post_gen_project hook is successful with open(os.path.join(tmpdir, "foo_app", "requirements.txt")) as requirements_file: assert "taipy==" in requirements_file.read() assert os.listdir(os.path.join(tmpdir, "foo_app", "config")).sort() == ["__init__.py", "config.py"].sort() with open(os.path.join(tmpdir, "foo_app", "config", "config.py")) as config_file: config_content = config_file.read() assert 'Config.load("config/config.toml")' not in config_content assert all([x in config_content for x in ["Config.configure_csv_data_node", "Config.configure_task"]]) oldpwd = os.getcwd() os.chdir(os.path.join(tmpdir, "foo_app")) stdout = _run_template("main.py") os.chdir(oldpwd) # Assert the message when the application is run successfully is in the stdout assert "[Taipy][INFO] * Server starting on" in str(stdout, "utf-8")
""" Contain the application's configuration including the scenario configurations. The configuration is run by the Core service. """ from algorithms import * from taipy import Config # ############################################################################# # PLACEHOLDER: Put your application's configurations here # # # # Example: # # scenario_config = Config.configure_scenario("placeholder_scenario", []) # # Comment, remove or replace the previous lines with your own use case # # #############################################################################