From a90a5015c46c5d1c4589a4dd04405348db335d9f Mon Sep 17 00:00:00 2001 From: zhuzhongshu123 Date: Fri, 20 Dec 2024 11:35:03 +0800 Subject: [PATCH 1/9] several components can be null for default chain --- kag/builder/default_chain.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/kag/builder/default_chain.py b/kag/builder/default_chain.py index cf925635..7ccce54c 100644 --- a/kag/builder/default_chain.py +++ b/kag/builder/default_chain.py @@ -94,9 +94,9 @@ def __init__( self, reader: ReaderABC, splitter: SplitterABC, - extractor: ExtractorABC, - vectorizer: VectorizerABC, - writer: SinkWriterABC, + extractor: ExtractorABC = None, + vectorizer: VectorizerABC = None, + writer: SinkWriterABC = None, post_processor: PostProcessorABC = None, ): """ From 1d7a44b51ab93a6b04e0a463155274d4527017df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=94=A6=E5=91=88?= Date: Tue, 24 Dec 2024 13:36:25 +0800 Subject: [PATCH 2/9] fix md reader dup in test --- kag/builder/component/reader/markdown_reader.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/kag/builder/component/reader/markdown_reader.py b/kag/builder/component/reader/markdown_reader.py index 8dbc0050..efd10832 100644 --- a/kag/builder/component/reader/markdown_reader.py +++ b/kag/builder/component/reader/markdown_reader.py @@ -131,7 +131,7 @@ def process_text_with_links(element): current_content = [] # Traverse all elements - for element in soup.find_all( + all_elements = soup.find_all( [ "h1", "h2", @@ -147,7 +147,8 @@ def process_text_with_links(element): "pre", "code", ] - ): + ) + for element in all_elements: if element.name.startswith("h") and not is_in_code_block(element): # Only process headers that are not in code blocks # Handle title logic @@ -166,7 +167,7 @@ def process_text_with_links(element): stack[-1].children.append(new_node) stack.append(new_node) - elif element.name in ["pre", "code"]: + elif element.name in ["code"]: # Preserve code blocks as is text = element.get_text() if text: From c93600a486d696a195f2b9a922d2cee77802dd83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=94=A6=E5=91=88?= Date: Tue, 24 Dec 2024 13:37:22 +0800 Subject: [PATCH 3/9] fix --- kag/builder/runner.py | 1 + kag/examples/2wiki/builder/indexer.py | 4 +++- kag/interface/common/vectorize_model.py | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/kag/builder/runner.py b/kag/builder/runner.py index a8bc9d8f..7825cb68 100644 --- a/kag/builder/runner.py +++ b/kag/builder/runner.py @@ -143,6 +143,7 @@ def process(data, data_id, data_abstract): futures = [] print(f"Processing {input}") + success = 0 try: with ThreadPoolExecutor(self.num_chains) as executor: for item in self.scanner.generate(input): diff --git a/kag/examples/2wiki/builder/indexer.py b/kag/examples/2wiki/builder/indexer.py index 5194e987..6b2b611a 100644 --- a/kag/examples/2wiki/builder/indexer.py +++ b/kag/examples/2wiki/builder/indexer.py @@ -8,6 +8,7 @@ # 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. +import os import logging from kag.common.registry import import_modules_from_path @@ -27,6 +28,7 @@ def buildKB(file_path): if __name__ == "__main__": import_modules_from_path(".") - file_path = "./data/2wiki_sub_corpus.json" + dir_path = os.path.dirname(__file__) + file_path = os.path.join(dir_path, "data/2wiki_sub_corpus.json") buildKB(file_path) diff --git a/kag/interface/common/vectorize_model.py b/kag/interface/common/vectorize_model.py index 920da783..69118d2b 100644 --- a/kag/interface/common/vectorize_model.py +++ b/kag/interface/common/vectorize_model.py @@ -69,7 +69,7 @@ def get_vector_dimensions(self): Raises: RuntimeError: If the embedding service is not available. """ - if self._vector_dimensions is not None: + if hasattr(self, "_vector_dimensions"): return int(self._vector_dimensions) try: example_input = "This is a test." From 29865dbbed59adbae4139b094a259e80295fc67e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=94=A6=E5=91=88?= Date: Tue, 24 Dec 2024 13:38:20 +0800 Subject: [PATCH 4/9] merge knext to kag parallel --- knext/__init__.py | 14 + knext/builder/__init__.py | 10 + knext/builder/builder_chain_abc.py | 26 + knext/builder/client.py | 38 + knext/builder/operator/__init__.py | 11 + knext/builder/operator/base.py | 78 + knext/builder/rest/__init__.py | 33 + knext/builder/rest/builder_api.py | 163 ++ knext/builder/rest/models/__init__.py | 14 + .../rest/models/writer_graph_request.py | 218 +++ knext/command/__init__.py | 10 + knext/command/exception.py | 21 + knext/command/knext_cli.py | 85 + knext/command/sub_command/__init__.py | 10 + knext/command/sub_command/builder.py | 11 + knext/command/sub_command/project.py | 240 +++ knext/command/sub_command/reasoner.py | 39 + knext/command/sub_command/schema.py | 54 + knext/command/sub_command/thinker.py | 28 + knext/common/__init__.py | 11 + knext/common/base/__init__.py | 11 + knext/common/base/chain.py | 169 ++ knext/common/base/client.py | 61 + knext/common/base/component.py | 120 ++ knext/common/base/restable.py | 61 + knext/common/base/runnable.py | 90 + knext/common/cache.py | 42 + knext/common/env.py | 142 ++ knext/common/rest/__init__.py | 21 + knext/common/rest/api_client.py | 774 +++++++++ knext/common/rest/configuration.py | 395 +++++ knext/common/rest/exceptions.py | 127 ++ knext/common/rest/models.py | 10 + knext/common/rest/models/__init__.py | 18 + knext/common/rest/rest.py | 396 +++++ knext/common/utils.py | 205 +++ knext/graph/__init__.py | 56 + knext/graph/client.py | 102 ++ knext/graph/rest/__init__.py | 56 + knext/graph/rest/graph_api.py | 991 +++++++++++ knext/graph/rest/models/__init__.py | 40 + .../graph/rest/models/delete_edge_request.py | 165 ++ .../rest/models/delete_vertex_request.py | 165 ++ knext/graph/rest/models/edge_record.py | 245 +++ .../graph/rest/models/edge_record_instance.py | 302 ++++ knext/graph/rest/models/edge_type_name.py | 208 +++ .../rest/models/expend_one_hop_request.py | 232 +++ .../rest/models/expend_one_hop_response.py | 191 +++ .../models/get_page_rank_scores_request.py | 207 +++ ...et_page_rank_scores_request_start_nodes.py | 226 +++ .../graph/rest/models/lpg_property_record.py | 160 ++ .../rest/models/page_rank_score_instance.py | 192 +++ .../graph/rest/models/query_vertex_request.py | 202 +++ .../rest/models/query_vertex_response.py | 129 ++ .../graph/rest/models/upsert_edge_request.py | 207 +++ .../rest/models/upsert_vertex_request.py | 165 ++ knext/graph/rest/models/vertex_record.py | 218 +++ .../rest/models/vertex_record_instance.py | 236 +++ .../graph/rest/models/writer_graph_request.py | 218 +++ knext/project/__init__.py | 16 + knext/project/client.py | 76 + knext/project/rest/__init__.py | 34 + knext/project/rest/models/__init__.py | 15 + knext/project/rest/models/project.py | 272 +++ .../rest/models/project_create_request.py | 299 ++++ knext/project/rest/project_api.py | 507 ++++++ knext/reasoner/__init__.py | 37 + knext/reasoner/client.py | 150 ++ knext/reasoner/lib/__init__.py | 18 + knext/reasoner/rest/__init__.py | 36 + knext/reasoner/rest/models/__init__.py | 33 + knext/reasoner/rest/models/ca_pipeline.py | 155 ++ knext/reasoner/rest/models/edge.py | 155 ++ knext/reasoner/rest/models/node.py | 245 +++ .../rest/models/reason_markdown_request.py | 156 ++ knext/reasoner/rest/models/reason_task.py | 363 ++++ .../rest/models/reason_task_response.py | 160 ++ .../rest/models/report_pipeline_request.py | 179 ++ .../reasoner/rest/models/spg_type_instance.py | 187 +++ .../rest/models/spg_type_query_request.py | 194 +++ knext/reasoner/rest/models/table_result.py | 194 +++ knext/reasoner/rest/reasoner_api.py | 777 +++++++++ knext/schema/__init__.py | 11 + knext/schema/client.py | 182 ++ knext/schema/marklang/__init__.py | 11 + knext/schema/marklang/concept_rule_ml.py | 488 ++++++ knext/schema/marklang/schema_ml.py | 1479 +++++++++++++++++ knext/schema/model/__init__.py | 10 + knext/schema/model/base.py | 920 ++++++++++ knext/schema/model/property.py | 60 + knext/schema/model/relation.py | 68 + knext/schema/model/schema_helper.py | 50 + knext/schema/model/spg_type.py | 295 ++++ knext/schema/rest/__init__.py | 118 ++ knext/schema/rest/concept_api.py | 533 ++++++ knext/schema/rest/models/__init__.py | 98 ++ knext/schema/rest/models/alter/__init__.py | 10 + .../rest/models/alter/schema_alter_request.py | 166 ++ .../schema/rest/models/alter/schema_draft.py | 131 ++ knext/schema/rest/models/base_ontology.py | 228 +++ knext/schema/rest/models/basic_info.py | 218 +++ knext/schema/rest/models/concept/__init__.py | 10 + .../define_dynamic_taxonomy_request.py | 187 +++ .../define_logical_causation_request.py | 286 ++++ .../remove_dynamic_taxonomy_request.py | 161 ++ .../remove_logical_causation_request.py | 259 +++ .../schema/rest/models/constraint/__init__.py | 10 + .../models/constraint/base_constraint_item.py | 162 ++ .../rest/models/constraint/constraint.py | 155 ++ .../rest/models/constraint/enum_constraint.py | 178 ++ .../models/constraint/multi_val_constraint.py | 148 ++ .../models/constraint/not_null_constraint.py | 148 ++ .../models/constraint/regular_constraint.py | 178 ++ .../schema/rest/models/identifier/__init__.py | 10 + .../models/identifier/base_spg_identifier.py | 166 ++ .../models/identifier/concept_identifier.py | 177 ++ .../models/identifier/operator_identifier.py | 177 ++ .../models/identifier/predicate_identifier.py | 177 ++ .../identifier/spg_triple_identifier.py | 240 +++ .../models/identifier/spg_type_identifier.py | 235 +++ knext/schema/rest/models/ontology_id.py | 155 ++ knext/schema/rest/models/operator/__init__.py | 10 + .../operator/operator_create_request.py | 210 +++ .../operator/operator_create_response.py | 161 ++ .../rest/models/operator/operator_overview.py | 266 +++ .../rest/models/operator/operator_version.py | 238 +++ .../operator/operator_version_request.py | 165 ++ .../operator/operator_version_response.py | 167 ++ .../schema/rest/models/predicate/__init__.py | 10 + .../predicate/mounted_concept_config.py | 155 ++ .../schema/rest/models/predicate/property.py | 363 ++++ .../predicate/property_advanced_config.py | 336 ++++ .../rest/models/predicate/property_ref.py | 380 +++++ .../predicate/property_ref_basic_info.py | 223 +++ .../schema/rest/models/predicate/relation.py | 390 +++++ .../rest/models/predicate/sub_property.py | 336 ++++ .../predicate/sub_property_basic_info.py | 218 +++ knext/schema/rest/models/semantic/__init__.py | 10 + .../rest/models/semantic/base_semantic.py | 271 +++ .../rest/models/semantic/logical_rule.py | 309 ++++ .../models/semantic/predicate_semantic.py | 352 ++++ .../schema/rest/models/semantic/rule_code.py | 129 ++ knext/schema/rest/models/type/__init__.py | 10 + .../rest/models/type/base_advanced_type.py | 421 +++++ .../schema/rest/models/type/base_spg_type.py | 424 +++++ knext/schema/rest/models/type/basic_type.py | 454 +++++ .../rest/models/type/concept_layer_config.py | 168 ++ .../models/type/concept_taxonomic_config.py | 131 ++ knext/schema/rest/models/type/concept_type.py | 493 ++++++ knext/schema/rest/models/type/entity_type.py | 412 +++++ knext/schema/rest/models/type/event_type.py | 412 +++++ .../rest/models/type/multi_version_config.py | 179 ++ knext/schema/rest/models/type/operator_key.py | 155 ++ .../rest/models/type/parent_type_info.py | 218 +++ .../schema/rest/models/type/project_schema.py | 129 ++ .../models/type/spg_type_advanced_config.py | 218 +++ knext/schema/rest/models/type/spg_type_ref.py | 171 ++ .../models/type/spg_type_ref_basic_info.py | 217 +++ .../schema/rest/models/type/standard_type.py | 466 ++++++ .../models/type/standard_type_basic_info.py | 218 +++ knext/schema/rest/models/user_info.py | 155 ++ knext/schema/rest/schema_api.py | 571 +++++++ knext/search/__init__.py | 36 + knext/search/client.py | 827 +++++++++ knext/search/rest/__init__.py | 36 + knext/search/rest/models/__init__.py | 21 + knext/search/rest/models/idx_record.py | 226 +++ .../search/rest/models/text_search_request.py | 260 +++ .../rest/models/vector_search_request.py | 327 ++++ knext/search/rest/search_api.py | 281 ++++ knext/thinker/__init__.py | 10 + knext/thinker/client.py | 54 + knext/thinker/rest/__init__.py | 33 + knext/thinker/rest/models/__init__.py | 28 + .../rest/models/thinker_task_request.py | 277 +++ .../rest/models/thinker_task_response.py | 194 +++ knext/thinker/rest/thinker_api.py | 161 ++ requirements.txt | 4 +- setup.py | 2 + 179 files changed, 34318 insertions(+), 2 deletions(-) create mode 100644 knext/__init__.py create mode 100644 knext/builder/__init__.py create mode 100644 knext/builder/builder_chain_abc.py create mode 100644 knext/builder/client.py create mode 100644 knext/builder/operator/__init__.py create mode 100644 knext/builder/operator/base.py create mode 100644 knext/builder/rest/__init__.py create mode 100644 knext/builder/rest/builder_api.py create mode 100644 knext/builder/rest/models/__init__.py create mode 100644 knext/builder/rest/models/writer_graph_request.py create mode 100644 knext/command/__init__.py create mode 100644 knext/command/exception.py create mode 100644 knext/command/knext_cli.py create mode 100644 knext/command/sub_command/__init__.py create mode 100644 knext/command/sub_command/builder.py create mode 100644 knext/command/sub_command/project.py create mode 100644 knext/command/sub_command/reasoner.py create mode 100644 knext/command/sub_command/schema.py create mode 100644 knext/command/sub_command/thinker.py create mode 100644 knext/common/__init__.py create mode 100644 knext/common/base/__init__.py create mode 100644 knext/common/base/chain.py create mode 100644 knext/common/base/client.py create mode 100644 knext/common/base/component.py create mode 100644 knext/common/base/restable.py create mode 100644 knext/common/base/runnable.py create mode 100644 knext/common/cache.py create mode 100644 knext/common/env.py create mode 100644 knext/common/rest/__init__.py create mode 100644 knext/common/rest/api_client.py create mode 100644 knext/common/rest/configuration.py create mode 100644 knext/common/rest/exceptions.py create mode 100644 knext/common/rest/models.py create mode 100644 knext/common/rest/models/__init__.py create mode 100644 knext/common/rest/rest.py create mode 100644 knext/common/utils.py create mode 100644 knext/graph/__init__.py create mode 100644 knext/graph/client.py create mode 100644 knext/graph/rest/__init__.py create mode 100644 knext/graph/rest/graph_api.py create mode 100644 knext/graph/rest/models/__init__.py create mode 100644 knext/graph/rest/models/delete_edge_request.py create mode 100644 knext/graph/rest/models/delete_vertex_request.py create mode 100644 knext/graph/rest/models/edge_record.py create mode 100644 knext/graph/rest/models/edge_record_instance.py create mode 100644 knext/graph/rest/models/edge_type_name.py create mode 100644 knext/graph/rest/models/expend_one_hop_request.py create mode 100644 knext/graph/rest/models/expend_one_hop_response.py create mode 100644 knext/graph/rest/models/get_page_rank_scores_request.py create mode 100644 knext/graph/rest/models/get_page_rank_scores_request_start_nodes.py create mode 100644 knext/graph/rest/models/lpg_property_record.py create mode 100644 knext/graph/rest/models/page_rank_score_instance.py create mode 100644 knext/graph/rest/models/query_vertex_request.py create mode 100644 knext/graph/rest/models/query_vertex_response.py create mode 100644 knext/graph/rest/models/upsert_edge_request.py create mode 100644 knext/graph/rest/models/upsert_vertex_request.py create mode 100644 knext/graph/rest/models/vertex_record.py create mode 100644 knext/graph/rest/models/vertex_record_instance.py create mode 100644 knext/graph/rest/models/writer_graph_request.py create mode 100644 knext/project/__init__.py create mode 100644 knext/project/client.py create mode 100644 knext/project/rest/__init__.py create mode 100644 knext/project/rest/models/__init__.py create mode 100644 knext/project/rest/models/project.py create mode 100644 knext/project/rest/models/project_create_request.py create mode 100644 knext/project/rest/project_api.py create mode 100644 knext/reasoner/__init__.py create mode 100644 knext/reasoner/client.py create mode 100644 knext/reasoner/lib/__init__.py create mode 100644 knext/reasoner/rest/__init__.py create mode 100644 knext/reasoner/rest/models/__init__.py create mode 100644 knext/reasoner/rest/models/ca_pipeline.py create mode 100644 knext/reasoner/rest/models/edge.py create mode 100644 knext/reasoner/rest/models/node.py create mode 100644 knext/reasoner/rest/models/reason_markdown_request.py create mode 100644 knext/reasoner/rest/models/reason_task.py create mode 100644 knext/reasoner/rest/models/reason_task_response.py create mode 100644 knext/reasoner/rest/models/report_pipeline_request.py create mode 100644 knext/reasoner/rest/models/spg_type_instance.py create mode 100644 knext/reasoner/rest/models/spg_type_query_request.py create mode 100644 knext/reasoner/rest/models/table_result.py create mode 100644 knext/reasoner/rest/reasoner_api.py create mode 100644 knext/schema/__init__.py create mode 100644 knext/schema/client.py create mode 100644 knext/schema/marklang/__init__.py create mode 100644 knext/schema/marklang/concept_rule_ml.py create mode 100644 knext/schema/marklang/schema_ml.py create mode 100644 knext/schema/model/__init__.py create mode 100644 knext/schema/model/base.py create mode 100644 knext/schema/model/property.py create mode 100644 knext/schema/model/relation.py create mode 100644 knext/schema/model/schema_helper.py create mode 100644 knext/schema/model/spg_type.py create mode 100644 knext/schema/rest/__init__.py create mode 100644 knext/schema/rest/concept_api.py create mode 100644 knext/schema/rest/models/__init__.py create mode 100644 knext/schema/rest/models/alter/__init__.py create mode 100644 knext/schema/rest/models/alter/schema_alter_request.py create mode 100644 knext/schema/rest/models/alter/schema_draft.py create mode 100644 knext/schema/rest/models/base_ontology.py create mode 100644 knext/schema/rest/models/basic_info.py create mode 100644 knext/schema/rest/models/concept/__init__.py create mode 100644 knext/schema/rest/models/concept/define_dynamic_taxonomy_request.py create mode 100644 knext/schema/rest/models/concept/define_logical_causation_request.py create mode 100644 knext/schema/rest/models/concept/remove_dynamic_taxonomy_request.py create mode 100644 knext/schema/rest/models/concept/remove_logical_causation_request.py create mode 100644 knext/schema/rest/models/constraint/__init__.py create mode 100644 knext/schema/rest/models/constraint/base_constraint_item.py create mode 100644 knext/schema/rest/models/constraint/constraint.py create mode 100644 knext/schema/rest/models/constraint/enum_constraint.py create mode 100644 knext/schema/rest/models/constraint/multi_val_constraint.py create mode 100644 knext/schema/rest/models/constraint/not_null_constraint.py create mode 100644 knext/schema/rest/models/constraint/regular_constraint.py create mode 100644 knext/schema/rest/models/identifier/__init__.py create mode 100644 knext/schema/rest/models/identifier/base_spg_identifier.py create mode 100644 knext/schema/rest/models/identifier/concept_identifier.py create mode 100644 knext/schema/rest/models/identifier/operator_identifier.py create mode 100644 knext/schema/rest/models/identifier/predicate_identifier.py create mode 100644 knext/schema/rest/models/identifier/spg_triple_identifier.py create mode 100644 knext/schema/rest/models/identifier/spg_type_identifier.py create mode 100644 knext/schema/rest/models/ontology_id.py create mode 100644 knext/schema/rest/models/operator/__init__.py create mode 100644 knext/schema/rest/models/operator/operator_create_request.py create mode 100644 knext/schema/rest/models/operator/operator_create_response.py create mode 100644 knext/schema/rest/models/operator/operator_overview.py create mode 100644 knext/schema/rest/models/operator/operator_version.py create mode 100644 knext/schema/rest/models/operator/operator_version_request.py create mode 100644 knext/schema/rest/models/operator/operator_version_response.py create mode 100644 knext/schema/rest/models/predicate/__init__.py create mode 100644 knext/schema/rest/models/predicate/mounted_concept_config.py create mode 100644 knext/schema/rest/models/predicate/property.py create mode 100644 knext/schema/rest/models/predicate/property_advanced_config.py create mode 100644 knext/schema/rest/models/predicate/property_ref.py create mode 100644 knext/schema/rest/models/predicate/property_ref_basic_info.py create mode 100644 knext/schema/rest/models/predicate/relation.py create mode 100644 knext/schema/rest/models/predicate/sub_property.py create mode 100644 knext/schema/rest/models/predicate/sub_property_basic_info.py create mode 100644 knext/schema/rest/models/semantic/__init__.py create mode 100644 knext/schema/rest/models/semantic/base_semantic.py create mode 100644 knext/schema/rest/models/semantic/logical_rule.py create mode 100644 knext/schema/rest/models/semantic/predicate_semantic.py create mode 100644 knext/schema/rest/models/semantic/rule_code.py create mode 100644 knext/schema/rest/models/type/__init__.py create mode 100644 knext/schema/rest/models/type/base_advanced_type.py create mode 100644 knext/schema/rest/models/type/base_spg_type.py create mode 100644 knext/schema/rest/models/type/basic_type.py create mode 100644 knext/schema/rest/models/type/concept_layer_config.py create mode 100644 knext/schema/rest/models/type/concept_taxonomic_config.py create mode 100644 knext/schema/rest/models/type/concept_type.py create mode 100644 knext/schema/rest/models/type/entity_type.py create mode 100644 knext/schema/rest/models/type/event_type.py create mode 100644 knext/schema/rest/models/type/multi_version_config.py create mode 100644 knext/schema/rest/models/type/operator_key.py create mode 100644 knext/schema/rest/models/type/parent_type_info.py create mode 100644 knext/schema/rest/models/type/project_schema.py create mode 100644 knext/schema/rest/models/type/spg_type_advanced_config.py create mode 100644 knext/schema/rest/models/type/spg_type_ref.py create mode 100644 knext/schema/rest/models/type/spg_type_ref_basic_info.py create mode 100644 knext/schema/rest/models/type/standard_type.py create mode 100644 knext/schema/rest/models/type/standard_type_basic_info.py create mode 100644 knext/schema/rest/models/user_info.py create mode 100644 knext/schema/rest/schema_api.py create mode 100644 knext/search/__init__.py create mode 100644 knext/search/client.py create mode 100644 knext/search/rest/__init__.py create mode 100644 knext/search/rest/models/__init__.py create mode 100644 knext/search/rest/models/idx_record.py create mode 100644 knext/search/rest/models/text_search_request.py create mode 100644 knext/search/rest/models/vector_search_request.py create mode 100644 knext/search/rest/search_api.py create mode 100644 knext/thinker/__init__.py create mode 100644 knext/thinker/client.py create mode 100644 knext/thinker/rest/__init__.py create mode 100644 knext/thinker/rest/models/__init__.py create mode 100644 knext/thinker/rest/models/thinker_task_request.py create mode 100644 knext/thinker/rest/models/thinker_task_response.py create mode 100644 knext/thinker/rest/thinker_api.py diff --git a/knext/__init__.py b/knext/__init__.py new file mode 100644 index 00000000..7ed2edab --- /dev/null +++ b/knext/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. + + +__package_name__ = "openspg-knext" +__version__ = "0.6-beta3" diff --git a/knext/builder/__init__.py b/knext/builder/__init__.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/builder/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/builder/builder_chain_abc.py b/knext/builder/builder_chain_abc.py new file mode 100644 index 00000000..2106b507 --- /dev/null +++ b/knext/builder/builder_chain_abc.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. +from abc import ABC, abstractmethod + +from knext.common.base.chain import Chain + + +class BuilderChainABC(Chain, ABC): + @abstractmethod + def build(self, **kwargs) -> Chain: + raise NotImplementedError( + f"`invoke` is not currently supported for {self.__class__.__name__}." + ) + + def invoke(self, file_path, max_workers=10, **kwargs): + chain = self.build(file_path=file_path, max_workers=max_workers, **kwargs) + chain.invoke(input=file_path, max_workers=max_workers, **kwargs) diff --git a/knext/builder/client.py b/knext/builder/client.py new file mode 100644 index 00000000..8666ae53 --- /dev/null +++ b/knext/builder/client.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. + +from knext.builder import rest +from knext.builder.rest.models.writer_graph_request import WriterGraphRequest +from knext.common.base.client import Client +from knext.common.rest import ApiClient, Configuration + + +class BuilderClient(Client): + """ """ + + def __init__(self, host_addr: str = None, project_id: int = None): + super().__init__(host_addr, project_id) + self._rest_client: rest.BuilderApi = rest.BuilderApi( + api_client=ApiClient(configuration=Configuration(host=host_addr)) + ) + + def write_graph(self, sub_graph: dict, operation: str, lead_to_builder: bool): + request = WriterGraphRequest( + project_id=self._project_id, + sub_graph=sub_graph, + operation=operation, + enable_lead_to=lead_to_builder, + ) + self._rest_client.builder_job_writer_graph_post(writer_graph_request=request) + + def submit(self, builder_job: dict): + pass diff --git a/knext/builder/operator/__init__.py b/knext/builder/operator/__init__.py new file mode 100644 index 00000000..93aa6cd4 --- /dev/null +++ b/knext/builder/operator/__init__.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/builder/operator/base.py b/knext/builder/operator/base.py new file mode 100644 index 00000000..0671af36 --- /dev/null +++ b/knext/builder/operator/base.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. + +from abc import ABC +from typing import Dict, Type + + +class BaseOp(ABC): + """Base class for all user-defined operator functions. + + The execution logic of the operator needs to be implemented in the `eval` method. + """ + + """Operator name.""" + name: str + """Operator description.""" + desc: str = "" + """Operator params.""" + params: Dict[str, str] = None + + _registry = {} + _local_path: str + _module_path: str + _version: int + _has_registered: bool = False + + def __init__(self, params: Dict[str, str] = None): + self.params = params + + def invoke(self, **kwargs): + """Used to implement operator execution logic.""" + raise NotImplementedError( + f"{self.__class__.__name__} need to implement `invoke` method." + ) + + @classmethod + def register(cls, name: str, local_path: str, module_path: str): + """ + Register a class as subclass of BaseOp with name and local_path. + After registration, the subclass object can be inspected by `BaseOp.by_name(op_name)`. + """ + + def add_subclass_to_registry(subclass: Type["BaseOp"]): + subclass.name = name + subclass._local_path = local_path + subclass._module_path = module_path + if name in cls._registry: + raise ValueError( + f"Operator [{name}] conflict in {subclass._local_path} and {cls.by_name(name)._local_path}." + ) + cls._registry[name] = subclass + if hasattr(subclass, "bind_to"): + subclass.__bases__[0].bind_schemas[subclass.bind_to] = name + return subclass + + return add_subclass_to_registry + + @classmethod + def by_name(cls, name: str): + """Reflection from op name to subclass object of BaseOp.""" + if name in cls._registry: + subclass = cls._registry[name] + return subclass + else: + raise ValueError(f"{name} is not a registered name for {cls.__name__}. ") + + @property + def has_registered(self): + return self._has_registered diff --git a/knext/builder/rest/__init__.py b/knext/builder/rest/__init__.py new file mode 100644 index 00000000..13c13574 --- /dev/null +++ b/knext/builder/rest/__init__.py @@ -0,0 +1,33 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +# flake8: noqa + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from __future__ import absolute_import + +__version__ = "1" + +# import apis into sdk package +from knext.builder.rest.builder_api import BuilderApi + +# import models into sdk package +from knext.builder.rest.models.writer_graph_request import WriterGraphRequest diff --git a/knext/builder/rest/builder_api.py b/knext/builder/rest/builder_api.py new file mode 100644 index 00000000..474c2189 --- /dev/null +++ b/knext/builder/rest/builder_api.py @@ -0,0 +1,163 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import re # noqa: F401 + +# python 2 and python 3 compatibility library +import six + +from knext.common.rest.api_client import ApiClient +from knext.common.rest.exceptions import ApiTypeError, ApiValueError # noqa: F401 + + +class BuilderApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def builder_job_writer_graph_post(self, **kwargs): # noqa: E501 + """write_graph # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.builder_job_writer_graph_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param WriterGraphRequest writer_graph_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: object + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.builder_job_writer_graph_post_with_http_info(**kwargs) # noqa: E501 + + def builder_job_writer_graph_post_with_http_info(self, **kwargs): # noqa: E501 + """write_graph # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.builder_job_writer_graph_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param WriterGraphRequest writer_graph_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["writer_graph_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method builder_job_writer_graph_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "writer_graph_request" in local_var_params: + body_params = local_var_params["writer_graph_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/graph/writerGraph", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="object", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) diff --git a/knext/builder/rest/models/__init__.py b/knext/builder/rest/models/__init__.py new file mode 100644 index 00000000..34633d66 --- /dev/null +++ b/knext/builder/rest/models/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. + +from __future__ import absolute_import + +from knext.builder.rest.models.writer_graph_request import WriterGraphRequest diff --git a/knext/builder/rest/models/writer_graph_request.py b/knext/builder/rest/models/writer_graph_request.py new file mode 100644 index 00000000..dca97030 --- /dev/null +++ b/knext/builder/rest/models/writer_graph_request.py @@ -0,0 +1,218 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class WriterGraphRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "project_id": "int", + "operation": "str", + "sub_graph": "object", + "enable_lead_to": "bool", + } + + attribute_map = { + "project_id": "projectId", + "operation": "operation", + "sub_graph": "subGraph", + "enable_lead_to": "enableLeadTo", + } + + def __init__( + self, + project_id=None, + operation=None, + sub_graph=None, + enable_lead_to=None, + local_vars_configuration=None, + ): # noqa: E501 + """WriterGraphRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._operation = None + self._sub_graph = None + self._enable_lead_to = None + self.discriminator = None + + if project_id is not None: + self.project_id = project_id + if operation is not None: + self.operation = operation + if sub_graph is not None: + self.sub_graph = sub_graph + if enable_lead_to is not None: + self.enable_lead_to = enable_lead_to + + @property + def project_id(self): + """Gets the project_id of this WriterGraphRequest. # noqa: E501 + + + :return: The project_id of this WriterGraphRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this WriterGraphRequest. + + + :param project_id: The project_id of this WriterGraphRequest. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def operation(self): + """Gets the operation of this WriterGraphRequest. # noqa: E501 + + + :return: The operation of this WriterGraphRequest. # noqa: E501 + :rtype: str + """ + return self._operation + + @operation.setter + def operation(self, operation): + """Sets the operation of this WriterGraphRequest. + + + :param operation: The operation of this WriterGraphRequest. # noqa: E501 + :type: str + """ + + self._operation = operation + + @property + def sub_graph(self): + """Gets the sub_graph of this WriterGraphRequest. # noqa: E501 + + + :return: The sub_graph of this WriterGraphRequest. # noqa: E501 + :rtype: object + """ + return self._sub_graph + + @sub_graph.setter + def sub_graph(self, sub_graph): + """Sets the sub_graph of this WriterGraphRequest. + + + :param sub_graph: The sub_graph of this WriterGraphRequest. # noqa: E501 + :type: object + """ + + self._sub_graph = sub_graph + + @property + def enable_lead_to(self): + """Gets the enable_lead_to of this WriterGraphRequest. # noqa: E501 + + + :return: The enable_lead_to of this WriterGraphRequest. # noqa: E501 + :rtype: bool + """ + return self._enable_lead_to + + @enable_lead_to.setter + def enable_lead_to(self, enable_lead_to): + """Sets the enable_lead_to of this WriterGraphRequest. + + + :param enable_lead_to: The enable_lead_to of this WriterGraphRequest. # noqa: E501 + :type: bool + """ + + self._enable_lead_to = enable_lead_to + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, WriterGraphRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, WriterGraphRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/command/__init__.py b/knext/command/__init__.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/command/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/command/exception.py b/knext/command/exception.py new file mode 100644 index 00000000..6a81111e --- /dev/null +++ b/knext/command/exception.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. + +from typing import Any +from click import Context, Group + + +class _ApiExceptionHandler(Group): + """Echo exceptions.""" + + def invoke(self, ctx: Context) -> Any: + return super().invoke(ctx) diff --git a/knext/command/knext_cli.py b/knext/command/knext_cli.py new file mode 100644 index 00000000..4cb356cc --- /dev/null +++ b/knext/command/knext_cli.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. + +import click + +# from knext.command.sub_command.builder import execute +from knext.command.sub_command.project import ( + create_project, + restore_project, + update_project, + list_project, +) +from knext.command.sub_command.reasoner import execute_reasoner_job +from knext.command.sub_command.schema import commit_schema +from knext.command.sub_command.schema import reg_concept_rule +from knext.command.exception import _ApiExceptionHandler +from knext import __version__ +from knext.command.sub_command.thinker import execute_thinker_job + + +@click.group(cls=_ApiExceptionHandler) +@click.version_option(__version__) +def _main() -> None: + pass + + +# @_main.group() +# def builder() -> None: +# """Builder client.""" +# pass +# +# +# builder.command("execute")(execute) + + +@_main.group() +def project() -> None: + """Project client.""" + pass + + +project.command("create")(create_project) +project.command("restore")(restore_project) +project.command("update")(update_project) +project.command("list")(list_project) + + +@_main.group() +def schema() -> None: + """Schema client.""" + pass + + +schema.command("commit")(commit_schema) +schema.command("reg_concept_rule")(reg_concept_rule) + + +@_main.group() +def reasoner() -> None: + """Reasoner client.""" + pass + + +reasoner.command("execute")(execute_reasoner_job) + + +@_main.group() +def thinker() -> None: + """Thinker client.""" + pass + + +thinker.command("execute")(execute_thinker_job) + +if __name__ == "__main__": + _main() diff --git a/knext/command/sub_command/__init__.py b/knext/command/sub_command/__init__.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/command/sub_command/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/command/sub_command/builder.py b/knext/command/sub_command/builder.py new file mode 100644 index 00000000..93aa6cd4 --- /dev/null +++ b/knext/command/sub_command/builder.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/command/sub_command/project.py b/knext/command/sub_command/project.py new file mode 100644 index 00000000..056097b8 --- /dev/null +++ b/knext/command/sub_command/project.py @@ -0,0 +1,240 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. +from collections import OrderedDict +import re +import json +import os +import sys +from configparser import ConfigParser +from pathlib import Path +from ruamel.yaml import YAML +from typing import Optional + +import click + +from knext.common.utils import copytree, copyfile +from knext.project.client import ProjectClient + +from knext.common.env import env, DEFAULT_HOST_ADDR +from shutil import copy2 + +yaml = YAML() + + +def _render_template(namespace: str, tmpl: str, **kwargs): + config_path = kwargs.get("config_path", None) + project_dir = Path(namespace) + if not project_dir.exists(): + project_dir.mkdir() + + import kag.templates.project + + src = Path(kag.templates.project.__path__[0]) + copytree( + src, + project_dir.resolve(), + namespace=namespace, + root=namespace, + tmpl=tmpl, + **kwargs, + ) + + import kag.templates.schema + + src = Path(kag.templates.schema.__path__[0]) / f"{{{{{tmpl}}}}}.schema.tmpl" + if not src.exists(): + click.secho( + f"ERROR: No such schema template: {tmpl}.schema.tmpl", + fg="bright_red", + ) + dst = project_dir.resolve() / "schema" / f"{{{{{tmpl}}}}}.schema.tmpl" + copyfile(src, dst, namespace=namespace, **{tmpl: namespace}) + + tmpls = [tmpl, "default"] if tmpl != "default" else [tmpl] + # find all .cfg files in project dir + config = yaml.load(Path(config_path).read_text() or "{}") + project_id = kwargs.get("id", None) + config["project"]["id"] = project_id + config_file_path = project_dir.resolve() / "kag_config.yaml" + with open(config_file_path, "w") as config_file: + yaml.dump(config, config_file) + return project_dir + + +def _recover_project(prj_path: str): + """ + Recover project by a project dir path. + """ + if not Path(prj_path).exists(): + click.secho(f"ERROR: No such directory: {prj_path}", fg="bright_red") + sys.exit() + + project_name = env.project_config.get("namespace", None) + namespace = env.project_config.get("namespace", None) + desc = env.project_config.get("description", None) + if not namespace: + click.secho( + f"ERROR: No project namespace found in {env.config_path}.", + fg="bright_red", + ) + sys.exit() + + client = ProjectClient() + project = client.get(namespace=namespace) or client.create( + name=project_name, desc=desc, namespace=namespace + ) + + env.config["project"]["id"] = project.id + env.dump() + + click.secho( + f"Project [{project_name}] with namespace [{namespace}] was successfully recovered from [{prj_path}].", + fg="bright_green", + ) + + +@click.option("--config_path", help="Path of config.", required=True) +@click.option( + "--tmpl", + help="Template of project, use default if not specified.", + default="default", + type=click.Choice(["default", "medical"], case_sensitive=False), +) +@click.option( + "--delete_cfg", + help="whether delete your defined .cfg file.", + default=True, + hidden=True, +) +def create_project( + config_path: str, tmpl: Optional[str] = None, delete_cfg: bool = False +): + """ + Create new project with a demo case. + """ + + config = yaml.load(Path(config_path).read_text() or "{}") + project_config = config.get("project", {}) + namespace = project_config.get("namespace", None) + name = project_config.get("namespace", None) + host_addr = project_config.get("host_addr", None) + + if not namespace: + click.secho("ERROR: namespace is required.") + sys.exit() + + if not re.match(r"^[A-Z][A-Za-z0-9]{0,15}$", namespace): + raise click.BadParameter( + f"Invalid namespace: {namespace}." + f" Must start with an uppercase letter, only contain letters and numbers, and have a maximum length of 16." + ) + + if not tmpl: + tmpl = "default" + + project_id = None + if host_addr: + client = ProjectClient(host_addr=host_addr) + project = client.create(name=name, namespace=namespace) + + if project and project.id: + project_id = project.id + else: + click.secho("ERROR: host_addr is required.", fg="bright_red") + sys.exit() + + project_dir = _render_template( + namespace=namespace, + tmpl=tmpl, + id=project_id, + with_server=(host_addr is not None), + host_addr=host_addr, + name=name, + config_path=config_path, + delete_cfg=delete_cfg, + ) + + config = yaml.load((Path(project_dir) / "kag_config.yaml").read_text() or "{}") + client.update(id=project_id, config=json.dumps(config)) + + if delete_cfg: + os.remove(env.config_path) + + click.secho( + f"Project with namespace [{namespace}] was successfully created in {project_dir.resolve()} \n" + + "You can checkout your project with: \n" + + f" cd {project_dir}", + fg="bright_green", + ) + + +@click.option("--host_addr", help="Address of spg server.", default=None) +@click.option("--proj_path", help="Path of project.", default=None) +def restore_project(host_addr, proj_path): + if host_addr is None: + host_addr = env.host_addr + if proj_path is None: + proj_path = env.project_path + proj_client = ProjectClient(host_addr=host_addr) + + project_wanted = proj_client.get_by_namespace(namespace=env.namespace) + if not project_wanted: + if host_addr: + client = ProjectClient(host_addr=host_addr) + project = client.create(name=env.name, namespace=env.namespace) + project_id = project.id + else: + project_id = project_wanted.id + # write project id and host addr to kag_config.cfg + + env.config["project"]["id"] = project_id + env.config["project"]["host_addr"] = host_addr + env.dump() + if proj_path: + _recover_project(proj_path) + update_project(proj_path) + + +@click.option("--proj_path", help="Path of config.", default=None) +def update_project(proj_path): + if not proj_path: + proj_path = env.project_path + client = ProjectClient(host_addr=env.host_addr) + + client.update(id=env.id, config=json.dumps(env.config)) + click.secho( + f"Project [{env.name}] with namespace [{env.namespace}] was successfully updated from [{proj_path}].", + fg="bright_green", + ) + + +def list_project(): + client = ProjectClient( + host_addr=env.host_addr + or os.getenv("KAG_PROJECT_HOST_ADDR") + or DEFAULT_HOST_ADDR + ) + projects = client.get_all() + + headers = ["Project Name", "Project ID"] + + click.echo(click.style(f"{' | '.join(headers)}", fg="bright_green", bold=True)) + click.echo( + click.style( + f"{'-' * (len(headers[0]) + len(headers[1]) + 3)}", fg="bright_green" + ) + ) + + for project_name, project_id in projects.items(): + click.echo( + click.style(f"{project_name:<20} | {project_id:<10}", fg="bright_green") + ) diff --git a/knext/command/sub_command/reasoner.py b/knext/command/sub_command/reasoner.py new file mode 100644 index 00000000..41323269 --- /dev/null +++ b/knext/command/sub_command/reasoner.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. +import os +import sys +from pathlib import Path +import yaml +import click + +from knext.reasoner.client import ReasonerClient +from knext.common.env import env + + +@click.option("--file", help="Path of DSL file.") +@click.option("--dsl", help="DSL string enclosed in double quotes.") +@click.option("--output", help="Output file.") +@click.option("--proj_path", help="Path of config.", default="./") +def execute_reasoner_job(file, dsl, output=None, proj_path="./"): + """ + Submit asynchronous reasoner jobs to server by providing DSL file or string. + """ + client = ReasonerClient(host_addr=env.host_addr, project_id=int(env.project_id)) + if file and not dsl: + with open(file, "r") as f: + dsl_content = f.read() + elif not file and dsl: + dsl_content = dsl + else: + click.secho("ERROR: Please choose either --file or --dsl.", fg="bright_red") + sys.exit() + client.execute(dsl_content, output_file=output) diff --git a/knext/command/sub_command/schema.py b/knext/command/sub_command/schema.py new file mode 100644 index 00000000..f6b6350d --- /dev/null +++ b/knext/command/sub_command/schema.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. + +import os +from pathlib import Path +import yaml +import click +import knext.project + +from knext.schema.marklang.concept_rule_ml import SPGConceptRuleMarkLang +from knext.schema.marklang.schema_ml import SPGSchemaMarkLang +from knext.common.env import env + + +def commit_schema(): + """ + Commit local schema and generate schema helper. + """ + schema_file = os.path.join( + env.project_path, + knext.project.DEFAULT_SCHEMA_DIR, + knext.project.DEFAULT_SCHEMA_FILE.replace("$namespace", env.namespace), + ) + if not Path(schema_file).exists(): + click.secho(f"ERROR: File {schema_file} not exists.", fg="bright_red") + return + + ml = SPGSchemaMarkLang(schema_file) + is_altered = ml.sync_schema() + + if is_altered: + click.secho("Schema is successfully committed.", fg="bright_green") + else: + click.secho( + "There is no diff between local and server-side schema.", fg="bright_yellow" + ) + + +@click.option("--file", help="Path of DSL file.") +def reg_concept_rule(file): + """ + Register a concept rule according to DSL file. + """ + SPGConceptRuleMarkLang(file) + click.secho(f"Concept rule is successfully registered", fg="bright_green") diff --git a/knext/command/sub_command/thinker.py b/knext/command/sub_command/thinker.py new file mode 100644 index 00000000..9e0399e5 --- /dev/null +++ b/knext/command/sub_command/thinker.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. + +import click + +from knext.thinker.client import ThinkerClient + + +@click.option("--subject", help="The subject of reasoning goal, eg: id,type or type") +@click.option("--predicate", help="The predicate of reasoning goal, eg: type") +@click.option("--object", help="The object of reasoning goal, eg: id,type or type") +@click.option("--mode", help="Reasoning mode, eg: spo or node") +@click.option("--params", help="Reasoning context") +def execute_thinker_job(subject="", predicate="", object="", mode="spo", params=""): + """ + Submit asynchronous reasoner jobs to server by providing DSL file or string. + """ + client = ThinkerClient() + client.execute(subject, predicate, object, mode, params) diff --git a/knext/common/__init__.py b/knext/common/__init__.py new file mode 100644 index 00000000..93aa6cd4 --- /dev/null +++ b/knext/common/__init__.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/common/base/__init__.py b/knext/common/base/__init__.py new file mode 100644 index 00000000..93aa6cd4 --- /dev/null +++ b/knext/common/base/__init__.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/common/base/chain.py b/knext/common/base/chain.py new file mode 100644 index 00000000..0c8f05ec --- /dev/null +++ b/knext/common/base/chain.py @@ -0,0 +1,169 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. + +from concurrent.futures import ThreadPoolExecutor, as_completed +from typing import Union, Type, List, Dict + +import networkx as nx +from tqdm import tqdm + +from knext.common.base.runnable import Runnable +from knext.common.base.restable import RESTable + + +class Chain(Runnable, RESTable): + """ + Base class for creating structured sequences of calls to components. + """ + + """The execution process of Chain, represented by a dag structure.""" + dag: nx.DiGraph + + def invoke(self, input: str, max_workers, **kwargs): + node_results = {} + futures = [] + + def execute_node(node, inputs: List[str]): + with ThreadPoolExecutor(max_workers) as inner_executor: + inner_futures = [ + inner_executor.submit(node.invoke, inp) for inp in inputs + ] + result = [] + for idx, inner_future in tqdm( + enumerate(as_completed(inner_futures)), + total=len(inner_futures), + desc=f"Processing {node.name}", + ): + ret = inner_future.result() + result.extend(ret) + return node, result + + # Initialize a ThreadPoolExecutor + with ThreadPoolExecutor(max_workers) as executor: + # Find the starting nodes (nodes with no predecessors) + start_nodes = [ + node for node in self.dag.nodes if self.dag.in_degree(node) == 0 + ] + + # Initialize the first set of tasks + for node in start_nodes: + futures.append(executor.submit(execute_node, node, [input])) + + # Process nodes as futures complete + while futures: + for future in as_completed(futures): + node, result = future.result() + node_results[node] = result + futures.remove(future) + + # Submit successors for execution + successors = list(self.dag.successors(node)) + for successor in successors: + # Check if all predecessors of the successor have finished processing + if all( + pred in node_results + for pred in self.dag.predecessors(successor) + ): + # Gather all inputs from predecessors for this successor + inputs = [] + for pred in self.dag.predecessors(successor): + inputs.extend(node_results[pred]) + futures.append( + executor.submit(execute_node, successor, inputs) + ) + + # Collect the final results from the output nodes + output_nodes = [ + node for node in self.dag.nodes if self.dag.out_degree(node) == 0 + ] + final_output = [] + for node in output_nodes: + if node in node_results: + final_output.extend(node_results[node]) + + return final_output + + def batch(self, inputs: List[str], max_workers, **kwargs): + for i in inputs: + self.invoke(i, max_workers, **kwargs) + + def to_rest(self): + from knext.builder import rest + + def __rshift__( + self, + other: Union[ + Type["Chain"], + List[Type["Chain"]], + Type["Component"], + List[Type["Component"]], + None, + ], + ): + """ + Implements the right shift operator ">>" functionality to link Component or Chain objects. + + This method can handle single Component/Chain objects or lists of them. + When linking Components, a new DAG (Directed Acyclic Graph) is created to represent the data flow connection. + When linking Chain objects, the DAGs of both Chains are merged. + + Parameters: + other (Union[Type["Chain"], List[Type["Chain"]], Type["Component"], List[Type["Component"]], None]): + The subsequent steps to link, which can be a single or list of Component/Chain objects. + + Returns: + A new Chain object with a DAG that represents the linked data flow between the current Chain and the parameter other. + """ + from knext.common.base.component import Component + + if not other: + return self + # If other is not a list, convert it to a list + if not isinstance(other, list): + other = [other] + + dag_list = [] + for o in other: + if not o: + dag_list.append(o.dag) + # If o is a Component, create a new DAG and try to add o to the graph + if isinstance(o, Component): + end_nodes = [ + node + for node, out_degree in self.dag.out_degree() + if out_degree == 0 or node._last + ] + dag = nx.DiGraph(self.dag) + if len(end_nodes) > 0: + for end_node in end_nodes: + dag.add_edge(end_node, o) + dag.add_node(o) + dag_list.append(dag) + # If o is a Chain, merge the DAGs of self and o + elif isinstance(o, Chain): + combined_dag = nx.compose(self.dag, o.dag) + end_nodes = [ + node + for node, out_degree in self.dag.out_degree() + if out_degree == 0 or node._last + ] + start_nodes = [ + node for node, in_degree in o.dag.in_degree() if in_degree == 0 + ] + + if len(end_nodes) > 0 and len(start_nodes) > 0: + for end_node in end_nodes: + for start_node in start_nodes: + combined_dag.add_edge(end_node, start_node) + # Merge all DAGs and create the final Chain object + final_dag = nx.compose_all(dag_list) + return Chain(dag=final_dag) diff --git a/knext/common/base/client.py b/knext/common/base/client.py new file mode 100644 index 00000000..90d3958b --- /dev/null +++ b/knext/common/base/client.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. +import os +from abc import ABC + +from knext.common import rest +from knext.common.env import env + + +class Client(ABC): + """ + Base client class. + + This abstract base class is used to derive specific client classes. + It defines a REST client instance for sending API requests. + + Attributes: + _rest_client (rest.BaseApi): REST client instance for sending API requests. + """ + + _rest_client: rest.BaseApi + + def __init__(self, host_addr: str = None, project_id: str = None): + """ + Initialization method to set the connection address and project ID. + + This method checks the provided `host_addr` and `project_id` parameters. + If these parameters are not provided, it retrieves the values from environment variables. + + Parameters: + host_addr (str): The address of the component server. If not provided, the value from the environment variable `KAG_PROJECT_HOST_ADDR` is used. + project_id (int): The ID of the user's project. If not provided, the value from the environment variable `KAG_PROJECT_ID` is used. + """ + self._host_addr = host_addr or env.host_addr + self._project_id = project_id or env.id + + @staticmethod + def serialize(obj): + """ + Serialize an object for transmission. + + This method uses an instance of rest.ApiClient to sanitize the object, + making it suitable for serialization into JSON or another format for network transmission. + Serialization is the process of converting an object into a form that can be transmitted and stored. + + Parameters: + obj (any): The object to be serialized. + + Returns: + any: The sanitized object, suitable for serialization and transmission. + """ + return rest.ApiClient().sanitize_for_serialization(obj) diff --git a/knext/common/base/component.py b/knext/common/base/component.py new file mode 100644 index 00000000..e6ae60aa --- /dev/null +++ b/knext/common/base/component.py @@ -0,0 +1,120 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. + + +from abc import ABC +from typing import List, Union, Type + +import networkx as nx + +from knext.common.base.runnable import Runnable +from knext.common.base.restable import RESTable + + +class Component(Runnable, RESTable, ABC): + """ + Base class for all component. + """ + + @property + def id(self): + return str(id(self)) + + @property + def type(self): + return + + @property + def label(self): + return + + @property + def name(self): + return self.__class__.__name__ + + def to_dict(self): + return {"id": self.id, "name": self.name} + + def __hash__(self): + return id(self) + + def __eq__(self, other): + return hash(self) == hash(other) + + def __rshift__( + self, + other: Union[ + Type["Chain"], + List[Type["Chain"]], + Type["Component"], + List[Type["Component"]], + None, + ], + ): + """ + Implements the right shift operator to support chaining. + + This method allows connecting components or chains (self) with other components or chains (other), + forming a new workflow graph. It supports connecting single or multiple components, + single or multiple chains. + + Parameters: + other (Union[Type["Chain"], List[Type["Chain"]], Type["Component"], List[Type["Component"]], None]): + The component(s) or chain(s) to connect with. + + Returns: + Chain: A new Chain instance representing the connected workflow. + """ + from knext.common.base.chain import Chain + + if not other: + return self + if not isinstance(other, list): + other = [other] + dag_list = [] + + for o in other: + # If o is empty, create an empty directed graph and add self to it + if not o: + dag = nx.DiGraph() + self.last = True + dag.add_node(self) + dag_list.append(dag) + # If o is an instance of Component, create a directed graph and add edges between self and o + elif isinstance(o, Component): + dag = nx.DiGraph() + dag.add_node(self) + dag.add_node(o) + dag.add_edge(self, o) + dag_list.append(dag) + # If o is an instance of Chain, create a directed graph and combine it with o's graph + elif isinstance(o, Chain): + dag = nx.DiGraph() + dag.add_node(self) + end_nodes = [ + node + for node, out_degree in dag.out_degree() + if out_degree == 0 or node.last + ] + start_nodes = [ + node for node, in_degree in o.dag.in_degree() if in_degree == 0 + ] + if len(end_nodes) > 0 and len(start_nodes) > 0: + for end_node in end_nodes: + for start_node in start_nodes: + dag.add_edge(end_node, start_node) + combined_dag = nx.compose(dag, o.dag) + dag_list.append(combined_dag) + # Combine all subgraphs into a final directed graph + final_dag = nx.compose_all(dag_list) + + return Chain(dag=final_dag) diff --git a/knext/common/base/restable.py b/knext/common/base/restable.py new file mode 100644 index 00000000..7a509d9a --- /dev/null +++ b/knext/common/base/restable.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. +from abc import ABC +from typing import Type, List + + +class RESTable(ABC): + """ + Abstract base class that can be serialized as REST model and submit to the SPG server. + """ + + @property + def upstream_types(self) -> List[Type["RESTable"]]: + """The types of upstream RESTable objects that the current RESTable object can support. + + Returns: RESTable type list. + + """ + return [] + + @property + def downstream_types(self) -> List[Type["RESTable"]]: + """The types of downstream RESTable objects that the current RESTable object can support. + + Returns: RESTable type list. + + """ + return [] + + def to_rest(self): + """Convert a RESTable object to REST model that can be serialized. + + Returns: REST model. + + """ + raise NotImplementedError( + f"`to_rest` is not currently supported for {self.__class__.__name__}." + ) + + @classmethod + def from_rest(cls, rest_model): + """Convert a REST model to RESTable object. + + Args: + rest_model: REST model that needs to be converted to a RESTable object. + + Returns: Object inherits from RESTable. + + """ + raise NotImplementedError( + f"`from_rest` is not currently supported for {cls.__name__}." + ) diff --git a/knext/common/base/runnable.py b/knext/common/base/runnable.py new file mode 100644 index 00000000..818f7dea --- /dev/null +++ b/knext/common/base/runnable.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. + +from typing import TypeVar, Type, List + +Other = TypeVar("Other") + +Input = TypeVar("Input", contravariant=True) +Output = TypeVar("Output", covariant=True) + + +class Runnable: + """ + Abstract base class that can be invoked synchronously. + """ + + _last: bool = False + + def __init__(self, **kwargs): + for key, value in kwargs.items(): + setattr(self, key, value) + + @property + def input_types(self) -> Type[Input]: + """The type of input this Runnable object accepts specified as a type annotation.""" + return + + @property + def output_types(self) -> Type[Output]: + """The type of output this Runnable object produces specified as a type annotation.""" + return + + def invoke(self, input: Input, **kwargs) -> List[Output]: + """Transform an input into an output sequence synchronously.""" + raise NotImplementedError( + f"`invoke` is not currently supported for {self.__class__.__name__}." + ) + + def batch(self, inputs: List[Input], **kwargs) -> List[Output]: + """Transform inputs into an output sequence synchronously.""" + raise NotImplementedError( + f"`batch` is not currently supported for {self.__class__.__name__}." + ) + + def __rshift__(self, other): + """ + Overloads the right shift operator (>>) for the Chain class. + + This method allows for chaining together Components and Chains using the + right shift operator. It takes an input `other`, which can be a single + Component, a list of Components, a single Chain, or a list of Chains. + + The process is as follows: + - If `other` is None or an empty value, the original Chain instance (`self`) + is returned. + - If `other` is not a list, it is converted into a list containing a single + element. + - For each element in `other`, a directed acyclic graph (DAG) is created: + - If the element is a Component, it is added to the DAG and an edge is created + from the current Chain (`self`) to the Component. + - If the element is a Chain, the method finds the end nodes of the current + DAG and the start nodes of the Chain's DAG to create appropriate edges + between them. The two DAGs are then combined. + - After processing all elements in `other`, all DAGs are combined into a final + DAG using `nx.compose_all`. + - A new Chain object is created and returned, initialized with the final combined DAG. + + Args: + other: A Chain, list of Chains, Component, list of Components, or None + representing the elements to chain with the current instance. + + Returns: + A new Chain object that represents the combined DAG of the current instance + and the provided elements. + """ + raise NotImplementedError( + f"`__rshift__` is not currently supported for {self.__class__.__name__}." + ) + + def _check_type(self, other: Other) -> bool: + pass diff --git a/knext/common/cache.py b/knext/common/cache.py new file mode 100644 index 00000000..79708bcd --- /dev/null +++ b/knext/common/cache.py @@ -0,0 +1,42 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. + +from cachetools import TTLCache + + +class LinkCache: + def __init__(self, maxsize: int = 500, ttl: int = 60): + self._cache = TTLCache(maxsize=maxsize, ttl=ttl) + + @property + def cache(self): + return self._cache + + def put(self, key, value): + self.cache[key] = value + + def get(self, key): + return self.cache.get(key) + + +class SchemaCache: + def __init__(self, maxsize: int = 10, ttl: int = 300): + self._cache = TTLCache(maxsize=maxsize, ttl=ttl) + + @property + def cache(self): + return self._cache + + def put(self, key, value): + self.cache[key] = value + + def get(self, key): + return self.cache.get(key) diff --git a/knext/common/env.py b/knext/common/env.py new file mode 100644 index 00000000..2fa9adff --- /dev/null +++ b/knext/common/env.py @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. +from collections import OrderedDict +import logging +import os +import sys +import json +from ruamel.yaml import YAML +from pathlib import Path +from typing import Union, Optional + +yaml = YAML() + +logger = logging.getLogger(__name__) + +DEFAULT_HOST_ADDR = "http://127.0.0.1:8887" + + +class Environment: + _instance = None + _config = None + + def __new__(cls): + if cls._instance is None: + cls._instance = super(Environment, cls).__new__(cls) + try: + log_config = cls._instance.config.get("log", {}) + value = log_config.get("level", "INFO") + logging.basicConfig(level=logging.getLevelName(value)) + except: + logger.info("logger info not set") + return cls._instance + + @property + def config(self): + if self._config is None: + self._config = self.get_config() + if self._config != self.get_config(): + with open(self.config_path, "w") as f: + yaml.dump(self._config, f) + return self._config + + @property + def project_path(self): + config_path = self._closest_config() + return os.path.abspath(os.path.dirname(config_path)) + + @property + def config_path(self): + return self._closest_config() + + @property + def project_config(self): + return self.config.get("project", {}) + + @property + def id(self): + if os.getenv("KAG_PROJECT_ID"): + return os.getenv("KAG_PROJECT_ID") + id = self.project_config.get("id", None) + if id is None: + raise Exception( + "project id not restore in spgserver, please restore project first" + ) + return id + + @property + def project_id(self): + return self.id + + @property + def namespace(self): + if os.getenv("KAG_PROJECT_NAMESPACE"): + return os.getenv("KAG_PROJECT_NAMESPACE") + namespace = self.project_config.get("namespace", None) + if namespace is None: + raise Exception("project namespace is not defined") + return namespace + + @property + def name(self): + return self.namespace + + @property + def host_addr(self): + if os.getenv("KAG_PROJECT_HOST_ADDR"): + return os.getenv("KAG_PROJECT_HOST_ADDR") + host_addr = self.project_config.get("host_addr", None) + if host_addr is None: + raise Exception("project host_addr is not defined") + return host_addr + + def get_config(self): + """ + Get knext config file as a ConfigParser. + """ + local_cfg_path = self._closest_config() + try: + with open(local_cfg_path) as f: + local_cfg = yaml.load(f) + except Exception as e: + raise Exception(f"failed to load config from {local_cfg_path}, error: {e}") + projdir = "" + if local_cfg_path: + projdir = str(Path(local_cfg_path).parent) + if projdir not in sys.path: + sys.path.append(projdir) + + return local_cfg + + def _closest_config( + self, + path: Union[str, os.PathLike] = ".", + prev_path: Optional[Union[str, os.PathLike]] = None, + ) -> str: + """ + Return the path to the closest .knext.cfg file by traversing the current + directory and its parents + """ + if prev_path is not None and str(path) == str(prev_path): + return "" + path = Path(path).resolve() + cfg_file = path / "kag_config.yaml" + if cfg_file.exists(): + return str(cfg_file) + return self._closest_config(path.parent, path) + + def dump(self, path=None, **kwargs): + with open(path or self.config_path, "w") as f: + yaml.dump(self.config, f, **kwargs) + + +env = Environment() diff --git a/knext/common/rest/__init__.py b/knext/common/rest/__init__.py new file mode 100644 index 00000000..0651489b --- /dev/null +++ b/knext/common/rest/__init__.py @@ -0,0 +1,21 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. + +__version__ = "1" + +from knext.common.rest.api_client import ApiClient +from knext.common.rest.api_client import BaseApi +from knext.common.rest.configuration import Configuration +from knext.common.rest.exceptions import ApiException +from knext.common.rest.exceptions import ApiKeyError +from knext.common.rest.exceptions import ApiTypeError +from knext.common.rest.exceptions import ApiValueError +from knext.common.rest.exceptions import OpenApiException diff --git a/knext/common/rest/api_client.py b/knext/common/rest/api_client.py new file mode 100644 index 00000000..9bc9a8e8 --- /dev/null +++ b/knext/common/rest/api_client.py @@ -0,0 +1,774 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import atexit +import datetime +import json +import mimetypes +import os +import re +import tempfile +from multiprocessing.pool import ThreadPool + +# python 2 and python 3 compatibility library +import six +from dateutil.parser import parse +from six.moves.urllib.parse import quote + +import knext +from knext.common.rest import rest +from knext.common.rest.configuration import Configuration +from knext.common.rest.exceptions import ApiValueError, ApiException + + +class ApiClient(object): + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + :param pool_threads: The number of threads to use for async requests + to the API. More threads means more concurrent API requests. + """ + + PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types + NATIVE_TYPES_MAPPING = { + "int": int, + "long": int if six.PY3 else long, # noqa: F821 + "float": float, + "str": str, + "bool": bool, + "date": datetime.date, + "datetime": datetime.datetime, + "object": object, + } + _pool = None + + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None, + pool_threads=1, + ): + if configuration is None: + configuration = Configuration.get_default_copy() + self.configuration = configuration + self.pool_threads = pool_threads + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = "OpenAPI-Generator/1.0.0/python" + self.client_side_validation = configuration.client_side_validation + self.url_prefix = "/public/v" + knext.common.rest.__version__ + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def close(self): + if self._pool: + self._pool.close() + self._pool.join() + self._pool = None + if hasattr(atexit, "unregister"): + atexit.unregister(self.close) + + @property + def pool(self): + """Create thread pool on first request + avoids instantiating unused threadpool for blocking clients. + """ + if self._pool is None: + atexit.register(self.close) + self._pool = ThreadPool(self.pool_threads) + return self._pool + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers["User-Agent"] + + @user_agent.setter + def user_agent(self, value): + self.default_headers["User-Agent"] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + def __call_api( + self, + resource_path, + method, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, + response_type=None, + auth_settings=None, + _return_http_data_only=None, + collection_formats=None, + _preload_content=True, + _request_timeout=None, + _host=None, + ): + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params["Cookie"] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict( + self.parameters_to_tuples(header_params, collection_formats) + ) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples(path_params, collection_formats) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + "{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + query_params = self.parameters_to_tuples(query_params, collection_formats) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples(post_params, collection_formats) + post_params.extend(self.files_parameters(files)) + + # auth setting + self.update_params_for_auth(header_params, query_params, auth_settings) + + # body + if body: + body = self.sanitize_for_serialization(body) + # request url + if _host is None: + url = self.configuration.host + self.url_prefix + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + try: + # perform request and return response + response_data = self.request( + method, + url, + query_params=query_params, + headers=header_params, + post_params=post_params, + body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + ) + except ApiException as e: + e.body = e.body.decode("utf-8") if six.PY3 else e.body + raise e + + content_type = response_data.getheader("content-type") + + self.last_response = response_data + + return_data = response_data + + if not _preload_content: + return return_data + + if six.PY3 and response_type not in ["file", "bytes"]: + match = None + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_data.data = response_data.data.decode(encoding) + + # deserialize response data + if response_type: + return_data = self.deserialize(response_data, response_type) + else: + return_data = None + + if _return_http_data_only: + return return_data + else: + return (return_data, response_data.status, response_data.getheaders()) + + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. + + If obj is None, return None. + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is list, sanitize each element in the list. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. + + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if obj is None: + return None + elif isinstance(obj, self.PRIMITIVE_TYPES): + return obj + elif isinstance(obj, list): + return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] + elif isinstance(obj, tuple): + return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) + elif isinstance(obj, (datetime.datetime, datetime.date)): + return obj.isoformat() + # elif hasattr(obj, "__type_name__"): + # return obj.__type_name__ + + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `openapi_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = { + obj.attribute_map[attr]: getattr(obj, attr) + for attr, _ in six.iteritems(obj.openapi_types) + if getattr(obj, attr) is not None + } + if obj.discriminator is not None: + obj_dict["@type"] = obj.discriminator + + obj_dict = { + key: self.sanitize_for_serialization(val) + for key, val in six.iteritems(obj_dict) + if val is not None + } + obj_dict = {key: val for key, val in six.iteritems(obj_dict) if val is not None} + + return obj_dict if obj_dict else None + + def deserialize(self, response, response_type): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialized object, or string of class name. + + :return: deserialized object. + """ + # handle file downloading + # save response body into a tmp file and return the instance + if response_type == "file": + return self.__deserialize_file(response) + + # fetch data from response object + try: + data = json.loads(response.data) + except ValueError: + data = response.data + + return self.__deserialize(data, response_type) + + def __deserialize(self, data, klass): + """Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if type(klass) == str: + if klass.startswith("list["): + sub_kls = re.match(r"list\[(.*)\]", klass).group(1) + return [self.__deserialize(sub_data, sub_kls) for sub_data in data] + + if klass.startswith("dict("): + sub_kls = re.match(r"dict\(([^,]*), (.*)\)", klass).group(2) + return { + k: self.__deserialize(v, sub_kls) for k, v in six.iteritems(data) + } + + # convert str to class + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] + else: + import knext.common.rest.models + + klass = getattr(knext.common.rest.models, klass) + + if klass in self.PRIMITIVE_TYPES: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object(data) + elif klass == datetime.date: + return self.__deserialize_date(data) + elif klass == datetime.datetime: + return self.__deserialize_datetime(data) + else: + return self.__deserialize_model(data, klass) + + def call_api( + self, + resource_path, + method, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, + response_type=None, + auth_settings=None, + async_req=None, + _return_http_data_only=None, + collection_formats=None, + _preload_content=True, + _request_timeout=None, + _host=None, + ): + """Makes the HTTP request (synchronous) and returns deserialized data. + + To make an async_req request, set the async_req parameter. + + :param resource_path: Path to method endpoint. + :param method: Method to call. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param response: Response data type. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: + If async_req parameter is True, + the request will be called asynchronously. + The method will return the request thread. + If parameter async_req is False or missing, + then the method will return the response directly. + """ + if not async_req: + return self.__call_api( + resource_path, + method, + path_params, + query_params, + header_params, + body, + post_params, + files, + response_type, + auth_settings, + _return_http_data_only, + collection_formats, + _preload_content, + _request_timeout, + _host, + ) + + return self.pool.apply_async( + self.__call_api, + ( + resource_path, + method, + path_params, + query_params, + header_params, + body, + post_params, + files, + response_type, + auth_settings, + _return_http_data_only, + collection_formats, + _preload_content, + _request_timeout, + _host, + ), + ) + + def request( + self, + method, + url, + query_params=None, + headers=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + """Makes the HTTP request using RESTClient.""" + if method == "GET": + return self.rest_client.GET( + url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers, + ) + elif method == "HEAD": + return self.rest_client.HEAD( + url, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + headers=headers, + ) + elif method == "OPTIONS": + return self.rest_client.OPTIONS( + url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + ) + elif method == "POST": + return self.rest_client.POST( + url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + elif method == "PUT": + return self.rest_client.PUT( + url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + elif method == "PATCH": + return self.rest_client.PATCH( + url, + query_params=query_params, + headers=headers, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + elif method == "DELETE": + return self.rest_client.DELETE( + url, + query_params=query_params, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + else: + raise ApiValueError( + "http method must be `GET`, `HEAD`, `OPTIONS`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in ( + six.iteritems(params) if isinstance(params, dict) else params + ): # noqa: E501 + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == "multi": + new_params.extend((k, value) for value in v) + else: + if collection_format == "ssv": + delimiter = " " + elif collection_format == "tsv": + delimiter = "\t" + elif collection_format == "pipes": + delimiter = "|" + else: # csv is the default + delimiter = "," + new_params.append((k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + + def files_parameters(self, files=None): + """Builds form parameters. + + :param files: File parameters. + :return: Form parameters with files. + """ + params = [] + + if files: + for k, v in six.iteritems(files): + if not v: + continue + file_names = v if type(v) is list else [v] + for n in file_names: + with open(n, "rb") as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = ( + mimetypes.guess_type(filename)[0] + or "application/octet-stream" + ) + params.append(tuple([k, tuple([filename, filedata, mimetype])])) + + return params + + def select_header_accept(self, accepts): + """Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return + + accepts = [x.lower() for x in accepts] + + if "application/json" in accepts: + return "application/json" + else: + return ", ".join(accepts) + + def select_header_content_type(self, content_types): + """Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return "application/json" + + content_types = [x.lower() for x in content_types] + + if "application/json" in content_types or "*/*" in content_types: + return "application/json" + else: + return content_types[0] + + def update_params_for_auth(self, headers, querys, auth_settings): + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param querys: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + """ + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + if auth_setting["in"] == "cookie": + headers["Cookie"] = auth_setting["value"] + elif auth_setting["in"] == "header": + headers[auth_setting["key"]] = auth_setting["value"] + elif auth_setting["in"] == "query": + querys.append((auth_setting["key"], auth_setting["value"])) + else: + raise ApiValueError( + "Authentication token must be in `query` or `header`" + ) + + def __deserialize_file(self, response): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + :param response: RESTResponse. + :return: file path. + """ + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + filename = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition + ).group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. + + :param data: str. + :param klass: class literal. + + :return: int, long, float, str, bool. + """ + try: + return klass(data) + except UnicodeEncodeError: + return six.text_type(data) + except TypeError: + return data + + def __deserialize_object(self, value): + """Return an original value. + + :return: object. + """ + return value + + def __deserialize_date(self, string): + """Deserializes string to date. + + :param string: str. + :return: date. + """ + try: + return parse(string).date() + except ImportError: + return string + except ValueError: + raise knext.common.rest.ApiException( + status=0, reason="Failed to parse `{0}` as date object".format(string) + ) + + def __deserialize_datetime(self, string): + """Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ + try: + return parse(string) + except ImportError: + return string + except ValueError: + raise knext.common.rest.ApiException( + status=0, + reason=("Failed to parse `{0}` as datetime object".format(string)), + ) + + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + has_discriminator = False + if ( + hasattr(klass, "get_real_child_model") + and klass.discriminator_value_class_map + ): + has_discriminator = True + + if not klass.openapi_types and has_discriminator is False: + return data + + kwargs = {} + if ( + data is not None + and klass.openapi_types is not None + and isinstance(data, (list, dict)) + ): + for attr, attr_type in six.iteritems(klass.openapi_types): + if klass.attribute_map[attr] in data: + value = data[klass.attribute_map[attr]] + kwargs[attr] = self.__deserialize(value, attr_type) + + instance = klass(**kwargs) + + if has_discriminator: + klass_name = instance.get_real_child_model(data) + if klass_name: + instance = self.__deserialize(data, klass_name) + return instance + + +class BaseApi(object): + api_client: ApiClient + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client diff --git a/knext/common/rest/configuration.py b/knext/common/rest/configuration.py new file mode 100644 index 00000000..965db0df --- /dev/null +++ b/knext/common/rest/configuration.py @@ -0,0 +1,395 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import copy +import logging +import multiprocessing +import os +from pathlib import Path +import sys +import yaml + +import six +import urllib3 +from six.moves import http_client as httplib +from knext.common.env import env + + +class Configuration(object): + """NOTE: This class is auto generated by OpenAPI Generator + + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param host: Base url + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer) + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication + :param password: Password for HTTP basic authentication + :param discard_unknown_keys: Boolean value indicating whether to discard + unknown properties. A server may send a response that includes additional + properties that are not known by the client in the following scenarios: + 1. The OpenAPI document is incomplete, i.e. it does not match the server + implementation. + 2. The client was generated using an older version of the OpenAPI document + and the server has been upgraded since then. + If a schema in the OpenAPI document defines the additionalProperties attribute, + then all undeclared properties received by the server are injected into the + additional properties map. In that case, there are undeclared properties, and + nothing to discard. + + """ + + _default = None + + def __init__( + self, + host=None, + api_key=None, + api_key_prefix=None, + username=None, + password=None, + discard_unknown_keys=False, + ): + """Constructor""" + self.host = host or os.getenv("KAG_PROJECT_HOST_ADDR") or env.host_addr + """Default Base url + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.discard_unknown_keys = discard_unknown_keys + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("rest") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = "%(asctime)s %(levelname)s %(message)s" + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + self.debug = False + """Debug switch + """ + + self.verify_ssl = True + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = None + """Set this to customize the certificate file to verify the peer. + """ + self.cert_file = None + """client certificate file + """ + self.key_file = None + """client key file + """ + self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. + """ + + self.proxy = None + """Proxy URL + """ + self.proxy_headers = None + """Proxy headers + """ + self.safe_chars_for_path_param = "" + """Safe chars for path_param + """ + self.retries = None + """Adding retries to override urllib3 default value 3 + """ + # Disable client side validation + self.client_side_validation = True + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ("logger", "logger_file_handler"): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name, value): + object.__setattr__(self, name, value) + + @classmethod + def set_default(cls, default): + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = copy.deepcopy(default) + + @classmethod + def get_default_copy(cls): + """Return new instance of configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration passed by the set_default method. + + :return: The configuration object. + """ + if cls._default is not None: + return copy.deepcopy(cls._default) + return Configuration() + + @property + def logger_file(self): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in six.iteritems(self.logger): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in six.iteritems(self.logger): + logger.setLevel(logging.DEBUG) + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in six.iteritems(self.logger): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier): + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :return: The token for api key authentication. + """ + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key + + def get_basic_auth_token(self): + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers(basic_auth=username + ":" + password).get( + "authorization" + ) + + def auth_settings(self): + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth = {} + return auth + + def to_debug_report(self): + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return ( + "Python SDK Debug Report:\n" + "OS: {env}\n" + "Python Version: {pyversion}\n" + "Version of the API: 1.0.0\n" + "SDK Package Version: 1.0.0".format(env=sys.platform, pyversion=sys.version) + ) + + def get_host_settings(self): + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + "url": "/", + "description": "No description provided", + } + ] + + def get_host_from_settings(self, index, variables=None): + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :return: URL based on host settings + """ + variables = {} if variables is None else variables + servers = self.get_host_settings() + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers)) + ) + + url = server["url"] + + # go through variables and replace placeholders + for variable_name, variable in server["variables"].items(): + used_value = variables.get(variable_name, variable["default_value"]) + + if "enum_values" in variable and used_value not in variable["enum_values"]: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], variable["enum_values"] + ) + ) + + url = url.replace("{" + variable_name + "}", used_value) + + return url diff --git a/knext/common/rest/exceptions.py b/knext/common/rest/exceptions.py new file mode 100644 index 00000000..4fd26710 --- /dev/null +++ b/knext/common/rest/exceptions.py @@ -0,0 +1,127 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import six + + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, key_type=None): + """Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + def __init__(self, status=None, reason=None, http_resp=None): + if http_resp: + self.status = http_resp.status + self.reason = http_resp.reason + self.body = http_resp.data + self.headers = http_resp.getheaders() + else: + self.status = status + self.reason = reason + self.body = None + self.headers = None + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n" "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format(self.headers) + + if self.body: + error_message += "HTTP response body: {0}\n".format(self.body) + + return error_message + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, six.integer_types): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/knext/common/rest/models.py b/knext/common/rest/models.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/common/rest/models.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/common/rest/models/__init__.py b/knext/common/rest/models/__init__.py new file mode 100644 index 00000000..ca17c13e --- /dev/null +++ b/knext/common/rest/models/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. + +# import models into sdk package +from knext.schema.rest.models import * +from knext.reasoner.rest.models import * +from knext.project.rest.models import * +from knext.search.rest.models import * +from knext.graph.rest.models import * +from knext.thinker.rest.models import * diff --git a/knext/common/rest/rest.py b/knext/common/rest/rest.py new file mode 100644 index 00000000..164e3446 --- /dev/null +++ b/knext/common/rest/rest.py @@ -0,0 +1,396 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import io +import json +import logging +import re +import ssl + +import certifi + +# python 2 and python 3 compatibility library +import six +import urllib3 +from six.moves.urllib.parse import urlencode + +from knext.common.rest.exceptions import ApiException, ApiValueError + +logger = logging.getLogger(__name__) + + +class RESTResponse(io.IOBase): + def __init__(self, resp): + self.urllib3_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = resp.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.urllib3_response.getheaders() + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.urllib3_response.getheader(name, default) + + +class RESTClientObject(object): + def __init__(self, configuration, pools_size=4, maxsize=None): + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + # ca_certs + if configuration.ssl_ca_cert: + ca_certs = configuration.ssl_ca_cert + else: + # if not set certificate file, use Mozilla's root certificates. + ca_certs = certifi.where() + + addition_pool_args = {} + if configuration.assert_hostname is not None: + addition_pool_args[ + "assert_hostname" + ] = configuration.assert_hostname # noqa: E501 + + if configuration.retries is not None: + addition_pool_args["retries"] = configuration.retries + + if maxsize is None: + if configuration.connection_pool_maxsize is not None: + maxsize = configuration.connection_pool_maxsize + else: + maxsize = 4 + + # https pool manager + if configuration.proxy: + self.pool_manager = urllib3.ProxyManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=ca_certs, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + proxy_headers=configuration.proxy_headers, + **addition_pool_args + ) + else: + self.pool_manager = urllib3.PoolManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=ca_certs, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + **addition_pool_args + ) + + def request( + self, + method, + url, + query_params=None, + headers=None, + body=None, + post_params=None, + _preload_content=True, + _request_timeout=None, + ): + """Perform requests. + + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in ["GET", "HEAD", "DELETE", "POST", "PUT", "PATCH", "OPTIONS"] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + + timeout = None + if _request_timeout: + if isinstance( + _request_timeout, (int,) if six.PY3 else (int, long) + ): # noqa: E501,F821 + timeout = urllib3.Timeout(total=_request_timeout) + elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2: + timeout = urllib3.Timeout( + connect=_request_timeout[0], read=_request_timeout[1] + ) + + if "Content-Type" not in headers: + headers["Content-Type"] = "application/json" + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]: + if query_params: + url += "?" + urlencode(query_params) + if re.search("json", headers["Content-Type"], re.IGNORECASE): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, + url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers, + ) + elif ( + headers["Content-Type"] == "application/x-www-form-urlencoded" + ): # noqa: E501 + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=False, + preload_content=_preload_content, + timeout=timeout, + headers=headers, + ) + elif headers["Content-Type"] == "multipart/form-data": + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers["Content-Type"] + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=True, + preload_content=_preload_content, + timeout=timeout, + headers=headers, + ) + # Pass a `string` parameter directly in the body to support + # other content types than Json when `body` argument is + # provided in serialized form + elif isinstance(body, str) or isinstance(body, bytes): + request_body = body + r = self.pool_manager.request( + method, + url, + body=request_body, + preload_content=_preload_content, + timeout=timeout, + headers=headers, + ) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request( + method, + url, + fields=query_params, + preload_content=_preload_content, + timeout=timeout, + headers=headers, + ) + except urllib3.exceptions.SSLError as e: + msg = "{0}\n{1}".format(type(e).__name__, str(e)) + raise ApiException(status=0, reason=msg) + + if _preload_content: + r = RESTResponse(r) + + # log response body + logger.debug("response body: %s", r.data) + + if not 200 <= r.status <= 299: + raise ApiException(http_resp=r) + + return r + + def GET( + self, + url, + headers=None, + query_params=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "GET", + url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params, + ) + + def HEAD( + self, + url, + headers=None, + query_params=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "HEAD", + url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params, + ) + + def OPTIONS( + self, + url, + headers=None, + query_params=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "OPTIONS", + url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + + def DELETE( + self, + url, + headers=None, + query_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "DELETE", + url, + headers=headers, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + + def POST( + self, + url, + headers=None, + query_params=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "POST", + url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + + def PUT( + self, + url, + headers=None, + query_params=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "PUT", + url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) + + def PATCH( + self, + url, + headers=None, + query_params=None, + post_params=None, + body=None, + _preload_content=True, + _request_timeout=None, + ): + return self.request( + "PATCH", + url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body, + ) diff --git a/knext/common/utils.py b/knext/common/utils.py new file mode 100644 index 00000000..5246aa97 --- /dev/null +++ b/knext/common/utils.py @@ -0,0 +1,205 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. +import re +import sys +import json +from typing import Type, Tuple +import inspect +import os +from pathlib import Path +import importlib +from shutil import copystat, copy2 +from typing import Any, Union +from jinja2 import Environment, FileSystemLoader, Template +from stat import S_IWUSR as OWNER_WRITE_PERMISSION + + +def _register(root, path, files, class_type): + relative_path = os.path.relpath(path, root) + module_prefix = relative_path.replace(".", "").replace("/", ".") + module_prefix = module_prefix + "." if module_prefix else "" + for file_name in files: + if file_name.endswith(".py"): + module_name = module_prefix + os.path.splitext(file_name)[0] + import importlib + + module = importlib.import_module(module_name) + classes = inspect.getmembers(module, inspect.isclass) + for class_name, class_obj in classes: + if ( + issubclass(class_obj, class_type) + and inspect.getmodule(class_obj) == module + ): + + class_type.register( + name=class_name, + local_path=os.path.join(path, file_name), + module_path=module_name, + )(class_obj) + + +def register_from_package(path: str, class_type: Type) -> None: + """ + Register all classes under the given package. + Only registered classes can be recognized by knext. + """ + if not append_python_path(path): + return + for root, dirs, files in os.walk(path): + _register(path, root, files, class_type) + class_type._has_registered = True + + +def append_python_path(path: str) -> bool: + """ + Append the given path to `sys.path`. + """ + path = Path(path).resolve() + path = str(path) + if path not in sys.path: + sys.path.append(path) + return True + return False + + +def render_template( + root_dir: Union[str, os.PathLike], file: Union[str, os.PathLike], **kwargs: Any +) -> None: + path_obj = Path(root_dir) / file + env = Environment(loader=FileSystemLoader(path_obj.parent)) + template = env.get_template(path_obj.name) + content = template.render(kwargs) + + render_path = path_obj.with_suffix("") if path_obj.suffix == ".tmpl" else path_obj + + if path_obj.suffix == ".tmpl": + path_obj.rename(render_path) + + render_path.write_text(content, "utf8") + + +def copytree(src: Path, dst: Path, **kwargs): + names = [x.name for x in src.iterdir()] + + if not dst.exists(): + dst.mkdir(parents=True) + + for name in names: + _name = Template(name).render(**kwargs) + src_name = src / name + dst_name = dst / _name + if src_name.is_dir(): + copytree(src_name, dst_name, **kwargs) + else: + copyfile(src_name, dst_name, **kwargs) + + copystat(src, dst) + _make_writable(dst) + + +def copyfile(src: Path, dst: Path, **kwargs): + if dst.exists(): + return + dst = Path(Template(str(dst)).render(**kwargs)) + copy2(src, dst) + _make_writable(dst) + if dst.suffix != ".tmpl": + return + render_template("/", dst, **kwargs) + + +def remove_files_except(path, file, new_file): + for filename in os.listdir(path): + file_path = os.path.join(path, filename) + if os.path.isfile(file_path) and filename != file: + os.remove(file_path) + os.rename(path / file, path / new_file) + + +def _make_writable(path): + current_permissions = os.stat(path).st_mode + os.chmod(path, current_permissions | OWNER_WRITE_PERMISSION) + + +def escape_single_quotes(s: str): + return s.replace("'", "\\'") + + +def load_json(content): + try: + return json.loads(content) + except json.JSONDecodeError as e: + + substr = content[: e.colno - 1] + return json.loads(substr) + + +def split_module_class_name(name: str, text: str) -> Tuple[str, str]: + """ + Split `name` as module name and class name pair. + + :param name: fully qualified class name, e.g. ``foo.bar.MyClass`` + :type name: str + :param text: describe the kind of the class, used in the exception message + :type text: str + :rtype: Tuple[str, str] + :raises RuntimeError: if `name` is not a fully qualified class name + """ + i = name.rfind(".") + if i == -1: + message = "invalid %s class name: %s" % (text, name) + raise RuntimeError(message) + module_name = name[:i] + class_name = name[i + 1 :] + return module_name, class_name + + +def dynamic_import_class(name: str, text: str): + """ + Import the class specified by `name` dyanmically. + + :param name: fully qualified class name, e.g. ``foo.bar.MyClass`` + :type name: str + :param text: describe the kind of the class, use in the exception message + :type text: str + :raises RuntimeError: if `name` is not a fully qualified class name, or + the class is not in the module specified by `name` + :raises ModuleNotFoundError: the module specified by `name` is not found + """ + module_name, class_name = split_module_class_name(name, text) + module = importlib.import_module(module_name) + class_ = getattr(module, class_name, None) + if class_ is None: + message = "class %r not found in module %r" % (class_name, module_name) + raise RuntimeError(message) + if not isinstance(class_, type): + message = "%r is not a class" % (name,) + raise RuntimeError(message) + return class_ + + +def processing_phrases(phrase): + phrase = str(phrase) + return re.sub("[^A-Za-z0-9\u4e00-\u9fa5 ]", " ", phrase.lower()).strip() + + +def to_camel_case(phrase): + s = processing_phrases(phrase).replace(" ", "_") + return "".join( + word.capitalize() if i != 0 else word for i, word in enumerate(s.split("_")) + ) + + +def to_snake_case(name): + words = re.findall("[A-Za-z][a-z0-9]*", name) + result = "_".join(words).lower() + return result diff --git a/knext/graph/__init__.py b/knext/graph/__init__.py new file mode 100644 index 00000000..ab480694 --- /dev/null +++ b/knext/graph/__init__.py @@ -0,0 +1,56 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +# flake8: noqa + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +__version__ = "1.0.0" + +# import apis into sdk package +from knext.graph.rest.graph_api import GraphApi + + +# import models into model package +from knext.graph.rest.models.get_page_rank_scores_request import ( + GetPageRankScoresRequest, +) +from knext.graph.rest.models.get_page_rank_scores_request_start_nodes import ( + GetPageRankScoresRequestStartNodes, +) +from knext.graph.rest.models.page_rank_score_instance import PageRankScoreInstance +from knext.graph.rest.models.delete_vertex_request import DeleteVertexRequest +from knext.graph.rest.models.delete_edge_request import DeleteEdgeRequest +from knext.graph.rest.models.edge_record_instance import EdgeRecordInstance +from knext.graph.rest.models.upsert_vertex_request import UpsertVertexRequest +from knext.graph.rest.models.upsert_edge_request import UpsertEdgeRequest +from knext.graph.rest.models.vertex_record_instance import VertexRecordInstance +from knext.graph.rest.models.writer_graph_request import WriterGraphRequest +from knext.graph.rest.models.edge_record import EdgeRecord +from knext.graph.rest.models.edge_type_name import EdgeTypeName +from knext.graph.rest.models.expend_one_hop_request import ExpendOneHopRequest +from knext.graph.rest.models.lpg_property_record import LpgPropertyRecord +from knext.graph.rest.models.query_vertex_request import QueryVertexRequest +from knext.graph.rest.models.query_vertex_response import QueryVertexResponse +from knext.graph.rest.models.vertex_record import VertexRecord +from knext.graph.rest.models.expend_one_hop_response import ExpendOneHopResponse diff --git a/knext/graph/client.py b/knext/graph/client.py new file mode 100644 index 00000000..08ba7fbc --- /dev/null +++ b/knext/graph/client.py @@ -0,0 +1,102 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. + +from typing import List, Dict + +from knext.common.base.client import Client +from knext.common.rest import ApiClient, Configuration +from knext.graph import ( + rest, + GetPageRankScoresRequest, + GetPageRankScoresRequestStartNodes, + WriterGraphRequest, + QueryVertexRequest, + ExpendOneHopRequest, + EdgeTypeName, +) + + +class GraphClient(Client): + """ """ + + def __init__(self, host_addr: str = None, project_id: int = None): + super().__init__(host_addr, project_id) + self._rest_client: rest.GraphApi = rest.GraphApi( + api_client=ApiClient(configuration=Configuration(host=host_addr)) + ) + + def calculate_pagerank_scores(self, target_vertex_type, start_nodes: List[Dict]): + """ + Calculate and retrieve PageRank scores for the given starting nodes. + + Parameters: + target_vertex_type (str): Return target vectex type ppr score + start_nodes (list): A list containing document fragment IDs to be used as starting nodes for the PageRank algorithm. + + Returns: + ppr_doc_scores (dict): A dictionary containing each document fragment ID and its corresponding PageRank score. + + This method uses the PageRank algorithm in the graph store to compute scores for document fragments. If `start_nodes` is empty, + it returns an empty dictionary. Otherwise, it attempts to retrieve PageRank scores from the graph store and converts the result + into a dictionary format where keys are document fragment IDs and values are their respective PageRank scores. Any exceptions, + such as failures in running `run_pagerank_igraph_chunk`, are logged. + """ + ppr_start_nodes = [ + GetPageRankScoresRequestStartNodes(id=node["name"], type=node["type"]) + for node in start_nodes + ] + req = GetPageRankScoresRequest( + self._project_id, target_vertex_type, ppr_start_nodes + ) + resp = self._rest_client.graph_get_page_rank_scores_post( + get_page_rank_scores_request=req + ) + return {item.id: item.score for item in resp} + + def write_graph(self, sub_graph: dict, operation: str, lead_to_builder: bool): + request = WriterGraphRequest( + project_id=self._project_id, + sub_graph=sub_graph, + operation=operation, + enable_lead_to=lead_to_builder, + ) + self._rest_client.graph_writer_graph_post(writer_graph_request=request) + + def query_vertex(self, type_name: str, biz_id: str): + request = QueryVertexRequest( + project_id=self._project_id, type_name=type_name, biz_id=biz_id + ) + return self._rest_client.graph_query_vertex_post(query_vertex_request=request) + + def expend_one_hop( + self, + type_name: str, + biz_id: str, + edge_type_name_constraint: List[EdgeTypeName] = None, + ): + request = ExpendOneHopRequest( + project_id=self._project_id, + type_name=type_name, + biz_id=biz_id, + edge_type_name_constraint=edge_type_name_constraint, + ) + return self._rest_client.graph_expend_one_hop_post( + expend_one_hop_request=request + ) + + +if __name__ == "__main__": + sc = GraphClient("http://127.0.0.1:8887", 4) + out = sc.calculate_pagerank_scores( + "Entity", [{"name": "Anxiety_and_nervousness", "type": "Entity"}] + ) + for o in out: + print(o) diff --git a/knext/graph/rest/__init__.py b/knext/graph/rest/__init__.py new file mode 100644 index 00000000..ab480694 --- /dev/null +++ b/knext/graph/rest/__init__.py @@ -0,0 +1,56 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +# flake8: noqa + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +__version__ = "1.0.0" + +# import apis into sdk package +from knext.graph.rest.graph_api import GraphApi + + +# import models into model package +from knext.graph.rest.models.get_page_rank_scores_request import ( + GetPageRankScoresRequest, +) +from knext.graph.rest.models.get_page_rank_scores_request_start_nodes import ( + GetPageRankScoresRequestStartNodes, +) +from knext.graph.rest.models.page_rank_score_instance import PageRankScoreInstance +from knext.graph.rest.models.delete_vertex_request import DeleteVertexRequest +from knext.graph.rest.models.delete_edge_request import DeleteEdgeRequest +from knext.graph.rest.models.edge_record_instance import EdgeRecordInstance +from knext.graph.rest.models.upsert_vertex_request import UpsertVertexRequest +from knext.graph.rest.models.upsert_edge_request import UpsertEdgeRequest +from knext.graph.rest.models.vertex_record_instance import VertexRecordInstance +from knext.graph.rest.models.writer_graph_request import WriterGraphRequest +from knext.graph.rest.models.edge_record import EdgeRecord +from knext.graph.rest.models.edge_type_name import EdgeTypeName +from knext.graph.rest.models.expend_one_hop_request import ExpendOneHopRequest +from knext.graph.rest.models.lpg_property_record import LpgPropertyRecord +from knext.graph.rest.models.query_vertex_request import QueryVertexRequest +from knext.graph.rest.models.query_vertex_response import QueryVertexResponse +from knext.graph.rest.models.vertex_record import VertexRecord +from knext.graph.rest.models.expend_one_hop_response import ExpendOneHopResponse diff --git a/knext/graph/rest/graph_api.py b/knext/graph/rest/graph_api.py new file mode 100644 index 00000000..4e7f0c22 --- /dev/null +++ b/knext/graph/rest/graph_api.py @@ -0,0 +1,991 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import re # noqa: F401 + +# python 2 and python 3 compatibility library +import six + +from knext.common.rest.api_client import ApiClient +from knext.common.rest.exceptions import ApiTypeError, ApiValueError # noqa: F401 + + +class GraphApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def graph_delete_edge_post(self, **kwargs): # noqa: E501 + """delete_edge # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_delete_edge_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param DeleteEdgeRequest delete_edge_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: object + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.graph_delete_edge_post_with_http_info(**kwargs) # noqa: E501 + + def graph_delete_edge_post_with_http_info(self, **kwargs): # noqa: E501 + """delete_edge # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_delete_edge_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param DeleteEdgeRequest delete_edge_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["delete_edge_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method graph_delete_edge_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "delete_edge_request" in local_var_params: + body_params = local_var_params["delete_edge_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/graph/deleteEdge", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="object", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def graph_delete_vertex_post(self, **kwargs): # noqa: E501 + """delete_vertex # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_delete_vertex_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param DeleteVertexRequest delete_vertex_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: object + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.graph_delete_vertex_post_with_http_info(**kwargs) # noqa: E501 + + def graph_delete_vertex_post_with_http_info(self, **kwargs): # noqa: E501 + """delete_vertex # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_delete_vertex_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param DeleteVertexRequest delete_vertex_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["delete_vertex_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method graph_delete_vertex_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "delete_vertex_request" in local_var_params: + body_params = local_var_params["delete_vertex_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/graph/deleteVertex", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="object", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def graph_get_page_rank_scores_post(self, **kwargs): # noqa: E501 + """page_rank # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_get_page_rank_scores_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param GetPageRankScoresRequest get_page_rank_scores_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: list[PageRankScoreInstance] + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.graph_get_page_rank_scores_post_with_http_info( + **kwargs + ) # noqa: E501 + + def graph_get_page_rank_scores_post_with_http_info(self, **kwargs): # noqa: E501 + """page_rank # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_get_page_rank_scores_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param GetPageRankScoresRequest get_page_rank_scores_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(list[PageRankScoreInstance], status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["get_page_rank_scores_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method graph_get_page_rank_scores_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "get_page_rank_scores_request" in local_var_params: + body_params = local_var_params["get_page_rank_scores_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/graph/getPageRankScores", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="list[PageRankScoreInstance]", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def graph_upsert_edge_post(self, **kwargs): # noqa: E501 + """upsert_edge # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_upsert_edge_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param UpsertEdgeRequest upsert_edge_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: object + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.graph_upsert_edge_post_with_http_info(**kwargs) # noqa: E501 + + def graph_upsert_edge_post_with_http_info(self, **kwargs): # noqa: E501 + """upsert_edge # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_upsert_edge_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param UpsertEdgeRequest upsert_edge_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["upsert_edge_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method graph_upsert_edge_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "upsert_edge_request" in local_var_params: + body_params = local_var_params["upsert_edge_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/graph/upsertEdge", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="object", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def graph_upsert_vertex_post(self, **kwargs): # noqa: E501 + """upsert_vertex # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_upsert_vertex_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param UpsertVertexRequest upsert_vertex_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: object + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.graph_upsert_vertex_post_with_http_info(**kwargs) # noqa: E501 + + def graph_upsert_vertex_post_with_http_info(self, **kwargs): # noqa: E501 + """upsert_vertex # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_upsert_vertex_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param UpsertVertexRequest upsert_vertex_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["upsert_vertex_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method graph_upsert_vertex_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "upsert_vertex_request" in local_var_params: + body_params = local_var_params["upsert_vertex_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/graph/upsertVertex", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="object", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def graph_writer_graph_post(self, **kwargs): # noqa: E501 + """write_graph # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_writer_graph_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param WriterGraphRequest writer_graph_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: object + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.graph_writer_graph_post_with_http_info(**kwargs) # noqa: E501 + + def graph_writer_graph_post_with_http_info(self, **kwargs): # noqa: E501 + """write_graph # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_writer_graph_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param WriterGraphRequest writer_graph_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["writer_graph_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method graph_writer_graph_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "writer_graph_request" in local_var_params: + body_params = local_var_params["writer_graph_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/graph/writerGraph", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="object", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def graph_expend_one_hop_post(self, **kwargs): # noqa: E501 + """expend_one_hop # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_expend_one_hop_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ExpendOneHopRequest expend_one_hop_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: ExpendOneHopResponse + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.graph_expend_one_hop_post_with_http_info(**kwargs) # noqa: E501 + + def graph_expend_one_hop_post_with_http_info(self, **kwargs): # noqa: E501 + """expend_one_hop # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_expend_one_hop_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ExpendOneHopRequest expend_one_hop_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(ExpendOneHopResponse, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["expend_one_hop_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method graph_expend_one_hop_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "expend_one_hop_request" in local_var_params: + body_params = local_var_params["expend_one_hop_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/graph/expendOneHop", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="ExpendOneHopResponse", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def graph_query_vertex_post(self, **kwargs): # noqa: E501 + """query_vertex # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_query_vertex_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param QueryVertexRequest query_vertex_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: QueryVertexResponse + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.graph_query_vertex_post_with_http_info(**kwargs) # noqa: E501 + + def graph_query_vertex_post_with_http_info(self, **kwargs): # noqa: E501 + """query_vertex # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.graph_query_vertex_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param QueryVertexRequest query_vertex_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(QueryVertexResponse, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["query_vertex_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method graph_query_vertex_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "query_vertex_request" in local_var_params: + body_params = local_var_params["query_vertex_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/graph/queryVertex", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="QueryVertexResponse", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) diff --git a/knext/graph/rest/models/__init__.py b/knext/graph/rest/models/__init__.py new file mode 100644 index 00000000..6bfdb661 --- /dev/null +++ b/knext/graph/rest/models/__init__.py @@ -0,0 +1,40 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +# flake8: noqa + +from __future__ import absolute_import + +# import models into model package +from knext.graph.rest.models.get_page_rank_scores_request import ( + GetPageRankScoresRequest, +) +from knext.graph.rest.models.get_page_rank_scores_request_start_nodes import ( + GetPageRankScoresRequestStartNodes, +) +from knext.graph.rest.models.page_rank_score_instance import PageRankScoreInstance +from knext.graph.rest.models.delete_vertex_request import DeleteVertexRequest +from knext.graph.rest.models.delete_edge_request import DeleteEdgeRequest +from knext.graph.rest.models.edge_record_instance import EdgeRecordInstance +from knext.graph.rest.models.upsert_vertex_request import UpsertVertexRequest +from knext.graph.rest.models.upsert_edge_request import UpsertEdgeRequest +from knext.graph.rest.models.vertex_record_instance import VertexRecordInstance +from knext.graph.rest.models.writer_graph_request import WriterGraphRequest +from knext.graph.rest.models.edge_record import EdgeRecord +from knext.graph.rest.models.edge_type_name import EdgeTypeName +from knext.graph.rest.models.expend_one_hop_request import ExpendOneHopRequest +from knext.graph.rest.models.lpg_property_record import LpgPropertyRecord +from knext.graph.rest.models.query_vertex_request import QueryVertexRequest +from knext.graph.rest.models.query_vertex_response import QueryVertexResponse +from knext.graph.rest.models.vertex_record import VertexRecord +from knext.graph.rest.models.expend_one_hop_response import ExpendOneHopResponse diff --git a/knext/graph/rest/models/delete_edge_request.py b/knext/graph/rest/models/delete_edge_request.py new file mode 100644 index 00000000..71400901 --- /dev/null +++ b/knext/graph/rest/models/delete_edge_request.py @@ -0,0 +1,165 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class DeleteEdgeRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"project_id": "int", "edges": "list[EdgeRecordInstance]"} + + attribute_map = {"project_id": "projectId", "edges": "edges"} + + def __init__( + self, project_id=None, edges=None, local_vars_configuration=None + ): # noqa: E501 + """DeleteEdgeRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._edges = None + self.discriminator = None + + self.project_id = project_id + self.edges = edges + + @property + def project_id(self): + """Gets the project_id of this DeleteEdgeRequest. # noqa: E501 + + + :return: The project_id of this DeleteEdgeRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this DeleteEdgeRequest. + + + :param project_id: The project_id of this DeleteEdgeRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def edges(self): + """Gets the edges of this DeleteEdgeRequest. # noqa: E501 + + + :return: The edges of this DeleteEdgeRequest. # noqa: E501 + :rtype: list[EdgeRecordInstance] + """ + return self._edges + + @edges.setter + def edges(self, edges): + """Sets the edges of this DeleteEdgeRequest. + + + :param edges: The edges of this DeleteEdgeRequest. # noqa: E501 + :type: list[EdgeRecordInstance] + """ + if ( + self.local_vars_configuration.client_side_validation and edges is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `edges`, must not be `None`" + ) # noqa: E501 + + self._edges = edges + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, DeleteEdgeRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, DeleteEdgeRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/delete_vertex_request.py b/knext/graph/rest/models/delete_vertex_request.py new file mode 100644 index 00000000..843bed00 --- /dev/null +++ b/knext/graph/rest/models/delete_vertex_request.py @@ -0,0 +1,165 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class DeleteVertexRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"project_id": "int", "vertices": "list[VertexRecordInstance]"} + + attribute_map = {"project_id": "projectId", "vertices": "vertices"} + + def __init__( + self, project_id=None, vertices=None, local_vars_configuration=None + ): # noqa: E501 + """DeleteVertexRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._vertices = None + self.discriminator = None + + self.project_id = project_id + self.vertices = vertices + + @property + def project_id(self): + """Gets the project_id of this DeleteVertexRequest. # noqa: E501 + + + :return: The project_id of this DeleteVertexRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this DeleteVertexRequest. + + + :param project_id: The project_id of this DeleteVertexRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def vertices(self): + """Gets the vertices of this DeleteVertexRequest. # noqa: E501 + + + :return: The vertices of this DeleteVertexRequest. # noqa: E501 + :rtype: list[VertexRecordInstance] + """ + return self._vertices + + @vertices.setter + def vertices(self, vertices): + """Sets the vertices of this DeleteVertexRequest. + + + :param vertices: The vertices of this DeleteVertexRequest. # noqa: E501 + :type: list[VertexRecordInstance] + """ + if ( + self.local_vars_configuration.client_side_validation and vertices is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `vertices`, must not be `None`" + ) # noqa: E501 + + self._vertices = vertices + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, DeleteVertexRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, DeleteVertexRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/edge_record.py b/knext/graph/rest/models/edge_record.py new file mode 100644 index 00000000..12414040 --- /dev/null +++ b/knext/graph/rest/models/edge_record.py @@ -0,0 +1,245 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class EdgeRecord(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "record_type": "str", + "edge_type": "EdgeTypeName", + "src_id": "str", + "dst_id": "str", + "properties": "list[LpgPropertyRecord]", + } + + attribute_map = { + "record_type": "recordType", + "edge_type": "edgeType", + "src_id": "srcId", + "dst_id": "dstId", + "properties": "properties", + } + + def __init__( + self, + record_type=None, + edge_type=None, + src_id=None, + dst_id=None, + properties=None, + local_vars_configuration=None, + ): # noqa: E501 + """EdgeRecord - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._record_type = None + self._edge_type = None + self._src_id = None + self._dst_id = None + self._properties = None + self.discriminator = None + + if record_type is not None: + self.record_type = record_type + if edge_type is not None: + self.edge_type = edge_type + if src_id is not None: + self.src_id = src_id + if dst_id is not None: + self.dst_id = dst_id + if properties is not None: + self.properties = properties + + @property + def record_type(self): + """Gets the record_type of this EdgeRecord. # noqa: E501 + + + :return: The record_type of this EdgeRecord. # noqa: E501 + :rtype: str + """ + return self._record_type + + @record_type.setter + def record_type(self, record_type): + """Sets the record_type of this EdgeRecord. + + + :param record_type: The record_type of this EdgeRecord. # noqa: E501 + :type: str + """ + + self._record_type = record_type + + @property + def edge_type(self): + """Gets the edge_type of this EdgeRecord. # noqa: E501 + + + :return: The edge_type of this EdgeRecord. # noqa: E501 + :rtype: EdgeTypeName + """ + return self._edge_type + + @edge_type.setter + def edge_type(self, edge_type): + """Sets the edge_type of this EdgeRecord. + + + :param edge_type: The edge_type of this EdgeRecord. # noqa: E501 + :type: EdgeTypeName + """ + + self._edge_type = edge_type + + @property + def src_id(self): + """Gets the src_id of this EdgeRecord. # noqa: E501 + + + :return: The src_id of this EdgeRecord. # noqa: E501 + :rtype: str + """ + return self._src_id + + @src_id.setter + def src_id(self, src_id): + """Sets the src_id of this EdgeRecord. + + + :param src_id: The src_id of this EdgeRecord. # noqa: E501 + :type: str + """ + + self._src_id = src_id + + @property + def dst_id(self): + """Gets the dst_id of this EdgeRecord. # noqa: E501 + + + :return: The dst_id of this EdgeRecord. # noqa: E501 + :rtype: str + """ + return self._dst_id + + @dst_id.setter + def dst_id(self, dst_id): + """Sets the dst_id of this EdgeRecord. + + + :param dst_id: The dst_id of this EdgeRecord. # noqa: E501 + :type: str + """ + + self._dst_id = dst_id + + @property + def properties(self): + """Gets the properties of this EdgeRecord. # noqa: E501 + + + :return: The properties of this EdgeRecord. # noqa: E501 + :rtype: list[LpgPropertyRecord] + """ + return self._properties + + @properties.setter + def properties(self, properties): + """Sets the properties of this EdgeRecord. + + + :param properties: The properties of this EdgeRecord. # noqa: E501 + :type: list[LpgPropertyRecord] + """ + + self._properties = properties + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, EdgeRecord): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, EdgeRecord): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/edge_record_instance.py b/knext/graph/rest/models/edge_record_instance.py new file mode 100644 index 00000000..17205072 --- /dev/null +++ b/knext/graph/rest/models/edge_record_instance.py @@ -0,0 +1,302 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class EdgeRecordInstance(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "src_type": "str", + "src_id": "str", + "dst_type": "str", + "dst_id": "str", + "label": "str", + "properties": "object", + } + + attribute_map = { + "src_type": "srcType", + "src_id": "srcId", + "dst_type": "dstType", + "dst_id": "dstId", + "label": "label", + "properties": "properties", + } + + def __init__( + self, + src_type=None, + src_id=None, + dst_type=None, + dst_id=None, + label=None, + properties=None, + local_vars_configuration=None, + ): # noqa: E501 + """EdgeRecordInstance - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._src_type = None + self._src_id = None + self._dst_type = None + self._dst_id = None + self._label = None + self._properties = None + self.discriminator = None + + self.src_type = src_type + self.src_id = src_id + self.dst_type = dst_type + self.dst_id = dst_id + self.label = label + self.properties = properties + + @property + def src_type(self): + """Gets the src_type of this EdgeRecordInstance. # noqa: E501 + + + :return: The src_type of this EdgeRecordInstance. # noqa: E501 + :rtype: str + """ + return self._src_type + + @src_type.setter + def src_type(self, src_type): + """Sets the src_type of this EdgeRecordInstance. + + + :param src_type: The src_type of this EdgeRecordInstance. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and src_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `src_type`, must not be `None`" + ) # noqa: E501 + + self._src_type = src_type + + @property + def src_id(self): + """Gets the src_id of this EdgeRecordInstance. # noqa: E501 + + + :return: The src_id of this EdgeRecordInstance. # noqa: E501 + :rtype: str + """ + return self._src_id + + @src_id.setter + def src_id(self, src_id): + """Sets the src_id of this EdgeRecordInstance. + + + :param src_id: The src_id of this EdgeRecordInstance. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and src_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `src_id`, must not be `None`" + ) # noqa: E501 + + self._src_id = src_id + + @property + def dst_type(self): + """Gets the dst_type of this EdgeRecordInstance. # noqa: E501 + + + :return: The dst_type of this EdgeRecordInstance. # noqa: E501 + :rtype: str + """ + return self._dst_type + + @dst_type.setter + def dst_type(self, dst_type): + """Sets the dst_type of this EdgeRecordInstance. + + + :param dst_type: The dst_type of this EdgeRecordInstance. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and dst_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `dst_type`, must not be `None`" + ) # noqa: E501 + + self._dst_type = dst_type + + @property + def dst_id(self): + """Gets the dst_id of this EdgeRecordInstance. # noqa: E501 + + + :return: The dst_id of this EdgeRecordInstance. # noqa: E501 + :rtype: str + """ + return self._dst_id + + @dst_id.setter + def dst_id(self, dst_id): + """Sets the dst_id of this EdgeRecordInstance. + + + :param dst_id: The dst_id of this EdgeRecordInstance. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and dst_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `dst_id`, must not be `None`" + ) # noqa: E501 + + self._dst_id = dst_id + + @property + def label(self): + """Gets the label of this EdgeRecordInstance. # noqa: E501 + + + :return: The label of this EdgeRecordInstance. # noqa: E501 + :rtype: str + """ + return self._label + + @label.setter + def label(self, label): + """Sets the label of this EdgeRecordInstance. + + + :param label: The label of this EdgeRecordInstance. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and label is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `label`, must not be `None`" + ) # noqa: E501 + + self._label = label + + @property + def properties(self): + """Gets the properties of this EdgeRecordInstance. # noqa: E501 + + + :return: The properties of this EdgeRecordInstance. # noqa: E501 + :rtype: object + """ + return self._properties + + @properties.setter + def properties(self, properties): + """Sets the properties of this EdgeRecordInstance. + + + :param properties: The properties of this EdgeRecordInstance. # noqa: E501 + :type: object + """ + if ( + self.local_vars_configuration.client_side_validation and properties is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `properties`, must not be `None`" + ) # noqa: E501 + + self._properties = properties + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, EdgeRecordInstance): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, EdgeRecordInstance): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/edge_type_name.py b/knext/graph/rest/models/edge_type_name.py new file mode 100644 index 00000000..fcdeafa0 --- /dev/null +++ b/knext/graph/rest/models/edge_type_name.py @@ -0,0 +1,208 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class EdgeTypeName(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "start_vertex_type": "str", + "edge_label": "str", + "end_vertex_type": "str", + } + + attribute_map = { + "start_vertex_type": "startVertexType", + "edge_label": "edgeLabel", + "end_vertex_type": "endVertexType", + } + + def __init__( + self, + start_vertex_type=None, + edge_label=None, + end_vertex_type=None, + local_vars_configuration=None, + ): # noqa: E501 + """EdgeTypeName - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._start_vertex_type = None + self._edge_label = None + self._end_vertex_type = None + self.discriminator = None + + self.start_vertex_type = start_vertex_type + self.edge_label = edge_label + self.end_vertex_type = end_vertex_type + + @property + def start_vertex_type(self): + """Gets the start_vertex_type of this EdgeTypeName. # noqa: E501 + + + :return: The start_vertex_type of this EdgeTypeName. # noqa: E501 + :rtype: str + """ + return self._start_vertex_type + + @start_vertex_type.setter + def start_vertex_type(self, start_vertex_type): + """Sets the start_vertex_type of this EdgeTypeName. + + + :param start_vertex_type: The start_vertex_type of this EdgeTypeName. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and start_vertex_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `start_vertex_type`, must not be `None`" + ) # noqa: E501 + + self._start_vertex_type = start_vertex_type + + @property + def edge_label(self): + """Gets the edge_label of this EdgeTypeName. # noqa: E501 + + + :return: The edge_label of this EdgeTypeName. # noqa: E501 + :rtype: str + """ + return self._edge_label + + @edge_label.setter + def edge_label(self, edge_label): + """Sets the edge_label of this EdgeTypeName. + + + :param edge_label: The edge_label of this EdgeTypeName. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and edge_label is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `edge_label`, must not be `None`" + ) # noqa: E501 + + self._edge_label = edge_label + + @property + def end_vertex_type(self): + """Gets the end_vertex_type of this EdgeTypeName. # noqa: E501 + + + :return: The end_vertex_type of this EdgeTypeName. # noqa: E501 + :rtype: str + """ + return self._end_vertex_type + + @end_vertex_type.setter + def end_vertex_type(self, end_vertex_type): + """Sets the end_vertex_type of this EdgeTypeName. + + + :param end_vertex_type: The end_vertex_type of this EdgeTypeName. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and end_vertex_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `end_vertex_type`, must not be `None`" + ) # noqa: E501 + + self._end_vertex_type = end_vertex_type + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, EdgeTypeName): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, EdgeTypeName): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/expend_one_hop_request.py b/knext/graph/rest/models/expend_one_hop_request.py new file mode 100644 index 00000000..94c339c5 --- /dev/null +++ b/knext/graph/rest/models/expend_one_hop_request.py @@ -0,0 +1,232 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ExpendOneHopRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "project_id": "int", + "type_name": "str", + "biz_id": "str", + "edge_type_name_constraint": "list[EdgeTypeName]", + } + + attribute_map = { + "project_id": "projectId", + "type_name": "typeName", + "biz_id": "bizId", + "edge_type_name_constraint": "edgeTypeNameConstraint", + } + + def __init__( + self, + project_id=None, + type_name=None, + biz_id=None, + edge_type_name_constraint=None, + local_vars_configuration=None, + ): # noqa: E501 + """ExpendOneHopRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._type_name = None + self._biz_id = None + self._edge_type_name_constraint = None + self.discriminator = None + + self.project_id = project_id + self.type_name = type_name + self.biz_id = biz_id + self.edge_type_name_constraint = edge_type_name_constraint + + @property + def project_id(self): + """Gets the project_id of this ExpendOneHopRequest. # noqa: E501 + + + :return: The project_id of this ExpendOneHopRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this ExpendOneHopRequest. + + + :param project_id: The project_id of this ExpendOneHopRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def type_name(self): + """Gets the type_name of this ExpendOneHopRequest. # noqa: E501 + + + :return: The type_name of this ExpendOneHopRequest. # noqa: E501 + :rtype: str + """ + return self._type_name + + @type_name.setter + def type_name(self, type_name): + """Sets the type_name of this ExpendOneHopRequest. + + + :param type_name: The type_name of this ExpendOneHopRequest. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and type_name is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `type_name`, must not be `None`" + ) # noqa: E501 + + self._type_name = type_name + + @property + def biz_id(self): + """Gets the biz_id of this ExpendOneHopRequest. # noqa: E501 + + + :return: The biz_id of this ExpendOneHopRequest. # noqa: E501 + :rtype: str + """ + return self._biz_id + + @biz_id.setter + def biz_id(self, biz_id): + """Sets the biz_id of this ExpendOneHopRequest. + + + :param biz_id: The biz_id of this ExpendOneHopRequest. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and biz_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `biz_id`, must not be `None`" + ) # noqa: E501 + + self._biz_id = biz_id + + @property + def edge_type_name_constraint(self): + """Gets the edge_type_name_constraint of this ExpendOneHopRequest. # noqa: E501 + + + :return: The edge_type_name_constraint of this ExpendOneHopRequest. # noqa: E501 + :rtype: list[EdgeTypeName] + """ + return self._edge_type_name_constraint + + @edge_type_name_constraint.setter + def edge_type_name_constraint(self, edge_type_name_constraint): + """Sets the edge_type_name_constraint of this ExpendOneHopRequest. + + + :param edge_type_name_constraint: The edge_type_name_constraint of this ExpendOneHopRequest. # noqa: E501 + :type: list[EdgeTypeName] + """ + + self._edge_type_name_constraint = edge_type_name_constraint + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ExpendOneHopRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ExpendOneHopRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/expend_one_hop_response.py b/knext/graph/rest/models/expend_one_hop_response.py new file mode 100644 index 00000000..fdc03665 --- /dev/null +++ b/knext/graph/rest/models/expend_one_hop_response.py @@ -0,0 +1,191 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ExpendOneHopResponse(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "vertex": "VertexRecord", + "edges": "list[EdgeRecord]", + "adjacent_vertices": "list[VertexRecord]", + } + + attribute_map = { + "vertex": "vertex", + "edges": "edges", + "adjacent_vertices": "adjacentVertices", + } + + def __init__( + self, + vertex=None, + edges=None, + adjacent_vertices=None, + local_vars_configuration=None, + ): # noqa: E501 + """ExpendOneHopResponse - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._vertex = None + self._edges = None + self._adjacent_vertices = None + self.discriminator = None + + if vertex is not None: + self.vertex = vertex + if edges is not None: + self.edges = edges + if adjacent_vertices is not None: + self.adjacent_vertices = adjacent_vertices + + @property + def vertex(self): + """Gets the vertex of this ExpendOneHopResponse. # noqa: E501 + + + :return: The vertex of this ExpendOneHopResponse. # noqa: E501 + :rtype: VertexRecord + """ + return self._vertex + + @vertex.setter + def vertex(self, vertex): + """Sets the vertex of this ExpendOneHopResponse. + + + :param vertex: The vertex of this ExpendOneHopResponse. # noqa: E501 + :type: VertexRecord + """ + + self._vertex = vertex + + @property + def edges(self): + """Gets the edges of this ExpendOneHopResponse. # noqa: E501 + + + :return: The edges of this ExpendOneHopResponse. # noqa: E501 + :rtype: list[EdgeRecord] + """ + return self._edges + + @edges.setter + def edges(self, edges): + """Sets the edges of this ExpendOneHopResponse. + + + :param edges: The edges of this ExpendOneHopResponse. # noqa: E501 + :type: list[EdgeRecord] + """ + + self._edges = edges + + @property + def adjacent_vertices(self): + """Gets the adjacent_vertices of this ExpendOneHopResponse. # noqa: E501 + + + :return: The adjacent_vertices of this ExpendOneHopResponse. # noqa: E501 + :rtype: list[VertexRecord] + """ + return self._adjacent_vertices + + @adjacent_vertices.setter + def adjacent_vertices(self, adjacent_vertices): + """Sets the adjacent_vertices of this ExpendOneHopResponse. + + + :param adjacent_vertices: The adjacent_vertices of this ExpendOneHopResponse. # noqa: E501 + :type: list[VertexRecord] + """ + + self._adjacent_vertices = adjacent_vertices + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ExpendOneHopResponse): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ExpendOneHopResponse): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/get_page_rank_scores_request.py b/knext/graph/rest/models/get_page_rank_scores_request.py new file mode 100644 index 00000000..032e251a --- /dev/null +++ b/knext/graph/rest/models/get_page_rank_scores_request.py @@ -0,0 +1,207 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class GetPageRankScoresRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "project_id": "int", + "target_vertex_type": "str", + "start_nodes": "list[GetPageRankScoresRequestStartNodes]", + } + + attribute_map = { + "project_id": "projectId", + "target_vertex_type": "targetVertexType", + "start_nodes": "startNodes", + } + + def __init__( + self, + project_id=None, + target_vertex_type=None, + start_nodes=None, + local_vars_configuration=None, + ): # noqa: E501 + """GetPageRankScoresRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._target_vertex_type = None + self._start_nodes = None + self.discriminator = None + + self.project_id = project_id + self.target_vertex_type = target_vertex_type + self.start_nodes = start_nodes + + @property + def project_id(self): + """Gets the project_id of this GetPageRankScoresRequest. # noqa: E501 + + + :return: The project_id of this GetPageRankScoresRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this GetPageRankScoresRequest. + + + :param project_id: The project_id of this GetPageRankScoresRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def target_vertex_type(self): + """Gets the target_vertex_type of this GetPageRankScoresRequest. # noqa: E501 + + + :return: The target_vertex_type of this GetPageRankScoresRequest. # noqa: E501 + :rtype: str + """ + return self._target_vertex_type + + @target_vertex_type.setter + def target_vertex_type(self, target_vertex_type): + """Sets the target_vertex_type of this GetPageRankScoresRequest. + + + :param target_vertex_type: The target_vertex_type of this GetPageRankScoresRequest. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and target_vertex_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `target_vertex_type`, must not be `None`" + ) # noqa: E501 + + self._target_vertex_type = target_vertex_type + + @property + def start_nodes(self): + """Gets the start_nodes of this GetPageRankScoresRequest. # noqa: E501 + + + :return: The start_nodes of this GetPageRankScoresRequest. # noqa: E501 + :rtype: list[GetPageRankScoresRequestStartNodes] + """ + return self._start_nodes + + @start_nodes.setter + def start_nodes(self, start_nodes): + """Sets the start_nodes of this GetPageRankScoresRequest. + + + :param start_nodes: The start_nodes of this GetPageRankScoresRequest. # noqa: E501 + :type: list[GetPageRankScoresRequestStartNodes] + """ + if ( + self.local_vars_configuration.client_side_validation and start_nodes is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `start_nodes`, must not be `None`" + ) # noqa: E501 + + self._start_nodes = start_nodes + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, GetPageRankScoresRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, GetPageRankScoresRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/get_page_rank_scores_request_start_nodes.py b/knext/graph/rest/models/get_page_rank_scores_request_start_nodes.py new file mode 100644 index 00000000..9357b4fa --- /dev/null +++ b/knext/graph/rest/models/get_page_rank_scores_request_start_nodes.py @@ -0,0 +1,226 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class GetPageRankScoresRequestStartNodes(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "type": "str", + "id": "str", + "properties": "object", + "vectors": "object", + } + + attribute_map = { + "type": "type", + "id": "id", + "properties": "properties", + "vectors": "vectors", + } + + def __init__( + self, + type=None, + id=None, + properties=None, + vectors=None, + local_vars_configuration=None, + ): # noqa: E501 + """GetPageRankScoresRequestStartNodes - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._type = None + self._id = None + self._properties = None + self._vectors = None + self.discriminator = None + + self.type = type + self.id = id + if properties is not None: + self.properties = properties + if vectors is not None: + self.vectors = vectors + + @property + def type(self): + """Gets the type of this GetPageRankScoresRequestStartNodes. # noqa: E501 + + + :return: The type of this GetPageRankScoresRequestStartNodes. # noqa: E501 + :rtype: str + """ + return self._type + + @type.setter + def type(self, type): + """Sets the type of this GetPageRankScoresRequestStartNodes. + + + :param type: The type of this GetPageRankScoresRequestStartNodes. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `type`, must not be `None`" + ) # noqa: E501 + + self._type = type + + @property + def id(self): + """Gets the id of this GetPageRankScoresRequestStartNodes. # noqa: E501 + + + :return: The id of this GetPageRankScoresRequestStartNodes. # noqa: E501 + :rtype: str + """ + return self._id + + @id.setter + def id(self, id): + """Sets the id of this GetPageRankScoresRequestStartNodes. + + + :param id: The id of this GetPageRankScoresRequestStartNodes. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and id is None + ): # noqa: E501 + raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 + + self._id = id + + @property + def properties(self): + """Gets the properties of this GetPageRankScoresRequestStartNodes. # noqa: E501 + + + :return: The properties of this GetPageRankScoresRequestStartNodes. # noqa: E501 + :rtype: object + """ + return self._properties + + @properties.setter + def properties(self, properties): + """Sets the properties of this GetPageRankScoresRequestStartNodes. + + + :param properties: The properties of this GetPageRankScoresRequestStartNodes. # noqa: E501 + :type: object + """ + + self._properties = properties + + @property + def vectors(self): + """Gets the vectors of this GetPageRankScoresRequestStartNodes. # noqa: E501 + + + :return: The vectors of this GetPageRankScoresRequestStartNodes. # noqa: E501 + :rtype: object + """ + return self._vectors + + @vectors.setter + def vectors(self, vectors): + """Sets the vectors of this GetPageRankScoresRequestStartNodes. + + + :param vectors: The vectors of this GetPageRankScoresRequestStartNodes. # noqa: E501 + :type: object + """ + + self._vectors = vectors + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, GetPageRankScoresRequestStartNodes): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, GetPageRankScoresRequestStartNodes): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/lpg_property_record.py b/knext/graph/rest/models/lpg_property_record.py new file mode 100644 index 00000000..33668e0a --- /dev/null +++ b/knext/graph/rest/models/lpg_property_record.py @@ -0,0 +1,160 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class LpgPropertyRecord(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"name": "str", "value": "str"} + + attribute_map = {"name": "name", "value": "value"} + + def __init__( + self, name=None, value=None, local_vars_configuration=None + ): # noqa: E501 + """LpgPropertyRecord - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._name = None + self._value = None + self.discriminator = None + + self.name = name + if value is not None: + self.value = value + + @property + def name(self): + """Gets the name of this LpgPropertyRecord. # noqa: E501 + + + :return: The name of this LpgPropertyRecord. # noqa: E501 + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this LpgPropertyRecord. + + + :param name: The name of this LpgPropertyRecord. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and name is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `name`, must not be `None`" + ) # noqa: E501 + + self._name = name + + @property + def value(self): + """Gets the value of this LpgPropertyRecord. # noqa: E501 + + + :return: The value of this LpgPropertyRecord. # noqa: E501 + :rtype: str + """ + return self._value + + @value.setter + def value(self, value): + """Sets the value of this LpgPropertyRecord. + + + :param value: The value of this LpgPropertyRecord. # noqa: E501 + :type: str + """ + + self._value = value + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, LpgPropertyRecord): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, LpgPropertyRecord): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/page_rank_score_instance.py b/knext/graph/rest/models/page_rank_score_instance.py new file mode 100644 index 00000000..65a9ac63 --- /dev/null +++ b/knext/graph/rest/models/page_rank_score_instance.py @@ -0,0 +1,192 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class PageRankScoreInstance(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"type": "str", "id": "str", "score": "float"} + + attribute_map = {"type": "type", "id": "id", "score": "score"} + + def __init__( + self, type=None, id=None, score=None, local_vars_configuration=None + ): # noqa: E501 + """PageRankScoreInstance - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._type = None + self._id = None + self._score = None + self.discriminator = None + + self.type = type + self.id = id + self.score = score + + @property + def type(self): + """Gets the type of this PageRankScoreInstance. # noqa: E501 + + + :return: The type of this PageRankScoreInstance. # noqa: E501 + :rtype: str + """ + return self._type + + @type.setter + def type(self, type): + """Sets the type of this PageRankScoreInstance. + + + :param type: The type of this PageRankScoreInstance. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `type`, must not be `None`" + ) # noqa: E501 + + self._type = type + + @property + def id(self): + """Gets the id of this PageRankScoreInstance. # noqa: E501 + + + :return: The id of this PageRankScoreInstance. # noqa: E501 + :rtype: str + """ + return self._id + + @id.setter + def id(self, id): + """Sets the id of this PageRankScoreInstance. + + + :param id: The id of this PageRankScoreInstance. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and id is None + ): # noqa: E501 + raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 + + self._id = id + + @property + def score(self): + """Gets the score of this PageRankScoreInstance. # noqa: E501 + + + :return: The score of this PageRankScoreInstance. # noqa: E501 + :rtype: float + """ + return self._score + + @score.setter + def score(self, score): + """Sets the score of this PageRankScoreInstance. + + + :param score: The score of this PageRankScoreInstance. # noqa: E501 + :type: float + """ + if ( + self.local_vars_configuration.client_side_validation and score is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `score`, must not be `None`" + ) # noqa: E501 + + self._score = score + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, PageRankScoreInstance): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, PageRankScoreInstance): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/query_vertex_request.py b/knext/graph/rest/models/query_vertex_request.py new file mode 100644 index 00000000..81ea26a6 --- /dev/null +++ b/knext/graph/rest/models/query_vertex_request.py @@ -0,0 +1,202 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class QueryVertexRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"project_id": "int", "type_name": "str", "biz_id": "str"} + + attribute_map = { + "project_id": "projectId", + "type_name": "typeName", + "biz_id": "bizId", + } + + def __init__( + self, + project_id=None, + type_name=None, + biz_id=None, + local_vars_configuration=None, + ): # noqa: E501 + """QueryVertexRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._type_name = None + self._biz_id = None + self.discriminator = None + + self.project_id = project_id + self.type_name = type_name + self.biz_id = biz_id + + @property + def project_id(self): + """Gets the project_id of this QueryVertexRequest. # noqa: E501 + + + :return: The project_id of this QueryVertexRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this QueryVertexRequest. + + + :param project_id: The project_id of this QueryVertexRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def type_name(self): + """Gets the type_name of this QueryVertexRequest. # noqa: E501 + + + :return: The type_name of this QueryVertexRequest. # noqa: E501 + :rtype: str + """ + return self._type_name + + @type_name.setter + def type_name(self, type_name): + """Sets the type_name of this QueryVertexRequest. + + + :param type_name: The type_name of this QueryVertexRequest. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and type_name is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `type_name`, must not be `None`" + ) # noqa: E501 + + self._type_name = type_name + + @property + def biz_id(self): + """Gets the biz_id of this QueryVertexRequest. # noqa: E501 + + + :return: The biz_id of this QueryVertexRequest. # noqa: E501 + :rtype: str + """ + return self._biz_id + + @biz_id.setter + def biz_id(self, biz_id): + """Sets the biz_id of this QueryVertexRequest. + + + :param biz_id: The biz_id of this QueryVertexRequest. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and biz_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `biz_id`, must not be `None`" + ) # noqa: E501 + + self._biz_id = biz_id + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, QueryVertexRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, QueryVertexRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/query_vertex_response.py b/knext/graph/rest/models/query_vertex_response.py new file mode 100644 index 00000000..eb48a99d --- /dev/null +++ b/knext/graph/rest/models/query_vertex_response.py @@ -0,0 +1,129 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class QueryVertexResponse(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"vertex": "VertexRecord"} + + attribute_map = {"vertex": "vertex"} + + def __init__(self, vertex=None, local_vars_configuration=None): # noqa: E501 + """QueryVertexResponse - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._vertex = None + self.discriminator = None + + if vertex is not None: + self.vertex = vertex + + @property + def vertex(self): + """Gets the vertex of this QueryVertexResponse. # noqa: E501 + + + :return: The vertex of this QueryVertexResponse. # noqa: E501 + :rtype: VertexRecord + """ + return self._vertex + + @vertex.setter + def vertex(self, vertex): + """Sets the vertex of this QueryVertexResponse. + + + :param vertex: The vertex of this QueryVertexResponse. # noqa: E501 + :type: VertexRecord + """ + + self._vertex = vertex + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, QueryVertexResponse): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, QueryVertexResponse): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/upsert_edge_request.py b/knext/graph/rest/models/upsert_edge_request.py new file mode 100644 index 00000000..74e786a0 --- /dev/null +++ b/knext/graph/rest/models/upsert_edge_request.py @@ -0,0 +1,207 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class UpsertEdgeRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "project_id": "int", + "upsert_adjacent_vertices": "bool", + "edges": "list[EdgeRecordInstance]", + } + + attribute_map = { + "project_id": "projectId", + "upsert_adjacent_vertices": "upsertAdjacentVertices", + "edges": "edges", + } + + def __init__( + self, + project_id=None, + upsert_adjacent_vertices=None, + edges=None, + local_vars_configuration=None, + ): # noqa: E501 + """UpsertEdgeRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._upsert_adjacent_vertices = None + self._edges = None + self.discriminator = None + + self.project_id = project_id + self.upsert_adjacent_vertices = upsert_adjacent_vertices + self.edges = edges + + @property + def project_id(self): + """Gets the project_id of this UpsertEdgeRequest. # noqa: E501 + + + :return: The project_id of this UpsertEdgeRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this UpsertEdgeRequest. + + + :param project_id: The project_id of this UpsertEdgeRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def upsert_adjacent_vertices(self): + """Gets the upsert_adjacent_vertices of this UpsertEdgeRequest. # noqa: E501 + + + :return: The upsert_adjacent_vertices of this UpsertEdgeRequest. # noqa: E501 + :rtype: bool + """ + return self._upsert_adjacent_vertices + + @upsert_adjacent_vertices.setter + def upsert_adjacent_vertices(self, upsert_adjacent_vertices): + """Sets the upsert_adjacent_vertices of this UpsertEdgeRequest. + + + :param upsert_adjacent_vertices: The upsert_adjacent_vertices of this UpsertEdgeRequest. # noqa: E501 + :type: bool + """ + if ( + self.local_vars_configuration.client_side_validation + and upsert_adjacent_vertices is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `upsert_adjacent_vertices`, must not be `None`" + ) # noqa: E501 + + self._upsert_adjacent_vertices = upsert_adjacent_vertices + + @property + def edges(self): + """Gets the edges of this UpsertEdgeRequest. # noqa: E501 + + + :return: The edges of this UpsertEdgeRequest. # noqa: E501 + :rtype: list[EdgeRecordInstance] + """ + return self._edges + + @edges.setter + def edges(self, edges): + """Sets the edges of this UpsertEdgeRequest. + + + :param edges: The edges of this UpsertEdgeRequest. # noqa: E501 + :type: list[EdgeRecordInstance] + """ + if ( + self.local_vars_configuration.client_side_validation and edges is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `edges`, must not be `None`" + ) # noqa: E501 + + self._edges = edges + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, UpsertEdgeRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, UpsertEdgeRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/upsert_vertex_request.py b/knext/graph/rest/models/upsert_vertex_request.py new file mode 100644 index 00000000..6982f49c --- /dev/null +++ b/knext/graph/rest/models/upsert_vertex_request.py @@ -0,0 +1,165 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class UpsertVertexRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"project_id": "int", "vertices": "list[VertexRecordInstance]"} + + attribute_map = {"project_id": "projectId", "vertices": "vertices"} + + def __init__( + self, project_id=None, vertices=None, local_vars_configuration=None + ): # noqa: E501 + """UpsertVertexRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._vertices = None + self.discriminator = None + + self.project_id = project_id + self.vertices = vertices + + @property + def project_id(self): + """Gets the project_id of this UpsertVertexRequest. # noqa: E501 + + + :return: The project_id of this UpsertVertexRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this UpsertVertexRequest. + + + :param project_id: The project_id of this UpsertVertexRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def vertices(self): + """Gets the vertices of this UpsertVertexRequest. # noqa: E501 + + + :return: The vertices of this UpsertVertexRequest. # noqa: E501 + :rtype: list[VertexRecordInstance] + """ + return self._vertices + + @vertices.setter + def vertices(self, vertices): + """Sets the vertices of this UpsertVertexRequest. + + + :param vertices: The vertices of this UpsertVertexRequest. # noqa: E501 + :type: list[VertexRecordInstance] + """ + if ( + self.local_vars_configuration.client_side_validation and vertices is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `vertices`, must not be `None`" + ) # noqa: E501 + + self._vertices = vertices + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, UpsertVertexRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, UpsertVertexRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/vertex_record.py b/knext/graph/rest/models/vertex_record.py new file mode 100644 index 00000000..9ed57e28 --- /dev/null +++ b/knext/graph/rest/models/vertex_record.py @@ -0,0 +1,218 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class VertexRecord(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "record_type": "str", + "vertex_type": "str", + "id": "str", + "properties": "list[LpgPropertyRecord]", + } + + attribute_map = { + "record_type": "recordType", + "vertex_type": "vertexType", + "id": "id", + "properties": "properties", + } + + def __init__( + self, + record_type=None, + vertex_type=None, + id=None, + properties=None, + local_vars_configuration=None, + ): # noqa: E501 + """VertexRecord - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._record_type = None + self._vertex_type = None + self._id = None + self._properties = None + self.discriminator = None + + if record_type is not None: + self.record_type = record_type + if vertex_type is not None: + self.vertex_type = vertex_type + if id is not None: + self.id = id + if properties is not None: + self.properties = properties + + @property + def record_type(self): + """Gets the record_type of this VertexRecord. # noqa: E501 + + + :return: The record_type of this VertexRecord. # noqa: E501 + :rtype: str + """ + return self._record_type + + @record_type.setter + def record_type(self, record_type): + """Sets the record_type of this VertexRecord. + + + :param record_type: The record_type of this VertexRecord. # noqa: E501 + :type: str + """ + + self._record_type = record_type + + @property + def vertex_type(self): + """Gets the vertex_type of this VertexRecord. # noqa: E501 + + + :return: The vertex_type of this VertexRecord. # noqa: E501 + :rtype: str + """ + return self._vertex_type + + @vertex_type.setter + def vertex_type(self, vertex_type): + """Sets the vertex_type of this VertexRecord. + + + :param vertex_type: The vertex_type of this VertexRecord. # noqa: E501 + :type: str + """ + + self._vertex_type = vertex_type + + @property + def id(self): + """Gets the id of this VertexRecord. # noqa: E501 + + + :return: The id of this VertexRecord. # noqa: E501 + :rtype: str + """ + return self._id + + @id.setter + def id(self, id): + """Sets the id of this VertexRecord. + + + :param id: The id of this VertexRecord. # noqa: E501 + :type: str + """ + + self._id = id + + @property + def properties(self): + """Gets the properties of this VertexRecord. # noqa: E501 + + + :return: The properties of this VertexRecord. # noqa: E501 + :rtype: list[LpgPropertyRecord] + """ + return self._properties + + @properties.setter + def properties(self, properties): + """Sets the properties of this VertexRecord. + + + :param properties: The properties of this VertexRecord. # noqa: E501 + :type: list[LpgPropertyRecord] + """ + + self._properties = properties + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, VertexRecord): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, VertexRecord): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/vertex_record_instance.py b/knext/graph/rest/models/vertex_record_instance.py new file mode 100644 index 00000000..675e4246 --- /dev/null +++ b/knext/graph/rest/models/vertex_record_instance.py @@ -0,0 +1,236 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class VertexRecordInstance(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "type": "str", + "id": "str", + "properties": "object", + "vectors": "object", + } + + attribute_map = { + "type": "type", + "id": "id", + "properties": "properties", + "vectors": "vectors", + } + + def __init__( + self, + type=None, + id=None, + properties=None, + vectors=None, + local_vars_configuration=None, + ): # noqa: E501 + """VertexRecordInstance - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._type = None + self._id = None + self._properties = None + self._vectors = None + self.discriminator = None + + self.type = type + self.id = id + self.properties = properties + self.vectors = vectors + + @property + def type(self): + """Gets the type of this VertexRecordInstance. # noqa: E501 + + + :return: The type of this VertexRecordInstance. # noqa: E501 + :rtype: str + """ + return self._type + + @type.setter + def type(self, type): + """Sets the type of this VertexRecordInstance. + + + :param type: The type of this VertexRecordInstance. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `type`, must not be `None`" + ) # noqa: E501 + + self._type = type + + @property + def id(self): + """Gets the id of this VertexRecordInstance. # noqa: E501 + + + :return: The id of this VertexRecordInstance. # noqa: E501 + :rtype: str + """ + return self._id + + @id.setter + def id(self, id): + """Sets the id of this VertexRecordInstance. + + + :param id: The id of this VertexRecordInstance. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and id is None + ): # noqa: E501 + raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 + + self._id = id + + @property + def properties(self): + """Gets the properties of this VertexRecordInstance. # noqa: E501 + + + :return: The properties of this VertexRecordInstance. # noqa: E501 + :rtype: object + """ + return self._properties + + @properties.setter + def properties(self, properties): + """Sets the properties of this VertexRecordInstance. + + + :param properties: The properties of this VertexRecordInstance. # noqa: E501 + :type: object + """ + if ( + self.local_vars_configuration.client_side_validation and properties is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `properties`, must not be `None`" + ) # noqa: E501 + + self._properties = properties + + @property + def vectors(self): + """Gets the vectors of this VertexRecordInstance. # noqa: E501 + + + :return: The vectors of this VertexRecordInstance. # noqa: E501 + :rtype: object + """ + return self._vectors + + @vectors.setter + def vectors(self, vectors): + """Sets the vectors of this VertexRecordInstance. + + + :param vectors: The vectors of this VertexRecordInstance. # noqa: E501 + :type: object + """ + if ( + self.local_vars_configuration.client_side_validation and vectors is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `vectors`, must not be `None`" + ) # noqa: E501 + + self._vectors = vectors + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, VertexRecordInstance): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, VertexRecordInstance): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/graph/rest/models/writer_graph_request.py b/knext/graph/rest/models/writer_graph_request.py new file mode 100644 index 00000000..dca97030 --- /dev/null +++ b/knext/graph/rest/models/writer_graph_request.py @@ -0,0 +1,218 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class WriterGraphRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "project_id": "int", + "operation": "str", + "sub_graph": "object", + "enable_lead_to": "bool", + } + + attribute_map = { + "project_id": "projectId", + "operation": "operation", + "sub_graph": "subGraph", + "enable_lead_to": "enableLeadTo", + } + + def __init__( + self, + project_id=None, + operation=None, + sub_graph=None, + enable_lead_to=None, + local_vars_configuration=None, + ): # noqa: E501 + """WriterGraphRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._operation = None + self._sub_graph = None + self._enable_lead_to = None + self.discriminator = None + + if project_id is not None: + self.project_id = project_id + if operation is not None: + self.operation = operation + if sub_graph is not None: + self.sub_graph = sub_graph + if enable_lead_to is not None: + self.enable_lead_to = enable_lead_to + + @property + def project_id(self): + """Gets the project_id of this WriterGraphRequest. # noqa: E501 + + + :return: The project_id of this WriterGraphRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this WriterGraphRequest. + + + :param project_id: The project_id of this WriterGraphRequest. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def operation(self): + """Gets the operation of this WriterGraphRequest. # noqa: E501 + + + :return: The operation of this WriterGraphRequest. # noqa: E501 + :rtype: str + """ + return self._operation + + @operation.setter + def operation(self, operation): + """Sets the operation of this WriterGraphRequest. + + + :param operation: The operation of this WriterGraphRequest. # noqa: E501 + :type: str + """ + + self._operation = operation + + @property + def sub_graph(self): + """Gets the sub_graph of this WriterGraphRequest. # noqa: E501 + + + :return: The sub_graph of this WriterGraphRequest. # noqa: E501 + :rtype: object + """ + return self._sub_graph + + @sub_graph.setter + def sub_graph(self, sub_graph): + """Sets the sub_graph of this WriterGraphRequest. + + + :param sub_graph: The sub_graph of this WriterGraphRequest. # noqa: E501 + :type: object + """ + + self._sub_graph = sub_graph + + @property + def enable_lead_to(self): + """Gets the enable_lead_to of this WriterGraphRequest. # noqa: E501 + + + :return: The enable_lead_to of this WriterGraphRequest. # noqa: E501 + :rtype: bool + """ + return self._enable_lead_to + + @enable_lead_to.setter + def enable_lead_to(self, enable_lead_to): + """Sets the enable_lead_to of this WriterGraphRequest. + + + :param enable_lead_to: The enable_lead_to of this WriterGraphRequest. # noqa: E501 + :type: bool + """ + + self._enable_lead_to = enable_lead_to + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, WriterGraphRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, WriterGraphRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/project/__init__.py b/knext/project/__init__.py new file mode 100644 index 00000000..e5399987 --- /dev/null +++ b/knext/project/__init__.py @@ -0,0 +1,16 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + +DEFAULT_SCHEMA_DIR = "schema" +DEFAULT_SCHEMA_FILE = "$namespace.schema" +DEFAULT_BUILDER_DIR = "builder" +DEFAULT_REASONER_DIR = "reasoner" diff --git a/knext/project/client.py b/knext/project/client.py new file mode 100644 index 00000000..c413b1dd --- /dev/null +++ b/knext/project/client.py @@ -0,0 +1,76 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. +import json +import os + +from knext.common.base.client import Client +from knext.common.rest import Configuration, ApiClient +from knext.project import rest + + +class ProjectClient(Client): + """ """ + + def __init__(self, host_addr: str = None, project_id: int = None): + super().__init__(host_addr, project_id) + self._rest_client: rest.ProjectApi = rest.ProjectApi( + api_client=ApiClient(configuration=Configuration(host=host_addr)) + ) + + def get_config(self, project_id: str): + project = self.get(id=int(project_id or os.getenv("KAG_PROJECT_ID"))) + if not project: + return {} + config = project.config + config = json.loads(config) if config else {} + return config + + def get(self, **conditions): + projects = self._rest_client.project_get() + for project in projects: + condition = True + for k, v in conditions.items(): + condition = condition and str(getattr(project, k)) == str(v) + if condition: + return project + return None + + def get_by_namespace(self, namespace: str): + projects = self._rest_client.project_get() + for project in projects: + if str(project.namespace) == str(namespace): + return project + return None + + def create(self, name: str, namespace: str, desc: str = None, auto_schema=False): + project_create_request = rest.ProjectCreateRequest( + name=name, desc=desc, namespace=namespace, auto_schema=auto_schema + ) + + project = self._rest_client.project_create_post( + project_create_request=project_create_request + ) + return project + + def update(self, id, config): + project_create_request = rest.ProjectCreateRequest(id=id, config=config) + project = self._rest_client.update_post( + project_create_request=project_create_request + ) + return project + + def get_all(self): + project_list = {} + projects = self._rest_client.project_get() + for project in projects: + project_list[project.namespace] = project.id + return project_list diff --git a/knext/project/rest/__init__.py b/knext/project/rest/__init__.py new file mode 100644 index 00000000..eda2e9c3 --- /dev/null +++ b/knext/project/rest/__init__.py @@ -0,0 +1,34 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +# flake8: noqa + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from __future__ import absolute_import + +__version__ = "1" + +# import apis into sdk package +from knext.project.rest.project_api import ProjectApi + +# import models into sdk package +from knext.project.rest.models.project import Project +from knext.project.rest.models.project_create_request import ProjectCreateRequest diff --git a/knext/project/rest/models/__init__.py b/knext/project/rest/models/__init__.py new file mode 100644 index 00000000..32bd1d5a --- /dev/null +++ b/knext/project/rest/models/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. + +from __future__ import absolute_import + +from knext.project.rest.models.project import Project +from knext.project.rest.models.project_create_request import ProjectCreateRequest diff --git a/knext/project/rest/models/project.py b/knext/project/rest/models/project.py new file mode 100644 index 00000000..2a46080a --- /dev/null +++ b/knext/project/rest/models/project.py @@ -0,0 +1,272 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class Project(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "id": "str", + "name": "str", + "description": "str", + "namespace": "str", + "tenant_id": "str", + "config": "str", + } + + attribute_map = { + "id": "id", + "name": "name", + "description": "description", + "namespace": "namespace", + "tenant_id": "tenantId", + "config": "config", + } + + def __init__( + self, + id=None, + name=None, + description=None, + namespace=None, + tenant_id=None, + config=None, + local_vars_configuration=None, + ): # noqa: E501 + """Project - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._id = None + self._name = None + self._description = None + self._namespace = None + self._tenant_id = None + self._config = None + self.discriminator = None + + if id is not None: + self.id = id + if name is not None: + self.name = name + if description is not None: + self.description = description + if namespace is not None: + self.namespace = namespace + if tenant_id is not None: + self.tenant_id = tenant_id + if config is not None: + self.config = config + + @property + def id(self): + """Gets the id of this Project. # noqa: E501 + + + :return: The id of this Project. # noqa: E501 + :rtype: str + """ + return self._id + + @id.setter + def id(self, id): + """Sets the id of this Project. + + + :param id: The id of this Project. # noqa: E501 + :type: str + """ + + self._id = id + + @property + def name(self): + """Gets the name of this Project. # noqa: E501 + + + :return: The name of this Project. # noqa: E501 + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this Project. + + + :param name: The name of this Project. # noqa: E501 + :type: str + """ + + self._name = name + + @property + def description(self): + """Gets the description of this Project. # noqa: E501 + + + :return: The description of this Project. # noqa: E501 + :rtype: str + """ + return self._description + + @description.setter + def description(self, description): + """Sets the description of this Project. + + + :param description: The description of this Project. # noqa: E501 + :type: str + """ + + self._description = description + + @property + def namespace(self): + """Gets the namespace of this Project. # noqa: E501 + + + :return: The namespace of this Project. # noqa: E501 + :rtype: str + """ + return self._namespace + + @namespace.setter + def namespace(self, namespace): + """Sets the namespace of this Project. + + + :param namespace: The namespace of this Project. # noqa: E501 + :type: str + """ + + self._namespace = namespace + + @property + def tenant_id(self): + """Gets the tenant_id of this Project. # noqa: E501 + + + :return: The tenant_id of this Project. # noqa: E501 + :rtype: str + """ + return self._tenant_id + + @tenant_id.setter + def tenant_id(self, tenant_id): + """Sets the tenant_id of this Project. + + + :param tenant_id: The tenant_id of this Project. # noqa: E501 + :type: str + """ + + self._tenant_id = tenant_id + + @property + def config(self): + """Gets the config of this Project. # noqa: E501 + + + :return: The config of this Project. # noqa: E501 + :rtype: str + """ + return self._config + + @config.setter + def config(self, config): + """Sets the config of this Project. + + + :param config: The config of this Project. # noqa: E501 + :type: str + """ + + self._config = config + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, Project): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, Project): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/project/rest/models/project_create_request.py b/knext/project/rest/models/project_create_request.py new file mode 100644 index 00000000..60b343c3 --- /dev/null +++ b/knext/project/rest/models/project_create_request.py @@ -0,0 +1,299 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ProjectCreateRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "id": "int", + "name": "str", + "desc": "str", + "namespace": "str", + "tenant_id": "str", + "config": "str", + "auto_schema": "str", + } + + attribute_map = { + "id": "id", + "name": "name", + "desc": "desc", + "namespace": "namespace", + "tenant_id": "tenantId", + "config": "config", + "auto_schema": "autoSchema", + } + + def __init__( + self, + id=None, + name=None, + desc=None, + namespace=None, + tenant_id=None, + config=None, + auto_schema=None, + local_vars_configuration=None, + ): # noqa: E501 + """ProjectCreateRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._id = None + self._name = None + self._desc = None + self._namespace = None + self._tenant_id = None + self._config = None + self._auto_schema = None + self.discriminator = None + + if id is not None: + self.id = id + if name is not None: + self.name = name + if desc is not None: + self.desc = desc + if namespace is not None: + self.namespace = namespace + if tenant_id is not None: + self.tenant_id = tenant_id + if config is not None: + self.config = config + if auto_schema is not None: + self.auto_schema = auto_schema + + @property + def id(self): + """Gets the id of this ProjectCreateRequest. # noqa: E501 + + + :return: The id of this ProjectCreateRequest. # noqa: E501 + :rtype: int + """ + return self._id + + @id.setter + def id(self, id): + """Sets the id of this ProjectCreateRequest. + + + :param id: The id of this ProjectCreateRequest. # noqa: E501 + :type: int + """ + + self._id = id + + @property + def name(self): + """Gets the name of this ProjectCreateRequest. # noqa: E501 + + + :return: The name of this ProjectCreateRequest. # noqa: E501 + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this ProjectCreateRequest. + + + :param name: The name of this ProjectCreateRequest. # noqa: E501 + :type: str + """ + + self._name = name + + @property + def desc(self): + """Gets the desc of this ProjectCreateRequest. # noqa: E501 + + + :return: The desc of this ProjectCreateRequest. # noqa: E501 + :rtype: str + """ + return self._desc + + @desc.setter + def desc(self, desc): + """Sets the desc of this ProjectCreateRequest. + + + :param desc: The desc of this ProjectCreateRequest. # noqa: E501 + :type: str + """ + + self._desc = desc + + @property + def namespace(self): + """Gets the namespace of this ProjectCreateRequest. # noqa: E501 + + + :return: The namespace of this ProjectCreateRequest. # noqa: E501 + :rtype: str + """ + return self._namespace + + @namespace.setter + def namespace(self, namespace): + """Sets the namespace of this ProjectCreateRequest. + + + :param namespace: The namespace of this ProjectCreateRequest. # noqa: E501 + :type: str + """ + + self._namespace = namespace + + @property + def tenant_id(self): + """Gets the tenant_id of this ProjectCreateRequest. # noqa: E501 + + + :return: The tenant_id of this ProjectCreateRequest. # noqa: E501 + :rtype: str + """ + return self._tenant_id + + @tenant_id.setter + def tenant_id(self, tenant_id): + """Sets the tenant_id of this ProjectCreateRequest. + + + :param tenant_id: The tenant_id of this ProjectCreateRequest. # noqa: E501 + :type: str + """ + + self._tenant_id = tenant_id + + @property + def config(self): + """Gets the config of this ProjectCreateRequest. # noqa: E501 + + + :return: The config of this ProjectCreateRequest. # noqa: E501 + :rtype: str + """ + return self._config + + @config.setter + def config(self, config): + """Sets the config of this ProjectCreateRequest. + + + :param config: The config of this ProjectCreateRequest. # noqa: E501 + :type: str + """ + + self._config = config + + @property + def auto_schema(self): + """Gets the auto_schema of this ProjectCreateRequest. # noqa: E501 + + + :return: The auto_schema of this ProjectCreateRequest. # noqa: E501 + :rtype: str + """ + return self._auto_schema + + @auto_schema.setter + def auto_schema(self, auto_schema): + """Sets the auto_schema of this ProjectCreateRequest. + + + :param auto_schema: The auto_schema of this ProjectCreateRequest. # noqa: E501 + :type: str + """ + + self._auto_schema = auto_schema + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ProjectCreateRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ProjectCreateRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/project/rest/project_api.py b/knext/project/rest/project_api.py new file mode 100644 index 00000000..bd3b768b --- /dev/null +++ b/knext/project/rest/project_api.py @@ -0,0 +1,507 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + + +# python 2 and python 3 compatibility library +import six + +from knext.common.rest.api_client import ApiClient +from knext.common.rest.exceptions import ApiTypeError # noqa: F401 + + +class ProjectApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def project_create_post(self, **kwargs): # noqa: E501 + """create # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.project_create_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ProjectCreateRequest project_create_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Project + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.project_create_post_with_http_info(**kwargs) # noqa: E501 + + def project_create_post_with_http_info(self, **kwargs): # noqa: E501 + """create # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.project_create_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ProjectCreateRequest project_create_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(Project, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["project_create_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method project_create_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "project_create_request" in local_var_params: + body_params = local_var_params["project_create_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/project", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="Project", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def project_get(self, **kwargs): # noqa: E501 + """query # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.project_get(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param str tenant_id: 按名称模糊查找 + :param int project_id: 按项目ID精确查找 + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: list[Project] + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.project_get_with_http_info(**kwargs) # noqa: E501 + + def project_get_with_http_info(self, **kwargs): # noqa: E501 + """query # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.project_get_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param str tenant_id: 按名称模糊查找 + :param int project_id: 按项目ID精确查找 + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(list[Project], status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["tenant_id", "project_id"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method project_get" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + if ( + "tenant_id" in local_var_params + and local_var_params["tenant_id"] is not None + ): # noqa: E501 + query_params.append( + ("tenantId", local_var_params["tenant_id"]) + ) # noqa: E501 + if ( + "project_id" in local_var_params + and local_var_params["project_id"] is not None + ): # noqa: E501 + query_params.append( + ("projectId", local_var_params["project_id"]) + ) # noqa: E501 + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/project", + "GET", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="list[Project]", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def update_post(self, **kwargs): # noqa: E501 + """update # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.update_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ProjectCreateRequest project_create_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: object + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.update_post_with_http_info(**kwargs) # noqa: E501 + + def update_post_with_http_info(self, **kwargs): # noqa: E501 + """update # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.update_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ProjectCreateRequest project_create_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["project_create_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method update_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "project_create_request" in local_var_params: + body_params = local_var_params["project_create_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/update", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="object", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def update_post(self, **kwargs): # noqa: E501 + """update # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.update_post(async_req=True) + >>> result = thread.get() + :param async_req bool: execute request asynchronously + :param ProjectCreateRequest project_create_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: object + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.update_post_with_http_info(**kwargs) # noqa: E501 + + def update_post_with_http_info(self, **kwargs): # noqa: E501 + """update # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.update_post_with_http_info(async_req=True) + >>> result = thread.get() + :param async_req bool: execute request asynchronously + :param ProjectCreateRequest project_create_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + local_var_params = locals() + all_params = ["project_create_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method update_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + collection_formats = {} + path_params = {} + query_params = [] + header_params = {} + form_params = [] + local_var_files = {} + body_params = None + if "project_create_request" in local_var_params: + body_params = local_var_params["project_create_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + # Authentication setting + auth_settings = [] # noqa: E501 + return self.api_client.call_api( + "/project/update", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="object", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) diff --git a/knext/reasoner/__init__.py b/knext/reasoner/__init__.py new file mode 100644 index 00000000..2e3e6758 --- /dev/null +++ b/knext/reasoner/__init__.py @@ -0,0 +1,37 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +# flake8: noqa + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from __future__ import absolute_import + +__version__ = "1" + + +from knext.reasoner.rest.models.reason_task import ReasonTask + +# import models into sdk package +from knext.reasoner.rest.models.reason_task_response import ReasonTaskResponse +from knext.reasoner.rest.models.table_result import TableResult + +# import apis into sdk package +from knext.reasoner.rest.reasoner_api import ReasonerApi diff --git a/knext/reasoner/client.py b/knext/reasoner/client.py new file mode 100644 index 00000000..c1fd83d3 --- /dev/null +++ b/knext/reasoner/client.py @@ -0,0 +1,150 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. +import os +import datetime +from knext.reasoner.rest.models.reason_task_response import ReasonTaskResponse + +import knext.common.cache +from knext.common.base.client import Client +from knext.common.rest import ApiClient, Configuration +from knext.reasoner import ReasonTask +from knext.reasoner import rest +from knext.reasoner.rest import SpgTypeQueryRequest +from knext.schema.client import SchemaSession +from knext.schema.model.base import SpgTypeEnum + +reason_cache = knext.common.cache.SchemaCache() + + +class ReasonerClient(Client): + """SPG Reasoner Client.""" + + def __init__(self, host_addr: str = None, project_id: int = None, namespace=None): + super().__init__(host_addr, str(project_id)) + self._rest_client: rest.ReasonerApi = rest.ReasonerApi( + api_client=ApiClient(configuration=Configuration(host=host_addr)) + ) + self._namespace = namespace or os.environ.get("KAG_PROJECT_NAMESPACE") + self._session = None + # load schema cache + self.get_reason_schema() + + def create_session(self): + """Create session for altering schema.""" + schema_session = reason_cache.get(self._project_id) + if not schema_session: + schema_session = SchemaSession(self._rest_client, self._project_id) + reason_cache.put(self._project_id, schema_session) + return schema_session + + def get_reason_schema(self): + """ + Create a new session and load schema information. + + - Create a session object `schema_session`. + - Iterate through all types in the session and filter out types that are Concepts, Entities, or Events. + - Construct a dictionary where keys are type names and values are the type objects themselves. + - Return the constructed dictionary `schema`. + """ + schema_session = self.create_session() + schema = { + k: v + for k, v in schema_session.spg_types.items() + if v.spg_type_enum + in [SpgTypeEnum.Concept, SpgTypeEnum.Entity, SpgTypeEnum.Event] + } + return schema + + def generate_graph_connect_config(self, lib): + """ + Generates the graph connection configuration based on environment variables. + + This function first attempts to retrieve the graph store URI from environment variables. + If the URI is not set, it returns the local graph store URL and the local graph state class. + If the URI is set, it retrieves the username, password, and database information from + environment variables and constructs a graph store URL with this information. + + Parameters: + lib (reasoner constants): Contains constants and classes related to graph connections. + + Returns: + tuple: A tuple containing the graph store URL and the graph state class. If the URI is from + environment variables, the URL is a remote address; otherwise, it is a local address. + """ + # Attempt to get the graph store URI; if not set, default to an empty string + uri = os.environ.get("KAG_GRAPH_STORE_URI", "") + # If URI is empty, return the local graph store URL and the local graph state class + if uri == "": + return lib.LOCAL_GRAPH_STORE_URL, lib.LOCAL_GRAPH_STATE_CLASS + + # Retrieve username, password, and database information from environment variables + user = os.getenv("KAG_GRAPH_STORE_USER") + password = os.getenv("KAG_GRAPH_STORE_PASSWORD") + database = os.getenv("KAG_GRAPH_STORE_DATABASE") + namespace = self._namespace or os.environ.get("KAG_PROJECT_NAMESPACE") + # Construct a graph store URL with authentication information + graph_store_url = f"{uri}?user={user}&password={password}&database={database}&namespace={namespace}" + + # Return the constructed graph store URL and the local graph state class + return graph_store_url, lib.LOCAL_GRAPH_STATE_CLASS + + def execute(self, dsl_content: str, output_file: str = None): + """ + Execute a synchronous builder job in local runner. + """ + task_response: ReasonTaskResponse = self.syn_execute(dsl_content) + task: ReasonTask = task_response.task + if task.status != "FINISH": + print(f"RUN {task.status} {dsl_content}") + else: + default_output_file = output_file or ( + f"./{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.csv" + ) + show_data = [ + task.result_table_result.header + ] + task.result_table_result.rows + import pandas as pd + + df = pd.DataFrame(show_data) + print(df) + df.to_csv(default_output_file, index=False) + + def query_node(self, label, id_value): + req = SpgTypeQueryRequest( + project_id=self._project_id, spg_type=label, ids=[id_value] + ) + resp = self._rest_client.query_spg_type_post(spg_type_query_request=req) + if len(resp) == 0: + return {} + return resp[0].properties + + def syn_execute(self, dsl_content: str, **kwargs): + task = ReasonTask(project_id=self._project_id, dsl=dsl_content, params=kwargs) + return self._rest_client.reason_run_post(reason_task=task) + + +if __name__ == "__main__": + sc = ReasonerClient("http://127.0.0.1:8887", 4) + reason_schema = sc.get_reason_schema() + print(reason_schema) + prop_set = sc.query_node("KQA.Others", "Panic_disorder") + import time + + start_time = time.time() + ret = sc.syn_execute( + "MATCH (n:KQA.Others)-[p:rdf_expand()]-(o:Entity) WHERE n.id in $nid and o.id in $oid RETURN p", + start_alias="n", + nid='["Panic_disorder"]', + oid='["Anxiety_and_nervousness"]', + ) + print(ret) + print(f"cost={time.time() - start_time}") diff --git a/knext/reasoner/lib/__init__.py b/knext/reasoner/lib/__init__.py new file mode 100644 index 00000000..8c48f853 --- /dev/null +++ b/knext/reasoner/lib/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. + +LOCAL_REASONER_JAR = "reasoner-local-runner-0.0.1-SNAPSHOT-jar-with-dependencies.jar" + +LOCAL_GRAPH_STORE_URL = "neo4j://127.0.0.1:7687" + +LOCAL_GRAPH_STATE_CLASS = ( + "com.antgroup.openspg.reasoner.warehouse.cloudext.CloudExtGraphState" +) diff --git a/knext/reasoner/rest/__init__.py b/knext/reasoner/rest/__init__.py new file mode 100644 index 00000000..c8d63f19 --- /dev/null +++ b/knext/reasoner/rest/__init__.py @@ -0,0 +1,36 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +# flake8: noqa + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from __future__ import absolute_import + +__version__ = "1" +# import models into sdk package +from knext.reasoner.rest.models.reason_task import ReasonTask +from knext.reasoner.rest.models.reason_task_response import ReasonTaskResponse +from knext.reasoner.rest.models.table_result import TableResult +from knext.reasoner.rest.models.spg_type_instance import SpgTypeInstance +from knext.reasoner.rest.models.spg_type_query_request import SpgTypeQueryRequest + +# import apis into sdk package +from knext.reasoner.rest.reasoner_api import ReasonerApi diff --git a/knext/reasoner/rest/models/__init__.py b/knext/reasoner/rest/models/__init__.py new file mode 100644 index 00000000..c30405d6 --- /dev/null +++ b/knext/reasoner/rest/models/__init__.py @@ -0,0 +1,33 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +# flake8: noqa + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from __future__ import absolute_import + +__version__ = "1" +# import models into sdk package +from knext.reasoner.rest.models.reason_task import ReasonTask +from knext.reasoner.rest.models.reason_task_response import ReasonTaskResponse +from knext.reasoner.rest.models.table_result import TableResult +from knext.reasoner.rest.models.spg_type_instance import SpgTypeInstance +from knext.reasoner.rest.models.spg_type_query_request import SpgTypeQueryRequest diff --git a/knext/reasoner/rest/models/ca_pipeline.py b/knext/reasoner/rest/models/ca_pipeline.py new file mode 100644 index 00000000..c6ff87e9 --- /dev/null +++ b/knext/reasoner/rest/models/ca_pipeline.py @@ -0,0 +1,155 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class CaPipeline(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"nodes": "list[Node]", "edges": "list[Edge]"} + + attribute_map = {"nodes": "nodes", "edges": "edges"} + + def __init__( + self, nodes=None, edges=None, local_vars_configuration=None + ): # noqa: E501 + """CaPipeline - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._nodes = None + self._edges = None + self.discriminator = None + + if nodes is not None: + self.nodes = nodes + if edges is not None: + self.edges = edges + + @property + def nodes(self): + """Gets the nodes of this CaPipeline. # noqa: E501 + + + :return: The nodes of this CaPipeline. # noqa: E501 + :rtype: list[Node] + """ + return self._nodes + + @nodes.setter + def nodes(self, nodes): + """Sets the nodes of this CaPipeline. + + + :param nodes: The nodes of this CaPipeline. # noqa: E501 + :type: list[Node] + """ + + self._nodes = nodes + + @property + def edges(self): + """Gets the edges of this CaPipeline. # noqa: E501 + + + :return: The edges of this CaPipeline. # noqa: E501 + :rtype: list[Edge] + """ + return self._edges + + @edges.setter + def edges(self, edges): + """Sets the edges of this CaPipeline. + + + :param edges: The edges of this CaPipeline. # noqa: E501 + :type: list[Edge] + """ + + self._edges = edges + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, CaPipeline): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, CaPipeline): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/reasoner/rest/models/edge.py b/knext/reasoner/rest/models/edge.py new file mode 100644 index 00000000..3f5be14f --- /dev/null +++ b/knext/reasoner/rest/models/edge.py @@ -0,0 +1,155 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class Edge(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"_from": "str", "to": "str"} + + attribute_map = {"_from": "from", "to": "to"} + + def __init__( + self, _from=None, to=None, local_vars_configuration=None + ): # noqa: E501 + """Edge - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self.__from = None + self._to = None + self.discriminator = None + + if _from is not None: + self._from = _from + if to is not None: + self.to = to + + @property + def _from(self): + """Gets the _from of this Edge. # noqa: E501 + + + :return: The _from of this Edge. # noqa: E501 + :rtype: str + """ + return self.__from + + @_from.setter + def _from(self, _from): + """Sets the _from of this Edge. + + + :param _from: The _from of this Edge. # noqa: E501 + :type: str + """ + + self.__from = _from + + @property + def to(self): + """Gets the to of this Edge. # noqa: E501 + + + :return: The to of this Edge. # noqa: E501 + :rtype: str + """ + return self._to + + @to.setter + def to(self, to): + """Sets the to of this Edge. + + + :param to: The to of this Edge. # noqa: E501 + :type: str + """ + + self._to = to + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, Edge): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, Edge): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/reasoner/rest/models/node.py b/knext/reasoner/rest/models/node.py new file mode 100644 index 00000000..068a331c --- /dev/null +++ b/knext/reasoner/rest/models/node.py @@ -0,0 +1,245 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class Node(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "id": "str", + "state": "str", + "question": "str", + "answer": "str", + "logs": "str", + } + + attribute_map = { + "id": "id", + "state": "state", + "question": "question", + "answer": "answer", + "logs": "logs", + } + + def __init__( + self, + id=None, + state=None, + question=None, + answer=None, + logs=None, + local_vars_configuration=None, + ): # noqa: E501 + """Node - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._id = None + self._state = None + self._question = None + self._answer = None + self._logs = None + self.discriminator = None + + if id is not None: + self.id = id + if state is not None: + self.state = state + if question is not None: + self.question = question + if answer is not None: + self.answer = answer + if logs is not None: + self.logs = logs + + @property + def id(self): + """Gets the id of this Node. # noqa: E501 + + + :return: The id of this Node. # noqa: E501 + :rtype: str + """ + return self._id + + @id.setter + def id(self, id): + """Sets the id of this Node. + + + :param id: The id of this Node. # noqa: E501 + :type: str + """ + + self._id = id + + @property + def state(self): + """Gets the state of this Node. # noqa: E501 + + + :return: The state of this Node. # noqa: E501 + :rtype: str + """ + return self._state + + @state.setter + def state(self, state): + """Sets the state of this Node. + + + :param state: The state of this Node. # noqa: E501 + :type: str + """ + + self._state = state + + @property + def question(self): + """Gets the question of this Node. # noqa: E501 + + + :return: The question of this Node. # noqa: E501 + :rtype: str + """ + return self._question + + @question.setter + def question(self, question): + """Sets the question of this Node. + + + :param question: The question of this Node. # noqa: E501 + :type: str + """ + + self._question = question + + @property + def answer(self): + """Gets the answer of this Node. # noqa: E501 + + + :return: The answer of this Node. # noqa: E501 + :rtype: str + """ + return self._answer + + @answer.setter + def answer(self, answer): + """Sets the answer of this Node. + + + :param answer: The answer of this Node. # noqa: E501 + :type: str + """ + + self._answer = answer + + @property + def logs(self): + """Gets the logs of this Node. # noqa: E501 + + + :return: The logs of this Node. # noqa: E501 + :rtype: str + """ + return self._logs + + @logs.setter + def logs(self, logs): + """Sets the logs of this Node. + + + :param logs: The logs of this Node. # noqa: E501 + :type: str + """ + + self._logs = logs + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, Node): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, Node): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/reasoner/rest/models/reason_markdown_request.py b/knext/reasoner/rest/models/reason_markdown_request.py new file mode 100644 index 00000000..9e20b232 --- /dev/null +++ b/knext/reasoner/rest/models/reason_markdown_request.py @@ -0,0 +1,156 @@ +# coding: utf-8 + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ReportMarkdownRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"task_id": "int", "content": "str"} + + attribute_map = {"task_id": "taskId", "content": "content"} + + def __init__( + self, task_id=None, content=None, local_vars_configuration=None + ): # noqa: E501 + """ReportMarkdownRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._task_id = None + self._content = None + self.discriminator = None + + self.task_id = task_id + self.content = content + + @property + def task_id(self): + """Gets the task_id of this ReportMarkdownRequest. # noqa: E501 + + + :return: The task_id of this ReportMarkdownRequest. # noqa: E501 + :rtype: int + """ + return self._task_id + + @task_id.setter + def task_id(self, task_id): + """Sets the task_id of this ReportMarkdownRequest. + + + :param task_id: The task_id of this ReportMarkdownRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and task_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `task_id`, must not be `None`" + ) # noqa: E501 + + self._task_id = task_id + + @property + def content(self): + """Gets the content of this ReportMarkdownRequest. # noqa: E501 + + + :return: The content of this ReportMarkdownRequest. # noqa: E501 + :rtype: str + """ + return self._content + + @content.setter + def content(self, content): + """Sets the content of this ReportMarkdownRequest. + + + :param content: The content of this ReportMarkdownRequest. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and content is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `content`, must not be `None`" + ) # noqa: E501 + + self._content = content + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: ( + (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item + ), + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ReportMarkdownRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ReportMarkdownRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/reasoner/rest/models/reason_task.py b/knext/reasoner/rest/models/reason_task.py new file mode 100644 index 00000000..43673aa4 --- /dev/null +++ b/knext/reasoner/rest/models/reason_task.py @@ -0,0 +1,363 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ReasonTask(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "task_id": "str", + "project_id": "int", + "graph_store_url": "str", + "dsl": "str", + "params": "object", + "status": "str", + "result_table_result": "TableResult", + "result_nodes": "list[str]", + "result_edges": "list[str]", + } + + attribute_map = { + "task_id": "taskId", + "project_id": "projectId", + "graph_store_url": "graphStoreUrl", + "dsl": "dsl", + "params": "params", + "status": "status", + "result_table_result": "resultTableResult", + "result_nodes": "resultNodes", + "result_edges": "resultEdges", + } + + def __init__( + self, + task_id=None, + project_id=None, + graph_store_url=None, + dsl=None, + params=None, + status=None, + result_table_result=None, + result_nodes=None, + result_edges=None, + local_vars_configuration=None, + ): # noqa: E501 + """ReasonTask - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._task_id = None + self._project_id = None + self._graph_store_url = None + self._dsl = None + self._params = None + self._status = None + self._result_table_result = None + self._result_nodes = None + self._result_edges = None + self.discriminator = None + + if task_id is not None: + self.task_id = task_id + self.project_id = project_id + if graph_store_url is not None: + self.graph_store_url = graph_store_url + self.dsl = dsl + if params is not None: + self.params = params + if status is not None: + self.status = status + if result_table_result is not None: + self.result_table_result = result_table_result + if result_nodes is not None: + self.result_nodes = result_nodes + if result_edges is not None: + self.result_edges = result_edges + + @property + def task_id(self): + """Gets the task_id of this ReasonTask. # noqa: E501 + + + :return: The task_id of this ReasonTask. # noqa: E501 + :rtype: str + """ + return self._task_id + + @task_id.setter + def task_id(self, task_id): + """Sets the task_id of this ReasonTask. + + + :param task_id: The task_id of this ReasonTask. # noqa: E501 + :type: str + """ + + self._task_id = task_id + + @property + def project_id(self): + """Gets the project_id of this ReasonTask. # noqa: E501 + + + :return: The project_id of this ReasonTask. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this ReasonTask. + + + :param project_id: The project_id of this ReasonTask. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def graph_store_url(self): + """Gets the graph_store_url of this ReasonTask. # noqa: E501 + + + :return: The graph_store_url of this ReasonTask. # noqa: E501 + :rtype: str + """ + return self._graph_store_url + + @graph_store_url.setter + def graph_store_url(self, graph_store_url): + """Sets the graph_store_url of this ReasonTask. + + + :param graph_store_url: The graph_store_url of this ReasonTask. # noqa: E501 + :type: str + """ + + self._graph_store_url = graph_store_url + + @property + def dsl(self): + """Gets the dsl of this ReasonTask. # noqa: E501 + + + :return: The dsl of this ReasonTask. # noqa: E501 + :rtype: str + """ + return self._dsl + + @dsl.setter + def dsl(self, dsl): + """Sets the dsl of this ReasonTask. + + + :param dsl: The dsl of this ReasonTask. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and dsl is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `dsl`, must not be `None`" + ) # noqa: E501 + + self._dsl = dsl + + @property + def params(self): + """Gets the params of this ReasonTask. # noqa: E501 + + + :return: The params of this ReasonTask. # noqa: E501 + :rtype: object + """ + return self._params + + @params.setter + def params(self, params): + """Sets the params of this ReasonTask. + + + :param params: The params of this ReasonTask. # noqa: E501 + :type: object + """ + + self._params = params + + @property + def status(self): + """Gets the status of this ReasonTask. # noqa: E501 + + + :return: The status of this ReasonTask. # noqa: E501 + :rtype: str + """ + return self._status + + @status.setter + def status(self, status): + """Sets the status of this ReasonTask. + + + :param status: The status of this ReasonTask. # noqa: E501 + :type: str + """ + + self._status = status + + @property + def result_table_result(self): + """Gets the result_table_result of this ReasonTask. # noqa: E501 + + + :return: The result_table_result of this ReasonTask. # noqa: E501 + :rtype: TableResult + """ + return self._result_table_result + + @result_table_result.setter + def result_table_result(self, result_table_result): + """Sets the result_table_result of this ReasonTask. + + + :param result_table_result: The result_table_result of this ReasonTask. # noqa: E501 + :type: TableResult + """ + + self._result_table_result = result_table_result + + @property + def result_nodes(self): + """Gets the result_nodes of this ReasonTask. # noqa: E501 + + + :return: The result_nodes of this ReasonTask. # noqa: E501 + :rtype: list[str] + """ + return self._result_nodes + + @result_nodes.setter + def result_nodes(self, result_nodes): + """Sets the result_nodes of this ReasonTask. + + + :param result_nodes: The result_nodes of this ReasonTask. # noqa: E501 + :type: list[str] + """ + + self._result_nodes = result_nodes + + @property + def result_edges(self): + """Gets the result_edges of this ReasonTask. # noqa: E501 + + + :return: The result_edges of this ReasonTask. # noqa: E501 + :rtype: list[str] + """ + return self._result_edges + + @result_edges.setter + def result_edges(self, result_edges): + """Sets the result_edges of this ReasonTask. + + + :param result_edges: The result_edges of this ReasonTask. # noqa: E501 + :type: list[str] + """ + + self._result_edges = result_edges + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ReasonTask): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ReasonTask): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/reasoner/rest/models/reason_task_response.py b/knext/reasoner/rest/models/reason_task_response.py new file mode 100644 index 00000000..4a772d95 --- /dev/null +++ b/knext/reasoner/rest/models/reason_task_response.py @@ -0,0 +1,160 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ReasonTaskResponse(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"project_id": "int", "task": "ReasonTask"} + + attribute_map = {"project_id": "projectId", "task": "task"} + + def __init__( + self, project_id=None, task=None, local_vars_configuration=None + ): # noqa: E501 + """ReasonTaskResponse - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._task = None + self.discriminator = None + + self.project_id = project_id + if task is not None: + self.task = task + + @property + def project_id(self): + """Gets the project_id of this ReasonTaskResponse. # noqa: E501 + + + :return: The project_id of this ReasonTaskResponse. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this ReasonTaskResponse. + + + :param project_id: The project_id of this ReasonTaskResponse. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def task(self): + """Gets the task of this ReasonTaskResponse. # noqa: E501 + + + :return: The task of this ReasonTaskResponse. # noqa: E501 + :rtype: ReasonTask + """ + return self._task + + @task.setter + def task(self, task): + """Sets the task of this ReasonTaskResponse. + + + :param task: The task of this ReasonTaskResponse. # noqa: E501 + :type: ReasonTask + """ + + self._task = task + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ReasonTaskResponse): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ReasonTaskResponse): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/reasoner/rest/models/report_pipeline_request.py b/knext/reasoner/rest/models/report_pipeline_request.py new file mode 100644 index 00000000..f7356b61 --- /dev/null +++ b/knext/reasoner/rest/models/report_pipeline_request.py @@ -0,0 +1,179 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ReportPipelineRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"task_id": "int", "pipeline": "CaPipeline", "node": "Node"} + + attribute_map = {"task_id": "taskId", "pipeline": "pipeline", "node": "node"} + + def __init__( + self, task_id=None, pipeline=None, node=None, local_vars_configuration=None + ): # noqa: E501 + """ReportPipelineRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._task_id = None + self._pipeline = None + self._node = None + self.discriminator = None + + if task_id is not None: + self.task_id = task_id + if pipeline is not None: + self.pipeline = pipeline + if node is not None: + self.node = node + + @property + def task_id(self): + """Gets the task_id of this ReportPipelineRequest. # noqa: E501 + + + :return: The task_id of this ReportPipelineRequest. # noqa: E501 + :rtype: int + """ + return self._task_id + + @task_id.setter + def task_id(self, task_id): + """Sets the task_id of this ReportPipelineRequest. + + + :param task_id: The task_id of this ReportPipelineRequest. # noqa: E501 + :type: int + """ + + self._task_id = task_id + + @property + def pipeline(self): + """Gets the pipeline of this ReportPipelineRequest. # noqa: E501 + + + :return: The pipeline of this ReportPipelineRequest. # noqa: E501 + :rtype: CaPipeline + """ + return self._pipeline + + @pipeline.setter + def pipeline(self, pipeline): + """Sets the pipeline of this ReportPipelineRequest. + + + :param pipeline: The pipeline of this ReportPipelineRequest. # noqa: E501 + :type: CaPipeline + """ + + self._pipeline = pipeline + + @property + def node(self): + """Gets the node of this ReportPipelineRequest. # noqa: E501 + + + :return: The node of this ReportPipelineRequest. # noqa: E501 + :rtype: Node + """ + return self._node + + @node.setter + def node(self, node): + """Sets the node of this ReportPipelineRequest. + + + :param node: The node of this ReportPipelineRequest. # noqa: E501 + :type: Node + """ + + self._node = node + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ReportPipelineRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ReportPipelineRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/reasoner/rest/models/spg_type_instance.py b/knext/reasoner/rest/models/spg_type_instance.py new file mode 100644 index 00000000..9ceb1e38 --- /dev/null +++ b/knext/reasoner/rest/models/spg_type_instance.py @@ -0,0 +1,187 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class SpgTypeInstance(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"id": "str", "spg_type": "str", "properties": "object"} + + attribute_map = {"id": "id", "spg_type": "spgType", "properties": "properties"} + + def __init__( + self, id=None, spg_type=None, properties=None, local_vars_configuration=None + ): # noqa: E501 + """SpgTypeInstance - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._id = None + self._spg_type = None + self._properties = None + self.discriminator = None + + self.id = id + self.spg_type = spg_type + if properties is not None: + self.properties = properties + + @property + def id(self): + """Gets the id of this SpgTypeInstance. # noqa: E501 + + + :return: The id of this SpgTypeInstance. # noqa: E501 + :rtype: str + """ + return self._id + + @id.setter + def id(self, id): + """Sets the id of this SpgTypeInstance. + + + :param id: The id of this SpgTypeInstance. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and id is None + ): # noqa: E501 + raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 + + self._id = id + + @property + def spg_type(self): + """Gets the spg_type of this SpgTypeInstance. # noqa: E501 + + + :return: The spg_type of this SpgTypeInstance. # noqa: E501 + :rtype: str + """ + return self._spg_type + + @spg_type.setter + def spg_type(self, spg_type): + """Sets the spg_type of this SpgTypeInstance. + + + :param spg_type: The spg_type of this SpgTypeInstance. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and spg_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type`, must not be `None`" + ) # noqa: E501 + + self._spg_type = spg_type + + @property + def properties(self): + """Gets the properties of this SpgTypeInstance. # noqa: E501 + + + :return: The properties of this SpgTypeInstance. # noqa: E501 + :rtype: object + """ + return self._properties + + @properties.setter + def properties(self, properties): + """Sets the properties of this SpgTypeInstance. + + + :param properties: The properties of this SpgTypeInstance. # noqa: E501 + :type: object + """ + + self._properties = properties + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, SpgTypeInstance): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, SpgTypeInstance): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/reasoner/rest/models/spg_type_query_request.py b/knext/reasoner/rest/models/spg_type_query_request.py new file mode 100644 index 00000000..b4dee0c8 --- /dev/null +++ b/knext/reasoner/rest/models/spg_type_query_request.py @@ -0,0 +1,194 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class SpgTypeQueryRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"project_id": "int", "spg_type": "str", "ids": "list[str]"} + + attribute_map = {"project_id": "projectId", "spg_type": "spgType", "ids": "ids"} + + def __init__( + self, project_id=None, spg_type=None, ids=None, local_vars_configuration=None + ): # noqa: E501 + """SpgTypeQueryRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._spg_type = None + self._ids = None + self.discriminator = None + + self.project_id = project_id + self.spg_type = spg_type + self.ids = ids + + @property + def project_id(self): + """Gets the project_id of this SpgTypeQueryRequest. # noqa: E501 + + + :return: The project_id of this SpgTypeQueryRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this SpgTypeQueryRequest. + + + :param project_id: The project_id of this SpgTypeQueryRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def spg_type(self): + """Gets the spg_type of this SpgTypeQueryRequest. # noqa: E501 + + + :return: The spg_type of this SpgTypeQueryRequest. # noqa: E501 + :rtype: str + """ + return self._spg_type + + @spg_type.setter + def spg_type(self, spg_type): + """Sets the spg_type of this SpgTypeQueryRequest. + + + :param spg_type: The spg_type of this SpgTypeQueryRequest. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and spg_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type`, must not be `None`" + ) # noqa: E501 + + self._spg_type = spg_type + + @property + def ids(self): + """Gets the ids of this SpgTypeQueryRequest. # noqa: E501 + + + :return: The ids of this SpgTypeQueryRequest. # noqa: E501 + :rtype: list[str] + """ + return self._ids + + @ids.setter + def ids(self, ids): + """Sets the ids of this SpgTypeQueryRequest. + + + :param ids: The ids of this SpgTypeQueryRequest. # noqa: E501 + :type: list[str] + """ + if ( + self.local_vars_configuration.client_side_validation and ids is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `ids`, must not be `None`" + ) # noqa: E501 + + self._ids = ids + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, SpgTypeQueryRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, SpgTypeQueryRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/reasoner/rest/models/table_result.py b/knext/reasoner/rest/models/table_result.py new file mode 100644 index 00000000..16891548 --- /dev/null +++ b/knext/reasoner/rest/models/table_result.py @@ -0,0 +1,194 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class TableResult(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"total": "int", "header": "list[str]", "rows": "list[list[str]]"} + + attribute_map = {"total": "total", "header": "header", "rows": "rows"} + + def __init__( + self, total=None, header=None, rows=None, local_vars_configuration=None + ): # noqa: E501 + """TableResult - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._total = None + self._header = None + self._rows = None + self.discriminator = None + + self.total = total + self.header = header + self.rows = rows + + @property + def total(self): + """Gets the total of this TableResult. # noqa: E501 + + + :return: The total of this TableResult. # noqa: E501 + :rtype: int + """ + return self._total + + @total.setter + def total(self, total): + """Sets the total of this TableResult. + + + :param total: The total of this TableResult. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and total is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `total`, must not be `None`" + ) # noqa: E501 + + self._total = total + + @property + def header(self): + """Gets the header of this TableResult. # noqa: E501 + + + :return: The header of this TableResult. # noqa: E501 + :rtype: list[str] + """ + return self._header + + @header.setter + def header(self, header): + """Sets the header of this TableResult. + + + :param header: The header of this TableResult. # noqa: E501 + :type: list[str] + """ + if ( + self.local_vars_configuration.client_side_validation and header is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `header`, must not be `None`" + ) # noqa: E501 + + self._header = header + + @property + def rows(self): + """Gets the rows of this TableResult. # noqa: E501 + + + :return: The rows of this TableResult. # noqa: E501 + :rtype: list[list[str]] + """ + return self._rows + + @rows.setter + def rows(self, rows): + """Sets the rows of this TableResult. + + + :param rows: The rows of this TableResult. # noqa: E501 + :type: list[list[str]] + """ + if ( + self.local_vars_configuration.client_side_validation and rows is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `rows`, must not be `None`" + ) # noqa: E501 + + self._rows = rows + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, TableResult): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, TableResult): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/reasoner/rest/reasoner_api.py b/knext/reasoner/rest/reasoner_api.py new file mode 100644 index 00000000..e6e3d3ca --- /dev/null +++ b/knext/reasoner/rest/reasoner_api.py @@ -0,0 +1,777 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import re # noqa: F401 + +# python 2 and python 3 compatibility library +import six + +from knext.common.rest.api_client import ApiClient +from knext.common.rest.exceptions import ApiTypeError, ApiValueError # noqa: F401 + + +class ReasonerApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def query_spg_type_post(self, **kwargs): # noqa: E501 + """query_spg_type # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.query_spg_type_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param SpgTypeQueryRequest spg_type_query_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: list[SpgTypeInstance] + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.query_spg_type_post_with_http_info(**kwargs) # noqa: E501 + + def query_spg_type_post_with_http_info(self, **kwargs): # noqa: E501 + """query_spg_type # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.query_spg_type_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param SpgTypeQueryRequest spg_type_query_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(list[SpgTypeInstance], status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["spg_type_query_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method query_spg_type_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "spg_type_query_request" in local_var_params: + body_params = local_var_params["spg_type_query_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params["Content-Type"] = ( + self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/query/spgType", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="list[SpgTypeInstance]", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def schema_query_project_schema_get(self, project_id, **kwargs): # noqa: E501 + """reason_schema # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.schema_query_project_schema_get(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param int project_id: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: ProjectSchema + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.schema_query_project_schema_get_info( + project_id, **kwargs + ) # noqa: E501 + + def schema_query_project_schema_get_info(self, project_id, **kwargs): # noqa: E501 + """reason_schema # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.schema_query_project_schema_get_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param int project_id: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(ProjectSchema, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["project_id"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method reason_schema_get" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + if ( + "project_id" in local_var_params + and local_var_params["project_id"] is not None + ): # noqa: E501 + query_params.append( + ("projectId", local_var_params["project_id"]) + ) # noqa: E501 + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/reason/schema", + "GET", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="ProjectSchema", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def reason_run_post(self, **kwargs): # noqa: E501 + """reason_run # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.reason_run_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ReasonTask reason_task: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: ReasonTaskResponse + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.reason_run_post_with_http_info(**kwargs) # noqa: E501 + + def reason_run_post_with_http_info(self, **kwargs): # noqa: E501 + """reason_run # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.reason_run_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ReasonTask reason_task: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(ReasonTaskResponse, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["reason_task"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method reason_run_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "reason_task" in local_var_params: + body_params = local_var_params["reason_task"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params["Content-Type"] = ( + self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/reason/run", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="ReasonTaskResponse", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def reasoner_dialog_report_node_post(self, **kwargs): # noqa: E501 + """report_node # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.reasoner_dialog_report_node_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ReportPipelineRequest report_pipeline_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: object + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.reasoner_dialog_report_node_post_with_http_info( + **kwargs + ) # noqa: E501 + + def reasoner_dialog_report_node_post_with_http_info(self, **kwargs): # noqa: E501 + """report_node # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.reasoner_dialog_report_node_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ReportPipelineRequest report_pipeline_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["report_pipeline_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method reasoner_dialog_report_node_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "report_pipeline_request" in local_var_params: + body_params = local_var_params["report_pipeline_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params["Content-Type"] = ( + self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/reasoner/dialog/report/node", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="object", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def reasoner_dialog_report_pipeline_post(self, **kwargs): # noqa: E501 + """report_pipeline # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.reasoner_dialog_report_pipeline_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param str task_id: + :param str pipeline: + :param ReportPipelineRequest report_pipeline_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: object + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.reasoner_dialog_report_pipeline_post_with_http_info( + **kwargs + ) # noqa: E501 + + def reasoner_dialog_report_pipeline_post_with_http_info( + self, **kwargs + ): # noqa: E501 + """report_pipeline # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.reasoner_dialog_report_pipeline_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param str task_id: + :param str pipeline: + :param ReportPipelineRequest report_pipeline_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["task_id", "pipeline", "report_pipeline_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method reasoner_dialog_report_pipeline_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + if ( + "task_id" in local_var_params and local_var_params["task_id"] is not None + ): # noqa: E501 + query_params.append(("taskId", local_var_params["task_id"])) # noqa: E501 + if ( + "pipeline" in local_var_params and local_var_params["pipeline"] is not None + ): # noqa: E501 + query_params.append( + ("pipeline", local_var_params["pipeline"]) + ) # noqa: E501 + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "report_pipeline_request" in local_var_params: + body_params = local_var_params["report_pipeline_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params["Content-Type"] = ( + self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/reasoner/dialog/report/pipeline", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="object", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def reasoner_dialog_report_markdown_post(self, **kwargs): # noqa: E501 + """report_markdown # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.reasoner_dialog_report_markdown_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ReportMarkdownRequest report_markdown_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: object + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.reasoner_dialog_report_markdown_post_with_http_info( + **kwargs + ) # noqa: E501 + + def reasoner_dialog_report_markdown_post_with_http_info( + self, **kwargs + ): # noqa: E501 + """report_markdown # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.reasoner_dialog_report_markdown_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ReportMarkdownRequest report_markdown_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["report_markdown_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method reasoner_dialog_report_markdown_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "report_markdown_request" in local_var_params: + body_params = local_var_params["report_markdown_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params["Content-Type"] = ( + self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/reasoner/dialog/report/markdown", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="object", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) diff --git a/knext/schema/__init__.py b/knext/schema/__init__.py new file mode 100644 index 00000000..6e3c2455 --- /dev/null +++ b/knext/schema/__init__.py @@ -0,0 +1,11 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/schema/client.py b/knext/schema/client.py new file mode 100644 index 00000000..26988176 --- /dev/null +++ b/knext/schema/client.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. +from typing import List, Dict + +import knext.common.cache +from knext.common.base.client import Client +from knext.schema import rest +from knext.schema.model.base import BaseSpgType, AlterOperationEnum, SpgTypeEnum +from knext.schema.model.relation import Relation + +cache = knext.common.cache.SchemaCache() + + +CHUNK_TYPE = "Chunk" +OTHER_TYPE = "Others" +TEXT_TYPE = "Text" +INTEGER_TYPE = "Integer" +FLOAT_TYPE = "Float" +BASIC_TYPES = [TEXT_TYPE, INTEGER_TYPE, FLOAT_TYPE] + + +class SchemaSession: + def __init__(self, client, project_id): + self._alter_spg_types: List[BaseSpgType] = [] + self._rest_client = client + self._project_id = project_id + + self._spg_types = {} + self.__spg_types = {} + self._init_spg_types() + + def _init_spg_types(self): + """Query project schema and init SPG types in session.""" + project_schema = self._rest_client.schema_query_project_schema_get( + self._project_id + ) + for spg_type in project_schema.spg_types: + spg_type_name = spg_type.basic_info.name.name + type_class = BaseSpgType.by_type_enum(spg_type.spg_type_enum) + if spg_type.spg_type_enum == SpgTypeEnum.Concept: + self._spg_types[spg_type_name] = type_class( + name=spg_type_name, + hypernym_predicate=spg_type.concept_layer_config.hypernym_predicate, + rest_model=spg_type, + ) + else: + self._spg_types[spg_type_name] = type_class( + name=spg_type_name, rest_model=spg_type + ) + + @property + def spg_types(self) -> Dict[str, BaseSpgType]: + return self._spg_types + + def get(self, spg_type_name) -> BaseSpgType: + """Get SPG type by name from project schema.""" + spg_type = self._spg_types.get(spg_type_name) + if spg_type is None: + spg_type = self.__spg_types.get(spg_type_name) + if spg_type is None: + raise ValueError(f"{spg_type_name} is not existed") + else: + return self.__spg_types.get(spg_type_name) + return self._spg_types.get(spg_type_name) + + def create_type(self, spg_type: BaseSpgType): + """Add an SPG type in session with `CREATE` operation.""" + spg_type.alter_operation = AlterOperationEnum.Create + self.__spg_types[spg_type.name] = spg_type + self._alter_spg_types.append(spg_type) + return self + + def update_type(self, spg_type: BaseSpgType): + """Add an SPG type in session with `UPDATE` operation.""" + spg_type.alter_operation = AlterOperationEnum.Update + self._alter_spg_types.append(spg_type) + return self + + def delete_type(self, spg_type: BaseSpgType): + """Add an SPG type in session with `DELETE` operation.""" + spg_type.alter_operation = AlterOperationEnum.Delete + self._alter_spg_types.append(spg_type) + return self + + def commit(self): + """Commit all altered schemas to server.""" + schema_draft = [] + for spg_type in self._alter_spg_types: + for prop in spg_type.properties.values(): + if prop.object_spg_type is None: + object_spg_type = self.get(prop.object_type_name) + prop.object_spg_type = object_spg_type.spg_type_enum + for sub_prop in prop.sub_properties.values(): + if sub_prop.object_spg_type is None: + object_spg_type = self.get(sub_prop.object_type_name) + sub_prop.object_spg_type = object_spg_type.spg_type_enum + for rel in spg_type.relations.values(): + if rel.is_dynamic is None: + rel.is_dynamic = False + if rel.object_spg_type is None: + object_spg_type = self.get(rel.object_type_name) + rel.object_spg_type = object_spg_type.spg_type_enum + for sub_prop in rel.sub_properties.values(): + if sub_prop.object_spg_type is None: + object_spg_type = self.get(sub_prop.object_type_name) + sub_prop.object_spg_type = object_spg_type.spg_type_enum + schema_draft.append(spg_type.to_rest()) + if len(schema_draft) == 0: + return + + request = rest.SchemaAlterRequest( + project_id=self._project_id, schema_draft=rest.SchemaDraft(schema_draft) + ) + print(request) + self._rest_client.schema_alter_schema_post(schema_alter_request=request) + + +class SchemaClient(Client): + """ """ + + _rest_client = rest.SchemaApi() + + def __init__(self, host_addr: str = None, project_id: str = None): + super().__init__(host_addr, project_id) + self._session = None + + def query_spg_type(self, spg_type_name: str) -> BaseSpgType: + """Query SPG type by name.""" + rest_model = self._rest_client.schema_query_spg_type_get(spg_type_name) + type_class = BaseSpgType.by_type_enum(f"{rest_model.spg_type_enum}") + + if rest_model.spg_type_enum == SpgTypeEnum.Concept: + return type_class( + name=spg_type_name, + hypernym_predicate=rest_model.concept_layer_config.hypernym_predicate, + rest_model=rest_model, + ) + else: + return type_class(name=spg_type_name, rest_model=rest_model) + + def query_relation( + self, subject_name: str, predicate_name: str, object_name: str + ) -> Relation: + """Query relation type by s_p_o name.""" + rest_model = self._rest_client.schema_query_relation_get( + subject_name, predicate_name, object_name + ) + return Relation( + name=predicate_name, object_type_name=object_name, rest_model=rest_model + ) + + def create_session(self): + """Create session for altering schema.""" + schema_session = cache.get(self._project_id) + if not schema_session: + schema_session = SchemaSession(self._rest_client, self._project_id) + cache.put(self._project_id, schema_session) + return schema_session + + def load(self): + schema_session = self.create_session() + schema = { + k.split(".")[-1]: v + for k, v in schema_session.spg_types.items() + if v.spg_type_enum + in [SpgTypeEnum.Concept, SpgTypeEnum.Entity, SpgTypeEnum.Event] + } + return schema + + def extract_types(self): + schema = self.load() + types = [t for t in schema.keys() if t not in [CHUNK_TYPE] + BASIC_TYPES] + return types diff --git a/knext/schema/marklang/__init__.py b/knext/schema/marklang/__init__.py new file mode 100644 index 00000000..6e3c2455 --- /dev/null +++ b/knext/schema/marklang/__init__.py @@ -0,0 +1,11 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/schema/marklang/concept_rule_ml.py b/knext/schema/marklang/concept_rule_ml.py new file mode 100644 index 00000000..d1ca3243 --- /dev/null +++ b/knext/schema/marklang/concept_rule_ml.py @@ -0,0 +1,488 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. +import re + +from knext.schema import rest +from knext.schema.client import SchemaClient +from knext.schema.model.base import SpgTypeEnum + + +combo_seperator = "\0+\0" + + +def is_blank(text): + if not text: + return True + if len(text) == 0: + return True + if text.isspace(): + return True + return False + + +class SPGConceptRuleMarkLang: + """ + SPG Concept Rule Mark Language Parser + Feature: parse rule script and then alter the schema of project + """ + + namespace = None + rule_quote_open = False + rule_text = "" + src_concept = () + dst_concept = () + predicate = None + is_reasoning = False + is_priority = False + + def __init__(self, filename): + self.current_line_num = 0 + self.session = SchemaClient().create_session() + self.concept_client = rest.ConceptApi() + self.load_script(filename) + + def error_msg(self, msg): + return f"Line# {self.current_line_num}: {msg}" + + def parse_concept(self, expression): + """ + parse the concept definition + """ + + namespace_match = re.match(r"^namespace\s+([a-zA-Z0-9]+)$", expression) + if namespace_match: + assert self.namespace is None, self.error_msg( + "Duplicated namespace define, please ensure define it only once" + ) + + self.namespace = namespace_match.group(1) + return + + reasoning_concept_priority_match = re.match( + r"^Priority\s*\(`?([a-zA-Z0-9\.]+)`?\):$", + expression, + ) + if reasoning_concept_priority_match: + assert self.namespace is not None, self.error_msg( + "please define namespace first" + ) + + self.dst_concept = (reasoning_concept_priority_match.group(1), "_root") + self.is_reasoning = True + self.is_priority = True + return + + reasoning_concept_match = re.match( + r"^\(`?([a-zA-Z0-9\.]+)`?/`([^`]+)`\):$", + expression, + ) + if reasoning_concept_match: + assert self.namespace is not None, self.error_msg( + "please define namespace first" + ) + + self.dst_concept = ( + reasoning_concept_match.group(1), + reasoning_concept_match.group(2), + ) + self.is_reasoning = True + return + + reasoning_po_match = re.match( + r"^\[([^\]]+)\]->\(`?([a-zA-Z0-9\.]+)`?/`([^`]+)`(\+`([^`]+)`)?\):$", + expression, + ) + if reasoning_po_match: + assert self.namespace is not None, self.error_msg( + "please define namespace first" + ) + + combo_add = reasoning_po_match.group(5) + self.predicate = reasoning_po_match.group(1) + self.dst_concept = ( + reasoning_po_match.group(2), + reasoning_po_match.group(3) + if combo_add is None + else reasoning_po_match.group(3) + combo_seperator + combo_add, + ) + self.is_reasoning = True + return + + reasoning_spo_match = re.match( + r"^\(`?([a-zA-Z0-9\.]+)`?/`([^`]+)`\)-\[([^\]]+)\]->\(`([a-zA-Z0-9\.]+)`/`([^`]+)`(\+`([^`]+)`)?\):$", + expression, + ) + if reasoning_spo_match: + assert self.namespace is not None, self.error_msg( + "please define namespace first" + ) + + self.src_concept = ( + reasoning_spo_match.group(1), + reasoning_spo_match.group(2), + ) + self.predicate = reasoning_spo_match.group(3) + combo_add = reasoning_po_match.group(7) + self.dst_concept = ( + reasoning_spo_match.group(4), + reasoning_spo_match.group(5) + if combo_add is None + else reasoning_spo_match.group(5) + combo_seperator + combo_add, + ) + self.is_reasoning = True + return + + type_match = re.match( + r"^`?([a-zA-Z0-9\.]+)`?/`([^`]+)`:(\s*?([a-zA-Z0-9\.]+)/`([^`]+)`)?$", + expression, + ) + if type_match: + assert self.namespace is not None, self.error_msg( + "please define namespace first" + ) + + self.src_concept = (type_match.group(1), type_match.group(2)) + if len(type_match.groups()) > 4: + self.dst_concept = (type_match.group(4), type_match.group(5)) + + else: + raise Exception( + self.error_msg("parse error, expect `ConceptType`/`ConceptName`:") + ) + + def parse_rule(self, rule): + """ + parse the logic rule from text + """ + + strip_rule = rule.strip() + if strip_rule.startswith("[["): + self.rule_quote_open = True + if len(strip_rule) > 2: + if strip_rule.endswith("]]"): + self.rule_quote_open = False + self.rule_text = strip_rule[2 : len(strip_rule) - 2].lstrip() + else: + self.rule_text = strip_rule[2].lstrip() + else: + self.rule_text = "" + else: + self.rule_text = rule + + def complete_rule(self, rule): + """ + Auto generate define statement and append namespace to the entity name + """ + + pattern = re.compile(r"Define\s*\(", re.IGNORECASE) + match = pattern.match(rule.strip()) + if not match: + subject_type = None + subject_name = None + if self.is_reasoning: + predicate_name = self.predicate + subject_type = ( + f"{self.namespace}.{self.src_concept[0]}" + if len(self.src_concept) > 0 + else None + ) + subject_name = ( + self.src_concept[1] if len(self.src_concept) > 0 else None + ) + object_type = ( + f"{self.namespace}.{self.dst_concept[0]}" + if len(self.dst_concept) > 0 + else None + ) + object_name = self.dst_concept[1] if len(self.dst_concept) > 0 else None + elif self.dst_concept[0] is not None: + predicate_name = "leadTo" + subject_type = f"{self.namespace}.{self.src_concept[0]}" + subject_name = self.src_concept[1] + object_type = f"{self.namespace}.{self.dst_concept[0]}" + object_name = self.dst_concept[1] + else: + predicate_name = "belongTo" + object_type = f"{self.namespace}.{self.src_concept[0]}" + object_name = self.src_concept[1] + assert object_type in self.session.spg_types, self.error_msg( + f"{object_type} not found in schema" + ) + + concept_type = self.session.get(object_type) + assert ( + concept_type.spg_type_enum == SpgTypeEnum.Concept + ), self.error_msg(f"{object_type} is not concept type") + + for spg_type in self.session.spg_types.values(): + for relation_name in spg_type.relations: + if relation_name.startswith(f"belongTo_{object_type}"): + subject_type = spg_type.name + break + + if self.is_reasoning: + if combo_seperator in object_name: + names = object_name.split(combo_seperator) + object_name = f"{names[0]}`+{object_type}/`{names[1]}" + if ( + subject_type is None + and self.predicate is None + and not self.is_priority + ): + head = f"Define ({object_type}/`{object_name}`)" + " {\n" + elif subject_type is None and self.predicate is not None: + head = ( + f"Define ()-[:{predicate_name}]->(:{object_type}/`{object_name}`)" + + " {\n" + ) + elif self.is_priority: + head = f"DefinePriority ({object_type})" + " {\n" + else: + head = ( + f"Define (:{subject_type}/`{subject_name}`)-[:{predicate_name}]->" + f"(:{object_type}/`{object_name}`)" + " {\n" + ) + elif subject_name is None: + head = ( + f"Define (s:{subject_type})-[p:{predicate_name}]->(o:`{object_type}`/`{object_name}`)" + + " {\n" + ) + else: + head = ( + f"Define " + f"(s:`{subject_type}`/`{subject_name}`)-[p:{predicate_name}]->(o:`{object_type}`/`{object_name}`)" + + " {\n" + ) + rule = head + rule + rule += "\n}" + elif self.is_reasoning: + raise Exception(self.error_msg("Wrong format for reasoning rule")) + + # complete the namespace of concept type + pattern = re.compile(r"\(([\w\s]*?:)`([\w\s\.]+)`/`([^`]+)`\)", re.IGNORECASE) + replace_list = [] + matches = re.findall(pattern, rule) + if matches: + for group in matches: + if "." in group[1]: + continue + replace_list.append( + ( + f"({group[0]}`{group[1]}`", + f"({group[0]}`{self.namespace}.{group[1].strip()}`", + ) + ) + + # complete the namespace of non-concept type + pattern = re.compile(r"\(([\w\s]*?:)([\w\s\.]+)\)", re.IGNORECASE) + matches = re.findall(pattern, rule) + if matches: + for group in matches: + if "." not in group[1]: + replace_list.append( + ( + f"({group[0]}{group[1]})", + f"({group[0]}{self.namespace}.{group[1].strip()})", + ) + ) + + # complete the namespace of type in action clause + pattern = re.compile( + r"createNodeInstance\s*?\([^)]+(type=)([^,]+),", re.IGNORECASE + ) + matches = re.findall(pattern, rule) + if matches: + for group in matches: + if "." not in group[1]: + replace_list.append( + ( + f"{group[0]}{group[1]}", + f"{group[0]}{self.namespace}.{group[1].strip()}", + ) + ) + + if len(replace_list) > 0: + for t in replace_list: + rule = rule.replace(t[0], t[1]) + + return rule + + def clear_session(self): + self.src_concept = () + self.dst_concept = () + self.rule_text = "" + self.predicate = None + self.is_reasoning = False + self.is_priority = False + + def submit_rule(self): + """ + submit the rule definition, make them available for inference + """ + + if self.is_reasoning: + # reasoning rule + if not is_blank(self.rule_text): + self.concept_client.concept_define_logical_causation_post( + define_logical_causation_request=rest.DefineLogicalCausationRequest( + subject_concept_type_name="Thing" + if len(self.src_concept) == 0 + else f"{self.namespace}.{self.src_concept[0]}", + subject_concept_name="1" + if len(self.src_concept) == 0 + else self.src_concept[1], + predicate_name="conclude" + if self.predicate is None + else self.predicate, + object_concept_type_name=f"{self.namespace}.{self.dst_concept[0]}", + object_concept_name=self.dst_concept[1], + semantic_type="REASONING_CONCEPT", + dsl=self.rule_text, + ) + ) + print( + f"Defined reasoning rule for `{self.dst_concept[0]}`/`{self.dst_concept[1]}`" + ) + else: + self.concept_client.concept_remove_logical_causation_post( + remove_logical_causation_request=rest.RemoveLogicalCausationRequest( + subject_concept_type_name="Thing" + if len(self.src_concept) == 0 + else f"{self.namespace}.{self.src_concept[0]}", + subject_concept_name="1" + if len(self.src_concept) == 0 + else self.src_concept[1], + predicate_name="conclude" + if self.predicate is None + else self.predicate, + object_concept_type_name=f"{self.namespace}.{self.dst_concept[0]}", + object_concept_name=self.dst_concept[1], + semantic_type="REASONING_CONCEPT", + ) + ) + print( + f"Removed reasoning rule for `{self.dst_concept[0]}`/`{self.dst_concept[1]}`" + ) + + elif self.dst_concept[0] is None: + # belongTo rule + if not is_blank(self.rule_text): + self.concept_client.concept_define_dynamic_taxonomy_post( + define_dynamic_taxonomy_request=rest.DefineDynamicTaxonomyRequest( + concept_type_name=f"{self.namespace}.{self.src_concept[0]}", + concept_name=self.src_concept[1], + dsl=self.rule_text, + ) + ) + print( + f"Defined belongTo rule for `{self.src_concept[0]}`/`{self.src_concept[1]}`" + ) + else: + self.concept_client.concept_remove_dynamic_taxonomy_post( + remove_dynamic_taxonomy_request=rest.RemoveDynamicTaxonomyRequest( + object_concept_type_name=f"{self.namespace}.{self.src_concept[0]}", + object_concept_name=self.src_concept[1], + ) + ) + print( + f"Removed belongTo rule for `{self.src_concept[0]}`/`{self.src_concept[1]}`" + ) + + else: + # leadTo rule + if not is_blank(self.rule_text): + self.concept_client.concept_define_logical_causation_post( + define_logical_causation_request=rest.DefineLogicalCausationRequest( + subject_concept_type_name=f"{self.namespace}.{self.src_concept[0]}", + subject_concept_name=self.src_concept[1], + predicate_name="leadTo", + object_concept_type_name=f"{self.namespace}.{self.dst_concept[0]}", + object_concept_name=self.dst_concept[1], + dsl=self.rule_text, + ) + ) + print( + f"Defined leadTo rule for " + f"`{self.src_concept[0]}`/`{self.src_concept[1]}` -> `{self.dst_concept[0]}`/`{self.dst_concept[1]}`" + ) + else: + self.concept_client.concept_remove_logical_causation_post( + remove_logical_causation_request=rest.RemoveLogicalCausationRequest( + subject_concept_type_name=f"{self.namespace}.{self.src_concept[0]}", + subject_concept_name=self.src_concept[1], + predicate_name="leadTo", + object_concept_type_name=f"{self.namespace}.{self.dst_concept[0]}", + object_concept_name=self.dst_concept[1], + ) + ) + print( + f"Removed leadTo rule for " + f"`{self.src_concept[0]}`/`{self.src_concept[1]}` -> `{self.dst_concept[0]}`/`{self.dst_concept[1]}`" + ) + + self.clear_session() + + def load_script(self, filename): + """ + Load and then parse the script file + """ + + file = open(filename, "r", encoding="utf-8") + lines = file.read().splitlines() + last_indent_level = 0 + + for line in lines: + self.current_line_num += 1 + strip_line = line.strip() + if strip_line == "" or strip_line.startswith("#"): + # skip empty or comments line + continue + + if self.rule_quote_open: + # process the multi-line assignment [[ .... ]] + right_strip_line = line.rstrip() + if strip_line.endswith("]]"): + self.rule_quote_open = False + if len(right_strip_line) > 2: + self.rule_text += right_strip_line[: len(right_strip_line) - 2] + if not is_blank(self.rule_text): + self.rule_text = self.complete_rule(self.rule_text) + self.submit_rule() + + else: + self.rule_text += line + "\n" + continue + elif len(self.rule_text) > 0: + self.submit_rule() + + indent_count = len(line) - len(line.lstrip()) + if indent_count == 0: + # the line without indent is namespace definition or a concept definition + if len(self.src_concept) > 1 and is_blank(self.rule_text): + self.submit_rule() + else: + self.clear_session() + self.parse_concept(strip_line) + + elif indent_count > last_indent_level: + # the line is the sub definition of the previous line + if strip_line.startswith("rule:"): + if len(strip_line) > 5: + self.parse_rule(strip_line[5:]) + else: + raise Exception(self.error_msg("parse error, expect rule:")) + + last_indent_level = indent_count + + # if rule is the last line of file, then submit it + if len(self.rule_text) > 0: + self.submit_rule() diff --git a/knext/schema/marklang/schema_ml.py b/knext/schema/marklang/schema_ml.py new file mode 100644 index 00000000..bf6e6fbe --- /dev/null +++ b/knext/schema/marklang/schema_ml.py @@ -0,0 +1,1479 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. +import os +import re +from enum import Enum +from pathlib import Path + +from knext.schema.model.base import ( + HypernymPredicateEnum, + BasicTypeEnum, + ConstraintTypeEnum, + AlterOperationEnum, + SpgTypeEnum, + PropertyGroupEnum, + IndexTypeEnum, +) +from knext.schema.model.spg_type import ( + EntityType, + ConceptType, + EventType, + StandardType, + Property, + Relation, + BasicType, +) +from knext.schema.client import SchemaClient + + +class IndentLevel(Enum): + # Define entity/concept/event/standard types or subtypes + Type = 0 + + # Define description/properties/relations of type + TypeMeta = 1 + + # Define property/relation name of type + Predicate = 2 + + # Define description/constraint/rule/index of property/relation + PredicateMeta = 3 + + # Define property about property + SubProperty = 4 + + # Define constraint of sub property + SubPropertyMeta = 5 + + +class RegisterUnit(Enum): + Type = "type" + Property = "property" + Relation = "relation" + SubProperty = "subProperty" + + +class SPGSchemaMarkLang: + """ + SPG Schema Mark Language Parser + Feature1: parse schema script and then alter the schema of project + Feature2: export schema script from a project + """ + + internal_type = set() + entity_internal_property = set() + event_internal_property = {"eventTime"} + concept_internal_property = {"stdId", "alias"} + keyword_type = { + "EntityType", + "ConceptType", + "EventType", + "StandardType", + "BasicType", + } + semantic_rel = { + "SYNANT": [ + "synonym", + "antonym", + "symbolOf", + "distinctFrom", + "definedAs", + "locatedNear", + "similarTo", + "etymologicallyRelatedTo", + ], + "CAU": ["leadTo", "causes", "obstructedBy", "createdBy", "causesDesire"], + "SEQ": [ + "happenedBefore", + "hasSubevent", + "hasFirstSubevent", + "hasLastSubevent", + "hasPrerequisite", + ], + "IND": ["belongTo"], + "INC": ["isPartOf", "hasA", "madeOf", "derivedFrom", "hasContext"], + "USE": ["usedFor", "capableOf", "receivesAction", "motivatedByGoal"], + } + semantic_rel_zh = { + "synonym": "同义", + "antonym": "反义", + "symbolOf": "象征", + "distinctFrom": "区别于", + "definedAs": "定义为", + "locatedNear": "位置临近", + "similarTo": "类似于", + "etymologicallyRelatedTo": "词源相关", + "leadTo": "导致", + "causes": "引起", + "obstructedBy": "受阻于", + "createdBy": "由...创建", + "causesDesire": "引发欲望", + "happenedBefore": "先于...发生", + "hasSubevent": "拥有子事件", + "hasFirstSubevent": "以...作为开始", + "hasLastSubevent": "以...作为结束", + "hasPrerequisite": "有前提条件", + "belongTo": "属于", + "isPartOf": "是...的一部分", + "hasA": "拥有", + "madeOf": "由…制成", + "derivedFrom": "源自于", + "hasContext": "有上下文", + "usedFor": "用于", + "capableOf": "能够", + "receivesAction": "接受动作", + "motivatedByGoal": "目标驱动", + } + parsing_register = { + RegisterUnit.Type: None, + RegisterUnit.Property: None, + RegisterUnit.Relation: None, + RegisterUnit.SubProperty: None, + } + indent_level_pos = [None, None, None, None, None, None] + rule_quote_predicate = None + rule_quote_open = False + current_parsing_level = 0 + last_indent_level = 0 + namespace = None + types = {} + defined_types = {} + + def __init__(self, filename, with_server=True): + self.reset() + self.schema_file = filename + self.current_line_num = 0 + if with_server: + self.schema = SchemaClient() + thing = self.schema.query_spg_type("Thing") + for prop in thing.properties: + self.entity_internal_property.add(prop) + self.event_internal_property.add(prop) + self.concept_internal_property.add(prop) + session = self.schema.create_session() + for type_name in session.spg_types: + spg_type = session.get(type_name) + if session.get(type_name).spg_type_enum in [ + SpgTypeEnum.Basic, + SpgTypeEnum.Standard, + ]: + self.internal_type.add(spg_type.name) + else: + self.internal_type = {"Text", "Float", "Integer"} + self.load_script() + + def reset(self): + self.internal_type = set() + self.entity_internal_property = set() + self.event_internal_property = {"eventTime"} + self.concept_internal_property = {"stdId", "alias"} + self.keyword_type = { + "EntityType", + "ConceptType", + "EventType", + "StandardType", + "BasicType", + } + + self.parsing_register = { + RegisterUnit.Type: None, + RegisterUnit.Property: None, + RegisterUnit.Relation: None, + RegisterUnit.SubProperty: None, + } + self.indent_level_pos = [None, None, None, None, None, None] + self.rule_quote_predicate = None + self.rule_quote_open = False + self.current_parsing_level = 0 + self.last_indent_level = 0 + self.namespace = None + self.types = {} + + def save_register(self, element: RegisterUnit, value): + """ + maintain the session for parsing + """ + + self.parsing_register[element] = value + if element == RegisterUnit.Type: + self.parsing_register[RegisterUnit.Property] = None + self.parsing_register[RegisterUnit.Relation] = None + self.parsing_register[RegisterUnit.SubProperty] = None + elif element == RegisterUnit.Property: + self.parsing_register[RegisterUnit.Relation] = None + self.parsing_register[RegisterUnit.SubProperty] = None + elif element == RegisterUnit.Relation: + self.parsing_register[RegisterUnit.Property] = None + self.parsing_register[RegisterUnit.SubProperty] = None + + def adjust_parsing_level(self, step): + """ + mark the indent level and clear related session + """ + + if step == 0: + self.current_parsing_level = IndentLevel.Type.value + # finish type parsing, clear the field in session + self.save_register(RegisterUnit.Type, None) + return + if step < 0: + self.current_parsing_level = max(0, self.current_parsing_level + step) + if self.current_parsing_level == IndentLevel.PredicateMeta.value: + # finish sub property parsing, clear the field in session + self.save_register(RegisterUnit.SubProperty, None) + elif self.current_parsing_level == IndentLevel.Predicate.value: + # finish predicate parsing, clear the fields in session + if self.parsing_register[RegisterUnit.Property] is not None: + self.save_register( + RegisterUnit.Property, + Property(name="_", object_type_name="Thing"), + ) + elif self.parsing_register[RegisterUnit.Relation] is not None: + self.save_register( + RegisterUnit.Relation, + Relation(name="_", object_type_name="Thing"), + ) + elif step == 1: + assert self.current_parsing_level + 1 < len(IndentLevel), self.error_msg( + "Invalid indentation (too many levels?)" + ) + + self.current_parsing_level += 1 + + def error_msg(self, msg): + return f"Line# {self.current_line_num}: {msg} (Please refer https://spg.openkg.cn/tutorial/schema/dsl for details)" + + def get_type_name_with_ns(self, type_name: str): + if "." in type_name: + return type_name + else: + return f"{self.namespace}.{type_name}" + + def parse_type(self, expression): + """ + parse the SPG type definition + """ + + namespace_match = re.match(r"^namespace\s+([a-zA-Z0-9]+)$", expression) + if namespace_match: + assert self.namespace is None, self.error_msg( + "Duplicated namespace define, please ensure define it only once" + ) + + self.namespace = namespace_match.group(1) + return + + type_match = re.match( + r"^([a-zA-Z0-9\.]+)\((\w+)\):\s*?([a-zA-Z0-9,]+)$", expression + ) + if type_match: + assert self.namespace is not None, self.error_msg( + "Missing namespace, please define namespace at the first" + ) + + type_name = type_match.group(1) + type_name_zh = type_match.group(2).strip() + type_class = type_match.group(3).strip() + assert type_class in self.keyword_type, self.error_msg( + f"{type_class} is illegal, please define it before current line" + ) + assert ( + type_name.startswith("STD.") + or "." not in type_name + or type_name.startswith(f"{self.namespace}.") + ), self.error_msg( + f"The name space of {type_name} does not belong to current project." + ) + + spg_type = None + if type_class == "EntityType": + spg_type = EntityType( + name=self.get_type_name_with_ns(type_name), name_zh=type_name_zh + ) + elif type_class == "ConceptType": + spg_type = ConceptType( + name=self.get_type_name_with_ns(type_name), + name_zh=type_name_zh, + hypernym_predicate=HypernymPredicateEnum.IsA, + ) + elif type_class == "EventType": + spg_type = EventType( + name=self.get_type_name_with_ns(type_name), name_zh=type_name_zh + ) + elif type_class == "StandardType": + spg_type = StandardType(name=f"{type_name}", name_zh=type_name_zh) + spg_type.spreadable = False + assert type_name.startswith("STD."), self.error_msg( + "The name of standard type must start with STD." + ) + elif type_class == "BasicType" and type_name == "Text": + spg_type = BasicType.Text + elif type_class == "BasicType" and type_name == "Integer": + spg_type = BasicType.Integer + elif type_class == "BasicType" and type_name == "Float": + spg_type = BasicType.Float + ns_type_name = self.get_type_name_with_ns(type_name) + assert ns_type_name not in self.types, self.error_msg( + f'Type "{type_name}" is duplicated in the schema' + ) + + self.types[ns_type_name] = spg_type + self.save_register(RegisterUnit.Type, spg_type) + return + + sub_type_match = re.match( + r"^([a-zA-Z0-9]+)\((\w+)\)\s*?->\s*?([a-zA-Z0-9\.]+):$", expression + ) + if sub_type_match: + assert self.namespace is not None, self.error_msg( + "Missing namespace, please define namespace at the first" + ) + + type_name = sub_type_match.group(1) + type_name_zh = sub_type_match.group(2).strip() + type_class = sub_type_match.group(3).strip() + if "." not in type_class: + ns_type_class = self.get_type_name_with_ns(type_class) + else: + ns_type_class = type_class + assert ( + type_class not in self.keyword_type + and type_class not in self.internal_type + ), self.error_msg(f"{type_class} is not a valid inheritable type") + assert ns_type_class in self.types, self.error_msg( + f"{type_class} not found, please define it first" + ) + + parent_spg_type = self.types[ns_type_class] + assert parent_spg_type.spg_type_enum in [ + SpgTypeEnum.Entity, + SpgTypeEnum.Event, + ], self.error_msg( + f'"{type_class}" cannot be inherited, only entity/event type can be inherited.' + ) + + spg_type = EntityType( + name=f"{self.namespace}.{type_name}", name_zh=type_name_zh + ) + if parent_spg_type.spg_type_enum == SpgTypeEnum.Event: + spg_type = EventType( + name=f"{self.namespace}.{type_name}", name_zh=type_name_zh + ) + spg_type.name = type_name + spg_type.name_zh = type_name_zh + spg_type.parent_type_name = ns_type_class + ns_type_name = f"{self.namespace}.{type_name}" + self.types[ns_type_name] = spg_type + self.save_register(RegisterUnit.Type, spg_type) + return + + raise Exception( + self.error_msg( + "unrecognized expression, expect namespace A or A(B):C or A(B)->C" + ) + ) + + def parse_type_meta(self, expression): + """ + parse the meta definition of SPG type + """ + + match = re.match( + r"^(desc|properties|relations|hypernymPredicate|regular|spreadable|autoRelate):\s*?(.*)$", + expression, + ) + assert match, self.error_msg( + "Unrecognized expression, expect desc:|properties:|relations:" + ) + + type_meta = match.group(1) + meta_value = match.group(2).strip() + + if type_meta == "desc" and len(meta_value) > 0: + self.parsing_register[RegisterUnit.Type].desc = meta_value + + elif type_meta == "properties": + assert self.parsing_register[RegisterUnit.Type].spg_type_enum not in [ + SpgTypeEnum.Standard, + SpgTypeEnum.Concept, + ], self.error_msg( + "Standard/concept type does not allow defining properties." + ) + self.save_register( + RegisterUnit.Property, Property(name="_", object_type_name="Thing") + ) + + elif type_meta == "relations": + assert self.parsing_register[RegisterUnit.Type].spg_type_enum not in [ + SpgTypeEnum.Standard + ], self.error_msg("Standard type does not allow defining relations.") + self.save_register( + RegisterUnit.Relation, Relation(name="_", object_type_name="Thing") + ) + + elif type_meta == "hypernymPredicate": + assert meta_value in ["isA", "locateAt", "mannerOf"], self.error_msg( + "Invalid hypernym predicate, expect isA or locateAt or mannerOf" + ) + assert ( + self.parsing_register[RegisterUnit.Type].spg_type_enum + == SpgTypeEnum.Concept + ), self.error_msg("Hypernym predicate is available for concept type only") + + if meta_value == "isA": + self.parsing_register[ + RegisterUnit.Type + ].hypernym_predicate = HypernymPredicateEnum.IsA + elif meta_value == "locateAt": + self.parsing_register[ + RegisterUnit.Type + ].hypernym_predicate = HypernymPredicateEnum.LocateAt + elif meta_value == "mannerOf": + self.parsing_register[ + RegisterUnit.Type + ].hypernym_predicate = HypernymPredicateEnum.MannerOf + + elif type_meta == "regular": + assert ( + self.parsing_register[RegisterUnit.Type].spg_type_enum + == SpgTypeEnum.Standard + ), self.error_msg("Regular is available for standard type only") + self.parsing_register[RegisterUnit.Type].constraint = { + "REGULAR": meta_value + } + + elif type_meta == "spreadable": + assert ( + self.parsing_register[RegisterUnit.Type].spg_type_enum + == SpgTypeEnum.Standard + ), self.error_msg("Spreadable is available for standard type only") + assert meta_value == "True" or meta_value == "False", self.error_msg( + "Spreadable only accept True or False as its value" + ) + self.parsing_register[RegisterUnit.Type].spreadable = meta_value == "True" + + elif type_meta == "autoRelate": + assert ( + self.parsing_register[RegisterUnit.Type].spg_type_enum + == SpgTypeEnum.Concept + ), self.error_msg( + "AutoRelate definition is available for concept type only" + ) + concept_types = meta_value.split(",") + for concept in concept_types: + c = self.get_type_name_with_ns(concept.strip()) + assert ( + c in self.types + and self.types[c].spg_type_enum == SpgTypeEnum.Concept + ), self.error_msg( + f"{concept.strip()} is not a concept type, " + f"concept type only allow relationships defined between concept types" + ) + for k in self.semantic_rel: + if k == "IND": + continue + for p in self.semantic_rel[k]: + predicate = Relation( + name=p, name_zh=self.semantic_rel_zh[p], object_type_name=c + ) + self.parsing_register[RegisterUnit.Type].add_relation(predicate) + return + + def check_semantic_relation(self, predicate_name, predicate_class): + """ + Check if the definition of semantic relations is correct + """ + + name_arr = predicate_name.split("#") + short_name = name_arr[0] + pred_name = name_arr[1] + assert short_name in self.semantic_rel, self.error_msg( + f"{short_name} is incorrect, expect SYNANT/CAU/SEQ/IND/INC" + ) + assert pred_name in self.semantic_rel[short_name], self.error_msg( + f'{pred_name} is incorrect, expect {" / ".join(self.semantic_rel[short_name])}' + ) + + subject_type = self.parsing_register[RegisterUnit.Type] + predicate_class_ns = predicate_class + if "." not in predicate_class: + predicate_class_ns = f"{self.namespace}.{predicate_class}" + assert ( + predicate_class_ns in self.types or predicate_class_ns in self.defined_types + ), self.error_msg( + f"{predicate_class} is illegal, please ensure that it appears in this schema." + ) + object_type = self.types[predicate_class_ns] + + if short_name == "SYNANT": + assert subject_type.spg_type_enum == SpgTypeEnum.Concept, self.error_msg( + "Only concept types could define synonym/antonym relation" + ) + assert object_type.spg_type_enum == SpgTypeEnum.Concept, self.error_msg( + "Synonymy/antonym relation can only point to concept types" + ) + elif short_name == "CAU": + assert subject_type.spg_type_enum in [ + SpgTypeEnum.Concept, + SpgTypeEnum.Event, + ], self.error_msg("Only concept/event types could define causal relation") + assert object_type.spg_type_enum in [ + SpgTypeEnum.Concept, + SpgTypeEnum.Event, + ], self.error_msg( + f'"{predicate_class}" must be a concept type to conform to the definition of causal relation' + ) + if subject_type.spg_type_enum == SpgTypeEnum.Concept: + assert object_type.spg_type_enum == SpgTypeEnum.Concept, self.error_msg( + "The causal relation of concept types can only point to concept types" + ) + elif short_name == "SEQ": + assert subject_type.spg_type_enum in [ + SpgTypeEnum.Event, + SpgTypeEnum.Concept, + ], self.error_msg( + "Only concept/event types could define sequential relation" + ) + assert ( + subject_type.spg_type_enum == object_type.spg_type_enum + ), self.error_msg( + f'"{predicate_class}" should keep the same type with "{subject_type.name.split(".")[1]}"' + ) + elif short_name == "IND": + assert subject_type.spg_type_enum in [ + SpgTypeEnum.Entity, + SpgTypeEnum.Event, + ], self.error_msg("Only entity/event types could define inductive relation") + assert object_type.spg_type_enum == SpgTypeEnum.Concept, self.error_msg( + f'"{predicate_class}" must be a concept type to conform to the definition of inductive relation' + ) + elif short_name == "INC": + assert subject_type.spg_type_enum == SpgTypeEnum.Concept, self.error_msg( + "Only concept types could define inclusive relation" + ) + assert object_type.spg_type_enum == SpgTypeEnum.Concept, self.error_msg( + "The inclusion relation of concept types can only point to concept types" + ) + elif short_name == "USE": + assert subject_type.spg_type_enum == SpgTypeEnum.Concept, self.error_msg( + "Only concept types could define usage relation" + ) + assert object_type.spg_type_enum == SpgTypeEnum.Concept, self.error_msg( + "The usage relation of concept types can only point to concept types" + ) + + def parse_predicate(self, expression): + """ + parse the property/relation definition of SPG type + """ + + match = re.match( + r"^([a-zA-Z0-9#]+)\(([\w\.]+)\):\s*?([a-zA-Z0-9,\.]+)$", expression + ) + assert match, self.error_msg( + "Unrecognized expression, expect pattern like english(Chinese):Type" + ) + + predicate_name = match.group(1) + predicate_name_zh = match.group(2).strip() + predicate_class = match.group(3).strip() + cur_type = self.parsing_register[RegisterUnit.Type] + type_name = cur_type.name + + if ( + cur_type.spg_type_enum == SpgTypeEnum.Concept + and self.parsing_register[RegisterUnit.Relation] is None + ): + assert "#" in predicate_name, self.error_msg( + "Concept type only accept following categories of relation: INC#/CAU#/SYNANT#/IND#/USE#/SEQ#" + ) + + if "#" in predicate_name: + self.check_semantic_relation(predicate_name, predicate_class) + predicate_name = predicate_name.split("#")[1] + else: + for semantic_short in self.semantic_rel.values(): + assert predicate_name not in semantic_short, self.error_msg( + f"{predicate_name} is a semantic predicate, please add the semantic prefix" + ) + + if ( + "." in predicate_class + and predicate_class not in self.types + and predicate_class not in self.internal_type + ): + try: + cross_type = self.schema.query_spg_type( + self.get_type_name_with_ns(predicate_class) + ) + self.types[self.get_type_name_with_ns(predicate_class)] = cross_type + except Exception as e: + raise ValueError( + self.error_msg( + f"{predicate_class} is illegal, please ensure the name space or type name is correct." + ) + ) + + assert ( + self.get_type_name_with_ns(predicate_class) in self.types + or predicate_class in self.internal_type + or predicate_class in self.defined_types + ), self.error_msg( + f"{predicate_class} is illegal, please ensure that it appears in this schema." + ) + + # assert predicate_name not in self.entity_internal_property, self.error_msg( + # f"property {predicate_name} is the default property of type" + # ) + if predicate_class not in self.internal_type: + spg_type_enum = SpgTypeEnum.Entity + if self.get_type_name_with_ns(predicate_class) in self.types: + predicate_type = self.types[self.get_type_name_with_ns(predicate_class)] + spg_type_enum = predicate_type.spg_type_enum + elif predicate_class in self.defined_types: + spg_type_enum_txt = self.defined_types[predicate_class] + if spg_type_enum_txt == "EntityType": + spg_type_enum = SpgTypeEnum.Entity + elif spg_type_enum_txt == "ConceptType": + spg_type_enum = SpgTypeEnum.Concept + elif spg_type_enum_txt == "EventType": + spg_type_enum = SpgTypeEnum.Event + elif spg_type_enum_txt == "StandardType": + spg_type_enum = SpgTypeEnum.Standard + + if cur_type.spg_type_enum == SpgTypeEnum.Concept: + assert spg_type_enum == SpgTypeEnum.Concept, self.error_msg( + "Concept type only allow relationships that point to themselves" + ) + elif cur_type.spg_type_enum == SpgTypeEnum.Entity: + assert spg_type_enum != SpgTypeEnum.Event, self.error_msg( + "Relationships of entity types are not allowed to point to event types; " + "instead, they are only permitted to point from event types to entity types, " + "adhering to the principle of moving from dynamic to static." + ) + + if self.parsing_register[RegisterUnit.Relation] is not None: + assert ( + predicate_name + not in self.parsing_register[RegisterUnit.Relation].sub_properties + ), self.error_msg( + f'Property "{predicate_name}" is duplicated under the relation ' + f"{self.parsing_register[RegisterUnit.Relation].name}" + ) + else: + assert ( + predicate_name + not in self.parsing_register[RegisterUnit.Type].properties + ), self.error_msg( + f'Property "{predicate_name}" is duplicated under the type {type_name[type_name.index(".") + 1:]}' + ) + if predicate_class == "ConceptType": + assert not self.is_internal_property( + predicate_name, SpgTypeEnum.Concept + ), self.error_msg( + f"property {predicate_name} is the default property of ConceptType" + ) + if predicate_class == "EventType": + assert not self.is_internal_property( + predicate_name, SpgTypeEnum.Event + ), self.error_msg( + f"property {predicate_name} is the default property of EventType" + ) + + if ( + "." not in predicate_class + and predicate_class not in BasicTypeEnum.__members__ + ): + predicate_class = f"{self.namespace}.{predicate_class}" + + if self.parsing_register[RegisterUnit.SubProperty]: + # predicate is sub property + predicate = Property( + name=predicate_name, + name_zh=predicate_name_zh, + object_type_name=predicate_class, + ) + if self.parsing_register[RegisterUnit.Property] is not None: + self.parsing_register[RegisterUnit.Property].add_sub_property(predicate) + elif self.parsing_register[RegisterUnit.Relation] is not None: + self.parsing_register[RegisterUnit.Relation].add_sub_property(predicate) + self.save_register(RegisterUnit.SubProperty, predicate) + + elif self.parsing_register[RegisterUnit.Property]: + # predicate is property + predicate = Property( + name=predicate_name, + name_zh=predicate_name_zh, + object_type_name=predicate_class, + ) + if predicate_class in self.types: + predicate.object_spg_type = self.types[predicate_class].spg_type_enum + predicate.object_type_name_zh = self.types[predicate_class].name_zh + if ( + self.parsing_register[RegisterUnit.Type].spg_type_enum + == SpgTypeEnum.Event + and predicate_name == "subject" + ): + assert predicate_class not in self.internal_type, self.error_msg( + f"The subject of event type only allows entity/concept type" + ) + + predicate.property_group = PropertyGroupEnum.Subject + if "," in predicate_class: + # multi-types for subject + predicate.object_type_name = "Text" + subject_types = predicate_class.split(",") + for subject_type in subject_types: + subject_type = subject_type.strip() + assert ( + subject_type not in BasicTypeEnum.__members__ + ), self.error_msg( + f"{predicate_class} is illegal for subject in event type" + ) + + if "." not in subject_type: + subject_type = f"{self.namespace}.{predicate_class}" + assert ( + subject_type in self.types + or predicate_class in self.defined_types + ), self.error_msg( + f"{predicate_class} is illegal, please ensure that it appears in this schema." + ) + + subject_predicate = Property( + name=f"subject{subject_type}", + name_zh=predicate_name_zh, + object_type_name=subject_type, + ) + subject_predicate.property_group = PropertyGroupEnum.Subject + self.parsing_register[RegisterUnit.Type].add_property( + subject_predicate + ) + + self.parsing_register[RegisterUnit.Type].add_property(predicate) + self.save_register(RegisterUnit.Property, predicate) + + else: + # predicate is relation + assert not predicate_class.startswith("STD."), self.error_msg( + f"{predicate_class} is not allow appear in the definition of relation." + ) + assert ( + predicate_class in self.types + or predicate_class.split(".")[1] in self.defined_types + ), self.error_msg( + f"{predicate_class} is illegal, please ensure that it appears in this schema." + ) + assert ( + f"{predicate_name}_{predicate_class}" + not in self.parsing_register[RegisterUnit.Type].relations + ), self.error_msg( + f'Relation "{match.group()}" is duplicated under the type {type_name[type_name.index(".") + 1:]}' + if self.parsing_register[RegisterUnit.Type].spg_type_enum + != SpgTypeEnum.Concept + else f'Relation "{match.group()}" is already defined by keyword autoRelate' + f'under the {type_name[type_name.index(".") + 1:]}' + ) + + predicate = Relation(name=predicate_name, object_type_name=predicate_class) + if predicate_class in self.types: + predicate.object_spg_type = self.types[predicate_class].spg_type_enum + predicate.object_type_name_zh = self.types[predicate_class].name_zh + self.parsing_register[RegisterUnit.Type].add_relation(predicate) + self.save_register(RegisterUnit.Relation, predicate) + predicate.name_zh = predicate_name_zh + + def parse_property_meta(self, expression): + """ + parse the property meta definition of SPG type + """ + + match = re.match( + r"^(desc|properties|constraint|rule|index):\s*?(.*)$", expression + ) + assert match, self.error_msg( + "Unrecognized expression, expect desc:|properties:|constraint:|rule:|index:" + ) + + property_meta = match.group(1) + meta_value = match.group(2) + + if property_meta == "desc" and len(meta_value) > 0: + if self.parsing_register[RegisterUnit.SubProperty] is not None: + self.parsing_register[ + RegisterUnit.SubProperty + ].desc = meta_value.strip() + elif self.parsing_register[RegisterUnit.Property] is not None: + self.parsing_register[RegisterUnit.Property].desc = meta_value.strip() + + elif property_meta == "constraint": + if self.parsing_register[RegisterUnit.SubProperty] is not None: + self.parse_constraint_for_property( + meta_value, self.parsing_register[RegisterUnit.SubProperty] + ) + elif self.parsing_register[RegisterUnit.Property] is not None: + self.parse_constraint_for_property( + meta_value, self.parsing_register[RegisterUnit.Property] + ) + elif property_meta == "index": + if self.parsing_register[RegisterUnit.SubProperty] is not None: + self.parse_index_for_property( + meta_value, self.parsing_register[RegisterUnit.SubProperty] + ) + elif self.parsing_register[RegisterUnit.Property] is not None: + self.parse_index_for_property( + meta_value, self.parsing_register[RegisterUnit.Property] + ) + + elif property_meta == "properties": + self.save_register( + RegisterUnit.SubProperty, Property(name="_", object_type_name="Thing") + ) + + elif property_meta == "rule": + self.parse_predicate_rule(meta_value.lstrip(), RegisterUnit.Property) + + def parse_relation_meta(self, expression): + """ + parse the relation meta definition of SPG type + """ + + match = re.match(r"^(desc|properties|rule):\s*?(.*)$", expression) + assert match, self.error_msg( + "Unrecognized expression, expect desc:|properties:|rule:" + ) + + property_meta = match.group(1) + meta_value = match.group(2) + + if property_meta == "desc" and len(meta_value) > 0: + self.parsing_register[RegisterUnit.Relation].desc = meta_value.strip() + + elif property_meta == "properties": + self.save_register( + RegisterUnit.SubProperty, Property(name="_", object_type_name="Thing") + ) + + elif property_meta == "rule": + self.parse_predicate_rule(meta_value.lstrip(), RegisterUnit.Relation) + + def parsing_dispatch(self, expression, parsing_level): + if parsing_level == IndentLevel.Type.value: + self.parse_type(expression) + + elif parsing_level == IndentLevel.TypeMeta.value: + self.parse_type_meta(expression) + + elif parsing_level == IndentLevel.Predicate.value: + self.parse_predicate(expression) + + elif parsing_level == IndentLevel.PredicateMeta.value: + if self.parsing_register[RegisterUnit.Property] is not None: + self.parse_property_meta(expression) + + else: + self.parse_relation_meta(expression) + + elif parsing_level == IndentLevel.SubProperty.value: + self.parse_predicate(expression) + + elif parsing_level == IndentLevel.SubPropertyMeta.value: + self.parse_property_meta(expression) + + def parse_predicate_rule(self, rule, key): + """ + parse the logic rule for property/relation + """ + + strip_rule = rule + if strip_rule.startswith("[["): + self.rule_quote_predicate = self.parsing_register[key] + self.rule_quote_open = True + if len(strip_rule) > 2: + self.rule_quote_predicate.logical_rule = strip_rule[2].lstrip() + else: + self.rule_quote_predicate.logical_rule = "" + else: + self.parsing_register[key].logical_rule = rule + + def parse_constraint_for_property(self, expression, prop): + """ + parse the constraint definition of property + """ + + if len(expression) == 0: + return + + pattern = re.compile(r"(Enum|Regular)\s*?=\s*?\"([^\"]+)\"", re.IGNORECASE) + matches = re.findall(pattern, expression) + if matches: + for group in matches: + if group[0].lower() == "enum": + enum_values = group[1].split(",") + strip_enum_values = list() + for ev in enum_values: + strip_enum_values.append(ev.strip()) + prop.add_constraint(ConstraintTypeEnum.Enum, strip_enum_values) + + elif group[0].lower() == "regular": + prop.add_constraint(ConstraintTypeEnum.Regular, group[1]) + + expression = re.sub(r"(Enum|Regular)\s*?=\s*?\"([^\"]+)\"", "", expression) + array = expression.split(",") + for cons in array: + cons = cons.strip() + if cons.lower() == "multivalue": + prop.add_constraint(ConstraintTypeEnum.MultiValue) + + elif cons.lower() == "notnull": + prop.add_constraint(ConstraintTypeEnum.NotNull) + + def parse_index_for_property(self, expression, prop): + """ + parse the index definition of property + """ + + if len(expression) == 0: + return + + array = expression.split(",") + for cons in array: + cons = cons.strip() + if cons.lower() == "text": + prop.index_type = IndexTypeEnum.Text + + elif cons.lower() == "vector": + prop.index_type = IndexTypeEnum.Vector + + elif cons.lower() == "textandvector": + prop.index_type = IndexTypeEnum.TextAndVector + + def complete_rule(self, rule): + """ + Auto generate define statement and append namespace to the entity name + """ + + pattern = re.compile(r"Define\s*\(", re.IGNORECASE) + match = pattern.match(rule.strip()) + if not match: + subject_name = self.parsing_register[RegisterUnit.Type].name + predicate = None + if self.parsing_register[RegisterUnit.Property] is not None: + predicate = self.parsing_register[RegisterUnit.Property] + elif self.parsing_register[RegisterUnit.Relation] is not None: + predicate = self.parsing_register[RegisterUnit.Relation] + head = ( + f"Define (s:{subject_name})-[p:{predicate.name}]->(o:{predicate.object_type_name})" + + " {\n" + ) + rule = head + rule + rule += "\n}" + + pattern = re.compile(r"\(([\w\s]*?:)(`?[\w\s\.]+)`?/?[^)]*?\)", re.IGNORECASE) + matches = re.findall(pattern, rule) + replace_list = [] + if matches: + for group in matches: + if "." in group[1] or group[1].lower() in ["integer", "text", "float"]: + continue + replace_list.append( + ( + f"({group[0]}{group[1]}", + f"({group[0]}{self.namespace}.{group[1].strip()}" + if "`" not in group[1] + else f"({group[0]}`{self.namespace}.{group[1].replace('`', '').strip()}", + ) + ) + if len(replace_list) > 0: + for t in replace_list: + rule = rule.replace(t[0], t[1]) + + return rule.strip() + + def preload_types(self, lines: list): + """ + Pre analyze the script to obtain defined types + """ + + for line in lines: + type_match = re.match( + r"^([a-zA-Z0-9\.]+)\((\w+)\):\s*?([a-zA-Z0-9,]+)$", line + ) + if type_match: + self.defined_types[type_match.group(1)] = type_match.group(3).strip() + continue + sub_type_match = re.match( + r"^([a-zA-Z0-9]+)\((\w+)\)\s*?->\s*?([a-zA-Z0-9\.]+):$", line + ) + if sub_type_match: + self.defined_types[sub_type_match.group(1)] = sub_type_match.group( + 3 + ).strip() + + def load_script(self): + """ + Load and then parse the script file + """ + + file = open(self.schema_file, "r", encoding="utf-8") + lines = file.read().splitlines() + self.preload_types(lines) + for line in lines: + self.current_line_num += 1 + strip_line = line.strip() + # replace tabs with two spaces + line = line.replace("\t", " ") + if strip_line == "" or strip_line.startswith("#"): + # skip empty or comments line + continue + + if self.rule_quote_open: + # process the multi-line assignment [[ .... ]] + right_strip_line = line.rstrip() + if strip_line.endswith("]]"): + self.rule_quote_open = False + if len(right_strip_line) > 2: + self.rule_quote_predicate.logical_rule += right_strip_line[ + : len(right_strip_line) - 2 + ] + self.rule_quote_predicate.logical_rule = self.complete_rule( + self.rule_quote_predicate.logical_rule + ) + + else: + self.rule_quote_predicate.logical_rule += line + "\n" + continue + + indent_count = len(line) - len(line.lstrip()) + if indent_count == 0: + # the line without indent is namespace definition or a type definition + self.adjust_parsing_level(0) + + elif indent_count > self.last_indent_level: + # the line is the sub definition of the previous line + self.adjust_parsing_level(1) + + elif indent_count < self.last_indent_level: + # finish current indent parsing + backward_step = None + for i in range(0, len(self.indent_level_pos)): + if indent_count == self.indent_level_pos[i]: + backward_step = i - self.current_parsing_level + break + assert backward_step, self.error_msg( + f"Invalid indentation, please align with the previous definition" + ) + + if backward_step != 0: + self.adjust_parsing_level(backward_step) + + self.parsing_dispatch(strip_line, self.current_parsing_level) + self.last_indent_level = indent_count + self.indent_level_pos[self.current_parsing_level] = indent_count + + def is_internal_property(self, prop: Property, spg_type: SpgTypeEnum): + if spg_type == SpgTypeEnum.Entity or spg_type == SpgTypeEnum.Standard: + return prop in self.entity_internal_property + + elif spg_type == SpgTypeEnum.Concept: + return prop in self.concept_internal_property + + elif spg_type == SpgTypeEnum.Event: + return prop in self.event_internal_property + + def sync_schema(self): + return self.diff_and_sync(False) + + def print_diff(self): + self.diff_and_sync(True) + + def diff_sub_property(self, new, old, old_type_name, old_property, new_property): + need_update = False + inherited_type = self.get_inherited_type(old_type_name) + for prop in old: + if not old_property.inherited and prop not in new: + assert inherited_type is None, self.error_msg( + f'"{old_type_name} was inherited by other type, such as "{inherited_type}". Prohibit property alteration!' + ) + + old[prop].alter_operation = AlterOperationEnum.Delete + need_update = True + print( + f"Delete sub property: [{old_type_name}] {old_property.name}.{prop}" + ) + + for prop, o in new.items(): + if prop not in old and not new_property.inherited: + assert inherited_type is None, self.error_msg( + f'"{old_type_name} was inherited by other type, such as "{inherited_type}". Prohibit property alteration!' + ) + + old_property.add_sub_property(new[prop]) + need_update = True + print( + f"Create sub property: [{old_type_name}] {old_property.name}.{prop}" + ) + + elif old[prop].object_type_name != new[prop].object_type_name: + assert inherited_type is None, self.error_msg( + f'"{old_type_name} was inherited by other type, such as "{inherited_type}". Prohibit property alteration!' + ) + assert not old_property.inherited, self.error_msg( + f"{old_type_name}] {old_property.name}.{prop} is inherited sub property, deny modify" + ) + + old[prop].alter_operation = AlterOperationEnum.Delete + old_property.add_sub_property(new[prop]) + need_update = True + print( + f"Recreate sub property: [{old_type_name}] {old_property.name}.{prop}" + ) + + elif old[prop] != new[prop]: + assert inherited_type is None, self.error_msg( + f'"{old_type_name} was inherited by other type, such as "{inherited_type}". Prohibit property alteration!' + ) + assert not old_property.inherited, self.error_msg( + f"{old_type_name}] {old_property.name}.{prop} is inherited property, deny modify" + ) + + old[prop].overwritten_by(o) + old[prop].alter_operation = AlterOperationEnum.Update + need_update = True + print(f"Update property: [{old_type_name}] {old_property.name}.{prop}") + return need_update + + def get_inherited_type(self, type_name): + for spg_type in self.types: + if self.types[spg_type].parent_type_name == type_name: + return spg_type + return None + + def diff_and_sync(self, print_only): + """ + Get the schema diff and then sync to graph storage + """ + session = self.schema.create_session() + + # generate the delete list of spg type + for spg_type in session.spg_types: + if not spg_type.startswith("STD.") and not spg_type.startswith( + f"{self.namespace}." + ): + continue + unique_id = session.spg_types[spg_type]._rest_model.ontology_id.unique_id + if spg_type in self.internal_type and unique_id < 1000: + continue + + if spg_type not in self.types: + session.delete_type(session.get(spg_type)) + print(f"Delete type: {spg_type}") + + for spg_type in self.types: + # generate the creation list of spg type + if not spg_type.startswith("STD.") and not spg_type.startswith( + f"{self.namespace}." + ): + continue + if spg_type not in session.spg_types: + session.create_type(self.types[spg_type]) + print(f"Create type: {spg_type}") + relations = self.types[spg_type].relations + if len(relations) > 0: + for rel in relations: + print(f'Create relation: [{spg_type}] {rel.split("_")[0]}') + + else: + # generate the update list + new_type = self.types[spg_type] + old_type = session.get(spg_type) + + assert ( + new_type.spg_type_enum == old_type.spg_type_enum + and new_type.parent_type_name == old_type.parent_type_name + ), self.error_msg( + f"Cannot alter the type definition or its parent type of {new_type.name}. " + "if you still want to make change, please delete it first then re-create it." + ) + + need_update = False + if new_type.desc != old_type.desc: + old_type.desc = new_type.desc + need_update = True + + if new_type.name_zh != old_type.name_zh: + old_type.name_zh = new_type.name_zh + need_update = True + + if new_type.spg_type_enum == SpgTypeEnum.Concept: + assert ( + new_type.hypernym_predicate == old_type.hypernym_predicate + ), self.error_msg( + f"Cannot alter the hypernym predicate of {new_type.name}. " + "if you still want to make change, please delete it first then re-create it." + ) + + if new_type.spg_type_enum == SpgTypeEnum.Standard: + assert old_type.spreadable == new_type.spreadable, self.error_msg( + f"Cannot alter the spreadable value of {new_type.name}. " + f"if you still want to make change, " + "please delete the definition first and then re-create it." + ) + + if old_type.constraint != new_type.constraint: + old_type.constraint = new_type.constraint + need_update = True + print(f"Update standard type constraint: {spg_type}") + + inherited_type = self.get_inherited_type(new_type.name) + for prop in old_type.properties: + if ( + not old_type.properties[prop].inherited + and prop not in new_type.properties + and not self.is_internal_property(prop, new_type.spg_type_enum) + ): + assert ( + prop != "subject" + and old_type.properties[prop].property_group + != PropertyGroupEnum.Subject + ), self.error_msg( + "The subject property of event type cannot be deleted" + ) + assert inherited_type is None, self.error_msg( + f'"{new_type.name} was inherited by other type, such as "{inherited_type}". Prohibit property alteration!' + ) + + old_type.properties[ + prop + ].alter_operation = AlterOperationEnum.Delete + need_update = True + print(f"Delete property: [{new_type.name}] {prop}") + + for prop, o in new_type.properties.items(): + + if ( + prop not in old_type.properties + and not self.is_internal_property(prop, new_type.spg_type_enum) + and not o.inherited + ): + assert inherited_type is None, self.error_msg( + f'"{new_type.name} was inherited by other type, such as "{inherited_type}". Prohibit property alteration!' + ) + + old_type.add_property(new_type.properties[prop]) + need_update = True + print(f"Create property: [{new_type.name}] {prop}") + + elif ( + old_type.properties[prop].object_type_name + != new_type.properties[prop].object_type_name + ): + assert inherited_type is None, self.error_msg( + f'"{new_type.name} was inherited by other type, such as "{inherited_type}". Prohibit property alteration!' + ) + assert not old_type.properties[prop].inherited, self.error_msg( + f"{new_type.name}] {prop} is inherited property, deny modify" + ) + + old_type.properties[ + prop + ].alter_operation = AlterOperationEnum.Delete + old_type.add_property(new_type.properties[prop]) + need_update = True + print(f"Recreate property: [{new_type.name}] {prop}") + + elif ( + old_type.properties[prop].sub_properties + != new_type.properties[prop].sub_properties + ): + need_update = self.diff_sub_property( + new_type.properties[prop].sub_properties, + old_type.properties[prop].sub_properties, + old_type.name, + old_type.properties[prop], + new_type.properties[prop], + ) + if need_update: + old_type.properties[ + prop + ].alter_operation = AlterOperationEnum.Update + + elif old_type.properties[prop] != new_type.properties[prop]: + assert inherited_type is None, self.error_msg( + f'"{new_type.name} was inherited by other type, such as "{inherited_type}". Prohibit property alteration!' + ) + assert not old_type.properties[prop].inherited, self.error_msg( + f"{new_type.name}] {prop} is inherited property, deny modify" + ) + + old_type.properties[prop].overwritten_by(o) + old_type.properties[ + prop + ].alter_operation = AlterOperationEnum.Update + need_update = True + print(f"Update property: [{new_type.name}] {prop}") + + for relation in new_type.relations: + p_name = relation.split("_")[0] + if ( + relation not in old_type.relations + or old_type.relations[relation].object_type_name + != new_type.relations[relation].object_type_name + ): + assert inherited_type is None, self.error_msg( + f'"{new_type.name} was inherited by other type, such as "{inherited_type}". Prohibit relation alteration!' + ) + old_type.add_relation(new_type.relations[relation]) + need_update = True + print(f"Create relation: [{new_type.name}] {p_name}") + + elif ( + old_type.relations[relation].sub_properties + != new_type.relations[relation].sub_properties + ): + need_update = self.diff_sub_property( + new_type.relations[relation].sub_properties, + old_type.relations[relation].sub_properties, + old_type.name, + old_type.relations[relation], + new_type.relations[relation], + ) + if need_update: + assert inherited_type is None, self.error_msg( + f'"{new_type.name} was inherited by other type, such as "{inherited_type}". Prohibit relation alteration!' + ) + old_type.relations[ + relation + ].alter_operation = AlterOperationEnum.Update + + elif old_type.relations[relation] != new_type.relations[relation]: + assert inherited_type is None, self.error_msg( + f'"{new_type.name} was inherited by other type, such as "{inherited_type}". Prohibit relation alteration!' + ) + assert not old_type.relations[ + relation + ].inherited, self.error_msg( + f"{new_type.name}] {p_name} is inherited relation, deny modify" + ) + + old_type.relations[relation].overwritten_by( + new_type.relations[relation] + ) + old_type.relations[ + relation + ].alter_operation = AlterOperationEnum.Update + need_update = True + print(f"Update relation: [{new_type.name}] {relation}") + + for relation, o in old_type.relations.items(): + p_name = relation.split("_")[0] + if o.inherited or p_name in new_type.properties or o.is_dynamic: + # skip the inherited and semantic relation + continue + if ( + relation not in new_type.relations + and not o.inherited + and not o.is_dynamic + and not ( + new_type.spg_type_enum == SpgTypeEnum.Concept + and p_name + in [member.value for member in HypernymPredicateEnum] + ) + ): + assert inherited_type is None, self.error_msg( + f'"{new_type.name} was inherited by other type, such as "{inherited_type}". Prohibit relation alteration!' + ) + old_type.relations[ + relation + ].alter_operation = AlterOperationEnum.Delete + need_update = True + print(f"Delete relation: [{new_type.name}] {p_name}") + + if need_update: + session.update_type(old_type) + if not print_only: + session.commit() + if session._alter_spg_types: + return True + return False + + def export_schema_python(self, filename): + """ + Export the schema helper class in python + You can import the exported class in your code to obtain the code prompt in IDE + """ + + schema = SchemaClient() + session = schema.create_session() + assert len(self.namespace) > 0, "Schema is invalid" + + spg_types = [] + for spg_type_name in sorted(session.spg_types): + if ( + spg_type_name.startswith("STD.") + or not spg_type_name.startswith(self.namespace) + or spg_type_name in self.internal_type + ): + continue + + sub_properties = {} + properties = set() + for prop, prop_type in session.get(spg_type_name).properties.items(): + if len(prop_type.sub_properties) > 0: + sub_properties[prop] = set() + for sub_prop in prop_type.sub_properties: + sub_properties[prop].add(sub_prop) + else: + properties.add(prop) + + relations = set() + relation_sub_properties = {} + hyp_predicate = [member.value for member in HypernymPredicateEnum] + for relation, relation_type in session.get(spg_type_name).relations.items(): + rel = relation.split("_")[0] + if ( + rel in relations + or rel in hyp_predicate + or rel in session.get(spg_type_name).properties + ): + continue + + if len(relation_type.sub_properties) > 0: + relation_sub_properties[rel] = set() + for sub_prop in relation_type.sub_properties: + relation_sub_properties[rel].add(sub_prop) + else: + relations.add(rel) + + spg_types.append( + { + "name": spg_type_name.split(".")[1], + "properties": properties, + "sub_properties": sub_properties, + "relations": relations, + "relation_sub_properties": relation_sub_properties, + } + ) + + metadata = {"namespace": self.namespace, "spg_types": spg_types} + + from knext.common.utils import render_template + + render_template(Path(filename).parent, Path(filename).name, **metadata) + + +if __name__ == "__main__": + os.environ["KAG_PROJECT_ID"] = "4" + schema = SPGSchemaMarkLang( + "/Users/jier/Desktop/openspgapp/openspg/python/knext/knext/examples/medicine/schema/medicine.schema" + ) + schema.diff_and_sync(False) diff --git a/knext/schema/model/__init__.py b/knext/schema/model/__init__.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/schema/model/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/schema/model/base.py b/knext/schema/model/base.py new file mode 100644 index 00000000..efd61208 --- /dev/null +++ b/knext/schema/model/base.py @@ -0,0 +1,920 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. + +import pprint +import typing +from abc import ABC +from enum import Enum +from typing import Type, Union, List, Dict, Optional + +from knext.schema import rest + +ROOT_TYPE_UNIQUE_NAME = "Thing" + + +class SpgTypeEnum(str, Enum): + Basic = "BASIC_TYPE" + Standard = "STANDARD_TYPE" + Entity = "ENTITY_TYPE" + Event = "EVENT_TYPE" + Concept = "CONCEPT_TYPE" + + +class BasicTypeEnum(str, Enum): + Text = "Text" + Integer = "Integer" + Float = "Float" + + +class PropertyGroupEnum(str, Enum): + Time = "TIME" + Subject = "SUBJECT" + Object = "OBJECT" + Loc = "LOC" + + +class ConstraintTypeEnum(str, Enum): + NotNull = "NOT_NULL" + MultiValue = "MULTI_VALUE" + Enum = "ENUM" + Regular = "REGULAR" + + +class HypernymPredicateEnum(str, Enum): + IsA = "isA" + LocateAt = "locateAt" + MannerOf = "mannerOf" + + +class AlterOperationEnum(str, Enum): + Create = "CREATE" + Update = "UPDATE" + Delete = "DELETE" + + +class IndexTypeEnum(str, Enum): + Vector = "VECTOR" + Text = "TEXT" + TextAndVector = "TEXT_AND_VECTOR" + + +def iter_init(klass): + """Initialize a REST model.""" + instance = klass() + for attr, attr_type in klass.openapi_types.items(): + if hasattr(rest, attr_type): + attr_klass = getattr(rest, attr_type) + attr_instance = iter_init(attr_klass) + setattr(instance, attr, attr_instance) + elif attr_type.startswith("list["): + setattr(instance, attr, []) + else: + pass + + return instance + + +class BaseProperty(ABC): + """Base class of `Property` and `Relation`.""" + + _rest_model: Union[rest.Relation, rest.Property] + + def __init__( + self, + name=None, + object_type_name=None, + name_zh=None, + desc=None, + property_group=None, + sub_properties=None, + constraint=None, + logical_rule=None, + index_type=None, + **kwargs, + ): + if "rest_model" in kwargs: + self._rest_model = kwargs["rest_model"] + else: + self._init_rest_model( + name=name, + object_type_name=object_type_name, + name_zh=name_zh, + desc=desc, + property_group=property_group, + sub_properties=sub_properties, + constraint=constraint, + logical_rule=logical_rule, + index_type=index_type, + ) + + def _init_rest_model(self, **kwargs): + """Init a BaseProperty object.""" + super_klass = self.__class__.__name__ + self._rest_model = iter_init(getattr(rest, super_klass)) + for param, value in kwargs.items(): + setattr(self, param, value) + + @property + def name(self) -> str: + """Gets the name of this Property/Relation. # noqa: E501 + + + :return: The name of this Property/Relation. # noqa: E501 + :rtype: str + """ + return self._rest_model.basic_info.name.name + + @name.setter + def name(self, name: str): + """Sets the name of this Property/Relation. + + + :param name: The name of this Property/Relation. # noqa: E501 + :type: str + """ + + self._rest_model.basic_info.name.name = name + + @property + def object_type_name(self) -> str: + """Gets the object_type_name of this Property/Relation. # noqa: E501 + + + :return: The object_type_name of this Property/Relation. # noqa: E501 + :rtype: str + """ + return self._rest_model.object_type_ref.basic_info.name.name + + @property + def object_type_name_en(self) -> str: + """Gets the object_type_name_en of this Property/Relation. # noqa: E501 + + + :return: The object_type_name_en of this Property/Relation. # noqa: E501 + :rtype: str + """ + return self._rest_model.object_type_ref.basic_info.name.name_en + + @object_type_name_en.setter + def object_type_name_en(self, object_type_name_en: str): + """Sets the object_type_name_en of this Property/Relation. + + + :param object_type_name_en: The object_type_name_en of this Property/Relation. # noqa: E501 + :type: str + """ + + self._rest_model.object_type_ref.basic_info.name.name_en = object_type_name_en + + @object_type_name.setter + def object_type_name(self, object_type_name: str): + """Sets the object_type_name of this Property/Relation. + + + :param object_type_name: The object_type_name of this Property/Relation. # noqa: E501 + :type: str + """ + + self._rest_model.object_type_ref.basic_info.name.name = object_type_name + + @property + def object_type_name_zh(self) -> str: + """Gets the object_type_name_zh of this Property/Relation. # noqa: E501 + + + :return: The object_type_name_zh of this Property/Relation. # noqa: E501 + :rtype: str + """ + return self._rest_model.object_type_ref.basic_info.name_zh + + @object_type_name_zh.setter + def object_type_name_zh(self, object_type_name_zh: str): + """Sets the object_type_name_zh of this Property/Relation. + + + :param object_type_name_zh: The object_type_name_zh of this Property/Relation. # noqa: E501 + :type: str + """ + self._rest_model.object_type_ref.basic_info.name_zh = object_type_name_zh + + @property + def inherited(self) -> bool: + """Gets the `inherited` of this Property/Relation. # noqa: E501 + + + :return: The `inherited` of this Property/Relation. # noqa: E501 + :rtype: bool + """ + return self._rest_model.inherited + + @inherited.setter + def inherited(self, inherited: bool): + """Sets the `inherited` of this Property/Relation. + + + :param inherited: The `inherited` of this Property/Relation. # noqa: E501 + :type: bool + """ + + if inherited is None: + return + + self._rest_model.inherited = inherited + + @property + def object_spg_type(self) -> Optional[SpgTypeEnum]: + """Gets the object_spg_type of this Property/Relation. # noqa: E501 + + + :return: The object_spg_type of this Property/Relation. # noqa: E501 + :rtype: str + """ + spg_type_enum = self._rest_model.object_type_ref.spg_type_enum + return SpgTypeEnum(spg_type_enum) if spg_type_enum else None + + @object_spg_type.setter + def object_spg_type(self, object_spg_type: SpgTypeEnum): + """Sets the object_spg_type of this Property/Relation. + + + :param object_spg_type: The object_spg_type of this Property/Relation. # noqa: E501 + :type: str + """ + + if object_spg_type is None: + return + + self._rest_model.object_type_ref.spg_type_enum = object_spg_type + + @property + def name_zh(self) -> str: + """Gets the name_zh of this Property/Relation. # noqa: E501 + + + :return: The name_zh of this Property/Relation. # noqa: E501 + :rtype: str + """ + return self._rest_model.basic_info.name_zh + + @name_zh.setter + def name_zh(self, name_zh: str): + """Sets the name_zh of this Property/Relation. + + + :param name_zh: The name_zh of this Property/Relation. # noqa: E501 + :type: str + """ + if name_zh is None: + return + + self._rest_model.basic_info.name_zh = name_zh + + @property + def desc(self) -> str: + """Gets the desc of this Property/Relation. # noqa: E501 + + + :return: The desc of this Property/Relation. # noqa: E501 + :rtype: str + """ + return self._rest_model.basic_info.desc + + @desc.setter + def desc(self, desc: str): + """Sets the desc of this Property/Relation. + + + :param desc: The desc of this Property/Relation. # noqa: E501 + :type: str + """ + if desc is None: + return + + self._rest_model.basic_info.desc = desc + + @property + def property_group(self) -> Optional[PropertyGroupEnum]: + """Gets the property_group of this Property/Relation. # noqa: E501 + + + :return: The property_group of this Property/Relation. # noqa: E501 + :rtype: str + """ + property_group = self._rest_model.advanced_config.property_group + return PropertyGroupEnum(property_group) if property_group else None + + @property_group.setter + def property_group(self, property_group: PropertyGroupEnum): + """Sets the property_group of this Property/Relation. + + + :param property_group: The property_group of this Property/Relation. # noqa: E501 + :type: str + """ + if property_group is None: + return + + self._rest_model.advanced_config.property_group = property_group + + @property + def sub_properties(self) -> Dict[str, Type["Property"]]: + """Gets the sub_properties of this Property/Relation. # noqa: E501 + + + :return: The sub_properties of this Property/Relation. # noqa: E501 + :rtype: dict + """ + if self._rest_model.advanced_config.sub_properties is None: + return {} + from knext.schema.model.property import Property + + sub_properties = {} + for sub_property in self._rest_model.advanced_config.sub_properties: + sub_properties[sub_property.basic_info.name.name] = Property( + name=sub_property.basic_info.name.name, + object_type_name=sub_property.object_type_ref.basic_info.name.name, + rest_model=sub_property, + ) + return sub_properties + + @sub_properties.setter + def sub_properties(self, sub_properties: List["Property"]): + """Sets the sub_properties of this Property/Relation. + + + :param sub_properties: The sub_properties of this Property/Relation. # noqa: E501 + :type: list[Property] + """ + + if sub_properties is None: + return + + self._rest_model.advanced_config.sub_properties = [ + prop.to_rest() for prop in sub_properties + ] + + def add_sub_property(self, sub_property: Type["Property"]): + """Adds a sub_property to this Property/Relation. + + + :param sub_property: The sub_property to add. + :type sub_property: Property + """ + + if self._rest_model.advanced_config.sub_properties is None: + self._rest_model.advanced_config.sub_properties = None + sub_property.alter_operation = AlterOperationEnum.Create + self._rest_model.advanced_config.sub_properties.append(sub_property.to_rest()) + return self + + @property + def constraint(self) -> Dict[ConstraintTypeEnum, Union[str, list]]: + """Gets the constraint of this Property. # noqa: E501 + + + :return: The constraint of this Property. # noqa: E501 + :rtype: dict + """ + if self._rest_model.advanced_config.constraint is None: + return {} + constraint = {} + for item in self._rest_model.advanced_config.constraint.constraint_items: + if item.constraint_type_enum == ConstraintTypeEnum.Enum: + value = item.enum_values + elif item.constraint_type_enum == ConstraintTypeEnum.Regular: + value = item.regular_pattern + else: + value = None + constraint[item.constraint_type_enum] = value + return constraint + + @constraint.setter + def constraint(self, constraint: Dict[ConstraintTypeEnum, Union[str, list]]): + """Sets the constraint of this Property. + + + :param constraint: The constraint of this Property. # noqa: E501 + :type: dict + """ + if constraint is None: + return + self._rest_model.advanced_config.constraint = rest.Constraint( + constraint_items=[] + ) + for type, value in constraint.items(): + self.add_constraint(type, value) + + def add_constraint(self, type: ConstraintTypeEnum, value: Union[str, list] = None): + """Adds a constraint to this Property. + + + :param type: The type of constraint to add. + :type type: ConstraintTypeEnum + :param value: The value(s) of the constraint. Optional. + :type value: str or list, optional + """ + + if self._rest_model.advanced_config.constraint is None: + self._rest_model.advanced_config.constraint = rest.Constraint( + constraint_items=[] + ) + if type == ConstraintTypeEnum.Enum: + if not isinstance(value, list): + raise ValueError("Invalid enum format.") + constraint_item = rest.EnumConstraint(enum_values=value) + elif type == ConstraintTypeEnum.Regular: + constraint_item = rest.RegularConstraint(regular_pattern=value) + else: + constraint_item = rest.BaseConstraintItem(type) + self._rest_model.advanced_config.constraint.constraint_items.append( + constraint_item + ) + return self + + @property + def logical_rule(self) -> str: + """Gets the logical_rule of this Property/Relation. # noqa: E501 + + + :return: The logical_rule of this Property/Relation. # noqa: E501 + :rtype: str + """ + if self._rest_model.advanced_config.logical_rule is None: + return "" + return self._rest_model.advanced_config.logical_rule.content + + @logical_rule.setter + def logical_rule(self, logical_rule: str): + """Sets the logical_rule of this Property/Relation. + + + :param logical_rule: The logical_rule of this Property/Relation. # noqa: E501 + :type: str + """ + if not logical_rule: + self._rest_model.advanced_config.logical_rule = None + return + if self._rest_model.advanced_config.logical_rule is None: + self._rest_model.advanced_config.logical_rule = rest.LogicalRule() + + self._rest_model.advanced_config.logical_rule.content = logical_rule + + @property + def index_type(self) -> IndexTypeEnum: + """Gets the index_type of this Property/Relation. # noqa: E501 + + + :return: The index_type of this Property/Relation. # noqa: E501 + :rtype: str + """ + return self._rest_model.advanced_config.index_type + + @index_type.setter + def index_type(self, index_type: IndexTypeEnum): + """Sets the index_type of this Property/Relation. + + + :param index_type: The index_type of this Property/Relation. # noqa: E501 + :type: str + """ + if index_type is None: + return + + self._rest_model.advanced_config.index_type = index_type + + @property + def alter_operation(self) -> AlterOperationEnum: + """Gets the alter_operation of this Property/Relation. # noqa: E501 + + + :return: The alter_operation of this Property/Relation. # noqa: E501 + :rtype: AlterOperationEnum + """ + alter_operation = self._rest_model.alter_operation + return AlterOperationEnum(alter_operation) if alter_operation else None + + @alter_operation.setter + def alter_operation(self, alter_operation: AlterOperationEnum): + """Sets the alter_operation of this Property/Relation. + + + :param alter_operation: The alter_operation of this Property/Relation. # noqa: E501 + :type: AlterOperationEnum + """ + self._rest_model.alter_operation = alter_operation + + def overwritten_by(self, other: Type["BaseProperty"]): + """Overwrite all variables of the current class instance from another class instance.""" + import inspect + + members = inspect.getmembers(self.__class__) + for name, member in members: + if isinstance(member, property): + if name == "sub_properties": + setattr( + self, name, [prop for _, prop in getattr(other, name).items()] + ) + else: + setattr(self, name, getattr(other, name)) + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in self.__annotations__.items(): + if attr == "sub_properties": + continue + value = getattr(self, attr) + if isinstance(value, typing.List): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, typing.Dict): + result[attr] = dict( + map( + lambda item: ( + (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item + ), + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def to_rest(self): + """Returns the REST model of this SpgType""" + return self._rest_model + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, self.__class__): + return True + + return self.to_dict() != other.to_dict() + + +class BaseSpgType(ABC): + """Base class of `ConceptType`, `EntityType`, `EventType`, `StandardType`, `BasicType`.""" + + _rest_model: Union[ + rest.ConceptType, rest.EntityType, rest.EventType, rest.StandardType + ] + + def __init__( + self, + spg_type_enum=None, + name=None, + name_zh=None, + desc=None, + parent_type_name=None, + properties=None, + relations=None, + **kwargs, + ): + if "rest_model" in kwargs: + self._rest_model = kwargs["rest_model"] + else: + self._init_rest_model( + spg_type_enum=spg_type_enum, + name=name, + name_zh=name_zh, + desc=desc, + parent_type_name=parent_type_name, + properties=properties, + relations=relations, + **kwargs, + ) + + def _init_rest_model(self, **kwargs): + """Init a BaseSpgType object.""" + super_klass = self.__class__.__name__ + self._rest_model = iter_init(getattr(rest, super_klass)) + for param, value in kwargs.items(): + setattr(self, param, value) + + @property + def spg_type_enum(self) -> SpgTypeEnum: + """Gets the spg_type_enum of this SpgType. # noqa: E501 + + + :return: The spg_type_enum of this SpgType. # noqa: E501 + :rtype: str + """ + spg_type_enum = self._rest_model.spg_type_enum + return SpgTypeEnum(spg_type_enum) if spg_type_enum else None + + @spg_type_enum.setter + def spg_type_enum(self, spg_type_enum: SpgTypeEnum): + """Sets the spg_type_enum of this SpgType. + + + :param spg_type_enum: The spg_type_enum of this SpgType. # noqa: E501 + :type: str + """ + self._rest_model.spg_type_enum = spg_type_enum + + @property + def name(self) -> str: + """Gets the name of this SpgType. # noqa: E501 + + + :return: The name of this SpgType. # noqa: E501 + :rtype: str + """ + return self._rest_model.basic_info.name.name + + @property + def name_en(self) -> str: + """Gets the name_en of this SpgType. # noqa: E501 + + + :return: The name_en of this SpgType. # noqa: E501 + :rtype: str + """ + return self._rest_model.basic_info.name.name_en + + @name.setter + def name(self, name: str): + """Sets the name of this SpgType. + + + :param name: The name of this SpgType. # noqa: E501 + :type: str + """ + if name is None: # noqa: E501 + raise ValueError( + "Invalid value for `name`, must not be `None`" + ) # noqa: E501 + + if self._rest_model.basic_info.name.name != name: + self._rest_model.basic_info.name.name = name + + @property + def name_zh(self) -> str: + """Gets the name_zh of this SpgType. # noqa: E501 + + + :return: The name_zh of this SpgType. # noqa: E501 + :rtype: str + """ + return self._rest_model.basic_info.name_zh + + @name_zh.setter + def name_zh(self, name_zh: str): + """Sets the name_zh of this SpgType. + + + :param name_zh: The name_zh of this SpgType. # noqa: E501 + :type: str + """ + + if self._rest_model.basic_info.name_zh == name_zh: + return + self._rest_model.basic_info.name_zh = name_zh + + @property + def desc(self) -> str: + """Gets the desc of this SpgType. # noqa: E501 + + + :return: The desc of this SpgType. # noqa: E501 + :rtype: str + """ + return self._rest_model.basic_info.desc + + @desc.setter + def desc(self, desc: str): + """Sets the desc of this SpgType. + + + :param desc: The desc of this SpgType. # noqa: E501 + :type: str + """ + + self._rest_model.basic_info.desc = desc + + @property + def parent_type_name(self) -> str: + """Gets the parent_type_name of this SpgType. # noqa: E501 + + + :return: The parent_type_name of this SpgType. # noqa: E501 + :rtype: str + """ + return self._rest_model.parent_type_info.parent_type_identifier.name + + @parent_type_name.setter + def parent_type_name(self, parent_type_name: str): + """Sets the parent_type_name of this SpgType. + + + :param parent_type_name: The parent_type_name of this SpgType. # noqa: E501 + :type: BaseSpgType + """ + if parent_type_name is None: + return + self._rest_model.parent_type_info.parent_type_identifier.name = parent_type_name + + @property + def properties(self) -> Dict[str, Type["Property"]]: + """Gets the properties of this SpgType. # noqa: E501 + + + :return: The properties of this SpgType. # noqa: E501 + :rtype: dict + """ + from knext.schema.model.property import Property + + properties = {} + for prop in self._rest_model.properties: + properties[prop.basic_info.name.name] = Property( + name=prop.basic_info.name.name, + object_type_name=prop.object_type_ref.basic_info.name.name, + rest_model=prop, + ) + return properties + + @properties.setter + def properties(self, properties: List[Type["Property"]]): + """Sets the properties of this SpgType. + + + :param properties: The properties of this SpgType. # noqa: E501 + :type: list[Property] + """ + if properties is None: + return + + self._rest_model.properties = [prop.to_rest() for prop in properties] + + def add_property(self, prop: Type["Property"]): + """Adds a property to this SpgType. + + + :param prop: The property to add. # noqa: E501 + :type: Property + """ + prop.alter_operation = AlterOperationEnum.Create + self._rest_model.properties.append(prop.to_rest()) + return self + + @property + def relations(self) -> Dict[str, Type["Relation"]]: + """Gets the relations of this SpgType. # noqa: E501 + + + :return: The relations of this SpgType. # noqa: E501 + :rtype: dict + """ + from knext.schema.model.relation import Relation + + relations = {} + for relation in self._rest_model.relations: + predicate_name = relation.basic_info.name.name + object_type_name = relation.object_type_ref.basic_info.name.name + relations[predicate_name + "_" + object_type_name] = Relation( + name=predicate_name, + object_type_name=object_type_name, + rest_model=relation, + ) + return relations + + @relations.setter + def relations(self, relations: List["Relation"]): + """Sets the relations of this SpgType. + + + :param relations: The relations of this SpgType. # noqa: E501 + :type: list[Relation] + """ + + if relations is None: + return + + self._rest_model.relations = [relation.to_rest() for relation in relations] + + def add_relation(self, relation: Type["Relation"]): + """Adds a relation to this SpgType. + + + :param relation: The relation to add. # noqa: E501 + :type: Relation + """ + + relation.alter_operation = AlterOperationEnum.Create + self._rest_model.relations.append(relation.to_rest()) + return self + + @property + def alter_operation(self) -> Optional[AlterOperationEnum]: + """Gets the alter_operation of this SpgType. # noqa: E501 + + + :return: The alter_operation of this SpgType. # noqa: E501 + :rtype: AlterOperationEnum + """ + alter_operation = self._rest_model.alter_operation + return AlterOperationEnum(alter_operation) if alter_operation else None + + @alter_operation.setter + def alter_operation(self, alter_operation: AlterOperationEnum): + """Sets the alter_operation of this SpgType. + + + :param alter_operation: The alter_operation of this SpgType. # noqa: E501 + :type: AlterOperationEnum + """ + self._rest_model.alter_operation = alter_operation + + @staticmethod + def by_type_enum(type_enum: str): + """Reflection from type enum to subclass object of BaseSpgType.""" + + import knext.schema.model.spg_type as spg_type + + class_obj = getattr(spg_type, f"{SpgTypeEnum(type_enum).name}Type") + return class_obj + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in self.__annotations__.items(): + value = getattr(self, attr) + if isinstance(value, typing.List): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, typing.Dict): + result[attr] = dict( + map( + lambda item: ( + (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item + ), + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def to_rest(self): + """Returns the REST model of this SpgType""" + return self._rest_model + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, self.__class__): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, self.__class__): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/model/property.py b/knext/schema/model/property.py new file mode 100644 index 00000000..be731142 --- /dev/null +++ b/knext/schema/model/property.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. + +from typing import List, Type, Union, Dict + +from knext.schema.model.base import ( + ConstraintTypeEnum, + PropertyGroupEnum, + BaseProperty, + IndexTypeEnum, +) + + +class Property(BaseProperty): + """Property Model.""" + + name: str + object_type_name: str + name_zh: str + desc: str + property_group: PropertyGroupEnum + sub_properties: Dict[str, Type["Property"]] + constraint: Dict[ConstraintTypeEnum, Union[str, List[str]]] + logical_rule: str + index_type: IndexTypeEnum + + def __init__( + self, + name: str, + object_type_name: str, + name_zh: str = None, + desc: str = None, + property_group: PropertyGroupEnum = None, + sub_properties: List[Type["Property"]] = None, + constraint: Dict[ConstraintTypeEnum, Union[str, List[str]]] = None, + logical_rule: str = None, + index_type: IndexTypeEnum = None, + **kwargs + ): + super().__init__( + name=name, + object_type_name=object_type_name, + name_zh=name_zh, + desc=desc, + property_group=property_group, + sub_properties=sub_properties, + constraint=constraint, + logical_rule=logical_rule, + index_type=index_type, + **kwargs + ) diff --git a/knext/schema/model/relation.py b/knext/schema/model/relation.py new file mode 100644 index 00000000..92a1e8f5 --- /dev/null +++ b/knext/schema/model/relation.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. + +from typing import List, Type, Dict + +from knext.schema.model.base import BaseProperty +from knext.schema.model.property import Property + + +class Relation(BaseProperty): + """Relation Model.""" + + name: str + object_type_name: str + name_zh: str + desc: str + sub_properties: Dict[str, Type["Property"]] + logical_rule: str + + def __init__( + self, + name: str, + object_type_name: str, + name_zh: str = None, + desc: str = None, + sub_properties: List[Property] = None, + logical_rule: str = None, + **kwargs + ): + super().__init__( + name=name, + object_type_name=object_type_name, + name_zh=name_zh, + desc=desc, + sub_properties=sub_properties, + logical_rule=logical_rule, + **kwargs + ) + + @property + def is_dynamic(self) -> bool: + """Gets the is_dynamic of this Property/Relation. # noqa: E501 + + + :return: The is_dynamic of this Property/Relation. # noqa: E501 + :rtype: str + """ + return self._rest_model.is_dynamic + + @is_dynamic.setter + def is_dynamic(self, is_dynamic: bool): + """Sets the is_dynamic of this Property/Relation. + + + :param is_dynamic: The is_dynamic of this Property/Relation. # noqa: E501 + :type: bool + """ + + self._rest_model.is_dynamic = is_dynamic diff --git a/knext/schema/model/schema_helper.py b/knext/schema/model/schema_helper.py new file mode 100644 index 00000000..b0bb84be --- /dev/null +++ b/knext/schema/model/schema_helper.py @@ -0,0 +1,50 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. + +from abc import ABC +from typing import Union, Tuple, Optional + + +class SchemaHelper(ABC, str): + + __type_name__: str + + def __init__(self, type_name: str): + self.__type_name__ = type_name + + +class SPGTypeHelper(SchemaHelper): + def __init__(self, type_name: str): + super().__init__(type_name) + + +class PropertyHelper(SchemaHelper): + def __init__(self, type_name: str): + super().__init__(type_name) + + +class RelationHelper(SchemaHelper): + def __init__(self, type_name: str): + super().__init__(type_name) + + +class SubPropertyHelper(SchemaHelper): + def __init__(self, type_name: str): + super().__init__(type_name) + + +SPGTypeName = Union[str, SPGTypeHelper] +PropertyName = Union[str, PropertyHelper] +RelationName = Union[str, RelationHelper] +SubPropertyName = Union[str, SubPropertyHelper] +TripletName = Tuple[ + SPGTypeName, Union[PropertyName, RelationName], Optional[SPGTypeName] +] diff --git a/knext/schema/model/spg_type.py b/knext/schema/model/spg_type.py new file mode 100644 index 00000000..0b24bf47 --- /dev/null +++ b/knext/schema/model/spg_type.py @@ -0,0 +1,295 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. + +from typing import List, Dict, Union, Optional + +from knext.schema import rest +from knext.schema.model.base import ( + BaseSpgType, + SpgTypeEnum, + ROOT_TYPE_UNIQUE_NAME, + HypernymPredicateEnum, + ConstraintTypeEnum, +) +from knext.schema.model.property import Property +from knext.schema.model.relation import Relation + + +class EntityType(BaseSpgType): + """EntityType Model.""" + + spg_type_enum: SpgTypeEnum + name: str + name_zh: str + desc: str + parent_type_name: str + properties: Dict[str, Property] + relations: Dict[str, Relation] + + def __init__( + self, + name: str, + name_zh: str = None, + desc: str = None, + parent_type_name: str = ROOT_TYPE_UNIQUE_NAME, + properties: List[Property] = None, + relations: List[Relation] = None, + **kwargs, + ): + super().__init__( + spg_type_enum=SpgTypeEnum.Entity, + name=name, + name_zh=name_zh, + desc=desc, + properties=properties, + relations=relations, + parent_type_name=parent_type_name, + **kwargs, + ) + + +class ConceptType(BaseSpgType): + """ConceptType Model.""" + + spg_type_enum: SpgTypeEnum + name: str + hypernym_predicate: HypernymPredicateEnum + name_zh: str + desc: str + parent_type_name: str + properties: Dict[str, Property] + relations: Dict[str, Relation] + taxonomic_type_name: str + + def __init__( + self, + name: str, + hypernym_predicate: HypernymPredicateEnum, + name_zh: str = None, + desc: str = None, + parent_type_name: str = ROOT_TYPE_UNIQUE_NAME, + properties: List[Property] = None, + relations: List[Relation] = None, + taxonomic_type_name: str = None, + **kwargs, + ): + super().__init__( + spg_type_enum=SpgTypeEnum.Concept, + name=name, + name_zh=name_zh, + desc=desc, + properties=properties, + relations=relations, + parent_type_name=parent_type_name, + **kwargs, + ) + if "rest_model" not in kwargs: + self.hypernym_predicate = hypernym_predicate + self.taxonomic_type_name = taxonomic_type_name + + @property + def hypernym_predicate(self) -> Optional[HypernymPredicateEnum]: + """Gets the hypernym_predicate of this ConceptType. # noqa: E501 + + + :return: The hypernym_predicate of this ConceptType. # noqa: E501 + :rtype: HypernymPredicateEnum + """ + hypernym_predicate = self._rest_model.concept_layer_config.hypernym_predicate + return HypernymPredicateEnum(hypernym_predicate) if hypernym_predicate else None + + @hypernym_predicate.setter + def hypernym_predicate(self, hypernym_predicate: HypernymPredicateEnum): + """Sets the hypernym_predicate of this ConceptType. + + + :param hypernym_predicate: The hypernym_predicate of this ConceptType. # noqa: E501 + :type: HypernymPredicateEnum + """ + + self._rest_model.concept_layer_config.hypernym_predicate = hypernym_predicate + + @property + def taxonomic_type_name(self) -> Optional[str]: + """Gets the taxonomic_type_name of this SpgType. # noqa: E501 + + + :return: The taxonomic_type_name of this SpgType. # noqa: E501 + :rtype: str + """ + if self._rest_model.concept_taxonomic_config is None: + return None + return self._rest_model.concept_taxonomic_config.taxonomic_type_unique_name.name + + @taxonomic_type_name.setter + def taxonomic_type_name(self, taxonomic_type_name: str): + """Sets the taxonomic_type_name of this ConceptType. + + + :param taxonomic_type_name: The taxonomic_type_name of this ConceptType. # noqa: E501 + :type: str + """ + if taxonomic_type_name is None: + self._rest_model.concept_taxonomic_config = None + return + self._rest_model.concept_taxonomic_config.taxonomic_type_unique_name.name = ( + taxonomic_type_name + ) + + +class EventType(BaseSpgType): + """EventType Model.""" + + spg_type_enum: SpgTypeEnum + name: str + name_zh: str + desc: str + parent_type_name: str + properties: Dict[str, Property] + relations: Dict[str, Relation] + + def __init__( + self, + name: str, + name_zh: str = None, + desc: str = None, + parent_type_name: str = ROOT_TYPE_UNIQUE_NAME, + properties: List[Property] = None, + relations: List[Relation] = None, + **kwargs, + ): + super().__init__( + spg_type_enum=SpgTypeEnum.Event, + name=name, + name_zh=name_zh, + desc=desc, + properties=properties, + relations=relations, + parent_type_name=parent_type_name, + **kwargs, + ) + + +class BasicType(BaseSpgType): + """BasicType Model.""" + + Text = BaseSpgType(SpgTypeEnum.Basic, "Text") + Integer = BaseSpgType(SpgTypeEnum.Basic, "Integer") + Float = BaseSpgType(SpgTypeEnum.Basic, "Float") + + def __init__(self, name: str, **kwargs): + super().__init__(spg_type_enum=SpgTypeEnum.Basic, name=name, **kwargs) + + +class StandardType(BaseSpgType): + """StandardType Model.""" + + spg_type_enum: SpgTypeEnum + name: str + parent_type_name: str + spreadable: bool + constraint: Dict[ConstraintTypeEnum, Union[str, List[str]]] + + def __init__( + self, + name: str, + parent_type_name: str = ROOT_TYPE_UNIQUE_NAME, + spreadable: bool = False, + constraint: Dict[ConstraintTypeEnum, Union[str, List[str]]] = None, + **kwargs, + ): + super().__init__( + spg_type_enum=SpgTypeEnum.Standard, + name=name, + parent_type_name=parent_type_name, + spreadable=spreadable, + constraint=constraint, + **kwargs, + ) + + @property + def spreadable(self) -> bool: + """Gets the `spreadable` of this StandardType. # noqa: E501 + + + :return: The `spreadable` of this StandardType. # noqa: E501 + :rtype: bool + """ + return self._rest_model.spreadable + + @spreadable.setter + def spreadable(self, spreadable: bool): + """Sets the `spreadable` of this StandardType. + + + :param spreadable: The `spreadable` of this StandardType. # noqa: E501 + :type: bool + """ + self._rest_model.spreadable = spreadable + + @property + def constraint(self) -> Dict[ConstraintTypeEnum, Union[str, list]]: + """Gets the constraint of this StandardType. # noqa: E501 + + + :return: The constraint of this StandardType. # noqa: E501 + :rtype: dict + """ + if self._rest_model.constraint_items is None: + return {} + constraint = {} + for item in self._rest_model.constraint_items: + if item.constraint_type_enum == ConstraintTypeEnum.Enum: + value = item.enum_values + elif item.constraint_type_enum == ConstraintTypeEnum.Regular: + value = item.regular_pattern + else: + value = None + constraint[item.constraint_type_enum] = value + return constraint + + @constraint.setter + def constraint(self, constraint: Dict[ConstraintTypeEnum, Union[str, list]]): + """Sets the constraint of this StandardType. + + + :param constraint: The constraint of this StandardType. # noqa: E501 + :type: dict + """ + if constraint is None: + return + self._rest_model.constraint_items = [] + for type, value in constraint.items(): + self.add_constraint(type, value) + + def add_constraint(self, type: ConstraintTypeEnum, value: Union[str, list] = None): + """Adds a constraint to this StandardType. + + + :param type: The type of constraint to add. + :type type: ConstraintTypeEnum + :param value: The value(s) of the constraint. Optional. + :type value: str or list, optional + """ + + if self._rest_model.constraint_items is None: + self._rest_model.constraint_items = [] + if type == ConstraintTypeEnum.Enum: + if not isinstance(value, list): + raise ValueError("Invalid enum format.") + constraint_item = rest.EnumConstraint(enum_values=value) + elif type == ConstraintTypeEnum.Regular: + constraint_item = rest.RegularConstraint(regular_pattern=value) + else: + constraint_item = rest.BaseConstraintItem(type) + self._rest_model.constraint_items.append(constraint_item) + return self diff --git a/knext/schema/rest/__init__.py b/knext/schema/rest/__init__.py new file mode 100644 index 00000000..fcee98a0 --- /dev/null +++ b/knext/schema/rest/__init__.py @@ -0,0 +1,118 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +# flake8: noqa + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from __future__ import absolute_import + +__version__ = "1" + +# import apis into sdk package +from knext.schema.rest.concept_api import ConceptApi +from knext.schema.rest.schema_api import SchemaApi + +# import models into sdk package +from knext.schema.rest.models.basic_info import BasicInfo +from knext.schema.rest.models.ontology_id import OntologyId +from knext.schema.rest.models.base_ontology import BaseOntology +from knext.schema.rest.models.user_info import UserInfo +from knext.schema.rest.models.predicate.relation import Relation +from knext.schema.rest.models.predicate.property import Property +from knext.schema.rest.models.predicate.property_ref import PropertyRef +from knext.schema.rest.models.predicate.mounted_concept_config import ( + MountedConceptConfig, +) +from knext.schema.rest.models.predicate.property_advanced_config import ( + PropertyAdvancedConfig, +) +from knext.schema.rest.models.predicate.sub_property import SubProperty +from knext.schema.rest.models.predicate.property_ref_basic_info import ( + PropertyRefBasicInfo, +) +from knext.schema.rest.models.predicate.sub_property_basic_info import ( + SubPropertyBasicInfo, +) +from knext.schema.rest.models.alter.schema_draft import SchemaDraft +from knext.schema.rest.models.alter.schema_alter_request import SchemaAlterRequest +from knext.schema.rest.models.type.base_spg_type import BaseSpgType +from knext.schema.rest.models.type.operator_key import OperatorKey +from knext.schema.rest.models.type.event_type import EventType +from knext.schema.rest.models.type.spg_type_ref_basic_info import SpgTypeRefBasicInfo +from knext.schema.rest.models.type.entity_type import EntityType +from knext.schema.rest.models.type.spg_type_advanced_config import SpgTypeAdvancedConfig +from knext.schema.rest.models.type.concept_type import ConceptType +from knext.schema.rest.models.type.base_advanced_type import BaseAdvancedType +from knext.schema.rest.models.type.concept_layer_config import ConceptLayerConfig +from knext.schema.rest.models.type.multi_version_config import MultiVersionConfig +from knext.schema.rest.models.type.standard_type_basic_info import StandardTypeBasicInfo +from knext.schema.rest.models.type.parent_type_info import ParentTypeInfo +from knext.schema.rest.models.type.project_schema import ProjectSchema +from knext.schema.rest.models.type.concept_taxonomic_config import ( + ConceptTaxonomicConfig, +) +from knext.schema.rest.models.type.standard_type import StandardType +from knext.schema.rest.models.type.spg_type_ref import SpgTypeRef +from knext.schema.rest.models.type.basic_type import BasicType +from knext.schema.rest.models.identifier.spg_type_identifier import SpgTypeIdentifier +from knext.schema.rest.models.identifier.base_spg_identifier import BaseSpgIdentifier +from knext.schema.rest.models.identifier.concept_identifier import ConceptIdentifier +from knext.schema.rest.models.identifier.operator_identifier import OperatorIdentifier +from knext.schema.rest.models.identifier.spg_triple_identifier import ( + SpgTripleIdentifier, +) +from knext.schema.rest.models.identifier.predicate_identifier import PredicateIdentifier +from knext.schema.rest.models.concept.remove_logical_causation_request import ( + RemoveLogicalCausationRequest, +) +from knext.schema.rest.models.concept.define_logical_causation_request import ( + DefineLogicalCausationRequest, +) +from knext.schema.rest.models.concept.remove_dynamic_taxonomy_request import ( + RemoveDynamicTaxonomyRequest, +) +from knext.schema.rest.models.concept.define_dynamic_taxonomy_request import ( + DefineDynamicTaxonomyRequest, +) +from knext.schema.rest.models.semantic.base_semantic import BaseSemantic +from knext.schema.rest.models.semantic.predicate_semantic import PredicateSemantic +from knext.schema.rest.models.semantic.rule_code import RuleCode +from knext.schema.rest.models.semantic.logical_rule import LogicalRule +from knext.schema.rest.models.operator.operator_version_response import ( + OperatorVersionResponse, +) +from knext.schema.rest.models.operator.operator_version_request import ( + OperatorVersionRequest, +) +from knext.schema.rest.models.operator.operator_overview import OperatorOverview +from knext.schema.rest.models.operator.operator_version import OperatorVersion +from knext.schema.rest.models.operator.operator_create_response import ( + OperatorCreateResponse, +) +from knext.schema.rest.models.operator.operator_create_request import ( + OperatorCreateRequest, +) +from knext.schema.rest.models.constraint.constraint import Constraint +from knext.schema.rest.models.constraint.base_constraint_item import BaseConstraintItem +from knext.schema.rest.models.constraint.multi_val_constraint import MultiValConstraint +from knext.schema.rest.models.constraint.regular_constraint import RegularConstraint +from knext.schema.rest.models.constraint.not_null_constraint import NotNullConstraint +from knext.schema.rest.models.constraint.enum_constraint import EnumConstraint diff --git a/knext/schema/rest/concept_api.py b/knext/schema/rest/concept_api.py new file mode 100644 index 00000000..403955b5 --- /dev/null +++ b/knext/schema/rest/concept_api.py @@ -0,0 +1,533 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import re # noqa: F401 + +# python 2 and python 3 compatibility library +import six + +from knext.common.rest.api_client import ApiClient +from knext.common.rest.exceptions import ApiTypeError, ApiValueError # noqa: F401 + + +class ConceptApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def concept_define_dynamic_taxonomy_post(self, **kwargs): # noqa: E501 + """define_dynamic_taxonomy # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.concept_define_dynamic_taxonomy_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param DefineDynamicTaxonomyRequest define_dynamic_taxonomy_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: bool + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.concept_define_dynamic_taxonomy_post_with_http_info( + **kwargs + ) # noqa: E501 + + def concept_define_dynamic_taxonomy_post_with_http_info( + self, **kwargs + ): # noqa: E501 + """define_dynamic_taxonomy # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.concept_define_dynamic_taxonomy_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param DefineDynamicTaxonomyRequest define_dynamic_taxonomy_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(bool, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["define_dynamic_taxonomy_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method concept_define_dynamic_taxonomy_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "define_dynamic_taxonomy_request" in local_var_params: + body_params = local_var_params["define_dynamic_taxonomy_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/concept/defineDynamicTaxonomy", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="bool", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def concept_define_logical_causation_post(self, **kwargs): # noqa: E501 + """define_logical_causation # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.concept_define_logical_causation_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param DefineLogicalCausationRequest define_logical_causation_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: bool + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.concept_define_logical_causation_post_with_http_info( + **kwargs + ) # noqa: E501 + + def concept_define_logical_causation_post_with_http_info( + self, **kwargs + ): # noqa: E501 + """define_logical_causation # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.concept_define_logical_causation_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param DefineLogicalCausationRequest define_logical_causation_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(bool, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["define_logical_causation_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method concept_define_logical_causation_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "define_logical_causation_request" in local_var_params: + body_params = local_var_params["define_logical_causation_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/concept/defineLogicalCausation", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="bool", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def concept_remove_dynamic_taxonomy_post(self, **kwargs): # noqa: E501 + """remove_dynamic_taxonomy # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.concept_remove_dynamic_taxonomy_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param RemoveDynamicTaxonomyRequest remove_dynamic_taxonomy_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: bool + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.concept_remove_dynamic_taxonomy_post_with_http_info( + **kwargs + ) # noqa: E501 + + def concept_remove_dynamic_taxonomy_post_with_http_info( + self, **kwargs + ): # noqa: E501 + """remove_dynamic_taxonomy # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.concept_remove_dynamic_taxonomy_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param RemoveDynamicTaxonomyRequest remove_dynamic_taxonomy_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(bool, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["remove_dynamic_taxonomy_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method concept_remove_dynamic_taxonomy_get" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "remove_dynamic_taxonomy_request" in local_var_params: + body_params = local_var_params["remove_dynamic_taxonomy_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/concept/removeDynamicTaxonomy", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="bool", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def concept_remove_logical_causation_post(self, **kwargs): # noqa: E501 + """remove_logical_causation # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.concept_remove_logical_causation_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param RemoveLogicalCausationRequest remove_logical_causation_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: bool + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.concept_remove_logical_causation_post_with_http_info( + **kwargs + ) # noqa: E501 + + def concept_remove_logical_causation_post_with_http_info( + self, **kwargs + ): # noqa: E501 + """remove_logical_causation # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.concept_remove_logical_causation_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param RemoveLogicalCausationRequest remove_logical_causation_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(bool, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["remove_logical_causation_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method schema_remove_logical_causation_get" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "remove_logical_causation_request" in local_var_params: + body_params = local_var_params["remove_logical_causation_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/concept/removeLogicalCausation", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="bool", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) diff --git a/knext/schema/rest/models/__init__.py b/knext/schema/rest/models/__init__.py new file mode 100644 index 00000000..5527c75b --- /dev/null +++ b/knext/schema/rest/models/__init__.py @@ -0,0 +1,98 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. + +from __future__ import absolute_import + +from knext.schema.rest.models.basic_info import BasicInfo +from knext.schema.rest.models.ontology_id import OntologyId +from knext.schema.rest.models.base_ontology import BaseOntology +from knext.schema.rest.models.user_info import UserInfo +from knext.schema.rest.models.predicate.relation import Relation +from knext.schema.rest.models.predicate.property import Property +from knext.schema.rest.models.predicate.property_ref import PropertyRef +from knext.schema.rest.models.predicate.mounted_concept_config import ( + MountedConceptConfig, +) +from knext.schema.rest.models.predicate.property_advanced_config import ( + PropertyAdvancedConfig, +) +from knext.schema.rest.models.predicate.sub_property import SubProperty +from knext.schema.rest.models.predicate.property_ref_basic_info import ( + PropertyRefBasicInfo, +) +from knext.schema.rest.models.predicate.sub_property_basic_info import ( + SubPropertyBasicInfo, +) +from knext.schema.rest.models.alter.schema_draft import SchemaDraft +from knext.schema.rest.models.alter.schema_alter_request import SchemaAlterRequest +from knext.schema.rest.models.type.base_spg_type import BaseSpgType +from knext.schema.rest.models.type.operator_key import OperatorKey +from knext.schema.rest.models.type.event_type import EventType +from knext.schema.rest.models.type.spg_type_ref_basic_info import SpgTypeRefBasicInfo +from knext.schema.rest.models.type.entity_type import EntityType +from knext.schema.rest.models.type.spg_type_advanced_config import SpgTypeAdvancedConfig +from knext.schema.rest.models.type.concept_type import ConceptType +from knext.schema.rest.models.type.base_advanced_type import BaseAdvancedType +from knext.schema.rest.models.type.concept_layer_config import ConceptLayerConfig +from knext.schema.rest.models.type.multi_version_config import MultiVersionConfig +from knext.schema.rest.models.type.standard_type_basic_info import StandardTypeBasicInfo +from knext.schema.rest.models.type.parent_type_info import ParentTypeInfo +from knext.schema.rest.models.type.project_schema import ProjectSchema +from knext.schema.rest.models.type.concept_taxonomic_config import ( + ConceptTaxonomicConfig, +) +from knext.schema.rest.models.type.standard_type import StandardType +from knext.schema.rest.models.type.spg_type_ref import SpgTypeRef +from knext.schema.rest.models.type.basic_type import BasicType +from knext.schema.rest.models.identifier.spg_type_identifier import SpgTypeIdentifier +from knext.schema.rest.models.identifier.base_spg_identifier import BaseSpgIdentifier +from knext.schema.rest.models.identifier.concept_identifier import ConceptIdentifier +from knext.schema.rest.models.identifier.operator_identifier import OperatorIdentifier +from knext.schema.rest.models.identifier.spg_triple_identifier import ( + SpgTripleIdentifier, +) +from knext.schema.rest.models.identifier.predicate_identifier import PredicateIdentifier +from knext.schema.rest.models.concept.remove_logical_causation_request import ( + RemoveLogicalCausationRequest, +) +from knext.schema.rest.models.concept.define_logical_causation_request import ( + DefineLogicalCausationRequest, +) +from knext.schema.rest.models.concept.remove_dynamic_taxonomy_request import ( + RemoveDynamicTaxonomyRequest, +) +from knext.schema.rest.models.concept.define_dynamic_taxonomy_request import ( + DefineDynamicTaxonomyRequest, +) +from knext.schema.rest.models.semantic.base_semantic import BaseSemantic +from knext.schema.rest.models.semantic.predicate_semantic import PredicateSemantic +from knext.schema.rest.models.semantic.rule_code import RuleCode +from knext.schema.rest.models.semantic.logical_rule import LogicalRule +from knext.schema.rest.models.operator.operator_version_response import ( + OperatorVersionResponse, +) +from knext.schema.rest.models.operator.operator_version_request import ( + OperatorVersionRequest, +) +from knext.schema.rest.models.operator.operator_overview import OperatorOverview +from knext.schema.rest.models.operator.operator_version import OperatorVersion +from knext.schema.rest.models.operator.operator_create_response import ( + OperatorCreateResponse, +) +from knext.schema.rest.models.operator.operator_create_request import ( + OperatorCreateRequest, +) +from knext.schema.rest.models.constraint.constraint import Constraint +from knext.schema.rest.models.constraint.base_constraint_item import BaseConstraintItem +from knext.schema.rest.models.constraint.multi_val_constraint import MultiValConstraint +from knext.schema.rest.models.constraint.regular_constraint import RegularConstraint +from knext.schema.rest.models.constraint.not_null_constraint import NotNullConstraint +from knext.schema.rest.models.constraint.enum_constraint import EnumConstraint diff --git a/knext/schema/rest/models/alter/__init__.py b/knext/schema/rest/models/alter/__init__.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/schema/rest/models/alter/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/schema/rest/models/alter/schema_alter_request.py b/knext/schema/rest/models/alter/schema_alter_request.py new file mode 100644 index 00000000..35e5a353 --- /dev/null +++ b/knext/schema/rest/models/alter/schema_alter_request.py @@ -0,0 +1,166 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class SchemaAlterRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"project_id": "int", "schema_draft": "SchemaDraft"} + + attribute_map = {"project_id": "projectId", "schema_draft": "schemaDraft"} + + def __init__( + self, project_id=None, schema_draft=None, local_vars_configuration=None + ): # noqa: E501 + """SchemaAlterRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._schema_draft = None + self.discriminator = None + + self.project_id = project_id + self.schema_draft = schema_draft + + @property + def project_id(self): + """Gets the project_id of this SchemaAlterRequest. # noqa: E501 + + + :return: The project_id of this SchemaAlterRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this SchemaAlterRequest. + + + :param project_id: The project_id of this SchemaAlterRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def schema_draft(self): + """Gets the schema_draft of this SchemaAlterRequest. # noqa: E501 + + + :return: The schema_draft of this SchemaAlterRequest. # noqa: E501 + :rtype: SchemaDraft + """ + return self._schema_draft + + @schema_draft.setter + def schema_draft(self, schema_draft): + """Sets the schema_draft of this SchemaAlterRequest. + + + :param schema_draft: The schema_draft of this SchemaAlterRequest. # noqa: E501 + :type: SchemaDraft + """ + if ( + self.local_vars_configuration.client_side_validation + and schema_draft is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `schema_draft`, must not be `None`" + ) # noqa: E501 + + self._schema_draft = schema_draft + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, SchemaAlterRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, SchemaAlterRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/alter/schema_draft.py b/knext/schema/rest/models/alter/schema_draft.py new file mode 100644 index 00000000..34037fd9 --- /dev/null +++ b/knext/schema/rest/models/alter/schema_draft.py @@ -0,0 +1,131 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class SchemaDraft(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"alter_spg_types": "list[BaseAdvancedType]"} + + attribute_map = {"alter_spg_types": "alterSpgTypes"} + + def __init__( + self, alter_spg_types=None, local_vars_configuration=None + ): # noqa: E501 + """SchemaDraft - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._alter_spg_types = None + self.discriminator = None + + if alter_spg_types is not None: + self.alter_spg_types = alter_spg_types + + @property + def alter_spg_types(self): + """Gets the alter_spg_types of this SchemaDraft. # noqa: E501 + + + :return: The alter_spg_types of this SchemaDraft. # noqa: E501 + :rtype: list[BaseAdvancedType] + """ + return self._alter_spg_types + + @alter_spg_types.setter + def alter_spg_types(self, alter_spg_types): + """Sets the alter_spg_types of this SchemaDraft. + + + :param alter_spg_types: The alter_spg_types of this SchemaDraft. # noqa: E501 + :type: list[BaseAdvancedType] + """ + + self._alter_spg_types = alter_spg_types + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, SchemaDraft): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, SchemaDraft): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/base_ontology.py b/knext/schema/rest/models/base_ontology.py new file mode 100644 index 00000000..d1972052 --- /dev/null +++ b/knext/schema/rest/models/base_ontology.py @@ -0,0 +1,228 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class BaseOntology(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + } + + attribute_map = { + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + } + + def __init__( + self, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + local_vars_configuration=None, + ): # noqa: E501 + """BaseOntology - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self.discriminator = None + + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + + @property + def project_id(self): + """Gets the project_id of this BaseOntology. # noqa: E501 + + + :return: The project_id of this BaseOntology. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this BaseOntology. + + + :param project_id: The project_id of this BaseOntology. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this BaseOntology. # noqa: E501 + + + :return: The ontology_id of this BaseOntology. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this BaseOntology. + + + :param ontology_id: The ontology_id of this BaseOntology. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this BaseOntology. # noqa: E501 + + + :return: The alter_operation of this BaseOntology. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this BaseOntology. + + + :param alter_operation: The alter_operation of this BaseOntology. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this BaseOntology. # noqa: E501 + + + :return: The ext_info of this BaseOntology. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this BaseOntology. + + + :param ext_info: The ext_info of this BaseOntology. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, BaseOntology): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, BaseOntology): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/basic_info.py b/knext/schema/rest/models/basic_info.py new file mode 100644 index 00000000..f3b7fdfc --- /dev/null +++ b/knext/schema/rest/models/basic_info.py @@ -0,0 +1,218 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class BasicInfo(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "name": "BaseSpgIdentifier", + "name_zh": "str", + "desc": "str", + "creator": "str", + } + + attribute_map = { + "name": "name", + "name_zh": "nameZh", + "desc": "desc", + "creator": "creator", + } + + def __init__( + self, + name=None, + name_zh=None, + desc=None, + creator=None, + local_vars_configuration=None, + ): # noqa: E501 + """BasicInfo - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._name = None + self._name_zh = None + self._desc = None + self._creator = None + self.discriminator = None + + if name is not None: + self.name = name + if name_zh is not None: + self.name_zh = name_zh + if desc is not None: + self.desc = desc + if creator is not None: + self.creator = creator + + @property + def name(self): + """Gets the name of this BasicInfo. # noqa: E501 + + + :return: The name of this BasicInfo. # noqa: E501 + :rtype: BaseSpgIdentifier + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this BasicInfo. + + + :param name: The name of this BasicInfo. # noqa: E501 + :type: BaseSpgIdentifier + """ + + self._name = name + + @property + def name_zh(self): + """Gets the name_zh of this BasicInfo. # noqa: E501 + + + :return: The name_zh of this BasicInfo. # noqa: E501 + :rtype: str + """ + return self._name_zh + + @name_zh.setter + def name_zh(self, name_zh): + """Sets the name_zh of this BasicInfo. + + + :param name_zh: The name_zh of this BasicInfo. # noqa: E501 + :type: str + """ + + self._name_zh = name_zh + + @property + def desc(self): + """Gets the desc of this BasicInfo. # noqa: E501 + + + :return: The desc of this BasicInfo. # noqa: E501 + :rtype: str + """ + return self._desc + + @desc.setter + def desc(self, desc): + """Sets the desc of this BasicInfo. + + + :param desc: The desc of this BasicInfo. # noqa: E501 + :type: str + """ + + self._desc = desc + + @property + def creator(self): + """Gets the creator of this BasicInfo. # noqa: E501 + + + :return: The creator of this BasicInfo. # noqa: E501 + :rtype: str + """ + return self._creator + + @creator.setter + def creator(self, creator): + """Sets the creator of this BasicInfo. + + + :param creator: The creator of this BasicInfo. # noqa: E501 + :type: str + """ + + self._creator = creator + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, BasicInfo): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, BasicInfo): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/concept/__init__.py b/knext/schema/rest/models/concept/__init__.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/schema/rest/models/concept/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/schema/rest/models/concept/define_dynamic_taxonomy_request.py b/knext/schema/rest/models/concept/define_dynamic_taxonomy_request.py new file mode 100644 index 00000000..44b441c4 --- /dev/null +++ b/knext/schema/rest/models/concept/define_dynamic_taxonomy_request.py @@ -0,0 +1,187 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class DefineDynamicTaxonomyRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"concept_type_name": "str", "concept_name": "str", "dsl": "str"} + + attribute_map = { + "concept_type_name": "conceptTypeName", + "concept_name": "conceptName", + "dsl": "dsl", + } + + def __init__( + self, + concept_type_name=None, + concept_name=None, + dsl=None, + local_vars_configuration=None, + ): # noqa: E501 + """DefineDynamicTaxonomyRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._concept_type_name = None + self._concept_name = None + self._dsl = None + self.discriminator = None + + if concept_type_name is not None: + self.concept_type_name = concept_type_name + if concept_name is not None: + self.concept_name = concept_name + if dsl is not None: + self.dsl = dsl + + @property + def concept_type_name(self): + """Gets the concept_type_name of this DefineDynamicTaxonomyRequest. # noqa: E501 + + + :return: The concept_type_name of this DefineDynamicTaxonomyRequest. # noqa: E501 + :rtype: str + """ + return self._concept_type_name + + @concept_type_name.setter + def concept_type_name(self, concept_type_name): + """Sets the concept_type_name of this DefineDynamicTaxonomyRequest. + + + :param concept_type_name: The concept_type_name of this DefineDynamicTaxonomyRequest. # noqa: E501 + :type: str + """ + + self._concept_type_name = concept_type_name + + @property + def concept_name(self): + """Gets the concept_name of this DefineDynamicTaxonomyRequest. # noqa: E501 + + + :return: The concept_name of this DefineDynamicTaxonomyRequest. # noqa: E501 + :rtype: str + """ + return self._concept_name + + @concept_name.setter + def concept_name(self, concept_name): + """Sets the concept_name of this DefineDynamicTaxonomyRequest. + + + :param concept_name: The concept_name of this DefineDynamicTaxonomyRequest. # noqa: E501 + :type: str + """ + + self._concept_name = concept_name + + @property + def dsl(self): + """Gets the dsl of this DefineDynamicTaxonomyRequest. # noqa: E501 + + + :return: The dsl of this DefineDynamicTaxonomyRequest. # noqa: E501 + :rtype: str + """ + return self._dsl + + @dsl.setter + def dsl(self, dsl): + """Sets the dsl of this DefineDynamicTaxonomyRequest. + + + :param dsl: The dsl of this DefineDynamicTaxonomyRequest. # noqa: E501 + :type: str + """ + + self._dsl = dsl + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, DefineDynamicTaxonomyRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, DefineDynamicTaxonomyRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/concept/define_logical_causation_request.py b/knext/schema/rest/models/concept/define_logical_causation_request.py new file mode 100644 index 00000000..5b17807d --- /dev/null +++ b/knext/schema/rest/models/concept/define_logical_causation_request.py @@ -0,0 +1,286 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class DefineLogicalCausationRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "subject_concept_type_name": "str", + "subject_concept_name": "str", + "predicate_name": "str", + "object_concept_type_name": "str", + "object_concept_name": "str", + "dsl": "str", + "semantic_type": "str", + } + + attribute_map = { + "subject_concept_type_name": "subjectConceptTypeName", + "subject_concept_name": "subjectConceptName", + "predicate_name": "predicateName", + "object_concept_type_name": "objectConceptTypeName", + "object_concept_name": "objectConceptName", + "dsl": "dsl", + "semantic_type": "semanticType", + } + + def __init__( + self, + subject_concept_type_name=None, + subject_concept_name=None, + predicate_name=None, + object_concept_type_name=None, + object_concept_name=None, + dsl=None, + semantic_type=None, + local_vars_configuration=None, + ): # noqa: E501 + """DefineLogicalCausationRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._subject_concept_type_name = None + self._subject_concept_name = None + self._predicate_name = None + self._object_concept_type_name = None + self._object_concept_name = None + self._dsl = None + self._semantic_type = None + self.discriminator = None + + if subject_concept_type_name is not None: + self.subject_concept_type_name = subject_concept_type_name + if subject_concept_name is not None: + self.subject_concept_name = subject_concept_name + if predicate_name is not None: + self.predicate_name = predicate_name + if object_concept_type_name is not None: + self.object_concept_type_name = object_concept_type_name + if object_concept_name is not None: + self.object_concept_name = object_concept_name + if dsl is not None: + self.dsl = dsl + if semantic_type is not None: + self.semantic_type = semantic_type + + @property + def subject_concept_type_name(self): + """Gets the subject_concept_type_name of this DefineLogicalCausationRequest. # noqa: E501 + + + :return: The subject_concept_type_name of this DefineLogicalCausationRequest. # noqa: E501 + :rtype: str + """ + return self._subject_concept_type_name + + @subject_concept_type_name.setter + def subject_concept_type_name(self, subject_concept_type_name): + """Sets the subject_concept_type_name of this DefineLogicalCausationRequest. + + + :param subject_concept_type_name: The subject_concept_type_name of this DefineLogicalCausationRequest. # noqa: E501 + :type: str + """ + + self._subject_concept_type_name = subject_concept_type_name + + @property + def subject_concept_name(self): + """Gets the subject_concept_name of this DefineLogicalCausationRequest. # noqa: E501 + + + :return: The subject_concept_name of this DefineLogicalCausationRequest. # noqa: E501 + :rtype: str + """ + return self._subject_concept_name + + @subject_concept_name.setter + def subject_concept_name(self, subject_concept_name): + """Sets the subject_concept_name of this DefineLogicalCausationRequest. + + + :param subject_concept_name: The subject_concept_name of this DefineLogicalCausationRequest. # noqa: E501 + :type: str + """ + + self._subject_concept_name = subject_concept_name + + @property + def predicate_name(self): + """Gets the predicate_name of this DefineLogicalCausationRequest. # noqa: E501 + + + :return: The predicate_name of this DefineLogicalCausationRequest. # noqa: E501 + :rtype: str + """ + return self._predicate_name + + @predicate_name.setter + def predicate_name(self, predicate_name): + """Sets the predicate_name of this DefineLogicalCausationRequest. + + + :param predicate_name: The predicate_name of this DefineLogicalCausationRequest. # noqa: E501 + :type: str + """ + + self._predicate_name = predicate_name + + @property + def object_concept_type_name(self): + """Gets the object_concept_type_name of this DefineLogicalCausationRequest. # noqa: E501 + + + :return: The object_concept_type_name of this DefineLogicalCausationRequest. # noqa: E501 + :rtype: str + """ + return self._object_concept_type_name + + @object_concept_type_name.setter + def object_concept_type_name(self, object_concept_type_name): + """Sets the object_concept_type_name of this DefineLogicalCausationRequest. + + + :param object_concept_type_name: The object_concept_type_name of this DefineLogicalCausationRequest. # noqa: E501 + :type: str + """ + + self._object_concept_type_name = object_concept_type_name + + @property + def object_concept_name(self): + """Gets the object_concept_name of this DefineLogicalCausationRequest. # noqa: E501 + + + :return: The object_concept_name of this DefineLogicalCausationRequest. # noqa: E501 + :rtype: str + """ + return self._object_concept_name + + @object_concept_name.setter + def object_concept_name(self, object_concept_name): + """Sets the object_concept_name of this DefineLogicalCausationRequest. + + + :param object_concept_name: The object_concept_name of this DefineLogicalCausationRequest. # noqa: E501 + :type: str + """ + + self._object_concept_name = object_concept_name + + @property + def dsl(self): + """Gets the dsl of this DefineLogicalCausationRequest. # noqa: E501 + + + :return: The dsl of this DefineLogicalCausationRequest. # noqa: E501 + :rtype: str + """ + return self._dsl + + @dsl.setter + def dsl(self, dsl): + """Sets the dsl of this DefineLogicalCausationRequest. + + + :param dsl: The dsl of this DefineLogicalCausationRequest. # noqa: E501 + :type: str + """ + + self._dsl = dsl + + @property + def semantic_type(self): + return self._semantic_type + + @semantic_type.setter + def semantic_type(self, semantic_type): + self._semantic_type = semantic_type + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, DefineLogicalCausationRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, DefineLogicalCausationRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/concept/remove_dynamic_taxonomy_request.py b/knext/schema/rest/models/concept/remove_dynamic_taxonomy_request.py new file mode 100644 index 00000000..94687eca --- /dev/null +++ b/knext/schema/rest/models/concept/remove_dynamic_taxonomy_request.py @@ -0,0 +1,161 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class RemoveDynamicTaxonomyRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"object_concept_type_name": "str", "object_concept_name": "str"} + + attribute_map = { + "object_concept_type_name": "objectConceptTypeName", + "object_concept_name": "objectConceptName", + } + + def __init__( + self, + object_concept_type_name=None, + object_concept_name=None, + local_vars_configuration=None, + ): # noqa: E501 + """RemoveDynamicTaxonomyRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._object_concept_type_name = None + self._object_concept_name = None + self.discriminator = None + + if object_concept_type_name is not None: + self.object_concept_type_name = object_concept_type_name + if object_concept_name is not None: + self.object_concept_name = object_concept_name + + @property + def object_concept_type_name(self): + """Gets the object_concept_type_name of this RemoveDynamicTaxonomyRequest. # noqa: E501 + + + :return: The object_concept_type_name of this RemoveDynamicTaxonomyRequest. # noqa: E501 + :rtype: str + """ + return self._object_concept_type_name + + @object_concept_type_name.setter + def object_concept_type_name(self, object_concept_type_name): + """Sets the object_concept_type_name of this RemoveDynamicTaxonomyRequest. + + + :param object_concept_type_name: The object_concept_type_name of this RemoveDynamicTaxonomyRequest. # noqa: E501 + :type: str + """ + + self._object_concept_type_name = object_concept_type_name + + @property + def object_concept_name(self): + """Gets the object_concept_name of this RemoveDynamicTaxonomyRequest. # noqa: E501 + + + :return: The object_concept_name of this RemoveDynamicTaxonomyRequest. # noqa: E501 + :rtype: str + """ + return self._object_concept_name + + @object_concept_name.setter + def object_concept_name(self, object_concept_name): + """Sets the object_concept_name of this RemoveDynamicTaxonomyRequest. + + + :param object_concept_name: The object_concept_name of this RemoveDynamicTaxonomyRequest. # noqa: E501 + :type: str + """ + + self._object_concept_name = object_concept_name + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RemoveDynamicTaxonomyRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, RemoveDynamicTaxonomyRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/concept/remove_logical_causation_request.py b/knext/schema/rest/models/concept/remove_logical_causation_request.py new file mode 100644 index 00000000..6ddcd980 --- /dev/null +++ b/knext/schema/rest/models/concept/remove_logical_causation_request.py @@ -0,0 +1,259 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class RemoveLogicalCausationRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "subject_concept_type_name": "str", + "subject_concept_name": "str", + "predicate_name": "str", + "object_concept_type_name": "str", + "object_concept_name": "str", + "semantic_type": "str", + } + + attribute_map = { + "subject_concept_type_name": "subjectConceptTypeName", + "subject_concept_name": "subjectConceptName", + "predicate_name": "predicateName", + "object_concept_type_name": "objectConceptTypeName", + "object_concept_name": "objectConceptName", + "semantic_type": "semanticType", + } + + def __init__( + self, + subject_concept_type_name=None, + subject_concept_name=None, + predicate_name=None, + object_concept_type_name=None, + object_concept_name=None, + semantic_type=None, + local_vars_configuration=None, + ): # noqa: E501 + """RemoveLogicalCausationRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._subject_concept_type_name = None + self._subject_concept_name = None + self._predicate_name = None + self._object_concept_type_name = None + self._object_concept_name = None + self._semantic_type = None + self.discriminator = None + + if subject_concept_type_name is not None: + self.subject_concept_type_name = subject_concept_type_name + if subject_concept_name is not None: + self.subject_concept_name = subject_concept_name + if predicate_name is not None: + self.predicate_name = predicate_name + if object_concept_type_name is not None: + self.object_concept_type_name = object_concept_type_name + if object_concept_name is not None: + self.object_concept_name = object_concept_name + if semantic_type is not None: + self.semantic_type = semantic_type + + @property + def subject_concept_type_name(self): + """Gets the subject_concept_type_name of this RemoveLogicalCausationRequest. # noqa: E501 + + + :return: The subject_concept_type_name of this RemoveLogicalCausationRequest. # noqa: E501 + :rtype: str + """ + return self._subject_concept_type_name + + @subject_concept_type_name.setter + def subject_concept_type_name(self, subject_concept_type_name): + """Sets the subject_concept_type_name of this RemoveLogicalCausationRequest. + + + :param subject_concept_type_name: The subject_concept_type_name of this RemoveLogicalCausationRequest. # noqa: E501 + :type: str + """ + + self._subject_concept_type_name = subject_concept_type_name + + @property + def subject_concept_name(self): + """Gets the subject_concept_name of this RemoveLogicalCausationRequest. # noqa: E501 + + + :return: The subject_concept_name of this RemoveLogicalCausationRequest. # noqa: E501 + :rtype: str + """ + return self._subject_concept_name + + @subject_concept_name.setter + def subject_concept_name(self, subject_concept_name): + """Sets the subject_concept_name of this RemoveLogicalCausationRequest. + + + :param subject_concept_name: The subject_concept_name of this RemoveLogicalCausationRequest. # noqa: E501 + :type: str + """ + + self._subject_concept_name = subject_concept_name + + @property + def predicate_name(self): + """Gets the predicate_name of this RemoveLogicalCausationRequest. # noqa: E501 + + + :return: The predicate_name of this RemoveLogicalCausationRequest. # noqa: E501 + :rtype: str + """ + return self._predicate_name + + @predicate_name.setter + def predicate_name(self, predicate_name): + """Sets the predicate_name of this RemoveLogicalCausationRequest. + + + :param predicate_name: The predicate_name of this RemoveLogicalCausationRequest. # noqa: E501 + :type: str + """ + + self._predicate_name = predicate_name + + @property + def object_concept_type_name(self): + """Gets the object_concept_type_name of this RemoveLogicalCausationRequest. # noqa: E501 + + + :return: The object_concept_type_name of this RemoveLogicalCausationRequest. # noqa: E501 + :rtype: str + """ + return self._object_concept_type_name + + @object_concept_type_name.setter + def object_concept_type_name(self, object_concept_type_name): + """Sets the object_concept_type_name of this RemoveLogicalCausationRequest. + + + :param object_concept_type_name: The object_concept_type_name of this RemoveLogicalCausationRequest. # noqa: E501 + :type: str + """ + + self._object_concept_type_name = object_concept_type_name + + @property + def object_concept_name(self): + """Gets the object_concept_name of this RemoveLogicalCausationRequest. # noqa: E501 + + + :return: The object_concept_name of this RemoveLogicalCausationRequest. # noqa: E501 + :rtype: str + """ + return self._object_concept_name + + @object_concept_name.setter + def object_concept_name(self, object_concept_name): + """Sets the object_concept_name of this RemoveLogicalCausationRequest. + + + :param object_concept_name: The object_concept_name of this RemoveLogicalCausationRequest. # noqa: E501 + :type: str + """ + + self._object_concept_name = object_concept_name + + @property + def semantic_type(self): + return self._semantic_type + + @semantic_type.setter + def semantic_type(self, semantic_type): + self._semantic_type = semantic_type + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RemoveLogicalCausationRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, RemoveLogicalCausationRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/constraint/__init__.py b/knext/schema/rest/models/constraint/__init__.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/schema/rest/models/constraint/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/schema/rest/models/constraint/base_constraint_item.py b/knext/schema/rest/models/constraint/base_constraint_item.py new file mode 100644 index 00000000..11ca1d05 --- /dev/null +++ b/knext/schema/rest/models/constraint/base_constraint_item.py @@ -0,0 +1,162 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class BaseConstraintItem(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"constraint_type_enum": "str"} + + attribute_map = {"constraint_type_enum": "constraintTypeEnum"} + + discriminator_value_class_map = { + "ENUM": "EnumConstraint", + "MULTI_VALUE": "MultiValConstraint", + "NOT_NULL": "NotNullConstraint", + "REGULAR": "RegularConstraint", + } + + def __init__( + self, constraint_type_enum=None, local_vars_configuration=None + ): # noqa: E501 + """BaseConstraintItem - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._constraint_type_enum = None + self.discriminator = constraint_type_enum + + self.constraint_type_enum = constraint_type_enum + + @property + def constraint_type_enum(self): + """Gets the constraint_type_enum of this BaseConstraintItem. # noqa: E501 + + + :return: The constraint_type_enum of this BaseConstraintItem. # noqa: E501 + :rtype: str + """ + return self._constraint_type_enum + + @constraint_type_enum.setter + def constraint_type_enum(self, constraint_type_enum): + """Sets the constraint_type_enum of this BaseConstraintItem. + + + :param constraint_type_enum: The constraint_type_enum of this BaseConstraintItem. # noqa: E501 + :type: str + """ + + allowed_values = [ + None, + "NOT_NULL", + "MULTI_VALUE", + "ENUM", + "REGULAR", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and constraint_type_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `constraint_type_enum` ({0}), must be one of {1}".format( # noqa: E501 + constraint_type_enum, allowed_values + ) + ) + + self._constraint_type_enum = constraint_type_enum + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def get_real_child_model(self, data): + """Returns the child model by discriminator""" + if "@type" in data: + child_type = data.get("@type") + real_child_model = self.discriminator_value_class_map.get(child_type) + return real_child_model + return None + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, BaseConstraintItem): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, BaseConstraintItem): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/constraint/constraint.py b/knext/schema/rest/models/constraint/constraint.py new file mode 100644 index 00000000..bc9a0db6 --- /dev/null +++ b/knext/schema/rest/models/constraint/constraint.py @@ -0,0 +1,155 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class Constraint(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"id": "int", "constraint_items": "list[BaseConstraintItem]"} + + attribute_map = {"id": "id", "constraint_items": "constraintItems"} + + def __init__( + self, id=None, constraint_items=None, local_vars_configuration=None + ): # noqa: E501 + """Constraint - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._id = None + self._constraint_items = None + self.discriminator = None + + if id is not None: + self.id = id + if constraint_items is not None: + self.constraint_items = constraint_items + + @property + def id(self): + """Gets the id of this Constraint. # noqa: E501 + + + :return: The id of this Constraint. # noqa: E501 + :rtype: int + """ + return self._id + + @id.setter + def id(self, id): + """Sets the id of this Constraint. + + + :param id: The id of this Constraint. # noqa: E501 + :type: int + """ + + self._id = id + + @property + def constraint_items(self): + """Gets the constraint_items of this Constraint. # noqa: E501 + + + :return: The constraint_items of this Constraint. # noqa: E501 + :rtype: list[BaseConstraintItem] + """ + return self._constraint_items + + @constraint_items.setter + def constraint_items(self, constraint_items): + """Sets the constraint_items of this Constraint. + + + :param constraint_items: The constraint_items of this Constraint. # noqa: E501 + :type: list[BaseConstraintItem] + """ + + self._constraint_items = constraint_items + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, Constraint): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, Constraint): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/constraint/enum_constraint.py b/knext/schema/rest/models/constraint/enum_constraint.py new file mode 100644 index 00000000..fa4c0909 --- /dev/null +++ b/knext/schema/rest/models/constraint/enum_constraint.py @@ -0,0 +1,178 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class EnumConstraint(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"constraint_type_enum": "str", "enum_values": "list[str]"} + + attribute_map = { + "constraint_type_enum": "constraintTypeEnum", + "enum_values": "enumValues", + } + + def __init__( + self, + constraint_type_enum="ENUM", + enum_values=None, + local_vars_configuration=None, + ): # noqa: E501 + """EnumConstraint - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._constraint_type_enum = None + self._enum_values = None + self.discriminator = constraint_type_enum + + self.constraint_type_enum = constraint_type_enum + if enum_values is not None: + self.enum_values = enum_values + + @property + def constraint_type_enum(self): + """Gets the constraint_type_enum of this EnumConstraint. # noqa: E501 + + + :return: The constraint_type_enum of this EnumConstraint. # noqa: E501 + :rtype: str + """ + return self._constraint_type_enum + + @constraint_type_enum.setter + def constraint_type_enum(self, constraint_type_enum): + """Sets the constraint_type_enum of this EnumConstraint. + + + :param constraint_type_enum: The constraint_type_enum of this EnumConstraint. # noqa: E501 + :type: str + """ + allowed_values = [ + None, + "NOTNULL", + "UNIQUE", + "MULTIVALUE", + "ENUM", + "RANGE", + "REGULAR", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and constraint_type_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `constraint_type_enum` ({0}), must be one of {1}".format( # noqa: E501 + constraint_type_enum, allowed_values + ) + ) + + self._constraint_type_enum = constraint_type_enum + + @property + def enum_values(self): + """Gets the enum_values of this EnumConstraint. # noqa: E501 + + + :return: The enum_values of this EnumConstraint. # noqa: E501 + :rtype: list[str] + """ + return self._enum_values + + @enum_values.setter + def enum_values(self, enum_values): + """Sets the enum_values of this EnumConstraint. + + + :param enum_values: The enum_values of this EnumConstraint. # noqa: E501 + :type: list[str] + """ + + self._enum_values = enum_values + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, EnumConstraint): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, EnumConstraint): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/constraint/multi_val_constraint.py b/knext/schema/rest/models/constraint/multi_val_constraint.py new file mode 100644 index 00000000..ab1a5c1b --- /dev/null +++ b/knext/schema/rest/models/constraint/multi_val_constraint.py @@ -0,0 +1,148 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class MultiValConstraint(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"constraint_type_enum": "str"} + + attribute_map = {"constraint_type_enum": "constraintTypeEnum"} + + def __init__( + self, constraint_type_enum="MULTI_VALUE", local_vars_configuration=None + ): # noqa: E501 + """MultiValConstraint - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._constraint_type_enum = None + self.discriminator = constraint_type_enum + + self.constraint_type_enum = constraint_type_enum + + @property + def constraint_type_enum(self): + """Gets the constraint_type_enum of this MultiValConstraint. # noqa: E501 + + + :return: The constraint_type_enum of this MultiValConstraint. # noqa: E501 + :rtype: str + """ + return self._constraint_type_enum + + @constraint_type_enum.setter + def constraint_type_enum(self, constraint_type_enum): + """Sets the constraint_type_enum of this MultiValConstraint. + + + :param constraint_type_enum: The constraint_type_enum of this MultiValConstraint. # noqa: E501 + :type: str + """ + allowed_values = [ + None, + "NOT_NULL", + "UNIQUE", + "MULTI_VALUE", + "ENUM", + "RANGE", + "REGULAR", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and constraint_type_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `constraint_type_enum` ({0}), must be one of {1}".format( # noqa: E501 + constraint_type_enum, allowed_values + ) + ) + + self._constraint_type_enum = constraint_type_enum + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, MultiValConstraint): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, MultiValConstraint): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/constraint/not_null_constraint.py b/knext/schema/rest/models/constraint/not_null_constraint.py new file mode 100644 index 00000000..00a14b81 --- /dev/null +++ b/knext/schema/rest/models/constraint/not_null_constraint.py @@ -0,0 +1,148 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class NotNullConstraint(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"constraint_type_enum": "str"} + + attribute_map = {"constraint_type_enum": "constraintTypeEnum"} + + def __init__( + self, constraint_type_enum="NOT_NULL", local_vars_configuration=None + ): # noqa: E501 + """NotNullConstraint - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._constraint_type_enum = None + self.discriminator = constraint_type_enum + + self.constraint_type_enum = constraint_type_enum + + @property + def constraint_type_enum(self): + """Gets the constraint_type_enum of this NotNullConstraint. # noqa: E501 + + + :return: The constraint_type_enum of this NotNullConstraint. # noqa: E501 + :rtype: str + """ + return self._constraint_type_enum + + @constraint_type_enum.setter + def constraint_type_enum(self, constraint_type_enum): + """Sets the constraint_type_enum of this NotNullConstraint. + + + :param constraint_type_enum: The constraint_type_enum of this NotNullConstraint. # noqa: E501 + :type: str + """ + allowed_values = [ + None, + "NOT_NULL", + "UNIQUE", + "MULTI_VALUE", + "ENUM", + "RANGE", + "REGULAR", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and constraint_type_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `constraint_type_enum` ({0}), must be one of {1}".format( # noqa: E501 + constraint_type_enum, allowed_values + ) + ) + + self._constraint_type_enum = constraint_type_enum + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, NotNullConstraint): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, NotNullConstraint): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/constraint/regular_constraint.py b/knext/schema/rest/models/constraint/regular_constraint.py new file mode 100644 index 00000000..5c97537b --- /dev/null +++ b/knext/schema/rest/models/constraint/regular_constraint.py @@ -0,0 +1,178 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class RegularConstraint(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"constraint_type_enum": "str", "regular_pattern": "str"} + + attribute_map = { + "constraint_type_enum": "constraintTypeEnum", + "regular_pattern": "regularPattern", + } + + def __init__( + self, + constraint_type_enum="REGULAR", + regular_pattern=None, + local_vars_configuration=None, + ): # noqa: E501 + """RegularConstraint - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._constraint_type_enum = None + self._regular_pattern = None + self.discriminator = constraint_type_enum + + self.constraint_type_enum = constraint_type_enum + if regular_pattern is not None: + self.regular_pattern = regular_pattern + + @property + def constraint_type_enum(self): + """Gets the constraint_type_enum of this RegularConstraint. # noqa: E501 + + + :return: The constraint_type_enum of this RegularConstraint. # noqa: E501 + :rtype: str + """ + return self._constraint_type_enum + + @constraint_type_enum.setter + def constraint_type_enum(self, constraint_type_enum): + """Sets the constraint_type_enum of this RegularConstraint. + + + :param constraint_type_enum: The constraint_type_enum of this RegularConstraint. # noqa: E501 + :type: str + """ + allowed_values = [ + None, + "NOT_NULL", + "UNIQUE", + "MULTI_VALUE", + "ENUM", + "RANGE", + "REGULAR", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and constraint_type_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `constraint_type_enum` ({0}), must be one of {1}".format( # noqa: E501 + constraint_type_enum, allowed_values + ) + ) + + self._constraint_type_enum = constraint_type_enum + + @property + def regular_pattern(self): + """Gets the regular_pattern of this RegularConstraint. # noqa: E501 + + + :return: The regular_pattern of this RegularConstraint. # noqa: E501 + :rtype: str + """ + return self._regular_pattern + + @regular_pattern.setter + def regular_pattern(self, regular_pattern): + """Sets the regular_pattern of this RegularConstraint. + + + :param regular_pattern: The regular_pattern of this RegularConstraint. # noqa: E501 + :type: str + """ + + self._regular_pattern = regular_pattern + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RegularConstraint): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, RegularConstraint): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/identifier/__init__.py b/knext/schema/rest/models/identifier/__init__.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/schema/rest/models/identifier/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/schema/rest/models/identifier/base_spg_identifier.py b/knext/schema/rest/models/identifier/base_spg_identifier.py new file mode 100644 index 00000000..ab75bcaa --- /dev/null +++ b/knext/schema/rest/models/identifier/base_spg_identifier.py @@ -0,0 +1,166 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class BaseSpgIdentifier(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"identity_type": "str"} + + attribute_map = {"identity_type": "identityType"} + + discriminator_value_class_map = { + "SPG_TYPE": "SpgTypeIdentifier", + "SPG_TRIPLE": "SpgTripleIdentifier", + "CONCEPT": "ConceptIdentifier", + "PREDICATE": "PredicateIdentifier", + "OPERATOR": "OperatorIdentifier", + } + + def __init__(self, identity_type=None, local_vars_configuration=None): # noqa: E501 + """BaseSpgIdentifier - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._identity_type = None + self.discriminator = None + + self.identity_type = identity_type + + @property + def identity_type(self): + """Gets the identity_type of this BaseSpgIdentifier. # noqa: E501 + + + :return: The identity_type of this BaseSpgIdentifier. # noqa: E501 + :rtype: str + """ + return self._identity_type + + @identity_type.setter + def identity_type(self, identity_type): + """Sets the identity_type of this BaseSpgIdentifier. + + + :param identity_type: The identity_type of this BaseSpgIdentifier. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and identity_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `identity_type`, must not be `None`" + ) # noqa: E501 + allowed_values = [ + "SPG_TYPE", + "SPG_TRIPLE", + "CONCEPT", + "PREDICATE", + "OPERATOR", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and identity_type not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `identity_type` ({0}), must be one of {1}".format( # noqa: E501 + identity_type, allowed_values + ) + ) + + self._identity_type = identity_type + + def get_real_child_model(self, data): + """Returns the child model by discriminator""" + if "@type" in data: + child_type = data.get("@type") + real_child_model = self.discriminator_value_class_map.get(child_type) + return real_child_model + return None + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, BaseSpgIdentifier): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, BaseSpgIdentifier): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/identifier/concept_identifier.py b/knext/schema/rest/models/identifier/concept_identifier.py new file mode 100644 index 00000000..0e648e5f --- /dev/null +++ b/knext/schema/rest/models/identifier/concept_identifier.py @@ -0,0 +1,177 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ConceptIdentifier(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"identity_type": "str", "name": "str"} + + attribute_map = {"identity_type": "identityType", "name": "name"} + + def __init__( + self, identity_type="CONCEPT", name=None, local_vars_configuration=None + ): # noqa: E501 + """ConceptIdentifier - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._identity_type = None + self._name = None + self.discriminator = identity_type + + self.identity_type = identity_type + if name is not None: + self.name = name + + @property + def identity_type(self): + """Gets the identity_type of this ConceptIdentifier. # noqa: E501 + + + :return: The identity_type of this ConceptIdentifier. # noqa: E501 + :rtype: str + """ + return self._identity_type + + @identity_type.setter + def identity_type(self, identity_type): + """Sets the identity_type of this ConceptIdentifier. + + + :param identity_type: The identity_type of this ConceptIdentifier. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and identity_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `identity_type`, must not be `None`" + ) # noqa: E501 + allowed_values = [ + "SPG_TYPE", + "SPG_TRIPLE", + "CONCEPT", + "PREDICATE", + "OPERATOR", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and identity_type not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `identity_type` ({0}), must be one of {1}".format( # noqa: E501 + identity_type, allowed_values + ) + ) + + self._identity_type = identity_type + + @property + def name(self): + """Gets the name of this ConceptIdentifier. # noqa: E501 + + + :return: The name of this ConceptIdentifier. # noqa: E501 + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this ConceptIdentifier. + + + :param name: The name of this ConceptIdentifier. # noqa: E501 + :type: str + """ + + self._name = name + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ConceptIdentifier): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ConceptIdentifier): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/identifier/operator_identifier.py b/knext/schema/rest/models/identifier/operator_identifier.py new file mode 100644 index 00000000..7278cccc --- /dev/null +++ b/knext/schema/rest/models/identifier/operator_identifier.py @@ -0,0 +1,177 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class OperatorIdentifier(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"identity_type": "str", "name": "str"} + + attribute_map = {"identity_type": "identityType", "name": "name"} + + def __init__( + self, identity_type="OPERATOR", name=None, local_vars_configuration=None + ): # noqa: E501 + """OperatorIdentifier - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._identity_type = None + self._name = None + self.discriminator = identity_type + + self.identity_type = identity_type + if name is not None: + self.name = name + + @property + def identity_type(self): + """Gets the identity_type of this OperatorIdentifier. # noqa: E501 + + + :return: The identity_type of this OperatorIdentifier. # noqa: E501 + :rtype: str + """ + return self._identity_type + + @identity_type.setter + def identity_type(self, identity_type): + """Sets the identity_type of this OperatorIdentifier. + + + :param identity_type: The identity_type of this OperatorIdentifier. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and identity_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `identity_type`, must not be `None`" + ) # noqa: E501 + allowed_values = [ + "SPG_TYPE", + "SPG_TRIPLE", + "CONCEPT", + "PREDICATE", + "OPERATOR", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and identity_type not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `identity_type` ({0}), must be one of {1}".format( # noqa: E501 + identity_type, allowed_values + ) + ) + + self._identity_type = identity_type + + @property + def name(self): + """Gets the name of this OperatorIdentifier. # noqa: E501 + + + :return: The name of this OperatorIdentifier. # noqa: E501 + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this OperatorIdentifier. + + + :param name: The name of this OperatorIdentifier. # noqa: E501 + :type: str + """ + + self._name = name + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, OperatorIdentifier): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, OperatorIdentifier): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/identifier/predicate_identifier.py b/knext/schema/rest/models/identifier/predicate_identifier.py new file mode 100644 index 00000000..892c5ffc --- /dev/null +++ b/knext/schema/rest/models/identifier/predicate_identifier.py @@ -0,0 +1,177 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class PredicateIdentifier(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"identity_type": "str", "name": "str"} + + attribute_map = {"identity_type": "identityType", "name": "name"} + + def __init__( + self, identity_type="PREDICATE", name=None, local_vars_configuration=None + ): # noqa: E501 + """PredicateIdentifier - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._identity_type = None + self._name = None + self.discriminator = identity_type + + self.identity_type = identity_type + if name is not None: + self.name = name + + @property + def identity_type(self): + """Gets the identity_type of this PredicateIdentifier. # noqa: E501 + + + :return: The identity_type of this PredicateIdentifier. # noqa: E501 + :rtype: str + """ + return self._identity_type + + @identity_type.setter + def identity_type(self, identity_type): + """Sets the identity_type of this PredicateIdentifier. + + + :param identity_type: The identity_type of this PredicateIdentifier. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and identity_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `identity_type`, must not be `None`" + ) # noqa: E501 + allowed_values = [ + "SPG_TYPE", + "SPG_TRIPLE", + "CONCEPT", + "PREDICATE", + "OPERATOR", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and identity_type not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `identity_type` ({0}), must be one of {1}".format( # noqa: E501 + identity_type, allowed_values + ) + ) + + self._identity_type = identity_type + + @property + def name(self): + """Gets the name of this PredicateIdentifier. # noqa: E501 + + + :return: The name of this PredicateIdentifier. # noqa: E501 + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this PredicateIdentifier. + + + :param name: The name of this PredicateIdentifier. # noqa: E501 + :type: str + """ + + self._name = name + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, PredicateIdentifier): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, PredicateIdentifier): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/identifier/spg_triple_identifier.py b/knext/schema/rest/models/identifier/spg_triple_identifier.py new file mode 100644 index 00000000..8697ab89 --- /dev/null +++ b/knext/schema/rest/models/identifier/spg_triple_identifier.py @@ -0,0 +1,240 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class SpgTripleIdentifier(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "identity_type": "str", + "subject": "BaseSpgIdentifier", + "predicate": "PredicateIdentifier", + "object": "BaseSpgIdentifier", + } + + attribute_map = { + "identity_type": "identityType", + "subject": "subject", + "predicate": "predicate", + "object": "object", + } + + def __init__( + self, + identity_type="SPG_TRIPLE", + subject=None, + predicate=None, + object=None, + local_vars_configuration=None, + ): # noqa: E501 + """SpgTripleIdentifier - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._identity_type = None + self._subject = None + self._predicate = None + self._object = None + self.discriminator = identity_type + + self.identity_type = identity_type + if subject is not None: + self.subject = subject + if predicate is not None: + self.predicate = predicate + if object is not None: + self.object = object + + @property + def identity_type(self): + """Gets the identity_type of this SpgTripleIdentifier. # noqa: E501 + + + :return: The identity_type of this SpgTripleIdentifier. # noqa: E501 + :rtype: str + """ + return self._identity_type + + @identity_type.setter + def identity_type(self, identity_type): + """Sets the identity_type of this SpgTripleIdentifier. + + + :param identity_type: The identity_type of this SpgTripleIdentifier. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and identity_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `identity_type`, must not be `None`" + ) # noqa: E501 + allowed_values = [ + "SPG_TYPE", + "SPG_TRIPLE", + "CONCEPT", + "PREDICATE", + "OPERATOR", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and identity_type not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `identity_type` ({0}), must be one of {1}".format( # noqa: E501 + identity_type, allowed_values + ) + ) + + self._identity_type = identity_type + + @property + def subject(self): + """Gets the subject of this SpgTripleIdentifier. # noqa: E501 + + + :return: The subject of this SpgTripleIdentifier. # noqa: E501 + :rtype: BaseSpgIdentifier + """ + return self._subject + + @subject.setter + def subject(self, subject): + """Sets the subject of this SpgTripleIdentifier. + + + :param subject: The subject of this SpgTripleIdentifier. # noqa: E501 + :type: BaseSpgIdentifier + """ + + self._subject = subject + + @property + def predicate(self): + """Gets the predicate of this SpgTripleIdentifier. # noqa: E501 + + + :return: The predicate of this SpgTripleIdentifier. # noqa: E501 + :rtype: PredicateIdentifier + """ + return self._predicate + + @predicate.setter + def predicate(self, predicate): + """Sets the predicate of this SpgTripleIdentifier. + + + :param predicate: The predicate of this SpgTripleIdentifier. # noqa: E501 + :type: PredicateIdentifier + """ + + self._predicate = predicate + + @property + def object(self): + """Gets the object of this SpgTripleIdentifier. # noqa: E501 + + + :return: The object of this SpgTripleIdentifier. # noqa: E501 + :rtype: BaseSpgIdentifier + """ + return self._object + + @object.setter + def object(self, object): + """Sets the object of this SpgTripleIdentifier. + + + :param object: The object of this SpgTripleIdentifier. # noqa: E501 + :type: BaseSpgIdentifier + """ + + self._object = object + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, SpgTripleIdentifier): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, SpgTripleIdentifier): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/identifier/spg_type_identifier.py b/knext/schema/rest/models/identifier/spg_type_identifier.py new file mode 100644 index 00000000..b032caa8 --- /dev/null +++ b/knext/schema/rest/models/identifier/spg_type_identifier.py @@ -0,0 +1,235 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class SpgTypeIdentifier(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"identity_type": "str", "namespace": "str", "name_en": "str"} + + attribute_map = { + "identity_type": "identityType", + "namespace": "namespace", + "name_en": "nameEn", + } + + def __init__( + self, + identity_type="SPG_TYPE", + namespace=None, + name_en=None, + local_vars_configuration=None, + ): # noqa: E501 + """SpgTypeIdentifier - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._identity_type = None + self._namespace = None + self._name_en = None + self.discriminator = identity_type + + self.identity_type = identity_type + if namespace is not None: + self.namespace = namespace + if name_en is not None: + self.name_en = name_en + + @property + def identity_type(self): + """Gets the identity_type of this SpgTypeIdentifier. # noqa: E501 + + + :return: The identity_type of this SpgTypeIdentifier. # noqa: E501 + :rtype: str + """ + return self._identity_type + + @identity_type.setter + def identity_type(self, identity_type): + """Sets the identity_type of this SpgTypeIdentifier. + + + :param identity_type: The identity_type of this SpgTypeIdentifier. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and identity_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `identity_type`, must not be `None`" + ) # noqa: E501 + allowed_values = [ + "SPG_TYPE", + "SPG_TRIPLE", + "CONCEPT", + "PREDICATE", + "OPERATOR", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and identity_type not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `identity_type` ({0}), must be one of {1}".format( # noqa: E501 + identity_type, allowed_values + ) + ) + + self._identity_type = identity_type + + @property + def namespace(self): + """Gets the namespace of this SpgTypeIdentifier. # noqa: E501 + + + :return: The namespace of this SpgTypeIdentifier. # noqa: E501 + :rtype: str + """ + return self._namespace + + @namespace.setter + def namespace(self, namespace): + """Sets the namespace of this SpgTypeIdentifier. + + + :param namespace: The namespace of this SpgTypeIdentifier. # noqa: E501 + :type: str + """ + + self._namespace = namespace + + @property + def name_en(self): + """Gets the name_en of this SpgTypeIdentifier. # noqa: E501 + + + :return: The name_en of this SpgTypeIdentifier. # noqa: E501 + :rtype: str + """ + return self._name_en + + @name_en.setter + def name_en(self, name_en): + """Sets the name_en of this SpgTypeIdentifier. + + + :param name_en: The name_en of this SpgTypeIdentifier. # noqa: E501 + :type: str + """ + + self._name_en = name_en + + @property + def name(self): + """Gets the full name of this SpgTypeIdentifier. # noqa: E501 + + + :return: The full name of this SpgTypeIdentifier. # noqa: E501 + :rtype: str + """ + return self.namespace + "." + self.name_en if self.namespace else self.name_en + + @name.setter + def name(self, name): + """Sets the name of this SpgTypeIdentifier. + + + :param name: The name of this SpgTypeIdentifier. # noqa: E501 + :type: str + """ + + name_split = name.split(".") + if len(name_split) == 1: + self.name_en = name + elif len(name_split) == 2: + self.namespace = name_split[0] + self.name_en = name_split[1] + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, SpgTypeIdentifier): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, SpgTypeIdentifier): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/ontology_id.py b/knext/schema/rest/models/ontology_id.py new file mode 100644 index 00000000..a1f98c42 --- /dev/null +++ b/knext/schema/rest/models/ontology_id.py @@ -0,0 +1,155 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class OntologyId(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"unique_id": "int", "alter_id": "int"} + + attribute_map = {"unique_id": "uniqueId", "alter_id": "alterId"} + + def __init__( + self, unique_id=None, alter_id=None, local_vars_configuration=None + ): # noqa: E501 + """OntologyId - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._unique_id = None + self._alter_id = None + self.discriminator = None + + if unique_id is not None: + self.unique_id = unique_id + if alter_id is not None: + self.alter_id = alter_id + + @property + def unique_id(self): + """Gets the unique_id of this OntologyId. # noqa: E501 + + + :return: The unique_id of this OntologyId. # noqa: E501 + :rtype: int + """ + return self._unique_id + + @unique_id.setter + def unique_id(self, unique_id): + """Sets the unique_id of this OntologyId. + + + :param unique_id: The unique_id of this OntologyId. # noqa: E501 + :type: int + """ + + self._unique_id = unique_id + + @property + def alter_id(self): + """Gets the alter_id of this OntologyId. # noqa: E501 + + + :return: The alter_id of this OntologyId. # noqa: E501 + :rtype: int + """ + return self._alter_id + + @alter_id.setter + def alter_id(self, alter_id): + """Sets the alter_id of this OntologyId. + + + :param alter_id: The alter_id of this OntologyId. # noqa: E501 + :type: int + """ + + self._alter_id = alter_id + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, OntologyId): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, OntologyId): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/operator/__init__.py b/knext/schema/rest/models/operator/__init__.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/schema/rest/models/operator/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/schema/rest/models/operator/operator_create_request.py b/knext/schema/rest/models/operator/operator_create_request.py new file mode 100644 index 00000000..8f98e196 --- /dev/null +++ b/knext/schema/rest/models/operator/operator_create_request.py @@ -0,0 +1,210 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class OperatorCreateRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"name": "str", "desc": "str", "operator_type": "str"} + + attribute_map = {"name": "name", "desc": "desc", "operator_type": "operatorType"} + + def __init__( + self, name=None, desc=None, operator_type=None, local_vars_configuration=None + ): # noqa: E501 + """OperatorCreateRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._name = None + self._desc = None + self._operator_type = None + self.discriminator = None + + self.name = name + self.desc = desc + self.operator_type = operator_type + + @property + def name(self): + """Gets the name of this OperatorCreateRequest. # noqa: E501 + + + :return: The name of this OperatorCreateRequest. # noqa: E501 + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this OperatorCreateRequest. + + + :param name: The name of this OperatorCreateRequest. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and name is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `name`, must not be `None`" + ) # noqa: E501 + + self._name = name + + @property + def desc(self): + """Gets the desc of this OperatorCreateRequest. # noqa: E501 + + + :return: The desc of this OperatorCreateRequest. # noqa: E501 + :rtype: str + """ + return self._desc + + @desc.setter + def desc(self, desc): + """Sets the desc of this OperatorCreateRequest. + + + :param desc: The desc of this OperatorCreateRequest. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and desc is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `desc`, must not be `None`" + ) # noqa: E501 + + self._desc = desc + + @property + def operator_type(self): + """Gets the operator_type of this OperatorCreateRequest. # noqa: E501 + + + :return: The operator_type of this OperatorCreateRequest. # noqa: E501 + :rtype: str + """ + return self._operator_type + + @operator_type.setter + def operator_type(self, operator_type): + """Sets the operator_type of this OperatorCreateRequest. + + + :param operator_type: The operator_type of this OperatorCreateRequest. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and operator_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `operator_type`, must not be `None`" + ) # noqa: E501 + allowed_values = [ + "KNOWLEDGE_EXTRACT", + "ENTITY_LINK", + "PROPERTY_NORMALIZE", + "ENTITY_FUSE", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and operator_type not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `operator_type` ({0}), must be one of {1}".format( # noqa: E501 + operator_type, allowed_values + ) + ) + + self._operator_type = operator_type + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, OperatorCreateRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, OperatorCreateRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/operator/operator_create_response.py b/knext/schema/rest/models/operator/operator_create_response.py new file mode 100644 index 00000000..849dafe5 --- /dev/null +++ b/knext/schema/rest/models/operator/operator_create_response.py @@ -0,0 +1,161 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class OperatorCreateResponse(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"name": "str", "operator_id": "str"} + + attribute_map = {"name": "name", "operator_id": "operatorId"} + + def __init__( + self, name=None, operator_id=None, local_vars_configuration=None + ): # noqa: E501 + """OperatorCreateResponse - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._name = None + self._operator_id = None + self.discriminator = None + + self.name = name + self.operator_id = operator_id + + @property + def name(self): + """Gets the name of this OperatorCreateResponse. # noqa: E501 + + + :return: The name of this OperatorCreateResponse. # noqa: E501 + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this OperatorCreateResponse. + + + :param name: The name of this OperatorCreateResponse. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and name is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `name`, must not be `None`" + ) # noqa: E501 + + self._name = name + + @property + def operator_id(self): + """Gets the operator_id of this OperatorCreateResponse. # noqa: E501 + + + :return: The operator_id of this OperatorCreateResponse. # noqa: E501 + :rtype: str + """ + return self._operator_id + + @operator_id.setter + def operator_id(self, operator_id): + """Sets the operator_id of this OperatorCreateResponse. + + + :param operator_id: The operator_id of this OperatorCreateResponse. # noqa: E501 + :type: str + """ + # if self.local_vars_configuration.client_side_validation and operator_id is None: # noqa: E501 + # raise ValueError("Invalid value for `operator_id`, must not be `None`") # noqa: E501 + + self._operator_id = operator_id + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, OperatorCreateResponse): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, OperatorCreateResponse): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/operator/operator_overview.py b/knext/schema/rest/models/operator/operator_overview.py new file mode 100644 index 00000000..849048a9 --- /dev/null +++ b/knext/schema/rest/models/operator/operator_overview.py @@ -0,0 +1,266 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class OperatorOverview(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "id": "str", + "name": "str", + "desc": "str", + "type": "str", + "lang_type": "str", + } + + attribute_map = { + "id": "id", + "name": "name", + "desc": "desc", + "type": "type", + "lang_type": "langType", + } + + def __init__( + self, + id=None, + name=None, + desc=None, + type=None, + lang_type=None, + local_vars_configuration=None, + ): # noqa: E501 + """OperatorOverview - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._id = None + self._name = None + self._desc = None + self._type = None + self._lang_type = None + self.discriminator = None + + self.id = id + self.name = name + self.desc = desc + self.type = type + self.lang_type = lang_type + + @property + def id(self): + """Gets the id of this OperatorOverview. # noqa: E501 + + + :return: The id of this OperatorOverview. # noqa: E501 + :rtype: str + """ + return self._id + + @id.setter + def id(self, id): + """Sets the id of this OperatorOverview. + + + :param id: The id of this OperatorOverview. # noqa: E501 + :type: str + """ + + self._id = id + + @property + def name(self): + """Gets the name of this OperatorOverview. # noqa: E501 + + + :return: The name of this OperatorOverview. # noqa: E501 + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this OperatorOverview. + + + :param name: The name of this OperatorOverview. # noqa: E501 + :type: str + """ + + self._name = name + + @property + def desc(self): + """Gets the desc of this OperatorOverview. # noqa: E501 + + + :return: The desc of this OperatorOverview. # noqa: E501 + :rtype: str + """ + return self._desc + + @desc.setter + def desc(self, desc): + """Sets the desc of this OperatorOverview. + + + :param desc: The desc of this OperatorOverview. # noqa: E501 + :type: str + """ + + self._desc = desc + + @property + def type(self): + """Gets the type of this OperatorOverview. # noqa: E501 + + + :return: The type of this OperatorOverview. # noqa: E501 + :rtype: str + """ + return self._type + + @type.setter + def type(self, type): + """Sets the type of this OperatorOverview. + + + :param type: The type of this OperatorOverview. # noqa: E501 + :type: str + """ + allowed_values = [ + None, + "KNOWLEDGE_EXTRACT", + "ENTITY_LINK", + "PROPERTY_NORMALIZE", + "ENTITY_FUSION", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and type not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `type` ({0}), must be one of {1}".format( # noqa: E501 + type, allowed_values + ) + ) + + self._type = type + + @property + def lang_type(self): + """Gets the lang_type of this OperatorOverview. # noqa: E501 + + + :return: The lang_type of this OperatorOverview. # noqa: E501 + :rtype: str + """ + return self._lang_type + + @lang_type.setter + def lang_type(self, lang_type): + """Sets the lang_type of this OperatorOverview. + + + :param lang_type: The lang_type of this OperatorOverview. # noqa: E501 + :type: str + """ + allowed_values = [None, "PYTHON", "JAVA"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and lang_type not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `lang_type` ({0}), must be one of {1}".format( # noqa: E501 + lang_type, allowed_values + ) + ) + + self._lang_type = lang_type + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, OperatorOverview): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, OperatorOverview): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/operator/operator_version.py b/knext/schema/rest/models/operator/operator_version.py new file mode 100644 index 00000000..275ff32e --- /dev/null +++ b/knext/schema/rest/models/operator/operator_version.py @@ -0,0 +1,238 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class OperatorVersion(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "overview_id": "int", + "main_class": "str", + "file_path": "str", + "version": "int", + } + + attribute_map = { + "overview_id": "overviewId", + "main_class": "mainClass", + "file_path": "filePath", + "version": "version", + } + + def __init__( + self, + overview_id=None, + main_class=None, + file_path=None, + version=None, + local_vars_configuration=None, + ): # noqa: E501 + """OperatorVersion - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._overview_id = None + self._main_class = None + self._file_path = None + self._version = None + self.discriminator = None + + self.overview_id = overview_id + self.main_class = main_class + self.file_path = file_path + self.version = version + + @property + def overview_id(self): + """Gets the overview_id of this OperatorVersion. # noqa: E501 + + + :return: The overview_id of this OperatorVersion. # noqa: E501 + :rtype: int + """ + return self._overview_id + + @overview_id.setter + def overview_id(self, overview_id): + """Sets the overview_id of this OperatorVersion. + + + :param overview_id: The overview_id of this OperatorVersion. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and overview_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `overview_id`, must not be `None`" + ) # noqa: E501 + + self._overview_id = overview_id + + @property + def main_class(self): + """Gets the main_class of this OperatorVersion. # noqa: E501 + + + :return: The main_class of this OperatorVersion. # noqa: E501 + :rtype: str + """ + return self._main_class + + @main_class.setter + def main_class(self, main_class): + """Sets the main_class of this OperatorVersion. + + + :param main_class: The main_class of this OperatorVersion. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and main_class is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `main_class`, must not be `None`" + ) # noqa: E501 + + self._main_class = main_class + + @property + def file_path(self): + """Gets the file_path of this OperatorVersion. # noqa: E501 + + + :return: The file_path of this OperatorVersion. # noqa: E501 + :rtype: str + """ + return self._file_path + + @file_path.setter + def file_path(self, file_path): + """Sets the file_path of this OperatorVersion. + + + :param file_path: The file_path of this OperatorVersion. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and file_path is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `file_path`, must not be `None`" + ) # noqa: E501 + + self._file_path = file_path + + @property + def version(self): + """Gets the version of this OperatorVersion. # noqa: E501 + + + :return: The version of this OperatorVersion. # noqa: E501 + :rtype: int + """ + return self._version + + @version.setter + def version(self, version): + """Sets the version of this OperatorVersion. + + + :param version: The version of this OperatorVersion. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and version is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `version`, must not be `None`" + ) # noqa: E501 + + self._version = version + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, OperatorVersion): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, OperatorVersion): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/operator/operator_version_request.py b/knext/schema/rest/models/operator/operator_version_request.py new file mode 100644 index 00000000..ebe521ab --- /dev/null +++ b/knext/schema/rest/models/operator/operator_version_request.py @@ -0,0 +1,165 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class OperatorVersionRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"project_id": "int", "operator_id": "int"} + + attribute_map = {"project_id": "projectId", "operator_id": "operatorId"} + + def __init__( + self, project_id=None, operator_id=None, local_vars_configuration=None + ): # noqa: E501 + """OperatorVersionRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._operator_id = None + self.discriminator = None + + self.project_id = project_id + self.operator_id = operator_id + + @property + def project_id(self): + """Gets the project_id of this OperatorVersionRequest. # noqa: E501 + + + :return: The project_id of this OperatorVersionRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this OperatorVersionRequest. + + + :param project_id: The project_id of this OperatorVersionRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def operator_id(self): + """Gets the operator_id of this OperatorVersionRequest. # noqa: E501 + + + :return: The operator_id of this OperatorVersionRequest. # noqa: E501 + :rtype: int + """ + return self._operator_id + + @operator_id.setter + def operator_id(self, operator_id): + """Sets the operator_id of this OperatorVersionRequest. + + + :param operator_id: The operator_id of this OperatorVersionRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and operator_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `operator_id`, must not be `None`" + ) # noqa: E501 + + self._operator_id = operator_id + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, OperatorVersionRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, OperatorVersionRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/operator/operator_version_response.py b/knext/schema/rest/models/operator/operator_version_response.py new file mode 100644 index 00000000..26c1d0d6 --- /dev/null +++ b/knext/schema/rest/models/operator/operator_version_response.py @@ -0,0 +1,167 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class OperatorVersionResponse(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"operator_name": "str", "latest_version": "str"} + + attribute_map = {"operator_name": "operatorName", "latest_version": "latestVersion"} + + def __init__( + self, operator_name=None, latest_version=None, local_vars_configuration=None + ): # noqa: E501 + """OperatorVersionResponse - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._operator_name = None + self._latest_version = None + self.discriminator = None + + self.operator_name = operator_name + self.latest_version = latest_version + + @property + def operator_name(self): + """Gets the operator_name of this OperatorVersionResponse. # noqa: E501 + + + :return: The operator_name of this OperatorVersionResponse. # noqa: E501 + :rtype: str + """ + return self._operator_name + + @operator_name.setter + def operator_name(self, operator_name): + """Sets the operator_name of this OperatorVersionResponse. + + + :param operator_name: The operator_name of this OperatorVersionResponse. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and operator_name is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `operator_name`, must not be `None`" + ) # noqa: E501 + + self._operator_name = operator_name + + @property + def latest_version(self): + """Gets the latest_version of this OperatorVersionResponse. # noqa: E501 + + + :return: The latest_version of this OperatorVersionResponse. # noqa: E501 + :rtype: str + """ + return self._latest_version + + @latest_version.setter + def latest_version(self, latest_version): + """Sets the latest_version of this OperatorVersionResponse. + + + :param latest_version: The latest_version of this OperatorVersionResponse. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and latest_version is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `latest_version`, must not be `None`" + ) # noqa: E501 + + self._latest_version = latest_version + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, OperatorVersionResponse): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, OperatorVersionResponse): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/predicate/__init__.py b/knext/schema/rest/models/predicate/__init__.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/schema/rest/models/predicate/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/schema/rest/models/predicate/mounted_concept_config.py b/knext/schema/rest/models/predicate/mounted_concept_config.py new file mode 100644 index 00000000..fd2ecbb6 --- /dev/null +++ b/knext/schema/rest/models/predicate/mounted_concept_config.py @@ -0,0 +1,155 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class MountedConceptConfig(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"concept_branch": "str", "concept_layer": "str"} + + attribute_map = {"concept_branch": "conceptBranch", "concept_layer": "conceptLayer"} + + def __init__( + self, concept_branch=None, concept_layer=None, local_vars_configuration=None + ): # noqa: E501 + """MountedConceptConfig - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._concept_branch = None + self._concept_layer = None + self.discriminator = None + + if concept_branch is not None: + self.concept_branch = concept_branch + if concept_layer is not None: + self.concept_layer = concept_layer + + @property + def concept_branch(self): + """Gets the concept_branch of this MountedConceptConfig. # noqa: E501 + + + :return: The concept_branch of this MountedConceptConfig. # noqa: E501 + :rtype: str + """ + return self._concept_branch + + @concept_branch.setter + def concept_branch(self, concept_branch): + """Sets the concept_branch of this MountedConceptConfig. + + + :param concept_branch: The concept_branch of this MountedConceptConfig. # noqa: E501 + :type: str + """ + + self._concept_branch = concept_branch + + @property + def concept_layer(self): + """Gets the concept_layer of this MountedConceptConfig. # noqa: E501 + + + :return: The concept_layer of this MountedConceptConfig. # noqa: E501 + :rtype: str + """ + return self._concept_layer + + @concept_layer.setter + def concept_layer(self, concept_layer): + """Sets the concept_layer of this MountedConceptConfig. + + + :param concept_layer: The concept_layer of this MountedConceptConfig. # noqa: E501 + :type: str + """ + + self._concept_layer = concept_layer + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, MountedConceptConfig): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, MountedConceptConfig): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/predicate/property.py b/knext/schema/rest/models/predicate/property.py new file mode 100644 index 00000000..1d20e9b0 --- /dev/null +++ b/knext/schema/rest/models/predicate/property.py @@ -0,0 +1,363 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class Property(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "basic_info": "SubPropertyBasicInfo", + "subject_type_ref": "SpgTypeRef", + "object_type_ref": "SpgTypeRef", + "inherited": "bool", + "advanced_config": "PropertyAdvancedConfig", + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + } + + attribute_map = { + "basic_info": "basicInfo", + "subject_type_ref": "subjectTypeRef", + "object_type_ref": "objectTypeRef", + "inherited": "inherited", + "advanced_config": "advancedConfig", + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + } + + def __init__( + self, + basic_info=None, + subject_type_ref=None, + object_type_ref=None, + inherited=None, + advanced_config=None, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + local_vars_configuration=None, + ): # noqa: E501 + """Property - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._basic_info = None + self._subject_type_ref = None + self._object_type_ref = None + self._inherited = None + self._advanced_config = None + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self.discriminator = None + + if basic_info is not None: + self.basic_info = basic_info + if subject_type_ref is not None: + self.subject_type_ref = subject_type_ref + if object_type_ref is not None: + self.object_type_ref = object_type_ref + if inherited is not None: + self.inherited = inherited + if advanced_config is not None: + self.advanced_config = advanced_config + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + + @property + def basic_info(self): + """Gets the basic_info of this Property. # noqa: E501 + + + :return: The basic_info of this Property. # noqa: E501 + :rtype: SubPropertyBasicInfo + """ + return self._basic_info + + @basic_info.setter + def basic_info(self, basic_info): + """Sets the basic_info of this Property. + + + :param basic_info: The basic_info of this Property. # noqa: E501 + :type: SubPropertyBasicInfo + """ + + self._basic_info = basic_info + + @property + def subject_type_ref(self): + """Gets the subject_type_ref of this Property. # noqa: E501 + + + :return: The subject_type_ref of this Property. # noqa: E501 + :rtype: SpgTypeRef + """ + return self._subject_type_ref + + @subject_type_ref.setter + def subject_type_ref(self, subject_type_ref): + """Sets the subject_type_ref of this Property. + + + :param subject_type_ref: The subject_type_ref of this Property. # noqa: E501 + :type: SpgTypeRef + """ + + self._subject_type_ref = subject_type_ref + + @property + def object_type_ref(self): + """Gets the object_type_ref of this Property. # noqa: E501 + + + :return: The object_type_ref of this Property. # noqa: E501 + :rtype: SpgTypeRef + """ + return self._object_type_ref + + @object_type_ref.setter + def object_type_ref(self, object_type_ref): + """Sets the object_type_ref of this Property. + + + :param object_type_ref: The object_type_ref of this Property. # noqa: E501 + :type: SpgTypeRef + """ + + self._object_type_ref = object_type_ref + + @property + def inherited(self): + """Gets the inherited of this Property. # noqa: E501 + + + :return: The inherited of this Property. # noqa: E501 + :rtype: bool + """ + return self._inherited + + @inherited.setter + def inherited(self, inherited): + """Sets the inherited of this Property. + + + :param inherited: The inherited of this Property. # noqa: E501 + :type: bool + """ + + self._inherited = inherited + + @property + def advanced_config(self): + """Gets the advanced_config of this Property. # noqa: E501 + + + :return: The advanced_config of this Property. # noqa: E501 + :rtype: PropertyAdvancedConfig + """ + return self._advanced_config + + @advanced_config.setter + def advanced_config(self, advanced_config): + """Sets the advanced_config of this Property. + + + :param advanced_config: The advanced_config of this Property. # noqa: E501 + :type: PropertyAdvancedConfig + """ + + self._advanced_config = advanced_config + + @property + def project_id(self): + """Gets the project_id of this Property. # noqa: E501 + + + :return: The project_id of this Property. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this Property. + + + :param project_id: The project_id of this Property. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this Property. # noqa: E501 + + + :return: The ontology_id of this Property. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this Property. + + + :param ontology_id: The ontology_id of this Property. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this Property. # noqa: E501 + + + :return: The alter_operation of this Property. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this Property. + + + :param alter_operation: The alter_operation of this Property. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this Property. # noqa: E501 + + + :return: The ext_info of this Property. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this Property. + + + :param ext_info: The ext_info of this Property. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, Property): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, Property): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/predicate/property_advanced_config.py b/knext/schema/rest/models/predicate/property_advanced_config.py new file mode 100644 index 00000000..ea03ad66 --- /dev/null +++ b/knext/schema/rest/models/predicate/property_advanced_config.py @@ -0,0 +1,336 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class PropertyAdvancedConfig(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "multi_version_config": "MultiVersionConfig", + "mounted_concept_config": "MountedConceptConfig", + "property_group": "str", + "constraint": "Constraint", + "sub_properties": "list[SubProperty]", + "semantics": "list[PredicateSemantic]", + "logical_rule": "LogicalRule", + "index_type": "str", + } + + attribute_map = { + "multi_version_config": "multiVersionConfig", + "mounted_concept_config": "MountedConceptConfig", + "property_group": "propertyGroup", + "constraint": "constraint", + "sub_properties": "subProperties", + "semantics": "semantics", + "logical_rule": "logicalRule", + "index_type": "indexType", + } + + def __init__( + self, + multi_version_config=None, + mounted_concept_config=None, + property_group=None, + constraint=None, + sub_properties=None, + semantics=None, + logical_rule=None, + index_type=None, + local_vars_configuration=None, + ): # noqa: E501 + """PropertyAdvancedConfig - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._multi_version_config = None + self._mounted_concept_config = None + self._property_group = None + self._constraint = None + self._sub_properties = None + self._semantics = None + self._logical_rule = None + self._index_type = None + self.discriminator = None + + if multi_version_config is not None: + self.multi_version_config = multi_version_config + if mounted_concept_config is not None: + self.mounted_concept_config = mounted_concept_config + if property_group is not None: + self.property_group = property_group + if constraint is not None: + self.constraint = constraint + if sub_properties is not None: + self.sub_properties = sub_properties + if semantics is not None: + self.semantics = semantics + if logical_rule is not None: + self.logical_rule = logical_rule + if index_type is not None: + self.index_type = index_type + + @property + def multi_version_config(self): + """Gets the multi_version_config of this PropertyAdvancedConfig. # noqa: E501 + + + :return: The multi_version_config of this PropertyAdvancedConfig. # noqa: E501 + :rtype: MultiVersionConfig + """ + return self._multi_version_config + + @multi_version_config.setter + def multi_version_config(self, multi_version_config): + """Sets the multi_version_config of this PropertyAdvancedConfig. + + + :param multi_version_config: The multi_version_config of this PropertyAdvancedConfig. # noqa: E501 + :type: MultiVersionConfig + """ + + self._multi_version_config = multi_version_config + + @property + def mounted_concept_config(self): + """Gets the mounted_concept_config of this PropertyAdvancedConfig. # noqa: E501 + + + :return: The mounted_concept_config of this PropertyAdvancedConfig. # noqa: E501 + :rtype: MountedConceptConfig + """ + return self._mounted_concept_config + + @mounted_concept_config.setter + def mounted_concept_config(self, mounted_concept_config): + """Sets the mounted_concept_config of this PropertyAdvancedConfig. + + + :param mounted_concept_config: The mounted_concept_config of this PropertyAdvancedConfig. # noqa: E501 + :type: MountedConceptConfig + """ + + self._mounted_concept_config = mounted_concept_config + + @property + def property_group(self): + """Gets the property_group of this PropertyAdvancedConfig. # noqa: E501 + + + :return: The property_group of this PropertyAdvancedConfig. # noqa: E501 + :rtype: str + """ + return self._property_group + + @property_group.setter + def property_group(self, property_group): + """Sets the property_group of this PropertyAdvancedConfig. + + + :param property_group: The property_group of this PropertyAdvancedConfig. # noqa: E501 + :type: str + """ + allowed_values = ["TIME", "SUBJECT", "OBJECT", "LOC"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and property_group not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `property_group` ({0}), must be one of {1}".format( # noqa: E501 + property_group, allowed_values + ) + ) + + self._property_group = property_group + + @property + def constraint(self): + """Gets the constraint of this PropertyAdvancedConfig. # noqa: E501 + + + :return: The constraint of this PropertyAdvancedConfig. # noqa: E501 + :rtype: Constraint + """ + return self._constraint + + @constraint.setter + def constraint(self, constraint): + """Sets the constraint of this PropertyAdvancedConfig. + + + :param constraint: The constraint of this PropertyAdvancedConfig. # noqa: E501 + :type: Constraint + """ + + self._constraint = constraint + + @property + def sub_properties(self): + """Gets the sub_properties of this PropertyAdvancedConfig. # noqa: E501 + + + :return: The sub_properties of this PropertyAdvancedConfig. # noqa: E501 + :rtype: list[SubProperty] + """ + return self._sub_properties + + @sub_properties.setter + def sub_properties(self, sub_properties): + """Sets the sub_properties of this PropertyAdvancedConfig. + + + :param sub_properties: The sub_properties of this PropertyAdvancedConfig. # noqa: E501 + :type: list[SubProperty] + """ + + self._sub_properties = sub_properties + + @property + def semantics(self): + """Gets the semantics of this PropertyAdvancedConfig. # noqa: E501 + + + :return: The semantics of this PropertyAdvancedConfig. # noqa: E501 + :rtype: list[PredicateSemantic] + """ + return self._semantics + + @semantics.setter + def semantics(self, semantics): + """Sets the semantics of this PropertyAdvancedConfig. + + + :param semantics: The semantics of this PropertyAdvancedConfig. # noqa: E501 + :type: list[PredicateSemantic] + """ + + self._semantics = semantics + + @property + def logical_rule(self): + """Gets the logical_rule of this PropertyAdvancedConfig. # noqa: E501 + + + :return: The logical_rule of this PropertyAdvancedConfig. # noqa: E501 + :rtype: LogicalRule + """ + return self._logical_rule + + @logical_rule.setter + def logical_rule(self, logical_rule): + """Sets the logical_rule of this PropertyAdvancedConfig. + + + :param logical_rule: The logical_rule of this PropertyAdvancedConfig. # noqa: E501 + :type: LogicalRule + """ + + self._logical_rule = logical_rule + + @property + def index_type(self): + """Gets the index_type of this PropertyAdvancedConfig. # noqa: E501 + + + :return: The index_type of this PropertyAdvancedConfig. # noqa: E501 + :rtype: str + """ + return self._index_type + + @index_type.setter + def index_type(self, index_type): + """Sets the index_type of this PropertyAdvancedConfig. + + + :param index_type: The logical_rule of this PropertyAdvancedConfig. # noqa: E501 + :type: str + """ + + self._index_type = index_type + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, PropertyAdvancedConfig): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, PropertyAdvancedConfig): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/predicate/property_ref.py b/knext/schema/rest/models/predicate/property_ref.py new file mode 100644 index 00000000..ada99917 --- /dev/null +++ b/knext/schema/rest/models/predicate/property_ref.py @@ -0,0 +1,380 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class PropertyRef(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "subject_type_ref": "SpgTypeRef", + "basic_info": "PropertyRefBasicInfo", + "object_type_ref": "SpgTypeRef", + "advanced_config": "PropertyAdvancedConfig", + "ontology_enum": "str", + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + } + + attribute_map = { + "subject_type_ref": "subjectTypeRef", + "basic_info": "basicInfo", + "object_type_ref": "objectTypeRef", + "advanced_config": "advancedConfig", + "ontology_enum": "ontologyEnum", + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + } + + def __init__( + self, + subject_type_ref=None, + basic_info=None, + object_type_ref=None, + advanced_config=None, + ontology_enum=None, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + local_vars_configuration=None, + ): # noqa: E501 + """PropertyRef - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._subject_type_ref = None + self._basic_info = None + self._object_type_ref = None + self._advanced_config = None + self._ontology_enum = None + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self.discriminator = None + + if subject_type_ref is not None: + self.subject_type_ref = subject_type_ref + if basic_info is not None: + self.basic_info = basic_info + if object_type_ref is not None: + self.object_type_ref = object_type_ref + if advanced_config is not None: + self.advanced_config = advanced_config + if ontology_enum is not None: + self.ontology_enum = ontology_enum + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + + @property + def subject_type_ref(self): + """Gets the subject_type_ref of this PropertyRef. # noqa: E501 + + + :return: The subject_type_ref of this PropertyRef. # noqa: E501 + :rtype: SpgTypeRef + """ + return self._subject_type_ref + + @subject_type_ref.setter + def subject_type_ref(self, subject_type_ref): + """Sets the subject_type_ref of this PropertyRef. + + + :param subject_type_ref: The subject_type_ref of this PropertyRef. # noqa: E501 + :type: SpgTypeRef + """ + + self._subject_type_ref = subject_type_ref + + @property + def basic_info(self): + """Gets the basic_info of this PropertyRef. # noqa: E501 + + + :return: The basic_info of this PropertyRef. # noqa: E501 + :rtype: PropertyRefBasicInfo + """ + return self._basic_info + + @basic_info.setter + def basic_info(self, basic_info): + """Sets the basic_info of this PropertyRef. + + + :param basic_info: The basic_info of this PropertyRef. # noqa: E501 + :type: PropertyRefBasicInfo + """ + + self._basic_info = basic_info + + @property + def object_type_ref(self): + """Gets the object_type_ref of this PropertyRef. # noqa: E501 + + + :return: The object_type_ref of this PropertyRef. # noqa: E501 + :rtype: SpgTypeRef + """ + return self._object_type_ref + + @object_type_ref.setter + def object_type_ref(self, object_type_ref): + """Sets the object_type_ref of this PropertyRef. + + + :param object_type_ref: The object_type_ref of this PropertyRef. # noqa: E501 + :type: SpgTypeRef + """ + + self._object_type_ref = object_type_ref + + @property + def advanced_config(self): + """Gets the advanced_config of this PropertyRef. # noqa: E501 + + + :return: The advanced_config of this PropertyRef. # noqa: E501 + :rtype: PropertyAdvancedConfig + """ + return self._advanced_config + + @advanced_config.setter + def advanced_config(self, advanced_config): + """Sets the advanced_config of this PropertyRef. + + + :param advanced_config: The advanced_config of this PropertyRef. # noqa: E501 + :type: PropertyAdvancedConfig + """ + + self._advanced_config = advanced_config + + @property + def ontology_enum(self): + """Gets the ontology_enum of this PropertyRef. # noqa: E501 + + + :return: The ontology_enum of this PropertyRef. # noqa: E501 + :rtype: str + """ + return self._ontology_enum + + @ontology_enum.setter + def ontology_enum(self, ontology_enum): + """Sets the ontology_enum of this PropertyRef. + + + :param ontology_enum: The ontology_enum of this PropertyRef. # noqa: E501 + :type: str + """ + allowed_values = [ + None, + "TYPE", + "PROPERTY", + "RELATION", + "SUB_PROPERTY", + "CONCEPT", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and ontology_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `ontology_enum` ({0}), must be one of {1}".format( # noqa: E501 + ontology_enum, allowed_values + ) + ) + + self._ontology_enum = ontology_enum + + @property + def project_id(self): + """Gets the project_id of this PropertyRef. # noqa: E501 + + + :return: The project_id of this PropertyRef. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this PropertyRef. + + + :param project_id: The project_id of this PropertyRef. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this PropertyRef. # noqa: E501 + + + :return: The ontology_id of this PropertyRef. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this PropertyRef. + + + :param ontology_id: The ontology_id of this PropertyRef. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this PropertyRef. # noqa: E501 + + + :return: The alter_operation of this PropertyRef. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this PropertyRef. + + + :param alter_operation: The alter_operation of this PropertyRef. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this PropertyRef. # noqa: E501 + + + :return: The ext_info of this PropertyRef. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this PropertyRef. + + + :param ext_info: The ext_info of this PropertyRef. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, PropertyRef): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, PropertyRef): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/predicate/property_ref_basic_info.py b/knext/schema/rest/models/predicate/property_ref_basic_info.py new file mode 100644 index 00000000..8085a4b5 --- /dev/null +++ b/knext/schema/rest/models/predicate/property_ref_basic_info.py @@ -0,0 +1,223 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class PropertyRefBasicInfo(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "name": "PredicateIdentifier", + "name_zh": "str", + "desc": "str", + "creator": "str", + } + + attribute_map = { + "name": "name", + "name_zh": "nameZh", + "desc": "desc", + "creator": "creator", + } + + def __init__( + self, + name=None, + name_zh=None, + desc=None, + creator=None, + local_vars_configuration=None, + ): # noqa: E501 + """PropertyRefBasicInfo - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._name = None + self._name_zh = None + self._desc = None + self._creator = None + self.discriminator = None + + self.name = name + if name_zh is not None: + self.name_zh = name_zh + if desc is not None: + self.desc = desc + if creator is not None: + self.creator = creator + + @property + def name(self): + """Gets the name of this PropertyRefBasicInfo. # noqa: E501 + + + :return: The name of this PropertyRefBasicInfo. # noqa: E501 + :rtype: PredicateIdentifier + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this PropertyRefBasicInfo. + + + :param name: The name of this PropertyRefBasicInfo. # noqa: E501 + :type: PredicateIdentifier + """ + if ( + self.local_vars_configuration.client_side_validation and name is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `name`, must not be `None`" + ) # noqa: E501 + + self._name = name + + @property + def name_zh(self): + """Gets the name_zh of this PropertyRefBasicInfo. # noqa: E501 + + + :return: The name_zh of this PropertyRefBasicInfo. # noqa: E501 + :rtype: str + """ + return self._name_zh + + @name_zh.setter + def name_zh(self, name_zh): + """Sets the name_zh of this PropertyRefBasicInfo. + + + :param name_zh: The name_zh of this PropertyRefBasicInfo. # noqa: E501 + :type: str + """ + + self._name_zh = name_zh + + @property + def desc(self): + """Gets the desc of this PropertyRefBasicInfo. # noqa: E501 + + + :return: The desc of this PropertyRefBasicInfo. # noqa: E501 + :rtype: str + """ + return self._desc + + @desc.setter + def desc(self, desc): + """Sets the desc of this PropertyRefBasicInfo. + + + :param desc: The desc of this PropertyRefBasicInfo. # noqa: E501 + :type: str + """ + + self._desc = desc + + @property + def creator(self): + """Gets the creator of this PropertyRefBasicInfo. # noqa: E501 + + + :return: The creator of this PropertyRefBasicInfo. # noqa: E501 + :rtype: str + """ + return self._creator + + @creator.setter + def creator(self, creator): + """Sets the creator of this PropertyRefBasicInfo. + + + :param creator: The creator of this PropertyRefBasicInfo. # noqa: E501 + :type: str + """ + + self._creator = creator + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, PropertyRefBasicInfo): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, PropertyRefBasicInfo): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/predicate/relation.py b/knext/schema/rest/models/predicate/relation.py new file mode 100644 index 00000000..7d1de514 --- /dev/null +++ b/knext/schema/rest/models/predicate/relation.py @@ -0,0 +1,390 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class Relation(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "basic_info": "SubPropertyBasicInfo", + "subject_type_ref": "SpgTypeRef", + "object_type_ref": "SpgTypeRef", + "inherited": "bool", + "advanced_config": "PropertyAdvancedConfig", + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + "is_dynamic": "bool", + } + + attribute_map = { + "basic_info": "basicInfo", + "subject_type_ref": "subjectTypeRef", + "object_type_ref": "objectTypeRef", + "inherited": "inherited", + "advanced_config": "advancedConfig", + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + "is_dynamic": "isDynamic", + } + + def __init__( + self, + basic_info=None, + subject_type_ref=None, + object_type_ref=None, + inherited=None, + advanced_config=None, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + is_dynamic=None, + local_vars_configuration=None, + ): # noqa: E501 + """Relation - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._basic_info = None + self._subject_type_ref = None + self._object_type_ref = None + self._inherited = None + self._advanced_config = None + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self._is_dynamic = None + self.discriminator = None + + if basic_info is not None: + self.basic_info = basic_info + if subject_type_ref is not None: + self.subject_type_ref = subject_type_ref + if object_type_ref is not None: + self.object_type_ref = object_type_ref + if inherited is not None: + self.inherited = inherited + if advanced_config is not None: + self.advanced_config = advanced_config + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + if is_dynamic is not None: + self.is_dynamic = is_dynamic + + @property + def basic_info(self): + """Gets the basic_info of this Relation. # noqa: E501 + + + :return: The basic_info of this Relation. # noqa: E501 + :rtype: SubPropertyBasicInfo + """ + return self._basic_info + + @basic_info.setter + def basic_info(self, basic_info): + """Sets the basic_info of this Relation. + + + :param basic_info: The basic_info of this Relation. # noqa: E501 + :type: SubPropertyBasicInfo + """ + + self._basic_info = basic_info + + @property + def subject_type_ref(self): + """Gets the subject_type_ref of this Relation. # noqa: E501 + + + :return: The subject_type_ref of this Relation. # noqa: E501 + :rtype: SpgTypeRef + """ + return self._subject_type_ref + + @subject_type_ref.setter + def subject_type_ref(self, subject_type_ref): + """Sets the subject_type_ref of this Relation. + + + :param subject_type_ref: The subject_type_ref of this Relation. # noqa: E501 + :type: SpgTypeRef + """ + + self._subject_type_ref = subject_type_ref + + @property + def object_type_ref(self): + """Gets the object_type_ref of this Relation. # noqa: E501 + + + :return: The object_type_ref of this Relation. # noqa: E501 + :rtype: SpgTypeRef + """ + return self._object_type_ref + + @object_type_ref.setter + def object_type_ref(self, object_type_ref): + """Sets the object_type_ref of this Relation. + + + :param object_type_ref: The object_type_ref of this Relation. # noqa: E501 + :type: SpgTypeRef + """ + + self._object_type_ref = object_type_ref + + @property + def inherited(self): + """Gets the inherited of this Relation. # noqa: E501 + + + :return: The inherited of this Relation. # noqa: E501 + :rtype: bool + """ + return self._inherited + + @inherited.setter + def inherited(self, inherited): + """Sets the inherited of this Relation. + + + :param inherited: The inherited of this Relation. # noqa: E501 + :type: bool + """ + + self._inherited = inherited + + @property + def advanced_config(self): + """Gets the advanced_config of this Relation. # noqa: E501 + + + :return: The advanced_config of this Relation. # noqa: E501 + :rtype: PropertyAdvancedConfig + """ + return self._advanced_config + + @advanced_config.setter + def advanced_config(self, advanced_config): + """Sets the advanced_config of this Relation. + + + :param advanced_config: The advanced_config of this Relation. # noqa: E501 + :type: PropertyAdvancedConfig + """ + + self._advanced_config = advanced_config + + @property + def project_id(self): + """Gets the project_id of this Relation. # noqa: E501 + + + :return: The project_id of this Relation. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this Relation. + + + :param project_id: The project_id of this Relation. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this Relation. # noqa: E501 + + + :return: The ontology_id of this Relation. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this Relation. + + + :param ontology_id: The ontology_id of this Relation. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this Relation. # noqa: E501 + + + :return: The alter_operation of this Relation. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this Relation. + + + :param alter_operation: The alter_operation of this Relation. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this Relation. # noqa: E501 + + + :return: The ext_info of this Relation. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this Relation. + + + :param ext_info: The ext_info of this Relation. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + @property + def is_dynamic(self): + """Gets the is_dynamic of this Relation. # noqa: E501 + + + :return: The is_dynamic of this Relation. # noqa: E501 + :rtype: bool + """ + return self._is_dynamic + + @is_dynamic.setter + def is_dynamic(self, is_dynamic): + """Sets the is_dynamic of this Relation. + + + :param is_dynamic: The is_dynamic of this Relation. # noqa: E501 + :type: bool + """ + + self._is_dynamic = is_dynamic + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, Relation): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, Relation): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/predicate/sub_property.py b/knext/schema/rest/models/predicate/sub_property.py new file mode 100644 index 00000000..edbe5185 --- /dev/null +++ b/knext/schema/rest/models/predicate/sub_property.py @@ -0,0 +1,336 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class SubProperty(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "basic_info": "SubPropertyBasicInfo", + "subject_type_ref": "PropertyRef", + "object_type_ref": "SpgTypeRef", + "advanced_config": "PropertyAdvancedConfig", + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + } + + attribute_map = { + "basic_info": "basicInfo", + "subject_type_ref": "subjectTypeRef", + "object_type_ref": "objectTypeRef", + "advanced_config": "advancedConfig", + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + } + + def __init__( + self, + basic_info=None, + subject_type_ref=None, + object_type_ref=None, + advanced_config=None, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + local_vars_configuration=None, + ): # noqa: E501 + """SubProperty - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._basic_info = None + self._subject_type_ref = None + self._object_type_ref = None + self._advanced_config = None + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self.discriminator = None + + if basic_info is not None: + self.basic_info = basic_info + if subject_type_ref is not None: + self.subject_type_ref = subject_type_ref + if object_type_ref is not None: + self.object_type_ref = object_type_ref + if advanced_config is not None: + self.advanced_config = advanced_config + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + + @property + def basic_info(self): + """Gets the basic_info of this SubProperty. # noqa: E501 + + + :return: The basic_info of this SubProperty. # noqa: E501 + :rtype: SubPropertyBasicInfo + """ + return self._basic_info + + @basic_info.setter + def basic_info(self, basic_info): + """Sets the basic_info of this SubProperty. + + + :param basic_info: The basic_info of this SubProperty. # noqa: E501 + :type: SubPropertyBasicInfo + """ + + self._basic_info = basic_info + + @property + def subject_type_ref(self): + """Gets the subject_type_ref of this SubProperty. # noqa: E501 + + + :return: The subject_type_ref of this SubProperty. # noqa: E501 + :rtype: PropertyRef + """ + return self._subject_type_ref + + @subject_type_ref.setter + def subject_type_ref(self, subject_type_ref): + """Sets the subject_type_ref of this SubProperty. + + + :param subject_type_ref: The subject_type_ref of this SubProperty. # noqa: E501 + :type: PropertyRef + """ + + self._subject_type_ref = subject_type_ref + + @property + def object_type_ref(self): + """Gets the object_type_ref of this SubProperty. # noqa: E501 + + + :return: The object_type_ref of this SubProperty. # noqa: E501 + :rtype: SpgTypeRef + """ + return self._object_type_ref + + @object_type_ref.setter + def object_type_ref(self, object_type_ref): + """Sets the object_type_ref of this SubProperty. + + + :param object_type_ref: The object_type_ref of this SubProperty. # noqa: E501 + :type: SpgTypeRef + """ + + self._object_type_ref = object_type_ref + + @property + def advanced_config(self): + """Gets the advanced_config of this SubProperty. # noqa: E501 + + + :return: The advanced_config of this SubProperty. # noqa: E501 + :rtype: PropertyAdvancedConfig + """ + return self._advanced_config + + @advanced_config.setter + def advanced_config(self, advanced_config): + """Sets the advanced_config of this SubProperty. + + + :param advanced_config: The advanced_config of this SubProperty. # noqa: E501 + :type: PropertyAdvancedConfig + """ + + self._advanced_config = advanced_config + + @property + def project_id(self): + """Gets the project_id of this SubProperty. # noqa: E501 + + + :return: The project_id of this SubProperty. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this SubProperty. + + + :param project_id: The project_id of this SubProperty. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this SubProperty. # noqa: E501 + + + :return: The ontology_id of this SubProperty. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this SubProperty. + + + :param ontology_id: The ontology_id of this SubProperty. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this SubProperty. # noqa: E501 + + + :return: The alter_operation of this SubProperty. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this SubProperty. + + + :param alter_operation: The alter_operation of this SubProperty. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this SubProperty. # noqa: E501 + + + :return: The ext_info of this SubProperty. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this SubProperty. + + + :param ext_info: The ext_info of this SubProperty. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, SubProperty): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, SubProperty): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/predicate/sub_property_basic_info.py b/knext/schema/rest/models/predicate/sub_property_basic_info.py new file mode 100644 index 00000000..fe79108b --- /dev/null +++ b/knext/schema/rest/models/predicate/sub_property_basic_info.py @@ -0,0 +1,218 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class SubPropertyBasicInfo(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "name": "PredicateIdentifier", + "name_zh": "str", + "desc": "str", + "creator": "str", + } + + attribute_map = { + "name": "name", + "name_zh": "nameZh", + "desc": "desc", + "creator": "creator", + } + + def __init__( + self, + name=None, + name_zh=None, + desc=None, + creator=None, + local_vars_configuration=None, + ): # noqa: E501 + """SubPropertyBasicInfo - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._name = None + self._name_zh = None + self._desc = None + self._creator = None + self.discriminator = None + + if name is not None: + self.name = name + if name_zh is not None: + self.name_zh = name_zh + if desc is not None: + self.desc = desc + if creator is not None: + self.creator = creator + + @property + def name(self): + """Gets the name of this SubPropertyBasicInfo. # noqa: E501 + + + :return: The name of this SubPropertyBasicInfo. # noqa: E501 + :rtype: PredicateIdentifier + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this SubPropertyBasicInfo. + + + :param name: The name of this SubPropertyBasicInfo. # noqa: E501 + :type: PredicateIdentifier + """ + + self._name = name + + @property + def name_zh(self): + """Gets the name_zh of this SubPropertyBasicInfo. # noqa: E501 + + + :return: The name_zh of this SubPropertyBasicInfo. # noqa: E501 + :rtype: str + """ + return self._name_zh + + @name_zh.setter + def name_zh(self, name_zh): + """Sets the name_zh of this SubPropertyBasicInfo. + + + :param name_zh: The name_zh of this SubPropertyBasicInfo. # noqa: E501 + :type: str + """ + + self._name_zh = name_zh + + @property + def desc(self): + """Gets the desc of this SubPropertyBasicInfo. # noqa: E501 + + + :return: The desc of this SubPropertyBasicInfo. # noqa: E501 + :rtype: str + """ + return self._desc + + @desc.setter + def desc(self, desc): + """Sets the desc of this SubPropertyBasicInfo. + + + :param desc: The desc of this SubPropertyBasicInfo. # noqa: E501 + :type: str + """ + + self._desc = desc + + @property + def creator(self): + """Gets the creator of this SubPropertyBasicInfo. # noqa: E501 + + + :return: The creator of this SubPropertyBasicInfo. # noqa: E501 + :rtype: str + """ + return self._creator + + @creator.setter + def creator(self, creator): + """Sets the creator of this SubPropertyBasicInfo. + + + :param creator: The creator of this SubPropertyBasicInfo. # noqa: E501 + :type: str + """ + + self._creator = creator + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, SubPropertyBasicInfo): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, SubPropertyBasicInfo): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/semantic/__init__.py b/knext/schema/rest/models/semantic/__init__.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/schema/rest/models/semantic/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/schema/rest/models/semantic/base_semantic.py b/knext/schema/rest/models/semantic/base_semantic.py new file mode 100644 index 00000000..3a6e86b9 --- /dev/null +++ b/knext/schema/rest/models/semantic/base_semantic.py @@ -0,0 +1,271 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class BaseSemantic(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "ontology_enum": "str", + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + } + + attribute_map = { + "ontology_enum": "ontologyEnum", + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + } + + def __init__( + self, + ontology_enum=None, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + local_vars_configuration=None, + ): # noqa: E501 + """BaseSemantic - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._ontology_enum = None + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self.discriminator = None + + self.ontology_enum = ontology_enum + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + + @property + def ontology_enum(self): + """Gets the ontology_enum of this BaseSemantic. # noqa: E501 + + + :return: The ontology_enum of this BaseSemantic. # noqa: E501 + :rtype: str + """ + return self._ontology_enum + + @ontology_enum.setter + def ontology_enum(self, ontology_enum): + """Sets the ontology_enum of this BaseSemantic. + + + :param ontology_enum: The ontology_enum of this BaseSemantic. # noqa: E501 + :type: str + """ + allowed_values = [ + None, + "TYPE", + "PROPERTY", + "RELATION", + "SUB_PROPERTY", + "CONCEPT", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and ontology_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `ontology_enum` ({0}), must be one of {1}".format( # noqa: E501 + ontology_enum, allowed_values + ) + ) + + self._ontology_enum = ontology_enum + + @property + def project_id(self): + """Gets the project_id of this BaseSemantic. # noqa: E501 + + + :return: The project_id of this BaseSemantic. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this BaseSemantic. + + + :param project_id: The project_id of this BaseSemantic. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this BaseSemantic. # noqa: E501 + + + :return: The ontology_id of this BaseSemantic. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this BaseSemantic. + + + :param ontology_id: The ontology_id of this BaseSemantic. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this BaseSemantic. # noqa: E501 + + + :return: The alter_operation of this BaseSemantic. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this BaseSemantic. + + + :param alter_operation: The alter_operation of this BaseSemantic. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this BaseSemantic. # noqa: E501 + + + :return: The ext_info of this BaseSemantic. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this BaseSemantic. + + + :param ext_info: The ext_info of this BaseSemantic. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, BaseSemantic): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, BaseSemantic): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/semantic/logical_rule.py b/knext/schema/rest/models/semantic/logical_rule.py new file mode 100644 index 00000000..e45dff22 --- /dev/null +++ b/knext/schema/rest/models/semantic/logical_rule.py @@ -0,0 +1,309 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class LogicalRule(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "code": "RuleCode", + "name": "str", + "version": "int", + "is_master": "bool", + "atatus": "str", + "content": "str", + "creator": "UserInfo", + } + + attribute_map = { + "code": "code", + "name": "name", + "version": "version", + "is_master": "isMaster", + "atatus": "atatus", + "content": "content", + "creator": "creator", + } + + def __init__( + self, + code=None, + name=None, + version=None, + is_master=None, + atatus=None, + content=None, + creator=None, + local_vars_configuration=None, + ): # noqa: E501 + """LogicalRule - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._code = None + self._name = None + self._version = None + self._is_master = None + self._atatus = None + self._content = None + self._creator = None + self.discriminator = None + + if code is not None: + self.code = code + if name is not None: + self.name = name + if version is not None: + self.version = version + if is_master is not None: + self.is_master = is_master + if atatus is not None: + self.atatus = atatus + if content is not None: + self.content = content + if creator is not None: + self.creator = creator + + @property + def code(self): + """Gets the code of this LogicalRule. # noqa: E501 + + + :return: The code of this LogicalRule. # noqa: E501 + :rtype: RuleCode + """ + return self._code + + @code.setter + def code(self, code): + """Sets the code of this LogicalRule. + + + :param code: The code of this LogicalRule. # noqa: E501 + :type: RuleCode + """ + + self._code = code + + @property + def name(self): + """Gets the name of this LogicalRule. # noqa: E501 + + + :return: The name of this LogicalRule. # noqa: E501 + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this LogicalRule. + + + :param name: The name of this LogicalRule. # noqa: E501 + :type: str + """ + + self._name = name + + @property + def version(self): + """Gets the version of this LogicalRule. # noqa: E501 + + + :return: The version of this LogicalRule. # noqa: E501 + :rtype: int + """ + return self._version + + @version.setter + def version(self, version): + """Sets the version of this LogicalRule. + + + :param version: The version of this LogicalRule. # noqa: E501 + :type: int + """ + + self._version = version + + @property + def is_master(self): + """Gets the is_master of this LogicalRule. # noqa: E501 + + + :return: The is_master of this LogicalRule. # noqa: E501 + :rtype: bool + """ + return self._is_master + + @is_master.setter + def is_master(self, is_master): + """Sets the is_master of this LogicalRule. + + + :param is_master: The is_master of this LogicalRule. # noqa: E501 + :type: bool + """ + + self._is_master = is_master + + @property + def atatus(self): + """Gets the atatus of this LogicalRule. # noqa: E501 + + + :return: The atatus of this LogicalRule. # noqa: E501 + :rtype: str + """ + return self._atatus + + @atatus.setter + def atatus(self, atatus): + """Sets the atatus of this LogicalRule. + + + :param atatus: The atatus of this LogicalRule. # noqa: E501 + :type: str + """ + allowed_values = ["INIT", "GRAY", "PROD", "OFF", "DEL"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and atatus not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `atatus` ({0}), must be one of {1}".format( # noqa: E501 + atatus, allowed_values + ) + ) + + self._atatus = atatus + + @property + def content(self): + """Gets the content of this LogicalRule. # noqa: E501 + + + :return: The content of this LogicalRule. # noqa: E501 + :rtype: str + """ + return self._content + + @content.setter + def content(self, content): + """Sets the content of this LogicalRule. + + + :param content: The content of this LogicalRule. # noqa: E501 + :type: str + """ + + self._content = content + + @property + def creator(self): + """Gets the creator of this LogicalRule. # noqa: E501 + + + :return: The creator of this LogicalRule. # noqa: E501 + :rtype: UserInfo + """ + return self._creator + + @creator.setter + def creator(self, creator): + """Sets the creator of this LogicalRule. + + + :param creator: The creator of this LogicalRule. # noqa: E501 + :type: UserInfo + """ + + self._creator = creator + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, LogicalRule): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, LogicalRule): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/semantic/predicate_semantic.py b/knext/schema/rest/models/semantic/predicate_semantic.py new file mode 100644 index 00000000..01c2d514 --- /dev/null +++ b/knext/schema/rest/models/semantic/predicate_semantic.py @@ -0,0 +1,352 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class PredicateSemantic(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "ontology_enum": "str", + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + "subject_type_ref": "PropertyRef", + "predicate": "PredicateIdentifier", + "object_type_ref": "PropertyRef", + } + + attribute_map = { + "ontology_enum": "ontologyEnum", + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + "subject_type_ref": "subjectTypeRef", + "predicate": "predicate", + "object_type_ref": "objectTypeRef", + } + + def __init__( + self, + ontology_enum=None, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + subject_type_ref=None, + predicate=None, + object_type_ref=None, + local_vars_configuration=None, + ): # noqa: E501 + """PredicateSemantic - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._ontology_enum = None + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self._subject_type_ref = None + self._predicate = None + self._object_type_ref = None + self.discriminator = None + + self.ontology_enum = ontology_enum + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + if subject_type_ref is not None: + self.subject_type_ref = subject_type_ref + if predicate is not None: + self.predicate = predicate + if object_type_ref is not None: + self.object_type_ref = object_type_ref + + @property + def ontology_enum(self): + """Gets the ontology_enum of this PredicateSemantic. # noqa: E501 + + + :return: The ontology_enum of this PredicateSemantic. # noqa: E501 + :rtype: str + """ + return self._ontology_enum + + @ontology_enum.setter + def ontology_enum(self, ontology_enum): + """Sets the ontology_enum of this PredicateSemantic. + + + :param ontology_enum: The ontology_enum of this PredicateSemantic. # noqa: E501 + :type: str + """ + allowed_values = [ + None, + "TYPE", + "PROPERTY", + "RELATION", + "SUB_PROPERTY", + "CONCEPT", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and ontology_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `ontology_enum` ({0}), must be one of {1}".format( # noqa: E501 + ontology_enum, allowed_values + ) + ) + + self._ontology_enum = ontology_enum + + @property + def project_id(self): + """Gets the project_id of this PredicateSemantic. # noqa: E501 + + + :return: The project_id of this PredicateSemantic. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this PredicateSemantic. + + + :param project_id: The project_id of this PredicateSemantic. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this PredicateSemantic. # noqa: E501 + + + :return: The ontology_id of this PredicateSemantic. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this PredicateSemantic. + + + :param ontology_id: The ontology_id of this PredicateSemantic. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this PredicateSemantic. # noqa: E501 + + + :return: The alter_operation of this PredicateSemantic. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this PredicateSemantic. + + + :param alter_operation: The alter_operation of this PredicateSemantic. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this PredicateSemantic. # noqa: E501 + + + :return: The ext_info of this PredicateSemantic. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this PredicateSemantic. + + + :param ext_info: The ext_info of this PredicateSemantic. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + @property + def subject_type_ref(self): + """Gets the subject_type_ref of this PredicateSemantic. # noqa: E501 + + + :return: The subject_type_ref of this PredicateSemantic. # noqa: E501 + :rtype: PropertyRef + """ + return self._subject_type_ref + + @subject_type_ref.setter + def subject_type_ref(self, subject_type_ref): + """Sets the subject_type_ref of this PredicateSemantic. + + + :param subject_type_ref: The subject_type_ref of this PredicateSemantic. # noqa: E501 + :type: PropertyRef + """ + + self._subject_type_ref = subject_type_ref + + @property + def predicate(self): + """Gets the predicate of this PredicateSemantic. # noqa: E501 + + + :return: The predicate of this PredicateSemantic. # noqa: E501 + :rtype: PredicateIdentifier + """ + return self._predicate + + @predicate.setter + def predicate(self, predicate): + """Sets the predicate of this PredicateSemantic. + + + :param predicate: The predicate of this PredicateSemantic. # noqa: E501 + :type: PredicateIdentifier + """ + + self._predicate = predicate + + @property + def object_type_ref(self): + """Gets the object_type_ref of this PredicateSemantic. # noqa: E501 + + + :return: The object_type_ref of this PredicateSemantic. # noqa: E501 + :rtype: PropertyRef + """ + return self._object_type_ref + + @object_type_ref.setter + def object_type_ref(self, object_type_ref): + """Sets the object_type_ref of this PredicateSemantic. + + + :param object_type_ref: The object_type_ref of this PredicateSemantic. # noqa: E501 + :type: PropertyRef + """ + + self._object_type_ref = object_type_ref + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, PredicateSemantic): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, PredicateSemantic): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/semantic/rule_code.py b/knext/schema/rest/models/semantic/rule_code.py new file mode 100644 index 00000000..10f935bd --- /dev/null +++ b/knext/schema/rest/models/semantic/rule_code.py @@ -0,0 +1,129 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class RuleCode(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"code": "str"} + + attribute_map = {"code": "code"} + + def __init__(self, code=None, local_vars_configuration=None): # noqa: E501 + """RuleCode - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._code = None + self.discriminator = None + + if code is not None: + self.code = code + + @property + def code(self): + """Gets the code of this RuleCode. # noqa: E501 + + + :return: The code of this RuleCode. # noqa: E501 + :rtype: str + """ + return self._code + + @code.setter + def code(self, code): + """Sets the code of this RuleCode. + + + :param code: The code of this RuleCode. # noqa: E501 + :type: str + """ + + self._code = code + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, RuleCode): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, RuleCode): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/__init__.py b/knext/schema/rest/models/type/__init__.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/schema/rest/models/type/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/schema/rest/models/type/base_advanced_type.py b/knext/schema/rest/models/type/base_advanced_type.py new file mode 100644 index 00000000..dda6e70f --- /dev/null +++ b/knext/schema/rest/models/type/base_advanced_type.py @@ -0,0 +1,421 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class BaseAdvancedType(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "basic_info": "StandardTypeBasicInfo", + "parent_type_info": "ParentTypeInfo", + "spg_type_enum": "str", + "properties": "list[Property]", + "relations": "list[Relation]", + "advanced_config": "SpgTypeAdvancedConfig", + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + } + + attribute_map = { + "basic_info": "basicInfo", + "parent_type_info": "parentTypeInfo", + "spg_type_enum": "spgTypeEnum", + "properties": "properties", + "relations": "relations", + "advanced_config": "advancedConfig", + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + } + + discriminator_value_class_map = { + "STANDARD_TYPE": "StandardType", + "ENTITY_TYPE": "EntityType", + "EVENT_TYPE": "EventType", + "CONCEPT_TYPE": "ConceptType", + } + + def __init__( + self, + basic_info=None, + parent_type_info=None, + spg_type_enum=None, + properties=None, + relations=None, + advanced_config=None, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + local_vars_configuration=None, + ): # noqa: E501 + """BaseAdvancedType - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._basic_info = None + self._parent_type_info = None + self._spg_type_enum = None + self._properties = None + self._relations = None + self._advanced_config = None + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self.discriminator = None + + if basic_info is not None: + self.basic_info = basic_info + if parent_type_info is not None: + self.parent_type_info = parent_type_info + if spg_type_enum is not None: + self.spg_type_enum = spg_type_enum + if properties is not None: + self.properties = properties + if relations is not None: + self.relations = relations + if advanced_config is not None: + self.advanced_config = advanced_config + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + + @property + def basic_info(self): + """Gets the basic_info of this BaseAdvancedType. # noqa: E501 + + + :return: The basic_info of this BaseAdvancedType. # noqa: E501 + :rtype: StandardTypeBasicInfo + """ + return self._basic_info + + @basic_info.setter + def basic_info(self, basic_info): + """Sets the basic_info of this BaseAdvancedType. + + + :param basic_info: The basic_info of this BaseAdvancedType. # noqa: E501 + :type: StandardTypeBasicInfo + """ + + self._basic_info = basic_info + + @property + def parent_type_info(self): + """Gets the parent_type_info of this BaseAdvancedType. # noqa: E501 + + + :return: The parent_type_info of this BaseAdvancedType. # noqa: E501 + :rtype: ParentTypeInfo + """ + return self._parent_type_info + + @parent_type_info.setter + def parent_type_info(self, parent_type_info): + """Sets the parent_type_info of this BaseAdvancedType. + + + :param parent_type_info: The parent_type_info of this BaseAdvancedType. # noqa: E501 + :type: ParentTypeInfo + """ + + self._parent_type_info = parent_type_info + + @property + def spg_type_enum(self): + """Gets the spg_type_enum of this BaseAdvancedType. # noqa: E501 + + + :return: The spg_type_enum of this BaseAdvancedType. # noqa: E501 + :rtype: str + """ + return self._spg_type_enum + + @spg_type_enum.setter + def spg_type_enum(self, spg_type_enum): + """Sets the spg_type_enum of this BaseAdvancedType. + + + :param spg_type_enum: The spg_type_enum of this BaseAdvancedType. # noqa: E501 + :type: str + """ + allowed_values = [ + "BASIC_TYPE", + "ENTITY_TYPE", + "CONCEPT_TYPE", + "EVENT_TYPE", + "STANDARD_TYPE", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and spg_type_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type_enum` ({0}), must be one of {1}".format( # noqa: E501 + spg_type_enum, allowed_values + ) + ) + + self._spg_type_enum = spg_type_enum + + @property + def properties(self): + """Gets the properties of this BaseAdvancedType. # noqa: E501 + + + :return: The properties of this BaseAdvancedType. # noqa: E501 + :rtype: list[Property] + """ + return self._properties + + @properties.setter + def properties(self, properties): + """Sets the properties of this BaseAdvancedType. + + + :param properties: The properties of this BaseAdvancedType. # noqa: E501 + :type: list[Property] + """ + + self._properties = properties + + @property + def relations(self): + """Gets the relations of this BaseAdvancedType. # noqa: E501 + + + :return: The relations of this BaseAdvancedType. # noqa: E501 + :rtype: list[Relation] + """ + return self._relations + + @relations.setter + def relations(self, relations): + """Sets the relations of this BaseAdvancedType. + + + :param relations: The relations of this BaseAdvancedType. # noqa: E501 + :type: list[Relation] + """ + + self._relations = relations + + @property + def advanced_config(self): + """Gets the advanced_config of this BaseAdvancedType. # noqa: E501 + + + :return: The advanced_config of this BaseAdvancedType. # noqa: E501 + :rtype: SpgTypeAdvancedConfig + """ + return self._advanced_config + + @advanced_config.setter + def advanced_config(self, advanced_config): + """Sets the advanced_config of this BaseAdvancedType. + + + :param advanced_config: The advanced_config of this BaseAdvancedType. # noqa: E501 + :type: SpgTypeAdvancedConfig + """ + + self._advanced_config = advanced_config + + @property + def project_id(self): + """Gets the project_id of this BaseAdvancedType. # noqa: E501 + + + :return: The project_id of this BaseAdvancedType. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this BaseAdvancedType. + + + :param project_id: The project_id of this BaseAdvancedType. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this BaseAdvancedType. # noqa: E501 + + + :return: The ontology_id of this BaseAdvancedType. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this BaseAdvancedType. + + + :param ontology_id: The ontology_id of this BaseAdvancedType. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this BaseAdvancedType. # noqa: E501 + + + :return: The alter_operation of this BaseAdvancedType. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this BaseAdvancedType. + + + :param alter_operation: The alter_operation of this BaseAdvancedType. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this BaseAdvancedType. # noqa: E501 + + + :return: The ext_info of this BaseAdvancedType. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this BaseAdvancedType. + + + :param ext_info: The ext_info of this BaseAdvancedType. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + def get_real_child_model(self, data): + """Returns the child model by discriminator""" + if "@type" in data: + child_type = data.get("@type") + real_child_model = self.discriminator_value_class_map.get(child_type) + return real_child_model + return None + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, BaseAdvancedType): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, BaseAdvancedType): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/base_spg_type.py b/knext/schema/rest/models/type/base_spg_type.py new file mode 100644 index 00000000..1a3539f3 --- /dev/null +++ b/knext/schema/rest/models/type/base_spg_type.py @@ -0,0 +1,424 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class BaseSpgType(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "basic_info": "StandardTypeBasicInfo", + "parent_type_info": "ParentTypeInfo", + "spg_type_enum": "str", + "properties": "list[Property]", + "relations": "list[Relation]", + "advanced_config": "SpgTypeAdvancedConfig", + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + } + + attribute_map = { + "basic_info": "basicInfo", + "parent_type_info": "parentTypeInfo", + "spg_type_enum": "spgTypeEnum", + "properties": "properties", + "relations": "relations", + "advanced_config": "advancedConfig", + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + } + + discriminator_value_class_map = { + "TEXT": "BasicType", + "LONG": "BasicType", + "DOUBLE": "BasicType", + "STANDARD_TYPE": "StandardType", + "ENTITY_TYPE": "EntityType", + "EVENT_TYPE": "EventType", + "CONCEPT_TYPE": "ConceptType", + } + + def __init__( + self, + basic_info=None, + parent_type_info=None, + spg_type_enum=None, + properties=None, + relations=None, + advanced_config=None, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + local_vars_configuration=None, + ): # noqa: E501 + """BaseSpgType - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._basic_info = None + self._parent_type_info = None + self._spg_type_enum = None + self._properties = None + self._relations = None + self._advanced_config = None + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self.discriminator = None + + if basic_info is not None: + self.basic_info = basic_info + if parent_type_info is not None: + self.parent_type_info = parent_type_info + if spg_type_enum is not None: + self.spg_type_enum = spg_type_enum + if properties is not None: + self.properties = properties + if relations is not None: + self.relations = relations + if advanced_config is not None: + self.advanced_config = advanced_config + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + + @property + def basic_info(self): + """Gets the basic_info of this BaseSpgType. # noqa: E501 + + + :return: The basic_info of this BaseSpgType. # noqa: E501 + :rtype: StandardTypeBasicInfo + """ + return self._basic_info + + @basic_info.setter + def basic_info(self, basic_info): + """Sets the basic_info of this BaseSpgType. + + + :param basic_info: The basic_info of this BaseSpgType. # noqa: E501 + :type: StandardTypeBasicInfo + """ + + self._basic_info = basic_info + + @property + def parent_type_info(self): + """Gets the parent_type_info of this BaseSpgType. # noqa: E501 + + + :return: The parent_type_info of this BaseSpgType. # noqa: E501 + :rtype: ParentTypeInfo + """ + return self._parent_type_info + + @parent_type_info.setter + def parent_type_info(self, parent_type_info): + """Sets the parent_type_info of this BaseSpgType. + + + :param parent_type_info: The parent_type_info of this BaseSpgType. # noqa: E501 + :type: ParentTypeInfo + """ + + self._parent_type_info = parent_type_info + + @property + def spg_type_enum(self): + """Gets the spg_type_enum of this BaseSpgType. # noqa: E501 + + + :return: The spg_type_enum of this BaseSpgType. # noqa: E501 + :rtype: str + """ + return self._spg_type_enum + + @spg_type_enum.setter + def spg_type_enum(self, spg_type_enum): + """Sets the spg_type_enum of this BaseSpgType. + + + :param spg_type_enum: The spg_type_enum of this BaseSpgType. # noqa: E501 + :type: str + """ + allowed_values = [ + "BASIC_TYPE", + "ENTITY_TYPE", + "CONCEPT_TYPE", + "EVENT_TYPE", + "STANDARD_TYPE", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and spg_type_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type_enum` ({0}), must be one of {1}".format( # noqa: E501 + spg_type_enum, allowed_values + ) + ) + + self._spg_type_enum = spg_type_enum + + @property + def properties(self): + """Gets the properties of this BaseSpgType. # noqa: E501 + + + :return: The properties of this BaseSpgType. # noqa: E501 + :rtype: list[Property] + """ + return self._properties + + @properties.setter + def properties(self, properties): + """Sets the properties of this BaseSpgType. + + + :param properties: The properties of this BaseSpgType. # noqa: E501 + :type: list[Property] + """ + + self._properties = properties + + @property + def relations(self): + """Gets the relations of this BaseSpgType. # noqa: E501 + + + :return: The relations of this BaseSpgType. # noqa: E501 + :rtype: list[Relation] + """ + return self._relations + + @relations.setter + def relations(self, relations): + """Sets the relations of this BaseSpgType. + + + :param relations: The relations of this BaseSpgType. # noqa: E501 + :type: list[Relation] + """ + + self._relations = relations + + @property + def advanced_config(self): + """Gets the advanced_config of this BaseSpgType. # noqa: E501 + + + :return: The advanced_config of this BaseSpgType. # noqa: E501 + :rtype: SpgTypeAdvancedConfig + """ + return self._advanced_config + + @advanced_config.setter + def advanced_config(self, advanced_config): + """Sets the advanced_config of this BaseSpgType. + + + :param advanced_config: The advanced_config of this BaseSpgType. # noqa: E501 + :type: SpgTypeAdvancedConfig + """ + + self._advanced_config = advanced_config + + @property + def project_id(self): + """Gets the project_id of this BaseSpgType. # noqa: E501 + + + :return: The project_id of this BaseSpgType. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this BaseSpgType. + + + :param project_id: The project_id of this BaseSpgType. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this BaseSpgType. # noqa: E501 + + + :return: The ontology_id of this BaseSpgType. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this BaseSpgType. + + + :param ontology_id: The ontology_id of this BaseSpgType. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this BaseSpgType. # noqa: E501 + + + :return: The alter_operation of this BaseSpgType. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this BaseSpgType. + + + :param alter_operation: The alter_operation of this BaseSpgType. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this BaseSpgType. # noqa: E501 + + + :return: The ext_info of this BaseSpgType. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this BaseSpgType. + + + :param ext_info: The ext_info of this BaseSpgType. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + def get_real_child_model(self, data): + """Returns the child model by discriminator""" + if "@type" in data: + child_type = data.get("@type") + real_child_model = self.discriminator_value_class_map.get(child_type) + return real_child_model + return None + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, BaseSpgType): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, BaseSpgType): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/basic_type.py b/knext/schema/rest/models/type/basic_type.py new file mode 100644 index 00000000..48d00723 --- /dev/null +++ b/knext/schema/rest/models/type/basic_type.py @@ -0,0 +1,454 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class BasicType(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "basic_info": "StandardTypeBasicInfo", + "parent_type_info": "ParentTypeInfo", + "spg_type_enum": "str", + "properties": "list[Property]", + "relations": "list[Relation]", + "advanced_config": "SpgTypeAdvancedConfig", + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + "basic_type": "str", + } + + attribute_map = { + "basic_info": "basicInfo", + "parent_type_info": "parentTypeInfo", + "spg_type_enum": "spgTypeEnum", + "properties": "properties", + "relations": "relations", + "advanced_config": "advancedConfig", + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + "basic_type": "basicType", + } + + def __init__( + self, + basic_info=None, + parent_type_info=None, + spg_type_enum="BASIC_TYPE", + properties=None, + relations=None, + advanced_config=None, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + basic_type=None, + local_vars_configuration=None, + ): # noqa: E501 + """BasicType - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._basic_info = None + self._parent_type_info = None + self._spg_type_enum = None + self._properties = None + self._relations = None + self._advanced_config = None + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self._basic_type = None + self.discriminator = spg_type_enum + + if basic_info is not None: + self.basic_info = basic_info + if parent_type_info is not None: + self.parent_type_info = parent_type_info + self.spg_type_enum = spg_type_enum + if properties is not None: + self.properties = properties + if relations is not None: + self.relations = relations + if advanced_config is not None: + self.advanced_config = advanced_config + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + self.basic_type = basic_type + + @property + def basic_info(self): + """Gets the basic_info of this BasicType. # noqa: E501 + + + :return: The basic_info of this BasicType. # noqa: E501 + :rtype: StandardTypeBasicInfo + """ + return self._basic_info + + @basic_info.setter + def basic_info(self, basic_info): + """Sets the basic_info of this BasicType. + + + :param basic_info: The basic_info of this BasicType. # noqa: E501 + :type: StandardTypeBasicInfo + """ + + self._basic_info = basic_info + + @property + def parent_type_info(self): + """Gets the parent_type_info of this BasicType. # noqa: E501 + + + :return: The parent_type_info of this BasicType. # noqa: E501 + :rtype: ParentTypeInfo + """ + return self._parent_type_info + + @parent_type_info.setter + def parent_type_info(self, parent_type_info): + """Sets the parent_type_info of this BasicType. + + + :param parent_type_info: The parent_type_info of this BasicType. # noqa: E501 + :type: ParentTypeInfo + """ + + self._parent_type_info = parent_type_info + + @property + def spg_type_enum(self): + """Gets the spg_type_enum of this BasicType. # noqa: E501 + + + :return: The spg_type_enum of this BasicType. # noqa: E501 + :rtype: str + """ + return self._spg_type_enum + + @spg_type_enum.setter + def spg_type_enum(self, spg_type_enum): + """Sets the spg_type_enum of this BasicType. + + + :param spg_type_enum: The spg_type_enum of this BasicType. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and spg_type_enum is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type_enum`, must not be `None`" + ) # noqa: E501 + allowed_values = [ + "BASIC_TYPE", + "ENTITY_TYPE", + "CONCEPT_TYPE", + "EVENT_TYPE", + "STANDARD_TYPE", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and spg_type_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type_enum` ({0}), must be one of {1}".format( # noqa: E501 + spg_type_enum, allowed_values + ) + ) + + self._spg_type_enum = spg_type_enum + + @property + def properties(self): + """Gets the properties of this BasicType. # noqa: E501 + + + :return: The properties of this BasicType. # noqa: E501 + :rtype: list[Property] + """ + return self._properties + + @properties.setter + def properties(self, properties): + """Sets the properties of this BasicType. + + + :param properties: The properties of this BasicType. # noqa: E501 + :type: list[Property] + """ + + self._properties = properties + + @property + def relations(self): + """Gets the relations of this BasicType. # noqa: E501 + + + :return: The relations of this BasicType. # noqa: E501 + :rtype: list[Relation] + """ + return self._relations + + @relations.setter + def relations(self, relations): + """Sets the relations of this BasicType. + + + :param relations: The relations of this BasicType. # noqa: E501 + :type: list[Relation] + """ + + self._relations = relations + + @property + def advanced_config(self): + """Gets the advanced_config of this BasicType. # noqa: E501 + + + :return: The advanced_config of this BasicType. # noqa: E501 + :rtype: SpgTypeAdvancedConfig + """ + return self._advanced_config + + @advanced_config.setter + def advanced_config(self, advanced_config): + """Sets the advanced_config of this BasicType. + + + :param advanced_config: The advanced_config of this BasicType. # noqa: E501 + :type: SpgTypeAdvancedConfig + """ + + self._advanced_config = advanced_config + + @property + def project_id(self): + """Gets the project_id of this BasicType. # noqa: E501 + + + :return: The project_id of this BasicType. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this BasicType. + + + :param project_id: The project_id of this BasicType. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this BasicType. # noqa: E501 + + + :return: The ontology_id of this BasicType. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this BasicType. + + + :param ontology_id: The ontology_id of this BasicType. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this BasicType. # noqa: E501 + + + :return: The alter_operation of this BasicType. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this BasicType. + + + :param alter_operation: The alter_operation of this BasicType. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this BasicType. # noqa: E501 + + + :return: The ext_info of this BasicType. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this BasicType. + + + :param ext_info: The ext_info of this BasicType. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + @property + def basic_type(self): + """Gets the basic_type of this BasicType. # noqa: E501 + + + :return: The basic_type of this BasicType. # noqa: E501 + :rtype: str + """ + return self._basic_type + + @basic_type.setter + def basic_type(self, basic_type): + """Sets the basic_type of this BasicType. + + + :param basic_type: The basic_type of this BasicType. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and basic_type is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `basic_type`, must not be `None`" + ) # noqa: E501 + allowed_values = ["TEXT", "LONG", "DOUBLE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and basic_type not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `basic_type` ({0}), must be one of {1}".format( # noqa: E501 + basic_type, allowed_values + ) + ) + + self._basic_type = basic_type + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, BasicType): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, BasicType): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/concept_layer_config.py b/knext/schema/rest/models/type/concept_layer_config.py new file mode 100644 index 00000000..07d70209 --- /dev/null +++ b/knext/schema/rest/models/type/concept_layer_config.py @@ -0,0 +1,168 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ConceptLayerConfig(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"hypernym_predicate": "str", "layer_names": "list[str]"} + + attribute_map = { + "hypernym_predicate": "hypernymPredicate", + "layer_names": "layerNames", + } + + def __init__( + self, hypernym_predicate=None, layer_names=None, local_vars_configuration=None + ): # noqa: E501 + """ConceptLayerConfig - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._hypernym_predicate = None + self._layer_names = None + self.discriminator = None + + if hypernym_predicate is not None: + self.hypernym_predicate = hypernym_predicate + if layer_names is not None: + self.layer_names = layer_names + + @property + def hypernym_predicate(self): + """Gets the hypernym_predicate of this ConceptLayerConfig. # noqa: E501 + + + :return: The hypernym_predicate of this ConceptLayerConfig. # noqa: E501 + :rtype: str + """ + return self._hypernym_predicate + + @hypernym_predicate.setter + def hypernym_predicate(self, hypernym_predicate): + """Sets the hypernym_predicate of this ConceptLayerConfig. + + + :param hypernym_predicate: The hypernym_predicate of this ConceptLayerConfig. # noqa: E501 + :type: str + """ + allowed_values = [None, "isA", "locateAt", "mannerOf"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and hypernym_predicate not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `hypernym_predicate` ({0}), must be one of {1}".format( # noqa: E501 + hypernym_predicate, allowed_values + ) + ) + + self._hypernym_predicate = hypernym_predicate + + @property + def layer_names(self): + """Gets the layer_names of this ConceptLayerConfig. # noqa: E501 + + + :return: The layer_names of this ConceptLayerConfig. # noqa: E501 + :rtype: list[str] + """ + return self._layer_names + + @layer_names.setter + def layer_names(self, layer_names): + """Sets the layer_names of this ConceptLayerConfig. + + + :param layer_names: The layer_names of this ConceptLayerConfig. # noqa: E501 + :type: list[str] + """ + + self._layer_names = layer_names + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ConceptLayerConfig): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ConceptLayerConfig): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/concept_taxonomic_config.py b/knext/schema/rest/models/type/concept_taxonomic_config.py new file mode 100644 index 00000000..96e18302 --- /dev/null +++ b/knext/schema/rest/models/type/concept_taxonomic_config.py @@ -0,0 +1,131 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ConceptTaxonomicConfig(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"taxonomic_type_identifier": "SpgTypeIdentifier"} + + attribute_map = {"taxonomic_type_identifier": "taxonomicTypeIdentifier"} + + def __init__( + self, taxonomic_type_identifier=None, local_vars_configuration=None + ): # noqa: E501 + """ConceptTaxonomicConfig - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._taxonomic_type_identifier = None + self.discriminator = None + + if taxonomic_type_identifier is not None: + self.taxonomic_type_identifier = taxonomic_type_identifier + + @property + def taxonomic_type_identifier(self): + """Gets the taxonomic_type_identifier of this ConceptTaxonomicConfig. # noqa: E501 + + + :return: The taxonomic_type_identifier of this ConceptTaxonomicConfig. # noqa: E501 + :rtype: SpgTypeIdentifier + """ + return self._taxonomic_type_identifier + + @taxonomic_type_identifier.setter + def taxonomic_type_identifier(self, taxonomic_type_identifier): + """Sets the taxonomic_type_identifier of this ConceptTaxonomicConfig. + + + :param taxonomic_type_identifier: The taxonomic_type_identifier of this ConceptTaxonomicConfig. # noqa: E501 + :type: SpgTypeIdentifier + """ + + self._taxonomic_type_identifier = taxonomic_type_identifier + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ConceptTaxonomicConfig): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ConceptTaxonomicConfig): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/concept_type.py b/knext/schema/rest/models/type/concept_type.py new file mode 100644 index 00000000..8ab0b573 --- /dev/null +++ b/knext/schema/rest/models/type/concept_type.py @@ -0,0 +1,493 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ConceptType(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "basic_info": "StandardTypeBasicInfo", + "parent_type_info": "ParentTypeInfo", + "spg_type_enum": "str", + "properties": "list[Property]", + "relations": "list[Relation]", + "advanced_config": "SpgTypeAdvancedConfig", + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + "concept_layer_config": "ConceptLayerConfig", + "concept_taxonomic_config": "ConceptTaxonomicConfig", + "concept_multi_version_config": "MultiVersionConfig", + } + + attribute_map = { + "basic_info": "basicInfo", + "parent_type_info": "parentTypeInfo", + "spg_type_enum": "spgTypeEnum", + "properties": "properties", + "relations": "relations", + "advanced_config": "advancedConfig", + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + "concept_layer_config": "conceptLayerConfig", + "concept_taxonomic_config": "conceptTaxonomicConfig", + "concept_multi_version_config": "conceptMultiVersionConfig", + } + + def __init__( + self, + basic_info=None, + parent_type_info=None, + spg_type_enum="CONCEPT_TYPE", + properties=None, + relations=None, + advanced_config=None, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + concept_layer_config=None, + concept_taxonomic_config=None, + concept_multi_version_config=None, + local_vars_configuration=None, + ): # noqa: E501 + """ConceptType - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._basic_info = None + self._parent_type_info = None + self._spg_type_enum = None + self._properties = None + self._relations = None + self._advanced_config = None + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self._concept_layer_config = None + self._concept_taxonomic_config = None + self._concept_multi_version_config = None + self.discriminator = spg_type_enum + + if basic_info is not None: + self.basic_info = basic_info + if parent_type_info is not None: + self.parent_type_info = parent_type_info + self.spg_type_enum = spg_type_enum + if properties is not None: + self.properties = properties + if relations is not None: + self.relations = relations + if advanced_config is not None: + self.advanced_config = advanced_config + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + if concept_layer_config is not None: + self.concept_layer_config = concept_layer_config + if concept_taxonomic_config is not None: + self.concept_taxonomic_config = concept_taxonomic_config + if concept_multi_version_config is not None: + self.concept_multi_version_config = concept_multi_version_config + + @property + def basic_info(self): + """Gets the basic_info of this ConceptType. # noqa: E501 + + + :return: The basic_info of this ConceptType. # noqa: E501 + :rtype: StandardTypeBasicInfo + """ + return self._basic_info + + @basic_info.setter + def basic_info(self, basic_info): + """Sets the basic_info of this ConceptType. + + + :param basic_info: The basic_info of this ConceptType. # noqa: E501 + :type: StandardTypeBasicInfo + """ + + self._basic_info = basic_info + + @property + def parent_type_info(self): + """Gets the parent_type_info of this ConceptType. # noqa: E501 + + + :return: The parent_type_info of this ConceptType. # noqa: E501 + :rtype: ParentTypeInfo + """ + return self._parent_type_info + + @parent_type_info.setter + def parent_type_info(self, parent_type_info): + """Sets the parent_type_info of this ConceptType. + + + :param parent_type_info: The parent_type_info of this ConceptType. # noqa: E501 + :type: ParentTypeInfo + """ + + self._parent_type_info = parent_type_info + + @property + def spg_type_enum(self): + """Gets the spg_type_enum of this ConceptType. # noqa: E501 + + + :return: The spg_type_enum of this ConceptType. # noqa: E501 + :rtype: str + """ + return self._spg_type_enum + + @spg_type_enum.setter + def spg_type_enum(self, spg_type_enum): + """Sets the spg_type_enum of this ConceptType. + + + :param spg_type_enum: The spg_type_enum of this ConceptType. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and spg_type_enum is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type_enum`, must not be `None`" + ) # noqa: E501 + allowed_values = [ + "BASIC_TYPE", + "ENTITY_TYPE", + "CONCEPT_TYPE", + "EVENT_TYPE", + "STANDARD_TYPE", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and spg_type_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type_enum` ({0}), must be one of {1}".format( # noqa: E501 + spg_type_enum, allowed_values + ) + ) + + self._spg_type_enum = spg_type_enum + + @property + def properties(self): + """Gets the properties of this ConceptType. # noqa: E501 + + + :return: The properties of this ConceptType. # noqa: E501 + :rtype: list[Property] + """ + return self._properties + + @properties.setter + def properties(self, properties): + """Sets the properties of this ConceptType. + + + :param properties: The properties of this ConceptType. # noqa: E501 + :type: list[Property] + """ + + self._properties = properties + + @property + def relations(self): + """Gets the relations of this ConceptType. # noqa: E501 + + + :return: The relations of this ConceptType. # noqa: E501 + :rtype: list[Relation] + """ + return self._relations + + @relations.setter + def relations(self, relations): + """Sets the relations of this ConceptType. + + + :param relations: The relations of this ConceptType. # noqa: E501 + :type: list[Relation] + """ + + self._relations = relations + + @property + def advanced_config(self): + """Gets the advanced_config of this ConceptType. # noqa: E501 + + + :return: The advanced_config of this ConceptType. # noqa: E501 + :rtype: SpgTypeAdvancedConfig + """ + return self._advanced_config + + @advanced_config.setter + def advanced_config(self, advanced_config): + """Sets the advanced_config of this ConceptType. + + + :param advanced_config: The advanced_config of this ConceptType. # noqa: E501 + :type: SpgTypeAdvancedConfig + """ + + self._advanced_config = advanced_config + + @property + def project_id(self): + """Gets the project_id of this ConceptType. # noqa: E501 + + + :return: The project_id of this ConceptType. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this ConceptType. + + + :param project_id: The project_id of this ConceptType. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this ConceptType. # noqa: E501 + + + :return: The ontology_id of this ConceptType. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this ConceptType. + + + :param ontology_id: The ontology_id of this ConceptType. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this ConceptType. # noqa: E501 + + + :return: The alter_operation of this ConceptType. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this ConceptType. + + + :param alter_operation: The alter_operation of this ConceptType. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this ConceptType. # noqa: E501 + + + :return: The ext_info of this ConceptType. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this ConceptType. + + + :param ext_info: The ext_info of this ConceptType. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + @property + def concept_layer_config(self): + """Gets the concept_layer_config of this ConceptType. # noqa: E501 + + + :return: The concept_layer_config of this ConceptType. # noqa: E501 + :rtype: ConceptLayerConfig + """ + return self._concept_layer_config + + @concept_layer_config.setter + def concept_layer_config(self, concept_layer_config): + """Sets the concept_layer_config of this ConceptType. + + + :param concept_layer_config: The concept_layer_config of this ConceptType. # noqa: E501 + :type: ConceptLayerConfig + """ + + self._concept_layer_config = concept_layer_config + + @property + def concept_taxonomic_config(self): + """Gets the concept_taxonomic_config of this ConceptType. # noqa: E501 + + + :return: The concept_taxonomic_config of this ConceptType. # noqa: E501 + :rtype: ConceptTaxonomicConfig + """ + return self._concept_taxonomic_config + + @concept_taxonomic_config.setter + def concept_taxonomic_config(self, concept_taxonomic_config): + """Sets the concept_taxonomic_config of this ConceptType. + + + :param concept_taxonomic_config: The concept_taxonomic_config of this ConceptType. # noqa: E501 + :type: ConceptTaxonomicConfig + """ + + self._concept_taxonomic_config = concept_taxonomic_config + + @property + def concept_multi_version_config(self): + """Gets the concept_multi_version_config of this ConceptType. # noqa: E501 + + + :return: The concept_multi_version_config of this ConceptType. # noqa: E501 + :rtype: MultiVersionConfig + """ + return self._concept_multi_version_config + + @concept_multi_version_config.setter + def concept_multi_version_config(self, concept_multi_version_config): + """Sets the concept_multi_version_config of this ConceptType. + + + :param concept_multi_version_config: The concept_multi_version_config of this ConceptType. # noqa: E501 + :type: MultiVersionConfig + """ + + self._concept_multi_version_config = concept_multi_version_config + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ConceptType): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ConceptType): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/entity_type.py b/knext/schema/rest/models/type/entity_type.py new file mode 100644 index 00000000..ca431965 --- /dev/null +++ b/knext/schema/rest/models/type/entity_type.py @@ -0,0 +1,412 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class EntityType(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "basic_info": "StandardTypeBasicInfo", + "parent_type_info": "ParentTypeInfo", + "spg_type_enum": "str", + "properties": "list[Property]", + "relations": "list[Relation]", + "advanced_config": "SpgTypeAdvancedConfig", + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + } + + attribute_map = { + "basic_info": "basicInfo", + "parent_type_info": "parentTypeInfo", + "spg_type_enum": "spgTypeEnum", + "properties": "properties", + "relations": "relations", + "advanced_config": "advancedConfig", + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + } + + def __init__( + self, + basic_info=None, + parent_type_info=None, + spg_type_enum="ENTITY_TYPE", + properties=None, + relations=None, + advanced_config=None, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + local_vars_configuration=None, + ): # noqa: E501 + """EntityType - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._basic_info = None + self._parent_type_info = None + self._spg_type_enum = None + self._properties = None + self._relations = None + self._advanced_config = None + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self.discriminator = spg_type_enum + + if basic_info is not None: + self.basic_info = basic_info + if parent_type_info is not None: + self.parent_type_info = parent_type_info + self.spg_type_enum = spg_type_enum + if properties is not None: + self.properties = properties + if relations is not None: + self.relations = relations + if advanced_config is not None: + self.advanced_config = advanced_config + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + + @property + def basic_info(self): + """Gets the basic_info of this EntityType. # noqa: E501 + + + :return: The basic_info of this EntityType. # noqa: E501 + :rtype: StandardTypeBasicInfo + """ + return self._basic_info + + @basic_info.setter + def basic_info(self, basic_info): + """Sets the basic_info of this EntityType. + + + :param basic_info: The basic_info of this EntityType. # noqa: E501 + :type: StandardTypeBasicInfo + """ + + self._basic_info = basic_info + + @property + def parent_type_info(self): + """Gets the parent_type_info of this EntityType. # noqa: E501 + + + :return: The parent_type_info of this EntityType. # noqa: E501 + :rtype: ParentTypeInfo + """ + return self._parent_type_info + + @parent_type_info.setter + def parent_type_info(self, parent_type_info): + """Sets the parent_type_info of this EntityType. + + + :param parent_type_info: The parent_type_info of this EntityType. # noqa: E501 + :type: ParentTypeInfo + """ + + self._parent_type_info = parent_type_info + + @property + def spg_type_enum(self): + """Gets the spg_type_enum of this EntityType. # noqa: E501 + + + :return: The spg_type_enum of this EntityType. # noqa: E501 + :rtype: str + """ + return self._spg_type_enum + + @spg_type_enum.setter + def spg_type_enum(self, spg_type_enum): + """Sets the spg_type_enum of this EntityType. + + + :param spg_type_enum: The spg_type_enum of this EntityType. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and spg_type_enum is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type_enum`, must not be `None`" + ) # noqa: E501 + allowed_values = [ + "BASIC_TYPE", + "ENTITY_TYPE", + "CONCEPT_TYPE", + "EVENT_TYPE", + "STANDARD_TYPE", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and spg_type_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type_enum` ({0}), must be one of {1}".format( # noqa: E501 + spg_type_enum, allowed_values + ) + ) + + self._spg_type_enum = spg_type_enum + + @property + def properties(self): + """Gets the properties of this EntityType. # noqa: E501 + + + :return: The properties of this EntityType. # noqa: E501 + :rtype: list[Property] + """ + return self._properties + + @properties.setter + def properties(self, properties): + """Sets the properties of this EntityType. + + + :param properties: The properties of this EntityType. # noqa: E501 + :type: list[Property] + """ + + self._properties = properties + + @property + def relations(self): + """Gets the relations of this EntityType. # noqa: E501 + + + :return: The relations of this EntityType. # noqa: E501 + :rtype: list[Relation] + """ + return self._relations + + @relations.setter + def relations(self, relations): + """Sets the relations of this EntityType. + + + :param relations: The relations of this EntityType. # noqa: E501 + :type: list[Relation] + """ + + self._relations = relations + + @property + def advanced_config(self): + """Gets the advanced_config of this EntityType. # noqa: E501 + + + :return: The advanced_config of this EntityType. # noqa: E501 + :rtype: SpgTypeAdvancedConfig + """ + return self._advanced_config + + @advanced_config.setter + def advanced_config(self, advanced_config): + """Sets the advanced_config of this EntityType. + + + :param advanced_config: The advanced_config of this EntityType. # noqa: E501 + :type: SpgTypeAdvancedConfig + """ + + self._advanced_config = advanced_config + + @property + def project_id(self): + """Gets the project_id of this EntityType. # noqa: E501 + + + :return: The project_id of this EntityType. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this EntityType. + + + :param project_id: The project_id of this EntityType. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this EntityType. # noqa: E501 + + + :return: The ontology_id of this EntityType. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this EntityType. + + + :param ontology_id: The ontology_id of this EntityType. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this EntityType. # noqa: E501 + + + :return: The alter_operation of this EntityType. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this EntityType. + + + :param alter_operation: The alter_operation of this EntityType. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this EntityType. # noqa: E501 + + + :return: The ext_info of this EntityType. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this EntityType. + + + :param ext_info: The ext_info of this EntityType. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, EntityType): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, EntityType): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/event_type.py b/knext/schema/rest/models/type/event_type.py new file mode 100644 index 00000000..1ec8938c --- /dev/null +++ b/knext/schema/rest/models/type/event_type.py @@ -0,0 +1,412 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class EventType(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "basic_info": "StandardTypeBasicInfo", + "parent_type_info": "ParentTypeInfo", + "spg_type_enum": "str", + "properties": "list[Property]", + "relations": "list[Relation]", + "advanced_config": "SpgTypeAdvancedConfig", + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + } + + attribute_map = { + "basic_info": "basicInfo", + "parent_type_info": "parentTypeInfo", + "spg_type_enum": "spgTypeEnum", + "properties": "properties", + "relations": "relations", + "advanced_config": "advancedConfig", + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + } + + def __init__( + self, + basic_info=None, + parent_type_info=None, + spg_type_enum="EVENT_TYPE", + properties=None, + relations=None, + advanced_config=None, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + local_vars_configuration=None, + ): # noqa: E501 + """EventType - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._basic_info = None + self._parent_type_info = None + self._spg_type_enum = None + self._properties = None + self._relations = None + self._advanced_config = None + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self.discriminator = spg_type_enum + + if basic_info is not None: + self.basic_info = basic_info + if parent_type_info is not None: + self.parent_type_info = parent_type_info + self.spg_type_enum = spg_type_enum + if properties is not None: + self.properties = properties + if relations is not None: + self.relations = relations + if advanced_config is not None: + self.advanced_config = advanced_config + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + + @property + def basic_info(self): + """Gets the basic_info of this EventType. # noqa: E501 + + + :return: The basic_info of this EventType. # noqa: E501 + :rtype: StandardTypeBasicInfo + """ + return self._basic_info + + @basic_info.setter + def basic_info(self, basic_info): + """Sets the basic_info of this EventType. + + + :param basic_info: The basic_info of this EventType. # noqa: E501 + :type: StandardTypeBasicInfo + """ + + self._basic_info = basic_info + + @property + def parent_type_info(self): + """Gets the parent_type_info of this EventType. # noqa: E501 + + + :return: The parent_type_info of this EventType. # noqa: E501 + :rtype: ParentTypeInfo + """ + return self._parent_type_info + + @parent_type_info.setter + def parent_type_info(self, parent_type_info): + """Sets the parent_type_info of this EventType. + + + :param parent_type_info: The parent_type_info of this EventType. # noqa: E501 + :type: ParentTypeInfo + """ + + self._parent_type_info = parent_type_info + + @property + def spg_type_enum(self): + """Gets the spg_type_enum of this EventType. # noqa: E501 + + + :return: The spg_type_enum of this EventType. # noqa: E501 + :rtype: str + """ + return self._spg_type_enum + + @spg_type_enum.setter + def spg_type_enum(self, spg_type_enum): + """Sets the spg_type_enum of this EventType. + + + :param spg_type_enum: The spg_type_enum of this EventType. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and spg_type_enum is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type_enum`, must not be `None`" + ) # noqa: E501 + allowed_values = [ + "BASIC_TYPE", + "ENTITY_TYPE", + "CONCEPT_TYPE", + "EVENT_TYPE", + "STANDARD_TYPE", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and spg_type_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type_enum` ({0}), must be one of {1}".format( # noqa: E501 + spg_type_enum, allowed_values + ) + ) + + self._spg_type_enum = spg_type_enum + + @property + def properties(self): + """Gets the properties of this EventType. # noqa: E501 + + + :return: The properties of this EventType. # noqa: E501 + :rtype: list[Property] + """ + return self._properties + + @properties.setter + def properties(self, properties): + """Sets the properties of this EventType. + + + :param properties: The properties of this EventType. # noqa: E501 + :type: list[Property] + """ + + self._properties = properties + + @property + def relations(self): + """Gets the relations of this EventType. # noqa: E501 + + + :return: The relations of this EventType. # noqa: E501 + :rtype: list[Relation] + """ + return self._relations + + @relations.setter + def relations(self, relations): + """Sets the relations of this EventType. + + + :param relations: The relations of this EventType. # noqa: E501 + :type: list[Relation] + """ + + self._relations = relations + + @property + def advanced_config(self): + """Gets the advanced_config of this EventType. # noqa: E501 + + + :return: The advanced_config of this EventType. # noqa: E501 + :rtype: SpgTypeAdvancedConfig + """ + return self._advanced_config + + @advanced_config.setter + def advanced_config(self, advanced_config): + """Sets the advanced_config of this EventType. + + + :param advanced_config: The advanced_config of this EventType. # noqa: E501 + :type: SpgTypeAdvancedConfig + """ + + self._advanced_config = advanced_config + + @property + def project_id(self): + """Gets the project_id of this EventType. # noqa: E501 + + + :return: The project_id of this EventType. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this EventType. + + + :param project_id: The project_id of this EventType. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this EventType. # noqa: E501 + + + :return: The ontology_id of this EventType. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this EventType. + + + :param ontology_id: The ontology_id of this EventType. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this EventType. # noqa: E501 + + + :return: The alter_operation of this EventType. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this EventType. + + + :param alter_operation: The alter_operation of this EventType. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this EventType. # noqa: E501 + + + :return: The ext_info of this EventType. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this EventType. + + + :param ext_info: The ext_info of this EventType. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, EventType): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, EventType): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/multi_version_config.py b/knext/schema/rest/models/type/multi_version_config.py new file mode 100644 index 00000000..a8452930 --- /dev/null +++ b/knext/schema/rest/models/type/multi_version_config.py @@ -0,0 +1,179 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class MultiVersionConfig(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"pattern": "str", "max_version": "int", "ttl": "int"} + + attribute_map = {"pattern": "pattern", "max_version": "maxVersion", "ttl": "ttl"} + + def __init__( + self, pattern=None, max_version=None, ttl=None, local_vars_configuration=None + ): # noqa: E501 + """MultiVersionConfig - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._pattern = None + self._max_version = None + self._ttl = None + self.discriminator = None + + if pattern is not None: + self.pattern = pattern + if max_version is not None: + self.max_version = max_version + if ttl is not None: + self.ttl = ttl + + @property + def pattern(self): + """Gets the pattern of this MultiVersionConfig. # noqa: E501 + + + :return: The pattern of this MultiVersionConfig. # noqa: E501 + :rtype: str + """ + return self._pattern + + @pattern.setter + def pattern(self, pattern): + """Sets the pattern of this MultiVersionConfig. + + + :param pattern: The pattern of this MultiVersionConfig. # noqa: E501 + :type: str + """ + + self._pattern = pattern + + @property + def max_version(self): + """Gets the max_version of this MultiVersionConfig. # noqa: E501 + + + :return: The max_version of this MultiVersionConfig. # noqa: E501 + :rtype: int + """ + return self._max_version + + @max_version.setter + def max_version(self, max_version): + """Sets the max_version of this MultiVersionConfig. + + + :param max_version: The max_version of this MultiVersionConfig. # noqa: E501 + :type: int + """ + + self._max_version = max_version + + @property + def ttl(self): + """Gets the ttl of this MultiVersionConfig. # noqa: E501 + + + :return: The ttl of this MultiVersionConfig. # noqa: E501 + :rtype: int + """ + return self._ttl + + @ttl.setter + def ttl(self, ttl): + """Sets the ttl of this MultiVersionConfig. + + + :param ttl: The ttl of this MultiVersionConfig. # noqa: E501 + :type: int + """ + + self._ttl = ttl + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, MultiVersionConfig): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, MultiVersionConfig): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/operator_key.py b/knext/schema/rest/models/type/operator_key.py new file mode 100644 index 00000000..915f688b --- /dev/null +++ b/knext/schema/rest/models/type/operator_key.py @@ -0,0 +1,155 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class OperatorKey(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"name": "str", "version": "int"} + + attribute_map = {"name": "name", "version": "version"} + + def __init__( + self, name=None, version=None, local_vars_configuration=None + ): # noqa: E501 + """OperatorKey - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._name = None + self._version = None + self.discriminator = None + + if name is not None: + self.name = name + if version is not None: + self.version = version + + @property + def name(self): + """Gets the name of this OperatorKey. # noqa: E501 + + + :return: The name of this OperatorKey. # noqa: E501 + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this OperatorKey. + + + :param name: The name of this OperatorKey. # noqa: E501 + :type: str + """ + + self._name = name + + @property + def version(self): + """Gets the version of this OperatorKey. # noqa: E501 + + + :return: The version of this OperatorKey. # noqa: E501 + :rtype: int + """ + return self._version + + @version.setter + def version(self, version): + """Sets the version of this OperatorKey. + + + :param version: The version of this OperatorKey. # noqa: E501 + :type: int + """ + + self._version = version + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, OperatorKey): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, OperatorKey): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/parent_type_info.py b/knext/schema/rest/models/type/parent_type_info.py new file mode 100644 index 00000000..ceea8ee6 --- /dev/null +++ b/knext/schema/rest/models/type/parent_type_info.py @@ -0,0 +1,218 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ParentTypeInfo(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "unique_id": "int", + "parent_unique_id": "int", + "parent_type_identifier": "SpgTypeIdentifier", + "inherit_path": "list[int]", + } + + attribute_map = { + "unique_id": "uniqueId", + "parent_unique_id": "parentUniqueId", + "parent_type_identifier": "parentTypeIdentifier", + "inherit_path": "inheritPath", + } + + def __init__( + self, + unique_id=None, + parent_unique_id=None, + parent_type_identifier=None, + inherit_path=None, + local_vars_configuration=None, + ): # noqa: E501 + """ParentTypeInfo - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._unique_id = None + self._parent_unique_id = None + self._parent_type_identifier = None + self._inherit_path = None + self.discriminator = None + + if unique_id is not None: + self.unique_id = unique_id + if parent_unique_id is not None: + self.parent_unique_id = parent_unique_id + if parent_type_identifier is not None: + self.parent_type_identifier = parent_type_identifier + if inherit_path is not None: + self.inherit_path = inherit_path + + @property + def unique_id(self): + """Gets the unique_id of this ParentTypeInfo. # noqa: E501 + + + :return: The unique_id of this ParentTypeInfo. # noqa: E501 + :rtype: int + """ + return self._unique_id + + @unique_id.setter + def unique_id(self, unique_id): + """Sets the unique_id of this ParentTypeInfo. + + + :param unique_id: The unique_id of this ParentTypeInfo. # noqa: E501 + :type: int + """ + + self._unique_id = unique_id + + @property + def parent_unique_id(self): + """Gets the parent_unique_id of this ParentTypeInfo. # noqa: E501 + + + :return: The parent_unique_id of this ParentTypeInfo. # noqa: E501 + :rtype: int + """ + return self._parent_unique_id + + @parent_unique_id.setter + def parent_unique_id(self, parent_unique_id): + """Sets the parent_unique_id of this ParentTypeInfo. + + + :param parent_unique_id: The parent_unique_id of this ParentTypeInfo. # noqa: E501 + :type: int + """ + + self._parent_unique_id = parent_unique_id + + @property + def parent_type_identifier(self): + """Gets the parent_type_identifier of this ParentTypeInfo. # noqa: E501 + + + :return: The parent_type_identifier of this ParentTypeInfo. # noqa: E501 + :rtype: SpgTypeIdentifier + """ + return self._parent_type_identifier + + @parent_type_identifier.setter + def parent_type_identifier(self, parent_type_identifier): + """Sets the parent_type_identifier of this ParentTypeInfo. + + + :param parent_type_identifier: The parent_type_identifier of this ParentTypeInfo. # noqa: E501 + :type: SpgTypeIdentifier + """ + + self._parent_type_identifier = parent_type_identifier + + @property + def inherit_path(self): + """Gets the inherit_path of this ParentTypeInfo. # noqa: E501 + + + :return: The inherit_path of this ParentTypeInfo. # noqa: E501 + :rtype: list[int] + """ + return self._inherit_path + + @inherit_path.setter + def inherit_path(self, inherit_path): + """Sets the inherit_path of this ParentTypeInfo. + + + :param inherit_path: The inherit_path of this ParentTypeInfo. # noqa: E501 + :type: list[int] + """ + + self._inherit_path = inherit_path + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ParentTypeInfo): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ParentTypeInfo): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/project_schema.py b/knext/schema/rest/models/type/project_schema.py new file mode 100644 index 00000000..2b2b6c9a --- /dev/null +++ b/knext/schema/rest/models/type/project_schema.py @@ -0,0 +1,129 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ProjectSchema(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"spg_types": "list[BaseSpgType]"} + + attribute_map = {"spg_types": "spgTypes"} + + def __init__(self, spg_types=None, local_vars_configuration=None): # noqa: E501 + """ProjectSchema - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._spg_types = None + self.discriminator = None + + if spg_types is not None: + self.spg_types = spg_types + + @property + def spg_types(self): + """Gets the spg_types of this ProjectSchema. # noqa: E501 + + + :return: The spg_types of this ProjectSchema. # noqa: E501 + :rtype: list[BaseSpgType] + """ + return self._spg_types + + @spg_types.setter + def spg_types(self, spg_types): + """Sets the spg_types of this ProjectSchema. + + + :param spg_types: The spg_types of this ProjectSchema. # noqa: E501 + :type: list[BaseSpgType] + """ + + self._spg_types = spg_types + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ProjectSchema): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ProjectSchema): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/spg_type_advanced_config.py b/knext/schema/rest/models/type/spg_type_advanced_config.py new file mode 100644 index 00000000..c97a5034 --- /dev/null +++ b/knext/schema/rest/models/type/spg_type_advanced_config.py @@ -0,0 +1,218 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class SpgTypeAdvancedConfig(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "link_operator": "OperatorKey", + "fuse_operator": "OperatorKey", + "extract_operator": "OperatorKey", + "normalized_operator": "OperatorKey", + } + + attribute_map = { + "link_operator": "linkOperator", + "fuse_operator": "fuseOperator", + "extract_operator": "extractOperator", + "normalized_operator": "normalizedOperator", + } + + def __init__( + self, + link_operator=None, + fuse_operator=None, + extract_operator=None, + normalized_operator=None, + local_vars_configuration=None, + ): # noqa: E501 + """SpgTypeAdvancedConfig - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._link_operator = None + self._fuse_operator = None + self._extract_operator = None + self._normalized_operator = None + self.discriminator = None + + if link_operator is not None: + self.link_operator = link_operator + if fuse_operator is not None: + self.fuse_operator = fuse_operator + if extract_operator is not None: + self.extract_operator = extract_operator + if normalized_operator is not None: + self.normalized_operator = normalized_operator + + @property + def link_operator(self): + """Gets the link_operator of this SpgTypeAdvancedConfig. # noqa: E501 + + + :return: The link_operator of this SpgTypeAdvancedConfig. # noqa: E501 + :rtype: OperatorKey + """ + return self._link_operator + + @link_operator.setter + def link_operator(self, link_operator): + """Sets the link_operator of this SpgTypeAdvancedConfig. + + + :param link_operator: The link_operator of this SpgTypeAdvancedConfig. # noqa: E501 + :type: OperatorKey + """ + + self._link_operator = link_operator + + @property + def fuse_operator(self): + """Gets the fuse_operator of this SpgTypeAdvancedConfig. # noqa: E501 + + + :return: The fuse_operator of this SpgTypeAdvancedConfig. # noqa: E501 + :rtype: OperatorKey + """ + return self._fuse_operator + + @fuse_operator.setter + def fuse_operator(self, fuse_operator): + """Sets the fuse_operator of this SpgTypeAdvancedConfig. + + + :param fuse_operator: The fuse_operator of this SpgTypeAdvancedConfig. # noqa: E501 + :type: OperatorKey + """ + + self._fuse_operator = fuse_operator + + @property + def extract_operator(self): + """Gets the extract_operator of this SpgTypeAdvancedConfig. # noqa: E501 + + + :return: The extract_operator of this SpgTypeAdvancedConfig. # noqa: E501 + :rtype: OperatorKey + """ + return self._extract_operator + + @extract_operator.setter + def extract_operator(self, extract_operator): + """Sets the extract_operator of this SpgTypeAdvancedConfig. + + + :param extract_operator: The extract_operator of this SpgTypeAdvancedConfig. # noqa: E501 + :type: OperatorKey + """ + + self._extract_operator = extract_operator + + @property + def normalized_operator(self): + """Gets the normalized_operator of this SpgTypeAdvancedConfig. # noqa: E501 + + + :return: The normalized_operator of this SpgTypeAdvancedConfig. # noqa: E501 + :rtype: OperatorKey + """ + return self._normalized_operator + + @normalized_operator.setter + def normalized_operator(self, normalized_operator): + """Sets the normalized_operator of this SpgTypeAdvancedConfig. + + + :param normalized_operator: The normalized_operator of this SpgTypeAdvancedConfig. # noqa: E501 + :type: OperatorKey + """ + + self._normalized_operator = normalized_operator + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, SpgTypeAdvancedConfig): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, SpgTypeAdvancedConfig): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/spg_type_ref.py b/knext/schema/rest/models/type/spg_type_ref.py new file mode 100644 index 00000000..08959935 --- /dev/null +++ b/knext/schema/rest/models/type/spg_type_ref.py @@ -0,0 +1,171 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class SpgTypeRef(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"basic_info": "SpgTypeRefBasicInfo", "spg_type_enum": "str"} + + attribute_map = {"basic_info": "basicInfo", "spg_type_enum": "spgTypeEnum"} + + def __init__( + self, basic_info=None, spg_type_enum=None, local_vars_configuration=None + ): # noqa: E501 + """SpgTypeRef - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._basic_info = None + self._spg_type_enum = None + self.discriminator = None + + if basic_info is not None: + self.basic_info = basic_info + if spg_type_enum is not None: + self.spg_type_enum = spg_type_enum + + @property + def basic_info(self): + """Gets the basic_info of this SpgTypeRef. # noqa: E501 + + + :return: The basic_info of this SpgTypeRef. # noqa: E501 + :rtype: SpgTypeRefBasicInfo + """ + return self._basic_info + + @basic_info.setter + def basic_info(self, basic_info): + """Sets the basic_info of this SpgTypeRef. + + + :param basic_info: The basic_info of this SpgTypeRef. # noqa: E501 + :type: SpgTypeRefBasicInfo + """ + + self._basic_info = basic_info + + @property + def spg_type_enum(self): + """Gets the spg_type_enum of this SpgTypeRef. # noqa: E501 + + + :return: The spg_type_enum of this SpgTypeRef. # noqa: E501 + :rtype: str + """ + return self._spg_type_enum + + @spg_type_enum.setter + def spg_type_enum(self, spg_type_enum): + """Sets the spg_type_enum of this SpgTypeRef. + + + :param spg_type_enum: The spg_type_enum of this SpgTypeRef. # noqa: E501 + :type: str + """ + allowed_values = [ + "BASIC_TYPE", + "ENTITY_TYPE", + "CONCEPT_TYPE", + "EVENT_TYPE", + "STANDARD_TYPE", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and spg_type_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type_enum` ({0}), must be one of {1}".format( # noqa: E501 + spg_type_enum, allowed_values + ) + ) + + self._spg_type_enum = spg_type_enum + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, SpgTypeRef): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, SpgTypeRef): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/spg_type_ref_basic_info.py b/knext/schema/rest/models/type/spg_type_ref_basic_info.py new file mode 100644 index 00000000..70550e9f --- /dev/null +++ b/knext/schema/rest/models/type/spg_type_ref_basic_info.py @@ -0,0 +1,217 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class SpgTypeRefBasicInfo(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "name": "SpgTypeIdentifier", + "name_zh": "str", + "desc": "str", + "creator": "str", + } + + attribute_map = { + "name": "name", + "name_zh": "nameZh", + "desc": "desc", + "creator": "creator", + } + + def __init__( + self, + name=None, + name_zh=None, + desc=None, + creator=None, + local_vars_configuration=None, + ): # noqa: E501 + """SpgTypeRefBasicInfo - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._name = None + self._name_zh = None + self._desc = None + self._creator = None + self.discriminator = None + + self.name = name + if name_zh is not None: + self.name_zh = name_zh + if desc is not None: + self.desc = desc + if creator is not None: + self.creator = creator + + @property + def name(self): + """Gets the name of this SpgTypeRefBasicInfo. # noqa: E501 + + + :return: The name of this SpgTypeRefBasicInfo. # noqa: E501 + :rtype: SpgTypeIdentifier + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this SpgTypeRefBasicInfo. + + + :param name: The name of this SpgTypeRefBasicInfo. # noqa: E501 + :type: SpgTypeIdentifier + """ + + self._name = name + + @property + def name_zh(self): + """Gets the name_zh of this SpgTypeRefBasicInfo. # noqa: E501 + + + :return: The name_zh of this SpgTypeRefBasicInfo. # noqa: E501 + :rtype: str + """ + return self._name_zh + + @name_zh.setter + def name_zh(self, name_zh): + """Sets the name_zh of this SpgTypeRefBasicInfo. + + + :param name_zh: The name_zh of this SpgTypeRefBasicInfo. # noqa: E501 + :type: str + """ + + self._name_zh = name_zh + + @property + def desc(self): + """Gets the desc of this SpgTypeRefBasicInfo. # noqa: E501 + + + :return: The desc of this SpgTypeRefBasicInfo. # noqa: E501 + :rtype: str + """ + return self._desc + + @desc.setter + def desc(self, desc): + """Sets the desc of this SpgTypeRefBasicInfo. + + + :param desc: The desc of this SpgTypeRefBasicInfo. # noqa: E501 + :type: str + """ + + self._desc = desc + + @property + def creator(self): + """Gets the creator of this SpgTypeRefBasicInfo. # noqa: E501 + + + :return: The creator of this SpgTypeRefBasicInfo. # noqa: E501 + :rtype: str + """ + return self._creator + + @creator.setter + def creator(self, creator): + """Sets the creator of this SpgTypeRefBasicInfo. + + + :param creator: The creator of this SpgTypeRefBasicInfo. # noqa: E501 + :type: str + """ + + self._creator = creator + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, SpgTypeRefBasicInfo): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, SpgTypeRefBasicInfo): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/standard_type.py b/knext/schema/rest/models/type/standard_type.py new file mode 100644 index 00000000..33d7bd18 --- /dev/null +++ b/knext/schema/rest/models/type/standard_type.py @@ -0,0 +1,466 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class StandardType(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "basic_info": "StandardTypeBasicInfo", + "parent_type_info": "ParentTypeInfo", + "spg_type_enum": "str", + "properties": "list[Property]", + "relations": "list[Relation]", + "advanced_config": "SpgTypeAdvancedConfig", + "project_id": "int", + "ontology_id": "OntologyId", + "alter_operation": "str", + "ext_info": "object", + "spreadable": "bool", + "constraint_items": "list[BaseConstraintItem]", + } + + attribute_map = { + "basic_info": "basicInfo", + "parent_type_info": "parentTypeInfo", + "spg_type_enum": "spgTypeEnum", + "properties": "properties", + "relations": "relations", + "advanced_config": "advancedConfig", + "project_id": "projectId", + "ontology_id": "ontologyId", + "alter_operation": "alterOperation", + "ext_info": "extInfo", + "spreadable": "spreadable", + "constraint_items": "constraintItems", + } + + def __init__( + self, + basic_info=None, + parent_type_info=None, + spg_type_enum="STANDARD_TYPE", + properties=None, + relations=None, + advanced_config=None, + project_id=None, + ontology_id=None, + alter_operation=None, + ext_info=None, + spreadable=None, + constraint_items=None, + local_vars_configuration=None, + ): # noqa: E501 + """StandardType - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._basic_info = None + self._parent_type_info = None + self._spg_type_enum = None + self._properties = None + self._relations = None + self._advanced_config = None + self._project_id = None + self._ontology_id = None + self._alter_operation = None + self._ext_info = None + self._spreadable = None + self._constraint_items = None + self.discriminator = spg_type_enum + + if basic_info is not None: + self.basic_info = basic_info + if parent_type_info is not None: + self.parent_type_info = parent_type_info + self.spg_type_enum = spg_type_enum + if properties is not None: + self.properties = properties + if relations is not None: + self.relations = relations + if advanced_config is not None: + self.advanced_config = advanced_config + if project_id is not None: + self.project_id = project_id + if ontology_id is not None: + self.ontology_id = ontology_id + if alter_operation is not None: + self.alter_operation = alter_operation + if ext_info is not None: + self.ext_info = ext_info + if spreadable is not None: + self.spreadable = spreadable + if constraint_items is not None: + self.constraint_items = constraint_items + + @property + def basic_info(self): + """Gets the basic_info of this StandardType. # noqa: E501 + + + :return: The basic_info of this StandardType. # noqa: E501 + :rtype: StandardTypeBasicInfo + """ + return self._basic_info + + @basic_info.setter + def basic_info(self, basic_info): + """Sets the basic_info of this StandardType. + + + :param basic_info: The basic_info of this StandardType. # noqa: E501 + :type: StandardTypeBasicInfo + """ + + self._basic_info = basic_info + + @property + def parent_type_info(self): + """Gets the parent_type_info of this StandardType. # noqa: E501 + + + :return: The parent_type_info of this StandardType. # noqa: E501 + :rtype: ParentTypeInfo + """ + return self._parent_type_info + + @parent_type_info.setter + def parent_type_info(self, parent_type_info): + """Sets the parent_type_info of this StandardType. + + + :param parent_type_info: The parent_type_info of this StandardType. # noqa: E501 + :type: ParentTypeInfo + """ + + self._parent_type_info = parent_type_info + + @property + def spg_type_enum(self): + """Gets the spg_type_enum of this StandardType. # noqa: E501 + + + :return: The spg_type_enum of this StandardType. # noqa: E501 + :rtype: str + """ + return self._spg_type_enum + + @spg_type_enum.setter + def spg_type_enum(self, spg_type_enum): + """Sets the spg_type_enum of this StandardType. + + + :param spg_type_enum: The spg_type_enum of this StandardType. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and spg_type_enum is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type_enum`, must not be `None`" + ) # noqa: E501 + allowed_values = [ + "BASIC_TYPE", + "ENTITY_TYPE", + "CONCEPT_TYPE", + "EVENT_TYPE", + "STANDARD_TYPE", + ] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and spg_type_enum not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `spg_type_enum` ({0}), must be one of {1}".format( # noqa: E501 + spg_type_enum, allowed_values + ) + ) + + self._spg_type_enum = spg_type_enum + + @property + def properties(self): + """Gets the properties of this StandardType. # noqa: E501 + + + :return: The properties of this StandardType. # noqa: E501 + :rtype: list[Property] + """ + return self._properties + + @properties.setter + def properties(self, properties): + """Sets the properties of this StandardType. + + + :param properties: The properties of this StandardType. # noqa: E501 + :type: list[Property] + """ + + self._properties = properties + + @property + def relations(self): + """Gets the relations of this StandardType. # noqa: E501 + + + :return: The relations of this StandardType. # noqa: E501 + :rtype: list[Relation] + """ + return self._relations + + @relations.setter + def relations(self, relations): + """Sets the relations of this StandardType. + + + :param relations: The relations of this StandardType. # noqa: E501 + :type: list[Relation] + """ + + self._relations = relations + + @property + def advanced_config(self): + """Gets the advanced_config of this StandardType. # noqa: E501 + + + :return: The advanced_config of this StandardType. # noqa: E501 + :rtype: SpgTypeAdvancedConfig + """ + return self._advanced_config + + @advanced_config.setter + def advanced_config(self, advanced_config): + """Sets the advanced_config of this StandardType. + + + :param advanced_config: The advanced_config of this StandardType. # noqa: E501 + :type: SpgTypeAdvancedConfig + """ + + self._advanced_config = advanced_config + + @property + def project_id(self): + """Gets the project_id of this StandardType. # noqa: E501 + + + :return: The project_id of this StandardType. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this StandardType. + + + :param project_id: The project_id of this StandardType. # noqa: E501 + :type: int + """ + + self._project_id = project_id + + @property + def ontology_id(self): + """Gets the ontology_id of this StandardType. # noqa: E501 + + + :return: The ontology_id of this StandardType. # noqa: E501 + :rtype: OntologyId + """ + return self._ontology_id + + @ontology_id.setter + def ontology_id(self, ontology_id): + """Sets the ontology_id of this StandardType. + + + :param ontology_id: The ontology_id of this StandardType. # noqa: E501 + :type: OntologyId + """ + + self._ontology_id = ontology_id + + @property + def alter_operation(self): + """Gets the alter_operation of this StandardType. # noqa: E501 + + + :return: The alter_operation of this StandardType. # noqa: E501 + :rtype: str + """ + return self._alter_operation + + @alter_operation.setter + def alter_operation(self, alter_operation): + """Sets the alter_operation of this StandardType. + + + :param alter_operation: The alter_operation of this StandardType. # noqa: E501 + :type: str + """ + allowed_values = ["CREATE", "UPDATE", "DELETE"] # noqa: E501 + if ( + self.local_vars_configuration.client_side_validation + and alter_operation not in allowed_values + ): # noqa: E501 + raise ValueError( + "Invalid value for `alter_operation` ({0}), must be one of {1}".format( # noqa: E501 + alter_operation, allowed_values + ) + ) + + self._alter_operation = alter_operation + + @property + def ext_info(self): + """Gets the ext_info of this StandardType. # noqa: E501 + + + :return: The ext_info of this StandardType. # noqa: E501 + :rtype: object + """ + return self._ext_info + + @ext_info.setter + def ext_info(self, ext_info): + """Sets the ext_info of this StandardType. + + + :param ext_info: The ext_info of this StandardType. # noqa: E501 + :type: object + """ + + self._ext_info = ext_info + + @property + def spreadable(self): + """Gets the spreadable of this StandardType. # noqa: E501 + + + :return: The spreadable of this StandardType. # noqa: E501 + :rtype: bool + """ + return self._spreadable + + @spreadable.setter + def spreadable(self, spreadable): + """Sets the spreadable of this StandardType. + + + :param spreadable: The spreadable of this StandardType. # noqa: E501 + :type: bool + """ + + self._spreadable = spreadable + + @property + def constraint_items(self): + """Gets the constraint_items of this StandardType. # noqa: E501 + + + :return: The constraint_items of this StandardType. # noqa: E501 + :rtype: list[BaseConstraintItem] + """ + return self._constraint_items + + @constraint_items.setter + def constraint_items(self, constraint_items): + """Sets the constraint_items of this StandardType. + + + :param constraint_items: The constraint_items of this StandardType. # noqa: E501 + :type: list[BaseConstraintItem] + """ + + self._constraint_items = constraint_items + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, StandardType): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, StandardType): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/type/standard_type_basic_info.py b/knext/schema/rest/models/type/standard_type_basic_info.py new file mode 100644 index 00000000..2ea0f824 --- /dev/null +++ b/knext/schema/rest/models/type/standard_type_basic_info.py @@ -0,0 +1,218 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class StandardTypeBasicInfo(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "name": "SpgTypeIdentifier", + "name_zh": "str", + "desc": "str", + "creator": "str", + } + + attribute_map = { + "name": "name", + "name_zh": "nameZh", + "desc": "desc", + "creator": "creator", + } + + def __init__( + self, + name=None, + name_zh=None, + desc=None, + creator=None, + local_vars_configuration=None, + ): # noqa: E501 + """StandardTypeBasicInfo - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._name = None + self._name_zh = None + self._desc = None + self._creator = None + self.discriminator = None + + if name is not None: + self.name = name + if name_zh is not None: + self.name_zh = name_zh + if desc is not None: + self.desc = desc + if creator is not None: + self.creator = creator + + @property + def name(self): + """Gets the name of this StandardTypeBasicInfo. # noqa: E501 + + + :return: The name of this StandardTypeBasicInfo. # noqa: E501 + :rtype: SpgTypeIdentifier + """ + return self._name + + @name.setter + def name(self, name): + """Sets the name of this StandardTypeBasicInfo. + + + :param name: The name of this StandardTypeBasicInfo. # noqa: E501 + :type: SpgTypeIdentifier + """ + + self._name = name + + @property + def name_zh(self): + """Gets the name_zh of this StandardTypeBasicInfo. # noqa: E501 + + + :return: The name_zh of this StandardTypeBasicInfo. # noqa: E501 + :rtype: str + """ + return self._name_zh + + @name_zh.setter + def name_zh(self, name_zh): + """Sets the name_zh of this StandardTypeBasicInfo. + + + :param name_zh: The name_zh of this StandardTypeBasicInfo. # noqa: E501 + :type: str + """ + + self._name_zh = name_zh + + @property + def desc(self): + """Gets the desc of this StandardTypeBasicInfo. # noqa: E501 + + + :return: The desc of this StandardTypeBasicInfo. # noqa: E501 + :rtype: str + """ + return self._desc + + @desc.setter + def desc(self, desc): + """Sets the desc of this StandardTypeBasicInfo. + + + :param desc: The desc of this StandardTypeBasicInfo. # noqa: E501 + :type: str + """ + + self._desc = desc + + @property + def creator(self): + """Gets the creator of this StandardTypeBasicInfo. # noqa: E501 + + + :return: The creator of this StandardTypeBasicInfo. # noqa: E501 + :rtype: str + """ + return self._creator + + @creator.setter + def creator(self, creator): + """Sets the creator of this StandardTypeBasicInfo. + + + :param creator: The creator of this StandardTypeBasicInfo. # noqa: E501 + :type: str + """ + + self._creator = creator + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, StandardTypeBasicInfo): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, StandardTypeBasicInfo): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/models/user_info.py b/knext/schema/rest/models/user_info.py new file mode 100644 index 00000000..5624f41f --- /dev/null +++ b/knext/schema/rest/models/user_info.py @@ -0,0 +1,155 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class UserInfo(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"user_id": "str", "nick_name": "str"} + + attribute_map = {"user_id": "userId", "nick_name": "nickName"} + + def __init__( + self, user_id=None, nick_name=None, local_vars_configuration=None + ): # noqa: E501 + """UserInfo - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._user_id = None + self._nick_name = None + self.discriminator = None + + if user_id is not None: + self.user_id = user_id + if nick_name is not None: + self.nick_name = nick_name + + @property + def user_id(self): + """Gets the user_id of this UserInfo. # noqa: E501 + + + :return: The user_id of this UserInfo. # noqa: E501 + :rtype: str + """ + return self._user_id + + @user_id.setter + def user_id(self, user_id): + """Sets the user_id of this UserInfo. + + + :param user_id: The user_id of this UserInfo. # noqa: E501 + :type: str + """ + + self._user_id = user_id + + @property + def nick_name(self): + """Gets the nick_name of this UserInfo. # noqa: E501 + + + :return: The nick_name of this UserInfo. # noqa: E501 + :rtype: str + """ + return self._nick_name + + @nick_name.setter + def nick_name(self, nick_name): + """Sets the nick_name of this UserInfo. + + + :param nick_name: The nick_name of this UserInfo. # noqa: E501 + :type: str + """ + + self._nick_name = nick_name + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, UserInfo): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, UserInfo): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/schema/rest/schema_api.py b/knext/schema/rest/schema_api.py new file mode 100644 index 00000000..f5a8b369 --- /dev/null +++ b/knext/schema/rest/schema_api.py @@ -0,0 +1,571 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import re # noqa: F401 + +# python 2 and python 3 compatibility library +import six + +from knext.common.rest.api_client import ApiClient +from knext.common.rest.exceptions import ApiTypeError, ApiValueError # noqa: F401 + + +class SchemaApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def schema_alter_schema_post(self, **kwargs): # noqa: E501 + """alter_schema # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.schema_alter_schema_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param SchemaAlterRequest schema_alter_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: object + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.schema_alter_schema_post_with_http_info(**kwargs) # noqa: E501 + + def schema_alter_schema_post_with_http_info(self, **kwargs): # noqa: E501 + """alter_schema # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.schema_alter_schema_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param SchemaAlterRequest schema_alter_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["schema_alter_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method schema_alter_schema_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "schema_alter_request" in local_var_params: + body_params = local_var_params["schema_alter_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/schema/alterSchema", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="object", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def schema_query_project_schema_get(self, project_id, **kwargs): # noqa: E501 + """query_project_schema # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.schema_query_project_schema_get(project_id, async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param int project_id: (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: ProjectSchema + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.schema_query_project_schema_get_with_http_info( + project_id, **kwargs + ) # noqa: E501 + + def schema_query_project_schema_get_with_http_info( + self, project_id, **kwargs + ): # noqa: E501 + """query_project_schema # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.schema_query_project_schema_get_with_http_info(project_id, async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param int project_id: (required) + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(ProjectSchema, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["project_id"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method schema_query_project_schema_get" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + # verify the required parameter 'project_id' is set + if self.api_client.client_side_validation and ( + "project_id" not in local_var_params + or local_var_params["project_id"] is None # noqa: E501 + ): # noqa: E501 + raise ApiValueError( + "Missing the required parameter `project_id` when calling `schema_query_project_schema_get`" + ) # noqa: E501 + + collection_formats = {} + + path_params = {} + + query_params = [] + if ( + "project_id" in local_var_params + and local_var_params["project_id"] is not None + ): # noqa: E501 + query_params.append( + ("projectId", local_var_params["project_id"]) + ) # noqa: E501 + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/schema/queryProjectSchema", + "GET", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="ProjectSchema", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def schema_query_relation_get( + self, s_name, relation, o_name, **kwargs + ): # noqa: E501 + """query_relation # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.schema_query_relation_get(s_name, relation, o_name, async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param str s_name: (required) + :param str relation: (required) + :param str o_name: (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Relation + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.schema_query_relation_get_with_http_info( + s_name, relation, o_name, **kwargs + ) # noqa: E501 + + def schema_query_relation_get_with_http_info( + self, s_name, relation, o_name, **kwargs + ): # noqa: E501 + """query_relation # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.schema_query_relation_get_with_http_info(s_name, relation, o_name, async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param str s_name: (required) + :param str relation: (required) + :param str o_name: (required) + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(Relation, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["s_name", "relation", "o_name"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method schema_query_relation_get" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + # verify the required parameter 's_name' is set + if self.api_client.client_side_validation and ( + "s_name" not in local_var_params + or local_var_params["s_name"] is None # noqa: E501 + ): # noqa: E501 + raise ApiValueError( + "Missing the required parameter `s_name` when calling `schema_query_relation_get`" + ) # noqa: E501 + # verify the required parameter 'relation' is set + if self.api_client.client_side_validation and ( + "relation" not in local_var_params + or local_var_params["relation"] is None # noqa: E501 + ): # noqa: E501 + raise ApiValueError( + "Missing the required parameter `relation` when calling `schema_query_relation_get`" + ) # noqa: E501 + # verify the required parameter 'o_name' is set + if self.api_client.client_side_validation and ( + "o_name" not in local_var_params + or local_var_params["o_name"] is None # noqa: E501 + ): # noqa: E501 + raise ApiValueError( + "Missing the required parameter `o_name` when calling `schema_query_relation_get`" + ) # noqa: E501 + + collection_formats = {} + + path_params = {} + + query_params = [] + if ( + "s_name" in local_var_params and local_var_params["s_name"] is not None + ): # noqa: E501 + query_params.append(("sName", local_var_params["s_name"])) # noqa: E501 + if ( + "relation" in local_var_params and local_var_params["relation"] is not None + ): # noqa: E501 + query_params.append( + ("relation", local_var_params["relation"]) + ) # noqa: E501 + if ( + "o_name" in local_var_params and local_var_params["o_name"] is not None + ): # noqa: E501 + query_params.append(("oName", local_var_params["o_name"])) # noqa: E501 + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/schema/queryRelation", + "GET", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="Relation", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def schema_query_spg_type_get(self, name, **kwargs): # noqa: E501 + """query_spg_type # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.schema_query_spg_type_get(name, async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param str name: 实体类型名称 (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: BaseSpgType + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.schema_query_spg_type_get_with_http_info( + name, **kwargs + ) # noqa: E501 + + def schema_query_spg_type_get_with_http_info(self, name, **kwargs): # noqa: E501 + """query_spg_type # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.schema_query_spg_type_get_with_http_info(name, async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param str name: 实体类型名称 (required) + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(BaseSpgType, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["name"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method schema_query_spg_type_get" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + # verify the required parameter 'name' is set + if self.api_client.client_side_validation and ( + "name" not in local_var_params + or local_var_params["name"] is None # noqa: E501 + ): # noqa: E501 + raise ApiValueError( + "Missing the required parameter `name` when calling `schema_query_spg_type_get`" + ) # noqa: E501 + + collection_formats = {} + + path_params = {} + + query_params = [] + if ( + "name" in local_var_params and local_var_params["name"] is not None + ): # noqa: E501 + query_params.append(("name", local_var_params["name"])) # noqa: E501 + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/schema/querySpgType", + "GET", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="BaseSpgType", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) diff --git a/knext/search/__init__.py b/knext/search/__init__.py new file mode 100644 index 00000000..936aa95d --- /dev/null +++ b/knext/search/__init__.py @@ -0,0 +1,36 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +# flake8: noqa + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +__version__ = "1.0.0" + +# import models into model package +from knext.search.rest.models.idx_record import IdxRecord +from knext.search.rest.models.text_search_request import TextSearchRequest +from knext.search.rest.models.vector_search_request import VectorSearchRequest + +# import apis into sdk package +from knext.search.rest.search_api import SearchApi diff --git a/knext/search/client.py b/knext/search/client.py new file mode 100644 index 00000000..4b28fe13 --- /dev/null +++ b/knext/search/client.py @@ -0,0 +1,827 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. + +from knext.common.base.client import Client +from knext.common.rest import Configuration, ApiClient + +from knext.search import rest, TextSearchRequest, VectorSearchRequest, IdxRecord + + +def idx_record_to_dict(record: IdxRecord): + return {"score": record.score, "node": record.fields} + + +class SearchClient(Client): + """ """ + + def __init__(self, host_addr: str = None, project_id: int = None): + super().__init__(host_addr, project_id) + self._rest_client: rest.SearchApi = rest.SearchApi( + api_client=ApiClient(configuration=Configuration(host=host_addr)) + ) + + def search_text(self, query_string, label_constraints=None, topk=10, params=None): + req = TextSearchRequest( + self._project_id, query_string, label_constraints, topk, params + ) + records = self._rest_client.search_text_post(text_search_request=req) + return [idx_record_to_dict(record) for record in records] + + def search_vector( + self, label, property_key, query_vector, topk=10, ef_search=None, params=None + ): + req = VectorSearchRequest( + self._project_id, label, property_key, query_vector, ef_search, topk, params + ) + records = self._rest_client.search_vector_post(vector_search_request=req) + return [idx_record_to_dict(record) for record in records] + + +if __name__ == "__main__": + sc = SearchClient("http://127.0.0.1:8887", 4) + a = sc.search_text("Depressive_or_psychotic_symptoms") + print(a) + + b = sc.search_vector( + "Entity", + "name", + [ + -0.011183402, + 0.048467062, + 0.034121536, + -0.012637187, + -0.0063864742, + -0.018192118, + -0.005130675, + 0.0001195873, + -0.050548747, + 0.0039880113, + -0.00019851669, + -0.021597484, + 0.072632715, + -0.015092217, + 0.06702121, + 0.004932689, + -0.021484349, + -0.0026530172, + 0.016630854, + 0.018146865, + 0.018237373, + -0.014526542, + 0.020669777, + 0.0030574752, + -0.019221647, + 0.0034647614, + 0.033148576, + 0.061771747, + -0.03303544, + -0.016314076, + 0.025297001, + 0.015963357, + 0.009311016, + -0.0052918927, + -0.022242354, + 0.015578698, + 0.011652912, + -0.013349937, + 0.030546468, + 0.057246342, + -0.009090402, + -0.018565465, + -0.0309085, + -0.04023083, + 0.03461933, + -0.016913692, + 0.060640395, + -0.012625873, + 0.043715388, + -0.024731325, + 0.009678705, + 0.1618284, + 0.011992317, + 0.010945817, + -0.022038711, + -0.023894126, + -0.0048025837, + -0.01371197, + -0.047697745, + -0.005190071, + -0.05122756, + -0.0063864742, + 0.054576356, + -0.060957175, + 0.010363172, + -0.031247905, + -0.011058953, + -0.023758363, + -0.030636976, + -0.051996876, + -0.023215316, + 0.0064260717, + -0.032243494, + -0.035275515, + -0.0061488906, + 0.0029556535, + 0.006584461, + 0.042787682, + -0.036836777, + 0.01242223, + -0.007042658, + 0.04009507, + -0.0143568395, + -0.0052324967, + -0.0010097305, + -0.023894126, + -0.010555502, + -0.018655973, + 0.038058635, + -0.054576356, + -0.06602562, + -0.005246639, + -0.0036882032, + -0.034822974, + 0.018622031, + 0.02393938, + -0.022445997, + -0.0119583765, + 0.0062789964, + 0.015080905, + -0.07552897, + 0.0048110685, + 0.035252888, + 0.0027322117, + 0.10019241, + 0.020352999, + 0.028012242, + 0.014243705, + 0.003965384, + 0.0031508117, + -0.030999009, + 0.037787113, + -0.007297212, + 0.008162695, + -0.00044122676, + -0.017603816, + -0.004002153, + -0.025093358, + -0.03016181, + -0.0061262636, + 0.0011143804, + -0.005190071, + 0.024595562, + 0.0139043, + 0.008575638, + -0.0051023914, + 0.018124238, + -0.008784938, + 0.01738886, + 0.03439306, + -0.054123815, + 0.048602823, + -0.08019014, + 0.018610718, + -0.012886084, + 0.026269963, + -0.03355586, + -0.007263271, + 0.010397113, + -0.05407856, + 0.033171203, + -0.026496232, + -0.037108302, + -0.048467062, + -0.016438525, + 0.014741499, + -0.0015414653, + 0.058015663, + -0.008151381, + -0.013474386, + -0.039122105, + 0.07534795, + 0.026043693, + -0.0065901177, + 0.0059452476, + 0.039733034, + -0.019889144, + 0.040660743, + 0.00012612792, + 0.010838339, + -0.040615488, + -0.027356058, + 0.0033063723, + -0.046430632, + 0.020601895, + -0.030863246, + -0.040570233, + 0.04742622, + -0.005068451, + -0.0865257, + 0.028894696, + -0.016596913, + -0.02477658, + 0.04136218, + -0.021280706, + -0.029369863, + 0.0030631318, + 0.032854423, + 0.025568524, + 0.016461153, + -0.03620322, + -0.051861115, + -0.014933828, + -0.0053512887, + 0.00020894632, + -0.015273234, + -0.021427782, + -0.012546679, + -0.01413057, + -0.024867088, + -0.032243494, + -0.010572472, + -0.026269963, + -0.022525191, + 0.019108513, + 0.017400173, + 0.006923866, + 0.00007247715, + -0.0016263166, + 0.032990184, + 0.0041407435, + 0.036768895, + 0.013915613, + 0.032944933, + 0.0150469635, + 0.009593854, + 0.034506194, + 0.0056284694, + 0.06616139, + 0.03409891, + -0.008536041, + -0.025206493, + 0.0108213695, + 0.006233742, + -0.03545653, + 0.035094496, + -0.010040737, + 0.07960183, + -0.016585601, + 0.042448275, + -0.0056058425, + -0.040887013, + 0.010159529, + 0.04968892, + -0.04756198, + -0.046611648, + -0.07955658, + 0.023984633, + -0.0057048355, + -0.053082973, + -0.035049245, + 0.0584682, + 0.008077844, + 0.043805897, + -0.11268253, + -0.03636161, + -0.007410347, + -0.0051844143, + -0.011375731, + 0.026405724, + 0.0578799, + 0.037606094, + 0.020816851, + -0.020058848, + -0.021597484, + 0.08172877, + 0.03925787, + -0.00016272004, + -0.03029757, + -0.029980792, + -0.04733571, + -0.04152057, + -0.011579374, + 0.008943327, + -0.036044832, + -0.005399371, + 0.041407432, + -0.03998193, + 0.06054989, + 0.045502923, + 0.02597581, + -0.0061206073, + 0.042923443, + -0.007772379, + -0.03371425, + 0.009639108, + 0.026564114, + -0.022445997, + -0.023826245, + 0.06150022, + -0.042312514, + 0.021529604, + 0.053309243, + 0.00052537094, + -0.057382107, + 0.03332959, + 0.03656525, + -0.014311586, + 0.061817, + 0.016212255, + -0.032628153, + 0.01829394, + -0.013892986, + 0.023396332, + 0.0780632, + 0.015431623, + -0.019889144, + -0.0046130824, + -0.08014488, + 0.014775439, + 0.006165861, + -0.067383245, + -0.015205353, + -0.044258438, + 0.3663766, + -0.008886759, + 0.013349937, + 0.034121536, + 0.07380932, + 0.10245512, + 0.033306964, + -0.057291597, + -0.012094138, + 0.016596913, + 0.022276293, + 0.044824112, + -0.067202225, + 0.05810617, + -0.033306964, + -0.060414124, + -0.0078968275, + 0.019425292, + 0.06236005, + -0.004941174, + 0.019119825, + -0.060730904, + -0.04029871, + -0.04652114, + -0.044778857, + -0.0013851975, + 0.005037339, + 0.022389429, + 0.024686072, + 0.0023970492, + -0.06394394, + -0.018916182, + -0.06398919, + -0.023645228, + -0.03461933, + 0.025025476, + -0.032605525, + 0.0009072018, + 0.02681301, + 0.026473606, + 0.017569875, + 0.04235777, + 0.03636161, + -0.05005095, + 0.010923191, + -0.03265078, + -0.0086718025, + 0.014945142, + 0.017400173, + -0.037900247, + -0.04258404, + 0.047018934, + -0.026315216, + -0.07996386, + -0.007336809, + -0.037809737, + -0.027310805, + 0.017728265, + 0.031881463, + -0.018237373, + 0.011415328, + 0.009876691, + -0.019447917, + -0.014741499, + 0.026699875, + 0.025319628, + -0.0006328493, + 0.0016150031, + -0.045050383, + 0.0023121978, + -0.07783692, + 0.025319628, + 0.051770605, + 0.018112924, + -0.030931126, + -0.028691053, + 0.02742394, + -0.015895477, + 0.008179666, + 0.027514448, + 0.011664225, + 0.0066636554, + 0.061817, + -0.046928424, + 0.038398042, + -0.05240416, + 0.013564894, + 0.06394394, + -0.009186568, + -0.03167782, + 0.00077921775, + -0.008009963, + 0.05014146, + -0.05552669, + -0.019436603, + 0.011211685, + -0.08810959, + -0.0390316, + 0.03068223, + -0.03278654, + -0.007274585, + -0.05765363, + 0.02681301, + -0.063129365, + 0.027695464, + 0.011217342, + -0.0151261585, + -0.030704856, + 0.04801452, + -0.00025844292, + -0.07684134, + 0.019481858, + -0.007201047, + 0.044756234, + 0.008043903, + -0.03771923, + 0.024233531, + -0.0018893556, + -0.01461705, + -0.0039455853, + -0.012286468, + 0.00030175244, + -0.01803373, + -0.04742622, + 0.029505625, + -0.00141136, + 0.026473606, + 0.06294835, + 0.04294607, + -0.00675982, + 0.09955886, + 0.010204783, + -0.034868225, + 0.043443866, + 0.032854423, + 0.008383309, + 0.03545653, + 0.03385001, + -0.0012734766, + 0.01810161, + 0.012625873, + 0.04097752, + -0.009627794, + -0.03172307, + 0.055798214, + -0.017830087, + -0.036248475, + 0.0139043, + 0.03197197, + -0.007240644, + 0.010827025, + 0.018078983, + 0.03226612, + 0.042674545, + -0.006601431, + 0.02235549, + -0.02207265, + -0.0020986556, + -0.000473046, + -0.06973645, + -0.01806767, + -0.07009849, + -0.01935741, + 0.042900816, + -0.0105385315, + 0.00011941053, + -0.021156257, + -0.01810161, + 0.014662305, + -0.0021962344, + 0.016076492, + 0.022672268, + 0.007093569, + -0.015476877, + -0.0032582898, + 0.055164658, + 0.05036773, + -0.039710406, + 0.024052516, + -0.024731325, + -0.033872638, + -0.014175824, + 0.013474386, + -0.01965156, + -0.014911202, + -0.055436183, + -0.024889715, + 0.032922305, + 0.0075800493, + 0.006918209, + 0.00077002554, + -0.022445997, + -0.078923024, + -0.019843891, + -0.055798214, + 0.06598037, + 0.016540347, + -0.027175043, + 0.0038098234, + -0.045570806, + 0.018146865, + -0.0064600124, + 0.0567938, + -0.021699306, + -0.015861535, + -0.05819668, + -0.013530954, + 0.06226954, + 0.043013953, + -0.021665365, + -0.047516726, + -0.020047534, + -0.0015980328, + 0.061002426, + 0.0012579205, + 0.029053085, + -0.01461705, + -0.0130557865, + -0.042516157, + 0.035411276, + 0.09539549, + -0.03029757, + 0.035637546, + -0.018146865, + 0.055571944, + -0.024233531, + 0.008722713, + -0.0018002618, + 0.050096206, + 0.0073198387, + -0.001998248, + -0.027242923, + 0.020805538, + -0.0052975495, + 0.027831227, + 0.027446566, + 0.023147434, + -0.019662874, + -0.03242451, + -0.04543504, + 0.014832007, + -0.041837346, + 0.0089546405, + -0.0054559386, + 0.053173482, + -0.0069634635, + -0.017852712, + -0.011845241, + -0.020126728, + -0.043534372, + -0.027740719, + 0.004106803, + -0.041475315, + 0.01583891, + 0.045344535, + -0.0021396668, + -0.0069747767, + -0.04566131, + 0.07186339, + 0.030659603, + -0.01603124, + -0.028781561, + -0.0348456, + 0.055888724, + -0.0020675433, + -0.027582329, + -0.017535934, + 0.007619647, + -0.025274374, + -0.016076492, + -0.012014944, + -0.009514659, + 0.01887093, + 0.025591152, + 0.015352428, + -0.018836988, + 0.04577445, + -0.0031790955, + -0.044281065, + 0.004760158, + -0.023351077, + 0.020375626, + 0.024957595, + -0.012229901, + 0.0065052663, + 0.011460582, + 0.0087509975, + -0.04710944, + 0.0032158643, + 0.012478798, + -0.02355472, + -0.010866623, + -0.051091794, + -0.03977829, + 0.005023197, + -0.039959304, + -0.021755872, + 0.0483313, + 0.06249581, + -0.00003367536, + -0.0027039282, + -0.016404584, + 0.006239399, + -0.0155334445, + -0.013372565, + 0.023170061, + -0.006782447, + -0.016234882, + -0.015363742, + -0.011256939, + -0.0020788568, + -0.010006797, + 0.019538425, + -0.026405724, + 0.023848873, + -0.04733571, + -0.030116554, + -0.0038777043, + 0.039371002, + 0.02584005, + 0.026835637, + 0.054802626, + -0.029369863, + -0.004533888, + -0.014741499, + -0.041565824, + 0.008089157, + -0.03550178, + 0.032447137, + 0.016008612, + -0.020386938, + 0.008960297, + 0.024663445, + 0.05023197, + -0.031021634, + -0.010793085, + -0.0024946283, + -0.01780746, + 0.027310805, + 0.050865527, + 0.0078742, + 0.0011355932, + -0.02961876, + -0.022830656, + -0.008202292, + 0.007432974, + -0.007268928, + -0.07602677, + -0.015567385, + -0.04910062, + -0.024980223, + -0.009876691, + -0.016189627, + 0.041090656, + 0.016404584, + -0.032356627, + 0.023577347, + -0.0186786, + 0.053309243, + 0.02200477, + -0.0068899253, + 0.024143023, + 0.026383096, + 0.006748507, + -0.015646579, + -0.018508896, + 0.02207265, + 0.031655192, + -0.008321084, + -0.0070256875, + -0.0060640397, + -0.07317576, + 0.022943791, + -0.045095637, + 0.037108302, + 0.013530954, + -0.054666862, + -0.054983642, + -0.0038692192, + -0.002036431, + -0.012761636, + 0.023962006, + 0.020239864, + 0.039506763, + 0.030342825, + -0.047245204, + -0.019187707, + -0.052901957, + 0.032152984, + -0.08838111, + -0.048919603, + -0.08883365, + -0.0133386245, + 0.016314076, + -0.0034195073, + -0.03464196, + -0.014741499, + 0.0072180172, + 0.01284083, + -0.034958735, + -0.021122316, + 0.057698883, + -0.014933828, + 0.07765591, + 0.003131013, + 0.018904869, + 0.018022416, + -0.0060923235, + -0.0052070413, + -0.041859973, + -0.028215885, + -0.037176184, + 0.025319628, + 0.012625873, + 0.0026077633, + -0.045344535, + -0.00400781, + -0.020149356, + 0.027061908, + 0.035999577, + 0.0059565613, + -0.0019402663, + -0.037085675, + 0.046475884, + 0.011562403, + 0.028826814, + -0.0086718025, + -0.016925005, + -0.028306393, + -0.036022205, + -0.007676214, + 0.05416907, + -0.005586044, + 0.002853832, + 0.0011942821, + -0.02461819, + -0.029867657, + 0.018927496, + -0.055662453, + -0.009118686, + 0.006256369, + -0.019764695, + 0.0011773118, + 0.06607088, + -0.03642949, + 0.029188847, + -0.10752357, + 0.019187707, + 0.021687992, + -0.027921734, + 0.017309666, + -0.021993456, + 0.0015895477, + -0.03658788, + -0.03303544, + -0.023192689, + 0.014277645, + -0.012026258, + 0.053354498, + -0.0013738839, + 0.041407432, + -0.047018934, + 0.028804189, + -0.010029424, + -0.00004401661, + 0.009769212, + -0.0004963801, + -0.018689914, + -0.0011886252, + 0.027491821, + -0.009254448, + -0.03468721, + 0.0139495535, + -0.026315216, + ], + ) + print(b) diff --git a/knext/search/rest/__init__.py b/knext/search/rest/__init__.py new file mode 100644 index 00000000..936aa95d --- /dev/null +++ b/knext/search/rest/__init__.py @@ -0,0 +1,36 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +# flake8: noqa + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +__version__ = "1.0.0" + +# import models into model package +from knext.search.rest.models.idx_record import IdxRecord +from knext.search.rest.models.text_search_request import TextSearchRequest +from knext.search.rest.models.vector_search_request import VectorSearchRequest + +# import apis into sdk package +from knext.search.rest.search_api import SearchApi diff --git a/knext/search/rest/models/__init__.py b/knext/search/rest/models/__init__.py new file mode 100644 index 00000000..34634808 --- /dev/null +++ b/knext/search/rest/models/__init__.py @@ -0,0 +1,21 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +# flake8: noqa + +from __future__ import absolute_import + +# import models into model package +from knext.search.rest.models.idx_record import IdxRecord +from knext.search.rest.models.text_search_request import TextSearchRequest +from knext.search.rest.models.vector_search_request import VectorSearchRequest diff --git a/knext/search/rest/models/idx_record.py b/knext/search/rest/models/idx_record.py new file mode 100644 index 00000000..01601bfa --- /dev/null +++ b/knext/search/rest/models/idx_record.py @@ -0,0 +1,226 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class IdxRecord(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "idx_name": "str", + "doc_id": "str", + "score": "float", + "fields": "object", + } + + attribute_map = { + "idx_name": "idxName", + "doc_id": "docId", + "score": "score", + "fields": "fields", + } + + def __init__( + self, + idx_name=None, + doc_id=None, + score=None, + fields=None, + local_vars_configuration=None, + ): # noqa: E501 + """IdxRecord - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._idx_name = None + self._doc_id = None + self._score = None + self._fields = None + self.discriminator = None + + self.idx_name = idx_name + self.doc_id = doc_id + self.score = score + if fields is not None: + self.fields = fields + + @property + def idx_name(self): + """Gets the idx_name of this IdxRecord. # noqa: E501 + + + :return: The idx_name of this IdxRecord. # noqa: E501 + :rtype: str + """ + return self._idx_name + + @idx_name.setter + def idx_name(self, idx_name): + """Sets the idx_name of this IdxRecord. + + + :param idx_name: The idx_name of this IdxRecord. # noqa: E501 + :type: str + """ + self._idx_name = idx_name + + @property + def doc_id(self): + """Gets the doc_id of this IdxRecord. # noqa: E501 + + + :return: The doc_id of this IdxRecord. # noqa: E501 + :rtype: str + """ + return self._doc_id + + @doc_id.setter + def doc_id(self, doc_id): + """Sets the doc_id of this IdxRecord. + + + :param doc_id: The doc_id of this IdxRecord. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and doc_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `doc_id`, must not be `None`" + ) # noqa: E501 + + self._doc_id = doc_id + + @property + def score(self): + """Gets the score of this IdxRecord. # noqa: E501 + + + :return: The score of this IdxRecord. # noqa: E501 + :rtype: float + """ + return self._score + + @score.setter + def score(self, score): + """Sets the score of this IdxRecord. + + + :param score: The score of this IdxRecord. # noqa: E501 + :type: float + """ + if ( + self.local_vars_configuration.client_side_validation and score is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `score`, must not be `None`" + ) # noqa: E501 + + self._score = score + + @property + def fields(self): + """Gets the fields of this IdxRecord. # noqa: E501 + + + :return: The fields of this IdxRecord. # noqa: E501 + :rtype: object + """ + return self._fields + + @fields.setter + def fields(self, fields): + """Sets the fields of this IdxRecord. + + + :param fields: The fields of this IdxRecord. # noqa: E501 + :type: object + """ + + self._fields = fields + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, IdxRecord): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, IdxRecord): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/search/rest/models/text_search_request.py b/knext/search/rest/models/text_search_request.py new file mode 100644 index 00000000..046301ee --- /dev/null +++ b/knext/search/rest/models/text_search_request.py @@ -0,0 +1,260 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class TextSearchRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "project_id": "int", + "query_string": "str", + "label_constraints": "list[str]", + "topk": "int", + "params": "object", + } + + attribute_map = { + "project_id": "projectId", + "query_string": "queryString", + "label_constraints": "labelConstraints", + "topk": "topk", + "params": "params", + } + + def __init__( + self, + project_id=None, + query_string=None, + label_constraints=None, + topk=None, + params=None, + local_vars_configuration=None, + ): # noqa: E501 + """TextSearchRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._query_string = None + self._label_constraints = None + self._topk = None + self._params = None + self.discriminator = None + + self.project_id = project_id + self.query_string = query_string + if label_constraints is not None: + self.label_constraints = label_constraints + self.topk = topk + if params is not None: + self.params = params + + @property + def project_id(self): + """Gets the project_id of this TextSearchRequest. # noqa: E501 + + + :return: The project_id of this TextSearchRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this TextSearchRequest. + + + :param project_id: The project_id of this TextSearchRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def query_string(self): + """Gets the query_string of this TextSearchRequest. # noqa: E501 + + + :return: The query_string of this TextSearchRequest. # noqa: E501 + :rtype: str + """ + return self._query_string + + @query_string.setter + def query_string(self, query_string): + """Sets the query_string of this TextSearchRequest. + + + :param query_string: The query_string of this TextSearchRequest. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and query_string is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `query_string`, must not be `None`" + ) # noqa: E501 + + self._query_string = query_string + + @property + def label_constraints(self): + """Gets the label_constraints of this TextSearchRequest. # noqa: E501 + + + :return: The label_constraints of this TextSearchRequest. # noqa: E501 + :rtype: list[str] + """ + return self._label_constraints + + @label_constraints.setter + def label_constraints(self, label_constraints): + """Sets the label_constraints of this TextSearchRequest. + + + :param label_constraints: The label_constraints of this TextSearchRequest. # noqa: E501 + :type: list[str] + """ + + self._label_constraints = label_constraints + + @property + def topk(self): + """Gets the topk of this TextSearchRequest. # noqa: E501 + + + :return: The topk of this TextSearchRequest. # noqa: E501 + :rtype: int + """ + return self._topk + + @topk.setter + def topk(self, topk): + """Sets the topk of this TextSearchRequest. + + + :param topk: The topk of this TextSearchRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and topk is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `topk`, must not be `None`" + ) # noqa: E501 + + self._topk = topk + + @property + def params(self): + """Gets the params of this TextSearchRequest. # noqa: E501 + + + :return: The params of this TextSearchRequest. # noqa: E501 + :rtype: object + """ + return self._params + + @params.setter + def params(self, params): + """Sets the params of this TextSearchRequest. + + + :param params: The params of this TextSearchRequest. # noqa: E501 + :type: object + """ + + self._params = params + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, TextSearchRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, TextSearchRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/search/rest/models/vector_search_request.py b/knext/search/rest/models/vector_search_request.py new file mode 100644 index 00000000..34727471 --- /dev/null +++ b/knext/search/rest/models/vector_search_request.py @@ -0,0 +1,327 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class VectorSearchRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "project_id": "int", + "label": "str", + "property_key": "str", + "query_vector": "list[float]", + "ef_search": "int", + "topk": "int", + "params": "object", + } + + attribute_map = { + "project_id": "projectId", + "label": "label", + "property_key": "propertyKey", + "query_vector": "queryVector", + "ef_search": "efSearch", + "topk": "topk", + "params": "params", + } + + def __init__( + self, + project_id=None, + label=None, + property_key=None, + query_vector=None, + ef_search=None, + topk=None, + params={}, + local_vars_configuration=None, + ): # noqa: E501 + """VectorSearchRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._label = None + self._property_key = None + self._query_vector = None + self._ef_search = None + self._topk = None + self._params = None + self.discriminator = None + + self.project_id = project_id + self.label = label + self.property_key = property_key + self.query_vector = query_vector + if ef_search is not None: + self.ef_search = ef_search + self.topk = topk + if params is not None: + self.params = params + + @property + def project_id(self): + """Gets the project_id of this VectorSearchRequest. # noqa: E501 + + + :return: The project_id of this VectorSearchRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this VectorSearchRequest. + + + :param project_id: The project_id of this VectorSearchRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def label(self): + """Gets the label of this VectorSearchRequest. # noqa: E501 + + + :return: The label of this VectorSearchRequest. # noqa: E501 + :rtype: str + """ + return self._label + + @label.setter + def label(self, label): + """Sets the label of this VectorSearchRequest. + + + :param label: The label of this VectorSearchRequest. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and label is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `label`, must not be `None`" + ) # noqa: E501 + + self._label = label + + @property + def property_key(self): + """Gets the property_key of this VectorSearchRequest. # noqa: E501 + + + :return: The property_key of this VectorSearchRequest. # noqa: E501 + :rtype: str + """ + return self._property_key + + @property_key.setter + def property_key(self, property_key): + """Sets the property_key of this VectorSearchRequest. + + + :param property_key: The property_key of this VectorSearchRequest. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation + and property_key is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `property_key`, must not be `None`" + ) # noqa: E501 + + self._property_key = property_key + + @property + def query_vector(self): + """Gets the query_vector of this VectorSearchRequest. # noqa: E501 + + + :return: The query_vector of this VectorSearchRequest. # noqa: E501 + :rtype: list[float] + """ + return self._query_vector + + @query_vector.setter + def query_vector(self, query_vector): + """Sets the query_vector of this VectorSearchRequest. + + + :param query_vector: The query_vector of this VectorSearchRequest. # noqa: E501 + :type: list[float] + """ + if ( + self.local_vars_configuration.client_side_validation + and query_vector is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `query_vector`, must not be `None`" + ) # noqa: E501 + + self._query_vector = query_vector + + @property + def ef_search(self): + """Gets the ef_search of this VectorSearchRequest. # noqa: E501 + + + :return: The ef_search of this VectorSearchRequest. # noqa: E501 + :rtype: int + """ + return self._ef_search + + @ef_search.setter + def ef_search(self, ef_search): + """Sets the ef_search of this VectorSearchRequest. + + + :param ef_search: The ef_search of this VectorSearchRequest. # noqa: E501 + :type: int + """ + + self._ef_search = ef_search + + @property + def topk(self): + """Gets the topk of this VectorSearchRequest. # noqa: E501 + + + :return: The topk of this VectorSearchRequest. # noqa: E501 + :rtype: int + """ + return self._topk + + @topk.setter + def topk(self, topk): + """Sets the topk of this VectorSearchRequest. + + + :param topk: The topk of this VectorSearchRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and topk is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `topk`, must not be `None`" + ) # noqa: E501 + + self._topk = topk + + @property + def params(self): + """Gets the params of this VectorSearchRequest. # noqa: E501 + + + :return: The params of this VectorSearchRequest. # noqa: E501 + :rtype: object + """ + return self._params + + @params.setter + def params(self, params): + """Sets the params of this VectorSearchRequest. + + + :param params: The params of this VectorSearchRequest. # noqa: E501 + :type: object + """ + + self._params = params + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: ( + (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item + ), + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, VectorSearchRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, VectorSearchRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/search/rest/search_api.py b/knext/search/rest/search_api.py new file mode 100644 index 00000000..a9f3cf21 --- /dev/null +++ b/knext/search/rest/search_api.py @@ -0,0 +1,281 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import re # noqa: F401 + +# python 2 and python 3 compatibility library +import six + +from knext.common.rest.api_client import ApiClient +from knext.common.rest.exceptions import ApiTypeError, ApiValueError # noqa: F401 + + +class SearchApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def search_text_post(self, **kwargs): # noqa: E501 + """search_text # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.search_text_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param TextSearchRequest text_search_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: list[IdxRecord] + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.search_text_post_with_http_info(**kwargs) # noqa: E501 + + def search_text_post_with_http_info(self, **kwargs): # noqa: E501 + """search_text # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.search_text_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param TextSearchRequest text_search_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(list[IdxRecord], status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["text_search_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method search_text_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "text_search_request" in local_var_params: + body_params = local_var_params["text_search_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/search/text", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="list[IdxRecord]", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) + + def search_vector_post(self, **kwargs): # noqa: E501 + """search_vector # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.search_vector_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param VectorSearchRequest vector_search_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: list[IdxRecord] + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.search_vector_post_with_http_info(**kwargs) # noqa: E501 + + def search_vector_post_with_http_info(self, **kwargs): # noqa: E501 + """search_vector # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.search_vector_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param VectorSearchRequest vector_search_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(list[IdxRecord], status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["vector_search_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method search_vector_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "vector_search_request" in local_var_params: + body_params = local_var_params["vector_search_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/search/vector", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="list[IdxRecord]", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) diff --git a/knext/thinker/__init__.py b/knext/thinker/__init__.py new file mode 100644 index 00000000..6f6914a4 --- /dev/null +++ b/knext/thinker/__init__.py @@ -0,0 +1,10 @@ +# Copyright 2023 OpenSPG Authors +# +# 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. diff --git a/knext/thinker/client.py b/knext/thinker/client.py new file mode 100644 index 00000000..d5f95a53 --- /dev/null +++ b/knext/thinker/client.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. +import os + +from knext.common.base.client import Client +from knext.common.rest import Configuration, ApiClient +from knext.thinker import rest +from knext.thinker.rest import ThinkerTaskRequest, ThinkerTaskResponse + + +class ThinkerClient(Client): + """SPG Thinker Client.""" + + def __init__(self, host_addr: str = None, project_id: int = None): + super().__init__(host_addr, project_id) + + self._rest_client: rest.ThinkerApi = rest.ThinkerApi( + api_client=ApiClient(configuration=Configuration(host=host_addr)) + ) + + def execute(self, subject="", predicate="", object="", mode="spo", params=""): + """ + Execute a synchronous builder job in local runner. + """ + req: ThinkerTaskRequest = ThinkerTaskRequest( + project_id=self._project_id, + subject=subject, + predicate=predicate, + object=object, + mode=mode, + params=params, + ) + rep: ThinkerTaskResponse = self._rest_client.reason_thinker_post( + thinker_task_request=req + ) + print(rep) + + +if __name__ == "__main__": + sc = ThinkerClient("http://127.0.0.1:8887", 2) + sc.execute( + subject="DiseaseLevel", + mode="node", + params='{"spg.reasoner.thinker.strict":·true,·"收缩压":150}', + ) diff --git a/knext/thinker/rest/__init__.py b/knext/thinker/rest/__init__.py new file mode 100644 index 00000000..913a32c7 --- /dev/null +++ b/knext/thinker/rest/__init__.py @@ -0,0 +1,33 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +# flake8: noqa + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +from __future__ import absolute_import + +__version__ = "1" +# import models into sdk package +from knext.thinker.rest.models.thinker_task_request import ThinkerTaskRequest +from knext.thinker.rest.models.thinker_task_response import ThinkerTaskResponse + +# import apis into sdk package +from knext.thinker.rest.thinker_api import ThinkerApi diff --git a/knext/thinker/rest/models/__init__.py b/knext/thinker/rest/models/__init__.py new file mode 100644 index 00000000..0ec2d921 --- /dev/null +++ b/knext/thinker/rest/models/__init__.py @@ -0,0 +1,28 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + +# flake8: noqa +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +# import models into model package +from knext.thinker.rest.models.thinker_task_request import ThinkerTaskRequest +from knext.thinker.rest.models.thinker_task_response import ThinkerTaskResponse diff --git a/knext/thinker/rest/models/thinker_task_request.py b/knext/thinker/rest/models/thinker_task_request.py new file mode 100644 index 00000000..cfdd3051 --- /dev/null +++ b/knext/thinker/rest/models/thinker_task_request.py @@ -0,0 +1,277 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ThinkerTaskRequest(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = { + "project_id": "int", + "subject": "str", + "predicate": "str", + "object": "str", + "mode": "str", + "params": "str", + } + + attribute_map = { + "project_id": "projectId", + "subject": "subject", + "predicate": "predicate", + "object": "object", + "mode": "mode", + "params": "params", + } + + def __init__( + self, + project_id=None, + subject=None, + predicate=None, + object=None, + mode=None, + params=None, + local_vars_configuration=None, + ): # noqa: E501 + """ThinkerTaskRequest - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._subject = None + self._predicate = None + self._object = None + self._mode = None + self._params = None + self.discriminator = None + + self.project_id = project_id + if subject is not None: + self.subject = subject + if predicate is not None: + self.predicate = predicate + if object is not None: + self.object = object + if mode is not None: + self.mode = mode + if params is not None: + self.params = params + + @property + def project_id(self): + """Gets the project_id of this ThinkerTaskRequest. # noqa: E501 + + + :return: The project_id of this ThinkerTaskRequest. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this ThinkerTaskRequest. + + + :param project_id: The project_id of this ThinkerTaskRequest. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def subject(self): + """Gets the subject of this ThinkerTaskRequest. # noqa: E501 + + + :return: The subject of this ThinkerTaskRequest. # noqa: E501 + :rtype: str + """ + return self._subject + + @subject.setter + def subject(self, subject): + """Sets the subject of this ThinkerTaskRequest. + + + :param subject: The subject of this ThinkerTaskRequest. # noqa: E501 + :type: str + """ + + self._subject = subject + + @property + def predicate(self): + """Gets the predicate of this ThinkerTaskRequest. # noqa: E501 + + + :return: The predicate of this ThinkerTaskRequest. # noqa: E501 + :rtype: str + """ + return self._predicate + + @predicate.setter + def predicate(self, predicate): + """Sets the predicate of this ThinkerTaskRequest. + + + :param predicate: The predicate of this ThinkerTaskRequest. # noqa: E501 + :type: str + """ + + self._predicate = predicate + + @property + def object(self): + """Gets the object of this ThinkerTaskRequest. # noqa: E501 + + + :return: The object of this ThinkerTaskRequest. # noqa: E501 + :rtype: str + """ + return self._object + + @object.setter + def object(self, object): + """Sets the object of this ThinkerTaskRequest. + + + :param object: The object of this ThinkerTaskRequest. # noqa: E501 + :type: str + """ + + self._object = object + + @property + def mode(self): + """Gets the mode of this ThinkerTaskRequest. # noqa: E501 + + + :return: The mode of this ThinkerTaskRequest. # noqa: E501 + :rtype: str + """ + return self._mode + + @mode.setter + def mode(self, mode): + """Sets the mode of this ThinkerTaskRequest. + + + :param mode: The mode of this ThinkerTaskRequest. # noqa: E501 + :type: str + """ + + self._mode = mode + + @property + def params(self): + """Gets the params of this ThinkerTaskRequest. # noqa: E501 + + + :return: The params of this ThinkerTaskRequest. # noqa: E501 + :rtype: str + """ + return self._params + + @params.setter + def params(self, params): + """Sets the params of this ThinkerTaskRequest. + + + :param params: The params of this ThinkerTaskRequest. # noqa: E501 + :type: str + """ + + self._params = params + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ThinkerTaskRequest): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ThinkerTaskRequest): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/thinker/rest/models/thinker_task_response.py b/knext/thinker/rest/models/thinker_task_response.py new file mode 100644 index 00000000..744b2aa9 --- /dev/null +++ b/knext/thinker/rest/models/thinker_task_response.py @@ -0,0 +1,194 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. + + +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import pprint +import re # noqa: F401 + +import six + +from knext.common.rest.configuration import Configuration + + +class ThinkerTaskResponse(object): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + """ + Attributes: + openapi_types (dict): The key is attribute name + and the value is attribute type. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + """ + openapi_types = {"project_id": "int", "task_id": "str", "result": "list[object]"} + + attribute_map = {"project_id": "projectId", "task_id": "taskId", "result": "result"} + + def __init__( + self, project_id=None, task_id=None, result=None, local_vars_configuration=None + ): # noqa: E501 + """ThinkerTaskResponse - a model defined in OpenAPI""" # noqa: E501 + if local_vars_configuration is None: + local_vars_configuration = Configuration() + self.local_vars_configuration = local_vars_configuration + + self._project_id = None + self._task_id = None + self._result = None + self.discriminator = None + + self.project_id = project_id + self.task_id = task_id + self.result = result + + @property + def project_id(self): + """Gets the project_id of this ThinkerTaskResponse. # noqa: E501 + + + :return: The project_id of this ThinkerTaskResponse. # noqa: E501 + :rtype: int + """ + return self._project_id + + @project_id.setter + def project_id(self, project_id): + """Sets the project_id of this ThinkerTaskResponse. + + + :param project_id: The project_id of this ThinkerTaskResponse. # noqa: E501 + :type: int + """ + if ( + self.local_vars_configuration.client_side_validation and project_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `project_id`, must not be `None`" + ) # noqa: E501 + + self._project_id = project_id + + @property + def task_id(self): + """Gets the task_id of this ThinkerTaskResponse. # noqa: E501 + + + :return: The task_id of this ThinkerTaskResponse. # noqa: E501 + :rtype: str + """ + return self._task_id + + @task_id.setter + def task_id(self, task_id): + """Sets the task_id of this ThinkerTaskResponse. + + + :param task_id: The task_id of this ThinkerTaskResponse. # noqa: E501 + :type: str + """ + if ( + self.local_vars_configuration.client_side_validation and task_id is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `task_id`, must not be `None`" + ) # noqa: E501 + + self._task_id = task_id + + @property + def result(self): + """Gets the result of this ThinkerTaskResponse. # noqa: E501 + + + :return: The result of this ThinkerTaskResponse. # noqa: E501 + :rtype: list[object] + """ + return self._result + + @result.setter + def result(self, result): + """Sets the result of this ThinkerTaskResponse. + + + :param result: The result of this ThinkerTaskResponse. # noqa: E501 + :type: list[object] + """ + if ( + self.local_vars_configuration.client_side_validation and result is None + ): # noqa: E501 + raise ValueError( + "Invalid value for `result`, must not be `None`" + ) # noqa: E501 + + self._result = result + + def to_dict(self): + """Returns the model properties as a dict""" + result = {} + + for attr, _ in six.iteritems(self.openapi_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list( + map(lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value) + ) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict( + map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") + else item, + value.items(), + ) + ) + else: + result[attr] = value + + return result + + def to_str(self): + """Returns the string representation of the model""" + return pprint.pformat(self.to_dict()) + + def __repr__(self): + """For `print` and `pprint`""" + return self.to_str() + + def __eq__(self, other): + """Returns true if both objects are equal""" + if not isinstance(other, ThinkerTaskResponse): + return False + + return self.to_dict() == other.to_dict() + + def __ne__(self, other): + """Returns true if both objects are not equal""" + if not isinstance(other, ThinkerTaskResponse): + return True + + return self.to_dict() != other.to_dict() diff --git a/knext/thinker/rest/thinker_api.py b/knext/thinker/rest/thinker_api.py new file mode 100644 index 00000000..d5b2782a --- /dev/null +++ b/knext/thinker/rest/thinker_api.py @@ -0,0 +1,161 @@ +# coding: utf-8 +# Copyright 2023 OpenSPG Authors +# +# 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. +""" + knext + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import re # noqa: F401 + +# python 2 and python 3 compatibility library +import six + +from knext.common.rest.api_client import ApiClient +from knext.common.rest.exceptions import ApiTypeError, ApiValueError # noqa: F401 + + +class ThinkerApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + + def reason_thinker_post(self, **kwargs): # noqa: E501 + """thinker # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.reason_thinker_post(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ThinkerTaskRequest thinker_task_request: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: ThinkerTaskResponse + If the method is called asynchronously, + returns the request thread. + """ + kwargs["_return_http_data_only"] = True + return self.reason_thinker_post_with_http_info(**kwargs) # noqa: E501 + + def reason_thinker_post_with_http_info(self, **kwargs): # noqa: E501 + """thinker # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + >>> thread = api.reason_thinker_post_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req bool: execute request asynchronously + :param ThinkerTaskRequest thinker_task_request: + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(ThinkerTaskResponse, status_code(int), headers(HTTPHeaderDict)) + If the method is called asynchronously, + returns the request thread. + """ + + local_var_params = locals() + + all_params = ["thinker_task_request"] + all_params.extend( + [ + "async_req", + "_return_http_data_only", + "_preload_content", + "_request_timeout", + ] + ) + + for key, val in six.iteritems(local_var_params["kwargs"]): + if key not in all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method reason_thinker_post" % key + ) + local_var_params[key] = val + del local_var_params["kwargs"] + + collection_formats = {} + + path_params = {} + + query_params = [] + + header_params = {} + + form_params = [] + local_var_files = {} + + body_params = None + if "thinker_task_request" in local_var_params: + body_params = local_var_params["thinker_task_request"] + # HTTP header `Accept` + header_params["Accept"] = self.api_client.select_header_accept( + ["application/json"] + ) # noqa: E501 + + # HTTP header `Content-Type` + header_params[ + "Content-Type" + ] = self.api_client.select_header_content_type( # noqa: E501 + ["application/json"] + ) # noqa: E501 + + # Authentication setting + auth_settings = [] # noqa: E501 + + return self.api_client.call_api( + "/reason/thinker", + "POST", + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type="ThinkerTaskResponse", # noqa: E501 + auth_settings=auth_settings, + async_req=local_var_params.get("async_req"), + _return_http_data_only=local_var_params.get( + "_return_http_data_only" + ), # noqa: E501 + _preload_content=local_var_params.get("_preload_content", True), + _request_timeout=local_var_params.get("_request_timeout"), + collection_formats=collection_formats, + ) diff --git a/requirements.txt b/requirements.txt index 585097bc..b8e314d9 100644 --- a/requirements.txt +++ b/requirements.txt @@ -37,11 +37,11 @@ openai python-docx charset_normalizer==3.3.2 pdfminer.six==20231228 -openspg-knext ollama tenacity pyhocon scikit-learn zodb matplotlib -PyPDF2 \ No newline at end of file +PyPDF2 +ruamel.yaml \ No newline at end of file diff --git a/setup.py b/setup.py index 334faea8..cbf94126 100644 --- a/setup.py +++ b/setup.py @@ -69,6 +69,8 @@ entry_points={ "console_scripts": [ "kag = kag.bin.kag_cmds:main", + "knext=knext.command.knext_cli:_main", ] }, ) + From d40e9fc84aabc45e6106af983af9eedf4ff1bb3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=94=A6=E5=91=88?= Date: Tue, 24 Dec 2024 13:46:18 +0800 Subject: [PATCH 5/9] fix package --- MANIFEST.in | 4 ++++ setup.py | 2 ++ 2 files changed, 6 insertions(+) diff --git a/MANIFEST.in b/MANIFEST.in index a922307c..9a655d7d 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,2 +1,6 @@ recursive-include kag * recursive-exclude kag/examples * +global-exclude *.pyc +global-exclude *.pyo +global-exclude *.pyd +global-exclude __pycache__ \ No newline at end of file diff --git a/setup.py b/setup.py index cbf94126..b816132d 100644 --- a/setup.py +++ b/setup.py @@ -54,6 +54,8 @@ "*.tests", "*.tests.*", "*.pyc", + "__pycache__", + "*/__pycache__/*", ], ), python_requires=">=3.8", From e736c0ae900f42c83640ab0f374c6fbf0d2d66ff Mon Sep 17 00:00:00 2001 From: zhuzhongshu123 Date: Tue, 24 Dec 2024 16:19:04 +0800 Subject: [PATCH 6/9] scanner update --- kag/builder/component/scanner/csv_scanner.py | 47 ++++++++----------- kag/builder/component/scanner/json_scanner.py | 1 + .../component/scanner/yuque_scanner.py | 23 +++++---- kag/interface/builder/scanner_abc.py | 26 ++++++++++ tests/unit/builder/component/test_scanner.py | 34 ++++++++++---- 5 files changed, 84 insertions(+), 47 deletions(-) diff --git a/kag/builder/component/scanner/csv_scanner.py b/kag/builder/component/scanner/csv_scanner.py index 54a8a953..2c3b292b 100644 --- a/kag/builder/component/scanner/csv_scanner.py +++ b/kag/builder/component/scanner/csv_scanner.py @@ -19,32 +19,18 @@ @ScannerABC.register("csv") class CSVScanner(ScannerABC): - """ - A class for reading CSV files and converting them into a list of dictionaries. - - This class inherits from `ScannerABC` and provides functionality to read CSV files. - It can either return the entire row as a dictionary or split the row into multiple dictionaries - based on specified columns. - - Attributes: - cols (List[str]): A list of column names to be processed. If None, the entire row is returned as a dictionary. - rank (int): The rank of the current process (used for distributed processing). - world_size (int): The total number of processes (used for distributed processing). - """ - - def __init__(self, cols: List[str] = None, rank: int = 0, world_size: int = 1): - """ - Initializes the CSVScanner with optional columns, rank, and world size. - - Args: - cols (List[str], optional): A list of column names to be processed. Defaults to None. - - If not specified, each row of the CSV file will be returned as a single dictionary. - - If specified, each row will be split into multiple dictionaries, one for each specified column. - rank (int, optional): The rank of the current process. Defaults to None. - world_size (int, optional): The total number of processes. Defaults to None. - """ + def __init__( + self, + header: bool = True, + col_names: List[str] = None, + col_ids: List[int] = None, + rank: int = 0, + world_size: int = 1, + ): super().__init__(rank=rank, world_size=world_size) - self.cols = cols + self.header = header + self.col_names = col_names + self.col_ids = col_ids @property def input_types(self) -> Input: @@ -65,14 +51,19 @@ def load_data(self, input: Input, **kwargs) -> List[Output]: Returns: List[Output]: A list of dictionaries containing the processed data. """ - data = pd.read_csv(input, dtype=str) - if self.cols is None: + input = self.download_data(input) + if self.header: + data = pd.read_csv(input, dtype=str) + else: + data = pd.read_csv(input, dtype=str, header=None) + col_keys = self.col_names if self.col_names else self.col_ids + if col_keys is None: return data.to_dict(orient="records") contents = [] for _, row in data.iterrows(): for k, v in row.items(): - if k in self.cols: + if k in col_keys: v = str(v) name = v[:5] + "..." + v[-5:] contents.append( diff --git a/kag/builder/component/scanner/json_scanner.py b/kag/builder/component/scanner/json_scanner.py index df614e13..e11a6e42 100644 --- a/kag/builder/component/scanner/json_scanner.py +++ b/kag/builder/component/scanner/json_scanner.py @@ -95,6 +95,7 @@ def load_data(self, input: Input, **kwargs) -> List[Output]: Raises: ValueError: If there is an error reading the JSON data or if the input is not a valid JSON array or object. """ + input = self.download_data(input) try: if os.path.exists(input): corpus = self._read_from_file(input) diff --git a/kag/builder/component/scanner/yuque_scanner.py b/kag/builder/component/scanner/yuque_scanner.py index dd694e19..2f5429e5 100644 --- a/kag/builder/component/scanner/yuque_scanner.py +++ b/kag/builder/component/scanner/yuque_scanner.py @@ -49,7 +49,7 @@ def __init__(self, token: str): @property def input_types(self) -> Type[Input]: """The type of input this Runnable object accepts specified as a type annotation.""" - return str + return Union[str, List[str]] @property def output_types(self) -> Type[Output]: @@ -90,12 +90,15 @@ def load_data(self, input: Input, **kwargs) -> List[Output]: List[Output]: A list of strings, where each string contains the token and the URL of each document. """ url = input - data = self.get_yuque_api_data(url) - if isinstance(data, dict): - # for single yuque doc - return [f"{self.token}@{url}"] - output = [] - for item in data: - slug = item["slug"] - output.append(os.path.join(url, slug)) - return [f"{self.token}@{url}" for url in output] + if isinstance(url, str): + data = self.get_yuque_api_data(url) + if isinstance(data, dict): + # for single yuque doc + return [f"{self.token}@{url}"] + output = [] + for item in data: + slug = item["slug"] + output.append(os.path.join(url, slug)) + return [f"{self.token}@{url}" for url in output] + else: + return [f"{self.token}@{x}" for x in url] diff --git a/kag/interface/builder/scanner_abc.py b/kag/interface/builder/scanner_abc.py index 62bed77d..27a0adee 100644 --- a/kag/interface/builder/scanner_abc.py +++ b/kag/interface/builder/scanner_abc.py @@ -9,9 +9,11 @@ # 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. +import os from abc import ABC, abstractmethod from typing import Any, Generator, List from kag.interface.builder.base import BuilderComponent +from kag.common.conf import KAG_PROJECT_CONF from knext.common.base.runnable import Input, Output @@ -95,6 +97,30 @@ def generate(self, input: Input, **kwargs) -> Generator[Output, Input, None]: for item in self._generate(data): yield item + def download_data(self, input: Input, **kwargs) -> List[Output]: + """ + Loads data by returning the input file path as a list of strings. + + This method takes the input file path and returns it as a list containing the file path. + + Args: + input (Input): The file path to load. + **kwargs: Additional keyword arguments. + + Returns: + List[Output]: A list containing the input file path. + """ + if input.startswith("http://") or input.startswith("https://"): + from kag.common.utils import download_from_http + + local_file_path = os.path.join(KAG_PROJECT_CONF.ckpt_dir, "file_scanner") + if not os.path.exists(local_file_path): + os.makedirs(local_file_path) + local_file = os.path.join(local_file_path, os.path.basename(input)) + local_file = download_from_http(input, local_file) + return local_file + return input + def invoke(self, input: Input, **kwargs) -> List[Output]: """ Invokes the component to process input data and return a list of processed results. diff --git a/tests/unit/builder/component/test_scanner.py b/tests/unit/builder/component/test_scanner.py index 5962562b..97525f16 100644 --- a/tests/unit/builder/component/test_scanner.py +++ b/tests/unit/builder/component/test_scanner.py @@ -61,7 +61,7 @@ def test_csv_scanner(): def test_csv_scanner_with_cols(): file_path = os.path.join(pwd, "../data/test_csv.csv") scanner = ScannerABC.from_config( - {"type": "csv", "rank": 0, "world_size": 1, "cols": ["title", "text"]} + {"type": "csv", "rank": 0, "world_size": 1, "col_names": ["title", "text"]} ) csv_content = [] for _, item in pd.read_csv(file_path, dtype=str).iterrows(): @@ -71,10 +71,10 @@ def test_csv_scanner_with_cols(): assert len(data) == len(csv_content) * 2 scanner_1 = ScannerABC.from_config( - {"type": "csv", "rank": 0, "world_size": 2, "cols": ["title", "text"]} + {"type": "csv", "rank": 0, "world_size": 2, "col_names": ["title", "text"]} ) scanner_2 = ScannerABC.from_config( - {"type": "csv", "rank": 1, "world_size": 2, "cols": ["title", "text"]} + {"type": "csv", "rank": 1, "world_size": 2, "col_names": ["title", "text"]} ) data_1 = scanner_1.invoke(file_path) @@ -82,6 +82,17 @@ def test_csv_scanner_with_cols(): data = data_1 + data_2 assert len(data) == len(csv_content) * 2 + file_path = os.path.join(pwd, "../data/test_csv_headerless.csv") + scanner = ScannerABC.from_config( + {"type": "csv", "rank": 0, "world_size": 1, "col_ids": [0, 1], "header": False} + ) + csv_content = [] + for _, item in pd.read_csv(file_path, dtype=str, header=None).iterrows(): + csv_content.append(item.to_dict()) + data = scanner.invoke(file_path) + + assert len(data) == len(csv_content) * 2 + def test_file_scanner(): scanner = ScannerABC.from_config({"type": "file"}) @@ -127,15 +138,20 @@ def test_directory_scanner(): def test_yuque_scanner(): - scanner = ScannerABC.from_config( - { - "type": "yuque", - "token": "f6QiFu1gIDEGJIsI6jziOWbE7E9MsFkipeV69NHq", - } - ) + token = "pKjtrFOr7w4QUzBTEjXdpV33QzVEHR49kvkZmGFV" + scanner = ScannerABC.from_config({"type": "yuque", "token": token}) urls = scanner.invoke( "https://yuque-api.antfin-inc.com/api/v2/repos/un8gkl/kg7h1z/docs/" ) for url in urls: token, rea_url = url.split("@", 1) assert token == scanner.token + + urls = scanner.invoke( + ["https://yuque-api.antfin-inc.com/api/v2/repos/un8gkl/kg7h1z/docs/"] + ) + assert ( + len(urls) == 1 + and urls[0] + == f"{token}@https://yuque-api.antfin-inc.com/api/v2/repos/un8gkl/kg7h1z/docs/" + ) From a523daa133b006c6762a3d3539cfa3fed1668c49 Mon Sep 17 00:00:00 2001 From: zhuzhongshu123 Date: Tue, 24 Dec 2024 16:21:01 +0800 Subject: [PATCH 7/9] scanner update --- .pre-commit-config.yaml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3bc21348..26ba54fb 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -10,3 +10,8 @@ repos: kag/solver/logic/core_modules/parser/logic_node_parser.py )$ + - repo: https://github.com/pycqa/flake8 + rev: 4.0.1 + hooks: + - id: flake8 + files: ^kag/.*\.py$ From 9499c3f5d6e29e85cafcac2faa10682b377db8ae Mon Sep 17 00:00:00 2001 From: zhuzhongshu123 Date: Tue, 24 Dec 2024 16:44:28 +0800 Subject: [PATCH 8/9] add doc and update example scripts --- kag/common/checkpointer/base.py | 12 ++++++++++++ kag/examples/2wiki/solver/evaFor2wiki.py | 15 +++++++++++++-- kag/examples/hotpotqa/solver/evaForHotpotqa.py | 16 ++++++++++++---- kag/examples/musique/solver/evaForMusique.py | 14 +++++++++++++- kag/interface/builder/scanner_abc.py | 11 +++++------ 5 files changed, 55 insertions(+), 13 deletions(-) diff --git a/kag/common/checkpointer/base.py b/kag/common/checkpointer/base.py index 4160ec8b..8c70ce8d 100644 --- a/kag/common/checkpointer/base.py +++ b/kag/common/checkpointer/base.py @@ -121,6 +121,18 @@ def size(self): raise NotImplementedError("size not implemented yet.") + def __contains__(self, key): + """ + Defines the behavior of the `in` operator for the object. + Args: + key (str): The key to check for existence in the checkpoint. + + Returns: + bool: True if the key exists in the checkpoint, False otherwise. + """ + + return self.exists(key) + class CheckpointerManager: """ diff --git a/kag/examples/2wiki/solver/evaFor2wiki.py b/kag/examples/2wiki/solver/evaFor2wiki.py index 125564ad..8b4af000 100644 --- a/kag/examples/2wiki/solver/evaFor2wiki.py +++ b/kag/examples/2wiki/solver/evaFor2wiki.py @@ -11,11 +11,12 @@ from kag.common.conf import KAG_CONFIG from kag.common.registry import import_modules_from_path +from kag.common.checkpointer import CheckpointerManager + logger = logging.getLogger(__name__) class EvaFor2wiki: - """ init for kag client """ @@ -43,13 +44,22 @@ def qa(self, query): def parallelQaAndEvaluate( self, qaFilePath, resFilePath, threadNum=1, upperLimit=10 ): + ckpt = CheckpointerManager.get_checkpointer( + {"type": "zodb", "ckpt_dir": "ckpt"} + ) + def process_sample(data): try: sample_idx, sample = data sample_id = sample["_id"] question = sample["question"] gold = sample["answer"] - prediction, traceLog = self.qa(question) + if question in ckpt: + print(f"found existing answer to question: {question}") + prediction, traceLog = ckpt.read_from_ckpt(question) + else: + prediction, traceLog = self.qa(question) + ckpt.write_to_ckpt(question, (prediction, traceLog)) evalObj = Evaluate() metrics = evalObj.getBenchMark([prediction], [gold]) @@ -107,6 +117,7 @@ def process_sample(data): res_metrics[item_key] = item_value / total_metrics["processNum"] else: res_metrics[item_key] = total_metrics["processNum"] + CheckpointerManager.close() return res_metrics diff --git a/kag/examples/hotpotqa/solver/evaForHotpotqa.py b/kag/examples/hotpotqa/solver/evaForHotpotqa.py index 743c485b..129b67a8 100644 --- a/kag/examples/hotpotqa/solver/evaForHotpotqa.py +++ b/kag/examples/hotpotqa/solver/evaForHotpotqa.py @@ -12,6 +12,8 @@ from kag.common.conf import KAG_CONFIG from kag.common.registry import import_modules_from_path +from kag.common.checkpointer import CheckpointerManager + logger = logging.getLogger(__name__) @@ -39,17 +41,22 @@ def qa(self, query): def parallelQaAndEvaluate( self, qaFilePath, resFilePath, threadNum=1, upperLimit=10, run_failed=False ): + ckpt = CheckpointerManager.get_checkpointer( + {"type": "zodb", "ckpt_dir": "ckpt"} + ) + def process_sample(data): try: sample_idx, sample = data sample_id = sample["_id"] question = sample["question"] gold = sample["answer"] - if "prediction" not in sample.keys(): - prediction, traceLog = self.qa(question) + if question in ckpt: + print(f"found existing answer to question: {question}") + prediction, traceLog = ckpt.read_from_ckpt(question) else: - prediction = sample["prediction"] - traceLog = sample["traceLog"] + prediction, traceLog = self.qa(question) + ckpt.write_to_ckpt(question, (prediction, traceLog)) evaObj = Evaluate() metrics = evaObj.getBenchMark([prediction], [gold]) @@ -107,6 +114,7 @@ def process_sample(data): res_metrics[item_key] = item_value / total_metrics["processNum"] else: res_metrics[item_key] = total_metrics["processNum"] + CheckpointerManager.close() return res_metrics diff --git a/kag/examples/musique/solver/evaForMusique.py b/kag/examples/musique/solver/evaForMusique.py index 56c52bb4..46be31d6 100644 --- a/kag/examples/musique/solver/evaForMusique.py +++ b/kag/examples/musique/solver/evaForMusique.py @@ -11,6 +11,8 @@ from kag.examples.utils import delay_run from kag.solver.logic.solver_pipeline import SolverPipeline +from kag.common.checkpointer import CheckpointerManager + logger = logging.getLogger(__name__) @@ -43,13 +45,22 @@ def qaWithoutLogicForm(self, query): def parallelQaAndEvaluate( self, qaFilePath, resFilePath, threadNum=1, upperLimit=10 ): + ckpt = CheckpointerManager.get_checkpointer( + {"type": "zodb", "ckpt_dir": "ckpt"} + ) + def process_sample(data): try: sample_idx, sample = data sample_id = sample["id"] question = sample["question"] gold = sample["answer"] - prediction, traceLog = self.qaWithoutLogicForm(question) + if question in ckpt: + print(f"found existing answer to question: {question}") + prediction, traceLog = ckpt.read_from_ckpt(question) + else: + prediction, traceLog = self.qa(question) + ckpt.write_to_ckpt(question, (prediction, traceLog)) evaObj = Evaluate() metrics = evaObj.getBenchMark([prediction], [gold]) @@ -107,6 +118,7 @@ def process_sample(data): res_metrics[item_key] = item_value / total_metrics["processNum"] else: res_metrics[item_key] = total_metrics["processNum"] + CheckpointerManager.close() return res_metrics diff --git a/kag/interface/builder/scanner_abc.py b/kag/interface/builder/scanner_abc.py index 27a0adee..1fd4da6a 100644 --- a/kag/interface/builder/scanner_abc.py +++ b/kag/interface/builder/scanner_abc.py @@ -99,16 +99,15 @@ def generate(self, input: Input, **kwargs) -> Generator[Output, Input, None]: def download_data(self, input: Input, **kwargs) -> List[Output]: """ - Loads data by returning the input file path as a list of strings. - - This method takes the input file path and returns it as a list containing the file path. + Downloads data from a given input URL or returns the input directly if it is not a URL. Args: - input (Input): The file path to load. - **kwargs: Additional keyword arguments. + input (Input): The input source, which can be a URL (starting with "http://" or "https://") or a local path. + **kwargs: Additional keyword arguments (currently unused). Returns: - List[Output]: A list containing the input file path. + List[Output]: A list containing the local file path if the input is a URL, or the input itself if it is not a URL. + """ if input.startswith("http://") or input.startswith("https://"): from kag.common.utils import download_from_http From 3768a81e717adf7d26de8295da7dfd0741c54beb Mon Sep 17 00:00:00 2001 From: zhuzhongshu123 Date: Tue, 24 Dec 2024 17:33:19 +0800 Subject: [PATCH 9/9] add bridge to spg server --- kag/bridge/__init__.py | 0 kag/bridge/spg_server_bridge.py | 38 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 kag/bridge/__init__.py create mode 100644 kag/bridge/spg_server_bridge.py diff --git a/kag/bridge/__init__.py b/kag/bridge/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/kag/bridge/spg_server_bridge.py b/kag/bridge/spg_server_bridge.py new file mode 100644 index 00000000..3820ab15 --- /dev/null +++ b/kag/bridge/spg_server_bridge.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 OpenSPG Authors +# +# 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. +import json +import kag.interface as interface + + +class SPGServerBridge: + def __init__(self): + pass + + def run_reader(self, config, input_data): + if isinstance(config, str): + config = json.loads(config) + scanner_config = config["scanner"] + reader_config = config["reader"] + scanner = interface.ScannerABC.from_config(scanner_config) + reader = interface.ReaderABC.from_config(reader_config) + chunks = [] + for data in scanner.generate(input_data): + chunks += reader.invoke(data) + return chunks + + def run_component(self, component_name, component_config, input_data): + if isinstance(component_config, str): + component_config = json.loads(component_config) + + cls = getattr(interface, component_name) + instance = cls.from_config(component_config) + return instance.invoke(input_data)