266 lines
8.9 KiB
Python
266 lines
8.9 KiB
Python
from dotenv import load_dotenv
|
|
import os
|
|
import sys
|
|
from dogpile.cache import make_region
|
|
import epo_ops
|
|
from requests import HTTPError
|
|
import requests
|
|
import json
|
|
import time
|
|
import xml.etree.ElementTree as ET
|
|
|
|
# Create a custom session class with a timeout
|
|
class CustomSession(requests.Session):
|
|
def request(self, *args, **kwargs):
|
|
kwargs.setdefault('timeout', 120) # Set timeout to 120 seconds
|
|
return super().request(*args, **kwargs)
|
|
|
|
# get key and secret
|
|
def get_auth():
|
|
key = None
|
|
secret = None
|
|
|
|
for arg in sys.argv[1:]:
|
|
if arg.startswith("key="):
|
|
key = arg.split("=", 1)[1]
|
|
elif arg.startswith("secret="):
|
|
secret = arg.split("=", 1)[1]
|
|
|
|
if key is not None and secret is not None:
|
|
return key, secret
|
|
|
|
load_dotenv()
|
|
key = os.getenv("key")
|
|
secret = os.getenv("secret")
|
|
|
|
if key is None or secret is None:
|
|
print("Error: Both key and secret must be provided. Either with Command Line Parameters or with .env. You can't mix this options!")
|
|
sys.exit(1)
|
|
|
|
return key, secret
|
|
|
|
# build epo ops client
|
|
def get_client(key, secret):
|
|
# Create a cache region using memory backend
|
|
region = make_region().configure(
|
|
'dogpile.cache.memory'
|
|
)
|
|
|
|
# Middleware
|
|
middlewares = [
|
|
epo_ops.middlewares.Dogpile(
|
|
region
|
|
),
|
|
epo_ops.middlewares.Throttler(),
|
|
]
|
|
|
|
# Create new EPO Client with given credentials
|
|
client = epo_ops.Client(
|
|
key = key,
|
|
secret = secret,
|
|
middlewares=middlewares,
|
|
)
|
|
|
|
# Create an instance of the custom session
|
|
custom_session = CustomSession()
|
|
|
|
# Assign the custom session to the client's session
|
|
client.session = custom_session
|
|
|
|
return client
|
|
|
|
# read in json
|
|
def read_codes():
|
|
file_name = "epo_codes.json"
|
|
codes = []
|
|
if os.path.exists(file_name):
|
|
with open(file_name, 'r') as file:
|
|
codes = json.load(file)
|
|
return codes
|
|
|
|
# write new json
|
|
def write_codes(codes):
|
|
file_name = "epo_codes.json"
|
|
|
|
if len(codes) == 0:
|
|
os.remove(file_name)
|
|
else:
|
|
with open(file_name, 'w') as file:
|
|
json.dump(codes, file)
|
|
|
|
# Get full Publications
|
|
def get_full_publications(doc_country, doc_kind, doc_nummer, folder, kind, client):
|
|
try:
|
|
response = client.published_data( # Retrieve bibliography data
|
|
reference_type = 'publication', # publication, application, priority
|
|
input = epo_ops.models.Docdb(doc_nummer, doc_country, doc_kind), # original, docdb, epodoc
|
|
endpoint = kind, # optional, defaults to biblio in case of published_data
|
|
constituents = [] # optional, list of constituents
|
|
)
|
|
except epo_ops.exceptions.HTTPError as e:
|
|
if "No results found" in e.response.text:
|
|
return
|
|
if "The request was invalid" in e.response.text:
|
|
return
|
|
if "InvalidCountryCode" in e.response.text:
|
|
return
|
|
if "The request could not be processed. Please try again later" in e.response.text:
|
|
print(" - - - 1")
|
|
return get_full_publications(doc_country, doc_kind, doc_nummer, folder, kind, client)
|
|
elif "Robot" in e.response.text:
|
|
raise Exception("Robot got detected by API. Please try again later. Best working time is 22:00 - 08:00.")
|
|
else:
|
|
print(" - - ")
|
|
print(f"HTTP error: {e}")
|
|
print(" - - ")
|
|
print(f"{e.response.status_code}")
|
|
print(" - - ")
|
|
print(f"{e.response.text}")
|
|
print(" - - ")
|
|
raise Exception("Position 1")
|
|
except HTTPError as error:
|
|
print(" - - ")
|
|
print(error)
|
|
print(" - - ")
|
|
raise Exception("Position 2")
|
|
except requests.exceptions.Timeout:
|
|
print(" - - - 2")
|
|
time.sleep(120)
|
|
return get_full_publications(doc_country, doc_kind, doc_nummer, folder, kind, client)
|
|
except requests.exceptions.RequestException as e:
|
|
print(" - - ")
|
|
print(error)
|
|
print(" - - ")
|
|
raise Exception("Position 3")
|
|
|
|
filename = doc_country + "_" + doc_nummer + "_" + doc_kind + "_" + kind + ".xml"
|
|
file_path = folder + "/" + filename
|
|
if os.path.isfile(file_path) == False:
|
|
f = open(file_path, "w", encoding="utf-8")
|
|
f.write(response.text)
|
|
f.close()
|
|
|
|
# Get full equivalents
|
|
def get_equivalents(doc_country, doc_kind, doc_nummer, client):
|
|
try:
|
|
response = client.published_data(
|
|
reference_type = 'publication',
|
|
input = epo_ops.models.Docdb(doc_nummer, doc_country, doc_kind),
|
|
endpoint = "equivalents",
|
|
constituents = []
|
|
)
|
|
except epo_ops.exceptions.HTTPError as e:
|
|
if "No results found" in e.response.text:
|
|
return ""
|
|
if "The request was invalid" in e.response.text:
|
|
return ""
|
|
if "InvalidCountryCode" in e.response.text:
|
|
return ""
|
|
if "The request could not be processed. Please try again later" in e.response.text:
|
|
print(" - - - 1")
|
|
return get_equivalents(doc_country, doc_kind, doc_nummer, client)
|
|
elif "Robot" in e.response.text:
|
|
raise Exception("Robot got detected by API. Please try again later. Best working time is 22:00 - 08:00.")
|
|
else:
|
|
print(" - - ")
|
|
print(f"HTTP error: {e}")
|
|
print(" - - ")
|
|
print(f"{e.response.status_code}")
|
|
print(" - - ")
|
|
print(f"{e.response.text}")
|
|
print(" - - ")
|
|
raise Exception("Position 1")
|
|
except HTTPError as error:
|
|
print(" - - ")
|
|
print(error)
|
|
print(" - - ")
|
|
raise Exception("Position 2")
|
|
except requests.exceptions.Timeout:
|
|
print(" - - - 2")
|
|
time.sleep(120)
|
|
return get_equivalents(doc_country, doc_kind, doc_nummer, client)
|
|
except requests.exceptions.RequestException as e:
|
|
print(" - - ")
|
|
print(error)
|
|
print(" - - ")
|
|
raise Exception("Position 3")
|
|
|
|
return response.text
|
|
|
|
# fetches the data and writes them to disc
|
|
def load_data(codes, kinds, client):
|
|
# Create Publications folder
|
|
source_folder = "./publications"
|
|
if not os.path.exists(source_folder):
|
|
os.makedirs(source_folder)
|
|
|
|
# fetch all codes
|
|
code_len = len(codes)
|
|
for i in range(code_len - 1, -1, -1):
|
|
print(f" - {code_len - i}/{code_len}: {codes[i].get('id')}")
|
|
|
|
# Create day folder if needed
|
|
date_modified = codes[i].get("date_modified")
|
|
day_folder = source_folder + "/" + date_modified
|
|
if not os.path.exists(day_folder):
|
|
os.makedirs(day_folder)
|
|
|
|
doc_country = codes[i].get("doc_country")
|
|
doc_nummer = codes[i].get("doc_nummer")
|
|
doc_kind = codes[i].get("doc_kind")
|
|
|
|
# Create patent folder if needed
|
|
single_patent_folder = day_folder + "/" + doc_country + "_" + doc_nummer + "_" + doc_kind
|
|
if not os.path.exists(single_patent_folder):
|
|
os.makedirs(single_patent_folder)
|
|
|
|
equivalents = get_equivalents(doc_country, doc_kind, doc_nummer, client)
|
|
|
|
if equivalents == "":
|
|
# fetch all wanted kinds
|
|
for kind in kinds:
|
|
get_full_publications(doc_country, doc_kind, doc_nummer, single_patent_folder, kind, client)
|
|
else:
|
|
equivalents_ids = []
|
|
root = ET.fromstring(equivalents)
|
|
|
|
for child in root.iter('*'):
|
|
if child.tag == "{http://www.epo.org/exchange}document-id":
|
|
id = child.attrib.get("document-id-type")
|
|
if id is not None and id == "epodoc":
|
|
for item in child.iter("*"):
|
|
if item.tag == "{http://www.epo.org/exchange}doc-number":
|
|
equivalents_ids.append(item.text)
|
|
|
|
# safety checks
|
|
check = doc_country + doc_nummer
|
|
if len(equivalents_ids) == 0:
|
|
equivalents_ids.append(check)
|
|
if check not in equivalents_ids:
|
|
equivalents_ids.append(check)
|
|
|
|
for equivalents_id in equivalents_ids:
|
|
doc_country_ = equivalents_id[0:2]
|
|
doc_nummer_ = equivalents_id[2:]
|
|
doc_kind_ = doc_kind
|
|
|
|
for kind in kinds:
|
|
get_full_publications(doc_country_, doc_kind_, doc_nummer_, single_patent_folder, kind, client)
|
|
|
|
# code done -> remove from list
|
|
del codes[i]
|
|
write_codes(codes)
|
|
|
|
# Run Script
|
|
if __name__ == '__main__':
|
|
print("Starting")
|
|
kinds = ["biblio", "abstract", "description", "claims"]
|
|
codes = read_codes()
|
|
print("Auth")
|
|
key, secret = get_auth()
|
|
print("Building Client")
|
|
client = get_client(key, secret)
|
|
print(f"Fetching {str(len(codes))} patents.")
|
|
print("Fetching Data")
|
|
load_data(codes, kinds, client)
|
|
print("Done") |