Debian Codegraph @

src/cif_files_validator.py

raw symbols SCIP
1 """
2 Python class for validating many cif files at once.
3
4 Usage Example:
5
6 from cif_files_validator import CifFilesValidator
7
8 cif_files_validator = CifFilesValidator()
9 cif_files_validator(
10 input_path=input_path,
11 input_type=input_type,
12 output_path=output_path,
13 output_type=output_type,
14 print_output=print_output,
15 only_print_errors=only_print_errors,
16 output_multiple_files=output_multiple_files,
17 verbose_validation=verbose_validation,
18 verbose_import=verbose_import
19 )
20
21 Created by the Bilbao Crystallographic Server.
22 """
23
24 from zipfile import ZipFile
25 from pathlib import Path
26 from typing import Generator, Tuple, List
27
28 import os
29 import shutil
30 import tarfile
31 import logging
32 import CifFile
33 import CifFile.yapps3_compiled_rt as yappsrt
34
35 logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
36
37 class CifFilesValidator:
38 """
39 Class for validating many cif files at once.
40
41 Attributes:
42 self.input_type_methods (dict): Dictionary to store the functions that read
43 the cif files in different formats.
44 self.output_type_methods (dict): Dictionary to store the functions that
45 write the validation result in different formats.
46 self.logger (Logger): Logger for printing information about the process.
47 """
48
49
50 def __init__(self) -> None:
51
52 # Add methods to open different types of files
53 self.input_type_methods = {}
54 self.input_type_methods['zip'] = self.__open_zip
55 self.input_type_methods['targz'] = self.__open_targz
56 self.input_type_methods['path'] = self.__open_path
57
58 # Add methods to write the output to different types of files
59 self.output_type_methods = {}
60 self.output_type_methods['md'] = self.__write_md
61 self.output_type_methods['err'] = self.__write_err
62
63 self.logger = logging.getLogger('info_logger')
64 self.logger.setLevel(logging.INFO)
65
66 def __open_zip(
67 self,
68 path: Path
69 ) -> Tuple[List, str]:
70 """Auxiliary function to extract the input cif files from
71 a zip file. It extracts all the cif files to a ./temp
72 directory, and afterwards read them with self.__read_path().
73
74 Args:
75 path (Path): Path of the zip file.
76
77 Raises:
78 FileNotFoundError: If the given path for the zip file
79 does not exist.
80 IsADirectoryError: If the given path is a directory.
81 ValueError: If the given path is not a zip file.
82
83 Returns:
84 Generator: Generator for the input cif files.
85 """
86
87 # Make sure that the zip file has the correct format
88 if not path.exists():
89 raise FileNotFoundError("The selected input path does not exist.")
90
91 if path.is_dir():
92 raise IsADirectoryError("The given input path is a directory.")
93
94 if path.suffix != ".zip":
95 raise ValueError("The given input file is not a .zip file.")
96
97 filename = path.stem
98
99 # Create a temporal file to store all the cif file contents
100 if not os.path.exists("./temp"):
101 os.mkdir("./temp")
102
103 if not os.path.exists("./temp/" + filename):
104 os.mkdir("./temp/" + filename)
105
106 # Path to the extracted files
107 zip_file_path = Path("./temp/" + filename)
108
109 # Extract the files
110 with ZipFile(path, "r") as zf:
111 zf.extractall(zip_file_path)
112 self.logger.info("Cifs succesfully extracted to path: %s", zip_file_path)
113
114 filenames, input_path = self.__open_path(zip_file_path)
115
116 return filenames, input_path
117
118 def __open_targz(
119 self,
120 path: Path
121 ) -> Tuple[List, str]:
122 """Auxiliary function to extract the input cif files from
123 a .tar.gz file. It extracts all the cif files to a ./temp
124 directory, and afterwards read them with self.__read_path().
125
126 Args:
127 path (Path): Path of the .tar.gz file.
128
129 Raises:
130 FileNotFoundError: If the given path for the .tar.gz file
131 does not exist.
132 IsADirectoryError: If the given path is a directory.
133 ValueError: If the given path is not a zip file.
134
135 Returns:
136 Generator: Generator for the input cif files.
137 """
138
139 # Make sure that the .tar.gz file has the correct format
140 if not path.exists():
141 raise FileNotFoundError("The selected input path does not exist.")
142
143 if path.is_dir():
144 raise IsADirectoryError("The given input path is a directory.")
145
146 if path.suffixes != ['.tar', '.gz']:
147 raise ValueError("The given input file is not a .tar.gz file.")
148
149 # Create a temporal file to store all the zif file contents
150 if not os.path.exists("./temp"):
151 os.mkdir("./temp")
152
153 tar_file = tarfile.open(path, encoding="utf-8")
154 temp_filename = path.parts[-1]
155 filename = temp_filename.split(".")[0]
156
157 # Path to the extracted files
158 targz_file_path = Path("./temp/" + filename)
159
160 # Extract the files
161 tar_file.extractall(targz_file_path)
162 self.logger.info("Cifs successfully extracted to path: %s.", targz_file_path)
163
164 filenames, input_path = self.__open_path(targz_file_path)
165
166 return filenames, input_path
167
168 def __open_path(
169 self,
170 path: Path
171 )-> Tuple[List, str]:
172 """Auxiliary function to read all the cif files inside of a path.
173 It returns a generator with the cif files, in an arbitrary order.
174
175 Args:
176 path (Path): Path of the input cif files.
177
178 Raises:
179 FileNotFoundError: If the given path does not exist.
180 NotADirectoryError: If the given path is not a directory.
181 ValueError: If the given path is empty.
182
183 Returns:
184 Generator: Generator for the input cif files.
185 """
186 # Check the input file
187 if not path.exists():
188 raise FileNotFoundError("The selected input path does not exist.")
189
190 if not path.is_dir():
191 raise NotADirectoryError("The given input path is not a directory.")
192
193 # Get the generator of the input files
194 filenames = []
195
196
197 for temp in path.iterdir():
198 temp_path = Path(temp)
199
200 if temp_path.is_dir():
201 temp_files, temp_dir = self.__open_path(temp_path)
202 filenames.extend(temp_files)
203
204 else:
205 filenames.append(temp)
206
207 if not filenames:
208 raise ValueError("The given input path does not have any cif file.")
209
210 self.logger.info("Cif files successfully loaded.")
211
212 return filenames, path
213
214 def __get_output_path(
215 self,
216 input_file: str,
217 output_type: str
218 ) -> list:
219 """Function for getting the output names of the validation
220 results for a given input cif.
221
222 Args:
223 input_file (str): Name of the input cif file.
224 output_type (str): Format of the validation result file.
225
226 Returns:
227 list: List with the output names:
228 output_path[0] => Name for the error file.
229 output_path[1] => Name for the warning file.
230 """
231
232 # Get the root of the cif file
233 temp_path = os.path.split(input_file)
234 base_name = temp_path[-1]
235 root_name = base_name.split(".")[0]
236
237 # Get the output names depeding on format
238 if output_type == "err":
239 root_name_err= ".".join((root_name, "err"))
240 root_name_warn = ".".join((root_name, "warn"))
241
242 output_path_err = os.path.join("./", root_name_err)
243 output_path_warn = os.path.join("./", root_name_warn)
244
245 output_path = [output_path_err, output_path_warn]
246
247 else:
248 root_name_err = "_".join((root_name, "err"))
249 root_name_warn = "_".join((root_name, "warn"))
250
251 root_name_err = ".".join((root_name_err, "md"))
252 root_name_warn = ".".join((root_name_warn, "md"))
253
254 output_path_err = os.path.join("./", root_name_err)
255 output_path_warn = os.path.join("./", root_name_warn)
256
257 output_path = [output_path_err, output_path_warn]
258
259 return output_path
260
261 def __get_warnings(
262 self,
263 validation_output: dict,
264 only_print_errors: bool,
265 ) -> dict:
266 """
267 Function for getting only the warnings from the general validation
268 result.
269
270 Args:
271 validation_output (dict): Validation result of all the input cif
272 files.
273 only_print_errors (bool): Whether to print the blocks that have
274 any warning or error. If only_print_errors == True, the blocks
275 that does not have any warning or error are not taken into
276 account.
277
278 Returns:
279 dict: Dictionary containing the warnings of the validation.
280 """
281 warnings = {}
282
283 # Iterate over all the cif files
284 for cif_name, cif_validation_dict in validation_output.items():
285 warnings[cif_name] = {}
286
287 # Iterate per block
288 for block_name, block_result in cif_validation_dict.get("blocks").items():
289 block_has_warnings = block_result.get("has_warnings", False)
290
291 # Retrive all the warnings, even if the block has not any
292 if not only_print_errors:
293 warnings[cif_name][block_name] = block_result["warning_str"]
294
295 # Only get the blocks that have warnings
296 if only_print_errors and block_has_warnings:
297 warnings[cif_name][block_name] = block_result["warning_str"]
298
299
300 return warnings
301
302 def __get_errors(
303 self,
304 validation_output:dict,
305 only_print_errors: bool
306 ) -> dict:
307 """
308 Function for getting only the errors from the general validation
309 result.
310
311 Args:
312 validation_output (dict): Validation result of all the input cif
313 files.
314 only_print_errors (bool): Whether to print the blocks that have
315 any warning or error. If only_print_errors == True, the blocks
316 that does not have any warning or error are not taken into
317 account.
318
319 Returns:
320 dict: Dictionary containing the errors of the validation.
321 """
322 errors = {}
323
324 # Iterate over all the cif files
325 for cif_name, cif_validation_dict in validation_output.items():
326 errors[cif_name] = {}
327
328 # Iterate per block
329 for block_name, block_result in cif_validation_dict.get("blocks").items():
330 block_is_valid = block_result.get("is_valid", False)
331
332 # Retrive all the errors, even if the block has not any
333 if not only_print_errors:
334 errors[cif_name][block_name] = block_result["error_str"]
335
336 # Only get the blocks that have errors
337 if only_print_errors and not block_is_valid:
338 errors[cif_name][block_name] = block_result["error_str"]
339
340 return errors
341
342
343
344 def __filter_errors(
345 self,
346 validation_output: dict
347 ) -> dict:
348 """Function for filtering the validation output dictionary to include only
349 the cifs and data blocks that have errors or warnings.
350
351 Args:
352 validation_output (dict): Full validation output dictionary.
353
354 Returns:
355 dict: Dictionary containing only the datablocks that have errors or warnings.
356 """
357
358 only_error_validation_output = {}
359 for cif_name, cif_validation_dict in validation_output.items():
360 cif_is_valid = cif_validation_dict.get("cif_is_valid", False)
361 cif_has_warnings = cif_validation_dict.get("cif_has_warnings", False)
362
363 # Only continue checking if
364 # the cif has any kind of error or warning
365 if not cif_is_valid or cif_has_warnings:
366
367 # Copy the contents of the cif
368 only_error_validation_output[cif_name] = {}
369 only_error_validation_output[cif_name]["cif_is_valid"] = cif_is_valid
370 only_error_validation_output[cif_name]["cif_has_warnings"] = cif_has_warnings
371 only_error_validation_output[cif_name]["output_str"] = \
372 cif_validation_dict.get("output_str", "")
373 only_error_validation_output[cif_name]["blocks"] = {}
374
375 # Iterate throught the cif block
376 for block_name, block_result in cif_validation_dict.get("blocks").items():
377 block_is_valid = block_result.get("is_valid", False)
378 block_has_warnings = block_result.get("has_warnings", False)
379
380 # Only add a block if its information is not valid
381 if not block_is_valid or block_has_warnings:
382 only_error_validation_output[cif_name]["blocks"][block_name] = block_result
383
384 return only_error_validation_output
385
386 def __write_cifs_to_md(
387 self,
388 output_dict: dict,
389 output_path: str,
390 ) -> None:
391 """
392 Function for writing the validation result of all the input cif
393 files in a single markdown file.
394
395 Args:
396 output_dict (dict): Filtered validation result. It can be
397 a dictionary with the errors or warnings.
398 output_path (str): Path of the output file to write the
399 results.
400 """
401
402 # All the results are written in a single file
403 with open(output_path, "w", encoding="utf-8") as file:
404 for cif_name, cif_result_dict in output_dict.items():
405 # The cif does not have errors or warnings
406 if not cif_result_dict.values():
407 continue
408
409 cif_header = "## " + cif_name + "\n"
410
411 file.write(cif_header)
412 file.write("```shell\n")
413
414 for block_result in cif_result_dict.values():
415 file.write(block_result + "\n")
416
417 file.write("```\n")
418
419 self.logger.info("Validation result generated at: %s.", output_path)
420
421
422 def __write_single_cif_to_md(
423 self,
424 output_dict: dict,
425 write_errors: bool
426 ):
427 """Function for writing the result of each of the input
428 cif files into a single markdown file. A markdown file per
429 input cif is generated.
430
431 Args:
432 output_dict (dict): iltered validation result. It can be
433 a dictionary with the errors or warnings.
434 write_errors (bool): Whether the result being written are
435 errors or warnings.
436 """
437
438 # The validation is stored at "./validation_result"
439 if not os.path.exists("./validation_result"):
440 os.mkdir("./validation_result")
441
442 # Iterate through each input cif
443 for cif_path, cif_result_dict in output_dict.items():
444 head_tail = os.path.split(cif_path)
445 cif_name = head_tail[1].split(".")[0]
446
447 if write_errors:
448 cif_name = cif_name + "_cif_error.md"
449 else:
450 cif_name = cif_name + "_cif_warn.md"
451
452 # Output filename
453 cif_md_filename = os.path.join("validation_result", cif_name)
454
455 # Create a md file per input cif
456 with open(cif_md_filename, "w", encoding="utf-8") as file:
457 cif_header = "## " + cif_name + "\n"
458
459 file.write(cif_header)
460 file.write("```shell\n")
461
462 for block_result in cif_result_dict.values():
463 file.write(block_result + "\n")
464
465 file.write("```\n")
466 self.logger.info("Validation result generated at: %s.", cif_md_filename)
467
468
469
470 def __write_md(
471 self,
472 validation_output: dict,
473 input_path: str,
474 only_print_errors: bool = False,
475 output_multiple_files: bool = False
476 ):
477 """Function to write the validation result to markdown format.
478
479 Args:
480 validation_output (dict): Validation result of the input cif
481 files.
482 input_path (str): Input path of the cif files.
483 only_print_errors (bool, optional): Whether to filter out the blocks
484 without errors or warnings. If only_print_errors == True,
485 All the correct blocks are removed from the result dictionary.
486 Defaults to False.
487 output_multiple_files (bool, optional): Whether to otuput a markdown
488 file per input cif file. Defaults to False.
489 """
490
491 # Remove the correct blocks from the validation result
492 if only_print_errors:
493 validation_output = self.__filter_errors(validation_output)
494
495 # Write all the results to a single markdown file
496 if not output_multiple_files:
497 errors = self.__get_errors(validation_output, only_print_errors)
498 warnings = self.__get_warnings(validation_output, only_print_errors)
499
500 output_paths = self.__get_output_path(input_path, "md")
501
502 error_path = output_paths[0]
503 warning_path = output_paths[1]
504
505 self.__write_cifs_to_md(errors, error_path)
506 self.__write_cifs_to_md(warnings, warning_path)
507
508 else:
509 # Generate a Markdown file per input cif file
510 errors = self.__get_errors(validation_output, only_print_errors)
511 warnings = self.__get_warnings(validation_output, only_print_errors)
512
513 self.__write_single_cif_to_md(errors, True)
514 self.__write_single_cif_to_md(warnings, False)
515
516
517 def __write_cifs_to_err(
518 self,
519 output_dict: dict,
520 output_path: str
521 ):
522 """
523 Function for writing the validation result of all the input cif
524 files in a single .err or .warn file.
525
526 Args:
527 output_dict (dict): Filtered validation result. It can be
528 a dictionary with the errors or warnings.
529 output_path (str): Path of the output file to write the
530 results.
531 """
532 # A single .err/.warn file will be generated
533 with open(output_path, "w", encoding="utf-8") as file:
534 for cif_name, cif_result_dict in output_dict.items():
535 # The cif does not have errors or warnings
536 if not cif_result_dict.values():
537 continue
538 header = "VALIDATION FOR CIF: " + str(cif_name)
539
540 file.write(header)
541
542 for block_result in cif_result_dict.values():
543 file.write(block_result)
544
545 file.write("=============================================\n\n")
546
547 self.logger.info("Validation result generated at: %s.", output_path)
548
549 def __write_single_cif_to_err(
550 self,
551 output_dict: dict,
552 write_errors: bool
553 ):
554 """
555 Function for writing the result of each of the input
556 cif files into a .err/.warn file. A .err/.warn file per
557 input cif is generated.
558
559 Args:
560 output_dict (dict): iltered validation result. It can be
561 a dictionary with the errors or warnings.
562 write_errors (bool): Whether the result being written are
563 errors or warnings.
564 """
565
566 # The validation is stored at "./validation_result"
567 if not os.path.exists("./validation_result"):
568 os.mkdir("./validation_result")
569
570 for cif_path, cif_result_dict in output_dict.items():
571 head_tail = os.path.split(cif_path)
572 cif_name = head_tail[1].split(".")[0]
573
574 if write_errors:
575 cif_name = cif_name + "_cif.err"
576 else:
577 cif_name = cif_name + "_cif.warn"
578
579 # Create output file name
580 cif_filename = os.path.join("validation_result", cif_name)
581
582 # Create a .err/.warn file per input cif
583 with open(cif_filename, "w", encoding="utf-8") as file:
584 header = "VALIDATION FOR CIF: " + str(cif_path)
585 file.write(header)
586
587 for block_result in cif_result_dict.values():
588 file.write(block_result)
589
590 self.logger.info("Validation result generated at: %s.", cif_filename)
591
592 def __write_err(
593 self,
594 validation_output: dict,
595 input_path: str,
596 only_print_errors: bool = False,
597 output_multiple_files: bool = False
598 ):
599 """Function to write the validation result to .err/.warn format.
600 All the errors will appear in the .err file, and the warning in
601 the .warn file.
602
603 Args:
604 validation_output (dict): Validation result of the input cif
605 files.
606 input_path (str): Input path of the cif files.
607 only_print_errors (bool, optional): Whether to filter out the blocks
608 without errors or warnings. If only_print_errors == True,
609 All the correct blocks are removed from the result dictionary.
610 Defaults to False.
611 output_multiple_files (bool, optional): Whether to otuput a .err/.warn
612 file per input cif file. Defaults to False.
613 """
614
615 # Remove all the correct blocks from the validation dict
616 if only_print_errors:
617 self.logger.info("Only print errors selected. Filtering out the correct cifs.")
618 validation_output = self.__filter_errors(validation_output)
619
620 # Generate a single output file
621 if not output_multiple_files:
622 errors = self.__get_errors(validation_output, only_print_errors)
623 warnings = self.__get_warnings(validation_output, only_print_errors)
624
625 output_paths = self.__get_output_path(input_path, "err")
626 error_path = output_paths[0]
627 warning_path = output_paths[1]
628
629 self.__write_cifs_to_err(errors, error_path)
630 self.__write_cifs_to_err(warnings, warning_path)
631
632 else:
633 # Generate an output file per input cif
634 errors = self.__get_errors(validation_output, only_print_errors)
635 warnings = self.__get_warnings(validation_output, only_print_errors)
636
637 self.__write_single_cif_to_err(errors, True)
638 self.__write_single_cif_to_err(warnings, False)
639
640 def __check_dictionaries_path(
641 self,
642 dirname: str,
643 dictnames: list
644 ) -> list:
645 """Function that checks if the provided dictionary paths are
646 correct. If all the paths are correct, it returns a list with
647 the paths of the dictionaries.
648
649 Args:
650 dirname (str): Directory where the dictionaries are stored.
651 dictnames (list): Names of the dictionaries that are stored
652 at dirname.
653
654 Raises:
655 NotADirectoryError: If dirname is not a directory.
656 FileNotFoundError: If any of the dictnames does not correspond
657 to a file.
658
659 Returns:
660 list: List with the joined paths.
661 """
662
663 if not os.path.isdir(dirname):
664 raise NotADirectoryError(f"The given dictionary path ({dirname}) does not exist.")
665
666 joined_dictnames = list(map(lambda a:os.path.join(dirname,a),dictnames))
667
668 for idx, joined_dictname in enumerate(joined_dictnames):
669 if not os.path.isfile(joined_dictname):
670 raise FileNotFoundError(f"The given dictionary path({joined_dictname}) does not exist.")
671
672 return joined_dictnames
673
674
675 def __get_merged_dictionaries(
676 self,
677 dictnames1_0: list,
678 dictnames2_0: list,
679 dirname1_0: str,
680 dirname2_0: str,
681 verbose_import: bool=False,
682 verbose_validation: bool=False
683 ) -> tuple:
684 """Function to get the DDL1 and DDLm dictionaries that are going
685 to be used for validation. This function does the merging of DDL1
686 dictionaries and the importation of the DDLm dictionaries.
687
688 Args:
689 dictnames1_0 (list): DDL1 dictionaries names.
690 dictnames2_0 (list): DDLm dictionaries names.
691 dirname1_0 (str): Directory name where the DDL1 dictionaries
692 are stored.
693 dirname2_0 (str): Directory name where the DDLm dictionaries
694 are stored.
695 verbose_import (bool, optional): Whether to show the dictionary
696 importation logging messages or not. Defaults to False.
697 verbose_validation (bool, optional): Whether to show the logging
698 messages in validation or not. Defaults to False.
699
700 Returns:
701 tuple: Tuple containing the validation dictionaries:
702 tuple[0] ==> DDL1 dictionary.
703 tuple[1] ==> DDLm dictionary.
704 """
705
706 # Merge all the DDL1 dictionaries
707 diclist1_0 = self.__check_dictionaries_path(dirname1_0, dictnames1_0)
708 fulldic1_0 = CifFile.CifFile_module.merge_dic(
709 diclist1_0, verbose_import=verbose_import, verbose_validation=verbose_validation
710 )
711
712 self.logger.info("DDL1 dictionaries merged: %s", dictnames1_0)
713
714 # Import all the DDLm dictionaries
715 # Notice that the imported dictionaries may be inside of the
716 # dictionary itself
717 diclist2_0 = self.__check_dictionaries_path(dirname2_0, dictnames2_0)
718 fulldic2_0 = CifFile.CifFile_module.merge_dic(
719 diclist2_0, verbose_import=verbose_import, verbose_validation=verbose_validation
720 )
721
722 self.logger.info(
723 "DDLm dictionaries successfully loaded: %s. Check also for the possible imported dictionaries.", dictnames2_0
724 )
725 return fulldic1_0, fulldic2_0
726
727 def __print_cif_syntax_error(
728 self,
729 parsing_result: list,
730 cif_file_name: str
731 ) -> str:
732 """Function for returning a syntax error, in case this happens.
733
734 Args:
735 parsing_result (list): List with the objects for getting
736 the parsing error.
737 cif_file_name (str): Name of the cif file that has the
738 parsing error.
739
740 Returns:
741 str: Parsing error string.
742 """
743 error = parsing_result[1]
744
745 # error[0] == -1
746 if isinstance(error, yappsrt.YappsSyntaxError):
747 parser = parsing_result[2]
748 Y = parsing_result[3]
749
750 scanner = parser._scanner
751 input = parser._scanner.input
752 pos = error.charpos
753
754 line_number = scanner.get_line_number_with_pos(pos)
755
756 out_str = "\n"
757 out_str += "======================================================================\n"
758 out_str += "\n"
759 out_str += "SYNTAX ERROR AT LINE " + str(line_number) + " WHEN PARSING INPUT FILE:" + str(cif_file_name) + ":\n"
760 out_str += str(error.msg) + "\n"
761 out_str += "\n"
762 out_str += "ERROR NEAR THE FOLLOWING INPUT TEXT:\n"
763
764 text_error = Y.yappsrt.print_line_with_pointer(input, pos)
765
766 out_str += text_error
767 print(out_str)
768
769 return out_str
770
771 # error[0] == -2
772 if isinstance(error, CifFile.StarError):
773 print(error.value)
774
775 return error.value
776
777 def __validate_cif(
778 self,
779 cif_input_path: Path,
780 fulldic1_0: CifFile.CifDic,
781 fulldic2_0: CifFile.CifDic
782 ) -> tuple:
783 """Function to validate a singe cif.
784
785 Args:
786 cif_input_path (Path): Path of the input cif file.
787 fulldic1_0 (CifFile.CifDic): DDL1 dictionary.
788 fulldic2_0 (CifFile.CifDic): DDLm dictionary.
789
790 Returns:
791 tuple: Validation result of the cif.
792 tuple[0] ==> String representing the whole validation.
793 tuple[1] ==> Dictionary that represents the result.
794 """
795
796 # Parse the input cif
797 cf = CifFile.CifFile(str(cif_input_path), grammar="auto")
798 result = cf.get_parsing_result()
799 output_dict = {}
800
801 # The cif has syntax errors
802 if result[0] < 0:
803 error_str = self.__print_cif_syntax_error(result, cif_input_path)
804 output_dict["output_str"] = error_str
805 return error_str, output_dict
806
807 # Determine the cif version
808 if cf.grammar in ["1.0", "1.1"]:
809 fulldic = fulldic1_0
810
811 else:
812 fulldic = fulldic2_0
813
814 # Validate the cif
815 cc = CifFile.Validate(cf, dic=fulldic, isdic=False)
816 repor_str, dict_summary = CifFile.validate_report(cc, use_html=False)
817
818 # Store the result in a more general dictionary
819 output_dict["output_str"] = repor_str
820
821 output_dict["cif_is_valid"] = dict_summary["cif_is_valid"]
822 output_dict["cif_has_warnings"] = dict_summary["cif_has_warnings"]
823 output_dict["blocks"] = dict_summary["blocks"]
824
825 return repor_str, output_dict
826
827
828 def __validate_cif_files(
829 self,
830 cif_files: Generator,
831 dictionaries: dict,
832 print_output: bool=False,
833 verbose_validation: bool=False,
834 verbose_import: bool=False
835 ) -> dict:
836 """General function to validate all the input cifs.
837
838 Args:
839 cif_files (Generator): Generator for the input cif filenames.
840 dictionaries (dict): Dictionary containing the names and the
841 directories of the DDL1 and DDLm dictionaries that will be used
842 for validation.
843 print_output (bool, optional): Whether to print the validation output
844 of each of the cifs. Defaults to False.
845 verbose_validation (bool, optional): Whether to log information in
846 the validation process. Defaults to False.
847 verbose_import (bool, optional): Whether to log information when
848 importing the dictionaries. Defaults to False.
849
850 Returns:
851 dict: Dictionary containing the validation results of all the input cifs.
852 """
853 # Get DDL1 and DDLm dictionaries
854 fulldic1_0, fulldic2_0 = self.__get_merged_dictionaries(
855 dictnames1_0=dictionaries.get("ddl1_dictionaries"),
856 dictnames2_0=dictionaries.get("ddlm_dictionaries"),
857 dirname1_0=dictionaries.get("ddl1_dir"),
858 dirname2_0=dictionaries.get("ddlm_dir"),
859 verbose_validation=verbose_validation,
860 verbose_import=verbose_import
861 )
862
863 validation_result = {}
864
865 # Validate the cif files
866 for cif_file in cif_files:
867 cif_file = str(cif_file)
868 repor_str, dict_summary = self.__validate_cif(cif_file, fulldic1_0, fulldic2_0)
869 if print_output:
870 print(repor_str)
871
872 validation_result[cif_file] = dict_summary
873
874 return validation_result
875
876
877 def __get_input_path_type(
878 self,
879 input_path: Path
880 ) -> str:
881 """Function to automatically infer the format of the input data.
882 It returns the format so that the file can be opened later.
883
884 Args:
885 input_path (Path): Path of the input file.
886
887 Raises:
888 ValueError: If the input file is not a file, a .zip or .tar.gz file.
889
890 Returns:
891 str: Extension of the input file.
892 """
893 if input_path.is_dir():
894 return "path"
895
896 if input_path.suffix == '.zip':
897 return "zip"
898
899 if input_path.suffix == '.gz':
900 return "targz"
901
902 raise ValueError("ERROR: Invalid input format. Only path, .zip and .tar.gz are accepted.")
903
904 def __call__(
905 self,
906 input_path: str,
907 output_type: str = None,
908 print_output: bool = False,
909 only_print_errors: bool = False,
910 dictionaries: dict = {},
911 output_multiple_files: bool = False,
912 verbose_validation: bool = False,
913 verbose_import: bool = False
914 ) -> None:
915 """Function for validating the input cifs. It reads, validates
916 and writes the result to the desired format.
917
918 Args:
919 input_path (str): Input path of the input cifs.
920 output_type (str, optional): Format of the output file. Defaults to None.
921 print_output (bool, optional): Whether to print the validation output
922 of each of the cifs. Defaults to False.
923 only_print_errors (bool, optional): Whether to filter out the blocks
924 without errors or warnings. If only_print_errors == True,
925 All the correct blocks are removed from the result dictionary.
926 Defaults to False.
927 dictionaries (dict, optional): Dictionary containing the names and the
928 directories of the DDL1 and DDLm dictionaries that will be used
929 for validation.
930 output_multiple_files (bool, optional): _description_. Defaults to False.
931 verbose_import (bool, optional): Whether to show the dictionary
932 importation logging messages or not. Defaults to False.
933 verbose_validation (bool, optional): Whether to show the logging
934 messages in validation or not. Defaults to False.
935 """
936
937 # Construct Path objects
938 input_path = Path(input_path)
939
940 # Open data
941 try:
942 input_type = self.__get_input_path_type(input_path)
943
944 except ValueError as e:
945 print(e)
946 return -1
947
948 input_data_function = self.input_type_methods[input_type]
949
950 # Read the input cifs
951 input_cifs, input_dir = input_data_function(input_path)
952
953 # Validating the input cifs
954 self.logger.info("Starting validation process.")
955 try:
956 validation_output = self.__validate_cif_files(
957 input_cifs, dictionaries, print_output ,verbose_validation, verbose_import
958 )
959
960 except Exception as e:
961 print(e)
962 return -1
963
964 self.logger.info("Validation process finished.")
965
966 try:
967 output_data_function = self.output_type_methods[output_type]
968
969 except KeyError:
970 print("The selected output type is incorrect.")
971
972 # Write the validation result
973 output_data_function(
974 validation_output,
975 input_path,
976 only_print_errors,
977 output_multiple_files
978 )
979
980 # Remove the temporal directory
981 if input_data_function != "path":
982 if input_dir.is_relative_to('./temp'):
983 shutil.rmtree('./temp')
984
985 else:
986 shutil.rmtree(input_dir)
987
988 self.logger.info("Temporal directory %s has been removed.", input_dir)