python-eigen-ingenuity 0.5.29b1__py3-none-any.whl → 0.5.30__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.
@@ -1,8 +1,13 @@
1
+ from __future__ import annotations
2
+
1
3
  from pathlib import Path
2
4
  import datetime
3
5
  from datetime import timezone
4
6
  import re
5
7
 
8
+ import codecs
9
+ import string
10
+
6
11
  # Define special types that are used by the Neo4j importer
7
12
  # They are also used in Java asset model builder
8
13
  # Could add these to the config file at some point, but they are unlikely to change
@@ -54,3 +59,180 @@ def validate(input, prefix=''):
54
59
  output = f'{prefix}`{input.replace("`","``")}`'
55
60
 
56
61
  return output
62
+
63
+
64
+ #!SECTION --------- Detect Encoding and Read CSV File --------- #
65
+ """Small utility to guess file encodings.
66
+
67
+ Usage:
68
+ python scripts/detect_encoding.py path/to/file
69
+ python scripts/detect_encoding.py path/to/file --top 5
70
+ """
71
+
72
+ BOM_MAP = {
73
+ codecs.BOM_UTF8: "utf-8-sig",
74
+ codecs.BOM_UTF16_LE: "utf-16-le",
75
+ codecs.BOM_UTF16_BE: "utf-16-be",
76
+ codecs.BOM_UTF32_LE: "utf-32-le",
77
+ codecs.BOM_UTF32_BE: "utf-32-be",
78
+ }
79
+
80
+ # Good practical set for CSV/text files seen on macOS/Windows/Linux.
81
+ CANDIDATE_ENCODINGS = [
82
+ "utf-8",
83
+ "utf-8-sig",
84
+ "utf-16",
85
+ "utf-16-le",
86
+ "utf-16-be",
87
+ "utf-32",
88
+ "cp1252",
89
+ "iso-8859-1",
90
+ "mac_roman",
91
+ ]
92
+
93
+
94
+ def has_bom(data: bytes) -> str | None:
95
+ for bom, name in BOM_MAP.items():
96
+ if data.startswith(bom):
97
+ return name
98
+ return None
99
+
100
+
101
+ def printable_score(text: str) -> float:
102
+ if not text:
103
+ return 0.0
104
+
105
+ printable = 0
106
+ for ch in text:
107
+ o = ord(ch)
108
+ if ch in "\n\r\t" or 32 <= o <= 126 or o >= 160:
109
+ printable += 1
110
+ return printable / len(text)
111
+
112
+
113
+ def control_ratio(text: str) -> float:
114
+ if not text:
115
+ return 1.0
116
+
117
+ bad = 0
118
+ for ch in text:
119
+ o = ord(ch)
120
+ if o < 32 and ch not in "\n\r\t":
121
+ bad += 1
122
+ return bad / len(text)
123
+
124
+
125
+ def latinish_ratio(text: str) -> float:
126
+ """Roughly how much text looks like western-language data."""
127
+ if not text:
128
+ return 0.0
129
+
130
+ allowed = set(string.ascii_letters + string.digits + " \n\r\t;,:._-()[]{}'\"/+*&%$#@!?=<>\\")
131
+ good = 0
132
+ for ch in text:
133
+ o = ord(ch)
134
+ if ch in allowed or (160 <= o <= 255):
135
+ good += 1
136
+ return good / len(text)
137
+
138
+
139
+ def csv_structure_score(text: str) -> float:
140
+ """Reward candidate decodings that preserve table-like delimiters."""
141
+ lines = [ln for ln in text.splitlines()[:30] if ln]
142
+ if not lines:
143
+ return 0.0
144
+
145
+ semicolons = sum(ln.count(";") for ln in lines)
146
+ commas = sum(ln.count(",") for ln in lines)
147
+ delimiters = max(semicolons, commas)
148
+ # Normalize: 2+ delimiters/line is a strong sign for CSV-like files.
149
+ per_line = delimiters / len(lines)
150
+ return min(per_line / 2.0, 1.0)
151
+
152
+
153
+ def utf16_raw_plausibility(data: bytes) -> float:
154
+ """UTF-16 text with many latin characters usually contains many zero bytes."""
155
+ if not data:
156
+ return 0.0
157
+ zero_ratio = data.count(0) / len(data)
158
+ return min(zero_ratio / 0.2, 1.0)
159
+
160
+
161
+ def encoding_score(enc: str, data: bytes, text: str, bom: str | None) -> tuple[float, str]:
162
+ p = printable_score(text)
163
+ c = control_ratio(text)
164
+ l = latinish_ratio(text)
165
+ s = csv_structure_score(text)
166
+
167
+ # Weighted blend: printable text matters, but structure and latin plausibility
168
+ # prevent false positives like random CJK-looking output from UTF-16 misdecode.
169
+ score = 0.35 * p + 0.25 * l + 0.35 * s + 0.05 * (1.0 - c)
170
+
171
+ notes = [f"p={p:.2f}", f"latin={l:.2f}", f"csv={s:.2f}", f"ctrl={c:.2f}"]
172
+
173
+ if enc.startswith("utf-16"):
174
+ raw_utf16 = utf16_raw_plausibility(data)
175
+ notes.append(f"utf16raw={raw_utf16:.2f}")
176
+ if bom is None:
177
+ # Without BOM, demand some raw-byte evidence before trusting UTF-16.
178
+ score *= (0.1 + 0.9 * raw_utf16)
179
+
180
+ return max(0.0, min(score, 1.0)), "; ".join(notes)
181
+
182
+
183
+ def try_candidates(data: bytes) -> list[tuple[str, float, str]]:
184
+ results: list[tuple[str, float, str]] = []
185
+ bom = has_bom(data)
186
+
187
+ for enc in CANDIDATE_ENCODINGS:
188
+ try:
189
+ text = data.decode(enc)
190
+ score, detail = encoding_score(enc, data, text, bom)
191
+ note = f"ok; {detail}"
192
+ except UnicodeDecodeError as exc:
193
+ score = 0.0
194
+ note = f"decode error at byte {exc.start}"
195
+ except Exception as exc: # defensive fallback
196
+ score = 0.0
197
+ note = f"error: {exc}"
198
+
199
+ results.append((enc, score, note))
200
+
201
+ results.sort(key=lambda x: x[1], reverse=True)
202
+ return results
203
+
204
+
205
+ def optional_charset_normalizer(data: bytes) -> tuple[str, float] | None:
206
+ try:
207
+ from charset_normalizer import from_bytes # type: ignore
208
+ except Exception:
209
+ return None
210
+
211
+ best = from_bytes(data).best()
212
+ if best is None:
213
+ return None
214
+
215
+ confidence = 1.0 - float(best.chaos or 1.0)
216
+ return str(best.encoding), max(0.0, min(confidence, 1.0))
217
+
218
+
219
+ def detect_encoding(file, threshold, logger, max_results=3) -> int:
220
+
221
+ file_path = Path(file)
222
+ if not file_path.exists() or not file_path.is_file():
223
+ return []
224
+
225
+ data = file_path.read_bytes()
226
+ if not data:
227
+ return []
228
+
229
+ candidates = try_candidates(data)
230
+ results = []
231
+ logger(f"Encoding candidates for {file}:")
232
+ logger(candidates)
233
+ for enc, score, note in candidates[: max(1, max_results)]:
234
+ if score > threshold:
235
+ results.append(enc)
236
+
237
+ return results
238
+
@@ -74,9 +74,17 @@ class ConfigManager:
74
74
 
