Files
2024-08-20 10:48:08 +02:00

477 lines
20 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
from datetime import datetime, timedelta
import xml.etree.ElementTree as ET
import json
import time
# Static Maps for hirachical scraping
country_codes_all = ["US","AL","AP","AR","AT","AU","BA","BE","BG","BR","CA","CH","CL","CN","CO","CR","CS","CU","CY","CZ","DD","DE","DK","DZ","EA","EC","EE","EG","EP","ES","FI","FR","GB","GC","GE","GR","GT","HK","HR","HU","ID","IE","IL","IN","IS","IT","JP","KE","KR","LI","LT","LU","LV","MA","MC","MD","ME","MK","MN","MT","MW","MX","MY","NC","NI","NL","NO","NZ","OA","PA","PE","PH","PL","PT","RO","RS","RU","SE","SG","SI","SK","SM","SU","SV","TJ","TR","TT","TW","UA","US","UY","VN","WO","YU","ZA","ZM","ZW"]
country_codes = ["EP"]
cpc_codes = {
"A": {
"A01": ["A01B", "A01C", "A01D", "A01F", "A01G", "A01H", "A01J", "A01K", "A01L", "A01M", "A01N", "A01P"],
"A21": ["A21B", "A21C", "A21D"],
"A22": ["A22B", "A22C"],
"A23": ["A23B", "A23C", "A23D", "A23F", "A23G", "A23J", "A23K", "A23L", "A23N", "A23P", "A23V"],
"A24": ["A24B", "A24C", "A24D", "A24F"],
"A41": ["A41B", "A41C", "A41D", "A41F", "A41G", "A41H"],
"A42": ["A42B", "A42C"],
"A43": ["A43B", "A43C", "A43D"],
"A44": ["A44B", "A44C", "A44D"],
"A45": ["A45B", "A45C", "A45D", "A45F"],
"A46": ["A46B", "A46D"],
"A47": ["A47B", "A47C", "A47D", "A47F", "A47G", "A47H", "A47J", "A47K", "A47L"],
"A61": ["A61B", "A61C", "A61D", "A61F", "A61G", "A61H", "A61J", "A61K", "A61L", "A61M", "A61N", "A61P", "A61Q"],
"A62": ["A62B", "A62C", "A62D"],
"A63": ["A63B", "A63C", "A63D", "A63F", "A63G", "A63H", "A63J", "A63K"],
"A64": ["A64B", "A64C"],
"A99": ["A99Z"]
},
"B": {
"B01": ["B01B", "B01D", "B01F", "B01J", "B01L"],
"B02": ["B02B", "B02C"],
"B03": ["B03B", "B03C", "B03D"],
"B04": ["B04B", "B04C"],
"B05": ["B05B", "B05C", "B05D"],
"B06": ["B06B"],
"B07": ["B07B", "B07C"],
"B08": ["B08B"],
"B09": ["B09B", "B09C"],
"B21": ["B21B", "B21C", "B21D", "B21F", "B21G", "B21H", "B21J", "B21K", "B21L"],
"B22": ["B22C", "B22D", "B22F"],
"B23": ["B23B", "B23C", "B23D", "B23F", "B23G", "B23H", "B23K", "B23P", "B23Q"],
"B24": ["B24B", "B24C", "B24D"],
"B25": ["B25B", "B25C", "B25D", "B25F", "B25G", "B25H", "B25J"],
"B26": ["B26B", "B26D", "B26F"],
"B27": ["B27B", "B27C", "B27D", "B27F", "B27G", "B27H", "B27J", "B27K", "B27L", "B27M", "B27N"],
"B28": ["B28B", "B28C", "B28D"],
"B29": ["B29B", "B29C", "B29D", "B29K", "B29L"],
"B30": ["B30B"],
"B31": ["B31B", "B31C", "B31D", "B31F"],
"B32": ["B32B"],
"B33": ["B33Y"],
"B41": ["B41B", "B41C", "B41D", "B41F", "B41G", "B41J", "B41K", "B41L", "B41M", "B41N", "B41P"],
"B42": ["B42B", "B42C", "B42D", "B42F"],
"B43": ["B43K"],
"B44": ["B44B", "B44C", "B44D"],
"B60": ["B60B", "B60C", "B60D", "B60F", "B60G", "B60H", "B60J", "B60K", "B60L", "B60M", "B60N", "B60P", "B60Q", "B60R", "B60S", "B60T", "B60W", "B60Y"],
"B61": ["B61B", "B61C", "B61D", "B61F", "B61G", "B61H", "B61J", "B61K", "B61L", "B61M"],
"B62": ["B62B", "B62C", "B62D", "B62H", "B62J", "B62K", "B62L", "B62M"],
"B63": ["B63B", "B63C", "B63G", "B63H", "B63J"],
"B64": ["B64B", "B64C", "B64D", "B64F", "B64F", "B64U"],
"B65": ["B65B", "B65C", "B65D", "B65F", "B65G", "B65H", "B65J"],
"B66": ["B66B", "B66C", "B66D", "B66F"],
"B67": ["B67B", "B67C", "B67D"],
"B68": ["B68B", "B68C", "B68F", "B68G"],
"B69": ["B69C"],
"B81": ["B81B", "B81C"],
"B82": ["B82B", "B82Y"],
"B83": ["B83B"],
"B99": ["B99Z"]
},
"C": {
"C01": ["C01B", "C01C", "C01D", "C01F", "C01G", "C01P"],
"C02": ["C02F"],
"C03": ["C03B", "C03C"],
"C04": ["C04B"],
"C05": ["C05B", "C05C", "C05D", "C05F", "C05G"],
"C06": ["C06B", "C06C", "C06D", "C06F"],
"C07": ["C07B", "C07C", "C07D", "C07F", "C07G", "C07H", "C07J", "C07K"],
"C08": ["C08B", "C08C", "C08F", "C08G", "C08H", "C08J", "C08K", "C08L"],
"C09": ["C09B", "C09C", "C09D", "C09F", "C09G", "C09H", "C09J", "C09K"],
"C10": ["C10B", "C10C", "C10F", "C10G", "C10H", "C10J", "C10K", "C10L", "C10M", "C10N"],
"C11": ["C11B", "C11C", "C11D"],
"C12": ["C12C", "C12F", "C12G", "C12H", "C12J", "C12L", "C12M", "C12N", "C12P", "C12Q", "C12R", "C12S", "C12Y"],
"C13": ["C13B", "C13C", "C13D", "C13K"],
"C14": ["C14B", "C14C"],
"C21": ["C21B", "C21C", "C21D"],
"C22": ["C22B", "C22C", "C22F"],
"C23": ["C23C", "C23D", "C23F", "C23G"],
"C25": ["C25B", "C25C", "C25D", "C25F"],
"C30": ["C30B"],
"C40": ["C40B"],
"C99": ["C99Z"]
},
"D": {
"D01": ["D01B", "D01C", "D01D", "D01F", "D01G", "D01H"],
"D02": ["D02G", "D02H", "D02J"],
"D03": ["D03C", "D03D", "D03J"],
"D04": ["D04B", "D04C", "D04D", "D04G", "D04H"],
"D05": ["D05B", "D05C", "D05D", "D05F", "D05G", "D05H"],
"D06": ["D06B", "D06C", "D06F", "D06G", "D06H", "D06J", "D06L", "D06M", "D06P", "D06Q"],
"D07": ["D07B"],
"D10": ["D10B"],
"D21": ["D21B", "D21C", "D21D", "D21F", "D21G", "D21H", "D21J"],
"D99": ["D99Z"]
},
"E": {
"E01": ["E01B", "E01C", "E01D", "E01F", "E01H"],
"E02": ["E02B", "E02C", "E02D", "E02F"],
"E03": ["E03B", "E03C", "E03D", "E03F"],
"E04": ["E04B", "E04C", "E04D", "E04F", "E04G", "E04H"],
"E05": ["E05B", "E05C", "E05D", "E05F", "E05G", "E05Y"],
"E06": ["E06B", "E06C"],
"E21": ["E21B", "E21C", "E21D", "E21F", "E21G", "E21H"],
"E99": ["E99Z"]
},
"F": {
"F01": ["F01B", "F01C", "F01D", "F01K", "F01L", "F01M", "F01N", "F01P"],
"F02": ["F02B", "F02C", "F02D", "F02F", "F02G", "F02K", "F02M", "F02N", "F02P"],
"F03": ["F03B", "F03C", "F03D", "F03G", "F03H"],
"F04": ["F04B", "F04C", "F04D", "F04F"],
"F15": ["F15B", "F15C", "F15D"],
"F16": ["F16B", "F16C", "F16D", "F16F", "F16G", "F16H", "F16J", "F16K", "F16L", "F16M", "F16N", "F16P", "F16S", "F16T"],
"F17": ["F17B", "F17C", "F17D"],
"F21": ["F21H", "F21K", "F21L", "F21P", "F21Q", "F21S", "F21V", "F21W", "F21Y"],
"F22": ["F22B", "F22D", "F22G", "F22J"],
"F23": ["F23B", "F23C", "F23D", "F23G", "F23H", "F23J", "F23K", "F23L", "F23M", "F23N", "F23Q", "F23R"],
"F24": ["F24B", "F24C", "F24D", "F24F", "F24H", "F24J", "F24S", "F24T", "F24V"],
"F25": ["F25B", "F25C", "F25D", "F25J"],
"F26": ["F26B"],
"F27": ["F27B", "F27D", "F27M"],
"F28": ["F28B", "F28C", "F28D", "F28F", "F28G"],
"F41": ["F41A", "F41B", "F41C", "F41F", "F41G", "F41H", "F41J"],
"F42": ["F42B", "F42C", "F42D"],
"F99": ["F99Z"]
},
"G": {
"G01": ["G01B", "G01C", "G01D", "G01F", "G01G", "G01H", "G01J", "G01K", "G01L", "G01M", "G01N", "G01P", "G01Q", "G01R", "G01S", "G01T", "G01V", "G01W"],
"G02": ["G02B", "G02C", "G02F", "G02G", "G02H"],
"G03": ["G03B", "G03C", "G03D", "G03F", "G03G", "G03H"],
"G04": ["G04B", "G04C", "G04D", "G04F", "G04G", "G04R", "G04Y"],
"G05": ["G05B", "G05D", "G05F", "G05G"],
"G06": ["G06C", "G06D", "G06F", "G06G", "G06J", "G06K", "G06M", "G06N", "G06Q", "G06T", "G06V", "G06Y"],
"G07": ["G07B", "G07C", "G07D", "G07F", "G07G", "G07H", "G07L"],
"G08": ["G08B", "G08C", "G08G"],
"G09": ["G09B", "G09C", "G09D", "G09F", "G09G", "G09H", "G09J", "G09K"],
"G10": ["G10B", "G10C", "G10D", "G10F", "G10G", "G10H", "G10K", "G10L"],
"G11": ["G11B", "G11C"],
"G12": ["G12B"],
"G16": ["G16B", "G16C", "G16H", "G16K", "G16Y", "G16Z"],
"G21": ["G21B", "G21C", "G21D", "G21F", "G21G", "G21H", "G21J", "G21K"],
"G99": ["G99Z"]
},
"H": {
"H01": ["H01B", "H01C", "H01F", "H01G", "H01H", "H01J", "H01K", "H01L", "H01M", "H01P", "H01Q", "H01R", "H01S", "H01T"],
"H02": ["H02B", "H02G", "H02H", "H02J", "H02K", "H02M", "H02N", "H02P", "H02S"],
"H03": ["H03B", "H03C", "H03D", "H03F", "H03G", "H03H", "H03J", "H03K", "H03L", "H03M", "H03P", "H03Q", "H03S"],
"H04": ["H04B", "H04H", "H04J", "H04K", "H04L", "H04M", "H04N", "H04Q", "H04R", "H04S", "H04T", "H04W"],
"H05": ["H05B", "H05C", "H05F", "H05G", "H05H", "H05K"],
"H10": ["H10B", "H10K", "H10N"],
"H99": ["H99Z"]
},
"Y": {
"Y02": ["Y02A", "Y02B", "Y02C", "Y02D", "Y02E", "Y02P", "Y02T", "Y02W"],
"Y04": ["Y04S"],
"Y10": ["Y10S", "Y10T"]
}
}
# 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)
# Exception indicating too large queries
class TooManyPatentsError(Exception):
def __init__(self, message, errors=None):
super().__init__(message)
self.errors = errors
# 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
# Get Tag, Kind und Contry Codes from Response
def parse_response(response):
documents = []
search_count = 0
root = ET.fromstring(response)
for child in root.iter('*'):
# Find Searchcount
if(child.tag == "{http://ops.epo.org}biblio-search"):
search_count = int(child.attrib['total-result-count'])
# Find publications
if(child.tag == "{http://ops.epo.org}publication-reference"):
doc_nummer, doc_kind, doc_country = ["", "", ""]
# Parse XML File
for item in child.iter("*"):
if(item.tag == "{http://www.epo.org/exchange}doc-number"):
doc_nummer = item.text
if(item.tag == "{http://www.epo.org/exchange}kind"):
doc_kind = item.text
if(item.tag == "{http://www.epo.org/exchange}country"):
doc_country = item.text
# Append all Documents to Document List
documents.append((doc_country, doc_kind, doc_nummer))
# Return informaiton from Response (search count and documents)
return (search_count, documents)
# Collect Publication IDs
def get_publication_ids(pr, cpc, date, client, try_count):
# Default Range 1:100 (limit of 100 publications per request)
range = [1, 100]
# Decide how to filter
if(cpc != None):
seary_query = 'pd within "'+date+' '+date+'" and pr='+pr+' and cpc='+cpc
else:
seary_query = 'pd within "'+date+' '+date+'" and pr='+pr
# Do first request
try:
response = client.published_data_search(seary_query, range_begin=range[0], range_end=range[1], constituents=None)
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 "Inconsistent request." in e.response.text:
return []
if "The request could not be processed. Please try again later" in e.response.text:
print(" - - - - - 1")
return get_publication_ids(pr, cpc, date, client, try_count)
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_publication_ids(pr, cpc, date, client, try_count)
except requests.exceptions.RequestException as e:
print(" - - ")
print(error)
print(" - - ")
raise Exception("Position 4")
# Parse first query
search_count, documents = parse_response(response.text)
# Decide how many
if(search_count > 2000):
if try_count == 4:
print(f" - - - - High search_count (limit at 2000) getting 2000/{search_count} of code {cpc}")
search_count = 2000
else:
raise TooManyPatentsError("Change Query!")
while(len(documents) < search_count):
# Do more requests until all all publications are found for query
range = [len(documents) + 1, (len(documents) + 100)]
if(range[1] > search_count):
range[1] = search_count
try:
response = client.published_data_search(seary_query, range_begin=range[0], range_end=range[1], constituents=None)
except epo_ops.exceptions.HTTPError as e:
if "No results found" in e.response.text:
return documents
if "The request was invalid" in e.response.text:
return documents
if "Inconsistent request." in e.response.text:
return documents
if "The request could not be processed. Please try again later" in e.response.text:
print(" - - - - - 3")
return get_publication_ids(pr, cpc, date, client, try_count)
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 5")
except HTTPError as error:
print(" - - ")
print(error)
print(" - - ")
raise Exception("Position 6")
except requests.exceptions.Timeout:
print(" - - - - - 4")
time.sleep(120)
return get_publication_ids(pr, cpc, date, client, try_count)
except requests.exceptions.RequestException as e:
print(" - - ")
print(error)
print(" - - ")
raise Exception("Position 8")
search_count, new_documents = parse_response(response.text)
# Add all new DocumentIds
documents.extend(new_documents)
return documents
# Get publication IDs for Date
def get_publications(date, client):
full_publications = []
# Get patets for every country
for country in country_codes:
try:
publications = get_publication_ids(country, None, date, client, 1)
full_publications.extend(publications)
except TooManyPatentsError:
# Check if more
print(" - - - Going deeper into CPC")
for cpc_code, sub_codes in cpc_codes.items():
try:
publications = get_publication_ids(country, cpc_code, date, client, 2)
full_publications.extend(publications)
except TooManyPatentsError:
print(" - - - Going deeeeper into CPC")
for sub_code, sub_sub_codes in sub_codes.items():
try:
publications = get_publication_ids(country, sub_code, date, client, 3)
full_publications.extend(publications)
except TooManyPatentsError:
print(" - - - Going deeeeeeper into CPC")
for sub_sub_code in sub_sub_codes:
publications = get_publication_ids(country, sub_sub_code, date, client, 4)
full_publications.extend(publications)
return full_publications
# get codes
def get_codes(client, x_days):
print(f" - Fetching the last {x_days} days.")
now = datetime.now()
# Get Patent list
for i in range(x_days, 0, -1):
day = now - timedelta(i)
codes = []
print(" - - " + str(i) + " - " + str(datetime.strftime(day, '%d.%m.%Y')))
try:
publications = get_publications(datetime.strftime(day, '%Y%m%d'), client)
except Exception as e:
print(e)
print(f"An Error occured. Days Left: {i}")
sys.exit()
# add to codes
for publication in publications:
doc_country, doc_kind, doc_nummer = publication
if doc_country not in country_codes:
continue
id = doc_country + "_" + doc_kind + "_" + doc_nummer + "_" + str(datetime.strftime(day, '%Y%m%d'))
new_code = {
"id": id,
"doc_country": doc_country,
"doc_kind": doc_kind,
"doc_nummer": doc_nummer,
"date": str(datetime.strftime(day, '%Y%m%d')),
"date_modified": str(datetime.strftime(day, '%d-%m-%Y'))
}
codes.append(new_code)
print(" - - Writing Codes")
write_codes(codes)
# write codes to disc
def write_codes(codes):
file_name = "epo_codes.json"
codes_list = []
ids = []
if os.path.exists(file_name):
with open(file_name, 'r') as file:
codes_list = json.load(file)
ids = [item['id'] for item in codes_list if 'id' in item]
for code in codes:
if code["id"] not in ids:
codes_list.append(code)
with open(file_name, 'w') as file:
json.dump(codes_list, file)
# Run Script
if __name__ == '__main__':
print("Starting")
x_days = 7
for arg in sys.argv[1:]:
if arg.startswith("days="):
x_days = int(arg.split("=", 1)[1])
if arg.startswith("all_countries"):
country_codes = country_codes_all
print("Auth")
key, secret = get_auth()
print(f"Crawling the last {x_days} days of {len(country_codes)} country/ countries!")
print("Building Client")
client = get_client(key, secret)
print("Loading Codes/ Crawling")
get_codes(client, x_days)
print("Done")