| 1 | """The bounded evidence block for one company's patent filings. |
| 2 | |
| 3 | ``lib.patents`` returns an artifact: whose names the filings were found under, |
| 4 | counts, a few filings with their abstract and first claim, and more by title. |
| 5 | This module turns it into the lines of the ``## Patent Digest`` block and |
| 6 | keeps the block under one size. It decides nothing about what a filing means. |
| 7 | |
| 8 | The caller supplies the two formatters, so every title, name and passage of |
| 9 | patent office text is escaped the way the rest of the evidence is. |
| 10 | """ |
| 11 | |
| 12 | from __future__ import annotations |
| 13 | |
| 14 | from collections.abc import Callable |
| 15 | from typing import Any |
| 16 | |
| 17 | from . import patents |
| 18 | from .company_names import CONFIRMED, NAME_MATCHED |
| 19 | |
| 20 | HEADING = "## Patent Digest" |
| 21 | # Ceiling for the whole block. Entries are added before titles, so when the |
| 22 | # block is cut it is the title list that is shortened. |
| 23 | DIGEST_MAX_CHARS = 36_000 |
| 24 | # Room kept for the note line, written after it is known what was cut. |
| 25 | _NOTE_RESERVE = 400 |
| 26 | _NAME_CHARS = 120 |
| 27 | _TITLE_CHARS = 300 |
| 28 | _FIELD_CHARS = 60 |
| 29 | # What the reader sees for filers whose names extend the company's name and |
| 30 | # could not be attributed to it: the line that lists them, and the marker on |
| 31 | # each of their entries. |
| 32 | OTHER_FILERS_LABEL = "- Other filers with the company's name, not verified:" |
| 33 | NOT_VERIFIED = "not verified" |
| 34 | |
| 35 | |
| 36 | def count(value: Any) -> int: |
| 37 | """A count from the artifact; anything that is not one is zero.""" |
| 38 | return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 0 |
| 39 | |
| 40 | |
| 41 | def quantity(number: int, noun: str, *, floor: bool = False, plural: str | None = None) -> str: |
| 42 | """``3 grants``, ``1 grant``, ``1,200+ grants`` when the count is a floor.""" |
| 43 | if number == 1 and not floor: |
| 44 | word = noun |
| 45 | else: |
| 46 | word = plural or f"{noun}s" |
| 47 | return f"{number:,}{'+' if floor else ''} {word}" |
| 48 | |
| 49 | |
| 50 | def groups(artifact: dict, kind: str) -> list[dict]: |
| 51 | """The artifact's filed-under name groups of one kind.""" |
| 52 | found = artifact.get("groups") |
| 53 | return [ |
| 54 | group for group in (found if isinstance(found, list) else []) |
| 55 | if isinstance(group, dict) and group.get("kind") == kind and group.get("name") |
| 56 | ] |
| 57 | |
| 58 | |
| 59 | def has_own_filings(artifact: dict, counts: dict) -> bool: |
| 60 | """True when any filing in the window is the company's own, so its counts |
| 61 | describe filings rather than sit at zero beside other filers'.""" |
| 62 | return bool( |
| 63 | groups(artifact, CONFIRMED) |
| 64 | or count(counts.get("applications")) |
| 65 | or count(counts.get("grants")) |
| 66 | or count(counts.get("first_publications")) |
| 67 | ) |
| 68 | |
| 69 | |
| 70 | def _dicts(value: Any) -> list[dict]: |
| 71 | return [item for item in (value if isinstance(value, list) else []) if isinstance(item, dict)] |
| 72 | |
| 73 | |
| 74 | def digest_lines( |
| 75 | artifact: Any, |
| 76 | *, |
| 77 | link: Callable[[str, str], str], |
| 78 | untrusted: Callable[[str, int], str], |
| 79 | ) -> list[str]: |
| 80 | """The lines of the block, or none when the artifact holds no digest. |
| 81 | |
| 82 | ``link(url, title)`` renders a filing's title linked to its document and |
| 83 | ``untrusted(text, limit)`` renders text that came from the patent office. |
| 84 | Entries filed under the company's own names come before other filers', |
| 85 | each in the lane's order. Entries, then titles, are added until the next one |
| 86 | would pass ``DIGEST_MAX_CHARS``; the note line counts what was left out. |
| 87 | """ |
| 88 | if not isinstance(artifact, dict) or artifact.get("status") != "digest": |
| 89 | return [] |
| 90 | entries = _dicts(artifact.get("entries")) |
| 91 | entries = [ |
| 92 | *(entry for entry in entries if entry.get("group_kind") != NAME_MATCHED), |
| 93 | *(entry for entry in entries if entry.get("group_kind") == NAME_MATCHED), |
| 94 | ] |
| 95 | index = _dicts(artifact.get("index")) |
| 96 | if not entries and not index: |
| 97 | return [] |
| 98 | |
| 99 | def inline(value: Any, limit: int = _FIELD_CHARS) -> str: |
| 100 | return untrusted(" ".join(str(value or "").split()), limit) |
| 101 | |
| 102 | counts = artifact.get("counts") if isinstance(artifact.get("counts"), dict) else {} |
| 103 | floor = bool(counts.get("floor")) |
| 104 | |
| 105 | head = [HEADING, "", _filings_line(artifact, counts, floor, inline)] |
| 106 | matched = groups(artifact, NAME_MATCHED) |
| 107 | if matched: |
| 108 | matched_first = count(counts.get("name_matched_first_publications")) |
| 109 | head.append( |
| 110 | f"{OTHER_FILERS_LABEL} " |
| 111 | + "; ".join( |
| 112 | f"{inline(group['name'], _NAME_CHARS)} (" |
| 113 | f"{quantity(count(group.get('applications')), 'application', floor=floor)}, " |
| 114 | f"{quantity(count(group.get('grants')), 'grant', floor=floor)})" |
| 115 | for group in matched |
| 116 | ) |
| 117 | + ( |
| 118 | f"; {quantity(matched_first, 'first US publication', floor=floor)} among them" |
| 119 | if matched_first |
| 120 | else "" |
| 121 | ) |
| 122 | ) |
| 123 | if has_own_filings(artifact, counts): |
| 124 | head.append(_first_publications_line(counts, floor)) |
| 125 | |
| 126 | tail = [] |
| 127 | others = [item for item in _dicts(artifact.get("other_names")) if item.get("name")] |
| 128 | if others: |
| 129 | tail.append( |
| 130 | "- Other names in the search, not read: " |
| 131 | + ", ".join( |
| 132 | f"{inline(item['name'], _NAME_CHARS)} ({count(item.get('count')):,})" |
| 133 | for item in others |
| 134 | ) |
| 135 | ) |
| 136 | |
| 137 | room = DIGEST_MAX_CHARS - _NOTE_RESERVE - sum(len(line) + 1 for line in (*head, *tail)) |
| 138 | shown_entries: list[str] = [] |
| 139 | for entry in entries: |
| 140 | line = _entry_line(entry, link, inline) |
| 141 | if len(line) + 1 > room: |
| 142 | break |
| 143 | room -= len(line) + 1 |
| 144 | shown_entries.append(line) |
| 145 | shown_titles: list[str] = [] |
| 146 | titles_heading = "- More first US publications (titles only):" |
| 147 | if len(shown_entries) == len(entries) and index: |
| 148 | room -= len(titles_heading) + 1 |
| 149 | for item in index: |
| 150 | line = _index_line(item, link, inline) |
| 151 | if len(line) + 1 > room: |
| 152 | break |
| 153 | room -= len(line) + 1 |
| 154 | shown_titles.append(line) |
| 155 | |
| 156 | note = _note( |
| 157 | artifact.get("partial"), |
| 158 | len(entries) - len(shown_entries), |
| 159 | len(index) - len(shown_titles), |
| 160 | ) |
| 161 | return [ |
| 162 | *head, |
| 163 | *([f"- Note: {note}"] if note else []), |
| 164 | *shown_entries, |
| 165 | *([titles_heading, *shown_titles] if shown_titles else []), |
| 166 | *tail, |
| 167 | ] |
| 168 | |
| 169 | |
| 170 | def _filings_line(artifact: dict, counts: dict, floor: bool, inline: Callable[..., str]) -> str: |
| 171 | company = inline(artifact.get("company"), _NAME_CHARS) or "the company" |
| 172 | if artifact.get("company_via_person"): |
| 173 | company += ", the company the person leads (the company's filings, not the person's)" |
| 174 | window = artifact.get("window") if isinstance(artifact.get("window"), dict) else {} |
| 175 | parts = [ |
| 176 | company, |
| 177 | f"US patent filings published {inline(window.get('from'))} to {inline(window.get('to'))}", |
| 178 | ] |
| 179 | if not has_own_filings(artifact, counts): |
| 180 | return "- Filings: " + " | ".join([*parts, "none filed under the company's own name"]) |
| 181 | own = groups(artifact, CONFIRMED) |
| 182 | parts += [ |
| 183 | quantity(count(counts.get("applications")), "application", floor=floor) + " published", |
| 184 | quantity(count(counts.get("grants")), "patent", floor=floor) + " granted", |
| 185 | ] |
| 186 | if own: |
| 187 | parts.append("filed as " + "; ".join(inline(group["name"], _NAME_CHARS) for group in own)) |
| 188 | return "- Filings: " + " | ".join(parts) |
| 189 | |
| 190 | |
| 191 | def _first_publications_line(counts: dict, floor: bool) -> str: |
| 192 | """The company's own first publications, and what else was counted under |
| 193 | its own names. Other filers' filings are on their own line.""" |
| 194 | line = ( |
| 195 | f"- First US publications: {count(counts.get('first_publications')):,}" |
| 196 | f"{'+' if floor else ''} (an application, or a grant with no earlier publication, " |
| 197 | "that does not continue an older application)." |
| 198 | ) |
| 199 | not_listed = [ |
| 200 | quantity(number, noun, floor=floor, plural=plural) + suffix |
| 201 | for number, noun, plural, suffix in ( |
| 202 | ( |
| 203 | count(counts.get("continuing")), "continuing application", None, |
| 204 | " (continuations, divisionals)", |
| 205 | ), |
| 206 | ( |
| 207 | count(counts.get("previously_published_grants")), |
| 208 | "grant of an application published earlier", |
| 209 | "grants of applications published earlier", "", |
| 210 | ), |
| 211 | (count(counts.get("designs")), "design patent", None, ""), |
| 212 | (count(counts.get("other_kinds")), "of another kind", "of other kinds", ""), |
| 213 | ) |
| 214 | if number |
| 215 | ] |
| 216 | if not_listed: |
| 217 | line += ( |
| 218 | " Counted and not listed, because none is the first US publication of an " |
| 219 | "invention: " + ", ".join(not_listed) + "." |
| 220 | ) |
| 221 | return line |
| 222 | |
| 223 | |
| 224 | def _note(partial: Any, cut_entries: int, cut_titles: int) -> str: |
| 225 | notes = [] |
| 226 | missing = count(partial.get("missing_text")) if isinstance(partial, dict) else 0 |
| 227 | if missing: |
| 228 | notes.append( |
| 229 | f"{missing:,} of the filings listed by title only " |
| 230 | f"{'has' if missing == 1 else 'have'} no abstract or claim text because the " |
| 231 | "patent office did not return it or time ran out" |
| 232 | ) |
| 233 | cut = [ |
| 234 | quantity(number, noun, plural=plural) |
| 235 | for number, noun, plural in ( |
| 236 | (cut_entries, "entry", "entries"), (cut_titles, "title", None), |
| 237 | ) |
| 238 | if number |
| 239 | ] |
| 240 | if cut: |
| 241 | notes.append( |
| 242 | f"{' and '.join(cut)} left out to keep this block under " |
| 243 | f"{DIGEST_MAX_CHARS:,} characters" |
| 244 | ) |
| 245 | return "; ".join(notes) + "." if notes else "" |
| 246 | |
| 247 | |
| 248 | def _kind(item: dict) -> str: |
| 249 | return "grant" if item.get("kind") == "grant" else "application" |
| 250 | |
| 251 | |
| 252 | def _filed_as(item: dict, inline: Callable[..., str], location: str = "") -> list[str]: |
| 253 | parts = [] |
| 254 | name = inline(item.get("filed_as"), _NAME_CHARS) |
| 255 | if name: |
| 256 | parts.append(f"filed as {name}" + (f" ({location})" if location else "")) |
| 257 | if item.get("group_kind") == NAME_MATCHED: |
| 258 | parts.append(NOT_VERIFIED) |
| 259 | return parts |
| 260 | |
| 261 | |
| 262 | def _title(item: dict, link: Callable[[str, str], str]) -> str: |
| 263 | title = " ".join(str(item.get("title") or "").split())[:_TITLE_CHARS] or "Untitled filing" |
| 264 | return link(str(item.get("url") or ""), title) |
| 265 | |
| 266 | |
| 267 | def _entry_line( |
| 268 | entry: dict, |
| 269 | link: Callable[[str, str], str], |
| 270 | inline: Callable[..., str], |
| 271 | ) -> str: |
| 272 | parts = [_title(entry, link), f"{_kind(entry)} {inline(entry.get('number'))}".rstrip()] |
| 273 | filed = inline(entry.get("filed")) |
| 274 | priority = inline(entry.get("earliest_priority")) |
| 275 | for label, value in (("published", inline(entry.get("published"))), ("filed", filed)): |
| 276 | if value: |
| 277 | parts.append(f"{label} {value}") |
| 278 | if priority and priority != filed: |
| 279 | parts.append(f"earliest priority {priority}") |
| 280 | codes = entry.get("cpc") |
| 281 | cpc = "; ".join(inline(code) for code in (codes if isinstance(codes, list) else []) if code) |
| 282 | if cpc: |
| 283 | parts.append(f"CPC {cpc}") |
| 284 | parts.extend(_filed_as(entry, inline, inline(entry.get("applicant_location"), _NAME_CHARS))) |
| 285 | for label, key, limit in ( |
| 286 | ("abstract", "abstract", patents.ABSTRACT_CHARS), |
| 287 | ("first claim", "first_claim", patents.FIRST_CLAIM_CHARS), |
| 288 | ): |
| 289 | text = inline(entry.get(key), limit) |
| 290 | if text: |
| 291 | parts.append(f"{label}: {text}") |
| 292 | return "- " + " | ".join(parts) |
| 293 | |
| 294 | |
| 295 | def _index_line(item: dict, link: Callable[[str, str], str], inline: Callable[..., str]) -> str: |
| 296 | parts = [_title(item, link), _kind(item)] |
| 297 | published = inline(item.get("published")) |
| 298 | if published: |
| 299 | parts.append(f"published {published}") |
| 300 | cpc = inline(item.get("cpc"), _NAME_CHARS) |
| 301 | if cpc: |
| 302 | parts.append(f"CPC {cpc}") |
| 303 | parts.extend(_filed_as(item, inline)) |
| 304 | return " - " + " | ".join(parts) |
| 305 |