75
75
  parser.add_argument('-ctl', '--csvtolabels', default='', help='Lists of labels to identify to nodes to write to csv file')
76
76
  parser.add_argument('-ctp', '--csvtoproperties', nargs='+', default=None, help='Primary node_key of To nodes')
77
+
78
+ parser.add_argument('-de', '--detect_encoding', action='store_true', help='Enable automatic encoding detection for input files. Will try to find the most likely match for a file. This is not bomb-proof, as it uses heuristic methods to guess the encoding, but it can be useful if you have files with non-standard encodings. Overrides the default encoding attempts if enabled')
79
+ parser.add_argument('-fe', '--force_encoding', default=False, help='Pass a specific encoding to force for input files e.g. "macroman", rather than assuming utf-8 as default. Overrides -de if both are present')
80
+ parser.add_argument('-dbg', '--debug', action='store_true', help='Enable debug mode')
77
81
 
78
82
  args = parser.parse_args()
79
83
 
84
+
85
+ self.logger = (lambda *args, **kwargs: print('[DEBUG]', *args, **kwargs)) if args.debug else (lambda *args, **kwargs: None)
86
+ self.detect_encoding = args.detect_encoding
87
+ self.force_encoding = args.force_encoding
80
88
  self.path = args.path
81
89
  self.config_file = args.config
82
90
  self.config_section = args.configsection
@@ -625,3 +633,12 @@ class ConfigManager:
625
633
 
626
634
  def get_parameters(self):
627
635
  return self.parameters
636
+
637
+ def get_logger(self):
638
+ return self.logger
639
+
640
+ def get_force_encoding(self):
641
+ return self.force_encoding
642
+
643
+ def get_detect_encoding(self):
644
+ return self.detect_encoding
@@ -133,21 +133,24 @@ class CSVContentsManager:
133
133
 
