| 1 | """A company's US patent filings in a date window, from USPTO Patent Public Search. |
| 2 | |
| 3 | Keyless, stdlib only. An artifact lane: it returns no ranked items, only what |
| 4 | a patent digest is rendered from. The engine does not judge which filing is |
| 5 | interesting; it finds the filings that are the company's, sets aside the ones |
| 6 | that publish nothing new, and reads the text of a few of the rest. |
| 7 | |
| 8 | One call makes one anonymous session, two list searches over the window |
| 9 | (published applications by applicant name, grants by assignee name), one list |
| 10 | search over the twelve months before the window, and up to ``DETAIL_SLOTS`` |
| 11 | document reads, all inside one wall-clock budget. The baseline search gets at |
| 12 | most a third of it, so the reads are left time. |
| 13 | |
| 14 | - Whose filings: every name a row was filed under is classified against the |
| 15 | company (``lib.company_names``). Rows are grouped by that name; a group is |
| 16 | confirmed (the company's own name, or one known to belong to it) or |
| 17 | name-matched (the company's name plus more words, such as a licensing |
| 18 | subsidiary). Names that are neither are only counted. |
| 19 | - What is new: a first US publication is an A1 application, or a B1 grant |
| 20 | (one with no earlier publication), that does not continue an older |
| 21 | application. Continuations, grants of applications already published, |
| 22 | designs and other kinds are counted, never shown. |
| 23 | - What is counted: ``counts`` holds the company's own filings, those in |
| 24 | confirmed groups: ``applications``, ``grants``, ``first_publications``, |
| 25 | ``continuing``, ``previously_published_grants``, ``designs`` and |
| 26 | ``other_kinds``. Filings in name-matched groups may be a stranger's, so |
| 27 | they are counted apart and only as ``name_matched_applications``, |
| 28 | ``name_matched_grants`` and ``name_matched_first_publications``. Entries |
| 29 | and the index still hold name-matched first publications, each labelled |
| 30 | by its ``group_kind``. |
| 31 | - Which get text: half the slots go to filings in the CPC subclasses the |
| 32 | company filed in least over the year before, half to the newest. |
| 33 | |
| 34 | USPTO has said the site will require sign-in. A refused anonymous session is |
| 35 | its own outcome, told by status and by the missing token, never by words in |
| 36 | the body: the working response already carries the notice. |
| 37 | |
| 38 | ``fetch_patent_data`` never raises. A run calls it through ``start`` and |
| 39 | ``collect``: the fetch runs on a daemon thread beside the run's other sources, |
| 40 | so it adds no time to a run that outlasts it. |
| 41 | """ |
| 42 | |
| 43 | from __future__ import annotations |
| 44 | |
| 45 | import html |
| 46 | import re |
| 47 | import threading |
| 48 | import time |
| 49 | from collections import Counter |
| 50 | from collections.abc import Callable |
| 51 | from datetime import date, timedelta |
| 52 | from typing import Any |
| 53 | |
| 54 | from . import env, http, log, schema |
| 55 | from .company_names import CONFIRMED, NAME_MATCHED, classify_applicant, name_key |
| 56 | |
| 57 | SOURCE = "patents" |
| 58 | |
| 59 | BASE_URL = "https://ppubs.uspto.gov" |
| 60 | PDF_URL = "https://image-ppubs.uspto.gov/dirsearch-public/print/downloadPdf/" |
| 61 | # A browser-style agent, sent with the Referer and Origin the site's own web app uses. |
| 62 | USER_AGENT = "Mozilla/5.0 (research-cli)" |
| 63 | |
| 64 | APPLICATIONS = "US-PGPUB" |
| 65 | GRANTS = "USPAT" |
| 66 | # database -> (search field, the row field holding the filed-under names) |
| 67 | _NAME_FIELDS = {APPLICATIONS: ("aanm", "applicantName"), GRANTS: ("asnm", "assigneeName")} |
| 68 | |
| 69 | # Everything one run spends on the lane, measured from ``start``. The lane |
| 70 | # runs beside a pipeline that takes minutes, so this rarely lengthens a run. |
| 71 | LANE_BUDGET_SECONDS = 90.0 |
| 72 | # The most of the lane's budget the year-back baseline search may take. |
| 73 | BASELINE_SHARE = 1 / 3 |
| 74 | COLLECT_GRACE_SECONDS = 2.0 |
| 75 | REQUEST_TIMEOUT_SECONDS = 8.0 |
| 76 | REQUEST_ATTEMPTS = 2 |
| 77 | # lib.http gives up on the 429 that brings its count to this number, so one |
| 78 | # wait named by the host is honoured and the second 429 is the answer. |
| 79 | MAX_429_ATTEMPTS = 2 |
| 80 | |
| 81 | PAGE_SIZE = 500 |
| 82 | MAX_PAGES = 2 |
| 83 | MAX_EXTRA_NAMES = 12 |
| 84 | MAX_GROUPS = 8 |
| 85 | MAX_OTHER_NAMES = 5 |
| 86 | DETAIL_SLOTS = 12 |
| 87 | MAX_REFILL_FETCHES = 6 |
| 88 | MAX_INDEX = 30 |
| 89 | MIN_BASELINE_ROWS = 20 |
| 90 | # An application filed more than 13 months after the earliest application it |
| 91 | # is related to continues it. A provisional is at most 12 months older. |
| 92 | CONTINUING_AFTER_DAYS = 396 |
| 93 | ABSTRACT_CHARS = 1_000 |
| 94 | FIRST_CLAIM_CHARS = 1_200 |
| 95 | # Confirmed filers other than the company's own name (a subsidiary named by |
| 96 | # Wikidata) that are each given one of the detailed slots, so the parent's |
| 97 | # filings cannot take every slot. |
| 98 | MAX_RESERVED_FILERS = 3 |
| 99 | MAX_CPC_CODES = 5 |
| 100 | |
| 101 | _FIRST = "first_publications" |
| 102 | _NAME_MATCHED_FIRST = "name_matched_first_publications" |
| 103 | _CONTINUING = "continuing" |
| 104 | _PUBLISHED_BEFORE = "previously_published_grants" |
| 105 | _DESIGNS = "designs" |
| 106 | _OTHER_KINDS = "other_kinds" |
| 107 | |
| 108 | _CONTINUES_A_PARENT = re.compile( |
| 109 | r"\b(?:continuation(?:-in-part)?|division(?:al)?)\b", re.IGNORECASE, |
| 110 | ) |
| 111 | _CLAIM_ONE = re.compile(r"<b>\s*1\s*</b>") |
| 112 | _CLAIM_TWO = re.compile(r"<b>\s*2\s*</b>") |
| 113 | |
| 114 | |
| 115 | class _SignInRequired(Exception): |
| 116 | """USPTO refused the anonymous session, or a later call made with it.""" |
| 117 | |
| 118 | |
| 119 | class _OutOfTime(Exception): |
| 120 | """The lane's budget ran out before a request could be sent.""" |
| 121 | |
| 122 | |
| 123 | # lib.http raises this when a request's deadline passes; every document read |
| 124 | # carries the lane's own deadline. Bound here so a test transport standing in |
| 125 | # for ``http`` does not have to provide it. |
| 126 | _LANE_DEADLINE_PASSED = http.DeadlineExceeded |
| 127 | |
| 128 | |
| 129 | def _log(message: str) -> None: |
| 130 | log.source_log("Patents", message, tty_only=False) |
| 131 | |
| 132 | |
| 133 | class _Budget: |
| 134 | """The wall-clock allowance for everything one call does.""" |
| 135 | |
| 136 | def __init__(self, seconds: float, *, within: _Budget | None = None) -> None: |
| 137 | self.seconds = max(0.0, float(seconds)) |
| 138 | self.deadline = time.monotonic() + self.seconds |
| 139 | if within is not None: |
| 140 | self.deadline = min(self.deadline, within.deadline) |
| 141 | |
| 142 | def share(self, fraction: float) -> _Budget: |
| 143 | """A budget of ``fraction`` of this one's seconds, from now, ending no |
| 144 | later than this one.""" |
| 145 | return _Budget(self.seconds * fraction, within=self) |
| 146 | |
| 147 | def bounds(self) -> dict[str, Any]: |
| 148 | """The limits of the next request: its own timeout clipped to what is |
| 149 | left, and the call's deadline, which also ends any retry wait.""" |
| 150 | remaining = self.deadline - time.monotonic() |
| 151 | if remaining <= 0: |
| 152 | raise _OutOfTime("Request deadline exceeded: the patent lane's time budget is spent") |
| 153 | return { |
| 154 | "timeout": min(REQUEST_TIMEOUT_SECONDS, remaining), |
| 155 | "deadline_monotonic": self.deadline, |
| 156 | "retries": REQUEST_ATTEMPTS, |
| 157 | "max_429_retries": MAX_429_ATTEMPTS, |
| 158 | } |
| 159 | |
| 160 | |
| 161 | def fetch_patent_data( |
| 162 | company: dict, |
| 163 | date_from: str, |
| 164 | date_to: str, |
| 165 | config: dict | None = None, |
| 166 | *, |
| 167 | budget_seconds: float = LANE_BUDGET_SECONDS, |
| 168 | ) -> dict: |
| 169 | """Return the company's filings published between two YYYY-MM-DD dates. |
| 170 | |
| 171 | One of: ``{"artifact": {...}}`` when a filing sits in a confirmed or |
| 172 | name-matched group; ``{"state": "none", "other_names": [...]}`` when the |
| 173 | searches answered and none does; ``{"state": "signin", "detail": str}`` |
| 174 | when USPTO refuses an anonymous session; ``{"state": "error", "detail": |
| 175 | str}`` for any other failure before the lists were read. ``config`` is the |
| 176 | lane calling convention; nothing here is configurable. |
| 177 | """ |
| 178 | try: |
| 179 | return _fetch(company, date_from, date_to, _Budget(budget_seconds)) |
| 180 | except _SignInRequired as exc: |
| 181 | _log(str(exc)) |
| 182 | return {"state": "signin", "detail": str(exc)} |
| 183 | except Exception as exc: # noqa: BLE001 - the lane must not fail a run |
| 184 | known = isinstance(exc, (http.HTTPError, _OutOfTime)) |
| 185 | detail = str(exc) if known else f"{type(exc).__name__}: {exc}" |
| 186 | _log(f"no patent data: {detail}") |
| 187 | return {"state": "error", "detail": detail} |
| 188 | |
| 189 | |
| 190 | def is_excluded(config: dict[str, Any] | None) -> bool: |
| 191 | """True when ``EXCLUDE_SOURCES`` names this source, or the caller's |
| 192 | environment asks for a run with no patent digest.""" |
| 193 | return SOURCE in env.exclude_sources(config or {}) or env.patent_digest_disabled() |
| 194 | |
| 195 | |
| 196 | def start( |
| 197 | company: dict | None, date_from: str, date_to: str, config: dict[str, Any] | None = None, |
| 198 | ) -> dict[str, Any] | None: |
| 199 | """Begin fetching the company's filings beside the run; ``collect`` takes |
| 200 | the handle. None, and no request, with no company name or with the source |
| 201 | excluded. |
| 202 | |
| 203 | The thread is a daemon: a fetch that outlives its budget is left behind |
| 204 | and cannot hold the process open.""" |
| 205 | if not (company or {}).get("company") or is_excluded(config): |
| 206 | return None |
| 207 | budget = LANE_BUDGET_SECONDS |
| 208 | handle: dict[str, Any] = { |
| 209 | "company": str(company["company"]), |
| 210 | # A little past the fetch's own budget, so a fetch that ran out of time |
| 211 | # reports that itself rather than racing the collector. |
| 212 | "deadline": time.monotonic() + budget + COLLECT_GRACE_SECONDS, |
| 213 | "outcome": None, |
| 214 | } |
| 215 | |
| 216 | def work() -> None: |
| 217 | handle["outcome"] = fetch_patent_data( |
| 218 | dict(company), date_from, date_to, config, budget_seconds=budget, |
| 219 | ) |
| 220 | |
| 221 | handle["thread"] = threading.Thread(target=work, name="patents-lane", daemon=True) |
| 222 | handle["thread"].start() |
| 223 | return handle |
| 224 | |
| 225 | |
| 226 | def collect(handle: dict[str, Any] | None, report: schema.Report) -> None: |
| 227 | """Record what the fetch begun by ``start`` found on the report. |
| 228 | |
| 229 | Waits only for what is left of the lane's budget. The ``patents`` artifact |
| 230 | on success; a degraded source outcome on a failed fetch; nothing for a |
| 231 | company with no filings, for USPTO requiring sign-in (nothing a user can |
| 232 | fix), or for a fetch still running when the budget ends.""" |
| 233 | if handle is None: |
| 234 | return |
| 235 | handle["thread"].join(max(0.0, handle["deadline"] - time.monotonic())) |
| 236 | outcome = handle["outcome"] |
| 237 | company = handle["company"] |
| 238 | if outcome is None: |
| 239 | _log(f"{company}: still searching after {LANE_BUDGET_SECONDS:g}s; patents skipped") |
| 240 | return |
| 241 | if "artifact" in outcome: |
| 242 | report.artifacts[SOURCE] = outcome["artifact"] |
| 243 | _log(_summary(outcome["artifact"])) |
| 244 | return |
| 245 | state = outcome.get("state") |
| 246 | if state == "error": |
| 247 | detail = str(outcome.get("detail") or "patent search failed") |
| 248 | report.source_status[SOURCE] = schema.SourceOutcome( |
| 249 | source=SOURCE, |
| 250 | state=http.classify_failure(message=detail), |
| 251 | detail=detail, |
| 252 | fix_hint="doctor", |
| 253 | ) |
| 254 | elif state == "signin": |
| 255 | _log(f"{company}: USPTO Patent Public Search now requires sign-in; patents skipped") |
| 256 | elif state == "none": |
| 257 | others = [str(name) for name in outcome.get("other_names") or []][:3] |
| 258 | seen = f"; other names seen: {', '.join(others)}" if others else "" |
| 259 | _log(f"{company}: no filings under the company's name in the window{seen}") |
| 260 | |
| 261 | |
| 262 | def _summary(artifact: dict[str, Any]) -> str: |
| 263 | counts = artifact.get("counts") or {} |
| 264 | applications = counts.get("applications", 0) + counts.get("name_matched_applications", 0) |
| 265 | grants = counts.get("grants", 0) + counts.get("name_matched_grants", 0) |
| 266 | groups = artifact.get("groups") or [] |
| 267 | names = ", ".join(f"{group['name']} ({group['kind']})" for group in groups[:3]) |
| 268 | more = f" and {len(groups) - 3} more" if len(groups) > 3 else "" |
| 269 | return ( |
| 270 | f"{artifact.get('company')}: {applications} applications, {grants} grants, " |
| 271 | f"{counts.get(_FIRST, 0) + counts.get(_NAME_MATCHED_FIRST, 0)} first publications; " |
| 272 | f"filed under {names}{more}" |
| 273 | ) |
| 274 | |
| 275 | |
| 276 | def _fetch(company: dict, date_from: str, date_to: str, budget: _Budget) -> dict: |
| 277 | day_from, day_to = date.fromisoformat(date_from), date.fromisoformat(date_to) |
| 278 | phrases = _phrases(company) |
| 279 | if not phrases: |
| 280 | raise ValueError("no company name to search patents for") |
| 281 | classify = _classifier(company) |
| 282 | |
| 283 | session = _open_session(budget) |
| 284 | rows: dict[str, list[dict]] = {} |
| 285 | floor = False |
| 286 | for database in (APPLICATIONS, GRANTS): |
| 287 | query = _query(phrases, database, day_from, day_to) |
| 288 | rows[database], cut = _search(session, query, database, budget, pages=MAX_PAGES) |
| 289 | floor = floor or cut |
| 290 | |
| 291 | groups, other_names = _group(rows, classify) |
| 292 | if not groups: |
| 293 | return {"state": "none", "other_names": other_names} |
| 294 | for group in groups: |
| 295 | group["other_filer"] = ( |
| 296 | group["kind"] == CONFIRMED |
| 297 | and classify_applicant(group["name"], company.get("company")) != CONFIRMED |
| 298 | ) |
| 299 | |
| 300 | # The company's own counts are of confirmed groups. Of a name-matched |
| 301 | # group, which may be a stranger's, only the first publications are |
| 302 | # counted, under their own key. |
| 303 | counts: Counter[str] = Counter() |
| 304 | candidates = [] |
| 305 | for group in groups: |
| 306 | confirmed = group["kind"] == CONFIRMED |
| 307 | for database, row in group["rows"]: |
| 308 | bucket = _bucket(database, row) |
| 309 | if confirmed: |
| 310 | counts[bucket] += 1 |
| 311 | elif bucket == _FIRST: |
| 312 | counts[_NAME_MATCHED_FIRST] += 1 |
| 313 | if bucket == _FIRST: |
| 314 | candidates.append(_candidate(database, row, group)) |
| 315 | |
| 316 | frequencies = None |
| 317 | if candidates: |
| 318 | frequencies = _baseline(session, phrases, day_from, classify, budget.share(BASELINE_SHARE)) |
| 319 | ordered, reserved = _order(candidates, frequencies) |
| 320 | entries, demoted, rest = _read_details(session, ordered, budget, reserved) |
| 321 | for candidate in demoted: |
| 322 | if candidate["group_kind"] == CONFIRMED: |
| 323 | counts[_FIRST] -= 1 |
| 324 | counts[_CONTINUING if candidate["kind"] == "application" else _PUBLISHED_BEFORE] += 1 |
| 325 | else: |
| 326 | counts[_NAME_MATCHED_FIRST] -= 1 |
| 327 | missing = min(DETAIL_SLOTS - len(entries), len(rest)) |
| 328 | index = [_index_item(candidate) for candidate in rest[:MAX_INDEX]] |
| 329 | |
| 330 | def total(kind: str, database: str) -> int: |
| 331 | return sum( |
| 332 | 1 for group in groups if group["kind"] == kind |
| 333 | for row_database, _row in group["rows"] if row_database == database |
| 334 | ) |
| 335 | |
| 336 | return {"artifact": { |
| 337 | "company": str(company["company"]), |
| 338 | "company_via_person": bool(company.get("company_via_person")), |
| 339 | "window": {"from": date_from, "to": date_to}, |
| 340 | "groups": [ |
| 341 | { |
| 342 | "name": group["name"], |
| 343 | "kind": group["kind"], |
| 344 | "applications": sum(1 for database, _row in group["rows"] if database == APPLICATIONS), |
| 345 | "grants": sum(1 for database, _row in group["rows"] if database == GRANTS), |
| 346 | } |
| 347 | for group in groups |
| 348 | ], |
| 349 | "other_names": other_names, |
| 350 | "counts": { |
| 351 | "applications": total(CONFIRMED, APPLICATIONS), |
| 352 | "grants": total(CONFIRMED, GRANTS), |
| 353 | "name_matched_applications": total(NAME_MATCHED, APPLICATIONS), |
| 354 | "name_matched_grants": total(NAME_MATCHED, GRANTS), |
| 355 | _FIRST: counts[_FIRST], |
| 356 | _NAME_MATCHED_FIRST: counts[_NAME_MATCHED_FIRST], |
| 357 | _CONTINUING: counts[_CONTINUING], |
| 358 | _PUBLISHED_BEFORE: counts[_PUBLISHED_BEFORE], |
| 359 | _DESIGNS: counts[_DESIGNS], |
| 360 | _OTHER_KINDS: counts[_OTHER_KINDS], |
| 361 | "floor": floor, |
| 362 | }, |
| 363 | "entries": entries, |
| 364 | "index": index, |
| 365 | "partial": {"missing_text": missing} if missing else None, |
| 366 | "status": "digest" if entries or index else "counts-only", |
| 367 | }} |
| 368 | |
| 369 | |
| 370 | # --- requests --------------------------------------------------------------- |
| 371 | |
| 372 | |
| 373 | def _headers(token: str | None) -> dict[str, str]: |
| 374 | return { |
| 375 | "User-Agent": USER_AGENT, |
| 376 | "Content-Type": "application/json", |
| 377 | "Referer": f"{BASE_URL}/pubwebapp/", |
| 378 | "Origin": BASE_URL, |
| 379 | "X-Access-Token": token or "null", |
| 380 | } |
| 381 | |
| 382 | |
| 383 | def _send(call: Callable[..., Any], *args: Any, budget: _Budget, **kwargs: Any) -> Any: |
| 384 | """Make one request inside the budget. A 401 or 403 is the sign-in outcome.""" |
| 385 | try: |
| 386 | return call(*args, **kwargs, **budget.bounds()) |
| 387 | except http.HTTPError as exc: |
| 388 | if exc.status_code in (401, 403): |
| 389 | raise _SignInRequired( |
| 390 | f"USPTO Patent Public Search refused an anonymous session (HTTP {exc.status_code})" |
| 391 | ) from exc |
| 392 | raise |
| 393 | |
| 394 | |
| 395 | def _open_session(budget: _Budget) -> dict[str, Any]: |
| 396 | """Open an anonymous session: the token every later call sends and the |
| 397 | case id every search names.""" |
| 398 | body, headers = _send( |
| 399 | http.post, |
| 400 | f"{BASE_URL}/api/users/me/session", |
| 401 | json_data=-1, |
| 402 | headers=_headers(None), |
| 403 | return_headers=True, |
| 404 | budget=budget, |
| 405 | ) |
| 406 | if not isinstance(body, dict): |
| 407 | raise TypeError("schema: the USPTO session response is not a JSON object") |
| 408 | token = (headers or {}).get("x-access-token") |
| 409 | case = body.get("userCase") |
| 410 | case_id = case.get("caseId") if isinstance(case, dict) else None |
| 411 | if not token or case_id is None: |
| 412 | raise _SignInRequired("USPTO Patent Public Search gave no anonymous session") |
| 413 | return {"token": str(token), "case_id": case_id} |
| 414 | |
| 415 | |
| 416 | def _phrases(company: Any) -> list[str]: |
| 417 | """The names to search under: the company's, then those of its other |
| 418 | names that the company's own name does not already match as a phrase.""" |
| 419 | if not isinstance(company, dict): |
| 420 | return [] |
| 421 | own = name_key(company.get("company")) |
| 422 | if not own: |
| 423 | return [] |
| 424 | phrases = [own] |
| 425 | for name in company.get("company_names") or (): |
| 426 | key = name_key(name) |
| 427 | if not key or key in phrases or key.startswith(f"{own} "): |
| 428 | continue |
| 429 | phrases.append(key) |
| 430 | if len(phrases) > MAX_EXTRA_NAMES: |
| 431 | break |
| 432 | return phrases |
| 433 | |
| 434 | |
| 435 | def _query(phrases: list[str], database: str, day_from: date, day_to: date) -> str: |
| 436 | names = " OR ".join(f'"{phrase}"' for phrase in phrases) |
| 437 | return ( |
| 438 | f"({names}).{_NAME_FIELDS[database][0]}. " |
| 439 | f'AND @pd>="{day_from:%Y%m%d}"<="{day_to:%Y%m%d}"' |
| 440 | ) |
| 441 | |
| 442 | |
| 443 | def _search( |
| 444 | session: dict[str, Any], query: str, database: str, budget: _Budget, *, pages: int, |
| 445 | ) -> tuple[list[dict], bool]: |
| 446 | """Rows of a list search, newest first, and whether more exist than the |
| 447 | pages read. Rows are documents and ``numFound`` counts them.""" |
| 448 | rows: list[dict] = [] |
| 449 | for page in range(pages): |
| 450 | body = _send( |
| 451 | http.post, |
| 452 | f"{BASE_URL}/api/searches/searchWithBeFamily", |
| 453 | json_data={ |
| 454 | "start": page * PAGE_SIZE, |
| 455 | "pageCount": PAGE_SIZE, |
| 456 | "sort": "date_publ desc", |
| 457 | "docFamilyFiltering": "noFiltering", |
| 458 | "searchType": 1, |
| 459 | "familyIdEnglishOnly": True, |
| 460 | "familyIdFirstPreferred": "US-PGPUB", |
| 461 | "familyIdSecondPreferred": "USPAT", |
| 462 | "familyIdThirdPreferred": "FPRS", |
| 463 | "showDocPerFamilyPref": "showEnglish", |
| 464 | "queryId": 0, |
| 465 | "tagDocSearch": False, |
| 466 | "query": { |
| 467 | "caseId": session["case_id"], |
| 468 | "hl_snippets": "2", |
| 469 | "op": "OR", |
| 470 | "q": query, |
| 471 | "queryName": query, |
| 472 | "highlights": "0", |
| 473 | "qt": "brs", |
| 474 | "spellCheck": False, |
| 475 | "viewName": "tile", |
| 476 | "plurals": True, |
| 477 | "britishEquivalents": True, |
| 478 | "databaseFilters": [{"databaseName": database, "countryCodes": []}], |
| 479 | "searchType": 1, |
| 480 | "ignorePersist": True, |
| 481 | "userEnteredQuery": query, |
| 482 | }, |
| 483 | }, |
| 484 | headers=_headers(session["token"]), |
| 485 | budget=budget, |
| 486 | ) |
| 487 | found = body.get("patents") if isinstance(body, dict) else "" |
| 488 | if not isinstance(found, list | None): |
| 489 | raise TypeError("schema: the USPTO search response has no list of patents") |
| 490 | rows.extend(row for row in found or () if isinstance(row, dict)) |
| 491 | total = body.get("numFound") |
| 492 | if not isinstance(total, int) or total <= (page + 1) * PAGE_SIZE: |
| 493 | return rows, False |
| 494 | return rows, True |
| 495 | |
| 496 | |
| 497 | def _baseline( |
| 498 | session: dict[str, Any], |
| 499 | phrases: list[str], |
| 500 | day_from: date, |
| 501 | classify: Callable[[str], str | None], |
| 502 | budget: _Budget, |
| 503 | ) -> Counter[str] | None: |
| 504 | """How many of the company's recent applications named each CPC subclass, |
| 505 | or None when that cannot be said, including when the search outlasts |
| 506 | ``budget``, the baseline's own share of the lane's. The sample is one page: the newest |
| 507 | ``PAGE_SIZE`` applications of the twelve months before the window, which |
| 508 | for a large filer covers only the latest months of that year. It says what |
| 509 | the company has been filing lately, not what it filed all year.""" |
| 510 | try: |
| 511 | start = day_from.replace(year=day_from.year - 1) |
| 512 | except ValueError: # 29 February |
| 513 | start = day_from.replace(year=day_from.year - 1, day=28) |
| 514 | query = _query(phrases, APPLICATIONS, start, day_from - timedelta(days=1)) |
| 515 | try: |
| 516 | rows, _cut = _search(session, query, APPLICATIONS, budget, pages=1) |
| 517 | except Exception as exc: # noqa: BLE001 - the digest is built without it |
| 518 | _log(f"no baseline of earlier filings, newest first instead: {exc}") |
| 519 | return None |
| 520 | field = _NAME_FIELDS[APPLICATIONS][1] |
| 521 | own = [row for row in rows if _best_name(_names(row.get(field)), classify)] |
| 522 | if len(own) < MIN_BASELINE_ROWS: |
| 523 | return None |
| 524 | return Counter(subclass for row in own for subclass in _subclasses(_cpc_codes(row))) |
| 525 | |
| 526 | |
| 527 | def _read_details( |
| 528 | session: dict[str, Any], ordered: list[dict], budget: _Budget, reserved: set[str] = frozenset(), |
| 529 | ) -> tuple[list[dict], list[dict], list[dict]]: |
| 530 | """Read candidates in order until the slots are full. |
| 531 | |
| 532 | Returns the entries built, the candidates their own continuity data showed |
| 533 | to continue an older application, and the candidates left with list data |
| 534 | only: those whose read failed, then those never read. A read that fails |
| 535 | or times out costs only its own document, and the reading goes on. The |
| 536 | reading ends, keeping what was built, when the lane's budget is spent, |
| 537 | when the site rate-limits past its one honoured wait, or when it asks for |
| 538 | sign-in. |
| 539 | |
| 540 | A filer in ``reserved`` keeps its slot: when its candidate is demoted or |
| 541 | its read fails before it has an entry, its next candidate is read next, |
| 542 | within the same number of reads. |
| 543 | """ |
| 544 | ordered = list(ordered) |
| 545 | entries: list[dict] = [] |
| 546 | demoted: list[dict] = [] |
| 547 | failed: list[dict] = [] |
| 548 | filled: set[str] = set() |
| 549 | position = 0 |
| 550 | |
| 551 | def keep_reserved_slot(candidate: dict) -> None: |
| 552 | key = candidate["group_key"] |
| 553 | if key not in reserved or key in filled: |
| 554 | return |
| 555 | later = next( |
| 556 | (index for index in range(position, len(ordered)) if ordered[index]["group_key"] == key), |
| 557 | None, |
| 558 | ) |
| 559 | if later is not None: |
| 560 | ordered.insert(position, ordered.pop(later)) |
| 561 | |
| 562 | while ( |
| 563 | position < len(ordered) |
| 564 | and len(entries) < DETAIL_SLOTS |
| 565 | and position < DETAIL_SLOTS + MAX_REFILL_FETCHES |
| 566 | ): |
| 567 | candidate = ordered[position] |
| 568 | try: |
| 569 | document = _send( |
| 570 | http.get, |
| 571 | f"{BASE_URL}/api/patents/highlight/{candidate['guid']}" |
| 572 | f"?queryId=1&source={candidate['database']}&includeSections=true&uniqueId=", |
| 573 | headers=_headers(session["token"]), |
| 574 | budget=budget, |
| 575 | ) |
| 576 | if not isinstance(document, dict): |
| 577 | raise TypeError("schema: the USPTO document response is not a JSON object") |
| 578 | except _SignInRequired: |
| 579 | if not entries: |
| 580 | raise |
| 581 | _log(f"stopped reading documents after {len(entries)}: sign-in required") |
| 582 | break |
| 583 | except (_OutOfTime, _LANE_DEADLINE_PASSED) as exc: |
| 584 | _log(f"stopped reading documents after {len(entries)}: {exc}") |
| 585 | break |
| 586 | except (http.HTTPError, TypeError) as exc: |
| 587 | if isinstance(exc, http.HTTPError) and exc.status_code == 429: |
| 588 | _log(f"stopped reading documents after {len(entries)}: {exc}") |
| 589 | break |
| 590 | _log(f"no text for {candidate['number']}, reading on: {exc}") |
| 591 | failed.append(candidate) |
| 592 | position += 1 |
| 593 | keep_reserved_slot(candidate) |
| 594 | continue |
| 595 | position += 1 |
| 596 | if _CONTINUES_A_PARENT.search(" ".join(_strings(document.get("continuityData")))): |
| 597 | demoted.append(candidate) |
| 598 | keep_reserved_slot(candidate) |
| 599 | else: |
| 600 | entries.append(_entry(candidate, document)) |
| 601 | filled.add(candidate["group_key"]) |
| 602 | return entries, demoted, failed + ordered[position:] |
| 603 | |
| 604 | |
| 605 | # --- whose filing ----------------------------------------------------------- |
| 606 | |
| 607 | |
| 608 | def _classifier(company: Any) -> Callable[[str], str | None]: |
| 609 | """A function from a filed-under name to CONFIRMED, NAME_MATCHED or None.""" |
| 610 | own = company.get("company") if isinstance(company, dict) else None |
| 611 | known = list(company.get("company_names") or ()) if isinstance(company, dict) else [] |
| 612 | seen: dict[str, str | None] = {} |
| 613 | |
| 614 | def classify(name: str) -> str | None: |
| 615 | if name not in seen: |
| 616 | kind = classify_applicant(name, own, known) |
| 617 | seen[name] = kind if kind in (CONFIRMED, NAME_MATCHED) else None |
| 618 | return seen[name] |
| 619 | |
| 620 | return classify |
| 621 | |
| 622 | |
| 623 | def _best_name(names: list[str], classify: Callable[[str], str | None]) -> str | None: |
| 624 | """The name that decides a row's group: a confirmed one before a |
| 625 | name-matched one, the first listed of each.""" |
| 626 | for kind in (CONFIRMED, NAME_MATCHED): |
| 627 | for name in names: |
| 628 | if classify(name) == kind: |
| 629 | return name |
| 630 | return None |
| 631 | |
| 632 | |
| 633 | def _group( |
| 634 | rows: dict[str, list[dict]], classify: Callable[[str], str | None], |
| 635 | ) -> tuple[list[dict], list[dict]]: |
| 636 | """Group rows by the name they were filed under. |
| 637 | |
| 638 | Returns the groups kept (every confirmed one, then name-matched ones |
| 639 | while fewer than ``MAX_GROUPS`` are kept, largest first within each kind) |
| 640 | and the largest names that are neither. Names with |
| 641 | the same key are one name, shown as its most frequent spelling. |
| 642 | """ |
| 643 | groups: dict[str, dict] = {} |
| 644 | others: dict[str, Counter[str]] = {} |
| 645 | for database, found in rows.items(): |
| 646 | field = _NAME_FIELDS[database][1] |
| 647 | for row in found: |
| 648 | names = _names(row.get(field)) |
| 649 | best = _best_name(names, classify) |
| 650 | if best is not None: |
| 651 | group = groups.setdefault( |
| 652 | name_key(best), {"kind": classify(best), "spellings": Counter(), "rows": []}, |
| 653 | ) |
| 654 | group["spellings"][best] += 1 |
| 655 | group["rows"].append((database, row)) |
| 656 | continue |
| 657 | counted = set() |
| 658 | for name in names: |
| 659 | key = name_key(name) |
| 660 | if key and key not in counted: |
| 661 | counted.add(key) |
| 662 | others.setdefault(key, Counter())[name] += 1 |
| 663 | ranked = sorted( |
| 664 | groups.items(), key=lambda item: (item[1]["kind"] != CONFIRMED, -len(item[1]["rows"])), |
| 665 | ) |
| 666 | # Every confirmed name is kept, however many there are: the company's |
| 667 | # counts are of all of them. The cap only limits name-matched names. |
| 668 | confirmed = sum(1 for _key, group in ranked if group["kind"] == CONFIRMED) |
| 669 | kept = ranked[:max(MAX_GROUPS, confirmed)] |
| 670 | largest = sorted(others.values(), key=lambda spellings: -sum(spellings.values())) |
| 671 | return ( |
| 672 | [ |
| 673 | {**group, "key": key, "name": group["spellings"].most_common(1)[0][0]} |
| 674 | for key, group in kept |
| 675 | ], |
| 676 | [ |
| 677 | {"name": spellings.most_common(1)[0][0], "count": sum(spellings.values())} |
| 678 | for spellings in largest[:MAX_OTHER_NAMES] |
| 679 | ], |
| 680 | ) |
| 681 | |
| 682 | |
| 683 | # --- what a row is ---------------------------------------------------------- |
| 684 | |
| 685 | |
| 686 | def _bucket(database: str, row: dict) -> str: |
| 687 | """Whether a row is a first US publication, or which count it belongs to.""" |
| 688 | kind_code = _kind_code(row) |
| 689 | if database == APPLICATIONS: |
| 690 | if kind_code != "A1": |
| 691 | return _OTHER_KINDS |
| 692 | return _CONTINUING if _continues_older_application(row) else _FIRST |
| 693 | if kind_code == "B1": |
| 694 | return _PUBLISHED_BEFORE if _continues_older_application(row) else _FIRST |
| 695 | if kind_code == "B2": |
| 696 | return _PUBLISHED_BEFORE |
| 697 | return _DESIGNS if kind_code.startswith("S") else _OTHER_KINDS |
| 698 | |
| 699 | |
| 700 | def _continues_older_application(row: dict) -> bool: |
| 701 | filed = _dates(row.get("applicationFilingDate")) |
| 702 | related = _dates(row.get("relatedApplFilingDate")) |
| 703 | if not filed or not related: |
| 704 | return False |
| 705 | return (filed[0] - min(related)).days > CONTINUING_AFTER_DAYS |
| 706 | |
| 707 | |
| 708 | def _candidate(database: str, row: dict, group: dict) -> dict: |
| 709 | """A first publication, with everything the list says about it.""" |
| 710 | guid = str(row.get("guid") or "") |
| 711 | parts = guid.split("-") |
| 712 | number = str(row.get("publicationReferenceDocumentNumber") or (parts[1] if len(parts) > 1 else guid)) |
| 713 | published = _dates(row.get("datePublished")) |
| 714 | filed = _dates(row.get("applicationFilingDate")) |
| 715 | earlier = _dates(row.get("priorityClaimsDate")) + _dates(row.get("relatedApplFilingDate")) |
| 716 | return { |
| 717 | "guid": guid, |
| 718 | "database": database, |
| 719 | "group_key": group["key"], |
| 720 | "number": number, |
| 721 | "title": _text(row.get("inventionTitle")), |
| 722 | "url": f"{PDF_URL}{number}", |
| 723 | "kind": "application" if database == APPLICATIONS else "grant", |
| 724 | "kind_code": _kind_code(row), |
| 725 | "published": published[0].isoformat() if published else "", |
| 726 | "filed": filed[0].isoformat() if filed else None, |
| 727 | "earliest_priority": min(earlier).isoformat() if earlier else None, |
| 728 | "cpc": _cpc_codes(row), |
| 729 | "filed_as": group["name"], |
| 730 | "group_kind": group["kind"], |
| 731 | "other_filer": bool(group.get("other_filer")), |
| 732 | } |
| 733 | |
| 734 | |
| 735 | def _order( |
| 736 | candidates: list[dict], frequencies: Counter[str] | None, |
| 737 | ) -> tuple[list[dict], set[str]]: |
| 738 | """The order candidates are read in, and the filers given a reserved slot. |
| 739 | |
| 740 | Without a baseline, newest first. With one, the first half of the slots |
| 741 | (rounded up) goes to the candidates whose rarest CPC subclass the company |
| 742 | filed in least in its recent filings, a subclass absent from them first; |
| 743 | everything else follows newest first. The newer candidate wins a tie. |
| 744 | |
| 745 | Then each confirmed filer other than the company's own name, up to |
| 746 | ``MAX_RESERVED_FILERS`` and largest first, is given one slot: when none of |
| 747 | its candidates is already among the first ``DETAIL_SLOTS``, its best one |
| 748 | takes the place of the lowest-ranked newest-first candidate there, which |
| 749 | moves to the head of the refills. |
| 750 | """ |
| 751 | newest = sorted(candidates, key=lambda candidate: candidate["published"], reverse=True) |
| 752 | rare: list[dict] = [] |
| 753 | if frequencies is not None: |
| 754 | def rarity(candidate: dict) -> float: |
| 755 | subclasses = _subclasses(candidate["cpc"]) |
| 756 | return min((frequencies[subclass] for subclass in subclasses), default=float("inf")) |
| 757 | |
| 758 | rare = sorted(newest, key=rarity)[:(DETAIL_SLOTS + 1) // 2] |
| 759 | chosen = {id(candidate) for candidate in rare} |
| 760 | ordered = rare + [candidate for candidate in newest if id(candidate) not in chosen] |
| 761 | |
| 762 | filers = Counter(candidate["group_key"] for candidate in ordered if candidate.get("other_filer")) |
| 763 | reserved = {key for key, _count in filers.most_common(MAX_RESERVED_FILERS)} |
| 764 | for key in sorted(reserved, key=lambda key: -filers[key]): |
| 765 | slots = ordered[:DETAIL_SLOTS] |
| 766 | if any(candidate["group_key"] == key for candidate in slots): |
| 767 | continue |
| 768 | # The lowest-ranked slot that is not a rare-class pick and is not a |
| 769 | # reserved filer's only slot; a reserved filer's extra slots can go. |
| 770 | held = Counter(candidate["group_key"] for candidate in slots) |
| 771 | replaceable = [ |
| 772 | position for position, candidate in enumerate(slots) |
| 773 | if id(candidate) not in chosen |
| 774 | and (candidate["group_key"] not in reserved or held[candidate["group_key"]] > 1) |
| 775 | ] |
| 776 | if not replaceable: |
| 777 | break |
| 778 | best = next(candidate for candidate in ordered if candidate["group_key"] == key) |
| 779 | ordered.remove(best) |
| 780 | displaced = ordered[replaceable[-1]] |
| 781 | ordered[replaceable[-1]] = best |
| 782 | ordered.insert(DETAIL_SLOTS, displaced) |
| 783 | return ordered, reserved |
| 784 | |
| 785 | |
| 786 | def _entry(candidate: dict, document: dict) -> dict: |
| 787 | codes = [str(code).split()[0] for code in _strings(document.get("cpcInventive")) if str(code).strip()] |
| 788 | return { |
| 789 | **{key: candidate[key] for key in ( |
| 790 | "guid", "number", "title", "url", "kind", "kind_code", "published", "filed", |
| 791 | "earliest_priority", |
| 792 | )}, |
| 793 | "cpc": codes[:MAX_CPC_CODES], |
| 794 | "filed_as": candidate["filed_as"], |
| 795 | "group_kind": candidate["group_kind"], |
| 796 | "applicant_location": _location(candidate, document), |
| 797 | "abstract": _text(document.get("abstractHtml"))[:ABSTRACT_CHARS].rstrip(), |
| 798 | "first_claim": _first_claim(document.get("claimsHtml")), |
| 799 | } |
| 800 | |
| 801 | |
| 802 | def _index_item(candidate: dict) -> dict: |
| 803 | return { |
| 804 | "title": candidate["title"], |
| 805 | "url": candidate["url"], |
| 806 | "kind": candidate["kind"], |
| 807 | "published": candidate["published"], |
| 808 | "cpc": "; ".join(candidate["cpc"][:MAX_CPC_CODES]), |
| 809 | "filed_as": candidate["filed_as"], |
| 810 | "group_kind": candidate["group_kind"], |
| 811 | } |
| 812 | |
| 813 | |
| 814 | def _location(candidate: dict, document: dict) -> str: |
| 815 | """City, state and country of the party the document was filed under: |
| 816 | the applicant of an application, the assignee of a grant.""" |
| 817 | parties = ("applicant", "assignee") if candidate["kind"] == "application" else ("assignee", "applicant") |
| 818 | for party in parties: |
| 819 | names = _strings(document.get(f"{party}Name")) |
| 820 | at = next( |
| 821 | (n for n, name in enumerate(names) if name_key(name) == candidate["group_key"]), 0, |
| 822 | ) |
| 823 | parts = [] |
| 824 | for field in ("City", "State", "Country"): |
| 825 | values = _strings(document.get(f"{party}{field}")) |
| 826 | value = values[at].strip() if at < len(values) else "" |
| 827 | if value and value.upper() != "N/A": |
| 828 | parts.append(value) |
| 829 | if parts: |
| 830 | return ", ".join(parts) |
| 831 | return "" |
| 832 | |
| 833 | |
| 834 | def _first_claim(claims_html: Any) -> str: |
| 835 | """Claim 1: from its number up to the number of claim 2.""" |
| 836 | claims = " ".join(_strings(claims_html)) |
| 837 | start = _CLAIM_ONE.search(claims) |
| 838 | if not start: |
| 839 | return "" |
| 840 | end = _CLAIM_TWO.search(claims, start.end()) |
| 841 | claim = claims[start.start():end.start() if end else len(claims)] |
| 842 | return _text(claim)[:FIRST_CLAIM_CHARS].rstrip() |
| 843 | |
| 844 | |
| 845 | # --- field shapes ----------------------------------------------------------- |
| 846 | |
| 847 | |
| 848 | def _strings(value: Any) -> list[str]: |
| 849 | """A field that may be null, one value or a list, as a list of strings.""" |
| 850 | if value is None: |
| 851 | return [] |
| 852 | values = value if isinstance(value, list | tuple) else [value] |
| 853 | return [str(item) for item in values if item is not None] |
| 854 | |
| 855 | |
| 856 | def _names(value: Any) -> list[str]: |
| 857 | """The distinct names in a name field, HTML entities decoded.""" |
| 858 | names: list[str] = [] |
| 859 | for raw in _strings(value): |
| 860 | name = " ".join(html.unescape(raw).split()) |
| 861 | if name and name not in names: |
| 862 | names.append(name) |
| 863 | return names |
| 864 | |
| 865 | |
| 866 | def _dates(value: Any) -> list[date]: |
| 867 | dates = [] |
| 868 | for raw in _strings(value): |
| 869 | try: |
| 870 | dates.append(date.fromisoformat(raw[:10])) |
| 871 | except ValueError: |
| 872 | continue |
| 873 | return dates |
| 874 | |
| 875 | |
| 876 | def _kind_code(row: dict) -> str: |
| 877 | codes = _strings(row.get("kindCode")) |
| 878 | return codes[0].strip().upper() if codes else "" |
| 879 | |
| 880 | |
| 881 | def _cpc_codes(row: dict) -> list[str]: |
| 882 | return [code.strip() for code in str(row.get("cpcInventiveFlattened") or "").split(";") if code.strip()] |
| 883 | |
| 884 | |
| 885 | def _subclasses(codes: list[str]) -> set[str]: |
| 886 | return {code[:4] for code in codes} |
| 887 | |
| 888 | |
| 889 | def _text(markup: Any) -> str: |
| 890 | """Markup as one line of text.""" |
| 891 | text = re.sub(r"<br\s*/?>", " ", " ".join(_strings(markup)), flags=re.IGNORECASE) |
| 892 | return " ".join(html.unescape(re.sub(r"<[^>]+>", "", text)).split()) |
| 893 |