fix(patents): correct author-institution query and name-matching ambiguity checks for org_patents
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit

This commit is contained in:
2026-07-05 15:44:30 +02:00
parent 6962b49771
commit c4e05a4376
10 changed files with 334 additions and 146 deletions
+10 -5
View File
@@ -20,9 +20,12 @@ Run tests: `./gradlew :service:test`
### index_org_patents.py
Builds the `org_patents` Elasticsearch index for a given institution. This pre-indexes
all patents linked to an institution (via institution assignee and author name matching)
so they can be browsed efficiently in the app.
Builds the `org_patents` Elasticsearch index for a given institution: fetches its
OpenAlex authors, searches EPO/USPTO for patents matched via institution assignee
and/or inventor name, and reindexes. Each patent is tagged with a `match_type`
(`institution`, `name`, or `both`, the latter being highest confidence). For common
inventor names, a name match is only kept if the assignee is the institution itself or
the person, to avoid pulling in unrelated patents via a shared name.
```bash
python scripts/index_org_patents.py --institution-id <OpenAlex-ID>
@@ -36,8 +39,10 @@ python scripts/index_org_patents.py --institution-id I62318514
The OpenAlex institution ID appears in the app URL, e.g. `/institution/I62318514/overview`.
**Runtime:** ~10–30 minutes for large institutions (UDE has ~76,000 patents).
Re-running is safe — existing entries are replaced.
**Runtime:** ~30–40 minutes for large institutions (author count is the main driver).
Re-running is safe — existing documents for the institution are deleted (via search +
`_bulk` delete-by-id, not `_delete_by_query`, which the patent-cluster API key rejects)
before reindexing, so stale documents don't linger.
**Note:** This script is intended to be integrated into an Admin Panel in a later sprint,
so that organisation admins can trigger the indexing as a background job via the UI.
+8 -40
View File
@@ -2,53 +2,21 @@
"""
index_org_patents.py — Build the org_patents Elasticsearch index for one institution.
What this script does
---------------------
1. Fetches all authors affiliated with the given institution from OpenAlex.
2. Searches EPO and USPTO for patents assigned to the institution (institution match).
3. Searches EPO and USPTO for patents where an author's name appears as inventor (name match).
4. Merges both result sets, deduplicates, and assigns a match_type per patent:
- "institution" — found via the institution assignee field only
- "name" — found via author name matching only
- "both" — found by both methods (highest confidence)
5. Deletes any existing org_patents documents for this institution in Elasticsearch.
6. Bulk-indexes the new documents into the `org_patents` index.
Usage
-----
Run from the smartguide/service directory:
Fetches all OpenAlex authors affiliated with the institution, searches EPO/USPTO for
patents matched via institution assignee and/or author name (match_type: "institution",
"name", or "both"), deletes existing documents for the institution, and reindexes.
Usage:
python scripts/index_org_patents.py --institution-id <OpenAlex-ID>
Example (University of Duisburg-Essen):
python scripts/index_org_patents.py --institution-id I62318514
The OpenAlex institution ID can be found in the app URL when browsing an institution,
e.g. /institution/I62318514/overview → ID is I62318514.
Requires src/main/inse/.env with PATENT_ELASTICSEARCH_URL/API_KEY (and OpenAlex ES
credentials for author lookup). Runtime scales with author count (~30-40 min for UDE's
4,740 authors). Re-running is safe: existing documents are deleted before reindexing.
Prerequisites
-------------
- A .env file must exist at src/main/inse/.env with:
PATENT_ELASTICSEARCH_URL=...
PATENT_ELASTICSEARCH_API_KEY=...
OPENALEX_ELASTICSEARCH_URL=... (or equivalent, for author lookups)
- The EPO and USPTO Elasticsearch indices (epo_index_1.0, uspto_patents_3.0) must be reachable.
Runtime
-------
For the University of Duisburg-Essen (~76,000 patents, ~500 authors) this takes
roughly 10–30 minutes depending on network speed and Elasticsearch performance.
Smaller institutions finish in a few minutes.
Re-running the script is safe: existing documents for the institution are deleted
before the new ones are indexed (full re-index).
Future plans
------------
This script is intended to be integrated into an Admin Panel in a later sprint,
so that organisation admins can trigger the indexing as a background job via the UI.
For now it must be run manually on the server or locally with VPN access.
Future: integrate into an Admin Panel so admins can trigger this via the UI.
"""
from __future__ import annotations
+10 -1
View File
@@ -5,7 +5,16 @@ This module defines the model classes returned from
our api using pydantic.
"""
from enum import StrEnum
import sys
if sys.version_info >= (3, 11):
from enum import StrEnum
else:
from enum import Enum
class StrEnum(str, Enum):
def __str__(self) -> str:
return self.value
from pydantic import BaseModel
from pydantic import Field
@@ -11,6 +11,7 @@ from inse.patents.common.text_normalization import (
name_token_variants,
normalize_name_part,
patent_transliteration_expansions,
strip_person_titles,
)
@@ -132,7 +133,7 @@ def inventor_search_phrases(display_name: str) -> list[str]:
def name_matches_person(inventor_name: str, person_display_name: str) -> bool:
author = parse_person_name(person_display_name)
inventor = parse_inventor_name(inventor_name)
inventor = parse_inventor_name(strip_person_titles(inventor_name))
if author is None or inventor is None:
return False
@@ -270,10 +271,17 @@ def _given_name_matches(author: ParsedPersonName, inventor: ParsedPersonName) ->
# Accept immediately when at least one inventor given-name token matches
# one of the author's given names as a full token (not only initial),
# e.g. "Maria Schmidt" vs "Anna Maria Schmidt".
# e.g. "Maria Schmidt" vs "Anna Maria Schmidt". This only counts if at
# least one side is a spelled-out name, not a bare initial — two
# coincidentally identical single-letter tokens (e.g. both just "K.")
# are far too weak a signal on their own and would otherwise match
# anyone sharing that one middle initial regardless of their actual
# first name (e.g. "Mahendra K. Sharma" incorrectly matching inventor
# "Vivek K." or "Virender K." on an unrelated patent).
if any(
any(
tokens_equal(author_given, inventor_given, allow_initial=False)
and not (_initial_letter(author_given) and _initial_letter(inventor_given))
for author_given in author.given_names
)
for inventor_given in inventor.given_names
@@ -35,6 +35,23 @@ _PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = (
(r"a([lmnrt])", r"ae\1"),
)
# Titles that can appear before a person's name in patent inventor fields
_PERSON_TITLE_PATTERN = re.compile(
r"^\s*(?:"
r"Prof\.?|Dr\.?|Dipl\.?(?:-Ing\.?|-Math\.?|-Phys\.?|-Inform\.?)?|"
r"M\.Sc\.?|B\.Sc\.?|M\.Eng\.?|PhD\.?|Ing\.?|"
r"Prof\.?\s+Dr\.?|Dr\.?-Ing\.?|Dr\.?\s+rer\.?\s+nat\.?"
r")[.,]?\s+",
re.IGNORECASE,
)
def strip_person_titles(value: str | None) -> str:
"""Remove academic/professional titles from the start of a person name string."""
if not value:
return ""
return _PERSON_TITLE_PATTERN.sub("", value).strip()
def normalize_name_part(value: str | None) -> str:
if not value:
@@ -39,7 +39,7 @@ async def get_patents_by_institution_id(
institution_client = institutions_client or InstitutionsSearchClient()
short_id = institution_id.replace("https://openalex.org/", "")
institution = institution_client.get_institution_by_id(short_id)
institution = await institution_client.get_institution_by_id(short_id)
search_names = _institution_search_names(institution)
if not search_names:
@@ -57,9 +57,12 @@ def institution_search_variants(value: str | None) -> list[str]:
def _significant_institution_tokens(text: str) -> set[str]:
# Normalize hyphens to spaces so "Duisburg-Essen" splits into "duisburg" + "essen",
# matching both hyphenated and space-separated forms in patent databases.
normalized = normalize_name_part(text).replace("-", " ")
return {
token
for token in normalize_name_part(text).split()
for token in normalized.split()
if len(token) >= MIN_INSTITUTION_VARIANT_LEN
and token not in _INSTITUTION_GENERIC_TOKENS
}
@@ -72,13 +75,16 @@ def assignee_matches_institution_name(assignee: str, institution_name: str) -> b
return False
original = institution_name.strip()
assignee_tokens = set(norm_assignee.split())
# Normalize hyphens to spaces for consistent token splitting across patent databases
norm_assignee_flat = norm_assignee.replace("-", " ")
norm_name_flat = norm_name.replace("-", " ")
assignee_tokens = set(norm_assignee_flat.split())
if len(original) <= 6 and " " not in original:
return norm_name in assignee_tokens
return norm_name_flat in assignee_tokens
if len(norm_name) >= MIN_INSTITUTION_SUBSTRING_LEN:
if norm_name in norm_assignee or norm_assignee in norm_name:
if len(norm_name_flat) >= MIN_INSTITUTION_SUBSTRING_LEN:
if norm_name_flat in norm_assignee_flat or norm_assignee_flat in norm_name_flat:
return True
significant = _significant_institution_tokens(institution_name)
@@ -1,10 +1,13 @@
"""HTTP client for the org_patents Elasticsearch index."""
import json
import logging
from datetime import datetime
from typing import Any
import httpx
from inse.integrations import elasticsearch
from inse.models.openalex.author import Author
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.org.mapping import ORG_PATENTS_INDEX, ORG_PATENTS_MAPPING
from inse.patents.org.model import MatchTypeFilter, OrgPatentEntry
@@ -13,6 +16,91 @@ from inse import config
logger = logging.getLogger(__name__)
DEFAULT_PAGE_SIZE = 20
OPENALEX_AUTHORS_INDEX = "openalex-authors"
AUTHOR_PAGE_SIZE = 500
async def fetch_authors_by_institution_name(institution_name: str) -> list[Author]:
"""Fetches OpenAlex authors currently affiliated with institution_name.
Mirrors the persons/search-list default filter: last_known_institutions
must match AND there must be an affiliations entry for the same
institution from the current year or the year before.
"""
target_year = datetime.now().year - 1
query = {
"bool": {
"filter": [
{
"nested": {
"path": "last_known_institutions",
"query": {
"match_phrase": {
"last_known_institutions.display_name": institution_name,
}
},
}
},
{
"nested": {
"path": "affiliations",
"query": {
"bool": {
"filter": [
{
"match_phrase": {
"affiliations.institution.display_name": institution_name,
}
},
{
"range": {
"affiliations.years": {"gte": target_year},
}
},
]
}
},
}
},
]
}
}
sort = [
{"works_count": {"order": "desc"}},
{"id": {"order": "asc"}},
]
authors: list[Author] = []
search_after: list | None = None
while True:
body: dict = {
"size": AUTHOR_PAGE_SIZE,
"query": query,
"sort": sort,
}
if search_after:
body["search_after"] = search_after
response = await elasticsearch.search(index=OPENALEX_AUTHORS_INDEX, body=body)
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
for hit in hits:
source = dict(hit.get("_source", {}))
source["id"] = source.get("id") or hit.get("_id", "")
author = Author.from_dict(source)
if author:
authors.append(author)
if len(hits) < AUTHOR_PAGE_SIZE:
break
search_after = hits[-1].get("sort")
if not search_after:
break
return authors
class OrgPatentsSearchClient:
@@ -65,24 +153,66 @@ class OrgPatentsSearchClient:
mapping_response.raise_for_status()
async def delete_by_institution(self, institution_id: str) -> int:
payload = {
"query": {"term": {"institution_id": institution_id.upper()}},
}
"""Deletes all org_patents documents for institution_id.
Uses a search + bulk-delete-by-id loop instead of _delete_by_query:
the patent-cluster API key has been observed to reject _delete_by_query
with 403 Forbidden, while individual document deletes via _bulk succeed.
"""
short_id = institution_id.upper()
query = {"term": {"institution_id": short_id}}
page_size = 1000
deleted_total = 0
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{ORG_PATENTS_INDEX}/_delete_by_query",
headers=self._headers(),
json=payload,
params={"refresh": "true"},
)
if response.status_code == 404:
return 0
response.raise_for_status()
return response.json().get("deleted", 0)
while True:
search_response = await client.post(
f"/{ORG_PATENTS_INDEX}/_search",
headers=self._headers(),
json={
"size": page_size,
"query": query,
"_source": False,
"sort": ["_doc"],
},
)
if search_response.status_code == 404:
return deleted_total
search_response.raise_for_status()
hits = search_response.json().get("hits", {}).get("hits", [])
if not hits:
break
bulk_lines = [
json.dumps({"delete": {"_index": ORG_PATENTS_INDEX, "_id": hit["_id"]}})
for hit in hits
]
bulk_response = await client.post(
"/_bulk",
content="\n".join(bulk_lines) + "\n",
headers=self._headers("application/x-ndjson"),
params={"refresh": "true"},
)
bulk_response.raise_for_status()
result = bulk_response.json()
if result.get("errors"):
failed = [
item
for item in result.get("items", [])
if item.get("delete", {}).get("status", 200) >= 400
]
logger.error("Bulk delete errors: %s", failed[:3])
raise RuntimeError("Bulk deleting existing org_patents documents failed.")
deleted_total += len(hits)
if len(hits) < page_size:
break
return deleted_total
async def bulk_index(self, documents: list[tuple[str, dict[str, Any]]]) -> None:
if not documents:
+78 -78
View File
@@ -10,11 +10,14 @@ from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.integrations import elasticsearch
from inse.models.openalex.author import Author
from inse.patents.authors.identity import is_ambiguous_name
from inse.patents.authors.identity import (
author_institution_names,
is_ambiguous_name,
patent_institution_match,
patent_personal_assignee_match,
)
from inse.patents.authors.name_matching import filter_patents_by_author_name
from inse.patents.authors.topic_filter import filter_patents_by_author_topics
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.common.model import PatentEntry
from inse.patents.common.parsing import (
@@ -26,7 +29,10 @@ from inse.patents.common.parsing import (
)
from inse.patents.institutions.logic import get_patents_by_institution_id
from inse.patents.ipc_search_client import IpcSearchClient
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
from inse.patents.org.elastic_search_client import (
OrgPatentsSearchClient,
fetch_authors_by_institution_name,
)
from inse.patents.org.model import (
MatchType,
MatchTypeFilter,
@@ -38,7 +44,6 @@ from inse.patents.search_client import PatentSearchClient
logger = logging.getLogger(__name__)
AUTHOR_PAGE_SIZE = 500
ORG_PATENT_SEARCH_SIZE = 500
AUTHOR_SEARCH_CONCURRENCY = 8
@@ -76,6 +81,33 @@ def resolve_match_type(institution_match: bool, has_name_match: bool) -> MatchTy
return "name"
def _canonical_authors_by_name(
author_patents: list[tuple[Author, list[PatentEntry]]],
) -> dict[str, Author]:
"""Picks one Author per case-normalized display name to attribute matches to.
OpenAlex sometimes merges multiple real people who share a name into a
single, noisy author record with a long, unrelated affiliation history
(e.g. an economist and a biochemist both named "Michael Ehrmann" ending up
under one ID with both "European Central Bank" and "University of X").
Such merged records tend to have an inflated works_count and therefore
sort first in the author list, which would otherwise make them "win" the
dedup below. Preferring the author with the fewest total institutions
favors the cleaner, more specific identity for the drill-down link.
"""
canonical: dict[str, Author] = {}
for author, _ in author_patents:
name_key = (author.display_name or "").casefold().strip()
if not name_key:
continue
current_best = canonical.get(name_key)
if current_best is None or (
len(author_institution_names(author)) < len(author_institution_names(current_best))
):
canonical[name_key] = author
return canonical
def merge_org_patents(
institution_id: str,
institution_name: str | None,
@@ -92,15 +124,25 @@ def merge_org_patents(
else:
entry.institution_match = True
canonical_authors = _canonical_authors_by_name(author_patents)
for author, patents in author_patents:
author_id = normalize_author_id(author.id)
author_name = author.display_name or ""
if not author_id or not author_name:
continue
# Use case-normalized name as dedup key to collapse OpenAlex duplicate records
# (e.g. "Kenji TANAKA" and "Kenji Tanaka" are the same person)
author_dedup_key = author_name.casefold().strip() or author_id
# Attribute the match to the canonical (cleanest-profile) author for
# this name, not necessarily the one whose patents we're iterating —
# see _canonical_authors_by_name().
canonical = canonical_authors.get(author_dedup_key, author)
matched_author = MatchedAuthor(
openalex_author_id=author_id,
author_name=author_name,
openalex_author_id=normalize_author_id(canonical.id) or author_id,
author_name=canonical.display_name or author_name,
)
for patent in patents:
key = patent_dedup_key(patent)
@@ -108,10 +150,10 @@ def merge_org_patents(
if entry is None:
accumulated[key] = _AccumulatedPatent(
patent=patent,
matched_authors={author_id: matched_author},
matched_authors={author_dedup_key: matched_author},
)
else:
entry.matched_authors[author_id] = matched_author
entry.matched_authors.setdefault(author_dedup_key, matched_author)
org_patents: list[OrgPatentEntry] = []
short_institution_id = normalize_institution_id(institution_id)
@@ -174,58 +216,9 @@ def org_patent_to_es_document(patent: OrgPatentEntry) -> dict:
}
def fetch_authors_for_institution(institution_id: str) -> list[Author]:
short_id = normalize_institution_id(institution_id)
query = {
"nested": {
"path": "last_known_institutions",
"query": {
"term": {
"last_known_institutions.id": f"https://openalex.org/{short_id}",
}
},
}
}
authors: list[Author] = []
search_after: list | None = None
sort = [
{"works_count": {"order": "desc"}},
{"id": {"order": "asc"}},
]
while True:
body: dict = {
"size": AUTHOR_PAGE_SIZE,
"query": query,
"sort": sort,
}
if search_after:
body["search_after"] = search_after
response = elasticsearch.search(index="openalex-authors", body=body)
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
for hit in hits:
source = dict(hit.get("_source", {}))
source["id"] = source.get("id") or hit.get("_id", "")
author = Author.from_dict(source)
if author:
authors.append(author)
if len(hits) < AUTHOR_PAGE_SIZE:
break
search_after = hits[-1].get("sort")
if not search_after:
break
return authors
async def _search_patents_by_author(
author: Author,
institution_name: str | None,
search_client: PatentSearchClient,
ipc_client: IpcSearchClient,
) -> list[PatentEntry]:
@@ -258,30 +251,35 @@ async def _search_patents_by_author(
if not name_matched:
return []
await enrich_patents_classifications(name_matched, ipc_client)
from inse.persons import logic as person_logic
from inse.patents.authors.name_variants import parse_person_name
# Ambiguity is derived only from existing project data.
full_name_count = await person_logic.count_authors_by_display_name(author_name)
parsed_for_last = parse_person_name(author_name)
last_name_count: int | None = None
if parsed_for_last and not parsed_for_last.is_single_token:
last_name_count = await person_logic.count_authors_by_last_name(
parsed_for_last.last_name
)
is_ambiguous = is_ambiguous_name(
author_name,
patent_hit_count=patent_hit_count,
openalex_full_name_count=full_name_count,
openalex_last_name_count=last_name_count,
)
fallback_topics: list[str] = []
if not (author.topics or []) and author.id:
fallback_topics = await person_logic.get_topic_names_for_author(author.id)
filtered = await asyncio.to_thread(
filter_patents_by_author_topics,
name_matched,
author,
is_ambiguous=is_ambiguous,
fallback_topic_names=fallback_topics,
)
return [item.patent for item in filtered]
if is_ambiguous:
# Common names (Zhang, Li, Wang): only keep if the assignee matches the
# institution we're building this index for (not any institution from
# the author's whole affiliation history) or the person themselves.
inst_names = [institution_name] if institution_name else []
return [
p for p in name_matched
if patent_institution_match(p, inst_names)
or patent_personal_assignee_match(p, author_name)
]
else:
return name_matched
async def build_org_patents_for_institution(
@@ -295,7 +293,7 @@ async def build_org_patents_for_institution(
institution_client = institutions_client or InstitutionsSearchClient()
short_id = normalize_institution_id(institution_id)
institution = institution_client.get_institution_by_id(short_id)
institution = await institution_client.get_institution_by_id(short_id)
institution_name = institution.display_name
institution_response = await get_patents_by_institution_id(
@@ -306,7 +304,7 @@ async def build_org_patents_for_institution(
)
institution_patents = institution_response.patents
authors = fetch_authors_for_institution(short_id)
authors = await fetch_authors_by_institution_name(institution_name)
logger.info(
"Building org_patents for %s (%s): %d authors, %d institution patents",
institution_name,
@@ -319,7 +317,9 @@ async def build_org_patents_for_institution(
async def _fetch_for_author(author: Author) -> tuple[Author, list[PatentEntry]]:
async with semaphore:
patents = await _search_patents_by_author(author, patent_client, ipc_search_client)
patents = await _search_patents_by_author(
author, institution_name, patent_client, ipc_search_client
)
return author, patents
author_results = await asyncio.gather(
@@ -395,7 +395,7 @@ async def get_org_patents_by_institution_id(
institution_client = institutions_client or InstitutionsSearchClient()
try:
institution = institution_client.get_institution_by_id(short_id)
institution = await institution_client.get_institution_by_id(short_id)
institution_name = institution.display_name
except Exception:
institution_name = None
+46 -1
View File
@@ -1,7 +1,9 @@
from functools import lru_cache
from typing import Annotated
from fastapi import APIRouter, Depends, Query
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query
from pydantic import BaseModel
from starlette.status import HTTP_202_ACCEPTED
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.patents.org import logic
@@ -9,6 +11,8 @@ from inse.patents.org.model import MatchTypeFilter, OrgPatentsResponse
router = APIRouter(prefix="/api/inse-service/institutions", tags=["Patents"])
_rebuild_running: set[str] = set()
@lru_cache
def get_institutions_search_client() -> InstitutionsSearchClient:
@@ -42,3 +46,44 @@ async def get_org_patents_by_institution(
source=source,
institutions_client=client,
)
class RebuildResponse(BaseModel):
status: str
institution_id: str
message: str
@router.post(
"/{id}/org-patents/rebuild",
operation_id="rebuildOrgPatents",
response_model=RebuildResponse,
status_code=HTTP_202_ACCEPTED,
summary="Trigger a background rebuild of the org_patents index for an institution.",
)
async def rebuild_org_patents(
id: str,
background_tasks: BackgroundTasks,
) -> RebuildResponse:
short_id = logic.normalize_institution_id(id)
if short_id in _rebuild_running:
raise HTTPException(
status_code=409,
detail=f"A rebuild for institution {short_id} is already in progress.",
)
async def _run() -> None:
_rebuild_running.add(short_id)
try:
await logic.index_org_patents_for_institution(short_id)
finally:
_rebuild_running.discard(short_id)
background_tasks.add_task(_run)
return RebuildResponse(
status="accepted",
institution_id=short_id,
message=f"Rebuild started for institution {short_id}. Check server logs for progress.",
)