134
134
  def get_property_values_dict(self, row_number, column_numbers, allow_blank_property_list, default_key='', prefix='', blank_override='', allow_split=True):
135
135
  this_row = self.data_list[row_number]
136
- if allow_split:
137
- split_values = [this_row[column].split('::') for column in column_numbers]
138
- else:
139
- split_values = [[this_row[column]] for column in column_numbers]
140
- split_keys = [(value[0] + ':').split(':') for value in split_values]
141
- this_list = {prefix + (self.mapped_keys[column] or default_key): Neo4jProperty(prefix + (self.mapped_keys[column] or default_key), this_row[column], self.formats[column], blank_override=blank_override) if len(split_values[count]) == 1 else {prefix + (split_keys[count][0] or default_key): Neo4jProperty(prefix + (split_keys[count][0] or default_key), split_values[count][1], split_keys[count][1] or self.formats[column], blank_override=blank_override)} for count, column in enumerate(column_numbers) if this_row[column] or self.mapped_keys[column] in allow_blank_property_list or allow_blank_property_list == []}
136
+ split_values, labels, split_keys = self.get_property_value_data(this_row, column_numbers, allow_split)
137
+ this_list = {prefix + (self.mapped_keys[column] or default_key): Neo4jProperty(prefix + (self.mapped_keys[column] or default_key), this_row[column], self.formats[column], blank_override=blank_override, labels=labels[count]) if len(split_values[count]) == 1 else {prefix + (split_keys[count][0] or default_key): Neo4jProperty(prefix + (split_keys[count][0] or default_key), split_values[count][1], split_keys[count][1] or self.formats[column], blank_override=blank_override, labels=labels[0])} for count, column in enumerate(column_numbers) if this_row[column] or self.mapped_keys[column] in allow_blank_property_list or allow_blank_property_list == []}
142
138
  return this_list
143
139
 
144
140
  def get_property_values_list(self, row_number, column_numbers, default_key='', override_key='', allow_split=True, override_format=None):
145
141
  this_row = self.data_list[row_number]
146
- if allow_split:
147
- split_values = [this_row[column].split('::') for column in column_numbers]
148
- else:
149
- split_values = [[this_row[column]] for column in column_numbers]
150
- split_keys = [(value[0]+':').split(':') for value in split_values]
142
+ split_values, labels, split_keys = self.get_property_value_data(this_row, column_numbers, allow_split)
151
143
  these_keys = [override_key or self.mapped_keys[column] if self.types[column] == '' else self.mapped_keys[column] or default_key for column in column_numbers]
152
- this_list = [Neo4jProperty(these_keys[count], this_row[column], override_format or self.formats[column]) if len(split_values[count]) == 1 else Neo4jProperty(split_values[count][0] or default_key, split_values[count][1], override_format or split_keys[count][1] or self.formats[column]) for count, column in enumerate(column_numbers) if this_row[column]]
144
+ this_list = [Neo4jProperty(these_keys[count], split_values[count][0], override_format or self.formats[column], labels=labels[count]) if len(split_values[count]) == 1 else Neo4jProperty(split_values[count][0] or default_key, split_values[count][1], override_format or split_keys[count][1] or self.formats[column], labels=labels[count]) for count, column in enumerate(column_numbers) if this_row[column]]
153
145
  return this_list
146
+
147
+ def get_property_value_data(self, this_row, column_numbers, allow_split=True):
148
+ if allow_split:
149
+ split_vals = [this_row[column].split('::') for column in column_numbers]
150
+ else:
151
+ split_vals = [[this_row[column]] for column in column_numbers]
152
+ split_values = [[split_val[0].split(':')[0]] if len(split_val) == 1 else [split_val[0], split_val[1].split(':')[0]] for split_val in split_vals]
153
+ labels = [[(split_val[-1]+':').split(':', 1)[1][0:-1]] for split_val in split_vals]
154
+ split_keys = [(value[0] + ':').split(':') for value in split_values]
155
+
156
+ return split_values, labels, split_keys
@@ -1,4 +1,7 @@
1
1
  import csv
2
+ from io import StringIO
3
+ from charset_normalizer import from_bytes
4
+ import unicodedata
2
5
 
3
6
  import messages
4
7
  from csvcontentsmanager import CSVContentsManager
@@ -9,6 +12,9 @@ class FileAnalyser():
9
12
  def __init__(self, config, section):
10
13
  self.separator = config.get_separator()[section]
11
14
  self.def_path = config.get_default_path()
15
+ self.logger = config.get_logger()
16
+ self.detect_encoding = config.get_detect_encoding()
17
+ self.force_encoding = config.get_force_encoding()
12
18
 
