import sys import os from datetime import date import json from io import StringIO from lxml import etree import xml.etree.ElementTree as ET import zipfile import fnmatch import logging import shutil #level 2: section #level 3: subsection overview #level 4: subsection #level 5: class #level 6: subclass #level 7: group #level 8: subgroup # Section (one letter A to H and also Y) # Class (two digits) # Subclass (one letter) # Group (one to three digits) # Main group and subgroups (at least two digits) # Example: "A01B33/00" # Section A # Class 01 # Subclass B # Group 33 # Main group 00 SECTIONS = [] SUBSECTIONS_OVERVIEW = [] SUBSECTIONS = [] CLASSES = [] SUBCLASSES = [] SUBCLASSES_OVERVIEW = [] GROUPS = [] SUBGROUPS = [] def get_level_four_backwards(node, level, item): try: if len(node.findall('.//classification-item[@level="%s"]'%level)) >= 1: subsection_elements = node.findall('.//classification-item[@level="%s"]'%level) for element in subsection_elements: date_revised = element.attrib["date-revised"] tag = element.find('./classification-symbol').text title_elements = element.findall('./class-title//text') title_list = [el.text for el in title_elements] titles = "; ".join(title_list) if level == 2: SECTIONS.append({ "cpc_section_date_revised": date_revised, "cpc_section_number": tag, "cpc_section_name": titles }) elif level == 3: SUBSECTIONS_OVERVIEW.append({ "cpc_subsection_overview_date_revised": date_revised, "cpc_subsection_overview_number": tag, "cpc_subsection_overview_name": titles }) elif level == 4: SUBSECTIONS.append({ "cpc_subsection_date_revised": date_revised, "cpc_subsection_number": tag, "cpc_subsection_name": titles }) except: print(f"Error in parsing {item} info in level {level}") def get_level_six_forwards(node, level, item): try: #check for the highlevel xml specifications if len(node.findall('.//classification-item[@level="2"]')) >= 1: return if len(node.findall('.//classification-item[@level="%s"]'%level)) >= 1: elements = node.findall('.//classification-item[@level="%s"]'%level) for element in elements: date_revised = element.attrib["date-revised"] tag = element.find('./classification-symbol').text if element.find('./class-title'): titles = " ".join(" ".join(element.find('./class-title').itertext()).split()) else: titles = "" if level == 6: SUBCLASSES_OVERVIEW.append({ "cpc_subclass_overview_date_revised": date_revised, "cpc_subclass_overview_number": tag, "cpc_subclass_overview_name": titles }) elif level == 7: SUBCLASSES.append({ "cpc_subclass_date_revised": date_revised, "cpc_subclass_number": tag, "cpc_subclass_name": titles }) elif level == 8: GROUPS.append({ "cpc_group_date_revised": date_revised, "cpc_group_number": tag, "cpc_group_name": titles }) elif level == 9: SUBGROUPS.append({ "cpc_subgroup_date_revised": date_revised, "cpc_subgroup_number": tag, "cpc_subgroup_name": titles }) except: print(f"Error in parsing {item} info in level {level}") def get_class_info(node): try: #check for the highlevel xml specifications if len(node.findall('.//classification-item[@level="2"]')) >= 1: return if len(node.findall('.//classification-item[@level="5"]')) == 1: class_element = node.find('.//classification-item[@level="5"]') date_revised = class_element.attrib["date-revised"] class_tag = class_element.find('./classification-symbol').text class_titles = " ".join("".join(class_element.find('./class-title').itertext()).split()) CLASSES.append({ "cpc_class_date_revised": date_revised, "cpc_class_number": class_tag, "cpc_class_name": class_titles }) except: print("Error in parsing class info") def write_json(): print('********WRITING JSON********') final_json = { "sections": SECTIONS, "subsections_overview": SUBSECTIONS_OVERVIEW, "subsections": SUBSECTIONS, "classes": CLASSES, "subclasses_overview": SUBCLASSES_OVERVIEW, "subclasses": SUBCLASSES, "groups": GROUPS, "subgroups": SUBGROUPS } with open('CPC_files.json', 'w', encoding='utf-8') as f: json.dump(final_json, f, indent=4, ensure_ascii=False) def parse_xml(node): get_level_four_backwards(node, 2, "section") get_level_four_backwards(node, 3, "subsection_overview") get_level_four_backwards(node, 4, "subsection") get_class_info(node) get_level_six_forwards(node, 6, "subclass_overview") get_level_six_forwards(node, 7, "subclass") get_level_six_forwards(node, 8, "group") get_level_six_forwards(node, 9, "subgroup") def read_parse_xmls(path): logger = logging.getLogger("run_parse_xmls") counter = 0 passes = 0 failes = 0 print('********PARSING: XMLs********') pattern = "*.xml" for root, dirs, files in os.walk(path): for file in fnmatch.filter(files, pattern): with open(os.path.join(root, file), "r", encoding='utf-8') as xml_file: if xml_file.name.endswith('.xml') and not file == "cpc-scheme.xml": print("Parsing file: " + xml_file.name) counter+=1 try: xml_string = xml_file.read() # xml_dict = xmltodict.parse(xml_read) # check_dtd_version(xml_dict) # tree = etree.parse(os.path.join(root, file)) tree_root = ET.fromstring(xml_string) parse_xml(tree_root) passes += 1 except Exception as e: print("Failed to parse " + xml_file.name) print(e) logger.error("Failed to parse " + xml_file.name) logger.error(e) # copy failed file into new directory path = "failed_xmls" if not os.path.exists(path): os.mkdir(path) try: shutil.copyfile((os.path.join(root, file)), (path + "/" + file)) except: print("Failed to copy file " + xml_file.name + "into failed_xmls - folder after the parsing failed.") logger.error("Failed to copy file " + xml_file.name + "into failed_xmls - folder after the parsing failed.") failes +=1 print(f"xml total count {counter}, total passes {round(passes/counter,2)}%, total failes {round(failes/counter,2)}%") logger.info(f"xml total count {counter}, total passes {round(passes/counter,2)}%, total failes {round(failes/counter,2)}%") # unzips main directory def unzip_first_level(path): logger = logging.getLogger("unzip_first_level") files=os.listdir(path) print('********UNZIPPING: top directory********') print(f'Current directory: {path}') for file in files: if file.endswith('.zip'): if not os.path.exists(os.path.join(path, os.path.splitext(file)[0])): try: print(f'Extracting file: {file}') print(os.path.join(file, os.path.splitext(file)[0])) zipfile.ZipFile(os.path.join(path, file)).extractall(os.path.join(path, os.path.splitext(file)[0])) except zipfile.BadZipfile: print(f'Cannot extract {file}: Not a valid zipfile (BadZipfile Exception)') logger.error(f'Cannot extract {file}: Not a valid zipfile (BadZipfile Exception)') else: print(f'File already exists: {file}') if __name__ == '__main__': logging.basicConfig(filename='app.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s %(message)s') logger=logging.getLogger(__name__) try: if len(sys.argv) != 2: sys.exit("No path given.") unzip_first_level(sys.argv[1]) read_parse_xmls(sys.argv[1]) write_json() except Exception as err: logger.error(err)