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.
@@ -0,0 +1,380 @@
1
+ import ast
2
+
3
+ from fileprocessors import FileProcessor
4
+ import assetmodelutilities as amu
5
+ from queries.query import *
6
+ from versionmanager import VersionManager
7
+ from messages import *
8
+ import os
9
+
10
+ class FileManager:
11
+
12
+ def __init__(self, config_manager):
13
+ self.config_manager = config_manager
14
+ self.validation_mode = config_manager.in_validation_mode()
15
+ self.report_queries = config_manager.get_show_query()
16
+ self.show_progress = config_manager.get_display_rate()
17
+ self.show_return = config_manager.get_show_return()
18
+ self.process_order = config_manager.get_process_order()
19
+ self.display_rate = config_manager.get_display_rate()
20
+ self.no_versions = config_manager.get_noversion()
21
+ self.start_from = config_manager.get_start_from()
22
+ self.batch_rate = config_manager.get_batch_rate()
23
+
24
+ # Create a list of error each type
25
+ self.both_file_list = []
26
+ self.neither_file_list = []
27
+ self.file_not_found_list = []
28
+ self.unrecognised_file_type_list = []
29
+ self.incorrect_file_list = []
30
+ self.incomplete_file_list = []
31
+ self.incomplete_file_errors = []
32
+
33
+ # And a list of lists for the queries in specified priority order
34
+ self.valid_file_list = [[], [], [], [], [], []]
35
+
36
+ if not self.no_versions:
37
+ self.version_manager = VersionManager(config_manager)
38
+
39
+ def analyse_a_file(self, filename):
40
+ a_file = filename.replace('\n', '')
41
+ a_file_split = a_file.split('.')
42
+ if len(a_file_split) > 1:
43
+ file_type = a_file_split[-1]
44
+ else:
45
+ file_type = ''
46
+ match file_type:
47
+ case 'csv':
48
+ self.analyse_csv_file(a_file)
49
+ ## json case 'json':
50
+ ## json self.analyse_json_file(a_file)
51
+ case 'cypher' | 'qry':
52
+ self.analyse_cypher_file(a_file)
53
+ case 'lst':
54
+ self.analyse_lst_file(a_file)
55
+ case _:
56
+ self.unrecognised_file_type_list.append(a_file)
57
+
58
+ def add_file_to_process_list(self, file_processor, file_type):
59
+ priority = self.process_order[file_type]
60
+ self.valid_file_list[priority].append({'processor': file_processor, 'type': file_type})
61
+
62
+ def analyse_lst_file(self, filename):
63
+
64
+ f_name = amu.find_file(self.config_manager.get_default_path(), filename)
65
+ if f_name is not None:
66
+ lst_File = open(f_name, 'r')
67
+ for a_File in lst_File:
68
+ if not a_File.startswith('#') and len(a_File) > 0:
69
+ self.analyse_a_file(a_File)
70
+ lst_File.close()
71
+ else:
72
+ warning_message(f'{filename} not found')
73
+
74
+ def analyse_files(self):
75
+
76
+ message('Checking file types...')
77
+ preprocess_list = self.config_manager.get_preprocess_query_list()
78
+ for a_query in preprocess_list:
79
+ if a_query is not None:
80
+ a_query_split = a_query.split('.')
81
+ if len(a_query_split) > 1:
82
+ file_type = a_query_split[-1]
83
+ else:
84
+ file_type = ''
85
+ if file_type == 'cypher' or file_type == 'qry':
86
+ this_file_processor = FileProcessor(a_query, self.config_manager)
87
+ self.add_file_to_process_list(this_file_processor, 'pre-file')
88
+ else:
89
+ query_processor = FileProcessor(a_query, self.config_manager, True)
90
+ self.add_file_to_process_list(query_processor, 'pre')
91
+
92
+ labels_to_delete_list = self.config_manager.get_labels_to_delete_list()
93
+ if labels_to_delete_list == []:
94
+ query = f'MATCH (n) DETACH DELETE n'
95
+ query_processor = FileProcessor(query, self.config_manager, True)
96
+ self.add_file_to_process_list(query_processor, 'pre')
97
+ else:
98
+ for label_list in labels_to_delete_list:
99
+ match_list = ''
100
+ no_match_list = ''
101
+ for label in label_list[1:].split(':'):
102
+ if label.startswith('!'):
103
+ no_match_list += ':' + label[1:]
104
+ else:
105
+ match_list += ':' + label
106
+ query = f'MATCH (n{match_list}) '
107
+ if no_match_list != '':
108
+ query += f'WHERE NOT n{no_match_list} '
109
+ query += 'DETACH DELETE n'
110
+ query_processor = FileProcessor(query, self.config_manager, True)
111
+ self.add_file_to_process_list(query_processor, 'pre')
112
+
113
+ # Process each file in the list, and determine its content type (ignoring any clues in the filename!)
114
+ # Analyse each of the specified input .csv files to determine if they contain Nodes or Relationships
115
+ # If the file doesn't have a valid combination of columns (or is missing) they are placed in the appropriate list
116
+ file_list = self.config_manager.get_input_file_list()
117
+ for a_file in file_list:
118
+ a_file_split = a_file.split(',')
119
+ for a_split_file in a_file_split:
120
+ if a_split_file != '':
121
+ self.analyse_a_file(a_split_file.strip())
122
+
123
+ query_list = self.config_manager.get_inline_query_list()
124
+ for a_query in query_list:
125
+ if a_query is not None:
126
+ query_processor = FileProcessor(a_query, self.config_manager, True)
127
+ self.add_file_to_process_list(query_processor, 'q')
128
+
129
+ postprocess_list = self.config_manager.get_postprocess_query_list()
130
+ for a_query in postprocess_list:
131
+ if a_query is not None:
132
+ a_query_split = a_query.split('.')
133
+ if len(a_query_split) > 1:
134
+ file_type = a_query_split[-1]
135
+ else:
136
+ file_type = ''
137
+ if file_type == 'cypher' or file_type == 'qry':
138
+ this_file_processor = FileProcessor(a_query, self.config_manager)
139
+ self.add_file_to_process_list(this_file_processor, 'post-file')
140
+ else:
141
+ query_processor = FileProcessor(a_query, self.config_manager, True)
142
+ self.add_file_to_process_list(query_processor, 'post')
143
+
144
+ def add_file_to_list(self, this_file_processor, this_file_type, file_errors=None):
145
+
146
+ match this_file_type:
147
+ case 'nodes':
148
+ self.add_file_to_process_list(this_file_processor, 'n')
149
+ case 'relationships':
150
+ self.add_file_to_process_list(this_file_processor, 'r')
151
+ case 'both':
152
+ self.both_file_list.append(this_file_processor.get_filename())
153
+ case 'neither':
154
+ self.neither_file_list.append(this_file_processor.get_filename())
155
+ case 'fnf':
156
+ self.file_not_found_list.append(this_file_processor.get_filename())
157
+ case 'incorrect file format':
158
+ self.incorrect_file_list.append(this_file_processor.get_filename())
159
+ case 'incomplete row(s)':
160
+ self.incomplete_file_list.append([this_file_processor.get_filename(), file_errors])
161
+ case _:
162
+ pass
163
+
164
+ def analyse_csv_file(self, csv_file):
165
+ # Analyse each of the specified input .csv files to determine if they contain Nodes or Relationships
166
+ # If the file doesn't have a valid combination of columns (or is missing) they are placed in the appropriate list
167
+ this_csv_file_processor = FileProcessor(csv_file, self.config_manager)
168
+ this_csv_file_type, file_errors = this_csv_file_processor.determine_file_type('csv')
169
+ self.add_file_to_list(this_csv_file_processor, this_csv_file_type, file_errors)
170
+
171
+ def analyse_json_file(self, json_file):
172
+ # Analyse each of the specified input .json files to determine if they contain Nodes or Relationships
173
+ # If the file doesn't have a valid combination of columns (or is missing) they are placed in the appropriate list
174
+ this_json_file_processor = FileProcessor(json_file, self.config_manager)
175
+ this_json_file_type, file_errors = this_json_file_processor.determine_file_type('json')
176
+ self.add_file_to_list(this_json_file_processor, this_json_file_type, file_errors)
177
+
178
+ def analyse_cypher_file(self, query_file):
179
+ this_file_processor = FileProcessor(query_file, self.config_manager)
180
+ self.add_file_to_process_list(this_file_processor, 'c')
181
+
182
+ def process_files(self, db_connector):
183
+
184
+ # Report on the missing or faulty files
185
+ self.process_invalid_files()
186
+
187
+ # Finally, process the files that we can
188
+ self.all_results = QueryResult(False)
189
+ self.all_version_results = QueryResult(False)
190
+ queries_processed = self.process_valid_files(db_connector)
191
+ info_message(f'{queries_processed} queries processed in total')
192
+ self.all_results.print_results('Total updates made: ')
193
+ self.all_version_results.print_results('Total version updates made: ', '')
194
+
195
+ def process_invalid_files(self):
196
+ self.process_not_found_files()
197
+ self.process_unrecognised_file_type_files()
198
+ self.process_incorrect_files()
199
+ self.process_incomplete_files()
200
+ self.process_neither_found_files()
201
+ self.process_both_files()
202
+
203
+ def process_not_found_files(self):
204
+ for file in self.file_not_found_list:
205
+ warning_message(f'{file} not found')
206
+
207
+ def process_unrecognised_file_type_files(self):
208
+ for file in self.unrecognised_file_type_list:
209
+ error_message(f'{file} has unrecognised file type - file not processed')
210
+
211
+ def process_incorrect_files(self):
212
+ for file in self.incorrect_file_list:
213
+ error_message(f'{file} is not a correctly formatted .csv file - file not processed')
214
+
215
+ def process_incomplete_files(self):
216
+ for file in self.incomplete_file_list:
217
+ error_message(f'{file[0]} has incomplete data in rows {file[1]} - file not processed')
218
+
219
+ def process_neither_found_files(self):
220
+ for file in self.neither_file_list:
221
+ error_message(f'Insufficient data in {file} to determine content type - file not processed')
222
+
223
+ def process_both_files(self):
224
+ for file in self.both_file_list:
225
+ error_message(f'Ambiguous data in {file} - could be multiple content types - file not processed')
226
+
227
+ def process_valid_files(self, db_connector):
228
+ num_queries = 0
229
+ for group in self.valid_file_list:
230
+ for file in group:
231
+ processor = file['processor']
232
+ match file['type']:
233
+ case 'n':
234
+ if self.batch_rate == 0:
235
+ queries, file_result, version_result = self.process_file(processor, FileProcessor.process_node_file, db_connector)
236
+ else:
237
+ queries, file_result, version_result = self.process_file(processor, FileProcessor.process_node_file_batch, db_connector)
238
+ case 'r':
239
+ if self.batch_rate == 0:
240
+ queries, file_result, version_result = self.process_file(processor, FileProcessor.process_relationship_file, db_connector)
241
+ else:
242
+ queries, file_result, version_result = self.process_file(processor, FileProcessor.process_relationship_file_batch, db_connector)
243
+ case 'c' | 'pre-file' | 'post-file':
244
+ queries, file_result, version_result = self.process_file(processor, FileProcessor.process_cypher_file, db_connector)
245
+ case 'q' | 'pre' | 'post':
246
+ queries, file_result, version_result = self.process_file(processor, FileProcessor.process_query_list, db_connector)
247
+ case _:
248
+ # This should never happen!
249
+ queries = 0
250
+ file_result = QueryResult(False)
251
+ version_result = QueryResult(False)
252
+
253
+ num_queries += queries
254
+ self.all_results.combine_results(file_result)
255
+ self.all_version_results.combine_results(version_result)
256
+
257
+ return num_queries
258
+
259
+ def process_file(self, file_to_process, file_processor, db_connector):
260
+ if not self.no_versions:
261
+ self.version_manager.set_db_connector(db_connector)
262
+ node_queries = 0
263
+ num_errors = 0
264
+ error_list = []
265
+ file_results = QueryResult(False)
266
+ version_results = QueryResult(False)
267
+
268
+ query_count = 0
269
+ file_queries = 0
270
+ error_filename = self.config_manager.get_default_path() + 'Failed_queries_' + amu.get_time_for_filename() + '.cypher'
271
+ if error_filename.endswith('.cypher'):
272
+ self.error_file = None
273
+ try:
274
+ self.error_file = open(error_filename, 'w')
275
+ except:
276
+ self.error_file = None
277
+ else:
278
+ self.error_file = None
279
+
280
+ if file_to_process.is_inline_query():
281
+ report_message(f'Processing query "{file_to_process.get_filename()}" at {amu.get_formatted_time_now()}')
282
+ else:
283
+ report_message(f'Processing file "{file_to_process.get_filename()}" at {amu.get_formatted_time_now()}')
284
+ # Build all the queries from the file, depending on the content type of the file
285
+ queries = file_processor(file_to_process, self.start_from)
286
+ message(f'{len(queries)} queries generated from {file_to_process.get_filename()}, processing...')
287
+
288
+ if not self.validation_mode:
289
+
290
+ num_queries = len(queries)
291
+ if self.display_rate == 'auto':
292
+ if num_queries > 10000:
293
+ display_rate = 1000
294
+ elif num_queries > 1000:
295
+ display_rate = 100
296
+ elif num_queries > 100:
297
+ display_rate = 10
298
+ else:
299
+ display_rate = 1
300
+ else:
301
+ try:
302
+ display_rate = int(ast.literal_eval(self.display_rate))
303
+ except:
304
+ display_rate = 0
305
+
306
+ if display_rate > 0:
307
+ message(f'0 of {num_queries} queries processed at {amu.get_formatted_time_now()}', False)
308
+
309
+ # And action each one in turn
310
+ for query in queries:
311
+ query_count += 1
312
+
313
+ if self.report_queries:
314
+ message(f'{query_count} of {num_queries}: {query.text}')
315
+ update_current_node = True
316
+ version_result = None
317
+ if query.type == 'node':
318
+ if not self.no_versions:
319
+ update_current_node, version_result = self.version_manager.make_new_version_of_node(query, db_connector)
320
+ if update_current_node:
321
+ version_results.combine_results(version_result)
322
+ result = db_connector.execute(query, query_count)
323
+ if result.get_status() == 200:
324
+
325
+ # Display info on how many of each batch were created
326
+ # new_nodes = result.get_updates()['nodes created']
327
+ # new_relationships = result.get_updates()['relationships created']
328
+ # if (query.type == 'batch node' and new_nodes != query.batch_size) or (query.type == 'batch relationship' and new_relationships != query.batch_size):
329
+ # info_message(f'Batch {query_count} contained {query.batch_size} updates: only {new_nodes+new_relationships} created')
330
+
331
+ if self.report_queries:
332
+ result.print_results('Updates made: ')
333
+ if version_result:
334
+ version_result.print_results('Version updates made: ', '')
335
+ if self.show_return:
336
+ db_connector.print_response(result.get_response())
337
+ file_results.combine_results(result)
338
+ file_queries += 1
339
+ else:
340
+ if result.get_status() == 414 | 505:
341
+ error_message(f'Query {query_count} returned ', f'{result.get_status()}')
342
+ else:
343
+ error_message(f'{query.text} returned ', f'{result.get_status()}')
344
+ num_errors += 1
345
+ error_list.append(query_count)
346
+ if self.error_file:
347
+ try:
348
+ self.error_file.write(query.text+'\n')
349
+ except:
350
+ pass
351
+ else:
352
+ info_message(f'No changes made by ', query.text)
353
+
354
+ if query.type == 'batch node':
355
+ batch_info = f'{query.batch_size} nodes, {query.property_count} properties, '
356
+ else:
357
+ batch_info = ''
358
+
359
+ if display_rate > 0 and not self.report_queries:
360
+ if query_count % display_rate == 0 or query_count == num_queries:
361
+ message(f'{query_count} of {num_queries} queries processed at {amu.get_formatted_time_now()} ({query_count / num_queries * 100:.2f}%)', False)
362
+ else:
363
+ message_no_cr(f'{query_count} of {num_queries} queries processed ({batch_info}{query_count / num_queries * 100:.2f}%) {chr(13)}')
364
+
365
+ report_message(f'{file_queries} queries processed from {file_to_process.get_filename()} at {amu.get_formatted_time_now()}')
366
+ file_results.print_results('Updates made: ')
367
+ version_results.print_results('Version updates made: ', '')
368
+ if self.error_file:
369
+ self.error_file.close()
370
+ if num_errors > 0:
371
+ report_message(f'{num_errors} queries returned errors: {error_list}')
372
+ report_message(f'Failed queries recorded in {error_filename}')
373
+ else:
374
+ try:
375
+ os.remove(error_filename)
376
+ except:
377
+ pass
378
+ node_queries += file_queries
379
+
380
+ return node_queries, file_results, version_results