13
19
  header_mappings, alias_mappings = config.get_header_mappings()
14
20
  self.header_mappings = header_mappings[section]
@@ -36,27 +42,106 @@ class FileAnalyser():
36
42
  file_name = amu.find_file(self.def_path, filename)
37
43
  if file_name is None:
38
44
  return 'fnf', contents, []
39
-
40
- match file_format:
41
- case 'csv':
42
- try:
43
- with open(file_name, encoding='utf-8') as csv_file:
44
- csv_data = csv.reader(csv_file, delimiter=self.separator)
45
- contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
46
- except:
47
- try:
48
- with open(file_name) as csv_file:
49
- csv_data = csv.reader(csv_file, delimiter=self.separator)
50
- contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
51
- except:
45
+
46
+
47
+ if self.force_encoding:
48
+ try:
49
+ self.logger(f"Trying to read file with forced encoding {self.force_encoding}")
50
+ with open(file_name, encoding=self.force_encoding) as csv_file:
51
+ csv_data = csv.reader(csv_file, delimiter=self.separator)
52
+ contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
53
+ except Exception as exc:
54
+ self.logger(f"Error reading file with forced encoding {self.force_encoding}: {exc}")
55
+ match file_format:
56
+ case 'csv':
52
57
  try:
53
- with open(file_name, encoding='iso-8859-1') as csv_file:
58
+ with open(file_name, "rb") as f:
59
+ raw = f.read()
60
+
61
+ # detect encoding
62
+ result = from_bytes(raw)
63
+ best = result.best()
64
+
65
+ if best is None:
66
+ return 'incorrect file format', None, []
67
+
68
+ text = str(best)
69
+
70
+ # normalize unicode (fix Mac/Windows accent differences)
71
+ text = unicodedata.normalize("NFC", text)
72
+
73
+ csv_data = csv.reader(
74
+ StringIO(text),
75
+ delimiter=self.separator
76
+ )
77
+
78
+ contents = CSVContentsManager(
79
+ csv_data,
80
+ self.header_mappings,
81
+ self.alias_mappings,
82
+ self.default_data_type
83
+ )
84
+
85
+ except Exception:
86
+ return 'incorrect file format', None, []
87
+ case _:
88
+ pass
89
+ elif self.detect_encoding:
90
+ try:
91
+ self.logger('Detecting file encoding...')
92
+
93
+ encoding_candidates = amu.detect_encoding(file_name, threshold=0.5, logger=self.logger)
94
+ if encoding_candidates and len(encoding_candidates) > 0:
95
+ self.logger(f"Found encoding candidates: {encoding_candidates}")
96
+ for encoding in encoding_candidates:
97
+ try:
98
+ with open(file_name, encoding=encoding) as csv_file:
54
99
  csv_data = csv.reader(csv_file, delimiter=self.separator)
55
100
  contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
56
- except:
101
+ break
102
+ except Exception as exc:
103
+ self.logger(f"Error reading file with encoding {encoding}: {exc}")
57
104
  return 'incorrect file format', contents, []
58
- case _:
59
- pass
105
+ except Exception as exc:
106
+ self.logger(f"Error during encoding detection: {exc}")
107
+ return 'incorrect file format', contents, []
108
+ else:
109
+ match file_format:
110
+ case 'csv':
111
+ try:
112
+ with open(file_name, "rb") as f:
113
+ raw = f.read()
114
+
115
+ # detect encoding
116
+ result = from_bytes(raw)
117
+ best = result.best()
118
+
119
+ if best is None:
120
+ return 'incorrect file format', None, []
121
+
122
+ text = str(best)
123
+
124
+ # normalize unicode (fix Mac/Windows accent differences)
125
+ text = unicodedata.normalize("NFC", text)
126
+
127
+ csv_data = csv.reader(
128
+ StringIO(text),
129
+ delimiter=self.separator
130
+ )
131
+
132
+ contents = CSVContentsManager(
133
+ csv_data,
134
+ self.header_mappings,
135
+ self.alias_mappings,
136
+ self.default_data_type
137
+ )
138
+
139
+ except Exception:
140
+ return 'incorrect file format', None, []
141
+ case _:
142
+ pass
143
+
144
+
60
145
 
61
146
  num_node_columns = contents.get_column_count(self.node_alias, self.node_types)
62
147
  num_from_columns = contents.get_column_count(self.from_node_alias, self.from_types)
@@ -71,7 +156,7 @@ class FileAnalyser():
71
156
  if num_node_columns > 0:
72
157
  could_be_node = True
73
158
  if num_node_columns > 1:
