ADDED: pipeline for USPTO patents

This commit is contained in:
2026-03-18 15:56:56 +01:00
parent af57ad5f80
commit 8c055c1347
5 changed files with 1499 additions and 0 deletions
+8
View File
@@ -131,6 +131,8 @@ Within a single point you have to do the scripts from top to bottom.
* Upload: upload.py
+ Parameter: Path to patent-JSONs
#### EPO Patents CPCs:
* Path: inse-internal-external-scripts\extern\epo-api\cpc_xml_parser_uploader
* CPC: Done - not needed again
@@ -138,6 +140,12 @@ Within a single point you have to do the scripts from top to bottom.
#### EPO Patents from EPO OPS API:
* Info: How to use -> check own README
* Path: inse-internal-external-scripts\extern\epo-api\EPO_API\v2
#### USPTO Patents from USPTO API:
* Info: How to use -> check own README
* Path: inse-internal-external-scripts\extern\uspto-crawler
#### EU Startups:
* Path: inse-internal-external-scripts\extern\eustartups\eustartups-v2
+192
View File
@@ -0,0 +1,192 @@
import requests
import json
import shutil
from pathlib import Path
from dotenv import load_dotenv
import os
import sys
import datetime
load_dotenv()
PRODUCT_RESPONSE_FILENAME = "product_response.json"
BASE_URL = "https://api.uspto.gov/api/v1/datasets"
PRODUCT_ID = "PTGRXML" # BULK Grants Dataset
API_KEY = os.getenv("API_KEY")
HEADERS = {
"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/121.0.0.0 Safari/537.36"
),
"Accept": "application/json",
"X-API-Key": API_KEY
}
def fetch_products_response(date_from=2014, date_to=2026, limit=0):
params = {
"fileDataFromDate": f"{date_from}",
"fileDataToDate": f"{date_to}",
"includeFiles": "true"
}
if limit > 0:
params["limit"] = limit
endpoint_url = f"{BASE_URL}/products/{PRODUCT_ID}"
print(f"Requesting: {endpoint_url}")
print(f"Parameters: {params}")
response = requests.get(
endpoint_url,
params=params,
headers=HEADERS,
timeout=30
)
response.raise_for_status()
data = response.json()
output_file = PRODUCT_RESPONSE_FILENAME
with open(output_file, "w") as f:
json.dump(data, f, indent=2)
""" file sample from product_response.json
{
"fileName": "ipg161220.zip",
"fileSize": 84100354,
"fileDataFromDate": "2016-12-20",
"fileDataToDate": "2016-12-20",
"fileTypeText": "Data",
"fileDownloadURI": "https://api.uspto.gov/api/v1/datasets/products/files/PTGRXML/2016/ipg161220.zip",
"fileReleaseDate": "2016-12-20 02:12:20",
"fileLastModifiedDateTime": "2024-09-30 10:49:01"
}
"""
def download_product(product_url,downloads_folder):
print(f"\nDownloading file from: {product_url}")
zip_name = product_url.split("/")[-1]
zip_path = os.path.join(downloads_folder,zip_name)
#By default requests follows redirects. To see the redirect URL, I have disabled it to show the faulty expiry.
with requests.get(product_url, headers=HEADERS, allow_redirects=False, stream=True, timeout=300) as r:
r.raise_for_status()
status_code = r.status_code
if status_code == 302:
redirected = {"redirect_url": r.headers.get("Location")}
print(f"Redirected to: {redirected['redirect_url']}")
content_type = r.headers.get("Content-Type", "")
# if "zip" not in content_type.lower():
# raise RuntimeError(f"Expected ZIP, got {content_type}")
with requests.get(redirected['redirect_url'], stream=True, timeout=300) as r:
print(f"Final download URL: {redirected['redirect_url']}")
r.raise_for_status()
with open(zip_path, "wb") as f:
for chunk in r.iter_content(chunk_size=1024 * 1024):
if chunk:
f.write(chunk)
# Create extraction folder (same name without .zip)
extract_folder = os.path.join(downloads_folder, zip_name.replace(".zip", ""))
os.makedirs(extract_folder, exist_ok=True)
# Extract archive
shutil.unpack_archive(zip_path, extract_folder)
# Remove ZIP file
os.unlink(zip_path)
def download_dtd(dtd_url,downloads_folder):
print(f"\nDownloading file from: {dtd_url}")
dtd_name = dtd_url.split("/")[-1]
dtd_path = os.path.join(downloads_folder, dtd_name)
#By default requests follows redirects. To see the redirect URL, I have disabled it to show the faulty expiry.
with requests.get(dtd_url, headers=HEADERS, allow_redirects=False, stream=True, timeout=300) as r:
r.raise_for_status()
status_code = r.status_code
if status_code == 302:
redirected = {"redirect_url": r.headers.get("Location")}
print(f"Redirected to: {redirected['redirect_url']}")
content_type = r.headers.get("Content-Type", "")
# if "zip" not in content_type.lower():
# raise RuntimeError(f"Expected ZIP, got {content_type}")
with requests.get(redirected['redirect_url'], stream=True, timeout=300) as r:
print(f"Final download URL: {redirected['redirect_url']}")
r.raise_for_status()
with open(dtd_path, "wb") as f:
for chunk in r.iter_content(chunk_size=1024 * 1024):
if chunk:
f.write(chunk)
def is_valid_date(date_str):
try:
datetime.strptime(date_str, "%Y-%m-%d")
return True
except ValueError:
return False
if __name__ == "__main__":
print("Starting.")
# Default values
date_from = "2014-01-01"
date_to = "2026-12-31"
for arg in sys.argv[1:]:
if arg.startswith("key="):
HEADERS["X-API-Key"] = arg.split("key=", 1)[1]
api_key = HEADERS.get("X-API-Key") or os.getenv("API_KEY")
if not api_key:
print("Error: API key not provided (CLI, .env, or stdin).")
sys.exit(1)
HEADERS["X-API-Key"] = api_key
# Download products info
fetch_products_response(date_to=date_to, date_from=date_from,limit=0) #set limit= here to limit the number of product downloads
with open(PRODUCT_RESPONSE_FILENAME, "r") as f:
prod_response = json.load(f)
product_downloads_folder = "product_downloads"
dtd_downloads_folder = "dtds"
os.makedirs(product_downloads_folder, exist_ok=True)
os.makedirs(dtd_downloads_folder, exist_ok=True)
product_uris = []
dtd_uris = []
for item in prod_response.get("bulkDataProductBag", []):
for product in item.get("productFileBag", {}).get("fileDataBag", []):
file_type = product.get("fileTypeText")
file_name = product.get("fileName", "")
file_uri = product.get("fileDownloadURI")
if file_type == "Data" and file_name.endswith(".zip"):
product_uris.append(file_uri)
elif file_type == "Document" and file_name.endswith(".dtd"):
dtd_uris.append(file_uri)
# Remove duplicates
product_uris = list(set(product_uris))
dtd_uris = list(set(dtd_uris))
print(f"Found {len(product_uris)} product files and {len(dtd_uris)} DTD files.")
for uri in product_uris:
print(f"Downloading product: {uri}")
download_product(product_url=uri, downloads_folder=product_downloads_folder)
for uri in dtd_uris:
print(f"Downloading DTD: {uri}")
download_dtd(dtd_url=uri, downloads_folder=dtd_downloads_folder)
print(f"Complete! Check {product_downloads_folder} for product contents.")
#endpoint_url = f"{BASE_URL}/products/files/{PRODUCT_ID}/2014/ipg141028.zip" #ipg161220.zip"
+738
View File
@@ -0,0 +1,738 @@
from lxml import etree
import json
import logging
import os
import re
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Define a parser that loads DTD and resolves entities
parser = etree.XMLParser(
load_dtd=True,
resolve_entities=True,
no_network=True
)
def get_dtd_version(xml_path):
with open(xml_path, "r", encoding="utf-8") as f:
head = f.read(1000) # read only the beginning
match = re.search(r'us-patent-(application|grant)-v(\d+)-\d{4}-\d{2}-\d{2}\.dtd', head)
return match.group(0)
def iter_xml_documents(file_path):
"""
Yields raw XML documents from a file containing multiple XML declarations.
"""
buffer = []
with open(file_path, "rb") as f:
for line in f:
if line.lstrip().startswith(b"<?xml"):
if buffer:
yield b"".join(buffer)
buffer = []
buffer.append(line)
if buffer:
yield b"".join(buffer)
def parse_multiple_xml(file_path, dtd_path, strict=True):
"""
Generator yielding parsed patent dicts from concatenated XML documents.
"""
# Load DTD once
with open(dtd_path, "rb") as f:
dtd = etree.DTD(f)
parser = etree.XMLParser(
dtd_validation=True,
load_dtd=True,
recover=not strict,
huge_tree=True
)
for xml_bytes in iter_xml_documents(file_path):
try:
root = etree.fromstring(xml_bytes, parser)
# if not dtd.validate(root):
# if strict:
# raise etree.DTDValidateError(dtd.error_log)
# continue
data = {}
# application reference
application_ref = root.find(".//{*}application-reference")
if application_ref is not None:
application_number = application_ref.find(".//{*}doc-number")
if application_number is not None and application_number.text:
data["application_number"] = application_number.text.strip()
application_date = application_ref.find(".//{*}date")
if application_date is not None and application_date.text:
data["application_date"] = application_date.text.strip()
application_country = application_ref.find(".//{*}country")
if application_country is not None and application_country.text:
data["application_country"] = application_country.text.strip()
# publication reference
publication_ref = root.find(".//{*}publication-reference")
if publication_ref is not None:
publication_number = publication_ref.find(".//{*}doc-number")
if publication_number is not None and publication_number.text:
data["publication_number"] = publication_number.text.strip()
publication_kind = publication_ref.find(".//{*}kind")
if publication_kind is not None and publication_kind.text:
data["publication_kind"] = publication_kind.text.strip()
publication_country = publication_ref.find(".//{*}country")
if publication_country is not None and publication_country.text:
data["publication_country"] = publication_country.text.strip()
publication_date = publication_ref.find(".//{*}date")
if publication_date is not None and publication_date.text:
data["publication_date"] = publication_date.text.strip()
data["publication_year"] = publication_date.text.strip()[:4]
# application series code
application_series_code = root.find(".//{*}us-application-series-code")
if application_series_code is not None and application_series_code.text:
data["series_code"] = application_series_code.text.strip()
# title
title = root.find(".//{*}invention-title")
if title is not None and title.text:
data["title"] = "".join(title.itertext()).strip()
# length of grant
term_of_graint = root.find(".//{*}us-term-of-grant")
if term_of_graint is not None and term_of_graint.text:
length_of_grant = root.find(".//{*}length-of-grant")
if length_of_grant is not None and length_of_grant.text:
data["length_of_grant"] = int(length_of_grant.text.strip())
term_extension = root.find(".//{*}us-term-extension")
if term_extension is not None and term_extension.text:
data["term_extension"] = int(term_extension.text.strip())
disclaimer = root.find(".//{*}disclaimer//{*}text")
if disclaimer is not None and disclaimer.text:
data["disclaimer"] = disclaimer.text.strip()
# proiority claims
priority_claims = []
for priority_claim in root.findall(".//{*}priority-claim"):
priority_claim_dict = {}
priority_claim_number = priority_claim.find(".//{*}doc-number")
if priority_claim_number is not None and priority_claim_number.text:
priority_claim_dict["number"] = priority_claim_number.text.strip()
priority_claim_date = priority_claim.find(".//{*}date")
if priority_claim_date is not None and priority_claim_date.text:
priority_claim_dict["date"] = priority_claim_date.text.strip()
priority_claim_country = priority_claim.find(".//{*}country")
if priority_claim_country is not None and priority_claim_country.text:
priority_claim_dict["country"] = priority_claim_country.text.strip()
if len(priority_claim_dict.values()) > 0:
priority_claims.append(priority_claim_dict)
if priority_claims:
data["priority_claims"] = priority_claims
# application reference
application_reference = root.find(".//{*}application-reference")
if application_reference is not None:
appl_type = application_reference.attrib.get("appl-type")
if appl_type:
data["application_type"] = appl_type.strip()
application_number = application_reference.find(".//{*}doc-number")
if application_number is not None and application_number.text:
data["application_number"] = application_number.text.strip()
application_date = application_reference.find(".//{*}date")
if application_date is not None and application_date.text:
data["application_date"] = application_date.text.strip()
# assignee
assignees = []
for assignee in root.findall(".//{*}assignee"):
assignee_dict = {}
orgname = assignee.find(".//{*}orgname")
if orgname is not None and orgname.text:
assignee_dict["orgname"] = orgname.text.strip()
assignee_address = assignee.find(".//{*}address")
if assignee_address is not None and assignee_address.text:
assignee_dict["address"] = ""
assignee_city = assignee_address.find(".//{*}city")
if assignee_city is not None and assignee_city.text:
assignee_dict["address"] = assignee_city.text.strip()
assignee_state = assignee_address.find(".//{*}state")
if assignee_state is not None and assignee_state.text:
assignee_dict["address"] = assignee_dict["address"] + ", " + assignee_state.text.strip()
assignee_country = assignee_address.find(".//{*}country")
if assignee_country is not None and assignee_country.text:
assignee_dict["address"] = assignee_dict["address"] + ", " + assignee_country.text.strip()
# create further formats
if len(assignee_dict.values()) > 0:
assignees.append(assignee_dict)
if assignees:
# data["assignees"] = assignees
data["assignees"] = [f"{assignee.get('orgname','')}, {assignee.get('address','')}" for assignee in assignees if assignee.get("orgname")]
data["assignees_text"] = "; ".join(data["assignees"])
data["assignees_orgs"] = [f"{assignee.get('orgname','')}" for assignee in assignees if assignee.get("orgname")]
data["assignees_orgs_text"]= "; ".join(data["assignees_orgs"])
data["assignees_addresses"] = [f"{assignee.get('address','')}" for assignee in assignees if assignee.get("address")]
data["assignees_addresses_text"] = "; ".join(data["assignees_addresses"])
# inventors
# inventors = []
# for applicant in root.findall(".//{*}applicant"):
# first_name = applicant.find(".//{*}first-name")
# last_name = applicant.find(".//{*}last-name")
# name_parts = []
# if first_name is not None and first_name.text:
# name_parts.append(first_name.text.strip())
# if last_name is not None and last_name.text:
# name_parts.append(last_name.text.strip())
# if name_parts:
# inventors.append(" ".join(name_parts))
# if inventors:
# data["inventors"] = inventors
# number of claims
number_of_claims = root.find(".//{*}number-of-claims")
if number_of_claims is not None and number_of_claims.text:
data["number_of_claims"] = int(number_of_claims.text.strip())
abstract = root.find(".//{*}abstract//{*}p")
if abstract is not None and abstract.text:
data["abstract"] = "".join(abstract.itertext()).strip()
description = root.find(".//{*}description")
description_paragraph = []
description_headings = []
if description is not None:
for desc in description.findall(".//{*}p"):
if desc is not None and desc.text:
description_paragraph.append("".join(desc.itertext()).strip())
data["description_paragraph"] = description_paragraph
data["description_text"] = "\n".join(description_paragraph)
for desc_heading in description.findall(".//{*}heading"):
if desc_heading is not None and desc_heading.text:
description_headings.append("".join(desc_heading.itertext()).strip())
data["description_header"] = description_headings
# primary examiners
primary_examiners = []
for prim_examiner in root.findall(".//{*}primary-examiner"):
if prim_examiner is not None:
examiner_first = prim_examiner.find(".//{*}first-name")
examiner_last = prim_examiner.find(".//{*}last-name")
examiner_dept = prim_examiner.find(".//{*}department")
examiner_dict = {}
if examiner_last is not None and examiner_last.text:
examiner_dict["name"] = examiner_last.text.strip()
if examiner_first is not None and examiner_first.text:
examiner_dict["name"] =examiner_dict["name"] + ", " + examiner_first.text.strip()
if examiner_dept is not None and examiner_dept.text:
examiner_dict["department"] = examiner_dept.text.strip()
if len(examiner_dict.values()) > 0:
primary_examiners.append(examiner_dict)
if primary_examiners:
data["primary_examiners"] = primary_examiners
# create further formats
data["primary_examiners_names"] = [f"{examiner.get('name','')}" for examiner in primary_examiners if examiner.get("name")]
data["primary_examiners_names_text"] = "; ".join(data["primary_examiners_names"])
data["primary_examiners_departments"] = [f"{examiner.get('department','')}" for examiner in primary_examiners if examiner.get("department")]
data["primary_examiners_departments_text"] = "; ".join(data["primary_examiners_departments"])
# assistant examiners
assistant_examiners = []
for asst_examiner in root.findall(".//{*}assistant-examiner"):
if asst_examiner is not None:
examiner_first = asst_examiner.find(".//{*}first-name")
examiner_last = asst_examiner.find(".//{*}last-name")
examiner_dept = asst_examiner.find(".//{*}department")
examiner_dict = {}
if examiner_last is not None and examiner_last.text:
examiner_dict["name"] = examiner_last.text.strip()
if examiner_first is not None and examiner_first.text:
examiner_dict["name"] =examiner_dict["name"] + ", " + examiner_first.text.strip()
if examiner_dept is not None and examiner_dept.text:
examiner_dict["department"] = examiner_dept.text.strip()
if len(examiner_dict.values()) > 0:
assistant_examiners.append(examiner_dict)
if assistant_examiners:
data["assistant_examiners"] = assistant_examiners
# create further formats
data["assistant_examiners_names"] = [f"{examiner.get('name','')}" for examiner in assistant_examiners if examiner.get("name")]
data["assistant_examiners_names_text"] = "; ".join(data["assistant_examiners_names"])
data["assistant_examiners_departments"] = [f"{examiner.get('department','')}" for examiner in assistant_examiners if examiner.get("department")]
data["assistant_examiners_departments_text"] = "; ".join(data["assistant_examiners_departments"])
# ipcr classifications
ipcr_classification = root.find(".//{*}classifications-ipcr")
versions = []
levels = []
sections = []
classes = []
subclasses = []
main_groups = []
subgroups = []
positions = []
classification_values = []
actions = []
data1 = []
data2 = []
offices = []
if ipcr_classification is not None:
for classification in ipcr_classification.findall(".//{*}classification-ipcr"):
for version in classification.findall(".//{*}ipc-version-indicator//{*}date"):
versions.append(version.text.strip())
for level in classification.findall(".//{*}classification-level"):
levels.append(level.text.strip())
for section in classification.findall(".//{*}section"):
sections.append(section.text.strip())
for class_ in classification.findall(".//{*}class"):
classes.append(class_.text.strip())
for subclass in classification.findall(".//{*}subclass"):
subclasses.append(subclass.text.strip())
for main_group in classification.findall(".//{*}main-group"):
main_groups.append(main_group.text.strip())
for subgroup in classification.findall(".//{*}subgroup"):
subgroups.append(subgroup.text.strip())
for position in classification.findall(".//{*}symbol-position"):
positions.append(position.text.strip())
for classification_value in classification.findall(".//{*}classification-value"):
classification_values.append(classification_value.text.strip())
for action in classification.findall(".//{*}action-date//{*}date"):
actions.append(action.text.strip())
for data_ in classification.findall(".//{*}classification-status"):
data1.append(data_.text.strip())
for data_ in classification.findall(".//{*}classification-data-source"):
data2.append(data_.text.strip())
for office in classification.findall(".//{*}generating-office//{*}country"):
offices.append(office.text.strip())
if versions:
data["ipcr_version"] = versions
if levels:
data["ipcr_level"] = levels
if sections:
data["ipcr_section"] = sections
if classes:
data["ipcr_class"] = classes
if subclasses:
data["ipcr_subclass"] = subclasses
if main_groups:
data["ipcr_main_group"] = main_groups
if subgroups:
data["ipcr_subgroup"] = subgroups
if positions:
data["ipcr_position"] = positions
if classification_values:
data["ipcr_classification_value"] = classification_values
if actions:
data["ipcr_action"] = actions
if data1:
data["ipcr_data1"] = data1
if data2:
data["ipcr_data2"] = data2
if offices:
data["ipcr_office"] = offices
# create further formats
ipcr = []
for i in range(max(len(sections), len(classes), len(subclasses), len(main_groups), len(subgroups), len(versions), len(levels), len(positions), len(classification_values), len(actions), len(data1), len(data2), len(offices))):
ipcr.append( f"{sections[i] if i < len(sections) else ''}{classes[i] if i < len(classes) else ''}{subclasses[i] if i < len(subclasses) else ''} {main_groups[i] if i < len(main_groups) else ''}/{subgroups[i] if i < len(subgroups) else ''} {versions[i] if i < len(versions) else ''}{levels[i] if i < len(levels) else ''}{positions[i] if i < len(positions) else ''}{classification_values[i] if i < len(classification_values) else ''}{actions[i] if i < len(actions) else ''}{data1[i] if i < len(data1) else ''}{data2[i] if i < len(data2) else ''}{offices[i] if i < len(offices) else ''}")
data["ipcr"] = ipcr
data["ipcr_text"] = " - ".join(ipcr)
data["ipcr_text_without"] = data["ipcr_text"].replace(" ", "").replace("/", ",")
# cpc classifications
cpc_classification = root.find(".//{*}classifications-cpc")
versions = []
levels = []
sections = []
classes = []
subclasses = []
main_groups = []
subgroups = []
positions = []
classification_values = []
actions = []
data1 = []
data2 = []
offices = []
schemes = []
if cpc_classification is not None:
for classification in cpc_classification.findall(".//{*}classification-cpc"):
for version in classification.findall(".//{*}cpc-version-indicator//{*}date"):
versions.append(version.text.strip())
for level in classification.findall(".//{*}classification-level"):
levels.append(level.text.strip())
for section in classification.findall(".//{*}section"):
sections.append(section.text.strip())
for class_ in classification.findall(".//{*}class"):
classes.append(class_.text.strip())
for subclass in classification.findall(".//{*}subclass"):
subclasses.append(subclass.text.strip())
for main_group in classification.findall(".//{*}main-group"):
main_groups.append(main_group.text.strip())
for subgroup in classification.findall(".//{*}subgroup"):
subgroups.append(subgroup.text.strip())
for position in classification.findall(".//{*}symbol-position"):
positions.append(position.text.strip())
for classification_value in classification.findall(".//{*}classification-value"):
classification_values.append(classification_value.text.strip())
for action in classification.findall(".//{*}action-date//{*}date"):
actions.append(action.text.strip())
for data_ in classification.findall(".//{*}classification-status"):
data1.append(data_.text.strip())
for data_ in classification.findall(".//{*}classification-data-source"):
data2.append(data_.text.strip())
for office in classification.findall(".//{*}generating-office//{*}country"):
offices.append(office.text.strip())
for scheme in classification.findall(".//{*}scheme-origination-code"):
schemes.append(scheme.text.strip())
if versions:
data["cpc_version"] = versions
if levels:
data["cpc_level"] = levels
if sections:
data["cpc_section"] = sections
if classes:
data["cpc_class"] = classes
if subclasses:
data["cpc_subclass"] = subclasses
if main_groups:
data["cpc_main_group"] = main_groups
if subgroups:
data["cpc_subgroup"] = subgroups
if positions:
data["cpc_position"] = positions
if classification_values:
data["cpc_classification_value"] = classification_values
if actions:
data["cpc_action"] = actions
if data1:
data["cpc_data1"] = data1
if data2:
data["cpc_data2"] = data2
if offices:
data["cpc_office"] = offices
if schemes:
data["cpc_scheme"] = schemes
# create further formats
cpc = []
for i in range(max(len(sections), len(classes), len(subclasses), len(main_groups), len(subgroups), len(versions), len(levels), len(positions), len(classification_values), len(actions), len(data1), len(data2), len(offices))):
cpc.append( f"{sections[i] if i < len(sections) else ''}{classes[i] if i < len(classes) else ''}{subclasses[i] if i < len(subclasses) else ''} {main_groups[i] if i < len(main_groups) else ''}/{subgroups[i] if i < len(subgroups) else ''} {versions[i] if i < len(versions) else ''}{levels[i] if i < len(levels) else ''}{positions[i] if i < len(positions) else ''}{classification_values[i] if i < len(classification_values) else ''}{actions[i] if i < len(actions) else ''}{data1[i] if i < len(data1) else ''}{data2[i] if i < len(data2) else ''}{offices[i] if i < len(offices) else ''}")
data["cpc"] = cpc
data["cpc_text"] = " - ".join(cpc)
data["cpc_text_without"] = data["cpc_text"].replace(" ", "").replace("/", ",")
# main classifications
uspcs = []
for classification in root.findall( ".//{*}us-bibliographic-data-grant/{*}classification-national/{*}main-classification"):
if classification.text and classification.text.strip():
uspcs.append(classification.text.strip())
if uspcs:
data["uspc"] = uspcs
# locarno classifications
locs = []
for classification_loc in root.findall(".//{*}classification-locarno//{*}main-classification"):
if classification_loc.text and classification_loc.text.strip():
locs.append(classification_loc.text.strip())
if locs:
data["loc"] = locs
# field of classification search USPC
classifications_foc = []
field_of_classification = root.find(".//{*}us-field-of-classification-search")
if field_of_classification is not None:
for classification in field_of_classification.findall(".//{*}classification-national"):
foc_classifications_main = classification.find(".//{*}main-classification")
if foc_classifications_main is not None and foc_classifications_main.text:
classifications_foc.append(foc_classifications_main.text.strip())
if classifications_foc:
data["field_of_clasification_uspc"] = classifications_foc
# further national classifications
classifications_further = []
for classification in root.findall(".//{*}classification-national//{*}further-classification"):
if classification.text:
classifications_further.append(classification.text.strip())
if classifications_further:
data["further_classifications"] = classifications_further
# applicants
applicants = []
for applicant in root.findall(".//{*}us-applicant"):
applicant_dict = {}
applicant_type = applicant.attrib.get("app-type")
if applicant_type is not None and applicant_type.strip():
applicant_dict["type"] = applicant_type.strip()
applicant_lastname = applicant.find(".//{*}last-name")
if applicant_lastname is not None and applicant_lastname.text:
applicant_dict["name"] = applicant_lastname.text.strip()
applicant_firstname = applicant.find(".//{*}first-name")
if applicant_firstname is not None and applicant_firstname.text:
applicant_dict["name"] =applicant_dict["name"] + ", " + applicant_firstname.text.strip()
applicant_orgname = applicant.find(".//{*}orgname")
if applicant_orgname is not None and applicant_orgname.text:
applicant_dict["org"] = applicant_orgname.text.strip()
applicant_address = applicant.find(".//{*}address")
if applicant_address is not None and applicant_address.text:
applicant_dict["address"] = ""
applicant_city = applicant_address.find(".//{*}city")
if applicant_city is not None and applicant_city.text:
applicant_dict["address"] = applicant_city.text.strip()
applicant_state = applicant_address.find(".//{*}state")
if applicant_state is not None and applicant_state.text:
applicant_dict["address"] = applicant_dict["address"] + ", " + applicant_state.text.strip()
applicant_country = applicant_address.find(".//{*}country")
if applicant_country is not None and applicant_country.text:
applicant_dict["address"] = applicant_dict["address"] + ", " + applicant_country.text.strip()
applicant_nationality = applicant.find(".//{*}nationality//{*}country")
if applicant_nationality is not None and applicant_nationality.text:
applicant_dict["nationality"] = applicant_nationality.text.strip()
if len(applicant_dict.values()) > 0:
applicants.append(applicant_dict)
if applicants:
data["applicants"] = applicants
# create further formats
data["applicants_orgs"] = [f"{applicant.get('org','')}" for applicant in applicants if applicant.get("org")]
data["applicants_orgs_text"]= "; ".join(data["applicants_orgs"])
data["applicants_names"] = [f"{applicant.get('name','')}" for applicant in applicants if applicant.get("name")]
data["applicants_names_text"] = "; ".join(data["applicants_names"])
data["applicants_addresses"] = [f"{applicant.get('address','')}" for applicant in applicants if applicant.get("address")]
data["applicants_addresses_text"] = "; ".join(data["applicants_addresses"])
# inventors
inventors = []
for inventor in root.findall(".//{*}inventor"):
inventor_dict = {}
inventor_lastname = inventor.find(".//{*}last-name")
if inventor_lastname is not None and inventor_lastname.text:
inventor_dict["name"] = inventor_lastname.text.strip()
inventor_firstname = inventor.find(".//{*}first-name")
if inventor_firstname is not None and inventor_firstname.text:
inventor_dict["name"] =inventor_dict["name"] + ", " + inventor_firstname.text.strip()
inventor_address = inventor.find(".//{*}address")
if inventor_address is not None and inventor_address.text:
inventor_dict["address"] = ""
inventor_city = inventor_address.find(".//{*}city")
if inventor_city is not None and inventor_city.text:
inventor_dict["address"] = inventor_city.text.strip()
inventor_state = inventor_address.find(".//{*}state")
if inventor_state is not None and inventor_state.text:
inventor_dict["address"] = inventor_dict["address"] + ", " + inventor_state.text.strip()
inventor_country = inventor_address.find(".//{*}country")
if inventor_country is not None and inventor_country.text:
inventor_dict["address"] = inventor_dict["address"] + ", " + inventor_country.text.strip()
if len(inventor_dict.values()) > 0:
inventors.append(inventor_dict)
if inventors:
data["inventors"] = inventors
# create further formats
data["inventors_names"] = [f"{inventor.get('name','')}" for inventor in inventors if inventor.get("name")]
data["inventors_names_text"] = "; ".join(data["inventors_names"])
data["inventors_addresses"] = [f"{inventor.get('address','')}" for inventor in inventors if inventor.get("address")]
data["inventors_addresses_text"] = "; ".join(data["inventors_addresses"])
# agents
agents = []
for agent in root.findall(".//{*}agent"):
agent_dict = {}
agent_lastname = agent.find(".//{*}last-name")
if agent_lastname is not None and agent_lastname.text:
agent_dict["name"] = agent_lastname.text.strip()
agent_firstname = agent.find(".//{*}first-name")
if agent_firstname is not None and agent_firstname.text:
agent_dict["name"] =agent_dict["name"] + ", " + agent_firstname.text.strip()
agent_orgname = agent.find(".//{*}orgname")
if agent_orgname is not None and agent_orgname.text:
agent_dict["org"] = agent_orgname.text.strip()
# agent_address = agent.find(".//{*}address")
# if agent_address is not None and agent_address.text:
# agent_dict["address"] = agent_address
if len(agent_dict.values()) > 0:
agents.append(agent_dict)
if agents:
data["agents"] = agents
# create further formats
data["agents_names"] = [f"{agent.get('name','')}" for agent in agents if agent.get("name")]
data["agents_names_text"] = "; ".join(data["agents_names"])
data["agents_orgs"] = [f"{agent.get('org','')}" for agent in agents if agent.get("org")]
data["agents_orgs_text"] = "; ".join(data["agents_orgs"])
# citations
citations = []
for citation in root.findall(".//{*}us-citation"):
citation_dict = {}
cited_doc = citation.find(".//{*}doc-number")
if cited_doc is not None and cited_doc.text:
citation_dict["doc_number"] = cited_doc.text.strip()
cited_kind = citation.find(".//{*}kind")
if cited_kind is not None and cited_kind.text:
citation_dict["kind"] = cited_kind.text.strip()
cited_date = citation.find(".//{*}date")
if cited_date is not None and cited_date.text:
citation_dict["date"] = cited_date.text.strip()
cited_name = citation.find(".//{*}name")
if cited_name is not None and cited_name.text:
citation_dict["name"] = cited_name.text.strip()
cited_country = citation.find(".//{*}country")
if cited_country is not None and cited_country.text:
citation_dict["country"] = cited_country.text.strip()
cited_classification = citation.find(".//{*}main-classification")
if cited_classification is not None and cited_classification.text:
citation_dict["classification"] = cited_classification.text.strip()
if len(citation_dict.values()) > 0:
citations.append(citation_dict)
if citations:
#data["citations"] = citations
# create further formats
data["citations_names"] = [f"{citation.get('name','')}" for citation in citations if citation.get("name")]
data["citations_names_text"] = "; ".join(data["citations_names"])
# claims
claims = []
for claim in root.findall(".//{*}claim"):
claim_text = claim.find(".//{*}claim-text")
if claim_text is not None and claim_text.text:
claims.append(claim_text.text.strip())
if claims:
data["claims"] = claims
data["claims_text"] = "; ".join(claims)
# attributes
data.update(root.attrib)
yield data
except (etree.XMLSyntaxError, etree.DTDValidateError) as e:
if strict:
raise
# else skip invalid document
if __name__ == "__main__":
product_downloads_dir = (
sys.argv[1]
if len(sys.argv) > 1
else os.path.join(BASE_DIR, "product_downloads")
)
dtds_path = (
sys.argv[2]
if len(sys.argv) > 2
else os.path.join(BASE_DIR, "dtds")
)
print(
f"Using:\n"
f" Product downloads: {product_downloads_dir}\n"
f" DTDs path: {dtds_path}"
)
for idx, filename in enumerate(sorted(os.listdir(product_downloads_dir))):
xml_dirname = os.path.join(product_downloads_dir, filename)
if not os.path.isdir(xml_dirname):
continue
xml_path = None
for root, dirs, files in os.walk(xml_dirname):
if filename + ".xml" in files:
xml_path = os.path.join(root, filename + ".xml")
break
elif filename[:9] + ".xml" in files:
xml_path = os.path.join(root, filename[:9] + ".xml")
break
if not xml_path:
continue
dtd_version = get_dtd_version(xml_path=xml_path)
dtd_path = os.path.join("dtds", dtd_version)
# Create per-directory logger
logger = logging.getLogger(filename)
logger.setLevel(logging.INFO)
handler = logging.FileHandler(
os.path.join(xml_dirname, "patents.log")
)
handler.setFormatter(logging.Formatter(
"%(asctime)s - %(levelname)s - %(message)s"
))
logger.addHandler(handler)
logger.propagate = False
json_path = os.path.join(xml_dirname, "patents.jsonl")
print(f"Parsing {idx + 1} of {len(os.listdir(product_downloads_dir))}\nPath: {xml_path}")
with open(json_path, "w") as f:
for i, patent in enumerate(
parse_multiple_xml(
file_path=xml_path,
dtd_path=dtd_path,
strict=False
)
):
json.dump(patent, f, ensure_ascii=False)
f.write("\n")
logger.info(f"Saved patent #{i}")
print("Done!")
+374
View File
@@ -0,0 +1,374 @@
import sys
import json
import logging
from logging.handlers import RotatingFileHandler
import os
from elasticsearch import Elasticsearch, exceptions as es_exceptions
from elasticsearch.helpers import bulk
LOG_LEVEL = logging.INFO
LOG_FILE = "patent_indexer.log"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
logger = logging.getLogger("patent_indexer")
logger.setLevel(LOG_LEVEL)
formatter = logging.Formatter(
fmt="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
file_handler = RotatingFileHandler(LOG_FILE, maxBytes=5_000_000, backupCount=3)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
index_name = "uspto_patents_1.0_2025"
try:
es = Elasticsearch('https://inse.nes.uni-due.de:443/elastic', basic_auth=('elastic', 'RLldUaJgbGeoqd3KCX3p'), request_timeout=60, max_retries=5, retry_on_timeout=True)
#es = Elasticsearch('http://localhost:9200',verify_certs=True, basic_auth=('elastic', '+JFa3xVIF0g_YAhpgTLl'), max_retries=5, retry_on_timeout=True)
logger.info("Elasticsearch client initialized.")
except Exception:
logger.exception("Failed to initialize Elasticsearch client.")
raise
def check_elastic(index_name):
logger.info(f"Checking Elasticsearch for index '{index_name}'...")
try:
if not es.ping():
logger.error("Elasticsearch not reachable.")
return False
if es.indices.exists(index=index_name):
logger.info(f"Index '{index_name}' already exists.")
return True
logger.warning(f"Index '{index_name}' does not exist. Creating...")
settings = {
"analysis": {
"analyzer": {
"searchabilityAnalyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": ["lowercase", "asciifolding"]
}
}
}
}
mappings = {"properties":{
"application_number": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
},
"application_date": { "type": "integer" },
"application_country": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"publication_number":{
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
},
"publication_kind": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"publication_country": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"publication_date": { "type": "integer"},
"publication_year": { "type": "integer"},
"series_code": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"title": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"length_of_grant": { "type": "integer" },
"number_of_claims": { "type": "integer" },
"application_type": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"assignees": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"assignees_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"assignees_orgs": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"assignees_orgs_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"assignees_addresses": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"assignees_addresses_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"description_paragraph": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"description_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"description_header": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"primary_examiners_names": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"primary_examiners_names_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"primary_examiners_departments": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"primary_examiners_departments_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"assistant_examiners_names": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"assistant_examiners_names_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"assistant_examiners_departments": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"assistant_examiners_departments_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"ipcr": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"ipcr_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"ipcr_text_without": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"cpc": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"cpc_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"cpc_text_without": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"uspc": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"loc": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"field_of_clasification_uspc": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"applicants_orgs": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"applicants_orgs_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"applicants_names": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"applicants_names_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"applicants_addresses": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"applicants_addresses_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"inventors_names": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"inventors_names_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"inventors_addresses": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"inventors_addresses_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"agents_names": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"agents_names_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"agents_orgs": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"agents_orgs_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"citations_names": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"citations_names_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"claims": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"claims_text": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"lang": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"dtd-version": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"file": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"status": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"id": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"country": { "type": "text", "analyzer": "searchabilityAnalyzer" },
"date-produced": { "type": "integer" },
"date-publ": { "type": "integer" },
"priority_claims": {
"type": "nested",
"properties": {
"inventor": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
}
}
},
"primary_examiners": {
"type": "nested",
"properties": {
"inventor": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
}
}
},
"assistant_examiners": {
"type": "nested",
"properties": {
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
}
}
},
"applicants": {
"type": "nested",
"properties": {
"inventor": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
}
}
},
"inventors": {
"type": "nested",
"properties": {
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
}
}
},
"agents": {
"type": "nested",
"properties": {
"inventor": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
}
}
}
}
}
es.indices.create(index=index_name, mappings=mappings, settings=settings)
logger.info(f"Index '{index_name}' created successfully.")
return True
except Exception:
logger.exception("Failed during index check/creation.")
return False
def get_patent(index_name, patents):
for patent in patents:
yield {
"_index": index_name,
"_source": patent
}
# Bulk Upload
def upload_patents_bulk(index_name, patents, chunk_size = 1000):
print("here")
if not patents:
logger.warning("No patents provided for indexing.")
return
logger.info(
f"Starting bulk indexing of {len(patents)} patents "
f"(chunk_size={chunk_size})..."
)
try:
success, errors = bulk(
es,
get_patent(index_name, patents),
chunk_size=chunk_size,
raise_on_error=False,
stats_only=False
)
logger.info(f"Bulk indexing completed. Successful documents: {success}")
if errors:
logger.error(f"{len(errors)} documents failed during bulk indexing.")
logger.debug(f"Bulk errors: {errors}")
except es_exceptions.ConnectionTimeout:
logger.exception("Bulk indexing failed due to timeout.")
except Exception:
logger.exception("Unexpected error during bulk indexing.")
if __name__ == "__main__":
logger.info("Starting")
if not check_elastic(index_name=index_name):
logger.critical("Startup check failed. Exiting.")
sys.exit(1)
product_downloads_dir = (
sys.argv[1]
if len(sys.argv) > 1
else os.path.join(BASE_DIR, "product_downloads")
)
print(
f"Using:\n"
f" Product downloads: {product_downloads_dir}\n"
)
if not os.path.isdir(product_downloads_dir):
logger.critical(f"Directory not found: {product_downloads_dir}")
sys.exit(1)
for filename in os.listdir(product_downloads_dir):
patents_dirname = os.path.join(product_downloads_dir, filename)
if not os.path.isdir(patents_dirname):
continue
patents_path = None
for root, dirs, files in os.walk(patents_dirname):
if "patents.jsonl" in files:
patents_path = os.path.join(root, "patents.jsonl")
break
if not patents_path:
logger.warning(f"No patents.jsonl found in {patents_dirname}")
continue
logger.info(f"Processing {patents_path}")
try:
with open(patents_path, "r", encoding="utf-8") as f:
batch = []
for line_number, line in enumerate(f, 1):
try:
batch.append(json.loads(line))
except json.JSONDecodeError as e:
logger.error(
f"JSON error in {patents_path} line {line_number}: {e}"
)
continue
if len(batch) >= 2000:
upload_patents_bulk(index_name=index_name, patents=batch)
batch = []
if batch:
upload_patents_bulk(index_name=index_name, patents=batch)
except Exception:
logger.exception(f"Failed processing {patents_path}")
continue
logger.info("Process finished.")
+187
View File
@@ -0,0 +1,187 @@
# USPTO Patent Pipeline
A three-stage pipeline for fetching, parsing, and uploading USPTO patents to Elasticsearch.
---
## Overview
```
1_download_products_api.py → 2_parse_xml.py → 3_upload_patents.py
↓ ↓ ↓
product_downloads/ .jsonl per product Elasticsearch
```
The pipeline is split into three independent scripts that are executed sequentially. Each script operates on the `product_downloads/` folder as the shared artifact between stages.
---
## Prerequisites
- Python 3.x
- A running Elasticsearch instance
- Internet access to reach the USPTO API
---
## Directory Structure
```
v1/
├── 1_download_products_api.py
├── 2_parse_xml.py
├── 3_upload_patents.py
├── product_response.json # generated in Stage 1
├── dtds/ # generated in Stage 1
│ └── *.dtd
└── product_downloads/ # generated in Stage 1
└── ipg250411/
├── *.xml
└── *.jsonl # generated in Stage 2
```
---
## Stage 1 — Download (`1_download_products_api.py`)
Queries the USPTO API for patents within a given date range, downloads them as `.zip` archives, and extracts their contents.
### Usage
```bash
python 1_download_products_api.py <date_from> <date_to> <key=value(if not in .env)>
```
### Parameters
| Parameter | Position | Format | Description |
|-----------|----------|--------|-------------|
| `date_from` | `sys.argv[1]` | `yyyy-mm-dd` | Start date (inclusive) |
| `date_to` | `sys.argv[2]` | `yyyy-mm-dd` | End date (inclusive) |
| `key` | `sys.argv[3]` | `key=value` | api_key for USPTO |
### Example
```bash
python 1_download_products_api.py 2025-01-01 2025-03-31 key=value(Optional-> if not in .env)
```
### What it does
1. Sends a search query to the USPTO API for patents in the specified date range.
2. Saves the API response (including direct download URLs) to `product_response.json`.
3. Downloads all DTD files for every XML version into the `dtds/` folder.
4. Downloads each product as a `.zip` archive into `product_downloads/`.
5. Extracts each archive into a same-named folder (e.g., `product_downloads/ipg250411/`).
6. Removes the `.zip` file after extraction.
### Output
- `product_response.json` — raw API response with product metadata and download URLs
- `dtds/` — DTD files used for XML validation in Stage 2
- `product_downloads/<product_name>/` — extracted product directories containing `.xml` files
---
## Stage 2 — Parse (`2_parse_xml.py`)
Iterates over all product directories in `product_downloads/`, parses the `.xml` patent files using DTD validation, and writes the results as `.jsonl` files.
### Usage
```bash
python 2_parse_xml.py [product_downloads_path] [dtds_path]
```
### Parameters
| Parameter | Position | Default | Description |
|-----------|----------|---------|-------------|
| `product_downloads_path` | `sys.argv[1]` | auto-detected in current directory | Path to the `product_downloads/` folder |
| `dtds_path` | `sys.argv[2]` | auto-detected in current directory | Path to the `dtds/` folder |
### Example
```bash
# With explicit paths
python 2_parse_xml.py ./product_downloads ./dtds
# With auto-detection
python 2_parse_xml.py
```
### What it does
1. Scans every subdirectory inside `product_downloads/`.
2. Locates `.xml` files within each product directory.
3. Parses each XML file against its corresponding DTD schema.
4. Writes the structured patent data into a `.jsonl` file inside the same product directory.
### Output
- `product_downloads/<product_name>/<product_name>.jsonl` — one JSON object per line, one file per product
---
## Stage 3 — Upload (`3_upload_patents.py`)
Iterates over all product directories in `product_downloads/`, reads the `.jsonl` files produced in Stage 2, and bulk-uploads the patent records to an Elasticsearch index.
### Usage
```bash
python 3_upload_patents.py [product_downloads_path]
```
### Parameters
| Parameter | Position | Default | Description |
|-----------|----------|---------|-------------|
| `product_downloads_path` | `sys.argv[1]` | auto-detected in current directory | Path to the `product_downloads/` folder |
### Example
```bash
# With explicit path
python 3_upload_patents.py ./product_downloads
# With auto-detection
python 3_upload_patents.py
```
### What it does
1. Scans every subdirectory inside `product_downloads/`.
2. Locates the `.jsonl` file in each product directory.
3. Reads and uploads each patent record to the configured Elasticsearch index.
### Output
- Patent records indexed in Elasticsearch.
---
## Running the Full Pipeline
```bash
# Step 1: Download patents for a given date range
python 1_download_products_api.py 2025-01-01 2025-03-31
# Step 2: Parse the downloaded XML files
python 2_parse_xml.py
# Step 3: Upload parsed patents to Elasticsearch
python 3_upload_patents.py
```
---
## Date Format Reference
All date parameters follow the `yyyy-mm-dd` format.
| ✅ Valid | ❌ Invalid |
|---------|----------|
| `2025-03-21` | `21.03.2025` |
| `2015-01-01` | `01/01/2015` |
| `2024-12-31` | `2024/12/31` |