python-eigen-ingenuity 0.5.30b2__py3-none-any.whl → 0.5.30b3__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
@@ -9,6 +9,9 @@ class FileAnalyser():
9
9
  def __init__(self, config, section):
10
10
  self.separator = config.get_separator()[section]
11
11
  self.def_path = config.get_default_path()
12
+ self.logger = config.get_logger()
13
+ self.detect_encoding = config.get_detect_encoding()
14
+ self.force_encoding = config.get_force_encoding()
12
15
 
13
16
  header_mappings, alias_mappings = config.get_header_mappings()
14
17
  self.header_mappings = header_mappings[section]
@@ -36,27 +39,61 @@ class FileAnalyser():
36
39
  file_name = amu.find_file(self.def_path, filename)
37
40
  if file_name is None:
38
41
  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:
42
+
43
+
44
+ if self.force_encoding:
45
+ try:
46
+ self.logger(f"Trying to read file with forced encoding {self.force_encoding}")
47
+ with open(file_name, encoding=self.force_encoding) as csv_file:
48
+ csv_data = csv.reader(csv_file, delimiter=self.separator)
49
+ contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
50
+ except Exception as exc:
51
+ self.logger(f"Error reading file with forced encoding {self.force_encoding}: {exc}")
52
+ return 'incorrect file format', contents, []
53
+ elif self.detect_encoding:
54
+ try:
55
+ self.logger('Detecting file encoding...')
56
+
57
+ encoding_candidates = amu.detect_encoding(file_name, threshold=0.5, logger=self.logger)
58
+ if encoding_candidates and len(encoding_candidates) > 0:
59
+ self.logger(f"Found encoding candidates: {encoding_candidates}")
60
+ for encoding in encoding_candidates:
61
+ try:
62
+ with open(file_name, encoding=encoding) as csv_file:
63
+ csv_data = csv.reader(csv_file, delimiter=self.separator)
64
+ contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
65
+ break
66
+ except Exception as exc:
67
+ self.logger(f"Error reading file with encoding {encoding}: {exc}")
68
+ return 'incorrect file format', contents, []
69
+ except Exception as exc:
70
+ self.logger(f"Error during encoding detection: {exc}")
71
+ return 'incorrect file format', contents, []
72
+ else:
73
+ match file_format:
74
+ case 'csv':
47
75
  try:
48
- with open(file_name) as csv_file:
76
+ self.logger('Trying to read file with utf-8 encoding')
77
+ with open(file_name, encoding='utf-8') as csv_file:
49
78
  csv_data = csv.reader(csv_file, delimiter=self.separator)
50
79
  contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
51
80
  except:
52
81
  try:
53
- with open(file_name, encoding='iso-8859-1') as csv_file:
82
+ self.logger('utf-8 encoding failed, trying to auto-detect encoding')
83
+ with open(file_name) as csv_file:
54
84
  csv_data = csv.reader(csv_file, delimiter=self.separator)
55
85
  contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
56
86
  except:
57
- return 'incorrect file format', contents, []
58
- case _:
59
- pass
87
+ try:
88
+ self.logger('auto-detect encoding failed, trying iso-8859-1')
89
+
90
+ with open(file_name, encoding='iso-8859-1') as csv_file:
91
+ csv_data = csv.reader(csv_file, delimiter=self.separator)
92
+ contents = CSVContentsManager(csv_data, self.header_mappings, self.alias_mappings, self.default_data_type)
93
+ except:
94
+ return 'incorrect file format', contents, []
95
+ case _:
96
+ pass
60
97
 
61
98
  num_node_columns = contents.get_column_count(self.node_alias, self.node_types)
62
99
  num_from_columns = contents.get_column_count(self.from_node_alias, self.from_types)
@@ -71,7 +108,7 @@ class FileAnalyser():
71
108
  if num_node_columns > 0:
72
109
  could_be_node = True
73
110
  if num_node_columns > 1:
74
- messages.warning_message(f'Multiple node columns found in ', f'{filename}')
111
+ messages.warning_message('Multiple node columns found in ', f'{filename}')
75
112
  else:
76
113
  could_be_node = False
77
114
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-eigen-ingenuity
3
- Version: 0.5.30b2
3
+ Version: 0.5.30b3
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,11 +39,11 @@ 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
42
+ modelbuilder/src/assetmodelutilities.py,sha256=1j-S2CKaxcde-Pj6AfgYMGOKu13kwA-sIJSIyLqMW94,6700
43
+ modelbuilder/src/configmanager.py,sha256=Orwg_75Zk8Go_RdmFnEoKKRLJp6_2XZAtPRQZuD5Zmc,31937
44
44
  modelbuilder/src/csvcontentsmanager.py,sha256=25JbbbmgnebAkjr_RvItBBZXK8Cq66a4Lcea9bWqcdk,8258
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=edcy8iyl0kGRuWApqA3339kz3bH8nYJ2PHD4w7edyrg,6711
47
47
  modelbuilder/src/filemanager.py,sha256=nfRQlW-AIp8ICu1CO0MO55OyWMWDQJrW4Z8yRRhBs-k,26454
48
48
  modelbuilder/src/messages.py,sha256=6JnW-ke6nHGUA4hTEBvo_kVlNJTXoV4LWw8mNwMpBCQ,1325
49
49
  modelbuilder/src/property.py,sha256=W67yx-vourlFDTsAcSgJOOlb4Q0exZFWf3gbNP2blJI,11615
@@ -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.30b2.dist-info/METADATA,sha256=AbdsRsoYzLw_z-GD-s8R7ieHaFvVP50ljsDzE1qCyIE,8124
92
- python_eigen_ingenuity-0.5.30b2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
93
- python_eigen_ingenuity-0.5.30b2.dist-info/entry_points.txt,sha256=G3LjFQX5xKaN4mqtqCL8uaC-gRbP5T5x9r0gBTJTXXA,70
94
- python_eigen_ingenuity-0.5.30b2.dist-info/top_level.txt,sha256=oDWOSmlNPKNBlIEKP8_JaV01O60jTcUIt2tDkq3OD18,56
95
- python_eigen_ingenuity-0.5.30b2.dist-info/RECORD,,
91
+ python_eigen_ingenuity-0.5.30b3.dist-info/METADATA,sha256=BadFVtYPUBR0rksSCT6nq8wwsUVATM-wf-Vgu3tWpVQ,8124
92
+ python_eigen_ingenuity-0.5.30b3.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
93
+ python_eigen_ingenuity-0.5.30b3.dist-info/entry_points.txt,sha256=G3LjFQX5xKaN4mqtqCL8uaC-gRbP5T5x9r0gBTJTXXA,70
94
+ python_eigen_ingenuity-0.5.30b3.dist-info/top_level.txt,sha256=oDWOSmlNPKNBlIEKP8_JaV01O60jTcUIt2tDkq3OD18,56
95
+ python_eigen_ingenuity-0.5.30b3.dist-info/RECORD,,