text
stringlengths
0
105k
import inspect import re import types from abc import abstractmethod from datetime import datetime, timedelta from typing import Any, Dict, Optional from .._config import _Config from ..common._template_handler import _TemplateHandler from ..common._validate_id import _validate_id from ..common.frequency import Frequency from ..common.scope import Scope from ..exceptions.exceptions import LoadingError from ..global_app.global_app_config import GlobalAppConfig from ..section import Section from ..unique_section import UniqueSection class _BaseSerializer(object): """Base serializer class for taipy configuration.""" _GLOBAL_NODE_NAME = "TAIPY" _section_class = {_GLOBAL_NODE_NAME: GlobalAppConfig} @classmethod @abstractmethod def _write(cls, configuration: _Config, filename: str): raise NotImplementedError @classmethod def _str(cls, configuration: _Config): config_as_dict = {cls._GLOBAL_NODE_NAME: configuration._global_config._to_dict()} for u_sect_name, u_sect in configuration._unique_sections.items(): config_as_dict[u_sect_name] = u_sect._to_dict() for sect_name, sections in configuration._sections.items(): config_as_dict[sect_name] = cls._to_dict(sections) return cls._stringify(config_as_dict) @classmethod def _to_dict(cls, sections: Dict[str, Any]): return {section_id: section._to_dict() for section_id, section in sections.items()} @classmethod def _stringify(cls, as_dict): if as_dict is None: return None if isinstance(as_dict, Section): return as_dict.id + ":SECTION" if isinstance(as_dict, Scope): return as_dict.name + ":SCOPE" if isinstance(as_dict, Frequency): return as_dict.name + ":FREQUENCY" if isinstance(as_dict, bool): return str(as_dict) + ":bool" if isinstance(as_dict, int): return str(as_dict) + ":int" if isinstance(as_dict, float): return str(as_dict) + ":float" if isinstance(as_dict, datetime): return as_dict.isoformat() + ":datetime" if isinstance(as_dict, timedelta): return cls._timedelta_to_str(as_dict) + ":timedelta" if inspect.isfunction(as_dict) or isinstance(as_dict, types.BuiltinFunctionType): return as_dict.__module__ + "." + as_dict.__name__ + ":function" if inspect.isclass(as_dict): return as_dict.__module__ + "." + as_dict.__qualname__ + ":class" if isinstance(as_dict, dict): return {str(key): cls._stringify(val) for key, val in as_dict.items()} if isinstance(as_dict, list): return [cls._stringify(val) for val in as_dict] if isinstance(as_dict, tuple): return [cls._stringify(val) for val in as_dict] return as_dict @staticmethod def _extract_node(config_as_dict, cls_config, node, config: Optional[Any]) -> Dict[str, Section]: res = {} for key, value in config_as_dict.get(node, {}).items(): # my_task, {input=[], output=[my_data_node], ...} key = _validate_id(key) res[key] = cls_config._from_dict(value, key, config) # if config is None else cls_config._from_dict(key, # value, config) return res @classmethod def _from_dict(cls, as_dict) -> _Config: config = _Config() config._global_config = GlobalAppConfig._from_dict(as_dict.get(cls._GLOBAL_NODE_NAME, {})) for section_name, sect_as_dict in as_dict.items(): if section_class := cls._section_class.get(section_name, None): if issubclass(section_class, UniqueSection): config._unique_sections[section_name] = section_class._from_dict( sect_as_dict, None, None ) # type: ignore elif issubclass(section_class, Section): config._sections[section_name] = cls._extract_node(as_dict, section_class, section_name, config) return config @classmethod def _pythonify(cls, val): match = re.fullmatch(_TemplateHandler._PATTERN, str(val)) if not match: if isinstance(val, str): TYPE_PATTERN = ( r"^(.+):(\bbool\b|\bstr\b|\bint\b|\bfloat\b|\bdatetime\b||\btimedelta\b|" r"\bfunction\b|\bclass\b|\bSCOPE\b|\bFREQUENCY\b|\bSECTION\b)?$" ) match = re.fullmatch(TYPE_PATTERN, str(val)) if match: actual_val = match.group(1) dynamic_type = match.group(2) if dynamic_type == "SECTION": return actual_val if dynamic_type == "FREQUENCY": return Frequency[actual_val] if dynamic_type == "SCOPE": return Scope[actual_val] if dynamic_type == "bool": return _TemplateHandler._to_bool(actual_val) elif dynamic_type == "int": return _TemplateHandler._to_int(actual_val) elif dynamic_type == "float": return _TemplateHandler._to_float(actual_val) elif dynamic_type == "datetime": return _TemplateHandler._to_datetime(actual_val) elif dynamic_type == "timedelta": return _TemplateHandler._to_timedelta(actual_val) elif dynamic_type == "function": return _TemplateHandler._to_function(actual_val) elif dynamic_type == "class": return _TemplateHandler._to_class(actual_val) elif dynamic_type == "str": return actual_val else: error_msg = f"Error loading toml configuration at {val}. {dynamic_type} type is not supported." raise LoadingError(error_msg) if isinstance(val, dict): return {str(k): cls._pythonify(v) for k, v in val.items()} if isinstance(val, list): return [cls._pythonify(v) for v in val] return val @classmethod def _timedelta_to_str(cls, obj: timedelta) -> str: total_seconds = obj.total_seconds() return ( f"{int(total_seconds // 86400)}d" f"{int(total_seconds % 86400 // 3600)}h" f"{int(total_seconds % 3600 // 60)}m" f"{int(total_seconds % 60)}s" )
import json # type: ignore from .._config import _Config from ..exceptions.exceptions import LoadingError from ._base_serializer import _BaseSerializer class _JsonSerializer(_BaseSerializer): """Convert configuration from JSON representation to Python Dict and reciprocally.""" @classmethod def _write(cls, configuration: _Config, filename: str): with open(filename, "w") as fd: json.dump(cls._str(configuration), fd, ensure_ascii=False, indent=0, check_circular=False) @classmethod def _read(cls, filename: str) -> _Config: try: with open(filename) as f: config_as_dict = cls._pythonify(json.load(f)) return cls._from_dict(config_as_dict) except json.JSONDecodeError as e: error_msg = f"Can not load configuration {e}" raise LoadingError(error_msg) @classmethod def _serialize(cls, configuration: _Config) -> str: return json.dumps(cls._str(configuration), ensure_ascii=False, indent=0, check_circular=False) @classmethod def _deserialize(cls, config_as_string: str) -> _Config: return cls._from_dict(cls._pythonify(dict(json.loads(config_as_string))))
# # 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 typing import Any, List from .issue import Issue class IssueCollector: """ A collection of issues (instances of class `Issue^`). Attributes: errors (List[Issue^]): List of ERROR issues collected. warnings (List[Issue^]): List WARNING issues collected. infos (List[Issue^]): List INFO issues collected. all (List[Issue^]): List of all issues collected ordered by decreasing level (ERROR, WARNING and INFO). """ _ERROR_LEVEL = "ERROR" _WARNING_LEVEL = "WARNING" _INFO_LEVEL = "INFO" def __init__(self): self._errors: List[Issue] = [] self._warnings: List[Issue] = [] self._infos: List[Issue] = [] @property def all(self) -> List[Issue]: return self._errors + self._warnings + self._infos @property def infos(self) -> List[Issue]: return self._infos @property def warnings(self) -> List[Issue]: return self._warnings @property def errors(self) -> List[Issue]: return self._errors def _add_error(self, field: str, value: Any, message: str, checker_name: str): self._errors.append(Issue(self._ERROR_LEVEL, field, value, message, checker_name)) def _add_warning(self, field: str, value: Any, message: str, checker_name: str): self._warnings.append(Issue(self._WARNING_LEVEL, field, value, message, checker_name)) def _add_info(self, field: str, value: Any, message: str, checker_name: str): self._infos.append(Issue(self._INFO_LEVEL, field, value, message, checker_name))
from dataclasses import dataclass from typing import Any, Optional @dataclass class Issue: """ An issue detected in the configuration. Attributes: level (str): Level of the issue among ERROR, WARNING, INFO. field (str): Configuration field on which the issue has been detected. value (Any): Value of the field on which the issue has been detected. message (str): Human readable message to help the user fix the issue. tag (Optional[str]): Optional tag to be used to filter issues. """ level: str field: str value: Any message: str tag: Optional[str] def __str__(self) -> str: message = self.message if self.value: current_value_str = f'"{self.value}"' if isinstance(self.value, str) else f"{self.value}" message += f" Current value of property `{self.field}` is {current_value_str}." return message
from typing import List from ._checkers._config_checker import _ConfigChecker from .issue_collector import IssueCollector class _Checker: """Holds the various checkers to perform on the config.""" _checkers: List[_ConfigChecker] = [] @classmethod def _check(cls, _applied_config): collector = IssueCollector() for checker in cls._checkers: checker(_applied_config, collector)._check() return collector @classmethod def add_checker(cls, checker_class: _ConfigChecker): cls._checkers.append(checker_class)
import abc from typing import Any, List, Optional, Set from ..._config import _Config from ..issue_collector import IssueCollector class _ConfigChecker: _PREDEFINED_PROPERTIES_KEYS = ["_entity_owner"] def __init__(self, config: _Config, collector): self._collector = collector self._config = config @abc.abstractmethod def _check(self) -> IssueCollector: raise NotImplementedError def _error(self, field: str, value: Any, message: str): self._collector._add_error(field, value, message, self.__class__.__name__) def _warning(self, field: str, value: Any, message: str): self._collector._add_warning(field, value, message, self.__class__.__name__) def _info(self, field: str, value: Any, message: str): self._collector._add_info(field, value, message, self.__class__.__name__) def _check_children( self, parent_config_class, config_id: str, config_key: str, config_value, child_config_class, can_be_empty: Optional[bool] = False, ): if not config_value and not can_be_empty: self._warning( config_key, config_value, f"{config_key} field of {parent_config_class.__name__} `{config_id}` is empty.", ) else: if not ( (isinstance(config_value, List) or isinstance(config_value, Set)) and all(map(lambda x: isinstance(x, child_config_class), config_value)) ): self._error( config_key, config_value, f"{config_key} field of {parent_config_class.__name__} `{config_id}` must be populated with a list " f"of {child_config_class.__name__} objects.", ) def _check_existing_config_id(self, config): if not config.id: self._error( "config_id", config.id, f"config_id of {config.__class__.__name__} `{config.id}` is empty.", ) def _check_if_entity_property_key_used_is_predefined(self, config): for key, value in config._properties.items(): if key in self._PREDEFINED_PROPERTIES_KEYS: self._error( key, value, f"Properties of {config.__class__.__name__} `{config.id}` cannot have `{key}` as its property.", )
from ..._config import _Config from ..issue_collector import IssueCollector from ._config_checker import _ConfigChecker class _AuthConfigChecker(_ConfigChecker): def __init__(self, config: _Config, collector: IssueCollector): super().__init__(config, collector) def _check(self) -> IssueCollector: auth_config = self._config._auth_config # type: ignore self._check_predefined_protocol(auth_config) return self._collector def _check_predefined_protocol(self, auth_config): if auth_config.protocol == auth_config._PROTOCOL_LDAP: self.__check_ldap(auth_config) if auth_config.protocol == auth_config._PROTOCOL_TAIPY: self.__check_taipy(auth_config) def __check_taipy(self, auth_config): if auth_config._TAIPY_ROLES not in auth_config.properties: self._error( "properties", auth_config._LDAP_SERVER, f"`{auth_config._LDAP_SERVER}` property must be populated when {auth_config._PROTOCOL_LDAP} is used.", ) if auth_config._TAIPY_PWD not in auth_config.properties: self._warning( "properties", auth_config._TAIPY_PWD, f"`In order to protect authentication with passwords using {auth_config._PROTOCOL_TAIPY} protocol," f" {auth_config._TAIPY_PWD}` property can be populated.", ) def __check_ldap(self, auth_config): if auth_config._LDAP_SERVER not in auth_config.properties: self._error( "properties", auth_config._LDAP_SERVER, f"`{auth_config._LDAP_SERVER}` attribute must be populated when {auth_config._PROTOCOL_LDAP} is used.", ) if auth_config._LDAP_BASE_DN not in auth_config.properties: self._error( "properties", auth_config._LDAP_BASE_DN, f"`{auth_config._LDAP_BASE_DN}` field must be populated when {auth_config._PROTOCOL_LDAP} is used.", )
# # 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.
# 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 .exceptions import *
class LoadingError(Exception): """Raised if an error occurs while loading the configuration file.""" class InconsistentEnvVariableError(Exception): """Inconsistency value has been detected in an environment variable referenced by the configuration.""" class MissingEnvVariableError(Exception): """Environment variable referenced in configuration is missing.""" class InvalidConfigurationId(Exception): """Configuration id is not valid.""" class ConfigurationUpdateBlocked(Exception): """The configuration is being blocked from update by other Taipy services."""
from ..common._repr_enum import _ReprEnum class Frequency(_ReprEnum): """Frequency of the recurrence of `Cycle^` and `Scenario^` objects. The frequency must be provided in the `ScenarioConfig^`. Each recurrent scenario is attached to the cycle corresponding to the creation date and the frequency. In other words, each cycle represents an iteration and contains the various scenarios created during this iteration. For instance, when scenarios have a _MONTHLY_ frequency, one cycle will be created for each month (January, February, March, etc.). A new scenario created on February 10th, gets attached to the _February_ cycle. The frequency is implemented as an enumeration with the following possible values: - With a _DAILY_ frequency, a new cycle is created for each day. - With a _WEEKLY_ frequency, a new cycle is created for each week (from Monday to Sunday). - With a _MONTHLY_ frequency, a new cycle is created for each month. - With a _QUARTERLY_ frequency, a new cycle is created for each quarter. - With a _YEARLY_ frequency, a new cycle is created for each year. """ DAILY = 1 WEEKLY = 2 MONTHLY = 3 QUARTERLY = 4 YEARLY = 5
class _Classproperty(object): def __init__(self, f): self.f = f def __get__(self, obj, owner): return self.f(owner)
# # 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 functools from enum import Enum class _ReprEnum(Enum): @classmethod @functools.lru_cache def _from_repr(cls, repr_: str): return next(filter(lambda e: repr(e) == repr_, cls)) # type: ignore
import keyword from ..exceptions.exceptions import InvalidConfigurationId __INVALID_TAIPY_ID_TERMS = ["CYCLE", "SCENARIO", "SEQUENCE", "TASK", "DATANODE"] def _validate_id(name: str): for invalid_taipy_id_term in __INVALID_TAIPY_ID_TERMS: if invalid_taipy_id_term in name: raise InvalidConfigurationId(f"{name} is not a valid identifier. {invalid_taipy_id_term} is restricted.") if name.isidentifier() and not keyword.iskeyword(name): return name raise InvalidConfigurationId(f"{name} is not a valid identifier.")
import functools from ...logger._taipy_logger import _TaipyLogger from ..exceptions.exceptions import ConfigurationUpdateBlocked class _ConfigBlocker: """Configuration blocker singleton.""" __logger = _TaipyLogger._get_logger() __block_config_update = False @classmethod def _block(cls): cls.__block_config_update = True @classmethod def _unblock(cls): cls.__block_config_update = False @classmethod def _check(cls): def inner(f): @functools.wraps(f) def _check_if_is_blocking(*args, **kwargs): if cls.__block_config_update: error_message = ( "The Core service should be stopped by running core.stop() before" " modifying the Configuration. For more information, please refer to:" " https://docs.taipy.io/en/latest/manuals/running_services/#running-core." ) cls.__logger.error("ConfigurationUpdateBlocked: " + error_message) raise ConfigurationUpdateBlocked(error_message) return f(*args, **kwargs) return _check_if_is_blocking return inner
from ..common._repr_enum import _ReprEnum class _OrderedEnum(_ReprEnum): def __ge__(self, other): if self.__class__ is other.__class__: return self.value >= other.value return NotImplemented def __gt__(self, other): if self.__class__ is other.__class__: return self.value > other.value return NotImplemented def __le__(self, other): if self.__class__ is other.__class__: return self.value <= other.value return NotImplemented def __lt__(self, other): if self.__class__ is other.__class__: return self.value < other.value return NotImplemented class Scope(_OrderedEnum): """Scope of a `DataNode^`. This enumeration can have the following values: - `GLOBAL` - `CYCLE` - `SCENARIO` """ GLOBAL = 3 CYCLE = 2 SCENARIO = 1
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)
import re from typing import Dict, List, Set from .._serializer._json_serializer import _JsonSerializer class _ComparatorResult(dict): ADDED_ITEMS_KEY = "added_items" REMOVED_ITEMS_KEY = "removed_items" MODIFIED_ITEMS_KEY = "modified_items" CONFLICTED_SECTION_KEY = "conflicted_sections" UNCONFLICTED_SECTION_KEY = "unconflicted_sections" def __init__(self, unconflicted_sections: Set[str]): super().__init__() self._unconflicted_sections = unconflicted_sections def _sort_by_section(self): if self.get(self.CONFLICTED_SECTION_KEY): for key in self[self.CONFLICTED_SECTION_KEY].keys(): self[self.CONFLICTED_SECTION_KEY][key].sort(key=lambda x: x[0][0]) if self.get(self.UNCONFLICTED_SECTION_KEY): for key in self[self.UNCONFLICTED_SECTION_KEY].keys(): self[self.UNCONFLICTED_SECTION_KEY][key].sort(key=lambda x: x[0][0]) def _check_added_items(self, config_deepdiff, new_json_config): if dictionary_item_added := config_deepdiff.get("dictionary_item_added"): for item_added in dictionary_item_added: section_name, config_id, attribute = self.__get_changed_entity_attribute(item_added) diff_sections = self.__get_section(section_name) if attribute: value_added = new_json_config[section_name][config_id][attribute] elif config_id: value_added = new_json_config[section_name][config_id] else: value_added = new_json_config[section_name] section_name = self.__rename_global_node_name(section_name) self.__create_or_append_list( diff_sections, self.ADDED_ITEMS_KEY, ((section_name, config_id, attribute), (value_added)), ) def _check_removed_items(self, config_deepdiff, old_json_config): if dictionary_item_removed := config_deepdiff.get("dictionary_item_removed"): for item_removed in dictionary_item_removed: section_name, config_id, attribute = self.__get_changed_entity_attribute(item_removed) diff_sections = self.__get_section(section_name) if attribute: value_removed = old_json_config[section_name][config_id][attribute] elif config_id: value_removed = old_json_config[section_name][config_id] else: value_removed = old_json_config[section_name] section_name = self.__rename_global_node_name(section_name) self.__create_or_append_list( diff_sections, self.REMOVED_ITEMS_KEY, ((section_name, config_id, attribute), (value_removed)), ) def _check_modified_items(self, config_deepdiff, old_json_config, new_json_config): if values_changed := config_deepdiff.get("values_changed"): for item_changed, value_changed in values_changed.items(): section_name, config_id, attribute = self.__get_changed_entity_attribute(item_changed) diff_sections = self.__get_section(section_name) section_name = self.__rename_global_node_name(section_name) self.__create_or_append_list( diff_sections, self.MODIFIED_ITEMS_KEY, ((section_name, config_id, attribute), (value_changed["old_value"], value_changed["new_value"])), ) # Iterable item added will be considered a modified item if iterable_item_added := config_deepdiff.get("iterable_item_added"): self.__check_modified_iterable(iterable_item_added, old_json_config, new_json_config) # Iterable item removed will be considered a modified item if iterable_item_removed := config_deepdiff.get("iterable_item_removed"): self.__check_modified_iterable(iterable_item_removed, old_json_config, new_json_config) def __check_modified_iterable(self, iterable_items, old_json_config, new_json_config): for item in iterable_items: section_name, config_id, attribute = self.__get_changed_entity_attribute(item) diff_sections = self.__get_section(section_name) if attribute: new_value = new_json_config[section_name][config_id][attribute] old_value = old_json_config[section_name][config_id][attribute] else: new_value = new_json_config[section_name][config_id] old_value = old_json_config[section_name][config_id] section_name = self.__rename_global_node_name(section_name) modified_value = ((section_name, config_id, attribute), (old_value, new_value)) if ( not diff_sections.get(self.MODIFIED_ITEMS_KEY) or modified_value not in diff_sections[self.MODIFIED_ITEMS_KEY] ): self.__create_or_append_list( diff_sections, self.MODIFIED_ITEMS_KEY, modified_value, ) def __get_section(self, section_name: str) -> Dict[str, List]: if section_name in self._unconflicted_sections: if not self.get(self.UNCONFLICTED_SECTION_KEY): self[self.UNCONFLICTED_SECTION_KEY] = {} return self[self.UNCONFLICTED_SECTION_KEY] if not self.get(self.CONFLICTED_SECTION_KEY): self[self.CONFLICTED_SECTION_KEY] = {} return self[self.CONFLICTED_SECTION_KEY] def __create_or_append_list(self, diff_dict, key, value): if diff_dict.get(key): diff_dict[key].append(value) else: diff_dict[key] = [value] def __get_changed_entity_attribute(self, attribute_bracket_notation): """Split the section name, the config id (if exists), and the attribute name (if exists) from JSON bracket notation. """ try: section_name, config_id, attribute = re.findall(r"\[\'(.*?)\'\]", attribute_bracket_notation) except ValueError: try: section_name, config_id = re.findall(r"\[\'(.*?)\'\]", attribute_bracket_notation) attribute = None except ValueError: section_name = re.findall(r"\[\'(.*?)\'\]", attribute_bracket_notation)[0] config_id = None attribute = None return section_name, config_id, attribute def __rename_global_node_name(self, node_name): if node_name == _JsonSerializer._GLOBAL_NODE_NAME: return "Global Configuration" return node_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 json from copy import copy from typing import Optional, Set, Union from deepdiff import DeepDiff from ...logger._taipy_logger import _TaipyLogger from .._config import _Config from .._serializer._json_serializer import _JsonSerializer from ._comparator_result import _ComparatorResult class _ConfigComparator: def __init__(self): self._unconflicted_sections: Set[str] = set() self.__logger = _TaipyLogger._get_logger() def _add_unconflicted_section(self, section_name: Union[str, Set[str]]): if isinstance(section_name, str): section_name = {section_name} self._unconflicted_sections.update(section_name) def _find_conflict_config( self, old_config: _Config, new_config: _Config, old_version_number: Optional[str] = None, new_version_number: Optional[str] = None, ): """Compare between 2 _Config object to check for compatibility. Args: old_config (_Config): The old _Config. new_config (_Config): The new _Config. old_version_number (str, optional): The old version number for logging. Defaults to None. new_version_number (str, optional): The new version number for logging. Defaults to None. Returns: _ComparatorResult: Return a _ComparatorResult dictionary with the following format: ```python { "added_items": [ ((section_name_1, config_id_1, attribute_1), added_object_1), ((section_name_2, config_id_2, attribute_2), added_object_2), ], "removed_items": [ ((section_name_1, config_id_1, attribute_1), removed_object_1), ((section_name_2, config_id_2, attribute_2), removed_object_2), ], "modified_items": [ ((section_name_1, config_id_1, attribute_1), (old_value_1, new_value_1)), ((section_name_2, config_id_2, attribute_2), (old_value_2, new_value_2)), ], } ``` """ comparator_result = self.__get_config_diff(old_config, new_config) self.__log_find_conflict_message(comparator_result, old_version_number, new_version_number) return comparator_result def _compare( self, config_1: _Config, config_2: _Config, version_number_1: str, version_number_2: str, ): """Compare between 2 _Config object to check for compatibility. Args: config_1 (_Config): The old _Config. config_2 (_Config): The new _Config. version_number_1 (str): The old version number for logging. version_number_2 (str): The new version number for logging. """ comparator_result = self.__get_config_diff(config_1, config_2) self.__log_comparison_message(comparator_result, version_number_1, version_number_2) return comparator_result def __get_config_diff(self, config_1, config_2): json_config_1 = json.loads(_JsonSerializer._serialize(config_1)) json_config_2 = json.loads(_JsonSerializer._serialize(config_2)) config_deepdiff = DeepDiff(json_config_1, json_config_2, ignore_order=True) comparator_result = _ComparatorResult(copy(self._unconflicted_sections)) comparator_result._check_added_items(config_deepdiff, json_config_2) comparator_result._check_removed_items(config_deepdiff, json_config_1) comparator_result._check_modified_items(config_deepdiff, json_config_1, json_config_2) comparator_result._sort_by_section() return comparator_result def __log_comparison_message( self, comparator_result: _ComparatorResult, version_number_1: str, version_number_2: str, ): config_str_1 = f"version {version_number_1} Configuration" config_str_2 = f"version {version_number_2} Configuration" diff_messages = [] for _, sections in comparator_result.items(): diff_messages = self.__get_messages(sections) if diff_messages: self.__logger.info( f"Differences between {config_str_1} and {config_str_2}:\n\t" + "\n\t".join(diff_messages) ) else: self.__logger.info(f"There is no difference between {config_str_1} and {config_str_2}.") def __log_find_conflict_message( self, comparator_result: _ComparatorResult, old_version_number: Optional[str] = None, new_version_number: Optional[str] = None, ): old_config_str = ( f"configuration for version {old_version_number}" if old_version_number else "current configuration" ) new_config_str = ( f"configuration for version {new_version_number}" if new_version_number else "current configuration" ) if unconflicted_sections := comparator_result.get(_ComparatorResult.UNCONFLICTED_SECTION_KEY): unconflicted_messages = self.__get_messages(unconflicted_sections) self.__logger.info( f"There are non-conflicting changes between the {old_config_str}" f" and the {new_config_str}:\n\t" + "\n\t".join(unconflicted_messages) ) if conflicted_sections := comparator_result.get(_ComparatorResult.CONFLICTED_SECTION_KEY): conflicted_messages = self.__get_messages(conflicted_sections) self.__logger.error( f"The {old_config_str} conflicts with the {new_config_str}:\n\t" + "\n\t".join(conflicted_messages) ) def __get_messages(self, diff_sections): dq = '"' messages = [] if added_items := diff_sections.get(_ComparatorResult.ADDED_ITEMS_KEY): for diff in added_items: ((section_name, config_id, attribute), added_object) = diff messages.append( f"{section_name} {dq}{config_id}{dq} " f"{f'has attribute {dq}{attribute}{dq}' if attribute else 'was'} added: {added_object}" ) if removed_items := diff_sections.get(_ComparatorResult.REMOVED_ITEMS_KEY): for diff in removed_items: ((section_name, config_id, attribute), removed_object) = diff messages.append( f"{section_name} {dq}{config_id}{dq} " f"{f'has attribute {dq}{attribute}{dq}' if attribute else 'was'} removed" ) if modified_items := diff_sections.get(_ComparatorResult.MODIFIED_ITEMS_KEY): for diff in modified_items: ((section_name, config_id, attribute), (old_value, new_value)) = diff messages.append( f"{section_name} {dq}{config_id}{dq} " f"{f'has attribute {dq}{attribute}{dq}' if attribute else 'was'} modified: " f"{old_value} -> {new_value}" ) return messages
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 __future__ import annotations import contextlib import logging import os import pathlib import re import sys import time import typing as t import webbrowser from importlib import util from random import randint import __main__ from flask import Blueprint, Flask, json, jsonify, render_template, send_from_directory from flask_cors import CORS from flask_socketio import SocketIO from gitignore_parser import parse_gitignore from kthread import KThread from taipy.logger._taipy_logger import _TaipyLogger from werkzeug.serving import is_running_from_reloader from ._renderers.json import _TaipyJsonProvider from .config import ServerConfig from .utils import _is_in_notebook, _is_port_open, _RuntimeManager if t.TYPE_CHECKING: from .gui import Gui class _Server: __RE_OPENING_CURLY = re.compile(r"([^\"])(\{)") __RE_CLOSING_CURLY = re.compile(r"(\})([^\"])") __OPENING_CURLY = r"\1&#x7B;" __CLOSING_CURLY = r"&#x7D;\2" def __init__( self, gui: Gui, flask: t.Optional[Flask] = None, path_mapping: t.Optional[dict] = None, async_mode: t.Optional[str] = None, allow_upgrades: bool = True, server_config: t.Optional[ServerConfig] = None, ): self._gui = gui server_config = server_config or {} self._flask = flask if self._flask is None: flask_config: t.Dict[str, t.Any] = {"import_name": "Taipy"} if "flask" in server_config and isinstance(server_config["flask"], dict): flask_config.update(server_config["flask"]) self._flask = Flask(**flask_config) if "SECRET_KEY" not in self._flask.config or not self._flask.config["SECRET_KEY"]: self._flask.config["SECRET_KEY"] = "TaIpY" # setup cors if "cors" not in server_config or ( "cors" in server_config and (isinstance(server_config["cors"], dict) or server_config["cors"] is True) ): cors_config = ( server_config["cors"] if "cors" in server_config and isinstance(server_config["cors"], dict) else {} ) CORS(self._flask, **cors_config) # setup socketio socketio_config: t.Dict[str, t.Any] = { "cors_allowed_origins": "*", "ping_timeout": 10, "ping_interval": 5, "json": json, "async_mode": async_mode, "allow_upgrades": allow_upgrades, } if "socketio" in server_config and isinstance(server_config["socketio"], dict): socketio_config.update(server_config["socketio"]) self._ws = SocketIO(self._flask, **socketio_config) self._apply_patch() # set json encoder (for Taipy specific types) self._flask.json_provider_class = _TaipyJsonProvider self._flask.json = self._flask.json_provider_class(self._flask) # type: ignore self.__path_mapping = path_mapping or {} self.__ssl_context = server_config.get("ssl_context", None) self._is_running = False # Websocket (handle json message) # adding args for the one call with a server ack request @self._ws.on("message") def handle_message(message, *args) -> None: if "status" in message: _TaipyLogger._get_logger().info(message["status"]) elif "type" in message: gui._manage_message(message["type"], message) def __is_ignored(self, file_path: str) -> bool: if not hasattr(self, "_ignore_matches"): __IGNORE_FILE = ".taipyignore" ignore_file = ( (pathlib.Path(__main__.__file__).parent / __IGNORE_FILE) if hasattr(__main__, "__file__") else None ) if not ignore_file or not ignore_file.is_file(): ignore_file = pathlib.Path(self._gui._root_dir) / __IGNORE_FILE self._ignore_matches = ( parse_gitignore(ignore_file) if ignore_file.is_file() and os.access(ignore_file, os.R_OK) else None ) if callable(self._ignore_matches): return self._ignore_matches(file_path) return False def _get_default_blueprint( self, static_folder: str, template_folder: str, title: str, favicon: str, root_margin: str, scripts: t.List[str], styles: t.List[str], version: str, client_config: t.Dict[str, t.Any], watermark: t.Optional[str], css_vars: str, base_url: str, ) -> Blueprint: taipy_bp = Blueprint("Taipy", __name__, static_folder=static_folder, template_folder=template_folder) # Serve static react build @taipy_bp.route("/", defaults={"path": ""}) @taipy_bp.route("/<path:path>") def my_index(path): if path == "" or path == "index.html" or "." not in path: try: return render_template( "index.html", title=title, favicon=favicon, root_margin=root_margin, watermark=watermark, config=client_config, scripts=scripts, styles=styles, version=version, css_vars=css_vars, base_url=base_url, ) except Exception: # pragma: no cover raise RuntimeError( "Something is wrong with the taipy-gui front-end installation. Check that the js bundle has been properly built (is Node.js installed?)." # noqa: E501 ) if path == "taipy.status.json": return self._direct_render_json(self._gui._serve_status(pathlib.Path(template_folder) / path)) if str(os.path.normpath(file_path := ((base_path := static_folder + os.path.sep) + path))).startswith( base_path ) and os.path.isfile(file_path): return send_from_directory(base_path, path) # use the path mapping to detect and find resources for k, v in self.__path_mapping.items(): if ( path.startswith(f"{k}/") and str( os.path.normpath(file_path := ((base_path := v + os.path.sep) + path[len(k) + 1 :])) ).startswith(base_path) and os.path.isfile(file_path) ): return send_from_directory(base_path, path[len(k) + 1 :]) if ( hasattr(__main__, "__file__") and str( os.path.normpath( file_path := ((base_path := os.path.dirname(__main__.__file__) + os.path.sep) + path) ) ).startswith(base_path) and os.path.isfile(file_path) and not self.__is_ignored(file_path) ): return send_from_directory(base_path, path) if ( str(os.path.normpath(file_path := (base_path := self._gui._root_dir + os.path.sep) + path)).startswith( base_path ) and os.path.isfile(file_path) and not self.__is_ignored(file_path) ): return send_from_directory(base_path, path) return ("", 404) return taipy_bp # Update to render as JSX def _render(self, html_fragment, style, head, context): template_str = _Server.__RE_OPENING_CURLY.sub(_Server.__OPENING_CURLY, html_fragment) template_str = _Server.__RE_CLOSING_CURLY.sub(_Server.__CLOSING_CURLY, template_str) template_str = template_str.replace('"{!', "{") template_str = template_str.replace('!}"', "}") return self._direct_render_json( { "jsx": template_str, "style": (style + os.linesep) if style else "", "head": head or [], "context": context or self._gui._get_default_module_name(), } ) def _direct_render_json(self, data): return jsonify(data) def get_flask(self): return self._flask def test_client(self): return self._flask.test_client() def _run_notebook(self): self._is_running = True self._ws.run(self._flask, host=self._host, port=self._port, debug=False, use_reloader=False) def _get_async_mode(self) -> str: return self._ws.async_mode def _apply_patch(self): if self._get_async_mode() == "gevent" and util.find_spec("gevent"): from gevent import monkey if not monkey.is_module_patched("time"): monkey.patch_time() if self._get_async_mode() == "eventlet" and util.find_spec("eventlet"): from eventlet import monkey_patch, patcher if not patcher.is_monkey_patched("time"): monkey_patch(time=True) def _get_random_port(self): # pragma: no cover while True: port = randint(49152, 65535) if port not in _RuntimeManager().get_used_port() and not _is_port_open(self._host, port): return port def run(self, host, port, debug, use_reloader, flask_log, run_in_thread, allow_unsafe_werkzeug, notebook_proxy): host_value = host if host != "0.0.0.0" else "localhost" self._host = host self._port = port if _is_in_notebook() and notebook_proxy: # pragma: no cover from .utils.proxy import NotebookProxy # Start proxy if not already started self._proxy = NotebookProxy(gui=self._gui, listening_port=port) self._proxy.run() self._port = self._get_random_port() if _is_in_notebook() or run_in_thread: runtime_manager = _RuntimeManager() runtime_manager.add_gui(self._gui, port) if debug and not is_running_from_reloader() and _is_port_open(host_value, port): raise ConnectionError( f"Port {port} is already opened on {host_value}. You have another server application running on the same port." # noqa: E501 ) if not flask_log: log = logging.getLogger("werkzeug") log.disabled = True if not is_running_from_reloader(): _TaipyLogger._get_logger().info(f" * Server starting on http://{host_value}:{port}") else: _TaipyLogger._get_logger().info(f" * Server reloaded on http://{host_value}:{port}") if not is_running_from_reloader() and self._gui._get_config("run_browser", False): webbrowser.open(f"http://{host_value}{f':{port}' if port else ''}", new=2) if _is_in_notebook() or run_in_thread: self._thread = KThread(target=self._run_notebook) self._thread.start() return self._is_running = True run_config = { "app": self._flask, "host": host, "port": port, "debug": debug, "use_reloader": use_reloader, } if self.__ssl_context is not None: run_config["ssl_context"] = self.__ssl_context # flask-socketio specific conditions for 'allow_unsafe_werkzeug' parameters to be popped out of kwargs if self._get_async_mode() == "threading" and (not sys.stdin or not sys.stdin.isatty()): run_config = {**run_config, "allow_unsafe_werkzeug": allow_unsafe_werkzeug} self._ws.run(**run_config) def stop_thread(self): if hasattr(self, "_thread") and self._thread.is_alive() and self._is_running: self._is_running = False with contextlib.suppress(Exception): if self._get_async_mode() == "gevent": if self._ws.wsgi_server is not None: self._ws.wsgi_server.stop() else: self._thread.kill() else: self._thread.kill() while _is_port_open(self._host, self._port): time.sleep(0.1) def stop_proxy(self): if hasattr(self, "_proxy"): self._proxy.stop()
import os import re import typing as t from importlib.util import find_spec import pytz import tzlocal from dotenv import dotenv_values from taipy.logger._taipy_logger import _TaipyLogger from werkzeug.serving import is_running_from_reloader from ._gui_cli import _GuiCLI from ._page import _Page from ._warnings import _warn from .partial import Partial from .utils import _is_in_notebook ConfigParameter = t.Literal[ "allow_unsafe_werkzeug", "async_mode", "change_delay", "chart_dark_template", "base_url", "dark_mode", "dark_theme", "data_url_max_size", "debug", "extended_status", "favicon", "flask_log", "host", "light_theme", "margin", "ngrok_token", "notebook_proxy", "notification_duration", "propagate", "run_browser", "run_in_thread", "run_server", "server_config", "single_client", "system_notification", "theme", "time_zone", "title", "stylekit", "upload_folder", "use_arrow", "use_reloader", "watermark", "webapp_path", "port", ] Stylekit = t.TypedDict( "Stylekit", { "color_primary": str, "color_secondary": str, "color_error": str, "color_warning": str, "color_success": str, "color_background_light": str, "color_paper_light": str, "color_background_dark": str, "color_paper_dark": str, "font_family": str, "root_margin": str, "border_radius": int, "input_button_height": str, }, total=False, ) ServerConfig = t.TypedDict( "ServerConfig", { "cors": t.Optional[t.Union[bool, t.Dict[str, t.Any]]], "socketio": t.Optional[t.Dict[str, t.Any]], "ssl_context": t.Optional[t.Union[str, t.Tuple[str, str]]], "flask": t.Optional[t.Dict[str, t.Any]], }, total=False, ) Config = t.TypedDict( "Config", { "allow_unsafe_werkzeug": bool, "async_mode": str, "change_delay": t.Optional[int], "chart_dark_template": t.Optional[t.Dict[str, t.Any]], "base_url": t.Optional[str], "dark_mode": bool, "dark_theme": t.Optional[t.Dict[str, t.Any]], "data_url_max_size": t.Optional[int], "debug": bool, "extended_status": bool, "favicon": t.Optional[str], "flask_log": bool, "host": str, "light_theme": t.Optional[t.Dict[str, t.Any]], "margin": t.Optional[str], "ngrok_token": str, "notebook_proxy": bool, "notification_duration": int, "propagate": bool, "run_browser": bool, "run_in_thread": bool, "run_server": bool, "server_config": t.Optional[ServerConfig], "single_client": bool, "system_notification": bool, "theme": t.Optional[t.Dict[str, t.Any]], "time_zone": t.Optional[str], "title": t.Optional[str], "stylekit": t.Union[bool, Stylekit], "upload_folder": t.Optional[str], "use_arrow": bool, "use_reloader": bool, "watermark": t.Optional[str], "webapp_path": t.Optional[str], "port": int, }, total=False, ) class _Config(object): __RE_PORT_NUMBER = re.compile( r"^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$" ) def __init__(self): self.pages: t.List[_Page] = [] self.root_page: t.Optional[_Page] = None self.routes: t.List[str] = [] self.partials: t.List[Partial] = [] self.partial_routes: t.List[str] = [] self.config: Config = {} def _load(self, config: Config) -> None: self.config.update(config) # Check that the user timezone configuration setting is valid self.get_time_zone() def _get_config(self, name: ConfigParameter, default_value: t.Any) -> t.Any: # pragma: no cover if name in self.config and self.config[name] is not None: if default_value is not None and not isinstance(self.config[name], type(default_value)): try: return type(default_value)(self.config[name]) except Exception as e: _warn(f'app_config "{name}" value "{self.config[name]}" is not of type {type(default_value)}', e) return default_value return self.config[name] return default_value def get_time_zone(self) -> t.Optional[str]: tz = self.config.get("time_zone") if tz is None or tz == "client": return tz if tz == "server": # return python tzlocal IANA Time Zone return str(tzlocal.get_localzone()) # Verify user defined IANA Time Zone is valid if tz not in pytz.all_timezones_set: raise Exception( "Time Zone configuration is not valid. Mistyped 'server', 'client' options or invalid IANA Time Zone" ) # return user defined IANA Time Zone (https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) return tz def _handle_argparse(self): _GuiCLI.create_parser() args = _GuiCLI.parse_arguments() config = self.config if args.taipy_port: if not _Config.__RE_PORT_NUMBER.match(args.taipy_port): _warn("Port value for --port option is not valid.") else: config["port"] = int(args.taipy_port) if args.taipy_host: config["host"] = args.taipy_host if args.taipy_debug: config["debug"] = True if args.taipy_no_debug: config["debug"] = False if args.taipy_use_reloader: config["use_reloader"] = True if args.taipy_no_reloader: config["use_reloader"] = False if args.taipy_ngrok_token: config["ngrok_token"] = args.taipy_ngrok_token if args.taipy_webapp_path: config["webapp_path"] = args.taipy_webapp_path elif os.environ.get("TAIPY_GUI_WEBAPP_PATH"): config["webapp_path"] = os.environ.get("TAIPY_GUI_WEBAPP_PATH") def _build_config(self, root_dir, env_filename, kwargs): # pragma: no cover config = self.config env_file_abs_path = env_filename if os.path.isabs(env_filename) else os.path.join(root_dir, env_filename) # Load keyword arguments for key, value in kwargs.items(): key = key.lower() if value is not None and key in config: # Special case for "stylekit" that can be a Boolean or a dict if key == "stylekit" and isinstance(value, bool): from ._default_config import _default_stylekit config[key] = _default_stylekit if value else {} continue try: if isinstance(value, dict) and isinstance(config[key], dict): config[key].update(value) else: config[key] = value if config[key] is None else type(config[key])(value) # type: ignore except Exception as e: _warn( f"Invalid keyword arguments value in Gui.run {key} - {value}. Unable to parse value to the correct type", # noqa: E501 e, ) # Load config from env file if os.path.isfile(env_file_abs_path): for key, value in dotenv_values(env_file_abs_path).items(): key = key.lower() if value is not None and key in config: try: config[key] = value if config[key] is None else type(config[key])(value) # type: ignore except Exception as e: _warn( f"Invalid env value in Gui.run(): {key} - {value}. Unable to parse value to the correct type", # noqa: E501 e, ) # Taipy-config if find_spec("taipy") and find_spec("taipy.config"): from taipy.config import Config as TaipyConfig try: section = TaipyConfig.unique_sections["gui"] self.config.update(section._to_dict()) except KeyError: _warn("taipy-config section for taipy-gui is not initialized.") # Load from system arguments self._handle_argparse() def __log_outside_reloader(self, logger, msg): if not is_running_from_reloader(): logger.info(msg) def resolve(self): app_config = self.config logger = _TaipyLogger._get_logger() # Special config for notebook runtime if _is_in_notebook() or app_config["run_in_thread"] and not app_config["single_client"]: app_config["single_client"] = True self.__log_outside_reloader(logger, "Running in 'single_client' mode in notebook environment") if app_config["run_server"] and app_config["ngrok_token"] and app_config["use_reloader"]: app_config["use_reloader"] = False self.__log_outside_reloader( logger, "'use_reloader' parameter will not be used when 'ngrok_token' parameter is available" ) if app_config["use_reloader"] and _is_in_notebook(): app_config["use_reloader"] = False self.__log_outside_reloader(logger, "'use_reloader' parameter is not available in notebook environment") if app_config["use_reloader"] and not app_config["debug"]: app_config["debug"] = True self.__log_outside_reloader(logger, "application is running in 'debug' mode") if app_config["debug"] and not app_config["allow_unsafe_werkzeug"]: app_config["allow_unsafe_werkzeug"] = True self.__log_outside_reloader(logger, "'allow_unsafe_werkzeug' has been set to True") if app_config["debug"] and app_config["async_mode"] != "threading": app_config["async_mode"] = "threading" self.__log_outside_reloader( logger, "'async_mode' parameter has been overridden to 'threading'. Using Flask built-in development server with debug mode", # noqa: E501 ) self._resolve_notebook_proxy() self._resolve_stylekit() self._resolve_url_prefix() def _resolve_stylekit(self): app_config = self.config # support legacy margin variable stylekit_config = app_config["stylekit"] if isinstance(app_config["stylekit"], dict) and "root_margin" in app_config["stylekit"]: from ._default_config import _default_stylekit, default_config stylekit_config = app_config["stylekit"] if ( stylekit_config["root_margin"] == _default_stylekit["root_margin"] and app_config["margin"] != default_config["margin"] ): app_config["stylekit"]["root_margin"] = str(app_config["margin"]) app_config["margin"] = None def _resolve_url_prefix(self): app_config = self.config base_url = app_config.get("base_url") if base_url is None: app_config["base_url"] = "/" else: base_url = f"{'' if base_url.startswith('/') else '/'}{base_url}" base_url = f"{base_url}{'' if base_url.endswith('/') else '/'}" app_config["base_url"] = base_url def _resolve_notebook_proxy(self): app_config = self.config app_config["notebook_proxy"] = app_config["notebook_proxy"] if _is_in_notebook() else False
from .gui import Gui
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 threading import typing as t from ._warnings import _warn from .gui import Gui from .state import State def download( state: State, content: t.Any, name: t.Optional[str] = "", on_action: t.Optional[t.Union[str, t.Callable]] = "" ): """Download content to the client. Arguments: state (State^): The current user state as received in any callback. content: File path or file content. See below. name: File name for the content on the client browser (defaults to content name). on_action: Callback function (or callback name) to call when the download ends. See below. ## Notes: - *content*: this parameter can hold several values depending on your use case: - a string: the value must be an existing path name to the file that gets downloaded or the URL to the resource you want to download. - a buffer (such as a `bytes` object): if the size of the buffer is smaller than the [*data_url_max_size*](../gui/configuration.md#p-data_url_max_size) configuration setting, then the [`python-magic`](https://pypi.org/project/python-magic/) package is used to determine the [MIME type](https://en.wikipedia.org/wiki/Media_type) of the buffer content, and the download is performed using a generated "data:" URL with the relevant type, and a base64-encoded version of the buffer content.<br/> If the buffer is too large, its content is transferred after saving it in a temporary server file. - *on_action*: this callback is triggered when the transfer of the content is achieved.</br> In this function, you can perform any clean-up operation that could be required after the download is completed.<br/> This callback can use three optional parameters: - *state*: the `State^` instance of the caller. - *id* (optional): a string representing the identifier of the caller. If this function is called directly, this will always be "Gui.download". Some controls may also trigger download actions, and then *id* would reflect the identifier of those controls. - *payload* (optional): an optional payload from the caller.<br/> This is a dictionary with the following keys: - *action*: the name of the callback; - *args*: an array of two strings. The first element reflects the *name* parameter, and the second element reflects the server-side URL where the file is located. """ if state and isinstance(state._gui, Gui): state._gui._download(content, name, on_action) else: _warn("'download()' must be called in the context of a callback.") def notify( state: State, notification_type: str = "I", message: str = "", system_notification: t.Optional[bool] = None, duration: t.Optional[int] = None, ): """Send a notification to the user interface. Arguments: state (State^): The current user state as received in any callback. notification_type: The notification type. This can be one of "success", "info", "warning", or "error".<br/> To remove the last notification, set this parameter to the empty string. message: The text message to display. system_notification: If True, the system will also show the notification.<br/> If not specified or set to None, this parameter will use the value of *configuration[system_notification]*. duration: The time, in milliseconds, during which the notification is shown. If not specified or set to None, this parameter will use the value of *configuration[notification_duration]*. Note that you can also call this function with *notification_type* set to the first letter or the alert type (i.e. setting *notification_type* to "i" is equivalent to setting it to "info"). If *system_notification* is set to True, then the browser requests the system to display a notification as well. They usually appear in small windows that fly out of the system tray.<br/> The first time your browser is requested to show such a system notification for Taipy applications, you may be prompted to authorize the browser to do so. Please refer to your browser documentation for details on how to allow or prevent this feature. """ if state and isinstance(state._gui, Gui): state._gui._notify(notification_type, message, system_notification, duration) else: _warn("'notify()' must be called in the context of a callback.") def hold_control( state: State, callback: t.Optional[t.Union[str, t.Callable]] = None, message: t.Optional[str] = "Work in Progress...", ): """Hold the User Interface actions. When the User Interface is held, users cannot interact with visual elements.<br/> The application must call `resume_control()^` so that users can interact again with the visual elements. You can set a callback function (or the name of a function) in the *callback* parameter. Then, a "Cancel" button will be displayed so the user can cancel whatever is happening in the application. When pressed, the callback is invoked. Arguments: state (State^): The current user state received in any callback. callback (Optional[Union[str, Callable]]): The function to be called if the user chooses to cancel.<br/> If empty or None, no cancel action is provided to the user.<br/> The signature of this function is: - state (State^): The user state; - id (str): the id of the button that triggered the callback. That will always be "UIBlocker" since it is created and managed internally; message: The message to show. The default value is the string "Work in Progress...". """ if state and isinstance(state._gui, Gui): state._gui._hold_actions(callback, message) else: _warn("'hold_actions()' must be called in the context of a callback.") def resume_control(state: State): """Resume the User Interface actions. This function must be called after `hold_control()^` was invoked, when interaction must be allowed again for the user. Arguments: state (State^): The current user state as received in any callback. """ if state and isinstance(state._gui, Gui): state._gui._resume_actions() else: _warn("'resume_actions()' must be called in the context of a callback.") def navigate( state: State, to: t.Optional[str] = "", params: t.Optional[t.Dict[str, str]] = None, tab: t.Optional[str] = None, force: t.Optional[bool] = False, ): """Navigate to a page. Arguments: state (State^): The current user state as received in any callback. to: The name of the page to navigate to. This can be a page identifier (as created by `Gui.add_page()^` with no leading '/') or an URL.<br/> If omitted, the application navigates to the root page. params: A dictionary of query parameters. tab: When navigating to a page that is not a known page, the page is opened in a tab identified by *tab* (as in [window.open](https://developer.mozilla.org/en-US/docs/Web/API/Window/open)).<br/> The default value creates a new tab for the page (which is equivalent to setting *tab* to "_blank"). force: When navigating to a known page, the content is refreshed even it the page is already shown. """ if state and isinstance(state._gui, Gui): state._gui._navigate(to, params, tab, force) else: _warn("'navigate()' must be called in the context of a callback.") def get_user_content_url( state: State, path: t.Optional[str] = None, params: t.Optional[t.Dict[str, str]] = None ) -> t.Optional[str]: """Get a user content URL. This function can be used if you need to deliver dynamic content to your page: you can create a path at run-time that, when queried, will deliver some user-defined content defined in the *on_user_content* callback (see the description of the `Gui^` class for more information). Arguments: state (State^): The current user state as received in any callback. path: An optional additional path to the URL. params: An optional dictionary sent to the *on_user_content* callback.<br/> These arguments are added as query parameters to the generated URL and converted into strings. Returns: An URL that, when queried, triggers the *on_user_content* callback. """ if state and isinstance(state._gui, Gui): return state._gui._get_user_content_url(path, params) _warn("'get_user_content_url()' must be called in the context of a callback.") return None def get_state_id(state: State) -> t.Optional[str]: """Get the identifier of a state. The state identifier is a string generated by Taipy GUI for a given `State^` that is used to serialize callbacks. See the [User Manual section on Long Running Callbacks](../gui/callbacks.md#long-running-callbacks) for details on when and how this function can be used. Arguments: state (State^): The current user state as received in any callback. Returns: A string that uniquely identifies the state.<br/> If None, then **state** was not handled by a `Gui^` instance. """ if state and isinstance(state._gui, Gui): return state._gui._get_client_id() return None def get_module_context(state: State) -> t.Optional[str]: """Get the name of the module currently in used when using page scopes Arguments: state (State^): The current user state as received in any callback. Returns: The name of the current module """ if state and isinstance(state._gui, Gui): return state._gui._get_locals_context() return None def get_context_id(state: State) -> t.Any: _warn("'get_context_id()' was deprecated in Taipy GUI 2.0. Use 'get_state_id()' instead.") return get_state_id(state) def get_module_name_from_state(state: State) -> t.Optional[str]: """Get the module name that triggered a callback. Pages can be defined in different modules yet refer to callback functions declared elsewhere (typically, the application's main module). This function returns the name of the module where the page that holds the control that triggered the callback was declared. This lets applications implement different behaviors depending on what page is involved. This function must be called only in the body of a callback function. Arguments: state (State^): The `State^` instance, as received in any callback. Returns: The name of the module that holds the definition of the page containing the control that triggered the callback that was provided the *state* object. """ if state and isinstance(state._gui, Gui): return state._gui._get_locals_context() return None def invoke_callback( gui: Gui, state_id: str, callback: t.Callable, args: t.Union[t.Tuple, t.List], module_context: t.Optional[str] = None, ) -> t.Any: """Invoke a user callback for a given state. See the [User Manual section on Long Running Callbacks in a Thread](../gui/callbacks.md#long-running-callbacks-in-a-thread) for details on when and how this function can be used. Arguments: gui (Gui^): The current Gui instance. state_id: The identifier of the state to use, as returned by `get_state_id()^`. callback (Callable[[State^, ...], None]): The user-defined function that is invoked.<br/> The first parameter of this function **must** be a `State^`. args (Union[Tuple, List]): The remaining arguments, as a List or a Tuple. module_context (Optional[str]): the name of the module that will be used. """ if isinstance(gui, Gui): return gui._call_user_callback(state_id, callback, list(args), module_context) _warn("'invoke_callback()' must be called with a valid Gui instance.") def broadcast_callback( gui: Gui, callback: t.Callable, args: t.Optional[t.Union[t.Tuple, t.List]] = None, module_context: t.Optional[str] = None, ) -> t.Any: """Invoke a callback for every client. This callback gets invoked for every client connected to the application with the appropriate `State^` instance. You can then perform client-specific tasks, such as updating the state variable reflected in the user interface. Arguments: gui (Gui^): The current Gui instance. callback: The user-defined function to be invoked.<br/> The first parameter of this function must be a `State^` object representing the client for which it is invoked.<br/> The other parameters should reflect the ones provided in the *args* collection. args: The parameters to send to *callback*, if any. """ if isinstance(gui, Gui): return gui._call_broadcast_callback(callback, list(args) if args else [], module_context) _warn("'broadcast_callback()' must be called with a valid Gui instance.") def invoke_state_callback(gui: Gui, state_id: str, callback: t.Callable, args: t.Union[t.Tuple, t.List]) -> t.Any: _warn("'invoke_state_callback()' was deprecated in Taipy GUI 2.0. Use 'invoke_callback()' instead.") return invoke_callback(gui, state_id, callback, args) def invoke_long_callback( state: State, user_function: t.Callable, user_function_args: t.Union[t.Tuple, t.List] = [], user_status_function: t.Optional[t.Callable] = None, user_status_function_args: t.Union[t.Tuple, t.List] = [], period=0, ): """Invoke a long running user callback. Long-running callbacks are run in a separate thread to not block the application itself. This function expects to be provided a function to run in the background (in *user_function*).<br/> It can also be specified a *status function* that is called when the operation performed by *user_function* is finished (successfully or not), or periodically (using the *period* parameter). See the [User Manual section on Long Running Callbacks](../gui/callbacks.md#long-running-callbacks) for details on when and how this function can be used. Arguments: state (State^): The `State^` instance, as received in any callback. user_function (Callable[[...], None]): The function that will be run independently of Taipy GUI. Note that this function must not use *state*, which is not persisted across threads. user_function_args (Optional[List|Tuple]): The arguments to send to *user_function*. user_status_function (Optional(Callable[[State^, bool, ...], None])): The optional user-defined status function that is invoked at the end of and possibly during the runtime of *user_function*: - The first parameter of this function is set to a `State^` instance. - The second parameter of this function is set to a bool or an int, depending on the conditions under which it is called: - If this parameter is set to a bool value, then: - If True, this indicates that *user_function* has finished properly. The last argument passed will be the result of the user_function call. - If False, this indicates that *user_function* failed. - If this parameter is set to an int value, then this value indicates how many periods (as lengthy as indicated in *period*) have elapsed since *user_function* was started. user_status_function_args (Optional[List|Tuple]): The remaining arguments of the user status function. period (int): The interval, in milliseconds, at which *user_status_function* is called.<br/> The default value is 0, meaning no call to *user_status_function* will happen until *user_function* terminates (then the second parameter of that call will be ).</br> When set to a value smaller than 500, *user_status_function* is called only when *user_function* terminates (as if *period* was set to 0). """ if not state or not isinstance(state._gui, Gui): _warn("'invoke_long_callback()' must be called in the context of a callback.") return state_id = get_state_id(state) module_context = get_module_context(state) if not isinstance(state_id, str) or not isinstance(module_context, str): return this_gui = state._gui def callback_on_exception(state: State, function_name: str, e: Exception): if not this_gui._call_on_exception(function_name, e): _warn(f"invoke_long_callback(): Exception raised in function {function_name}()", e) def callback_on_status( status: t.Union[int, bool], e: t.Optional[Exception] = None, function_name: t.Optional[str] = None, function_result: t.Optional[t.Any] = None, ): if callable(user_status_function): invoke_callback( this_gui, str(state_id), user_status_function, [status] + list(user_status_function_args) + [function_result], # type: ignore str(module_context), ) if e: invoke_callback( this_gui, str(state_id), callback_on_exception, ( str(function_name), e, ), str(module_context), ) def user_function_in_thread(*uf_args): try: res = user_function(*uf_args) callback_on_status(True, function_result=res) except Exception as e: callback_on_status(False, e, user_function.__name__) def thread_status(name: str, period_s: float, count: int): active_thread = next((t for t in threading.enumerate() if t.name == name), None) if active_thread: callback_on_status(count) threading.Timer(period_s, thread_status, (name, period_s, count + 1)).start() thread = threading.Thread(target=user_function_in_thread, args=user_function_args) thread.start() if isinstance(period, int) and period >= 500 and callable(user_status_function): thread_status(thread.name, period / 1000.0, 0)
import typing as t from copy import copy from taipy.config import Config as TaipyConfig from taipy.config import UniqueSection from ._default_config import default_config class _GuiSection(UniqueSection): name = "gui" def __init__(self, property_list: t.Optional[t.List] = None, **properties): self._property_list = property_list super().__init__(**properties) def __copy__(self): return _GuiSection(property_list=copy(self._property_list), **copy(self._properties)) def _clean(self): self._properties.clear() def _to_dict(self): as_dict = {} as_dict.update(self._properties) return as_dict @classmethod def _from_dict(cls, as_dict: t.Dict[str, t.Any], *_): return _GuiSection(property_list=list(default_config), **as_dict) def _update(self, as_dict: t.Dict[str, t.Any]): if self._property_list: as_dict = {k: v for k, v in as_dict.items() if k in self._property_list} self._properties.update(as_dict) @staticmethod def _configure(**properties) -> "_GuiSection": """NOT DOCUMENTED Configure the Graphical User Interface. Parameters: **properties (dict[str, any]): Keyword arguments that configure the behavior of the `Gui^` instances.<br/> Please refer to the [Configuration section](../gui/configuration.md#configuring-the-gui-instance) of the User Manual for more information on the accepted arguments. Returns: The GUI configuration. """ section = _GuiSection(property_list=list(default_config), **properties) TaipyConfig._register(section) return TaipyConfig.unique_sections[_GuiSection.name]
# _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 __future__ import annotations import contextlib import importlib import inspect import json import os import pathlib import re import sys import tempfile import time import typing as t import warnings from importlib import metadata, util from importlib.util import find_spec from types import FrameType, SimpleNamespace from urllib.parse import unquote, urlencode, urlparse import __main__ import markdown as md_lib import tzlocal from flask import Blueprint, Flask, g, jsonify, request, send_file, send_from_directory from taipy.logger._taipy_logger import _TaipyLogger from werkzeug.utils import secure_filename if util.find_spec("pyngrok"): from pyngrok import ngrok from ._default_config import _default_stylekit, default_config from ._page import _Page from ._renderers import _EmptyPage from ._renderers._markdown import _TaipyMarkdownExtension from ._renderers.factory import _Factory from ._renderers.json import _TaipyJsonEncoder from ._renderers.utils import _get_columns_dict from ._warnings import TaipyGuiWarning, _warn from .builder import _ElementApiGenerator from .config import Config, ConfigParameter, _Config from .data.content_accessor import _ContentAccessor from .data.data_accessor import _DataAccessor, _DataAccessors from .data.data_format import _DataFormat from .data.data_scope import _DataScopes from .extension.library import Element, ElementLibrary from .gui_types import _WsType from .page import Page from .partial import Partial from .server import _Server from .state import State from .utils import ( _delscopeattr, _filter_locals, _get_broadcast_var_name, _get_client_var_name, _get_css_var_value, _get_expr_var_name, _get_module_name_from_frame, _get_non_existent_file_path, _get_page_from_module, _getscopeattr, _getscopeattr_drill, _hasscopeattr, _is_in_notebook, _LocalsContext, _MapDict, _setscopeattr, _setscopeattr_drill, _TaipyBase, _TaipyContent, _TaipyContentHtml, _TaipyContentImage, _TaipyData, _TaipyLov, _TaipyLovValue, _to_camel_case, _variable_decode, is_debugging, ) from .utils._adapter import _Adapter from .utils._bindings import _Bindings from .utils._evaluator import _Evaluator from .utils._variable_directory import _MODULE_ID, _VariableDirectory from .utils.chart_config_builder import _build_chart_config from .utils.table_col_builder import _enhance_columns class _DoNotUpdate: def __repr__(self): return "Taipy: Do not update" class Gui: """Entry point for the Graphical User Interface generation. Attributes: on_action (Callable): The function that is called when a control triggers an action, as the result of an interaction with the end-user.<br/> It defaults to the `on_action()` global function defined in the Python application. If there is no such function, actions will not trigger anything.<br/> The signature of the *on_action* callback function must be: - *state*: the `State^` instance of the caller. - *id* (optional): a string representing the identifier of the caller. - *payload* (optional): an optional payload from the caller. on_change (Callable): The function that is called when a control modifies variables it is bound to, as the result of an interaction with the end-user.<br/> It defaults to the `on_change()` global function defined in the Python application. If there is no such function, user interactions will not trigger anything.<br/> The signature of the *on_change* callback function must be: - *state*: the `State^` instance of the caller. - *var_name* (str): The name of the variable that triggered this callback. - *var_value* (any): The new value for this variable. on_init (Callable): The function that is called on the first connection of a new client.<br/> It defaults to the `on_init()` global function defined in the Python application. If there is no such function, the first connection will not trigger anything.<br/> The signature of the *on_init* callback function must be: - *state*: the `State^` instance of the caller. on_navigate (Callable): The function that is called when a page is requested.<br/> It defaults to the `on_navigate()` global function defined in the Python application. If there is no such function, page requests will not trigger anything.<br/> The signature of the *on_navigate* callback function must be: - *state*: the `State^` instance of the caller. - *page_name*: the name of the page the user is navigating to. - *params* (Optional): the query parameters provided in the URL. The *on_navigate* callback function must return the name of the page the user should be directed to. on_exception (Callable): The function that is called an exception occurs on user code.<br/> It defaults to the `on_exception()` global function defined in the Python application. If there is no such function, exceptions will not trigger anything.<br/> The signature of the *on_exception* callback function must be: - *state*: the `State^` instance of the caller. - *function_name*: the name of the function that raised the exception. - *exception*: the exception object that was raised. on_status (Callable): The function that is called when the status page is shown.<br/> It defaults to the `on_status()` global function defined in the Python application. If there is no such function, status page content shows only the status of the server.<br/> The signature of the *on_status* callback function must be: - *state*: the `State^` instance of the caller. It must return raw and valid HTML content as a string. on_user_content (Callable): The function that is called when a specific URL (generated by `get_user_content_url()^`) is requested.<br/> This callback function must return the raw HTML content of the page to be displayed on the browser. This attribute defaults to the `on_user_content()` global function defined in the Python application. If there is no such function, those specific URLs will not trigger anything.<br/> The signature of the *on_user_content* callback function must be: - *state*: the `State^` instance of the caller. - *path*: the path provided to the `get_user_content_url()^` to build the URL. - *parameters*: An optional dictionary as defined in the `get_user_content_url()^` call. The returned HTML content can therefore use both the variables stored in the *state* and the parameters provided in the call to `get_user_content_url()^`. state (State^): **Only defined when running in an IPython notebook context.**<br/> The unique instance of `State^` that you can use to change bound variables directly, potentially impacting the user interface in real-time. !!! note This class belongs to and is documented in the `taipy.gui` package but it is accessible from the top `taipy` package to simplify its access, allowing to use: ```py from taipy import Gui ``` """ __root_page_name = "TaiPy_root_page" __env_filename = "taipy.gui.env" __UI_BLOCK_NAME = "TaipyUiBlockVar" __MESSAGE_GROUPING_NAME = "TaipyMessageGrouping" __ON_INIT_NAME = "TaipyOnInit" __ARG_CLIENT_ID = "client_id" __INIT_URL = "taipy-init" __JSX_URL = "taipy-jsx" __CONTENT_ROOT = "taipy-content" __UPLOAD_URL = "taipy-uploads" _EXTENSION_ROOT = "taipy-extension" __USER_CONTENT_URL = "taipy-user-content" __BROADCAST_G_ID = "taipy_broadcasting" __BRDCST_CALLBACK_G_ID = "taipy_brdcst_callback" __SELF_VAR = "__gui" __DO_NOT_UPDATE_VALUE = _DoNotUpdate() _HTML_CONTENT_KEY = "__taipy_html_content" __USER_CONTENT_CB = "custom_user_content_cb" __RE_HTML = re.compile(r"(.*?)\.html$") __RE_MD = re.compile(r"(.*?)\.md$") __RE_PY = re.compile(r"(.*?)\.py$") __RE_PAGE_NAME = re.compile(r"^[\w\-\/]+$") __reserved_routes: t.List[str] = [ __INIT_URL, __JSX_URL, __CONTENT_ROOT, __UPLOAD_URL, _EXTENSION_ROOT, __USER_CONTENT_URL, ] __LOCAL_TZ = str(tzlocal.get_localzone()) __extensions: t.Dict[str, t.List[ElementLibrary]] = {} __shared_variables: t.List[str] = [] __content_providers: t.Dict[type, t.Callable[..., str]] = {} def __init__( self, page: t.Optional[t.Union[str, Page]] = None, pages: t.Optional[dict] = None, css_file: t.Optional[str] = None, path_mapping: t.Optional[dict] = {}, env_filename: t.Optional[str] = None, libraries: t.Optional[t.List[ElementLibrary]] = None, flask: t.Optional[Flask] = None, ): """Initialize a new Gui instance. Arguments: page (Optional[Union[str, Page^]]): An optional `Page^` instance that is used when there is a single page in this interface, referenced as the *root* page (located at `/`).<br/> If *page* is a raw string and if it holds a path to a readable file then a `Markdown^` page is built from the content of that file.<br/> If *page* is a string that does not indicate a path to readable file then a `Markdown^` page is built from that string.<br/> Note that if *pages* is provided, those pages are added as well. pages (Optional[dict]): Used if you want to initialize this instance with a set of pages.<br/> The method `(Gui.)add_pages(pages)^` is called if *pages* is not None. You can find details on the possible values of this argument in the documentation for this method. css_file (Optional[str]): A pathname to a CSS file that gets used as a style sheet in all the pages.<br/> The default value is a file that has the same base name as the Python file defining the `main` function, sitting next to this Python file, with the `.css` extension. path_mapping (Optional[dict]): A dictionary that associates a URL prefix to a path in the server file system.<br/> If the assets of your application are located in */home/me/app_assets* and you want to access them using only '*assets*' in your application, you can set *path_mapping={"assets": "/home/me/app_assets"}*. If your application then requests the file *"/assets/images/logo.png"*, the server searches for the file *"/home/me/app_assets/images/logo.png"*.<br/> If empty or not defined, access through the browser to all resources under the directory of the main Python file is allowed. env_filename (Optional[str]): An optional file from which to load application configuration variables (see the [Configuration](../gui/configuration.md#configuring-the-gui-instance) section of the User Manual for details.)<br/> The default value is "taipy.gui.env" libraries (Optional[List[ElementLibrary]]): An optional list of extension library instances that pages can reference.<br/> Using this argument is equivalent to calling `(Gui.)add_library()^` for each list's elements. flask (Optional[Flask]): An optional instance of a Flask application object.<br/> If this argument is set, this `Gui` instance will use the value of this argument as the underlying server. If omitted or set to None, this `Gui` will create its own Flask application instance and use it to serve the pages. """ # store suspected local containing frame self.__frame = t.cast(FrameType, t.cast(FrameType, inspect.currentframe()).f_back) self.__default_module_name = _get_module_name_from_frame(self.__frame) self._set_css_file(css_file) # Preserve server config for server initialization self._path_mapping = path_mapping self._flask = flask self._config = _Config() self.__content_accessor = None self._accessors = _DataAccessors() self.__state: t.Optional[State] = None self.__bindings = _Bindings(self) self.__locals_context = _LocalsContext() self.__var_dir = _VariableDirectory(self.__locals_context) self.__evaluator: _Evaluator = None # type: ignore self.__adapter = _Adapter() self.__directory_name_of_pages: t.List[str] = [] # default actions self.on_action: t.Optional[t.Callable] = None self.on_change: t.Optional[t.Callable] = None self.on_init: t.Optional[t.Callable] = None self.on_navigate: t.Optional[t.Callable] = None self.on_exception: t.Optional[t.Callable] = None self.on_status: t.Optional[t.Callable] = None self.on_user_content: t.Optional[t.Callable] = None # sid from client_id self.__client_id_2_sid: t.Dict[str, t.Set[str]] = {} # Load default config self._flask_blueprint: t.List[Blueprint] = [] self._config._load(default_config) # get taipy version try: gui_file = pathlib.Path(__file__ or ".").resolve() with open(gui_file.parent / "version.json") as version_file: self.__version = json.load(version_file) except Exception as e: # pragma: no cover _warn("Cannot retrieve version.json file", e) self.__version = {} # Load Markdown extension # NOTE: Make sure, if you change this extension list, that the User Manual gets updated. # There's a section that explicitly lists these extensions in # docs/gui/pages.md#markdown-specifics self._markdown = md_lib.Markdown( extensions=[ "fenced_code", "meta", "admonition", "sane_lists", "tables", "attr_list", "md_in_html", _TaipyMarkdownExtension(gui=self), ] ) if page: self.add_page(name=Gui.__root_page_name, page=page) if pages is not None: self.add_pages(pages) if env_filename is not None: self.__env_filename = env_filename if libraries is not None: for library in libraries: Gui.add_library(library) @staticmethod def add_library(library: ElementLibrary) -> None: """Add a custom visual element library. This application will be able to use custom visual elements defined in this library. Arguments: library: The custom visual element library to add to this application. Multiple libraries with the same name can be added. This allows to split multiple custom visual elements in several `ElementLibrary^` instances, but still refer to these elements with the same prefix in the page definitions. """ if isinstance(library, ElementLibrary): _Factory.set_library(library) library_name = library.get_name() if library_name.isidentifier(): libs = Gui.__extensions.get(library_name) if libs is None: Gui.__extensions[library_name] = [library] else: libs.append(library) _ElementApiGenerator().add_library(library) else: raise NameError(f"ElementLibrary passed to add_library() has an invalid name: '{library_name}'") else: # pragma: no cover raise RuntimeError( f"add_library() argument should be a subclass of ElementLibrary instead of '{type(library)}'" ) @staticmethod def register_content_provider(content_type: type, content_provider: t.Callable[..., str]) -> None: """Add a custom content provider. The application can use custom content for the `part` block when its *content* property is set to an object with type *type*. Arguments: content_type: The type of the content that triggers the content provider. content_provider: The function that converts content of type *type* into an HTML string. """ # noqa: E501 if Gui.__content_providers.get(content_type): _warn(f"The type {content_type} is already associated with a provider.") return if not callable(content_provider): _warn(f"The provider for {content_type} must be a function.") return Gui.__content_providers[content_type] = content_provider def __process_content_provider(self, state: State, path: str, query: t.Dict[str, str]): variable_name = query.get("variable_name") content = None if variable_name: content = _getscopeattr(self, variable_name) if isinstance(content, _TaipyContentHtml): content = content.get() provider_fn = Gui.__content_providers.get(type(content)) if provider_fn is None: # try plotly if find_spec("plotly") and find_spec("plotly.graph_objs"): from plotly.graph_objs import Figure as PlotlyFigure if isinstance(content, PlotlyFigure): def get_plotly_content(figure: PlotlyFigure): return figure.to_html() Gui.register_content_provider(PlotlyFigure, get_plotly_content) provider_fn = get_plotly_content if provider_fn is None: # try matplotlib if find_spec("matplotlib") and find_spec("matplotlib.figure"): from matplotlib.figure import Figure as MatplotlibFigure if isinstance(content, MatplotlibFigure): def get_matplotlib_content(figure: MatplotlibFigure): import base64 from io import BytesIO buf = BytesIO() figure.savefig(buf, format="png") data = base64.b64encode(buf.getbuffer()).decode("ascii") return f'<img src="data:image/png;base64,{data}"/>' Gui.register_content_provider(MatplotlibFigure, get_matplotlib_content) provider_fn = get_matplotlib_content if callable(provider_fn): try: return provider_fn(content) except Exception as e: _warn(f"Error in content provider for type {str(type(content))}", e) return ( '<div style="background:white;color:red;">' + (f"No valid provider for type {type(content).__name__}" if content else "Wrong context.") + "</div>" ) @staticmethod def add_shared_variable(*names: str) -> None: """Add shared variables. The variables will be synchronized between all clients when updated. Note that only variables from the main module will be registered. This is a synonym for `(Gui.)add_shared_variables()^`. Arguments: names: The names of the variables that become shared, as a list argument. """ for name in names: if name not in Gui.__shared_variables: Gui.__shared_variables.append(name) @staticmethod def add_shared_variables(*names: str) -> None: """Add shared variables. The variables will be synchronized between all clients when updated. Note that only variables from the main module will be registered. This is a synonym for `(Gui.)add_shared_variable()^`. Arguments: names: The names of the variables that become shared, as a list argument. """ Gui.add_shared_variable(*names) def _get_shared_variables(self) -> t.List[str]: return self.__evaluator.get_shared_variables() def __get_content_accessor(self): if self.__content_accessor is None: self.__content_accessor = _ContentAccessor(self._get_config("data_url_max_size", 50 * 1024)) return self.__content_accessor def _bindings(self): return self.__bindings def _get_data_scope(self) -> SimpleNamespace: return self.__bindings._get_data_scope() def _get_all_data_scopes(self) -> t.Dict[str, SimpleNamespace]: return self.__bindings._get_all_scopes() def _get_config(self, name: ConfigParameter, default_value: t.Any) -> t.Any: return self._config._get_config(name, default_value) def _get_themes(self) -> t.Optional[t.Dict[str, t.Any]]: theme = self._get_config("theme", None) dark_theme = self._get_config("dark_theme", None) light_theme = self._get_config("light_theme", None) res = {} if theme: res["base"] = theme if dark_theme: res["dark"] = dark_theme if light_theme: res["light"] = light_theme return res if theme or dark_theme or light_theme else None def _bind(self, name: str, value: t.Any) -> None: self._bindings()._bind(name, value) def __get_state(self): return self.__state def _get_client_id(self) -> str: return ( _DataScopes._GLOBAL_ID if self._bindings()._is_single_client() else getattr(g, Gui.__ARG_CLIENT_ID, "unknown id") ) def __set_client_id_in_context(self, client_id: t.Optional[str] = None, force=False): if not client_id and request: client_id = request.args.get(Gui.__ARG_CLIENT_ID, "") if not client_id and force: res = self._bindings()._get_or_create_scope("") client_id = res[0] if res[1] else None if client_id and request: if sid := getattr(request, "sid", None): sids = self.__client_id_2_sid.get(client_id, None) if sids is None: sids = set() self.__client_id_2_sid[client_id] = sids sids.add(sid) g.client_id = client_id def __is_var_modified_in_context(self, var_name: str, derived_vars: t.Set[str]) -> bool: modified_vars: t.Optional[t.Set[str]] = getattr(g, "modified_vars", None) der_vars: t.Optional[t.Set[str]] = getattr(g, "derived_vars", None) setattr(g, "update_count", getattr(g, "update_count", 0) + 1) if modified_vars is None: modified_vars = set() g.modified_vars = modified_vars if der_vars is None: g.derived_vars = derived_vars else: der_vars.update(derived_vars) if var_name in modified_vars: return True modified_vars.add(var_name) return False def __clean_vars_on_exit(self) -> t.Optional[t.Set[str]]: update_count = getattr(g, "update_count", 0) - 1 if update_count < 1: derived_vars: t.Set[str] = getattr(g, "derived_vars", set()) delattr(g, "update_count") delattr(g, "modified_vars") delattr(g, "derived_vars") return derived_vars else: setattr(g, "update_count", update_count) return None def _manage_message(self, msg_type: _WsType, message: dict) -> None: try: client_id = None if msg_type == _WsType.CLIENT_ID.value: res = self._bindings()._get_or_create_scope(message.get("payload", "")) client_id = res[0] if res[1] else None self.__set_client_id_in_context(client_id or message.get(Gui.__ARG_CLIENT_ID)) with self._set_locals_context(message.get("module_context") or None): if msg_type == _WsType.UPDATE.value: payload = message.get("payload", {}) self.__front_end_update( str(message.get("name")), payload.get("value"), message.get("propagate", True), payload.get("relvar"), payload.get("on_change"), ) elif msg_type == _WsType.ACTION.value: self.__on_action(message.get("name"), message.get("payload")) elif msg_type == _WsType.DATA_UPDATE.value: self.__request_data_update(str(message.get("name")), message.get("payload")) elif msg_type == _WsType.REQUEST_UPDATE.value: self.__request_var_update(message.get("payload")) self.__send_ack(message.get("ack_id")) except Exception as e: # pragma: no cover _warn(f"Decoding Message has failed: {message}", e) def __front_end_update( self, var_name: str, value: t.Any, propagate=True, rel_var: t.Optional[str] = None, on_change: t.Optional[str] = None, ) -> None: if not var_name: return # Check if Variable is a managed type current_value = _getscopeattr_drill(self, self.__evaluator.get_hash_from_expr(var_name)) if isinstance(current_value, _TaipyData): return elif rel_var and isinstance(current_value, _TaipyLovValue): # pragma: no cover lov_holder = _getscopeattr_drill(self, self.__evaluator.get_hash_from_expr(rel_var)) if isinstance(lov_holder, _TaipyLov): val = value if isinstance(value, list) else [value] elt_4_ids = self.__adapter._get_elt_per_ids(lov_holder.get_name(), lov_holder.get()) ret_val = [elt_4_ids.get(x, x) for x in val] if isinstance(value, list): value = ret_val elif ret_val: value = ret_val[0] elif isinstance(current_value, _TaipyBase): value = current_value.cast_value(value) self._update_var( var_name, value, propagate, current_value if isinstance(current_value, _TaipyBase) else None, on_change ) def _update_var( self, var_name: str, value: t.Any, propagate=True, holder: t.Optional[_TaipyBase] = None, on_change: t.Optional[str] = None, ) -> None: if holder: var_name = holder.get_name() hash_expr = self.__evaluator.get_hash_from_expr(var_name) derived_vars = {hash_expr} # set to broadcast mode if hash_expr is in shared_variable if hash_expr in self._get_shared_variables(): self._set_broadcast() # Use custom attrsetter function to allow value binding for _MapDict if propagate: _setscopeattr_drill(self, hash_expr, value) # In case expression == hash (which is when there is only a single variable in expression) if var_name == hash_expr or hash_expr.startswith("tpec_"): derived_vars.update(self._re_evaluate_expr(var_name)) elif holder: derived_vars.update(self._evaluate_holders(hash_expr)) # if the variable has been evaluated then skip updating to prevent infinite loop var_modified = self.__is_var_modified_in_context(hash_expr, derived_vars) if not var_modified: self._call_on_change( var_name, value.get() if isinstance(value, _TaipyBase) else value._dict if isinstance(value, _MapDict) else value, on_change, ) derived_modified = self.__clean_vars_on_exit() if derived_modified is not None: self.__send_var_list_update(list(derived_modified), var_name) def _get_real_var_name(self, var_name: str) -> t.Tuple[str, str]: if not var_name: return (var_name, var_name) # Handle holder prefix if needed if var_name.startswith(_TaipyBase._HOLDER_PREFIX): for hp in _TaipyBase._get_holder_prefixes(): if var_name.startswith(hp): var_name = var_name[len(hp) :] break suffix_var_name = "" if "." in var_name: first_dot_index = var_name.index(".") suffix_var_name = var_name[first_dot_index + 1 :] var_name = var_name[:first_dot_index] var_name_decode, module_name = _variable_decode(self._get_expr_from_hash(var_name)) current_context = self._get_locals_context() # #583: allow module resolution for var_name in current_context root_page context if ( module_name and self._config.root_page and self._config.root_page._renderer and self._config.root_page._renderer._get_module_name() == module_name ): return f"{var_name_decode}.{suffix_var_name}" if suffix_var_name else var_name_decode, module_name if module_name == current_context: var_name = var_name_decode else: if var_name not in self.__var_dir._var_head: raise NameError(f"Can't find matching variable for {var_name} on context: {current_context}") _found = False for k, v in self.__var_dir._var_head[var_name]: if v == current_context: var_name = k _found = True break if not _found: # pragma: no cover raise NameError(f"Can't find matching variable for {var_name} on context: {current_context}") return f"{var_name}.{suffix_var_name}" if suffix_var_name else var_name, current_context def _call_on_change(self, var_name: str, value: t.Any, on_change: t.Optional[str] = None): try: var_name, current_context = self._get_real_var_name(var_name) except Exception as e: # pragma: no cover _warn("", e) return on_change_fn = self._get_user_function(on_change) if on_change else None if not callable(on_change_fn): on_change_fn = self._get_user_function("on_change") if callable(on_change_fn): try: argcount = on_change_fn.__code__.co_argcount if argcount > 0 and inspect.ismethod(on_change_fn): argcount -= 1 args: t.List[t.Any] = [None for _ in range(argcount)] if argcount > 0: args[0] = self.__get_state() if argcount > 1: args[1] = var_name if argcount > 2: args[2] = value if argcount > 3: args[3] = current_context on_change_fn(*args) except Exception as e: # pragma: no cover if not self._call_on_exception(on_change or "on_change", e): _warn(f"{on_change or 'on_change'}(): callback function raised an exception", e) def _get_content(self, var_name: str, value: t.Any, image: bool) -> t.Any: ret_value = self.__get_content_accessor().get_info(var_name, value, image) return f"/{Gui.__CONTENT_ROOT}/{ret_value[0]}" if isinstance(ret_value, tuple) else ret_value def __serve_content(self, path: str) -> t.Any: self.__set_client_id_in_context() parts = path.split("/") if len(parts) > 1: file_name = parts[-1] (dir_path, as_attachment) = self.__get_content_accessor().get_content_path( path[: -len(file_name) - 1], file_name, request.args.get("bypass") ) if dir_path: return send_from_directory(str(dir_path), file_name, as_attachment=as_attachment) return ("", 404) def _get_user_content_url( self, path: t.Optional[str] = None, query_args: t.Optional[t.Dict[str, str]] = None ) -> t.Optional[str]: qargs = query_args or {} qargs.update({Gui.__ARG_CLIENT_ID: self._get_client_id()}) return f"/{Gui.__USER_CONTENT_URL}/{path or 'TaIpY'}?{urlencode(qargs)}" def __serve_user_content(self, path: str) -> t.Any: self.__set_client_id_in_context() qargs: t.Dict[str, str] = {} qargs.update(request.args) qargs.pop(Gui.__ARG_CLIENT_ID, None) cb_function: t.Optional[t.Union[t.Callable, str]] = None cb_function_name = None if qargs.get(Gui._HTML_CONTENT_KEY): cb_function = self.__process_content_provider cb_function_name = cb_function.__name__ else: cb_function_name = qargs.get(Gui.__USER_CONTENT_CB) if cb_function_name: cb_function = self._get_user_function(cb_function_name) if not callable(cb_function): parts = cb_function_name.split(".", 1) if len(parts) > 1: base = _getscopeattr(self, parts[0], None) if base and (meth := getattr(base, parts[1], None)): cb_function = meth else: base = self.__evaluator._get_instance_in_context(parts[0]) if base and (meth := getattr(base, parts[1], None)): cb_function = meth if not callable(cb_function): _warn(f"{cb_function_name}() callback function has not been defined.") cb_function = None if cb_function is None: cb_function_name = "on_user_content" if hasattr(self, cb_function_name) and callable(self.on_user_content): cb_function = self.on_user_content else: _warn("on_user_content() callback function has not been defined.") if callable(cb_function): try: args: t.List[t.Any] = [] if path: args.append(path) if len(qargs): args.append(qargs) ret = self._call_function_with_state(cb_function, args) if ret is None: _warn(f"{cb_function_name}() callback function must return a value.") else: return (ret, 200) except Exception as e: # pragma: no cover if not self._call_on_exception(str(cb_function_name), e): _warn(f"{cb_function_name}() callback function raised an exception", e) return ("", 404) def __serve_extension(self, path: str) -> t.Any: parts = path.split("/") last_error = "" resource_name = None if len(parts) > 1: libs = Gui.__extensions.get(parts[0], []) for library in libs: try: resource_name = library.get_resource("/".join(parts[1:])) if resource_name: return send_file(resource_name) except Exception as e: last_error = f"\n{e}" # Check if the resource is served by another library with the same name _warn(f"Resource '{resource_name or path}' not accessible for library '{parts[0]}'{last_error}") return ("", 404) def __get_version(self) -> str: return f'{self.__version.get("major", 0)}.{self.__version.get("minor", 0)}.{self.__version.get("patch", 0)}' def __append_libraries_to_status(self, status: t.Dict[str, t.Any]): libraries: t.Dict[str, t.Any] = {} for libs_list in self.__extensions.values(): for lib in libs_list: if not isinstance(lib, ElementLibrary): continue libs = libraries.get(lib.get_name()) if libs is None: libs = [] libraries[lib.get_name()] = libs elts: t.List[t.Dict[str, str]] = [] libs.append({"js module": lib.get_js_module_name(), "elements": elts}) for element_name, elt in lib.get_elements().items(): if not isinstance(elt, Element): continue elt_dict = {"name": element_name} if hasattr(elt, "_render_xhtml"): elt_dict["render function"] = elt._render_xhtml.__code__.co_name else: elt_dict["react name"] = elt._get_js_name(element_name) elts.append(elt_dict) status.update({"libraries": libraries}) def _serve_status(self, template: pathlib.Path) -> t.Dict[str, t.Dict[str, str]]: base_json: t.Dict[str, t.Any] = {"user_status": str(self.__call_on_status() or "")} if self._get_config("extended_status", False): base_json.update( { "flask_version": str(metadata.version("flask") or ""), "backend_version": self.__get_version(), "host": f'{self._get_config("host", "localhost")}:{self._get_config("port", "default")}', "python_version": sys.version, } ) self.__append_libraries_to_status(base_json) try: base_json.update(json.loads(template.read_text())) except Exception as e: # pragma: no cover _warn(f"Exception raised reading JSON in '{template}'", e) return {"gui": base_json} def __upload_files(self): self.__set_client_id_in_context() if "var_name" not in request.form: _warn("No var name") return ("No var name", 400) var_name = request.form["var_name"] multiple = "multiple" in request.form and request.form["multiple"] == "True" if "blob" not in request.files: _warn("No file part") return ("No file part", 400) file = request.files["blob"] # If the user does not select a file, the browser submits an # empty file without a filename. if file.filename == "": _warn("No selected file") return ("No selected file", 400) suffix = "" complete = True part = 0 if "total" in request.form: total = int(request.form["total"]) if total > 1 and "part" in request.form: part = int(request.form["part"]) suffix = f".part.{part}" complete = part == total - 1 if file: # and allowed_file(file.filename) upload_path = pathlib.Path(self._get_config("upload_folder", tempfile.gettempdir())).resolve() file_path = _get_non_existent_file_path(upload_path, secure_filename(file.filename)) file.save(str(upload_path / (file_path.name + suffix))) if complete: if part > 0: try: with open(file_path, "wb") as grouped_file: for nb in range(part + 1): with open(upload_path / f"{file_path.name}.part.{nb}", "rb") as part_file: grouped_file.write(part_file.read()) except EnvironmentError as ee: # pragma: no cover _warn("Cannot group file after chunk upload", ee) return # notify the file is uploaded newvalue = str(file_path) if multiple: value = _getscopeattr(self, var_name) if not isinstance(value, t.List): value = [] if value is None else [value] value.append(newvalue) newvalue = value setattr(self._bindings(), var_name, newvalue) return ("", 200) _data_request_counter = 1 def __send_var_list_update( # noqa C901 self, modified_vars: t.List[str], front_var: t.Optional[str] = None, ): ws_dict = {} values = {v: _getscopeattr_drill(self, v) for v in modified_vars} for k, v in values.items(): if isinstance(v, (_TaipyData, _TaipyContentHtml)) and v.get_name() in modified_vars: modified_vars.remove(v.get_name()) elif isinstance(v, _DoNotUpdate): modified_vars.remove(k) for _var in modified_vars: newvalue = values.get(_var) if isinstance(newvalue, _TaipyData): # A changing integer that triggers a data request newvalue = Gui._data_request_counter Gui._data_request_counter = (Gui._data_request_counter % 100) + 1 else: if isinstance(newvalue, (_TaipyContent, _TaipyContentImage)): ret_value = self.__get_content_accessor().get_info( front_var, newvalue.get(), isinstance(newvalue, _TaipyContentImage) ) if isinstance(ret_value, tuple): newvalue = f"/{Gui.__CONTENT_ROOT}/{ret_value[0]}" else: newvalue = ret_value elif isinstance(newvalue, _TaipyContentHtml): newvalue = self._get_user_content_url( None, {"variable_name": str(_var), Gui._HTML_CONTENT_KEY: str(time.time())} ) elif isinstance(newvalue, _TaipyLov): newvalue = [self.__adapter._run_for_var(newvalue.get_name(), elt) for elt in newvalue.get()] elif isinstance(newvalue, _TaipyLovValue): if isinstance(newvalue.get(), list): newvalue = [ self.__adapter._run_for_var(newvalue.get_name(), elt, id_only=True) for elt in newvalue.get() ] else: newvalue = self.__adapter._run_for_var(newvalue.get_name(), newvalue.get(), id_only=True) if isinstance(newvalue, (dict, _MapDict)): continue # this var has no transformer debug_warnings: t.List[warnings.WarningMessage] = [] with warnings.catch_warnings(record=True) as warns: warnings.resetwarnings() json.dumps(newvalue, cls=_TaipyJsonEncoder) if len(warns): keep_value = True for w in list(warns): if is_debugging(): debug_warnings.append(w) if w.category is not DeprecationWarning and w.category is not PendingDeprecationWarning: keep_value = False break if not keep_value: # do not send data that is not serializable continue for w in debug_warnings: warnings.warn(w.message, w.category) ws_dict[_var] = newvalue # TODO: What if value == newvalue? self.__send_ws_update_with_dict(ws_dict) def __request_data_update(self, var_name: str, payload: t.Any) -> None: # Use custom attrgetter function to allow value binding for _MapDict newvalue = _getscopeattr_drill(self, var_name) if isinstance(newvalue, _TaipyData): ret_payload = None if isinstance(payload, dict): lib_name = payload.get("library") if isinstance(lib_name, str): libs = self.__extensions.get(lib_name, []) for lib in libs: user_var_name = var_name try: with contextlib.suppress(NameError): # ignore name error and keep var_name user_var_name = self._get_real_var_name(var_name)[0] ret_payload = lib.get_data(lib_name, payload, user_var_name, newvalue) if ret_payload: break except Exception as e: # pragma: no cover _warn( f"Exception raised in '{lib_name}.get_data({lib_name}, payload, {user_var_name}, value)'", # noqa: E501 e, ) if not isinstance(ret_payload, dict): ret_payload = self._accessors._get_data(self, var_name, newvalue, payload) self.__send_ws_update_with_dict({var_name: ret_payload}) def __request_var_update(self, payload: t.Any): if isinstance(payload, dict) and isinstance(payload.get("names"), list): if payload.get("refresh", False): # refresh vars for _var in t.cast(list, payload.get("names")): val = _getscopeattr_drill(self, _var) self._refresh_expr( val.get_name() if isinstance(val, _TaipyBase) else _var, val if isinstance(val, _TaipyBase) else None, ) self.__send_var_list_update(payload["names"]) def __send_ws(self, payload: dict, allow_grouping=True) -> None: grouping_message = self.__get_message_grouping() if allow_grouping else None if grouping_message is None: try: self._server._ws.emit( "message", payload, to=self.__get_ws_receiver(), ) time.sleep(0.001) except Exception as e: # pragma: no cover _warn(f"Exception raised in WebSocket communication in '{self.__frame.f_code.co_name}'", e) else: grouping_message.append(payload) def __broadcast_ws(self, payload: dict): try: self._server._ws.emit( "message", payload, ) time.sleep(0.001) except Exception as e: # pragma: no cover _warn(f"Exception raised in WebSocket communication in '{self.__frame.f_code.co_name}'", e) def __send_ack(self, ack_id: t.Optional[str]) -> None: if ack_id: try: self._server._ws.emit("message", {"type": _WsType.ACKNOWLEDGEMENT.value, "id": ack_id}) time.sleep(0.001) except Exception as e: # pragma: no cover _warn(f"Exception raised in WebSocket communication (send ack) in '{self.__frame.f_code.co_name}'", e) def _send_ws_id(self, id: str) -> None: self.__send_ws( { "type": _WsType.CLIENT_ID.value, "id": id, }, allow_grouping=False, ) def __send_ws_download(self, content: str, name: str, on_action: str) -> None: self.__send_ws({"type": _WsType.DOWNLOAD_FILE.value, "content": content, "name": name, "onAction": on_action}) def __send_ws_alert(self, type: str, message: str, system_notification: bool, duration: int) -> None: self.__send_ws( { "type": _WsType.ALERT.value, "atype": type, "message": message, "system": system_notification, "duration": duration, } ) def __send_ws_partial(self, partial: str): self.__send_ws( { "type": _WsType.PARTIAL.value, "name": partial, } ) def __send_ws_block( self, action: t.Optional[str] = None, message: t.Optional[str] = None, close: t.Optional[bool] = False, cancel: t.Optional[bool] = False, ): self.__send_ws( { "type": _WsType.BLOCK.value, "action": action, "close": close, "message": message, "noCancel": not cancel, } ) def __send_ws_navigate( self, to: str, params: t.Optional[t.Dict[str, str]], tab: t.Optional[str], force: bool, ): self.__send_ws({"type": _WsType.NAVIGATE.value, "to": to, "params": params, "tab": tab, "force": force}) def __send_ws_update_with_dict(self, modified_values: dict) -> None: payload = [ {"name": _get_client_var_name(k), "payload": (v if isinstance(v, dict) and "value" in v else {"value": v})} for k, v in modified_values.items() ] if self._is_broadcasting(): self.__broadcast_ws({"type": _WsType.MULTIPLE_UPDATE.value, "payload": payload}) self._set_broadcast(False) else: self.__send_ws({"type": _WsType.MULTIPLE_UPDATE.value, "payload": payload}) def __send_ws_broadcast(self, var_name: str, var_value: t.Any): self.__broadcast_ws( {"type": _WsType.UPDATE.value, "name": _get_broadcast_var_name(var_name), "payload": {"value": var_value}} ) def __get_ws_receiver(self) -> t.Union[t.List[str], t.Any, None]: if self._bindings()._is_single_client(): return None sid = getattr(request, "sid", None) if request else None sids = self.__client_id_2_sid.get(self._get_client_id(), set()) if sid: sids.add(sid) return list(sids) def __get_message_grouping(self): return ( _getscopeattr(self, Gui.__MESSAGE_GROUPING_NAME) if _hasscopeattr(self, Gui.__MESSAGE_GROUPING_NAME) else None ) def __enter__(self): self.__hold_messages() return self def __exit__(self, exc_type, exc_value, traceback): try: self.__send_messages() except Exception as e: # pragma: no cover _warn("Exception raised while sending messages", e) if exc_value: # pragma: no cover _warn(f"An {exc_type or 'Exception'} was raised", exc_value) return True def __hold_messages(self): grouping_message = self.__get_message_grouping() if grouping_message is None: self._bind_var_val(Gui.__MESSAGE_GROUPING_NAME, []) def __send_messages(self): grouping_message = self.__get_message_grouping() if grouping_message is not None: _delscopeattr(self, Gui.__MESSAGE_GROUPING_NAME) if len(grouping_message): self.__send_ws({"type": _WsType.MULTIPLE_MESSAGE.value, "payload": grouping_message}) def _get_user_function(self, func_name: str) -> t.Union[t.Callable, str]: func = _getscopeattr(self, func_name, None) if not callable(func): func = self._get_locals_bind().get(func_name) if not callable(func): func = self.__locals_context.get_default().get(func_name) return func if callable(func) else func_name def _get_user_instance(self, class_name: str, class_type: type) -> t.Union[object, str]: cls = _getscopeattr(self, class_name, None) if not isinstance(cls, class_type): cls = self._get_locals_bind().get(class_name) if not isinstance(cls, class_type): cls = self.__locals_context.get_default().get(class_name) return cls if isinstance(cls, class_type) else class_name def __on_action(self, id: t.Optional[str], payload: t.Any) -> None: if isinstance(payload, dict): action = payload.get("action") else: action = str(payload) payload = {"action": action} if action: if self.__call_function_with_args(action_function=self._get_user_function(action), id=id, payload=payload): return else: # pragma: no cover _warn(f"on_action(): '{action}' is not a valid function.") if hasattr(self, "on_action"): self.__call_function_with_args(action_function=self.on_action, id=id, payload=payload) def __call_function_with_args(self, **kwargs): action_function = kwargs.get("action_function") id = kwargs.get("id") payload = kwargs.get("payload") if callable(action_function): try: argcount = action_function.__code__.co_argcount if argcount > 0 and inspect.ismethod(action_function): argcount -= 1 args = [None for _ in range(argcount)] if argcount > 0: args[0] = self.__get_state() if argcount > 1: try: args[1] = self._get_real_var_name(id)[0] except Exception: args[1] = id if argcount > 2: args[2] = payload action_function(*args) return True except Exception as e: # pragma: no cover if not self._call_on_exception(action_function.__name__, e): _warn(f"on_action(): Exception raised in '{action_function.__name__}()'", e) return False def _call_function_with_state(self, user_function: t.Callable, args: t.List[t.Any]) -> t.Any: args.insert(0, self.__get_state()) argcount = user_function.__code__.co_argcount if argcount > 0 and inspect.ismethod(user_function): argcount -= 1 if argcount > len(args): args += (argcount - len(args)) * [None] else: args = args[:argcount] return user_function(*args) def _set_module_context(self, module_context: t.Optional[str]) -> t.ContextManager[None]: return self._set_locals_context(module_context) if module_context is not None else contextlib.nullcontext() def _call_user_callback( self, state_id: t.Optional[str], user_callback: t.Callable, args: t.List[t.Any], module_context: t.Optional[str] ) -> t.Any: try: with self.get_flask_app().app_context(): self.__set_client_id_in_context(state_id) with self._set_module_context(module_context): return self._call_function_with_state(user_callback, args) except Exception as e: # pragma: no cover if not self._call_on_exception(user_callback.__name__, e): _warn(f"invoke_callback(): Exception raised in '{user_callback.__name__}()'", e) return None def _call_broadcast_callback( self, user_callback: t.Callable, args: t.List[t.Any], module_context: t.Optional[str] ) -> t.Any: @contextlib.contextmanager def _broadcast_callback() -> t.Iterator[None]: try: setattr(g, Gui.__BRDCST_CALLBACK_G_ID, True) yield finally: setattr(g, Gui.__BRDCST_CALLBACK_G_ID, False) with _broadcast_callback(): # Use global scopes for broadcast callbacks return self._call_user_callback(_DataScopes._GLOBAL_ID, user_callback, args, module_context) def _is_in_brdcst_callback(self): try: return getattr(g, Gui.__BRDCST_CALLBACK_G_ID, False) except RuntimeError: return False # Proxy methods for Evaluator def _evaluate_expr(self, expr: str) -> t.Any: return self.__evaluator.evaluate_expr(self, expr) def _re_evaluate_expr(self, var_name: str) -> t.Set[str]: return self.__evaluator.re_evaluate_expr(self, var_name) def _refresh_expr(self, var_name: str, holder: t.Optional[_TaipyBase]): return self.__evaluator.refresh_expr(self, var_name, holder) def _get_expr_from_hash(self, hash_val: str) -> str: return self.__evaluator.get_expr_from_hash(hash_val) def _evaluate_bind_holder(self, holder: t.Type[_TaipyBase], expr: str) -> str: return self.__evaluator.evaluate_bind_holder(self, holder, expr) def _evaluate_holders(self, expr: str) -> t.List[str]: return self.__evaluator.evaluate_holders(self, expr) def _is_expression(self, expr: str) -> bool: if self.__evaluator is None: return False return self.__evaluator._is_expression(expr) # make components resettable def _set_building(self, building: bool): self._building = building def __is_building(self): return hasattr(self, "_building") and self._building def _get_rebuild_fn_name(self, name: str): return f"{Gui.__SELF_VAR}.{name}" def __get_attributes(self, attr_json: str, hash_json: str, args_dict: t.Dict[str, t.Any]): attributes: t.Dict[str, t.Any] = json.loads(unquote(attr_json)) hashes: t.Dict[str, str] = json.loads(unquote(hash_json)) attributes.update({k: args_dict.get(v) for k, v in hashes.items()}) return attributes, hashes def _tbl_cols( self, rebuild: bool, rebuild_val: t.Optional[bool], attr_json: str, hash_json: str, **kwargs ) -> t.Union[str, _DoNotUpdate]: if not self.__is_building(): try: rebuild = rebuild_val if rebuild_val is not None else rebuild if rebuild: attributes, hashes = self.__get_attributes(attr_json, hash_json, kwargs) data_hash = hashes.get("data", "") data = kwargs.get(data_hash) col_dict = _get_columns_dict( data, attributes.get("columns", {}), self._accessors._get_col_types(data_hash, _TaipyData(data, data_hash)), attributes.get("date_format"), attributes.get("number_format"), ) _enhance_columns(attributes, hashes, col_dict, "table(cols)") return json.dumps(col_dict, cls=_TaipyJsonEncoder) except Exception as e: # pragma: no cover _warn("Exception while rebuilding table columns", e) return Gui.__DO_NOT_UPDATE_VALUE def _chart_conf( self, rebuild: bool, rebuild_val: t.Optional[bool], attr_json: str, hash_json: str, **kwargs ) -> t.Union[str, _DoNotUpdate]: if not self.__is_building(): try: rebuild = rebuild_val if rebuild_val is not None else rebuild if rebuild: attributes, hashes = self.__get_attributes(attr_json, hash_json, kwargs) data_hash = hashes.get("data", "") config = _build_chart_config( self, attributes, self._accessors._get_col_types(data_hash, _TaipyData(kwargs.get(data_hash), data_hash)), ) return json.dumps(config, cls=_TaipyJsonEncoder) except Exception as e: # pragma: no cover _warn("Exception while rebuilding chart config", e) return Gui.__DO_NOT_UPDATE_VALUE # Proxy methods for Adapter def _add_adapter_for_type(self, type_name: str, adapter: t.Callable) -> None: self.__adapter._add_for_type(type_name, adapter) def _add_type_for_var(self, var_name: str, type_name: str) -> None: self.__adapter._add_type_for_var(var_name, type_name) def _get_adapter_for_type(self, type_name: str) -> t.Optional[t.Callable]: return self.__adapter._get_for_type(type_name) def _get_unique_type_adapter(self, type_name: str) -> str: return self.__adapter._get_unique_type(type_name) def _run_adapter( self, adapter: t.Optional[t.Callable], value: t.Any, var_name: str, id_only=False ) -> t.Union[t.Tuple[str, ...], str, None]: return self.__adapter._run(adapter, value, var_name, id_only) def _get_valid_adapter_result(self, value: t.Any, id_only=False) -> t.Union[t.Tuple[str, ...], str, None]: return self.__adapter._get_valid_result(value, id_only) def _is_ui_blocked(self): return _getscopeattr(self, Gui.__UI_BLOCK_NAME, False) def __get_on_cancel_block_ui(self, callback: t.Optional[str]): def _taipy_on_cancel_block_ui(guiApp, id: t.Optional[str], payload: t.Any): if _hasscopeattr(guiApp, Gui.__UI_BLOCK_NAME): _setscopeattr(guiApp, Gui.__UI_BLOCK_NAME, False) guiApp.__on_action(id, {"action": callback}) return _taipy_on_cancel_block_ui def __add_pages_in_folder(self, folder_name: str, folder_path: str): from ._renderers import Html, Markdown list_of_files = os.listdir(folder_path) for file_name in list_of_files: if file_name.startswith("__"): continue if (re_match := Gui.__RE_HTML.match(file_name)) and f"{re_match.group(1)}.py" not in list_of_files: _renderers = Html(os.path.join(folder_path, file_name), frame=None) _renderers.modify_taipy_base_url(folder_name) self.add_page(name=f"{folder_name}/{re_match.group(1)}", page=_renderers) elif (re_match := Gui.__RE_MD.match(file_name)) and f"{re_match.group(1)}.py" not in list_of_files: _renderers_md = Markdown(os.path.join(folder_path, file_name), frame=None) self.add_page(name=f"{folder_name}/{re_match.group(1)}", page=_renderers_md) elif re_match := Gui.__RE_PY.match(file_name): module_name = re_match.group(1) module_path = os.path.join(folder_name, module_name).replace(os.path.sep, ".") try: module = importlib.import_module(module_path) page_instance = _get_page_from_module(module) if page_instance is not None: self.add_page(name=f"{folder_name}/{module_name}", page=page_instance) except Exception as e: _warn(f"Error while importing module '{module_path}'", e) elif os.path.isdir(child_dir_path := os.path.join(folder_path, file_name)): child_dir_name = f"{folder_name}/{file_name}" self.__add_pages_in_folder(child_dir_name, child_dir_path) # Proxy methods for LocalsContext def _get_locals_bind(self) -> t.Dict[str, t.Any]: return self.__locals_context.get_locals() def _get_default_locals_bind(self) -> t.Dict[str, t.Any]: return self.__locals_context.get_default() def _get_locals_bind_from_context(self, context: t.Optional[str]) -> t.Dict[str, t.Any]: return self.__locals_context._get_locals_bind_from_context(context) def _get_locals_context(self) -> str: current_context = self.__locals_context.get_context() return current_context if current_context is not None else self.__default_module_name def _set_locals_context(self, context: t.Optional[str]) -> t.ContextManager[None]: return self.__locals_context.set_locals_context(context) def _get_page_context(self, page_name: str) -> str | None: if page_name not in self._config.routes: return None page = None for p in self._config.pages: if p._route == page_name: page = p if page is None: return None return ( (page._renderer._get_module_name() or self.__default_module_name) if page._renderer is not None else self.__default_module_name ) @staticmethod def _get_root_page_name(): return Gui.__root_page_name def _set_flask(self, flask: Flask): self._flask = flask def _get_default_module_name(self): return self.__default_module_name @staticmethod def _get_timezone() -> str: return Gui.__LOCAL_TZ @staticmethod def _set_timezone(tz: str): Gui.__LOCAL_TZ = tz # Public methods def add_page( self, name: str, page: t.Union[str, Page], style: t.Optional[str] = "", ) -> None: """Add a page to the Graphical User Interface. Arguments: name: The name of the page. page (Union[str, Page^]): The content of the page.<br/> It can be an instance of `Markdown^` or `Html^`.<br/> If *page* is a string, then: - If *page* is set to the pathname of a readable file, the page content is read as Markdown input text. - If it is not, the page content is read from this string as Markdown text. style (Optional[str]): Additional CSS style to apply to this page. - if there is style associated with a page, it is used at a global level - if there is no style associated with the page, the style is cleared at a global level - if the page is embedded in a block control, the style is ignored Note that page names cannot start with the slash ('/') character and that each page must have a unique name. """ # Validate name if name is None: # pragma: no cover raise Exception("name is required for add_page() function.") if not Gui.__RE_PAGE_NAME.match(name): # pragma: no cover raise SyntaxError( f'Page name "{name}" is invalid. It must only contain letters, digits, dash (-), underscore (_), and forward slash (/) characters.' # noqa: E501 ) if name.startswith("/"): # pragma: no cover raise SyntaxError(f'Page name "{name}" cannot start with forward slash (/) character.') if name in self._config.routes: # pragma: no cover raise Exception(f'Page name "{name if name != Gui.__root_page_name else "/"}" is already defined.') if isinstance(page, str): from ._renderers import Markdown page = Markdown(page, frame=None) elif not isinstance(page, Page): # pragma: no cover raise Exception( f'Parameter "page" is invalid for page name "{name if name != Gui.__root_page_name else "/"}.' ) # Init a new page new_page = _Page() new_page._route = name new_page._renderer = page new_page._style = style # Append page to _config self._config.pages.append(new_page) self._config.routes.append(name) # set root page if name == Gui.__root_page_name: self._config.root_page = new_page # Update locals context self.__locals_context.add(page._get_module_name(), page._get_locals()) # Update variable directory if not page._is_class_module(): self.__var_dir.add_frame(page._frame) def add_pages(self, pages: t.Optional[t.Union[t.Mapping[str, t.Union[str, Page]], str]] = None) -> None: """Add several pages to the Graphical User Interface. Arguments: pages (Union[dict[str, Union[str, Page^]], str]): The pages to add.<br/> If *pages* is a dictionary, a page is added to this `Gui` instance for each of the entries in *pages*: - The entry key is used as the page name. - The entry value is used as the page content: - The value can can be an instance of `Markdown^` or `Html^`, then it is used as the page definition. - If entry value is a string, then: - If it is set to the pathname of a readable file, the page content is read as Markdown input text. - If it is not, the page content is read from this string as Markdown text. !!! note "Reading pages from a directory" If *pages* is a string that holds the path to a readable directory, then this directory is traversed, recursively, to find files that Taipy can build pages from. For every new directory that is traversed, a new hierarchical level for pages is created. For every file that is found: - If the filename extension is *.md*, it is read as Markdown content and a new page is created with the base name of this filename. - If the filename extension is *.html*, it is read as HTML content and a new page is created with the base name of this filename. For example, say you have the following directory structure: ``` reports ├── home.html ├── budget/ │ ├── expenses/ │ │ ├── marketing.md │ │ └── production.md │ └── revenue/ │ ├── EMAE.md │ ├── USA.md │ └── ASIA.md └── cashflow/ ├── weekly.md ├── monthly.md └── yearly.md ``` Calling `gui.add_pages('reports')` is equivalent to calling: ```py gui.add_pages({ "reports/home", Html("reports/home.html"), "reports/budget/expenses/marketing", Markdown("reports/budget/expenses/marketing.md"), "reports/budget/expenses/production", Markdown("reports/budget/expenses/production.md"), "reports/budget/revenue/EMAE", Markdown("reports/budget/revenue/EMAE.md"), "reports/budget/revenue/USA", Markdown("reports/budget/revenue/USA.md"), "reports/budget/revenue/ASIA", Markdown("reports/budget/revenue/ASIA.md"), "reports/cashflow/weekly", Markdown("reports/cashflow/weekly.md"), "reports/cashflow/monthly", Markdown("reports/cashflow/monthly.md"), "reports/cashflow/yearly", Markdown("reports/cashflow/yearly.md") }) ``` """ if isinstance(pages, dict): for k, v in pages.items(): if k == "/": k = Gui.__root_page_name self.add_page(name=k, page=v) elif isinstance(folder_name := pages, str): if not hasattr(self, "_root_dir"): self._root_dir = os.path.dirname(inspect.getabsfile(self.__frame)) folder_path = folder_name if os.path.isabs(folder_name) else os.path.join(self._root_dir, folder_name) folder_name = os.path.basename(folder_path) if not os.path.isdir(folder_path): # pragma: no cover raise RuntimeError(f"Path {folder_path} is not a valid directory") if folder_name in self.__directory_name_of_pages: # pragma: no cover raise Exception(f"Base directory name {folder_name} of path {folder_path} is not unique") if folder_name in Gui.__reserved_routes: # pragma: no cover raise Exception(f"Invalid directory. Directory {folder_name} is a reserved route") self.__directory_name_of_pages.append(folder_name) self.__add_pages_in_folder(folder_name, folder_path) # partials def add_partial( self, page: t.Union[str, Page], ) -> Partial: """Create a new `Partial^`. The [User Manual section on Partials](../gui/pages/index.md#partials) gives details on when and how to use this class. Arguments: page (Union[str, Page^]): The page to create a new Partial from.<br/> It can be an instance of `Markdown^` or `Html^`.<br/> If *page* is a string, then: - If *page* is set to the pathname of a readable file, the content of the new `Partial` is read as Markdown input text. - If it is not, the content of the new `Partial` is read from this string as Markdown text. Returns: The new `Partial` object defined by *page*. """ new_partial = Partial() # Validate name if ( new_partial._route in self._config.partial_routes or new_partial._route in self._config.routes ): # pragma: no cover _warn(f'Partial name "{new_partial._route}" is already defined.') if isinstance(page, str): from ._renderers import Markdown page = Markdown(page, frame=None) elif not isinstance(page, Page): # pragma: no cover raise Exception(f'Partial name "{new_partial._route}" has an invalid Page.') new_partial._renderer = page # Append partial to _config self._config.partials.append(new_partial) self._config.partial_routes.append(str(new_partial._route)) # Update locals context self.__locals_context.add(page._get_module_name(), page._get_locals()) # Update variable directory self.__var_dir.add_frame(page._frame) return new_partial def _update_partial(self, partial: Partial): partials = _getscopeattr(self, Partial._PARTIALS, {}) partials[partial._route] = partial _setscopeattr(self, Partial._PARTIALS, partials) self.__send_ws_partial(str(partial._route)) def _get_partial(self, route: str) -> t.Optional[Partial]: partials = _getscopeattr(self, Partial._PARTIALS, {}) partial = partials.get(route) if partial is None: partial = next((p for p in self._config.partials if p._route == route), None) return partial # Main binding method (bind in markdown declaration) def _bind_var(self, var_name: str) -> str: bind_context = None if var_name in self._get_locals_bind().keys(): bind_context = self._get_locals_context() if bind_context is None: encoded_var_name = self.__var_dir.add_var(var_name, self._get_locals_context(), var_name) else: encoded_var_name = self.__var_dir.add_var(var_name, bind_context) if not hasattr(self._bindings(), encoded_var_name): bind_locals = self._get_locals_bind_from_context(bind_context) if var_name in bind_locals.keys(): self._bind(encoded_var_name, bind_locals[var_name]) else: _warn( f"Variable '{var_name}' is not available in either the '{self._get_locals_context()}' or '__main__' modules." # noqa: E501 ) return encoded_var_name def _bind_var_val(self, var_name: str, value: t.Any) -> bool: if _MODULE_ID not in var_name: var_name = self.__var_dir.add_var(var_name, self._get_locals_context()) if not hasattr(self._bindings(), var_name): self._bind(var_name, value) return True return False def __bind_local_func(self, name: str): func = getattr(self, name, None) if func is not None and not callable(func): # pragma: no cover _warn(f"{self.__class__.__name__}.{name}: {func} should be a function; looking for {name} in the script.") func = None if func is None: func = self._get_locals_bind().get(name) if func is not None: if callable(func): setattr(self, name, func) else: # pragma: no cover _warn(f"{name}: {func} should be a function.") def load_config(self, config: Config) -> None: self._config._load(config) def _broadcast(self, name: str, value: t.Any): """NOT UNDOCUMENTED Send the new value of a variable to all connected clients. Arguments: name: The name of the variable to update or create. value: The value (must be serializable to the JSON format). """ self.__send_ws_broadcast(name, value) def _broadcast_all_clients(self, name: str, value: t.Any): try: self._set_broadcast() self._update_var(name, value) finally: self._set_broadcast(False) def _set_broadcast(self, broadcast: bool = True): with contextlib.suppress(RuntimeError): setattr(g, Gui.__BROADCAST_G_ID, broadcast) def _is_broadcasting(self) -> bool: try: return getattr(g, Gui.__BROADCAST_G_ID, False) except RuntimeError: return False def _download( self, content: t.Any, name: t.Optional[str] = "", on_action: t.Optional[t.Union[str, t.Callable]] = "" ): if callable(on_action) and on_action.__name__: on_action_name = ( _get_expr_var_name(str(on_action.__code__)) if on_action.__name__ == "<lambda>" else _get_expr_var_name(on_action.__name__) ) if on_action_name: self._bind_var_val(on_action_name, on_action) on_action = on_action_name else: _warn("download() on_action is invalid.") content_str = self._get_content("Gui.download", content, False) self.__send_ws_download(content_str, str(name), str(on_action)) def _notify( self, notification_type: str = "I", message: str = "", system_notification: t.Optional[bool] = None, duration: t.Optional[int] = None, ): self.__send_ws_alert( notification_type, message, self._get_config("system_notification", False) if system_notification is None else system_notification, self._get_config("notification_duration", 3000) if duration is None else duration, ) def _hold_actions( self, callback: t.Optional[t.Union[str, t.Callable]] = None, message: t.Optional[str] = "Work in Progress...", ): # pragma: no cover action_name = callback.__name__ if callable(callback) else callback # TODO: what if lambda? (it does work) func = self.__get_on_cancel_block_ui(action_name) def_action_name = func.__name__ _setscopeattr(self, def_action_name, func) if _hasscopeattr(self, Gui.__UI_BLOCK_NAME): _setscopeattr(self, Gui.__UI_BLOCK_NAME, True) else: self._bind(Gui.__UI_BLOCK_NAME, True) self.__send_ws_block(action=def_action_name, message=message, cancel=bool(action_name)) def _resume_actions(self): # pragma: no cover if _hasscopeattr(self, Gui.__UI_BLOCK_NAME): _setscopeattr(self, Gui.__UI_BLOCK_NAME, False) self.__send_ws_block(close=True) def _navigate( self, to: t.Optional[str] = "", params: t.Optional[t.Dict[str, str]] = None, tab: t.Optional[str] = None, force: t.Optional[bool] = False, ): to = to or Gui.__root_page_name if not to.startswith("/") and to not in self._config.routes and not urlparse(to).netloc: _warn(f'Cannot navigate to "{to if to != Gui.__root_page_name else "/"}": unknown page.') return False self.__send_ws_navigate(to if to != Gui.__root_page_name else "/", params, tab, force or False) return True def __init_libs(self): for name, libs in self.__extensions.items(): for lib in libs: if not isinstance(lib, ElementLibrary): continue try: self._call_function_with_state(lib.on_user_init, []) except Exception as e: # pragma: no cover if not self._call_on_exception(f"{name}.on_user_init", e): _warn(f"Exception raised in {name}.on_user_init()", e) def __init_route(self): self.__set_client_id_in_context(force=True) if not _hasscopeattr(self, Gui.__ON_INIT_NAME): _setscopeattr(self, Gui.__ON_INIT_NAME, True) self.__pre_render_pages() self.__init_libs() if hasattr(self, "on_init") and callable(self.on_init): try: self._call_function_with_state(self.on_init, []) except Exception as e: # pragma: no cover if not self._call_on_exception("on_init", e): _warn("Exception raised in on_init()", e) return self._render_route() def _call_on_exception(self, function_name: str, exception: Exception) -> bool: if hasattr(self, "on_exception") and callable(self.on_exception): try: self.on_exception(self.__get_state(), str(function_name), exception) except Exception as e: # pragma: no cover _warn("Exception raised in on_exception()", e) return True return False def __call_on_status(self) -> t.Optional[str]: if hasattr(self, "on_status") and callable(self.on_status): try: return self.on_status(self.__get_state()) except Exception as e: # pragma: no cover if not self._call_on_exception("on_status", e): _warn("Exception raised in on_status", e) return None def __pre_render_pages(self) -> None: """Pre-render all pages to have a proper initialization of all variables""" self.__set_client_id_in_context() for page in self._config.pages: if page is not None: with contextlib.suppress(Exception): page.render(self) def __render_page(self, page_name: str) -> t.Any: self.__set_client_id_in_context() nav_page = page_name if hasattr(self, "on_navigate") and callable(self.on_navigate): try: if self.on_navigate.__code__.co_argcount == 2: nav_page = self.on_navigate(self.__get_state(), page_name) else: params = request.args.to_dict() if hasattr(request, "args") else {} params.pop("client_id", None) params.pop("v", None) nav_page = self.on_navigate(self.__get_state(), page_name, params) if nav_page != page_name: if isinstance(nav_page, str): if self._navigate(nav_page): return ("Root page cannot be re-routed by on_navigate().", 302) else: _warn(f"on_navigate() returned an invalid page name '{nav_page}'.") nav_page = page_name except Exception as e: # pragma: no cover if not self._call_on_exception("on_navigate", e): _warn("Exception raised in on_navigate()", e) page = next((page_i for page_i in self._config.pages if page_i._route == nav_page), None) # Try partials if page is None: page = self._get_partial(nav_page) # Make sure that there is a page instance found if page is None: return ( jsonify({"error": f"Page '{nav_page}' doesn't exist."}), 400, {"Content-Type": "application/json; charset=utf-8"}, ) context = page.render(self) if ( nav_page == Gui.__root_page_name and page._rendered_jsx is not None and "<PageContent" not in page._rendered_jsx ): page._rendered_jsx += "<PageContent />" # Return jsx page if page._rendered_jsx is not None: return self._server._render( page._rendered_jsx, page._style if page._style is not None else "", page._head, context ) else: return ("No page template", 404) def _render_route(self) -> t.Any: return self._server._direct_render_json( { "locations": { "/" if route == Gui.__root_page_name else f"/{route}": f"/{route}" for route in self._config.routes }, "blockUI": self._is_ui_blocked(), } ) def _register_data_accessor(self, data_accessor_class: t.Type[_DataAccessor]) -> None: self._accessors._register(data_accessor_class) def get_flask_app(self) -> Flask: """Get the internal Flask application. This method must be called **after** `(Gui.)run()^` was invoked. Returns: The Flask instance used. """ if hasattr(self, "_server"): return self._server.get_flask() raise RuntimeError("get_flask_app() cannot be invoked before run() has been called.") def _set_frame(self, frame: FrameType): if not isinstance(frame, FrameType): # pragma: no cover raise RuntimeError("frame must be a FrameType where Gui can collect the local variables.") self.__frame = frame self.__default_module_name = _get_module_name_from_frame(self.__frame) def _set_css_file(self, css_file: t.Optional[str] = None): if css_file is None: script_file = pathlib.Path(self.__frame.f_code.co_filename or ".").resolve() if script_file.with_suffix(".css").exists(): css_file = f"{script_file.stem}.css" elif script_file.is_dir() and (script_file / "taipy.css").exists(): css_file = "taipy.css" self.__css_file = css_file def _set_state(self, state: State): if isinstance(state, State): self.__state = state def __get_client_config(self) -> t.Dict[str, t.Any]: config = { "timeZone": self._config.get_time_zone(), "darkMode": self._get_config("dark_mode", True), "baseURL": self._config._get_config("base_url", "/"), } if themes := self._get_themes(): config["themes"] = themes if len(self.__extensions): config["extensions"] = {} for libs in self.__extensions.values(): for lib in libs: config["extensions"][f"./{Gui._EXTENSION_ROOT}/{lib.get_js_module_name()}"] = [ # type: ignore e._get_js_name(n) for n, e in lib.get_elements().items() if isinstance(e, Element) and not e._is_server_only() ] if stylekit := self._get_config("stylekit", _default_stylekit): config["stylekit"] = {_to_camel_case(k): v for k, v in stylekit.items()} return config def __get_css_vars(self) -> str: css_vars = [] if stylekit := self._get_config("stylekit", _default_stylekit): for k, v in stylekit.items(): css_vars.append(f'--{k.replace("_", "-")}:{_get_css_var_value(v)};') return " ".join(css_vars) def __init_server(self): app_config = self._config.config # Init server if there is no server if not hasattr(self, "_server"): self._server = _Server( self, path_mapping=self._path_mapping, flask=self._flask, async_mode=app_config["async_mode"], allow_upgrades=not app_config["notebook_proxy"], server_config=app_config.get("server_config"), ) # Stop and reinitialize the server if it is still running as a thread if (_is_in_notebook() or app_config["run_in_thread"]) and hasattr(self._server, "_thread"): self.stop() self._flask_blueprint = [] self._server = _Server( self, path_mapping=self._path_mapping, flask=self._flask, async_mode=app_config["async_mode"], allow_upgrades=not app_config["notebook_proxy"], server_config=app_config.get("server_config"), ) self._bindings()._new_scopes() def __init_ngrok(self): app_config = self._config.config if app_config["run_server"] and app_config["ngrok_token"]: # pragma: no cover if not util.find_spec("pyngrok"): raise RuntimeError("Cannot use ngrok as pyngrok package is not installed.") ngrok.set_auth_token(app_config["ngrok_token"]) http_tunnel = ngrok.connect(app_config["port"], "http") _TaipyLogger._get_logger().info(f" * NGROK Public Url: {http_tunnel.public_url}") def __bind_default_function(self): with self.get_flask_app().app_context(): self.__var_dir.process_imported_var() # bind on_* function if available self.__bind_local_func("on_init") self.__bind_local_func("on_change") self.__bind_local_func("on_action") self.__bind_local_func("on_navigate") self.__bind_local_func("on_exception") self.__bind_local_func("on_status") self.__bind_local_func("on_user_content") def __register_blueprint(self): # add en empty main page if it is not defined if Gui.__root_page_name not in self._config.routes: new_page = _Page() new_page._route = Gui.__root_page_name new_page._renderer = _EmptyPage() self._config.pages.append(new_page) self._config.routes.append(Gui.__root_page_name) pages_bp = Blueprint("taipy_pages", __name__) self._flask_blueprint.append(pages_bp) # server URL Rule for taipy images images_bp = Blueprint("taipy_images", __name__) images_bp.add_url_rule(f"/{Gui.__CONTENT_ROOT}/<path:path>", view_func=self.__serve_content) self._flask_blueprint.append(images_bp) # server URL for uploaded files upload_bp = Blueprint("taipy_upload", __name__) upload_bp.add_url_rule(f"/{Gui.__UPLOAD_URL}", view_func=self.__upload_files, methods=["POST"]) self._flask_blueprint.append(upload_bp) # server URL for user content user_content_bp = Blueprint("taipy_user_content", __name__) user_content_bp.add_url_rule(f"/{Gui.__USER_CONTENT_URL}/<path:path>", view_func=self.__serve_user_content) self._flask_blueprint.append(user_content_bp) # server URL for extension resources extension_bp = Blueprint("taipy_extensions", __name__) extension_bp.add_url_rule(f"/{Gui._EXTENSION_ROOT}/<path:path>", view_func=self.__serve_extension) scripts = [ s if bool(urlparse(s).netloc) else f"/{Gui._EXTENSION_ROOT}/{name}/{s}{lib.get_query(s)}" for name, libs in Gui.__extensions.items() for lib in libs for s in (lib.get_scripts() or []) ] styles = [ s if bool(urlparse(s).netloc) else f"/{Gui._EXTENSION_ROOT}/{name}/{s}{lib.get_query(s)}" for name, libs in Gui.__extensions.items() for lib in libs for s in (lib.get_styles() or []) ] if self._get_config("stylekit", True): styles.append("stylekit/stylekit.css") else: styles.append("https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap") if self.__css_file: styles.append(f"/{self.__css_file}") self._flask_blueprint.append(extension_bp) _conf_webapp_path = ( pathlib.Path(self._get_config("webapp_path", None)) if self._get_config("webapp_path", None) else None ) _webapp_path = str((pathlib.Path(__file__).parent / "webapp").resolve()) if _conf_webapp_path: if _conf_webapp_path.is_dir(): _webapp_path = str(_conf_webapp_path.resolve()) _warn(f"Using webapp_path: '{_conf_webapp_path}'.") else: # pragma: no cover _warn( f"webapp_path: '{_conf_webapp_path}' is not a valid directory path. Falling back to '{_webapp_path}'." # noqa: E501 ) self._flask_blueprint.append( self._server._get_default_blueprint( static_folder=_webapp_path, template_folder=_webapp_path, title=self._get_config("title", "Taipy App"), favicon=self._get_config("favicon", "favicon.png"), root_margin=self._get_config("margin", None), scripts=scripts, styles=styles, version=self.__get_version(), client_config=self.__get_client_config(), watermark=self._get_config("watermark", None), css_vars=self.__get_css_vars(), base_url=self._get_config("base_url", "/"), ) ) # Run parse markdown to force variables binding at runtime pages_bp.add_url_rule(f"/{Gui.__JSX_URL}/<path:page_name>", view_func=self.__render_page) # server URL Rule for flask rendered react-router pages_bp.add_url_rule(f"/{Gui.__INIT_URL}", view_func=self.__init_route) # Register Flask Blueprint if available for bp in self._flask_blueprint: self._server.get_flask().register_blueprint(bp) def run( self, run_server: bool = True, run_in_thread: bool = False, async_mode: str = "gevent", **kwargs, ) -> t.Optional[Flask]: """ Start the server that delivers pages to web clients. Once you enter `run()`, users can run web browsers and point to the web server URL that `Gui` serves. The default is to listen to the *localhost* address (127.0.0.1) on the port number 5000. However, the configuration of this `Gui` object may impact that (see the [Configuration](../gui/configuration.md#configuring-the-gui-instance) section of the User Manual for details). Arguments: run_server (bool): Whether or not to run a web server locally. If set to *False*, a web server is *not* created and started. run_in_thread (bool): Whether or not to run a web server in a separated thread. If set to *True*, the web server runs is a separated thread.<br/> Note that if you are running in an IPython notebook context, the web server always runs in a separate thread. async_mode (str): The asynchronous model to use for the Flask-SocketIO. Valid values are:<br/> - "gevent": Use a [gevent](https://www.gevent.org/servers.html) server. - "threading": Use the Flask Development Server. This allows the application to use the Flask reloader (the *use_reloader* option) and Debug mode (the *debug* option). - "eventlet": Use an [*eventlet*](https://flask.palletsprojects.com/en/2.2.x/deploying/eventlet/) event-driven WSGI server. The default value is "gevent"<br/> Note that only the "threading" value provides support for the development reloader functionality (*use_reloader* option). Any other value makes the *use_reloader* configuration parameter ignored.<br/> Also note that setting the *debug* argument to True forces *async_mode* to "threading". **kwargs (dict[str, any]): Additional keyword arguments that configure how this `Gui` is run. Please refer to the [Configuration section](../gui/configuration.md#configuring-the-gui-instance) of the User Manual for more information. Returns: The Flask instance if *run_server* is False else None. """ # -------------------------------------------------------------------------------- # The ssl_context argument was removed just after 1.1. It was defined as: # t.Optional[t.Union[ssl.SSLContext, t.Tuple[str, t.Optional[str]], t.Literal["adhoc"]]] = None # # With the doc: # ssl_context (Optional[Union[ssl.SSLContext, Tuple[str, Optional[str]], te.Literal['adhoc']]]): # Configures TLS to serve over HTTPS. This value can be: # # - An `ssl.SSLContext` object # - A `(cert_file, key_file)` tuple to create a typical context # - The string "adhoc" to generate a temporary self-signed certificate. # # The default value is None. # -------------------------------------------------------------------------------- app_config = self._config.config run_root_dir = os.path.dirname(inspect.getabsfile(self.__frame)) # Register _root_dir for abs path if not hasattr(self, "_root_dir"): self._root_dir = run_root_dir is_reloading = kwargs.pop("_reload", False) if not is_reloading: self.__run_kwargs = kwargs = { **kwargs, "run_server": run_server, "run_in_thread": run_in_thread, "async_mode": async_mode, } # Load application config from multiple sources (env files, kwargs, command line) self._config._build_config(run_root_dir, self.__env_filename, kwargs) self._config.resolve() TaipyGuiWarning.set_debug_mode(self._get_config("debug", False)) self.__init_server() self.__init_ngrok() locals_bind = _filter_locals(self.__frame.f_locals) self.__locals_context.set_default(locals_bind, self.__default_module_name) self.__var_dir.set_default(self.__frame) if self.__state is None or is_reloading: self.__state = State(self, self.__locals_context.get_all_keys(), self.__locals_context.get_all_context()) if _is_in_notebook(): # Allow gui.state.x in notebook mode self.state = self.__state self.__bind_default_function() # Base global ctx is TaipyHolder classes + script modules and callables glob_ctx: t.Dict[str, t.Any] = {t.__name__: t for t in _TaipyBase.__subclasses__()} glob_ctx.update({k: v for k, v in locals_bind.items() if inspect.ismodule(v) or callable(v)}) glob_ctx[Gui.__SELF_VAR] = self # Call on_init on each library for name, libs in self.__extensions.items(): for lib in libs: if not isinstance(lib, ElementLibrary): continue try: lib_context = lib.on_init(self) if ( isinstance(lib_context, tuple) and len(lib_context) > 1 and isinstance(lib_context[0], str) and lib_context[0].isidentifier() ): if lib_context[0] in glob_ctx: _warn(f"Method {name}.on_init() returned a name already defined '{lib_context[0]}'.") else: glob_ctx[lib_context[0]] = lib_context[1] elif lib_context: _warn( f"Method {name}.on_init() should return a Tuple[str, Any] where the first element must be a valid Python identifier." # noqa: E501 ) except Exception as e: # pragma: no cover if not self._call_on_exception(f"{name}.on_init", e): _warn(f"Method {name}.on_init() raised an exception", e) # Initiate the Evaluator with the right context self.__evaluator = _Evaluator(glob_ctx, self.__shared_variables) self.__register_blueprint() # Register data accessor communication data format (JSON, Apache Arrow) self._accessors._set_data_format(_DataFormat.APACHE_ARROW if app_config["use_arrow"] else _DataFormat.JSON) # Use multi user or not self._bindings()._set_single_client(bool(app_config["single_client"])) # Start Flask Server if not run_server: return self.get_flask_app() return self._server.run( host=app_config["host"], port=app_config["port"], debug=app_config["debug"], use_reloader=app_config["use_reloader"], flask_log=app_config["flask_log"], run_in_thread=app_config["run_in_thread"], allow_unsafe_werkzeug=app_config["allow_unsafe_werkzeug"], notebook_proxy=app_config["notebook_proxy"], ) def reload(self): # pragma: no cover """ Reload the web server. This function reloads the underlying web server only in the situation where it was run in a separated thread: the *run_in_thread* parameter to the `(Gui.)run^` method was set to True, or you are running in an IPython notebook context. """ if hasattr(self, "_server") and hasattr(self._server, "_thread") and self._server._is_running: self._server.stop_thread() self.run(**self.__run_kwargs, _reload=True) _TaipyLogger._get_logger().info("Gui server has been reloaded.") def stop(self): """ Stop the web server. This function stops the underlying web server only in the situation where it was run in a separated thread: the *run_in_thread* parameter to the `(Gui.)run()^` method was set to True, or you are running in an IPython notebook context. """ if hasattr(self, "_server") and hasattr(self._server, "_thread") and self._server._is_running: self._server.stop_thread() _TaipyLogger._get_logger().info("Gui server has been stopped.")
import inspect import typing as t from contextlib import nullcontext from operator import attrgetter from types import FrameType from flask import has_app_context from flask.ctx import AppContext from .utils import _get_module_name_from_frame, _is_in_notebook from .utils._attributes import _attrsetter if t.TYPE_CHECKING: from .gui import Gui class State: """Accessor to the bound variables from callbacks. `State` is used when you need to access the value of variables bound to visual elements (see [Binding](../gui/binding.md)).<br/> Because each browser connected to the application server may represent and modify any variable at any moment as the result of user interaction, each connection holds its own set of variables along with their values. We call the set of these the application variables the application _state_, as seen by a given client. Each callback (see [Callbacks](../gui/callbacks.md)) receives a specific instance of the `State` class, where you can find all the variables bound to visual elements in your application. Note that `State` also is a Python Context Manager: In situations where you have several variables to update, it is more clear and more efficient to assign the variable values in a `with` construct: ```py def my_callback(state, ...): ... with state as s: s.var1 = value1 s.var2 = value2 ... ``` You cannot set a variable in the context of a lambda function because Python prevents any use of the assignment operator.<br/> You can, however, use the `assign()` method on the state that the lambda function receives, so you can work around this limitation: Here is how you could define a button that changes the value of a variable directly in a page expressed using Markdown: ``` <|Set variable|button|on_action={lambda s: s.assign("var_name", new_value)}|> ``` This would be strictly similar to the Markdown line: ``` <|Set variable|button|on_action=change_variable|> ``` with the Python code: ```py def change_variable(state): state.var_name = new_value ``` """ __gui_attr = "_gui" __attrs = ( __gui_attr, "_user_var_list", "_context_list", ) __methods = ( "assign", "broadcast", "get_gui", "refresh", "_set_context", "_notebook_context", "_get_placeholder", "_set_placeholder", "_get_gui_attr", "_get_placeholder_attrs", "_add_attribute", ) __placeholder_attrs = ( "_taipy_p1", "_current_context", ) __excluded_attrs = __attrs + __methods + __placeholder_attrs def __init__(self, gui: "Gui", var_list: t.Iterable[str], context_list: t.Iterable[str]) -> None: super().__setattr__(State.__attrs[1], list(State.__filter_var_list(var_list, State.__excluded_attrs))) super().__setattr__(State.__attrs[2], list(context_list)) super().__setattr__(State.__attrs[0], gui) def get_gui(self) -> "Gui": """Return the Gui instance for this state object. Returns: Gui: The Gui instance for this state object. """ return super().__getattribute__(State.__gui_attr) @staticmethod def __filter_var_list(var_list: t.Iterable[str], excluded_attrs: t.Iterable[str]) -> t.Iterable[str]: return filter(lambda n: n not in excluded_attrs, var_list) def __getattribute__(self, name: str) -> t.Any: if name in State.__methods: return super().__getattribute__(name) gui: "Gui" = self.get_gui() if name == State.__gui_attr: return gui if name in State.__excluded_attrs: raise AttributeError(f"Variable '{name}' is protected and is not accessible.") if gui._is_in_brdcst_callback() and ( name not in gui._get_shared_variables() and not gui._bindings()._is_single_client() ): raise AttributeError(f"Variable '{name}' is not available to be accessed in shared callback.") if name not in super().__getattribute__(State.__attrs[1]): raise AttributeError(f"Variable '{name}' is not defined.") with self._notebook_context(gui), self._set_context(gui): encoded_name = gui._bind_var(name) return getattr(gui._bindings(), encoded_name) def __setattr__(self, name: str, value: t.Any) -> None: gui: "Gui" = super().__getattribute__(State.__gui_attr) if gui._is_in_brdcst_callback() and ( name not in gui._get_shared_variables() and not gui._bindings()._is_single_client() ): raise AttributeError(f"Variable '{name}' is not available to be accessed in shared callback.") if name not in super().__getattribute__(State.__attrs[1]): raise AttributeError(f"Variable '{name}' is not accessible.") with self._notebook_context(gui), self._set_context(gui): encoded_name = gui._bind_var(name) setattr(gui._bindings(), encoded_name, value) def __getitem__(self, key: str): context = key if key in super().__getattribute__(State.__attrs[2]) else None if context is None: gui: "Gui" = super().__getattribute__(State.__gui_attr) page_ctx = gui._get_page_context(key) context = page_ctx if page_ctx is not None else None if context is None: raise RuntimeError(f"Can't resolve context '{key}' from state object") self._set_placeholder(State.__placeholder_attrs[1], context) return self def _set_context(self, gui: "Gui") -> t.ContextManager[None]: if (pl_ctx := self._get_placeholder(State.__placeholder_attrs[1])) is not None: self._set_placeholder(State.__placeholder_attrs[1], None) if pl_ctx != gui._get_locals_context(): return gui._set_locals_context(pl_ctx) if len(inspect.stack()) > 1: ctx = _get_module_name_from_frame(t.cast(FrameType, t.cast(FrameType, inspect.stack()[2].frame))) current_context = gui._get_locals_context() # ignore context if the current one starts with the new one (to resolve for class modules) if ctx != current_context and not current_context.startswith(str(ctx)): return gui._set_locals_context(ctx) return nullcontext() def _notebook_context(self, gui: "Gui"): return gui.get_flask_app().app_context() if not has_app_context() and _is_in_notebook() else nullcontext() def _get_placeholder(self, name: str): if name in State.__placeholder_attrs: try: return super().__getattribute__(name) except AttributeError: return None return None def _set_placeholder(self, name: str, value: t.Any): if name in State.__placeholder_attrs: super().__setattr__(name, value) def _get_placeholder_attrs(self): return State.__placeholder_attrs def _add_attribute(self, name: str, default_value: t.Optional[t.Any] = None) -> bool: attrs: t.List[str] = super().__getattribute__(State.__attrs[1]) if name not in attrs: attrs.append(name) gui = super().__getattribute__(State.__gui_attr) return gui._bind_var_val(name, default_value) return False def assign(self, name: str, value: t.Any) -> t.Any: """Assign a value to a state variable. This should be used only from within a lambda function used as a callback in a visual element. Arguments: name (str): The variable name to assign to. value (Any): The new variable value. Returns: Any: The previous value of the variable. """ val = attrgetter(name)(self) _attrsetter(self, name, value) return val def refresh(self, name: str): """Refresh a state variable. This allows to re-sync the user interface with a variable value. Arguments: name (str): The variable name to refresh. """ val = attrgetter(name)(self) _attrsetter(self, name, val) def broadcast(self, name: str, value: t.Any): """Update a variable on all clients. All connected clients will receive an update of the variable called *name* with the provided value, even if it is not shared. Arguments: name (str): The variable name to update. value (Any): The new variable value. """ gui: "Gui" = super().__getattribute__(State.__gui_attr) with self._set_context(gui): encoded_name = gui._bind_var(name) gui._broadcast_all_clients(encoded_name, value) def __enter__(self): super().__getattribute__(State.__attrs[0]).__enter__() return self def __exit__(self, exc_type, exc_value, traceback): return super().__getattribute__(State.__attrs[0]).__exit__(exc_type, exc_value, traceback)
import re import sys import typing as t import xml.etree.ElementTree as etree from abc import ABC, abstractmethod from inspect import isclass from pathlib import Path from urllib.parse import urlencode from .._renderers.builder import _Builder from .._warnings import _warn from ..gui_types import PropertyType from ..utils import _get_broadcast_var_name, _TaipyBase, _to_camel_case if t.TYPE_CHECKING: from ..gui import Gui from ..state import State class ElementProperty: """ The declaration of a property of a visual element. Each visual element property is described by an instance of `ElementProperty`. This class holds the information on the name, type and default value for the element property. """ def __init__( self, property_type: PropertyType, default_value: t.Optional[t.Any] = None, js_name: t.Optional[str] = None, ) -> None: """Initializes a new custom property declaration for an `Element^`. Arguments: property_type (PropertyType): The type of this property. default_value (Optional[Any]): The default value for this property. Default is None. js_name (Optional[str]): The name of this property, in the front-end JavaScript code.<br/> If unspecified, a camel case version of `name` is generated: for example, if `name` is "my_property_name", then this property is referred to as "myPropertyName" in the JavaScript code. """ self.default_value = default_value if property_type == PropertyType.broadcast: if isinstance(default_value, str): self.default_value = _get_broadcast_var_name(default_value) else: _warn("Element property with type 'broadcast' must define a string default value.") self.property_type = PropertyType.react else: self.property_type = property_type self._js_name = js_name super().__init__() def check(self, element_name: str, prop_name: str): if not isinstance(prop_name, str) or not prop_name or not prop_name.isidentifier(): _warn(f"Property name '{prop_name}' is invalid for element '{element_name}'.") if not isinstance(self.property_type, PropertyType) and not ( isclass(self.property_type) and issubclass(self.property_type, _TaipyBase) ): _warn(f"Property type '{self.property_type}' is invalid for element property '{element_name}.{prop_name}'.") def _get_tuple(self, name: str) -> tuple: return (name, self.property_type, self.default_value) def get_js_name(self, name: str) -> str: return self._js_name or _to_camel_case(name) class Element: """ The definition of a custom visual element. An element is defined by its properties (name, type and default value) and what the default property name is. """ __RE_PROP_VAR = re.compile(r"<tp:prop:(\w+)>") def __init__( self, default_property: str, properties: t.Dict[str, ElementProperty], react_component: t.Optional[str] = None, render_xhtml: t.Optional[t.Callable[[t.Dict[str, t.Any]], str]] = None, inner_properties: t.Optional[t.Dict[str, ElementProperty]] = None, ) -> None: """Initializes a new custom element declaration. If *render_xhtml* is specified, then this is a static element, and *react_component* is ignored. Arguments: default_property (str): the name of the default property for this element. properties (List[ElementProperty]): The list of properties for this element. inner_properties (Optional[List[ElementProperty]]): The optional list of inner properties for this element.<br/> Default values are set/binded automatically. react_component (Optional[str]): The name of the component to be created on the front-end.<br/> If not specified, it is set to a camel case version of the element's name ("one_name" is transformed to "OneName"). render_xhtml (Optional[callable[[dict[str, Any]], str]]): A function that receives a dictionary containing the element's properties and their values and that must return a valid XHTML string. """ # noqa: E501 self.default_attribute = default_property self.attributes = properties self.inner_properties = inner_properties self.js_name = react_component if callable(render_xhtml): self._render_xhtml = render_xhtml super().__init__() def _get_js_name(self, name: str) -> str: return self.js_name or _to_camel_case(name, True) def check(self, name: str): if not isinstance(name, str) or not name or not name.isidentifier(): _warn(f"Invalid element name: '{name}'.") default_found = False if self.attributes: for prop_name, property in self.attributes.items(): if isinstance(property, ElementProperty): property.check(name, prop_name) if not default_found: default_found = self.default_attribute == prop_name else: _warn(f"Property must inherit from 'ElementProperty' '{name}.{prop_name}'.") if not default_found: _warn(f"Element {name} has no default property.") def _is_server_only(self): return hasattr(self, "_render_xhtml") and callable(self._render_xhtml) def _call_builder( self, name, gui: "Gui", properties: t.Optional[t.Dict[str, t.Any]], lib: "ElementLibrary", is_html: t.Optional[bool] = False, ) -> t.Union[t.Any, t.Tuple[str, str]]: attributes = properties if isinstance(properties, dict) else {} if self.inner_properties: self.attributes.update(self.inner_properties) for prop, attr in self.inner_properties.items(): val = attr.default_value if val: # handling property replacement in inner properties <tp:prop:...> while m := Element.__RE_PROP_VAR.search(val): var = attributes.get(m.group(1)) hash_value = "None" if var is None else gui._evaluate_expr(var) val = val[: m.start()] + hash_value + val[m.end() :] attributes[prop] = val # this modifies attributes hash_names = _Builder._get_variable_hash_names(gui, attributes) # variable replacement # call user render if any if self._is_server_only(): xhtml = self._render_xhtml(attributes) try: xml_root = etree.fromstring(xhtml) if is_html: return xhtml, name else: return xml_root except Exception as e: _warn(f"{name}.render_xhtml() did not return a valid XHTML string", e) return f"{name}.render_xhtml() did not return a valid XHTML string. {e}" else: default_attr: t.Optional[ElementProperty] = None default_value = None default_name = None attrs = [] if self.attributes: for prop_name, property in self.attributes.items(): if isinstance(property, ElementProperty): if self.default_attribute == prop_name: default_name = prop_name default_attr = property default_value = property.default_value else: attrs.append(property._get_tuple(prop_name)) elt_built = _Builder( gui=gui, control_type=name, element_name=f"{lib.get_js_module_name()}_{self._get_js_name(name)}", attributes=properties, hash_names=hash_names, lib_name=lib.get_name(), default_value=default_value, ) if default_attr is not None: elt_built.set_value_and_default( var_name=default_name, var_type=default_attr.property_type, default_val=default_attr.default_value, with_default=default_attr.property_type != PropertyType.data, ) elt_built.set_attributes(attrs) return elt_built._build_to_string() if is_html else elt_built.el class ElementLibrary(ABC): """ A library of user-defined visual elements. An element library can declare any number of custom visual elements. In order to use those elements you must register the element library using the function `Gui.add_library()^`. An element library can mix *static* and *dynamic* elements. """ @abstractmethod def get_elements(self) -> t.Dict[str, Element]: """ Return the dictionary holding all visual element declarations. The key for each of this dictionary's entry is the name of the element, and the value is an instance of `Element^`. The default implementation returns an empty dictionary, indicating that this library contains no custom visual elements. """ return {} @abstractmethod def get_name(self) -> str: """ Return the library name. This string is used for different purposes: - It allows for finding the definition of visual elements when parsing the page content.<br/> Custom elements are defined with the fragment `<|<library_name>.<element_name>|>` in Markdown pages, and with the tag `<<library_name>:<element_name>>` in HTML pages. - In element libraries that hold elements with dynamic properties (where JavaScript) is involved, the name of the JavaScript module that has the front-end code is derived from this name, as described in `(ElementLibrary.)get_js_module_name()^`. Returns: The name of this element library. This must be a valid Python identifier. !!! note "Element libraries with the same name" You can add different libraries that have the same name.<br/> This is useful in large projects where you want to split a potentially large number of custom visual elements into different groups but still access them from your pages using the same library name prefix.<br/> In this situation, you will have to implement `(ElementLibrary.)get_js_module_name()^` because each JavaScript module will have to have a unique name. """ return NotImplementedError # type: ignore def get_js_module_name(self) -> str: """ Return the name of the JavaScript module. The JavaScript module is the JavaScript file that contains all the front-end code for this element library. Typically, the name of JavaScript modules uses camel case.<br/> This module name must be unique on the browser window scope: if your application uses several custom element libraries, they must define a unique name for their JavaScript module. The default implementation transforms the return value of `(ElementLibrary.)get_name()^` in the following manner: - The JavaScript module name is a camel case version of the element library name (see `(ElementLibrary.)get_name()^`): - If the library name is "library", the JavaScript module name defaults to "Library". - If the library name is "myLibrary", the JavaScript module name defaults to "Mylibrary". - If the element library name has underscore characters, each underscore-separated fragment is considered as a distinct word: - If the library name is "my_library", the JavaScript module name defaults to "MyLibrary". Returns: The name of the JavaScript module for this element library.<br/> The default implementation returns a camel case version of `self.get_name()`, as described above. """ return _to_camel_case(self.get_name(), True) def get_scripts(self) -> t.List[str]: """ Return the list of the mandatory script file pathnames. If a script file pathname is an absolute URL it will be used as is.<br/> If it's not it will be passed to `(ElementLibrary.)get_resource()^` to retrieve a local path to the resource. The default implementation returns an empty list, indicating that this library contains no custom visual elements with dynamic properties. Returns: A list of paths (relative to the element library Python implementation file or absolute) to all JavaScript module files to be loaded on the front-end.<br/> The default implementation returns an empty list. """ return [] def get_styles(self) -> t.List[str]: """ TODO Returns the list of resources names for the css stylesheets. Defaults to [] """ return [] def get_resource(self, name: str) -> Path: """ TODO Defaults to return None? Returns a path for a resource name. Resource URL should be formed as /taipy-extension/<library_name>/<resource virtual path> with(see get_resource_url) - <resource virtual path> being the `name` parameter - <library_name> the value returned by `get_name()` Arguments: name (str): The name of the resource for which a local Path should be returned. """ # noqa: E501 module_obj = sys.modules.get(self.__class__.__module__) base = (Path(".") if module_obj is None else Path(module_obj.__file__).parent).resolve() # type: ignore base = base if base.exists() else Path(".").resolve() file = (base / name).resolve() if str(file).startswith(str(base)) and file.exists(): return file else: raise FileNotFoundError(f"Cannot access resource {file}.") def get_resource_url(self, resource: str) -> str: """TODO""" from ..gui import Gui return f"/{Gui._EXTENSION_ROOT}/{self.get_name()}/{resource}{self.get_query(resource)}" def get_data(self, library_name: str, payload: t.Dict, var_name: str, value: t.Any) -> t.Optional[t.Dict]: """ TODO Called if implemented (i.e returns a dict). Arguments: library_name (str): The name of this library. payload (dict): The payload send by the `createRequestDataUpdateAction()` front-end function. var_name (str): The name of the variable holding the data. value (any): The current value of the variable identified by *var_name*. """ return None def on_init(self, gui: "Gui") -> t.Optional[t.Tuple[str, t.Any]]: """ Initialize this element library. This method is invoked by `Gui.run()^`. It allows to define variables that are accessible from elements defined in this element library. Arguments gui: The `Gui^` instance. Returns: An optional tuple composed of a variable name (that *must* be a valid Python identifier), associated with its value.<br/> This name can be used as the name of a variable accessible by the elements defined in this library.<br/> This name must be unique across the entire application, which is a problem since different element libraries might use the same symbol. A good development practice is to make this variable name unique by prefixing it with the name of the element library itself. """ return None def on_user_init(self, state: "State"): """ Initialize user state on first access. Arguments state: The `State^` instance. """ pass def get_query(self, name: str) -> str: """ Return an URL query depending on the resource name.<br/> Default implementation returns the version if defined. Arguments: name (str): The name of the resource for which a query should be returned. Returns: A string that holds the query part of an URL (starting with ?). """ if version := self.get_version(): return f"?{urlencode({'v': version})}" return "" def get_version(self) -> t.Optional[str]: """ The optional library version Returns: An optional string representing the library version.<br/> This version will be appended to the resource URL as a query arg (?v=<version>) """ return None
from ..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 from enum import Enum from .._renderers.utils import _get_columns_dict from .._warnings import _warn from ..gui_types import PropertyType from ..utils import _MapDict if t.TYPE_CHECKING: from ..gui import Gui class _Chart_iprops(Enum): x = 0 y = 1 z = 2 label = 3 text = 4 mode = 5 type = 6 color = 7 xaxis = 8 yaxis = 9 selected_color = 10 marker = 11 selected_marker = 12 orientation = 13 _name = 14 line = 15 text_anchor = 16 options = 17 lon = 18 lat = 19 base = 20 r = 21 theta = 22 close = 23 open = 24 high = 25 low = 26 locations = 27 values = 28 labels = 29 decimator = 30 measure = 31 parents = 32 __CHART_AXIS: t.Dict[str, t.Tuple[_Chart_iprops, ...]] = { "bar": (_Chart_iprops.x, _Chart_iprops.y, _Chart_iprops.base), "candlestick": ( _Chart_iprops.x, _Chart_iprops.close, _Chart_iprops.open, _Chart_iprops.high, _Chart_iprops.low, ), "choropleth": (_Chart_iprops.locations, _Chart_iprops.z), "densitymapbox": (_Chart_iprops.lon, _Chart_iprops.lat, _Chart_iprops.z), "funnelarea": (_Chart_iprops.values,), "pie": (_Chart_iprops.values, _Chart_iprops.labels), "scattergeo": (_Chart_iprops.lon, _Chart_iprops.lat), "scattermapbox": (_Chart_iprops.lon, _Chart_iprops.lat), "scatterpolar": (_Chart_iprops.r, _Chart_iprops.theta), "scatterpolargl": (_Chart_iprops.r, _Chart_iprops.theta), "treemap": (_Chart_iprops.labels, _Chart_iprops.parents, _Chart_iprops.values), "waterfall": (_Chart_iprops.x, _Chart_iprops.y, _Chart_iprops.measure), } __CHART_DEFAULT_AXIS: t.Tuple[_Chart_iprops, ...] = (_Chart_iprops.x, _Chart_iprops.y, _Chart_iprops.z) __CHART_MARKER_TO_COLS: t.Tuple[str, ...] = ("color", "size", "symbol", "opacity") __CHART_NO_INDEX: t.Tuple[str, ...] = ("pie", "histogram", "heatmap", "funnelarea") _CHART_NAMES: t.Tuple[str, ...] = tuple(e.name[1:] if e.name[0] == "_" else e.name for e in _Chart_iprops) def __check_dict(values: t.List[t.Any], properties: t.Iterable[_Chart_iprops]) -> None: for prop in properties: if values[prop.value] is not None and not isinstance(values[prop.value], (dict, _MapDict)): _warn(f"Property {prop.name} of chart control should be a dict.") values[prop.value] = None def __get_multiple_indexed_attributes( attributes: t.Dict[str, t.Any], names: t.Iterable[str], index: t.Optional[int] = None ) -> t.List[t.Optional[str]]: names = names if index is None else [f"{n}[{index}]" for n in names] # type: ignore return [attributes.get(name) for name in names] __RE_INDEXED_DATA = re.compile(r"^(\d+)\/(.*)") def __get_col_from_indexed(col_name: str, idx: int) -> t.Optional[str]: if re_res := __RE_INDEXED_DATA.search(col_name): return col_name if str(idx) == re_res.group(1) else None return col_name def _build_chart_config(gui: "Gui", attributes: t.Dict[str, t.Any], col_types: t.Dict[str, str]): # noqa: C901 default_type = attributes.get("_default_type", "scatter") default_mode = attributes.get("_default_mode", "lines+markers") trace = __get_multiple_indexed_attributes(attributes, _CHART_NAMES) if not trace[_Chart_iprops.mode.value]: trace[_Chart_iprops.mode.value] = default_mode # type if not trace[_Chart_iprops.type.value]: trace[_Chart_iprops.type.value] = default_type if not trace[_Chart_iprops.xaxis.value]: trace[_Chart_iprops.xaxis.value] = "x" if not trace[_Chart_iprops.yaxis.value]: trace[_Chart_iprops.yaxis.value] = "y" # Indexed properties: Check for arrays for prop in _Chart_iprops: values = trace[prop.value] if isinstance(values, (list, tuple)) and len(values): prop_name = prop.name[1:] if prop.name[0] == "_" else prop.name for idx, val in enumerate(values): if idx == 0: trace[prop.value] = val if val is not None: indexed_prop = f"{prop_name}[{idx + 1}]" if attributes.get(indexed_prop) is None: attributes[indexed_prop] = val # marker selected_marker options __check_dict(trace, (_Chart_iprops.marker, _Chart_iprops.selected_marker, _Chart_iprops.options)) axis = [] traces: t.List[t.List[t.Optional[str]]] = [] idx = 1 indexed_trace = __get_multiple_indexed_attributes(attributes, _CHART_NAMES, idx) if len([x for x in indexed_trace if x]): while len([x for x in indexed_trace if x]): axis.append( __CHART_AXIS.get( indexed_trace[_Chart_iprops.type.value] or trace[_Chart_iprops.type.value] or "", __CHART_DEFAULT_AXIS, ) ) # marker selected_marker options __check_dict(indexed_trace, (_Chart_iprops.marker, _Chart_iprops.selected_marker, _Chart_iprops.options)) if trace[_Chart_iprops.decimator.value] and not indexed_trace[_Chart_iprops.decimator.value]: # copy the decimator only once indexed_trace[_Chart_iprops.decimator.value] = trace[_Chart_iprops.decimator.value] trace[_Chart_iprops.decimator.value] = None traces.append([x or trace[i] for i, x in enumerate(indexed_trace)]) idx += 1 indexed_trace = __get_multiple_indexed_attributes(attributes, _CHART_NAMES, idx) else: traces.append(trace) # axis names axis.append(__CHART_AXIS.get(trace[_Chart_iprops.type.value] or "", __CHART_DEFAULT_AXIS)) # list of data columns name indexes with label text dt_idx = tuple(e.value for e in (axis[0] + (_Chart_iprops.label, _Chart_iprops.text))) # configure columns columns: t.Set[str] = set() for j, trace in enumerate(traces): dt_idx = tuple( e.value for e in (axis[j] if j < len(axis) else axis[0]) + (_Chart_iprops.label, _Chart_iprops.text) ) columns.update([trace[i] or "" for i in dt_idx if trace[i]]) # add optionnal column if any markers = [ t[_Chart_iprops.marker.value] or ({"color": t[_Chart_iprops.color.value]} if t[_Chart_iprops.color.value] else None) for t in traces ] opt_cols = set() for m in markers: if isinstance(m, (dict, _MapDict)): for prop1 in __CHART_MARKER_TO_COLS: val = m.get(prop1) if isinstance(val, str) and val not in columns: opt_cols.add(val) # Validate the column names col_dict = _get_columns_dict(attributes.get("data"), list(columns), col_types, opt_columns=opt_cols) # Manage Decimator decimators: t.List[t.Optional[str]] = [] for tr in traces: if tr[_Chart_iprops.decimator.value]: cls = gui._get_user_instance( class_name=str(tr[_Chart_iprops.decimator.value]), class_type=PropertyType.decimator.value ) if isinstance(cls, PropertyType.decimator.value): decimators.append(str(tr[_Chart_iprops.decimator.value])) continue decimators.append(None) # set default columns if not defined icols = [[c2 for c2 in [__get_col_from_indexed(c1, i) for c1 in col_dict.keys()] if c2] for i in range(len(traces))] for i, tr in enumerate(traces): if i < len(axis): used_cols = {tr[ax.value] for ax in axis[i] if tr[ax.value]} unused_cols = [c for c in icols[i] if c not in used_cols] if unused_cols and not any(tr[ax.value] for ax in axis[i]): traces[i] = list( v or (unused_cols.pop(0) if unused_cols and _Chart_iprops(j) in axis[i] else v) for j, v in enumerate(tr) ) if col_dict is not None: reverse_cols = {str(cd.get("dfid")): c for c, cd in col_dict.items()} # List used axis used_axis = [[e for e in (axis[j] if j < len(axis) else axis[0]) if tr[e.value]] for j, tr in enumerate(traces)] ret_dict = { "columns": col_dict, "labels": [ reverse_cols.get(tr[_Chart_iprops.label.value] or "", (tr[_Chart_iprops.label.value] or "")) for tr in traces ], "texts": [ reverse_cols.get(tr[_Chart_iprops.text.value] or "", (tr[_Chart_iprops.text.value] or None)) for tr in traces ], "modes": [tr[_Chart_iprops.mode.value] for tr in traces], "types": [tr[_Chart_iprops.type.value] for tr in traces], "xaxis": [tr[_Chart_iprops.xaxis.value] for tr in traces], "yaxis": [tr[_Chart_iprops.yaxis.value] for tr in traces], "markers": markers, "selectedMarkers": [ tr[_Chart_iprops.selected_marker.value] or ( {"color": tr[_Chart_iprops.selected_color.value]} if tr[_Chart_iprops.selected_color.value] else None ) for tr in traces ], "traces": [ [reverse_cols.get(c or "", c) for c in [tr[e.value] for e in used_axis[j]]] for j, tr in enumerate(traces) ], "orientations": [tr[_Chart_iprops.orientation.value] for tr in traces], "names": [tr[_Chart_iprops._name.value] for tr in traces], "lines": [ tr[_Chart_iprops.line.value] if isinstance(tr[_Chart_iprops.line.value], (dict, _MapDict)) else {"dash": tr[_Chart_iprops.line.value]} if tr[_Chart_iprops.line.value] else None for tr in traces ], "textAnchors": [tr[_Chart_iprops.text_anchor.value] for tr in traces], "options": [tr[_Chart_iprops.options.value] for tr in traces], "axisNames": [[e.name for e in ax] for ax in used_axis], "addIndex": [tr[_Chart_iprops.type.value] not in __CHART_NO_INDEX for tr in traces], } if len([d for d in decimators if d]): ret_dict.update(decimators=decimators) return ret_dict return {}
import re import typing as t _RE_MODULE = re.compile(r"^__(.*?)__$") def _filter_locals(locals_dict: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]: return {k: v for k, v in locals_dict.items() if (not _RE_MODULE.match(k) or k == "__name__")}
import typing as t from .singleton import _Singleton if t.TYPE_CHECKING: from ..gui import Gui class _RuntimeManager(object, metaclass=_Singleton): def __init__(self): self.__port_gui: t.Dict[int, "Gui"] = {} def add_gui(self, gui: "Gui", port: int): if port in self.__port_gui: self.__port_gui[port].stop() self.__port_gui[port] = gui def get_used_port(self): return list(self.__port_gui.keys())
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)
from __future__ import annotations import typing as t from .._warnings import _warn from ..icon import Icon from . import _MapDict class _Adapter: def __init__(self): self.__adapter_for_type: t.Dict[str, t.Callable] = {} self.__type_for_variable: t.Dict[str, str] = {} self.__warning_by_type: t.Set[str] = set() def _add_for_type(self, type_name: str, adapter: t.Callable) -> None: self.__adapter_for_type[type_name] = adapter def _add_type_for_var(self, var_name: str, type_name: str) -> None: self.__type_for_variable[var_name] = type_name def _get_for_type(self, type_name: str) -> t.Optional[t.Callable]: return self.__adapter_for_type.get(type_name) def _get_unique_type(self, type_name: str) -> str: index = 0 while type_name in self.__adapter_for_type: type_name = f"{type_name}{index}" index += 1 return type_name def _run_for_var(self, var_name: str, value: t.Any, id_only=False) -> t.Any: ret = self._run(self.__get_for_var(var_name, value), value, var_name, id_only) return ret if ret is not None else value def __get_for_var(self, var_name: str, value: t.Any) -> t.Optional[t.Callable]: adapter = None type_name = self.__type_for_variable.get(var_name) if not isinstance(type_name, str): adapter = self.__adapter_for_type.get(var_name) type_name = var_name if callable(adapter) else type(value).__name__ if adapter is None: adapter = self.__adapter_for_type.get(type_name) return adapter if callable(adapter) else None def _get_elt_per_ids(self, var_name: str, lov: t.List[t.Any]) -> t.Dict[str, t.Any]: dict_res = {} adapter = self.__get_for_var(var_name, lov[0] if lov else None) for value in lov: try: result = adapter(value._dict if isinstance(value, _MapDict) else value) if adapter else value if result is not None: dict_res[self.__get_id(result)] = value children = self.__get_children(result) if children is not None: dict_res.update(self._get_elt_per_ids(var_name, children)) except Exception as e: _warn(f"Cannot run adapter for {var_name}", e) return dict_res def _run( self, adapter: t.Optional[t.Callable], value: t.Any, var_name: str, id_only=False ) -> t.Union[t.Tuple[str, ...], str, None]: if value is None: return None try: result = value._dict if isinstance(value, _MapDict) else value if adapter: result = adapter(result) if result is None: return result elif isinstance(result, str): return result tpl_res = self._get_valid_result(result, id_only) if tpl_res is None: _warn( f"Adapter for {var_name} did not return a valid result. Please check the documentation on List of Values Adapters." # noqa: E501 ) else: if not id_only and len(tpl_res) > 2 and isinstance(tpl_res[2], list) and len(tpl_res[2]) > 0: tpl_res = (tpl_res[0], tpl_res[1], self.__on_tree(adapter, tpl_res[2])) return ( (tpl_res + result[len(tpl_res) :]) if isinstance(result, tuple) and isinstance(tpl_res, tuple) else tpl_res ) except Exception as e: _warn(f"Cannot run adapter for {var_name}", e) return None def __on_tree(self, adapter: t.Optional[t.Callable], tree: t.List[t.Any]): ret_list = [] for elt in tree: ret = self._run(adapter, elt, adapter.__name__ if adapter else "adapter") if ret is not None: ret_list.append(ret) return ret_list def _get_valid_result(self, value: t.Any, id_only=False) -> t.Union[t.Tuple[str, ...], str, None]: id = self.__get_id(value) if id_only: return id label = self.__get_label(value) if label is None: return None children = self.__get_children(value) return (id, label) if children is None else (id, label, children) # type: ignore def __get_id(self, value: t.Any, dig=True) -> str: if isinstance(value, str): return value elif dig: if isinstance(value, (list, tuple)) and len(value): return self.__get_id(value[0], False) elif hasattr(value, "id"): return self.__get_id(value.id, False) elif hasattr(value, "__getitem__") and "id" in value: return self.__get_id(value.get("id"), False) if value is not None and type(value).__name__ not in self.__warning_by_type: _warn(f"LoV id must be a string, using a string representation of {type(value)}.") self.__warning_by_type.add(type(value).__name__) return "" if value is None else str(value) def __get_label(self, value: t.Any, dig=True) -> t.Union[str, t.Dict, None]: if isinstance(value, (str, Icon)): return Icon.get_dict_or(value) elif dig: if isinstance(value, (list, tuple)) and len(value) > 1: return self.__get_label(value[1], False) elif hasattr(value, "label"): return self.__get_label(value.label, False) elif hasattr(value, "__getitem__") and "label" in value: return self.__get_label(value["label"], False) return None def __get_children(self, value: t.Any) -> t.Optional[t.List[t.Any]]: if isinstance(value, (tuple, list)) and len(value) > 2: return value[2] if isinstance(value[2], list) else [value[2]] elif hasattr(value, "children"): return value.children if isinstance(value.children, list) else [value.children] elif hasattr(value, "__getitem__") and "children" in value: return value["children"] if isinstance(value["children"], list) else [value["children"]] return None
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]
from __future__ import annotations import ast import builtins import re import typing as t from .._warnings import _warn if t.TYPE_CHECKING: from ..gui import Gui from . import ( _get_client_var_name, _get_expr_var_name, _getscopeattr, _getscopeattr_drill, _hasscopeattr, _MapDict, _setscopeattr, _setscopeattr_drill, _TaipyBase, _variable_decode, _variable_encode, ) class _Evaluator: # Regex to separate content from inside curly braces when evaluating f string expressions __EXPR_RE = re.compile(r"\{(([^\}]*)([^\{]*))\}") __EXPR_IS_EXPR = re.compile(r"[^\\][{}]") __EXPR_IS_EDGE_CASE = re.compile(r"^\s*{([^}]*)}\s*$") __EXPR_VALID_VAR_EDGE_CASE = re.compile(r"^([a-zA-Z\.\_0-9\[\]]*)$") __EXPR_EDGE_CASE_F_STRING = re.compile(r"[\{]*[a-zA-Z_][a-zA-Z0-9_]*:.+") __IS_TAIPYEXPR_RE = re.compile(r"TpExPr_(.*)") def __init__(self, default_bindings: t.Dict[str, t.Any], shared_variable: t.List[str]) -> None: # key = expression, value = hashed value of the expression self.__expr_to_hash: t.Dict[str, str] = {} # key = hashed value of the expression, value = expression self.__hash_to_expr: t.Dict[str, str] = {} # key = variable name of the expression, key = list of related expressions # ex: {x + y} # "x_TPMDL_0": ["{x + y}"], # "y_TPMDL_0": ["{x + y}"], self.__var_to_expr_list: t.Dict[str, t.List[str]] = {} # key = expression, value = list of related variables # "{x + y}": {"x": "x_TPMDL_", "y": "y_TPMDL_0"} self.__expr_to_var_map: t.Dict[str, t.Dict[str, str]] = {} # instead of binding everywhere the types self.__global_ctx = default_bindings # expr to holders self.__expr_to_holders: t.Dict[str, t.Set[t.Type[_TaipyBase]]] = {} # shared variables between multiple clients self.__shared_variable = shared_variable @staticmethod def _expr_decode(s: str): return str(result[1]) if (result := _Evaluator.__IS_TAIPYEXPR_RE.match(s)) else s def get_hash_from_expr(self, expr: str) -> str: return self.__expr_to_hash.get(expr, expr) def get_expr_from_hash(self, hash_val: str) -> str: return self.__hash_to_expr.get(hash_val, hash_val) def get_shared_variables(self) -> t.List[str]: return self.__shared_variable def _is_expression(self, expr: str) -> bool: return len(_Evaluator.__EXPR_IS_EXPR.findall(expr)) != 0 def _fetch_expression_list(self, expr: str) -> t.List: return [v[0] for v in _Evaluator.__EXPR_RE.findall(expr)] def _analyze_expression(self, gui: Gui, expr: str) -> t.Tuple[t.Dict[str, t.Any], t.Dict[str, str]]: var_val: t.Dict[str, t.Any] = {} var_map: t.Dict[str, str] = {} non_vars = list(self.__global_ctx.keys()) non_vars.extend(dir(builtins)) # Get a list of expressions (value that has been wrapped in curly braces {}) and find variables to bind for e in self._fetch_expression_list(expr): var_name = e.split(sep=".")[0] st = ast.parse('f"{' + e + '}"' if _Evaluator.__EXPR_EDGE_CASE_F_STRING.match(e) else e) args = [arg.arg for node in ast.walk(st) if isinstance(node, ast.arguments) for arg in node.args] targets = [ # type: ignore compr.target.id for node in ast.walk(st) if isinstance(node, ast.ListComp) for compr in node.generators ] for node in ast.walk(st): if isinstance(node, ast.Name): var_name = node.id.split(sep=".")[0] if var_name not in args and var_name not in targets and var_name not in non_vars: try: encoded_var_name = gui._bind_var(var_name) var_val[var_name] = _getscopeattr_drill(gui, encoded_var_name) var_map[var_name] = encoded_var_name except AttributeError as e: _warn(f"Variable '{var_name}' is not defined (in expression '{expr}')", e) return var_val, var_map def __save_expression( self, gui: Gui, expr: str, expr_hash: t.Optional[str], expr_evaluated: t.Optional[t.Any], var_map: t.Dict[str, str], ): if expr in self.__expr_to_hash: expr_hash = self.__expr_to_hash[expr] gui._bind_var_val(expr_hash, expr_evaluated) return expr_hash if expr_hash is None: expr_hash = _get_expr_var_name(expr) else: # edge case, only a single variable expr_hash = f"tpec_{_get_client_var_name(expr)}" self.__expr_to_hash[expr] = expr_hash gui._bind_var_val(expr_hash, expr_evaluated) self.__hash_to_expr[expr_hash] = expr for var in var_map.values(): if var not in self.__global_ctx.keys(): lst = self.__var_to_expr_list.get(var) if lst is None: self.__var_to_expr_list[var] = [expr] else: lst.append(expr) if expr not in self.__expr_to_var_map: self.__expr_to_var_map[expr] = var_map # save expr_hash to shared variable if valid for encoded_var_name in var_map.values(): var_name, module_name = _variable_decode(encoded_var_name) # only variables in the main module with be taken into account if module_name is not None and module_name != gui._get_default_module_name(): continue if var_name in self.__shared_variable: self.__shared_variable.append(expr_hash) return expr_hash def evaluate_bind_holder(self, gui: Gui, holder: t.Type[_TaipyBase], expr: str) -> str: expr_hash = self.__expr_to_hash.get(expr, "unknownExpr") hash_name = self.__get_holder_hash(holder, expr_hash) expr_lit = expr.replace("'", "\\'") holder_expr = f"{holder.__name__}({expr},'{expr_lit}')" self.__evaluate_holder(gui, holder, expr) if a_set := self.__expr_to_holders.get(expr): a_set.add(holder) else: self.__expr_to_holders[expr] = {holder} self.__expr_to_hash[holder_expr] = hash_name # expression is only the first part ... expr = expr.split(".")[0] self.__expr_to_var_map[holder_expr] = {expr: expr} if a_list := self.__var_to_expr_list.get(expr): if holder_expr not in a_list: a_list.append(holder_expr) else: self.__var_to_expr_list[expr] = [holder_expr] return hash_name def evaluate_holders(self, gui: Gui, expr: str) -> t.List[str]: lst = [] for hld in self.__expr_to_holders.get(expr, []): hash_val = self.__get_holder_hash(hld, self.__expr_to_hash.get(expr, "")) self.__evaluate_holder(gui, hld, expr) lst.append(hash_val) return lst @staticmethod def __get_holder_hash(holder: t.Type[_TaipyBase], expr_hash: str) -> str: return f"{holder.get_hash()}_{_get_client_var_name(expr_hash)}" def __evaluate_holder(self, gui: Gui, holder: t.Type[_TaipyBase], expr: str) -> t.Optional[_TaipyBase]: try: expr_hash = self.__expr_to_hash.get(expr, "unknownExpr") holder_hash = self.__get_holder_hash(holder, expr_hash) expr_value = _getscopeattr_drill(gui, expr_hash) holder_value = _getscopeattr(gui, holder_hash, None) if not isinstance(holder_value, _TaipyBase): holder_value = holder(expr_value, expr_hash) _setscopeattr(gui, holder_hash, holder_value) else: holder_value.set(expr_value) return holder_value except Exception as e: _warn(f"Cannot evaluate expression {holder.__name__}({expr_hash},'{expr_hash}') for {expr}", e) return None def evaluate_expr(self, gui: Gui, expr: str) -> t.Any: if not self._is_expression(expr): return expr var_val, var_map = self._analyze_expression(gui, expr) expr_hash = None is_edge_case = False # The expr_string is placed here in case expr get replaced by edge case expr_string = 'f"' + expr.replace('"', '\\"') + '"' # simplify expression if it only contains var_name m = _Evaluator.__EXPR_IS_EDGE_CASE.match(expr) if m and not _Evaluator.__EXPR_EDGE_CASE_F_STRING.match(expr): expr = m.group(1) expr_hash = expr if _Evaluator.__EXPR_VALID_VAR_EDGE_CASE.match(expr) else None is_edge_case = True # validate whether expression has already been evaluated module_name = gui._get_locals_context() not_encoded_expr = expr expr = f"TpExPr_{_variable_encode(expr, module_name)}" if expr in self.__expr_to_hash and _hasscopeattr(gui, self.__expr_to_hash[expr]): return self.__expr_to_hash[expr] try: # evaluate expressions ctx: t.Dict[str, t.Any] = {} ctx.update(self.__global_ctx) # entries in var_val are not always seen (NameError) when passed as locals ctx.update(var_val) expr_evaluated = eval(not_encoded_expr if is_edge_case else expr_string, ctx) except Exception as e: _warn(f"Cannot evaluate expression '{not_encoded_expr if is_edge_case else expr_string}'", e) expr_evaluated = None # save the expression if it needs to be re-evaluated return self.__save_expression(gui, expr, expr_hash, expr_evaluated, var_map) def refresh_expr(self, gui: Gui, var_name: str, holder: t.Optional[_TaipyBase]): """ This function will execute when the __request_var_update function receive a refresh order """ expr = self.__hash_to_expr.get(var_name) if expr: expr_decoded, _ = _variable_decode(expr) var_map = self.__expr_to_var_map.get(expr, {}) eval_dict = {k: _getscopeattr_drill(gui, gui._bind_var(v)) for k, v in var_map.items()} if self._is_expression(expr_decoded): expr_string = 'f"' + _variable_decode(expr)[0].replace('"', '\\"') + '"' else: expr_string = expr_decoded try: ctx: t.Dict[str, t.Any] = {} ctx.update(self.__global_ctx) ctx.update(eval_dict) expr_evaluated = eval(expr_string, ctx) _setscopeattr(gui, var_name, expr_evaluated) if holder is not None: holder.set(expr_evaluated) except Exception as e: _warn(f"Exception raised evaluating {expr_string}", e) def re_evaluate_expr(self, gui: Gui, var_name: str) -> t.Set[str]: """ This function will execute when the _update_var function is handling an expression with only a single variable """ modified_vars: t.Set[str] = set() # Verify that the current hash is an edge case one (only a single variable inside the original expression) if var_name.startswith("tp_"): return modified_vars expr_original = None # if var_name starts with tpec_ --> it is an edge case with modified var if var_name.startswith("tpec_"): # backup for later reference var_name_original = var_name expr_original = self.__hash_to_expr[var_name] temp_expr_var_map = self.__expr_to_var_map[expr_original] if len(temp_expr_var_map) <= 1: # since this is an edge case --> only 1 item in the dict and that item is the original var for v in temp_expr_var_map.values(): var_name = v # construct correct var_path to reassign values var_name_full, _ = _variable_decode(expr_original) var_name_full = var_name_full.split(".") var_name_full[0] = var_name var_name_full = ".".join(var_name_full) _setscopeattr_drill(gui, var_name_full, _getscopeattr(gui, var_name_original)) else: # multiple key-value pair in expr_var_map --> expr is special case a["b"] key = "" for v in temp_expr_var_map.values(): if isinstance(_getscopeattr(gui, v), _MapDict): var_name = v else: key = v if key == "": return modified_vars _setscopeattr_drill(gui, f"{var_name}.{_getscopeattr(gui, key)}", _getscopeattr(gui, var_name_original)) # A middle check to see if var_name is from _MapDict if "." in var_name: var_name = var_name[: var_name.index(".")] # otherwise, thar var_name is correct and doesn't require any resolution if var_name not in self.__var_to_expr_list: # _warn("{var_name} not found.") return modified_vars # refresh expressions and holders for expr in self.__var_to_expr_list[var_name]: expr_decoded, _ = _variable_decode(expr) hash_expr = self.__expr_to_hash.get(expr, "UnknownExpr") if expr != var_name and not expr.startswith(_TaipyBase._HOLDER_PREFIX): expr_var_map = self.__expr_to_var_map.get(expr) # ["x", "y"] if expr_var_map is None: _warn(f"Something is amiss with expression list for {expr}.") else: eval_dict = {k: _getscopeattr_drill(gui, gui._bind_var(v)) for k, v in expr_var_map.items()} if self._is_expression(expr_decoded): expr_string = 'f"' + _variable_decode(expr)[0].replace('"', '\\"') + '"' else: expr_string = expr_decoded try: ctx: t.Dict[str, t.Any] = {} ctx.update(self.__global_ctx) ctx.update(eval_dict) expr_evaluated = eval(expr_string, ctx) _setscopeattr(gui, hash_expr, expr_evaluated) except Exception as e: _warn(f"Exception raised evaluating {expr_string}", e) # refresh holders if any for h in self.__expr_to_holders.get(expr, []): holder_hash = self.__get_holder_hash(h, self.get_hash_from_expr(expr)) if holder_hash not in modified_vars: _setscopeattr(gui, holder_hash, self.__evaluate_holder(gui, h, expr)) modified_vars.add(holder_hash) modified_vars.add(hash_expr) return modified_vars def _get_instance_in_context(self, name: str): return self.__global_ctx.get(name)
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 from datetime import datetime from importlib import util import numpy as np import pandas as pd from .._warnings import _warn from ..gui import Gui from ..gui_types import PropertyType from ..utils import _RE_PD_TYPE, _get_date_col_str_name from .data_accessor import _DataAccessor from .data_format import _DataFormat from .utils import _df_data_filter, _df_relayout _has_arrow_module = False if util.find_spec("pyarrow"): _has_arrow_module = True import pyarrow as pa class _PandasDataAccessor(_DataAccessor): __types = (pd.DataFrame,) __INDEX_COL = "_tp_index" __AGGREGATE_FUNCTIONS: t.List[str] = ["count", "sum", "mean", "median", "min", "max", "std", "first", "last"] @staticmethod def get_supported_classes() -> t.List[str]: return [t.__name__ for t in _PandasDataAccessor.__types] # type: ignore @staticmethod def __user_function( row: pd.Series, gui: Gui, column_name: t.Optional[str], user_function: t.Callable, function_name: str ) -> str: # pragma: no cover args = [] if column_name: args.append(row[column_name]) args.extend((row.name, row)) if column_name: args.append(column_name) try: return str(gui._call_function_with_state(user_function, args)) except Exception as e: _warn(f"Exception raised when calling user function {function_name}()", e) return "" def __is_date_column(self, data: pd.DataFrame, col_name: str) -> bool: col_types = data.dtypes[data.dtypes.index.astype(str) == col_name] return len(col_types[col_types.astype(str).str.startswith("datetime")]) > 0 # type: ignore def __build_transferred_cols( self, gui: Gui, payload_cols: t.Any, dataframe: pd.DataFrame, styles: t.Optional[t.Dict[str, str]] = None, tooltips: t.Optional[t.Dict[str, str]] = None, is_copied: t.Optional[bool] = False, new_indexes: t.Optional[np.ndarray] = None, handle_nan: t.Optional[bool] = False, ) -> pd.DataFrame: if isinstance(payload_cols, list) and len(payload_cols): col_types = dataframe.dtypes[dataframe.dtypes.index.astype(str).isin(payload_cols)] else: col_types = dataframe.dtypes cols = col_types.index.astype(str).tolist() if styles: if not is_copied: # copy the df so that we don't "mess" with the user's data dataframe = dataframe.copy() is_copied = True for k, v in styles.items(): col_applied = False func = gui._get_user_function(v) if callable(func): col_applied = self.__apply_user_function(gui, func, k if k in cols else None, v, dataframe, "tps__") if not col_applied: dataframe[v] = v cols.append(col_applied or v) if tooltips: if not is_copied: # copy the df so that we don't "mess" with the user's data dataframe = dataframe.copy() is_copied = True for k, v in tooltips.items(): col_applied = False func = gui._get_user_function(v) if callable(func): col_applied = self.__apply_user_function(gui, func, k if k in cols else None, v, dataframe, "tpt__") cols.append(col_applied or v) # deal with dates datecols = col_types[col_types.astype(str).str.startswith("datetime")].index.tolist() # type: ignore if len(datecols) != 0: if not is_copied: # copy the df so that we don't "mess" with the user's data dataframe = dataframe.copy() tz = Gui._get_timezone() for col in datecols: newcol = _get_date_col_str_name(cols, col) cols.append(newcol) re_type = _RE_PD_TYPE.match(str(col_types[col])) grps = re_type.groups() if re_type else () if len(grps) > 4 and grps[4]: dataframe[newcol] = ( dataframe[col] .dt.tz_convert("UTC") .dt.strftime(_DataAccessor._WS_DATE_FORMAT) .astype(str) .replace("nan", "NaT" if handle_nan else None) ) else: dataframe[newcol] = ( dataframe[col] .dt.tz_localize(tz) .dt.tz_convert("UTC") .dt.strftime(_DataAccessor._WS_DATE_FORMAT) .astype(str) .replace("nan", "NaT" if handle_nan else None) ) # remove the date columns from the list of columns cols = list(set(cols) - set(datecols)) dataframe = dataframe.iloc[new_indexes] if new_indexes is not None else dataframe dataframe = dataframe.loc[ :, dataframe.dtypes[dataframe.dtypes.index.astype(str).isin(cols)].index ] # type: ignore return dataframe def __apply_user_function( self, gui: Gui, user_function: t.Callable, column_name: t.Optional[str], function_name: str, data: pd.DataFrame, prefix: t.Optional[str], ): try: new_col_name = f"{prefix}{column_name}__{function_name}" if column_name else function_name data[new_col_name] = data.apply( _PandasDataAccessor.__user_function, axis=1, args=(gui, column_name, user_function, function_name), ) return new_col_name except Exception as e: _warn(f"Exception raised when invoking user function {function_name}()", e) return False def __format_data( self, data: pd.DataFrame, data_format: _DataFormat, orient: str, start: t.Optional[int] = None, rowcount: t.Optional[int] = None, data_extraction: t.Optional[bool] = None, handle_nan: t.Optional[bool] = False, ) -> t.Dict[str, t.Any]: ret: t.Dict[str, t.Any] = { "format": str(data_format.value), } if rowcount is not None: ret["rowcount"] = rowcount if start is not None: ret["start"] = start if data_extraction is not None: ret["dataExtraction"] = data_extraction # Extract data out of dictionary on front-end if data_format == _DataFormat.APACHE_ARROW: if not _has_arrow_module: raise RuntimeError("Cannot use Arrow as pyarrow package is not installed") # Convert from pandas to Arrow table = pa.Table.from_pandas(data) # Create sink buffer stream sink = pa.BufferOutputStream() # Create Stream writer writer = pa.ipc.new_stream(sink, table.schema) # Write data to table writer.write_table(table) writer.close() # End buffer stream buf = sink.getvalue() # Convert buffer to Python bytes and return ret["data"] = buf.to_pybytes() ret["orient"] = orient else: # Workaround for Python built in JSON encoder that does not yet support ignore_nan ret["data"] = data.replace([np.nan, pd.NA], [None, None]).to_dict(orient=orient) # type: ignore return ret def get_col_types(self, var_name: str, value: t.Any) -> t.Union[None, t.Dict[str, str]]: # type: ignore if isinstance(value, _PandasDataAccessor.__types): # type: ignore return {str(k): v for k, v in value.dtypes.apply(lambda x: x.name.lower()).items()} elif isinstance(value, list): ret_dict: t.Dict[str, str] = {} for i, v in enumerate(value): ret_dict.update({f"{i}/{k}": v for k, v in v.dtypes.apply(lambda x: x.name.lower()).items()}) return ret_dict return None def __get_data( # noqa: C901 self, gui: Gui, var_name: str, value: pd.DataFrame, payload: t.Dict[str, t.Any], data_format: _DataFormat, col_prefix: t.Optional[str] = "", ) -> t.Dict[str, t.Any]: columns = payload.get("columns", []) if col_prefix: columns = [c[len(col_prefix) :] if c.startswith(col_prefix) else c for c in columns] ret_payload = {"pagekey": payload.get("pagekey", "unknown page")} paged = not payload.get("alldata", False) is_copied = False # add index if not chart if paged: if _PandasDataAccessor.__INDEX_COL not in value.columns: value = value.copy() is_copied = True value[_PandasDataAccessor.__INDEX_COL] = value.index if columns and _PandasDataAccessor.__INDEX_COL not in columns: columns.append(_PandasDataAccessor.__INDEX_COL) # filtering filters = payload.get("filters") if isinstance(filters, list) and len(filters) > 0: query = "" vars = [] for fd in filters: col = fd.get("col") val = fd.get("value") action = fd.get("action") if isinstance(val, str): if self.__is_date_column(value, col): val = datetime.fromisoformat(val[:-1]) vars.append(val) val = f"@vars[{len(vars) - 1}]" if isinstance(val, (str, datetime)) else val right = f".str.contains({val})" if action == "contains" else f" {action} {val}" if query: query += " and " query += f"`{col}`{right}" try: value = value.query(query) is_copied = True except Exception as e: _warn(f"Dataframe filtering: invalid query '{query}' on {value.head()}", e) if paged: aggregates = payload.get("aggregates") applies = payload.get("applies") if isinstance(aggregates, list) and len(aggregates) and isinstance(applies, dict): applies_with_fn = { k: v if v in _PandasDataAccessor.__AGGREGATE_FUNCTIONS else gui._get_user_function(v) for k, v in applies.items() } for col in columns: if col not in applies_with_fn.keys(): applies_with_fn[col] = "first" try: value = value.groupby(aggregates).agg(applies_with_fn) except Exception: _warn(f"Cannot aggregate {var_name} with groupby {aggregates} and aggregates {applies}.") inf = payload.get("infinite") if inf is not None: ret_payload["infinite"] = inf # real number of rows is needed to calculate the number of pages rowcount = len(value) # here we'll deal with start and end values from payload if present if isinstance(payload["start"], int): start = int(payload["start"]) else: try: start = int(str(payload["start"]), base=10) except Exception: _warn(f'start should be an int value {payload["start"]}.') start = 0 if isinstance(payload["end"], int): end = int(payload["end"]) else: try: end = int(str(payload["end"]), base=10) except Exception: end = -1 if start < 0 or start >= rowcount: start = 0 if end < 0 or end >= rowcount: end = rowcount - 1 # deal with sort order_by = payload.get("orderby") if isinstance(order_by, str) and len(order_by): try: if value.columns.dtype.name == "int64": order_by = int(order_by) new_indexes = value[order_by].values.argsort(axis=0) if payload.get("sort") == "desc": # reverse order new_indexes = new_indexes[::-1] new_indexes = new_indexes[slice(start, end + 1)] except Exception: _warn(f"Cannot sort {var_name} on columns {order_by}.") new_indexes = slice(start, end + 1) # type: ignore else: new_indexes = slice(start, end + 1) # type: ignore value = self.__build_transferred_cols( gui, columns, value, styles=payload.get("styles"), tooltips=payload.get("tooltips"), is_copied=is_copied, new_indexes=new_indexes, handle_nan=payload.get("handlenan", False), ) dictret = self.__format_data( value, data_format, "records", start, rowcount, handle_nan=payload.get("handlenan", False) ) else: ret_payload["alldata"] = True decimator_payload: t.Dict[str, t.Any] = payload.get("decimatorPayload", {}) decimators = decimator_payload.get("decimators", []) nb_rows_max = decimator_payload.get("width") for decimator_pl in decimators: decimator = decimator_pl.get("decimator") decimator_instance = ( gui._get_user_instance(decimator, PropertyType.decimator.value) if decimator is not None else None ) if isinstance(decimator_instance, PropertyType.decimator.value): x_column, y_column, z_column = ( decimator_pl.get("xAxis", ""), decimator_pl.get("yAxis", ""), decimator_pl.get("zAxis", ""), ) chart_mode = decimator_pl.get("chartMode", "") if decimator_instance._zoom and "relayoutData" in decimator_payload and not z_column: relayoutData = decimator_payload.get("relayoutData", {}) x0 = relayoutData.get("xaxis.range[0]") x1 = relayoutData.get("xaxis.range[1]") y0 = relayoutData.get("yaxis.range[0]") y1 = relayoutData.get("yaxis.range[1]") value, is_copied = _df_relayout( value, x_column, y_column, chart_mode, x0, x1, y0, y1, is_copied ) if nb_rows_max and decimator_instance._is_applicable(value, nb_rows_max, chart_mode): try: value, is_copied = _df_data_filter( value, x_column, y_column, z_column, decimator=decimator_instance, payload=decimator_payload, is_copied=is_copied, ) gui._call_on_change(f"{var_name}.{decimator}.nb_rows", len(value)) except Exception as e: _warn(f"Limit rows error with {decimator} for Dataframe", e) value = self.__build_transferred_cols(gui, columns, value, is_copied=is_copied) dictret = self.__format_data(value, data_format, "list", data_extraction=True) ret_payload["value"] = dictret return ret_payload def get_data( self, gui: Gui, var_name: str, value: t.Any, payload: t.Dict[str, t.Any], data_format: _DataFormat ) -> t.Dict[str, t.Any]: if isinstance(value, list): # If is_chart data if payload.get("alldata", False): ret_payload = { "alldata": True, "value": {"multi": True}, "pagekey": payload.get("pagekey", "unknown page"), } data = [] for i, v in enumerate(value): ret = ( self.__get_data(gui, var_name, v, payload, data_format, f"{i}/") if isinstance(v, pd.DataFrame) else {} ) ret_val = ret.get("value", {}) data.append(ret_val.pop("data", None)) ret_payload.get("value", {}).update(ret_val) ret_payload["value"]["data"] = data return ret_payload else: value = value[0] if isinstance(value, _PandasDataAccessor.__types): # type: ignore return self.__get_data(gui, var_name, value, payload, data_format) return {}
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()