74
- messages.warning_message(f'Multiple node columns found in ', f'{filename}')
159
+ messages.warning_message('Multiple node columns found in ', f'{filename}')
75
160
  else:
76
161
  could_be_node = False
77
162
 
@@ -121,6 +121,12 @@ def strip_quotes(quote_list):
121
121
  return stripped_list
122
122
 
123
123
 
124
+ def merge_node_labels(merge_labels, node_labels):
125
+ wanted, _, remove = sort_labels(merge_labels, node_labels)
126
+ merged_labels = [i for i in merge_labels + wanted if not i in remove]
127
+ return merged_labels
128
+
129
+
124
130
  def merge_labels(self, required_labels, unrequired_labels, remove_labels):
125
131
  merged_labels = [i for i in self.required_labels + required_labels if (not ('!' + i in unrequired_labels) and not (i in remove_labels) and not (i.startswith('!')))]
126
132
  return merged_labels
@@ -70,7 +70,6 @@ class NodeFileProcessor:
70
70
 
71
71
  while this_row < last_row:
72
72
  validated_csv_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, label_columns))
73
- merge_labels, new_labels, remove_labels = lm.sort_node_labels(self.required_labels, validated_csv_labels)
74
73
  row_properties = self.contents.get_property_values_dict(this_row, property_columns, self.blank_property_list, blank_override=self.blank_property_override, allow_split=False)
75
74
  properties = pm.combine_properties(self.required_properties, row_properties)
76
75
  # Remove any properties we don't want
@@ -82,11 +81,13 @@ class NodeFileProcessor:
82
81
 
83
82
  for primary_property in self.contents.get_property_values_list(this_row, node_columns, self.primary_property, allow_split=True, override_format='str'):
84
83
  time_now = amu.get_formatted_time_now()
84
+ merge_labels, new_labels, remove_labels = lm.sort_node_labels(self.required_labels, validated_csv_labels)
85
+ node_labels = lm.merge_node_labels(merge_labels, primary_property.labels)
85
86
 
86
87
  # Build a simple MERGE query using queries
87
88
  query_text = (QueryBuilder()
88
89
  .merge()
89
- .node(labels=merge_labels, ref_name=property_ref, properties=primary_property)
90
+ .node(labels=node_labels, ref_name=property_ref, properties=primary_property)
90
91
  )
91
92
 
92
93
  # Add in System properties if required
@@ -156,10 +157,11 @@ class NodeFileProcessor:
156
157
 
157
158
  while this_row < last_row:
158
159
  validated_csv_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, label_columns))
159
- merge_labels, new_labels, remove_labels = lm.sort_node_labels(self.required_labels, validated_csv_labels)
160
160
  row_properties = self.contents.get_property_values_dict(this_row, property_columns, self.blank_property_list, blank_override=self.blank_property_override, allow_split=False)
161
161
 
162
162
  for primary_property in self.contents.get_property_values_list(this_row, node_columns, self.primary_property, allow_split=True, override_format='str'):
163
+ merge_labels, new_labels, remove_labels = lm.sort_node_labels(self.required_labels, validated_csv_labels)
164
+ node_labels = lm.merge_node_labels(merge_labels, primary_property.labels)
163
165
  properties = pm.combine_properties(self.required_properties, row_properties)
164
166
  # Remove any properties we don't want
165
167
  for unwanted in self.unrequired_properties:
@@ -181,7 +183,7 @@ class NodeFileProcessor:
181
183
  # So now we know all about this particular update. Let's put it in the query dictionary
182
184
  # We'll group these by unique combinations of labels and primary key type
183
185
  # Have to use a list since a dictionary key can't be a dictionary
184
- dictionary_key = [new_labels, merge_labels, remove_labels, [primary_property.key], calculated_properties.keys()]
186
+ dictionary_key = [new_labels, node_labels, remove_labels, [primary_property.key], calculated_properties.keys()]
185
187
  try:
186
188
  dictionary_index = batch_keys.index(dictionary_key)
187
189
  query_dictionary[dictionary_index] += query_data_list
@@ -98,9 +98,11 @@ class RelationshipFileProcessor:
98
98
  for from_node in self.contents.get_property_values_list(this_row, from_columns, self.primary_property, self.from_property, override_format='str'):
99
99
  validated_csv_from_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, from_label_columns))
100
100
  from_labels = lm.sort_relationship_labels(self.required_labels + self.from_required_labels, validated_csv_from_labels)
101
+ from_node_labels = lm.merge_node_labels(from_labels, from_node.labels)
101
102
  for to_node in self.contents.get_property_values_list(this_row, to_columns, self.primary_property, self.to_property, override_format='str'):
