added logging, fixed bugs, coping failed files into folder

This commit is contained in:
2023-03-03 16:04:38 +01:00
parent 77336a3e23
commit 0fa4095aa5
+126 -6
View File
@@ -8,6 +8,7 @@ from lxml import etree
import zipfile
import fnmatch
import logging
import shutil
# writes the python-dict into a json
def write_to_json(es_dict, id, name):
@@ -23,7 +24,7 @@ def write_to_json(es_dict, id, name):
except:
print("-Failed to write "+ name)
# parses aa xpath-tree
# parses a xpath-tree
def parse_Element(tree, i, o, current_text, list_depth, additional_node, section_name):
return_text = current_text
@@ -259,6 +260,7 @@ def parse(xml_dict, filename, tree):
# patent information tags
if sdobi.get("B500") != None:
# patent classification tags from 2005 and earlier
# ipc
if sdobi.get("B500").get("B510") != None:
es_dict["ipc"] = [sdobi.get("B500").get("B510")]
es_dict["ipc_text"] = sdobi.get("B500").get("B510")
@@ -277,6 +279,7 @@ def parse(xml_dict, filename, tree):
# patent classification tags from 2006 and later
# its one string that needs to be splittet into the classification parts
# ipc
if sdobi.get("B500").get("B510EP") != None:
ip = sdobi.get("B500").get("B510EP").get("classification-ipcr")
@@ -339,6 +342,30 @@ def parse(xml_dict, filename, tree):
es_dict["data2"] = data2
es_dict["office"] = office
# patent classification
# cpc
if sdobi.get("B500").get("B520EP") != None:
if sdobi.get("B500").get("B520EP").get("classification-cpc") != None:
cp = sdobi.get("B500").get("B520EP").get("classification-cpc")
texte = []
try:
if cp.get("text") != None:
texte.append(ip.get("text"))
except:
for i in range(len(cp)):
texte.append(cp[i].get("text"))
es_dict["cpc"] = texte
text_combi = ""
for text in texte:
text_combi += text + " - "
text_combi = text_combi[:-3]
es_dict["cpc_text"] = text_combi
# title in en, de and fr
if sdobi.get("B500").get("B540") != None:
if sdobi.get("B500").get("B540").get("B541")[0] == "de":
@@ -377,6 +404,16 @@ def parse(xml_dict, filename, tree):
street = sdobi.get("B700").get("B710").get("B711").get("adr").get("str")
city = sdobi.get("B700").get("B710").get("B711").get("adr").get("city")
country = sdobi.get("B700").get("B710").get("B711").get("adr").get("ctry")
if name == None:
name = ""
if street == None:
street = ""
if city == None:
city = ""
if country == None:
country = ""
applicant = name + ", " + street + ", " + city + ", " + country
es_dict["applicants"] = [applicant]
es_dict["applicants_name"] = [name]
@@ -406,6 +443,16 @@ def parse(xml_dict, filename, tree):
street = appli.get("adr").get("str")
city = appli.get("adr").get("city")
country = appli.get("adr").get("ctry")
if name == None:
name = ""
if street == None:
street = ""
if city == None:
city = ""
if country == None:
country = ""
applis.append(name + ", " + street + ", " + city + ", " + country)
names.append(name)
adrs.append("" + street + ", " + city + ", " + country)
@@ -418,6 +465,8 @@ def parse(xml_dict, filename, tree):
t = ""
for name in names:
if name == None:
continue
t += name + " - "
t = t[:-3]
es_dict["applicants_name_text"] = t
@@ -433,6 +482,16 @@ def parse(xml_dict, filename, tree):
street = sdobi.get("B700").get("B720").get("B721").get("adr").get("str")
city = sdobi.get("B700").get("B720").get("B721").get("adr").get("city")
country = sdobi.get("B700").get("B720").get("B721").get("adr").get("ctry")
if name == None:
name = ""
if street == None:
street = ""
if city == None:
city = ""
if country == None:
country = ""
inventor = name + ", " + street + ", " + city + ", " + country
es_dict["inventors"] = [inventor]
es_dict["inventors_name"] = [name]
@@ -462,6 +521,16 @@ def parse(xml_dict, filename, tree):
street = inv.get("adr").get("str")
city = inv.get("adr").get("city")
country = inv.get("adr").get("ctry")
if name == None:
name = ""
if street == None:
street = ""
if city == None:
city = ""
if country == None:
country = ""
invs.append(name + ", " + street + ", " + city + ", " + country)
names.append(name)
adrs.append("" + street + ", " + city + ", " + country)
@@ -474,6 +543,8 @@ def parse(xml_dict, filename, tree):
t = ""
for name in names:
if name == None:
continue
t += name + " - "
t = t[:-3]
es_dict["inventors_name_text"] = t
@@ -489,6 +560,16 @@ def parse(xml_dict, filename, tree):
street = sdobi.get("B700").get("B740").get("B741").get("adr").get("str")
city = sdobi.get("B700").get("B740").get("B741").get("adr").get("city")
country = sdobi.get("B700").get("B740").get("B741").get("adr").get("ctry")
if name == None:
name = ""
if street == None:
street = ""
if city == None:
city = ""
if country == None:
country = ""
rep = name + ", " + street + ", " + city + ", " + country
es_dict["representatives"] = [rep]
es_dict["representatives_name"] = [name]
@@ -518,6 +599,16 @@ def parse(xml_dict, filename, tree):
street = rep.get("adr").get("str")
city = rep.get("adr").get("city")
country = rep.get("adr").get("ctry")
if name == None:
name = ""
if street == None:
street = ""
if city == None:
city = ""
if country == None:
country = ""
reps.append(name + ", " + street + ", " + city + ", " + country)
names.append(name)
adrs.append("" + street + ", " + city + ", " + country)
@@ -530,6 +621,8 @@ def parse(xml_dict, filename, tree):
t = ""
for name in names:
if name == None:
continue
t += name + " - "
t = t[:-3]
es_dict["representatives_name_text"] = t
@@ -548,6 +641,8 @@ def parse(xml_dict, filename, tree):
t = ""
for state in states:
if state == None:
continue
t += state + " - "
t = t[:-3]
es_dict["states_text"] = t
@@ -568,6 +663,8 @@ def parse(xml_dict, filename, tree):
t = ""
for extended_state in extended_states:
if extended_state == None:
continue
t += extended_state + " - "
t = t[:-3]
es_dict["extended_states_text"] = t
@@ -752,6 +849,7 @@ def check_dtd_version(xml_dict):
# 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}')
@@ -765,6 +863,7 @@ def unzip_first_level(path):
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}')
whitelist.append(file)
@@ -772,6 +871,7 @@ def unzip_first_level(path):
# unzips all subdirectories
def unzip_sub_levels(path, whitelist):
logger = logging.getLogger("unzip_sub_levels")
print('********UNZIPPING: subdirectories********')
pattern = '*.zip'
for root, dirs, files in os.walk(path, topdown=True):
@@ -783,10 +883,12 @@ def unzip_sub_levels(path, whitelist):
print(f'Extracting file: {filename}')
zipfile.ZipFile(os.path.join(root, filename)).extractall(os.path.join(root, os.path.splitext(filename)[0]))
except zipfile.BadZipfile:
print(f'Cannot extract {filename}: Not a valid zipfile (BadZipfile Exception)')
print(f'Cannot extract {filename}: Not a valid zipfile (BadZipfile Exception)')
logger.error(f'Cannot extract {filename}: Not a valid zipfile (BadZipfile Exception)')
# reads and parses the xml files in subdirectories
def load_parse(path):
logger = logging.getLogger("load_parse")
counter = 0
passes = 0
failes = 0
@@ -795,7 +897,8 @@ def load_parse(path):
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 "TOC" not in xml_file.name and "index" not in xml_file.name:
if xml_file.name.endswith('.xml') and "TOC" not in xml_file.name and "index" not in xml_file.name and "SL000001" not in xml_file.name:
print("Parsing file: " + xml_file.name)
counter+=1
try:
xml_read = xml_file.read()
@@ -806,16 +909,33 @@ def load_parse(path):
parse(xml_dict, xml_file.name, tree)
passes += 1
except:
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)}%")
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)}%")
# main
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:
try:
if len(sys.argv) != 2:
sys.exit("No path given.")
whitelist = unzip_first_level(sys.argv[1])