text
stringlengths
0
24.9k
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 d...
# # 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 u...
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...
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. ...
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): ...
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 s...
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) -> IssueColle...
# # 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 u...
# 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 unde...
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): ...
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 freq...
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 u...
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 Inv...
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(...
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__: ...
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 __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:...
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"...
# # 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 u...
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 _Confi...
# # 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 u...
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...
from ._cli import _CLI
"""The setup script.""" import json import os from setuptools import find_namespace_packages, find_packages, setup with open("README.md", "rb") as readme_file: readme = readme_file.read().decode("UTF-8") with open(f"src{os.sep}taipy{os.sep}templates{os.sep}version.json") as version_file: version ...
import os import pytest from cookiecutter.exceptions import FailedHookException from cookiecutter.main import cookiecutter from .utils import _run_template def test_default_answer(tmpdir): cookiecutter( template="src/taipy/templates/default", output_dir=str(tmpdir), no_input...
# # 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 u...
import subprocess import sys def _run_template(main_path, time_out=30): """Run the templates on a subprocess and get stdout after timeout""" with subprocess.Popen([sys.executable, main_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc: try: stdout, stderr = proc.commun...
import os from cookiecutter.main import cookiecutter from .utils import _run_template def test_scenario_management_with_toml_config(tmpdir): cookiecutter( template="src/taipy/templates/scenario-management", output_dir=tmpdir, no_input=True, extra_context={ ...
# # 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 u...
from config.config import configure from pages import job_page, scenario_page from pages.root import content, root, selected_data_node, selected_scenario import taipy as tp from taipy import Core, Gui def on_init(state): ... def on_change(state, var, val): if var == "selected_data_node" and va...
from algos import clean_data from taipy import Config, Frequency, Scope def configure(): # ################################################################################################################## # PLACEHOLDER: Add your scenario configurations here ...
from taipy import Config def configure(): Config.load("config/config.toml") return Config.scenarios["scenario_configuration"]
def clean_data(df, replacement_type): df = df.fillna(replacement_type) return df
from .algos import clean_data
from .scenario_page import scenario_page from .job_page import job_page
from taipy.gui import Markdown selected_scenario = None selected_data_node = None content = "" root = Markdown("pages/root.md")
from .job_page import job_page
from taipy.gui import Markdown job_page = Markdown("pages/job_page/job_page.md")
from taipy.gui import Markdown, notify from .data_node_management import manage_partial def notify_on_submission(state, submitable, details): if details['submission_status'] == 'COMPLETED': notify(state, "success", "Submision completed!") elif details['submission_status'] == 'FAILED': ...
from .scenario_page import scenario_page
# build partial content for a specific data node def build_dn_partial(dn, dn_label): partial_content = "<|part|render={selected_scenario}|\n\n" # ################################################################################################################## # PLACEHOLDER: data node specific content...
import os import taipy # Add taipy version to requirements.txt with open(os.path.join(os.getcwd(), "requirements.txt"), "a") as requirement_file: requirement_file.write(f"taipy=={taipy.version._get_version()}\n") # Use TOML config file or not use_toml_config = "{{ cookiecutter.__use_toml_config }}".uppe...
""" Contain the application's configuration including the scenario configurations. The configuration is run by the Core service. """ from algorithms import * from taipy import Config # ############################################################################# # PLACEHOLDER: Put your application's conf...
from .config import *
""" This file is designed to contain the various Python functions used to configure tasks. The functions will be imported by the __init__.py file in this folder. """ # ################################################################################################################## # PLACEHOLDER: Put your Pyth...
from algorithms import *
from .root import root_page
""" The root page of the application. Page content is imported from the root.md file. Please refer to https://docs.taipy.io/en/latest/manuals/gui/pages for more details. """ from taipy.gui import Markdown root_page = Markdown("pages/root.md")
""" A page of the application. Page content is imported from the page_example.md file. Please refer to https://docs.taipy.io/en/latest/manuals/gui/pages for more details. """ from taipy.gui import Markdown page_example = Markdown("pages/page_example/page_example.md")
import sys pages = "{{ cookiecutter.__pages }}".split(" ") # Remove empty string from pages list pages = [page for page in pages if page != ""] for page in pages: if not page.isidentifier(): sys.exit(f'Page name "{page}" is not a valid Python identifier. Please choose another name.')
import os import shutil import taipy def handle_services(use_rest, use_core): if use_core or use_rest: # Write "import taipy as tp" at the third line of the import.txt file with open(os.path.join(os.getcwd(), "sections", "import.txt"), "r") as import_file: import_lines = imp...
import os import threading from flask import Flask from pyngrok import ngrok from hf_hub_ctranslate2 import GeneratorCT2fromHfHub from flask import request, jsonify model_name = "taipy5-ct2" # note this is local folder model, the model uploaded to huggingface did not response correctly #model_name = "micha...
import os import json def tokenize_code(code, max_characters=256): """ Tokenize code into snippets of specified max_characters, breaking at new lines. """ lines = code.split('\n') snippets = [] current_snippet = "" for line in lines: if len(current_snippet) + len(line) ...
from taipy.gui import Gui from tensorflow.keras import models from PIL import Image import numpy as np model = models.load_model("assets/baseline.keras") class_names = { 0: "airplane", 1: "automobile", 2: "bird", 3: "cat", 4: "deer", 5: "dog", 6: "frog", 7: "horse", ...
from taipy.gui import Gui from tensorflow.keras import models from PIL import Image import numpy as np model = models.load_model("baseline_mariya.keras") class_names = { 0: "airplane", 1: "automobile", 2: "bird", 3: "cat", 4: "deer", 5: "dog", 6: "frog", 7: "horse", ...
print("Hello, World!") print("Hi Taipy!")
# # 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 u...
from unittest import mock import pytest from flask import url_for from src.taipy.rest.api.exceptions.exceptions import ScenarioIdMissingException, SequenceNameMissingException from taipy.core.exceptions.exceptions import NonExistingScenario from taipy.core.scenario._scenario_manager_factory import _ScenarioMan...
from unittest import mock from flask import url_for def test_get_job(client, default_job): # test 404 user_url = url_for("api.job_by_id", job_id="foo") rep = client.get(user_url) assert rep.status_code == 404 with mock.patch("taipy.core.job._job_manager._JobManager._get") as manager_m...
import os import shutil import uuid from datetime import datetime, timedelta import pandas as pd import pytest from dotenv import load_dotenv from src.taipy.rest.app import create_app from taipy.config import Config from taipy.config.common.frequency import Frequency from taipy.config.common.scope import ...
from unittest import mock from flask import url_for def test_get_task(client, default_task): # test 404 user_url = url_for("api.task_by_id", task_id="foo") rep = client.get(user_url) assert rep.status_code == 404 with mock.patch("taipy.core.task._task_manager._TaskManager._get") as ma...
from functools import wraps from unittest.mock import MagicMock, patch from src.taipy.rest.api.middlewares._middleware import _middleware def mock_enterprise_middleware(f): @wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) return wrapper @patch("src.taipy.rest.api...
from unittest import mock import pytest from flask import url_for def test_get_datanode(client, default_datanode): # test 404 user_url = url_for("api.datanode_by_id", datanode_id="foo") rep = client.get(user_url) assert rep.status_code == 404 with mock.patch("taipy.core.data._data_ma...
# # 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 u...
import json from typing import Dict from flask import url_for def create_and_submit_scenario(config_id: str, client) -> Dict: response = client.post(url_for("api.scenarios", config_id=config_id)) assert response.status_code == 201 scenario = response.json.get("scenario") assert (set(scena...
from unittest import mock from flask import url_for def test_get_cycle(client, default_cycle): # test 404 cycle_url = url_for("api.cycle_by_id", cycle_id="foo") rep = client.get(cycle_url) assert rep.status_code == 404 with mock.patch("taipy.core.cycle._cycle_manager._CycleManager._ge...
from unittest import mock import pytest from flask import url_for def test_get_scenario(client, default_scenario): # test 404 user_url = url_for("api.scenario_by_id", scenario_id="foo") rep = client.get(user_url) assert rep.status_code == 404 with mock.patch("taipy.core.scenario._sce...
# # 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 u...
import pickle import random from datetime import datetime, timedelta from typing import Any, Dict import pandas as pd n_predictions = 14 def forecast(model, date: datetime): dates = [date + timedelta(days=i) for i in range(n_predictions)] forecasts = [f + random.uniform(0, 2) for f in model.fore...
from taipy.core import Config, Frequency from .algorithms import evaluate, forecast model_cfg = Config.configure_data_node("model", path="my_model.p", storage_type="pickle") day_cfg = Config.configure_data_node(id="day") forecasts_cfg = Config.configure_data_node(id="forecasts") forecast_task_cfg = Config.co...
# # 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 u...
from importlib.util import find_spec if find_spec("taipy"): if find_spec("taipy.config"): from taipy.config._init import * # type: ignore if find_spec("taipy.gui"): from taipy.gui._init import * # type: ignore if find_spec("taipy.core"): from taipy.core._init import * ...
import json import os def _get_version(): with open(f"{os.path.dirname(os.path.abspath(__file__))}{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 := v...
from .rest import Rest
# # 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 u...
"""# Taipy Rest The Taipy Rest package exposes the Runnable `Rest^` service to provide REST APIs on top of Taipy Core. (more details on Taipy Core functionalities in the [user manual](../../../manuals/core/)). Once the `Rest^` service runs, users can call REST APIs to create, read, update, submit and remove Taip...
"""Extensions registry All extensions here are used as singletons and initialized in application factory """ from .commons.apispec import APISpecExt apispec = APISpecExt()
import os from flask import Flask from . import api from .commons.encoder import _CustomEncoder from .extensions import apispec def create_app(testing=False, flask_env=None, secret_key=None): """Application factory, used to create application""" app = Flask(__name__) app.config.update( ...
from taipy.core.cycle._cycle_converter import _CycleConverter from taipy.core.data._data_converter import _DataNodeConverter from taipy.core.scenario._scenario_converter import _ScenarioConverter from taipy.core.sequence._sequence_converter import _SequenceConverter from taipy.core.task._task_converter import _Task...
# # 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 u...
from apispec import APISpec from apispec.exceptions import APISpecError from apispec.ext.marshmallow import MarshmallowPlugin from apispec_webframeworks.flask import FlaskPlugin from flask import Blueprint, jsonify, render_template class FlaskRestfulPlugin(FlaskPlugin): """Small plugin override to handle ...
import json from typing import Any, Union from datetime import datetime from enum import Enum Json = Union[dict, list, str, int, float, bool, None] class _CustomEncoder(json.JSONEncoder): def default(self, o: Any) -> Json: if isinstance(o, Enum): result = o.value elif is...
"""Simple helper to paginate query """ from flask import request, url_for DEFAULT_PAGE_SIZE = 50 DEFAULT_PAGE_NUMBER = 1 def extract_pagination(page=None, per_page=None, **request_args): page = int(page) if page is not None else DEFAULT_PAGE_NUMBER per_page = int(per_page) if per_page is not None e...
from . import error_handler, views __all__ = ["views", "error_handler"]
from flask import jsonify from marshmallow import ValidationError from taipy.core.exceptions.exceptions import ( NonExistingCycle, NonExistingDataNode, NonExistingDataNodeConfig, NonExistingJob, NonExistingScenario, NonExistingScenarioConfig, NonExistingSequence, NonExistingS...
from flask import Blueprint, current_app from flask_restful import Api from taipy.core.common._utils import _load_fct from taipy.logger._taipy_logger import _TaipyLogger from ..extensions import apispec from .middlewares._middleware import _using_enterprise from .resources import ( CycleList, CycleR...
from datetime import datetime from flask import request from flask_restful import Resource from taipy.config.common.frequency import Frequency from taipy.core import Cycle from taipy.core.cycle._cycle_manager_factory import _CycleManagerFactory from taipy.core.exceptions.exceptions import NonExistingCycle ...
from flask import request from flask_restful import Resource from taipy.config.config import Config from taipy.core.exceptions.exceptions import NonExistingTask, NonExistingTaskConfig from taipy.core.task._task_manager_factory import _TaskManagerFactory from ...commons.to_from_model import _to_model from ..ex...
import uuid from typing import Optional from flask import request from flask_restful import Resource from taipy.config.config import Config from taipy.core import Job, JobId from taipy.core.exceptions.exceptions import NonExistingJob, NonExistingTaskConfig from taipy.core.job._job_manager_factory import _Job...
from flask import request from flask_restful import Resource from taipy.core.exceptions.exceptions import NonExistingScenario, NonExistingSequence from taipy.core.scenario._scenario_manager_factory import _ScenarioManagerFactory from taipy.core.sequence._sequence_manager_factory import _SequenceManagerFactory ...
from .cycle import CycleList, CycleResource from .datanode import DataNodeList, DataNodeReader, DataNodeResource, DataNodeWriter from .job import JobExecutor, JobList, JobResource from .scenario import ScenarioExecutor, ScenarioList, ScenarioResource from .sequence import SequenceExecutor, SequenceList, SequenceRes...
from typing import List import numpy as np import pandas as pd from flask import request from flask_restful import Resource from taipy.config.config import Config from taipy.core.data._data_manager_factory import _DataManagerFactory from taipy.core.data.operator import Operator from taipy.core.exceptions.ex...
from flask import request from flask_restful import Resource from taipy.config.config import Config from taipy.core.exceptions.exceptions import NonExistingScenario, NonExistingScenarioConfig from taipy.core.scenario._scenario_manager_factory import _ScenarioManagerFactory from ...commons.to_from_model import ...
# # 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 u...
from functools import wraps from importlib import util from taipy.core.common._utils import _load_fct def _middleware(f): @wraps(f) def wrapper(*args, **kwargs): if _using_enterprise(): return _enterprise_middleware()(f)(*args, **kwargs) else: return f(*arg...