102
103
  validated_csv_to_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, to_label_columns))
103
104
  to_labels = lm.sort_relationship_labels(self.required_labels + self.to_required_labels, validated_csv_to_labels)
105
+ to_node_labels = lm.merge_node_labels(to_labels, to_node.labels)
104
106
 
105
107
  # Build a MERGE query for the relationship(s)
106
108
  for relationship in relationships:
@@ -110,9 +112,9 @@ class RelationshipFileProcessor:
110
112
  time_now = amu.get_formatted_time_now()
111
113
  query_text = (QueryBuilder()
112
114
  .match()
113
- .node(labels=from_labels, ref_name=from_ref, properties=from_node)
115
+ .node(labels=from_node_labels, ref_name=from_ref, properties=from_node)
114
116
  .match()
115
- .node(labels=to_labels, ref_name=to_ref, properties=to_node)
117
+ .node(labels=to_node_labels, ref_name=to_ref, properties=to_node)
116
118
  .merge()
117
119
  .node(ref_name=from_ref)
118
120
  .related_to(label=relation, ref_name=relation_ref)
@@ -134,7 +136,7 @@ class RelationshipFileProcessor:
134
136
  query_list = self.query_manager.parameterise(query_text, self.section)
135
137
 
136
138
  for a_query in query_list:
137
- query = Neo4jQuery('node', a_query, time_now)
139
+ query = Neo4jQuery('relationship', a_query, time_now)
138
140
  if self.validate_only and not self.summarise:
139
141
  print(a_query)
140
142
  queries.append(query)
@@ -196,9 +198,11 @@ class RelationshipFileProcessor:
196
198
  for from_node in self.contents.get_property_values_list(this_row, from_columns, self.primary_property, self.from_property, override_format='str'):
197
199
  validated_csv_from_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, from_label_columns))
198
200
  from_labels = lm.sort_relationship_labels(self.required_labels + self.from_required_labels, validated_csv_from_labels)
201
+ from_node_labels = lm.merge_node_labels(from_labels, from_node.labels)
199
202
  for to_node in self.contents.get_property_values_list(this_row, to_columns, self.primary_property, self.to_property, override_format='str'):
200
203
  validated_csv_to_labels = lm.validate_labels(self.contents.get_column_values_list(this_row, to_label_columns))
201
204
  to_labels = lm.sort_relationship_labels(self.required_labels + self.to_required_labels, validated_csv_to_labels)
205
+ to_node_labels = lm.merge_node_labels(to_labels, to_node.labels)
202
206
 
203
207
  # Build a MERGE query for the relationship(s)
204
208
  for relationship in relationships:
@@ -214,7 +218,7 @@ class RelationshipFileProcessor:
214
218
 
215
219
  query_data_list = []
216
220
  for count in range(max(len(param_from_nodes), len(param_to_nodes), len(param_explicit_props), len(param_calc_props))):
217
- new_labels_list = [[from_labels, to_labels, relation, from_node.key, to_node.key, param_calc_props[min(count, len(param_calc_props) - 1)]]]
221
+ new_labels_list = [[from_node_labels, to_node_labels, relation, from_node.key, to_node.key, param_calc_props[min(count, len(param_calc_props) - 1)]]]
218
222
  query_data_list += [[param_from_nodes[min(count, len(param_from_nodes) - 1)].value.replace('\\\\n', '\n'), param_to_nodes[min(count, len(param_to_nodes) - 1)].value.replace('\\\\n', '\n'), param_explicit_props[min(count, len(param_explicit_props) - 1)], param_calc_props[min(count, len(param_calc_props) - 1)], time_now]]
219
223
 
220
224
  # So now we know all about this particular update. Let's put it in the query dictionary
@@ -2,15 +2,20 @@ import datetime
2
2
  import messages
3
3
  import ast
4
4
  import processors.propertymanager as pm
5
+ import processors.labelmanager as lm
5
6
  from querymanager import QueryManager
6
7
 
7
8
  class Neo4jProperty():
8
9
 
9
- def __init__(self, key, value = None, format = None, type = None, blank_override = False):
10
+ def __init__(self, key, value=None, format=None, type=None, blank_override=False, labels=[]):
10
11
 
11
12
  self.key = pm.validate_property(key)
12
13
  # Sanitise the value
13
14
  self.value = value.replace('\\', '\\\\').replace('\r', '\\r').replace('"', '\\"')
15
+ if labels == ['']:
16
+ self.labels = []
17
+ else:
18
+ self.labels = lm.validate_labels(labels)
14
19
 
15
20
  if self.value == "":
16
21
  if blank_override:
@@ -54,7 +59,7 @@ class Neo4jProperty():
54
59
 
