python-eigen-ingenuity 0.4.33__py3-none-any.whl → 0.4.34__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52,7 +52,7 @@ class EigenServer (object):
52
52
  baseurl = "http://localhost:8080/"
53
53
 
54
54
  if settings._azure_auth_enabled_:
55
- preflight = requests.get(baseurl + "historian-servlet/jsonbridge/calc?cmd=LISTHISTORIANS")
55
+ preflight = requests.get(baseurl + "historian-servlet/jsonbridge/calc?cmd=LISTHISTORIANS", verify=False)
56
56
 
57
57
  if preflight.status_code != 200:
58
58
  raise EigenException("Could not find an ingenuity Instance at this url: ", baseurl)
@@ -0,0 +1,7 @@
1
+ import sys,os
2
+ from modelbuilder.src.assetmodelbuilder import _asset_model_builder_ as cli_builder, build
3
+
4
+ __all__ = ["build"]
5
+
6
+ def __cli_entrypoint__():
7
+ cli_builder()
File without changes
@@ -0,0 +1,163 @@
1
+ import sys, os, functools, inspect
2
+
3
+ # Add current dir to python path to allow relative imports
4
+ current_dir = os.path.dirname(os.path.abspath(__file__))
5
+ sys.path.append(current_dir)
6
+
7
+ from configmanager import ConfigManager
8
+ from connectors.dbconnectors import ConnectionManager
9
+ from filemanager import FileManager
10
+
11
+ import sys
12
+ import inspect
13
+ import functools
14
+
15
+ # Take Arguments passed to build function and convert them to sys args to use the cli tool from script
16
+ def _convert_sys_argv_(func):
17
+ @functools.wraps(func)
18
+ def wrapper(*args, **kwargs):
19
+ # Get the function signature
20
+ sig = inspect.signature(func)
21
+
22
+ # Create an empty list to hold the sys.argv entries
23
+ argv_entries = []
24
+
25
+ # Get the arguments passed by position
26
+ args_dict = dict(zip(sig.parameters, args))
27
+
28
+ # Loop through the parameters in the function signature
29
+ for param_name, param in sig.parameters.items():
30
+ param_name_cleaned = param_name.replace('_', '')
31
+
32
+ # Check if the parameter is provided as a keyword argument
33
+ if param_name in kwargs:
34
+ arg_value = kwargs[param_name]
35
+ # Check if the parameter is provided as a positional argument
36
+ elif param_name in args_dict:
37
+ arg_value = args_dict[param_name]
38
+ else:
39
+ continue # Skip if not provided
40
+
41
+ # If parameter is a boolean, handle it as store_true action
42
+ if param.annotation == bool:
43
+ if arg_value: # If True, add only the flag
44
+ argv_entries.append(f"--{param_name_cleaned}")
45
+ else: # If False, skip adding this argument
46
+ continue
47
+ elif param.annotation == list:
48
+ argv_entries.extend([f"--{param_name_cleaned}"])
49
+ argv_entries.extend(arg_value)
50
+ else:
51
+ # For non-boolean parameters, add the value
52
+ argv_entries.extend([f"--{param_name_cleaned}", str(arg_value)])
53
+
54
+ # Extend sys.argv with the generated entries
55
+ sys.argv.extend(argv_entries)
56
+
57
+ # Call the original function
58
+ return func(*args, **kwargs)
59
+
60
+ return wrapper
61
+
62
+
63
+ @_convert_sys_argv_
64
+ def build(path:str='.', config:str='config.ini', file:str='', query:list=[], preprocess:list=[], postprocess:list=[], delete_all:list=[], separator:str=';',
65
+ start_from:int=1, end_at:int=1, no_versions:bool=False, no_system_properties:bool=False, ignore_nodes:bool=False, skip_duplicates:bool=False,
66
+ no_duplicates:bool=False, allow_blanks:bool=False, batch:int=0, auth:bool=False, order:str='qnrc', primary_property:str='', required_labels:list=[],
67
+ required_properties:list=[], database:str='0', verify:bool=False, summarise:bool=False, show_queries:bool=False, show_returns:bool=False,
68
+ write_queries:str='', write_returns:str='', display_rate='auto', create_node_csv_file:bool=False, node_labels:list=[], node_properties:list=[],
69
+ csv_file_suffix:str='', create_relationship_csv_file:bool=False, csv_to_labels:list=[], csv_to_properties:str=''):
70
+ """The main model builder tools, features a suite of options that allow for importing, exporting, building and updating neo4j data models
71
+
72
+ Args:
73
+ ## Input Parameters
74
+ path: Location of the input and output files. Default is current folder
75
+ config: Name of the configuration file, default is config.ini in the folder from path parameter
76
+ database: Database ID (as set in config file). Defaults to first entry
77
+ file: Space separated string list of input files
78
+ query: Space separated string list of queries to run
79
+ preprocess: Command(s) to execute before processing input files
80
+ postprocess: Command(s) to execute after processing input files
81
+ delete_all: Lists of labels to identify nodes to delete before processing any files
82
+
83
+ ## Change the behaviour of the processing away from the default
84
+ separator: The separator used in the csv files. Default is a semi-colon ';'
85
+ start_from: The first query to process in a .csv file. No effect on cypher files. Default is 1
86
+ end_at: The last query to process in a .csv file. No effect on cypher files. Default is last query in the file
87
+ no_versions: Suppress creation of version nodes
88
+ no_system_properties: Suppress creation of system properties on nodes and relationships. Implies -nov
89
+ ignore_nodes: Treat node columns in relationship files as relationship properties
90
+ skip_duplicates: Don't create a version node if there are no changes. Same as -nod
91
+ allow_blanks: Update a property even if it is blank
92
+ batch: Number of queries to batch together when processing a node .csv file, significantly improves performance
93
+ auth: Enable Azure Authentication
94
+ order: Order in which to process the input files. Default is qnrc
95
+
96
+ # Override values in the config file
97
+ primary_property: Primary property
98
+ required_labels: Required labels - appended to contents of config; use !Label to remove
99
+ required_properties: Required properties - appended to contents of config; use !property to remove
100
+
101
+ # What output is required
102
+ verify: Display the generated queries, but do not process them
103
+ summarise: Show a summary of the queries, but do not process them
104
+ show_queries: Display the queries as they are processed. No effect if -v present
105
+ show_returns: Display data from any RETURN clause
106
+ write_queries: Name of a file to record the processed queries. No effect if -v present
107
+ write_returns: Name of a file to record the results of the queries. No effect if -v present
108
+ display_rate: Set the frequency of progress update messages. No effect if -v present
109
+
110
+ # Control of the CSV writer
111
+ create_node_csv_file: Create Node csv file(s) from Asset Model'
112
+ node_labels: Lists of labels to identify nodes to write to csv file'
113
+ node_properties: Primary property of nodes'
114
+ csv_file_suffix: Suffix to use in the output Node .csv file'
115
+ create_relationship_csv_file: Create Relationship csv file(s) from Asset Model'
116
+ csv_to_labels: Lists of labels to identify to nodes to write to csv file'
117
+ csv_to_properties: Primary property of To nodes'
118
+
119
+ Returns:
120
+ Boolean for Sucess/Failure. If any queries failed gives False. Logs are printed to terminal during running. TBE
121
+ """
122
+ _asset_model_builder_()
123
+
124
+
125
+ def _asset_model_builder_():
126
+ # Create a configuration manager which will read the command line parameters and the contents of the settings file
127
+ # Any errors are stored in a List, which are then displayed to the user
128
+ config_manager = ConfigManager()
129
+ if config_manager.get_error_count() > 0:
130
+ sys.exit()
131
+
132
+ config_manager.read_csv_config()
133
+ if config_manager.get_error_count() > 0:
134
+ sys.exit()
135
+
136
+ output_file = config_manager.get_query_output()
137
+
138
+ # Read the data needed to create version nodes and relationships
139
+ config_manager.reset_errors()
140
+ config_manager.read_version_config()
141
+ if config_manager.get_error_count() > 0:
142
+ sys.exit()
143
+
144
+ # Create a csv file Manager to process all the input files
145
+ file_manager = FileManager(config_manager)
146
+ file_manager.analyse_files()
147
+
148
+ # Create a connection to the database
149
+ config_manager.reset_errors()
150
+ config_manager.read_db_config()
151
+ if config_manager.get_error_count() > 0:
152
+ sys.exit()
153
+ connection_manager = ConnectionManager(config_manager)
154
+ db_connector = connection_manager.get_db_connector()
155
+
156
+ # And process the generated queries
157
+ file_manager.process_files(db_connector)
158
+
159
+ connection_manager.close()
160
+
161
+
162
+ if __name__ == "__main__":
163
+ _asset_model_builder_()
@@ -0,0 +1,30 @@
1
+ import sys
2
+ from configmanager import ConfigManager
3
+ from connectors.dbconnectors import ConnectionManager
4
+ from filemanager import FileManager
5
+ from csvwriter import CSVFileWriter
6
+
7
+ if __name__ == "__main__":
8
+
9
+ # Create a configuration manager which will read the command line parameters and the contents of the settings file
10
+ # Any errors are stored in a List, which are then displayed to the user
11
+ config_manager = ConfigManager()
12
+ if config_manager.get_error_count() > 0:
13
+ sys.exit()
14
+
15
+ config_manager.read_csv_config()
16
+ if config_manager.get_error_count() > 0:
17
+ sys.exit()
18
+
19
+ # Create a connection to the database
20
+ config_manager.reset_errors()
21
+ config_manager.read_db_config()
22
+ if config_manager.get_error_count() > 0:
23
+ sys.exit()
24
+ connection_manager = ConnectionManager(config_manager)
25
+ db_connector = connection_manager.get_db_connector()
26
+
27
+ csv_generator = CSVFileWriter(config_manager, db_connector)
28
+ csv_generator.write_csv_files()
29
+
30
+ connection_manager.close()
@@ -0,0 +1,121 @@
1
+ from pathlib import Path
2
+ import datetime
3
+ from datetime import timezone
4
+ import re
5
+
6
+ def find_file(path, filename):
7
+ # try the provided path file first, then with the current path. Otherwise, return None to indicate file not found
8
+ if Path(path + filename).is_file():
9
+ full_name = path + filename
10
+ elif Path(filename).is_file():
11
+ full_name = filename
12
+ else:
13
+ full_name = None
14
+ return full_name
15
+
16
+ def get_formatted_time_now():
17
+ # now = datetime.datetime.now(pytz.timezone('Europe/Oslo')).strftime("%Y-%m-%dT%H:%M:%S.%f[%z]")
18
+ now = datetime.datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%dT%H:%M:%S.%f%z")
19
+ return now
20
+
21
+ def get_formatted_time_now_noms():
22
+ now = datetime.datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%dT%H:%M:%S%z")
23
+ return now
24
+
25
+ def get_formatted_future_time():
26
+ future = datetime.datetime(2199, 12, 31).strftime("%Y-%m-%dT%H:%M:%S.%f%z")
27
+ return future
28
+
29
+ def get_time_for_filename():
30
+ now = datetime.datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H-%M-%S-%f")[0:-3]
31
+ return now
32
+
33
+ def remove_leading_chars(string, chars):
34
+ if string:
35
+ while string[0] in chars:
36
+ string = string[1:]
37
+ return string
38
+
39
+ def validate(input, prefix = ''):
40
+ output = f'{prefix}{input}'
41
+ if input:
42
+ if ''.join(re.findall("[A-Za-z0-9_]", input)) != input or ''.join(re.findall("[A-Za-z]", input[0])) != input[0]:
43
+ output = f'{prefix}`{input.replace("`","")}`'
44
+ return output
45
+
46
+ def validate_property(typed_property):
47
+ validated = ''
48
+ property_name = typed_property.split(':')[0]
49
+ if property_name:
50
+ validated += validate(property_name)
51
+ try:
52
+ validated += ':' + typed_property.split(':')[1]
53
+ except:
54
+ pass
55
+ else:
56
+ validated = typed_property
57
+
58
+ return validated
59
+
60
+ def validate_properties(properties):
61
+ validated = {}
62
+ unwanted = []
63
+ if properties:
64
+ for property in properties:
65
+ for prop in property.strip().split(','):
66
+ split_prop = prop.replace('=', ':').split(':')
67
+ ## print(f'vp SP: {split_prop}')
68
+ valid_key = validate(remove_leading_chars(split_prop[0], '!'))
69
+ try:
70
+ validated[valid_key] = split_prop[1]
71
+ except:
72
+ unwanted.append(valid_key)
73
+
74
+ return validated, unwanted
75
+
76
+ def validate_labels_and_relationships(label_list):
77
+ validated = ''
78
+ if label_list:
79
+ required = []
80
+ unwanted = []
81
+ override = []
82
+ for labels in label_list:
83
+ for label in labels.replace(':', ',').split(','):
84
+ if label:
85
+ if label.startswith('!!'):
86
+ override.append(validate(label[2:].strip(), ''))
87
+ elif label.startswith('!'):
88
+ unwanted.append(validate(label[1:].strip(), ''))
89
+ else:
90
+ required.append(validate(label.strip(), ''))
91
+
92
+ combined = [':!!'+i for i in override if i not in unwanted and i not in required]
93
+ combined += [':!'+i for i in unwanted if i not in override and i not in required]
94
+ combined += [':'+i for i in required if i not in override and i not in unwanted]
95
+ validated = ''.join(combined)
96
+
97
+ return validated
98
+
99
+ def combine_required_labels(config_labels, override_labels):
100
+ valid_config_labels = validate_labels_and_relationships(config_labels)[1:].split(':')
101
+ valid_override_labels = validate_labels_and_relationships(override_labels)[1:].split(':')
102
+ required_labels = [i for i in valid_config_labels if (not(i.startswith('!') and ('!'+i not in valid_config_labels)) and ('!'+i not in valid_override_labels))] + [i for i in valid_override_labels if (not(i.startswith('!')) and ('!'+i not in valid_override_labels))]
103
+ unwanted_labels = [i for i in valid_config_labels if ((i.startswith('!') and (i[1:] not in valid_override_labels) and ('!' + i not in valid_override_labels)))] + [i for i in valid_override_labels if i.startswith('!') and not i.startswith('!!')]
104
+
105
+ combined_list = list(set(required_labels + unwanted_labels))
106
+ if '' in combined_list:
107
+ combined_list.remove('')
108
+
109
+ return combined_list
110
+
111
+ def combine_required_properties(config_properties, override_properties):
112
+ valid_config_properties, unwanted_config_properties = validate_properties(config_properties)
113
+ valid_override_properties, unwanted_override_properties = validate_properties(override_properties)
114
+
115
+ config_properties = {i: valid_config_properties[i] for i in valid_config_properties if i not in unwanted_override_properties}
116
+ override_properties = {i: valid_override_properties[i] for i in valid_override_properties}
117
+ required_properties = {**config_properties, **override_properties}
118
+
119
+ unwanted_properties = [i for i in unwanted_override_properties] + [i for i in unwanted_config_properties if i not in valid_override_properties.keys()]
120
+
121
+ return required_properties, unwanted_properties