55
60
  def get_value(self, ref):
56
61
  # Check to see if we have a formatted value, and if not do it now
57
- if not ref in self.formatted_values.keys():
62
+ if ref not in self.formatted_values.keys():
58
63
  self.formatted_values[ref] = format_value(self, ref)
59
64
 
60
65
  return self.formatted_values[ref]
@@ -336,6 +341,7 @@ def format(properties, property_ref='', query_manager = None, section='DEFAULT')
336
341
  return QueryManager.parameterise(query_manager, pair_data, section)
337
342
 
338
343
 
344
+
339
345
  def to_str(properties, comparison_operator: str = ':', boolean_operator: str = ',', property_ref='', key_ref='') -> str:
340
346
  pairs = [f'{key_ref}{key.split(":")[0]}{comparison_operator}{Neo4jProperty(key, str(value)).get_value(property_ref)}' for key, value in properties.items()]
341
347
  res = boolean_operator.join(pairs)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-eigen-ingenuity
3
- Version: 0.5.29b1
3
+ Version: 0.5.30
4
4
  Summary: A python library used to query data from the Eigen Ingenuity system
5
5
  Home-page: https://www.eigen.co/
6
6
  Author: Murray Callander
@@ -39,14 +39,14 @@ modelbuilder/__init__.py,sha256=HSsHItu5BbGQiHYTG00QPMNDbC3RkRUaaN50YpksIUA,171
39
39
  modelbuilder/src/__init__.py,sha256=bMvb-E_plw2dz9_TYIPevQuvDNmKtW0dmBgnQE9ylwc,57
40
40
  modelbuilder/src/assetmodelbuilder.py,sha256=92Yu9CvmObPYDdqCpn8eBCaZ_KGBhm307YsFt6cg2Eg,8886
41
41
  modelbuilder/src/assetmodelcsvwriter.py,sha256=GKNi_fw7AlY-UG2XhwFIS34Ff3XiVRss-o5MUzyJSV0,1071
42
- modelbuilder/src/assetmodelutilities.py,sha256=S_q5F7mVulk13zCeC1A8cLkJDXj_BR5_yFi3vTw3xUQ,1746
43
- modelbuilder/src/configmanager.py,sha256=PbqzYwav6rAm-3Wd8JegYuEEY44iugC_IQ45abUkGbI,30789
44
- modelbuilder/src/csvcontentsmanager.py,sha256=rVJmR6cPZMS851GeCsRgKzY7b6E_wdbM24rvS0c2feA,7838
42
+ modelbuilder/src/assetmodelutilities.py,sha256=1j-S2CKaxcde-Pj6AfgYMGOKu13kwA-sIJSIyLqMW94,6700
43
+ modelbuilder/src/configmanager.py,sha256=Orwg_75Zk8Go_RdmFnEoKKRLJp6_2XZAtPRQZuD5Zmc,31937
44
+ modelbuilder/src/csvcontentsmanager.py,sha256=601JuaT5rxlTlj58uK50c6vSUk4NKh4pGOrVq9ECX8o,8247
45
45
  modelbuilder/src/csvwriter.py,sha256=2Xc6kdV6cYwCjrVF6WaZfS6tVp8-oc0ksIHSOx6iqj8,14132
46
- modelbuilder/src/fileanalyser.py,sha256=L7x44NmOaD0spXO9GLAWrGTp-npM8T0xCqCYesMGHgU,4301
46
+ modelbuilder/src/fileanalyser.py,sha256=4hFuggAKG2N67iuQSISKDRiV2SedNZzgcyqJ2bU6Ibg,7660
47
47
  modelbuilder/src/filemanager.py,sha256=nfRQlW-AIp8ICu1CO0MO55OyWMWDQJrW4Z8yRRhBs-k,26454
48
48
  modelbuilder/src/messages.py,sha256=6JnW-ke6nHGUA4hTEBvo_kVlNJTXoV4LWw8mNwMpBCQ,1325
49
- modelbuilder/src/property.py,sha256=MQ2jY3EKvPAIF-bWKrkrXj55I3AW1eujAnY4pkw_4IE,11441
49
+ modelbuilder/src/property.py,sha256=lwYUuN17q1g9MHE2K2yM03ArfEPWmzRP9yxfS1tYbo8,11605
50
50
  modelbuilder/src/querymanager.py,sha256=Wr0LcY7iCwmLyeSx8LcdbQT2xt1viltp6XFvP3Bg5v8,3270
51
51
  modelbuilder/src/versionmanager.py,sha256=B8mrYY5Der0sWi1GQjduyVGZ6BuAb6rTNVAZzQlP4k4,19148
52
52
  modelbuilder/src/connectors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -56,10 +56,10 @@ modelbuilder/src/connectors/genericconnector.py,sha256=bMfnbrOWq97BC9oM7RIA58bNd
56
56
  modelbuilder/src/connectors/httpsconnector.py,sha256=DOZyxRW3JQcaiaYtnx0_Jq2dBEhgSUIubnx5jj7OY_g,6078
57
57
  modelbuilder/src/processors/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
58
58
  modelbuilder/src/processors/cypherfileprocessor.py,sha256=EmaLsBhC6gWQwvhyY7Ks2HEbGEzDoGAZfu2nBkh2hOs,2941
59
- modelbuilder/src/processors/labelmanager.py,sha256=b2xkIqMd2hptplm5Sp10zoc7LGOKTVZH2jDKN7brvYU,6619
60
- modelbuilder/src/processors/nodefileprocessor.py,sha256=-9vH1trZuYY6OFxfABCimJ2eEKCwGUnby-1ExDraQug,14561
59
+ modelbuilder/src/processors/labelmanager.py,sha256=iJRygoLYcKj5v8d2ncRMMqAYfKzYL1jgYwoYVA2sycw,6833
60
+ modelbuilder/src/processors/nodefileprocessor.py,sha256=DLzJzsl4APjX8CsKyZY7GRNtr0rJcteFi0TsdM4hAXI,14747
61
61
  modelbuilder/src/processors/propertymanager.py,sha256=zLr8S0HPZMXeUp1RUzVXWyNa64MxLufXrOqh5uL1mwU,6978
62
- modelbuilder/src/processors/relationshipfileprocessor.py,sha256=1osOMAaSKkVZTDZlk_XiZQyp8mGPAsmWgCMYm59ccdo,19143
62
+ modelbuilder/src/processors/relationshipfileprocessor.py,sha256=e0YewiXMZRRFs-wl-vl7VDPI06xEoltHXHHk1SOSRuk,19515
63
63
  modelbuilder/src/processors/relationshipmanager.py,sha256=lDtE_5AdKzL3boq7VD8Gmpai8Uscq79vRxkzYQL8A9A,1105
64
64
  modelbuilder/src/queries/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
65
65
  modelbuilder/src/queries/cypherbuilder.py,sha256=VpUGuPo-Ba3skjCVBFjmxm4ORQBGgF5cDiQYnK67hLA,10418
@@ -88,8 +88,8 @@ regressiontests/eigeningenuity/historian-multi/test_getRawDatapoints.py,sha256=f
88
88
  regressiontests/eigeningenuity/historian-multi/test_listDataTags.py,sha256=TcceNSjCKoiK5SJcgTH2JXfKLYxIHdQdwZWlkpGnEVM,2006
89
89
  regressiontests/eigeningenuity/historian-multi/test_tagManagement.py,sha256=ylInBt453d1RaSih1eTTxGPZmb60UK4vMwI3UW-U1JY,4830
90
90
  regressiontests/eigeningenuity/historian-multi/test_writePoints.py,sha256=51tfUSLUqLKcCKJ1EyhjfzoC_4OP6n1oL3zgTSkXu4s,2696
91
- python_eigen_ingenuity-0.5.29b1.dist-info/METADATA,sha256=QPLpg6vx1IHUfMtVYc-rkpf6IaZBLeoILABSx9LwIXw,8124
92
- python_eigen_ingenuity-0.5.29b1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
93
- python_eigen_ingenuity-0.5.29b1.dist-info/entry_points.txt,sha256=G3LjFQX5xKaN4mqtqCL8uaC-gRbP5T5x9r0gBTJTXXA,70
94
- python_eigen_ingenuity-0.5.29b1.dist-info/top_level.txt,sha256=oDWOSmlNPKNBlIEKP8_JaV01O60jTcUIt2tDkq3OD18,56
95
- python_eigen_ingenuity-0.5.29b1.dist-info/RECORD,,
91
+ python_eigen_ingenuity-0.5.30.dist-info/METADATA,sha256=LlMjmLPXv4OUvbe6jGpnucmq1hzVeL_1zd0y20Il_5w,8122
92
+ python_eigen_ingenuity-0.5.30.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
93
+ python_eigen_ingenuity-0.5.30.dist-info/entry_points.txt,sha256=G3LjFQX5xKaN4mqtqCL8uaC-gRbP5T5x9r0gBTJTXXA,70
94
+ python_eigen_ingenuity-0.5.30.dist-info/top_level.txt,sha256=oDWOSmlNPKNBlIEKP8_JaV01O60jTcUIt2tDkq3OD18,56
95
+ python_eigen_ingenuity-0.5.30.dist-info/RECORD,,